repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
parheliamm/T440p-kernel | drivers/i2c/busses/i2c-ali1535.c | 1845 | 16244 | /*
* Copyright (c) 2000 Frodo Looijaard <frodol@dds.nl>,
* Philip Edelbrock <phil@netroedge.com>,
* Mark D. Studebaker <mdsxyz123@yahoo.com>,
* Dan Eaton <dan.eaton@rocketlogix.com> and
* Stephen Rousset <stephen.rousset@rocketlogix.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.
*/
/*
This is the driver for the SMB Host controller on
Acer Labs Inc. (ALI) M1535 South Bridge.
The M1535 is a South bridge for portable systems.
It is very similar to the M15x3 South bridges also produced
by Acer Labs Inc. Some of the registers within the part
have moved and some have been redefined slightly. Additionally,
the sequencing of the SMBus transactions has been modified
to be more consistent with the sequencing recommended by
the manufacturer and observed through testing. These
changes are reflected in this driver and can be identified
by comparing this driver to the i2c-ali15x3 driver.
For an overview of these chips see http://www.acerlabs.com
The SMB controller is part of the 7101 device, which is an
ACPI-compliant Power Management Unit (PMU).
The whole 7101 device has to be enabled for the SMB to work.
You can't just enable the SMB alone.
The SMB and the ACPI have separate I/O spaces.
We make sure that the SMB is enabled. We leave the ACPI alone.
This driver controls the SMB Host only.
This driver does not use interrupts.
*/
/* Note: we assume there can only be one ALI1535, with one SMBus interface */
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/kernel.h>
#include <linux/stddef.h>
#include <linux/delay.h>
#include <linux/ioport.h>
#include <linux/i2c.h>
#include <linux/acpi.h>
#include <linux/io.h>
/* ALI1535 SMBus address offsets */
#define SMBHSTSTS (0 + ali1535_smba)
#define SMBHSTTYP (1 + ali1535_smba)
#define SMBHSTPORT (2 + ali1535_smba)
#define SMBHSTCMD (7 + ali1535_smba)
#define SMBHSTADD (3 + ali1535_smba)
#define SMBHSTDAT0 (4 + ali1535_smba)
#define SMBHSTDAT1 (5 + ali1535_smba)
#define SMBBLKDAT (6 + ali1535_smba)
/* PCI Address Constants */
#define SMBCOM 0x004
#define SMBREV 0x008
#define SMBCFG 0x0D1
#define SMBBA 0x0E2
#define SMBHSTCFG 0x0F0
#define SMBCLK 0x0F2
/* Other settings */
#define MAX_TIMEOUT 500 /* times 1/100 sec */
#define ALI1535_SMB_IOSIZE 32
#define ALI1535_SMB_DEFAULTBASE 0x8040
/* ALI1535 address lock bits */
#define ALI1535_LOCK 0x06 /* dwe */
/* ALI1535 command constants */
#define ALI1535_QUICK 0x00
#define ALI1535_BYTE 0x10
#define ALI1535_BYTE_DATA 0x20
#define ALI1535_WORD_DATA 0x30
#define ALI1535_BLOCK_DATA 0x40
#define ALI1535_I2C_READ 0x60
#define ALI1535_DEV10B_EN 0x80 /* Enable 10-bit addressing in */
/* I2C read */
#define ALI1535_T_OUT 0x08 /* Time-out Command (write) */
#define ALI1535_A_HIGH_BIT9 0x08 /* Bit 9 of 10-bit address in */
/* Alert-Response-Address */
/* (read) */
#define ALI1535_KILL 0x04 /* Kill Command (write) */
#define ALI1535_A_HIGH_BIT8 0x04 /* Bit 8 of 10-bit address in */
/* Alert-Response-Address */
/* (read) */
#define ALI1535_D_HI_MASK 0x03 /* Mask for isolating bits 9-8 */
/* of 10-bit address in I2C */
/* Read Command */
/* ALI1535 status register bits */
#define ALI1535_STS_IDLE 0x04
#define ALI1535_STS_BUSY 0x08 /* host busy */
#define ALI1535_STS_DONE 0x10 /* transaction complete */
#define ALI1535_STS_DEV 0x20 /* device error */
#define ALI1535_STS_BUSERR 0x40 /* bus error */
#define ALI1535_STS_FAIL 0x80 /* failed bus transaction */
#define ALI1535_STS_ERR 0xE0 /* all the bad error bits */
#define ALI1535_BLOCK_CLR 0x04 /* reset block data index */
/* ALI1535 device address register bits */
#define ALI1535_RD_ADDR 0x01 /* Read/Write Bit in Device */
/* Address field */
/* -> Write = 0 */
/* -> Read = 1 */
#define ALI1535_SMBIO_EN 0x04 /* SMB I/O Space enable */
static struct pci_driver ali1535_driver;
static unsigned long ali1535_smba;
static unsigned short ali1535_offset;
/* Detect whether a ALI1535 can be found, and initialize it, where necessary.
Note the differences between kernels with the old PCI BIOS interface and
newer kernels with the real PCI interface. In compat.h some things are
defined to make the transition easier. */
static int ali1535_setup(struct pci_dev *dev)
{
int retval;
unsigned char temp;
/* Check the following things:
- SMB I/O address is initialized
- Device is enabled
- We can use the addresses
*/
retval = pci_enable_device(dev);
if (retval) {
dev_err(&dev->dev, "ALI1535_smb can't enable device\n");
goto exit;
}
/* Determine the address of the SMBus area */
pci_read_config_word(dev, SMBBA, &ali1535_offset);
dev_dbg(&dev->dev, "ALI1535_smb is at offset 0x%04x\n", ali1535_offset);
ali1535_offset &= (0xffff & ~(ALI1535_SMB_IOSIZE - 1));
if (ali1535_offset == 0) {
dev_warn(&dev->dev,
"ALI1535_smb region uninitialized - upgrade BIOS?\n");
retval = -ENODEV;
goto exit;
}
if (pci_resource_flags(dev, 0) & IORESOURCE_IO)
ali1535_smba = pci_resource_start(dev, 0) + ali1535_offset;
else
ali1535_smba = ali1535_offset;
retval = acpi_check_region(ali1535_smba, ALI1535_SMB_IOSIZE,
ali1535_driver.name);
if (retval)
goto exit;
if (!request_region(ali1535_smba, ALI1535_SMB_IOSIZE,
ali1535_driver.name)) {
dev_err(&dev->dev, "ALI1535_smb region 0x%lx already in use!\n",
ali1535_smba);
retval = -EBUSY;
goto exit;
}
/* check if whole device is enabled */
pci_read_config_byte(dev, SMBCFG, &temp);
if ((temp & ALI1535_SMBIO_EN) == 0) {
dev_err(&dev->dev, "SMB device not enabled - upgrade BIOS?\n");
retval = -ENODEV;
goto exit_free;
}
/* Is SMB Host controller enabled? */
pci_read_config_byte(dev, SMBHSTCFG, &temp);
if ((temp & 1) == 0) {
dev_err(&dev->dev, "SMBus controller not enabled - upgrade BIOS?\n");
retval = -ENODEV;
goto exit_free;
}
/* set SMB clock to 74KHz as recommended in data sheet */
pci_write_config_byte(dev, SMBCLK, 0x20);
/*
The interrupt routing for SMB is set up in register 0x77 in the
1533 ISA Bridge device, NOT in the 7101 device.
Don't bother with finding the 1533 device and reading the register.
if ((....... & 0x0F) == 1)
dev_dbg(&dev->dev, "ALI1535 using Interrupt 9 for SMBus.\n");
*/
pci_read_config_byte(dev, SMBREV, &temp);
dev_dbg(&dev->dev, "SMBREV = 0x%X\n", temp);
dev_dbg(&dev->dev, "ALI1535_smba = 0x%lx\n", ali1535_smba);
return 0;
exit_free:
release_region(ali1535_smba, ALI1535_SMB_IOSIZE);
exit:
return retval;
}
static int ali1535_transaction(struct i2c_adapter *adap)
{
int temp;
int result = 0;
int timeout = 0;
dev_dbg(&adap->dev, "Transaction (pre): STS=%02x, TYP=%02x, "
"CMD=%02x, ADD=%02x, DAT0=%02x, DAT1=%02x\n",
inb_p(SMBHSTSTS), inb_p(SMBHSTTYP), inb_p(SMBHSTCMD),
inb_p(SMBHSTADD), inb_p(SMBHSTDAT0), inb_p(SMBHSTDAT1));
/* get status */
temp = inb_p(SMBHSTSTS);
/* Make sure the SMBus host is ready to start transmitting */
/* Check the busy bit first */
if (temp & ALI1535_STS_BUSY) {
/* If the host controller is still busy, it may have timed out
* in the previous transaction, resulting in a "SMBus Timeout"
* printk. I've tried the following to reset a stuck busy bit.
* 1. Reset the controller with an KILL command. (this
* doesn't seem to clear the controller if an external
* device is hung)
* 2. Reset the controller and the other SMBus devices with a
* T_OUT command. (this clears the host busy bit if an
* external device is hung, but it comes back upon a new
* access to a device)
* 3. Disable and reenable the controller in SMBHSTCFG. Worst
* case, nothing seems to work except power reset.
*/
/* Try resetting entire SMB bus, including other devices - This
* may not work either - it clears the BUSY bit but then the
* BUSY bit may come back on when you try and use the chip
* again. If that's the case you are stuck.
*/
dev_info(&adap->dev,
"Resetting entire SMB Bus to clear busy condition (%02x)\n",
temp);
outb_p(ALI1535_T_OUT, SMBHSTTYP);
temp = inb_p(SMBHSTSTS);
}
/* now check the error bits and the busy bit */
if (temp & (ALI1535_STS_ERR | ALI1535_STS_BUSY)) {
/* do a clear-on-write */
outb_p(0xFF, SMBHSTSTS);
temp = inb_p(SMBHSTSTS);
if (temp & (ALI1535_STS_ERR | ALI1535_STS_BUSY)) {
/* This is probably going to be correctable only by a
* power reset as one of the bits now appears to be
* stuck */
/* This may be a bus or device with electrical problems. */
dev_err(&adap->dev,
"SMBus reset failed! (0x%02x) - controller or "
"device on bus is probably hung\n", temp);
return -EBUSY;
}
} else {
/* check and clear done bit */
if (temp & ALI1535_STS_DONE)
outb_p(temp, SMBHSTSTS);
}
/* start the transaction by writing anything to the start register */
outb_p(0xFF, SMBHSTPORT);
/* We will always wait for a fraction of a second! */
timeout = 0;
do {
usleep_range(1000, 2000);
temp = inb_p(SMBHSTSTS);
} while (((temp & ALI1535_STS_BUSY) && !(temp & ALI1535_STS_IDLE))
&& (timeout++ < MAX_TIMEOUT));
/* If the SMBus is still busy, we give up */
if (timeout > MAX_TIMEOUT) {
result = -ETIMEDOUT;
dev_err(&adap->dev, "SMBus Timeout!\n");
}
if (temp & ALI1535_STS_FAIL) {
result = -EIO;
dev_dbg(&adap->dev, "Error: Failed bus transaction\n");
}
/* Unfortunately the ALI SMB controller maps "no response" and "bus
* collision" into a single bit. No response is the usual case so don't
* do a printk. This means that bus collisions go unreported.
*/
if (temp & ALI1535_STS_BUSERR) {
result = -ENXIO;
dev_dbg(&adap->dev,
"Error: no response or bus collision ADD=%02x\n",
inb_p(SMBHSTADD));
}
/* haven't ever seen this */
if (temp & ALI1535_STS_DEV) {
result = -EIO;
dev_err(&adap->dev, "Error: device error\n");
}
/* check to see if the "command complete" indication is set */
if (!(temp & ALI1535_STS_DONE)) {
result = -ETIMEDOUT;
dev_err(&adap->dev, "Error: command never completed\n");
}
dev_dbg(&adap->dev, "Transaction (post): STS=%02x, TYP=%02x, "
"CMD=%02x, ADD=%02x, DAT0=%02x, DAT1=%02x\n",
inb_p(SMBHSTSTS), inb_p(SMBHSTTYP), inb_p(SMBHSTCMD),
inb_p(SMBHSTADD), inb_p(SMBHSTDAT0), inb_p(SMBHSTDAT1));
/* take consequent actions for error conditions */
if (!(temp & ALI1535_STS_DONE)) {
/* issue "kill" to reset host controller */
outb_p(ALI1535_KILL, SMBHSTTYP);
outb_p(0xFF, SMBHSTSTS);
} else if (temp & ALI1535_STS_ERR) {
/* issue "timeout" to reset all devices on bus */
outb_p(ALI1535_T_OUT, SMBHSTTYP);
outb_p(0xFF, SMBHSTSTS);
}
return result;
}
/* Return negative errno on error. */
static s32 ali1535_access(struct i2c_adapter *adap, u16 addr,
unsigned short flags, char read_write, u8 command,
int size, union i2c_smbus_data *data)
{
int i, len;
int temp;
int timeout;
s32 result = 0;
/* make sure SMBus is idle */
temp = inb_p(SMBHSTSTS);
for (timeout = 0;
(timeout < MAX_TIMEOUT) && !(temp & ALI1535_STS_IDLE);
timeout++) {
usleep_range(1000, 2000);
temp = inb_p(SMBHSTSTS);
}
if (timeout >= MAX_TIMEOUT)
dev_warn(&adap->dev, "Idle wait Timeout! STS=0x%02x\n", temp);
/* clear status register (clear-on-write) */
outb_p(0xFF, SMBHSTSTS);
switch (size) {
case I2C_SMBUS_QUICK:
outb_p(((addr & 0x7f) << 1) | (read_write & 0x01),
SMBHSTADD);
size = ALI1535_QUICK;
outb_p(size, SMBHSTTYP); /* output command */
break;
case I2C_SMBUS_BYTE:
outb_p(((addr & 0x7f) << 1) | (read_write & 0x01),
SMBHSTADD);
size = ALI1535_BYTE;
outb_p(size, SMBHSTTYP); /* output command */
if (read_write == I2C_SMBUS_WRITE)
outb_p(command, SMBHSTCMD);
break;
case I2C_SMBUS_BYTE_DATA:
outb_p(((addr & 0x7f) << 1) | (read_write & 0x01),
SMBHSTADD);
size = ALI1535_BYTE_DATA;
outb_p(size, SMBHSTTYP); /* output command */
outb_p(command, SMBHSTCMD);
if (read_write == I2C_SMBUS_WRITE)
outb_p(data->byte, SMBHSTDAT0);
break;
case I2C_SMBUS_WORD_DATA:
outb_p(((addr & 0x7f) << 1) | (read_write & 0x01),
SMBHSTADD);
size = ALI1535_WORD_DATA;
outb_p(size, SMBHSTTYP); /* output command */
outb_p(command, SMBHSTCMD);
if (read_write == I2C_SMBUS_WRITE) {
outb_p(data->word & 0xff, SMBHSTDAT0);
outb_p((data->word & 0xff00) >> 8, SMBHSTDAT1);
}
break;
case I2C_SMBUS_BLOCK_DATA:
outb_p(((addr & 0x7f) << 1) | (read_write & 0x01),
SMBHSTADD);
size = ALI1535_BLOCK_DATA;
outb_p(size, SMBHSTTYP); /* output command */
outb_p(command, SMBHSTCMD);
if (read_write == I2C_SMBUS_WRITE) {
len = data->block[0];
if (len < 0) {
len = 0;
data->block[0] = len;
}
if (len > 32) {
len = 32;
data->block[0] = len;
}
outb_p(len, SMBHSTDAT0);
/* Reset SMBBLKDAT */
outb_p(inb_p(SMBHSTTYP) | ALI1535_BLOCK_CLR, SMBHSTTYP);
for (i = 1; i <= len; i++)
outb_p(data->block[i], SMBBLKDAT);
}
break;
default:
dev_warn(&adap->dev, "Unsupported transaction %d\n", size);
result = -EOPNOTSUPP;
goto EXIT;
}
result = ali1535_transaction(adap);
if (result)
goto EXIT;
if ((read_write == I2C_SMBUS_WRITE) || (size == ALI1535_QUICK)) {
result = 0;
goto EXIT;
}
switch (size) {
case ALI1535_BYTE: /* Result put in SMBHSTDAT0 */
data->byte = inb_p(SMBHSTDAT0);
break;
case ALI1535_BYTE_DATA:
data->byte = inb_p(SMBHSTDAT0);
break;
case ALI1535_WORD_DATA:
data->word = inb_p(SMBHSTDAT0) + (inb_p(SMBHSTDAT1) << 8);
break;
case ALI1535_BLOCK_DATA:
len = inb_p(SMBHSTDAT0);
if (len > 32)
len = 32;
data->block[0] = len;
/* Reset SMBBLKDAT */
outb_p(inb_p(SMBHSTTYP) | ALI1535_BLOCK_CLR, SMBHSTTYP);
for (i = 1; i <= data->block[0]; i++) {
data->block[i] = inb_p(SMBBLKDAT);
dev_dbg(&adap->dev, "Blk: len=%d, i=%d, data=%02x\n",
len, i, data->block[i]);
}
break;
}
EXIT:
return result;
}
static u32 ali1535_func(struct i2c_adapter *adapter)
{
return I2C_FUNC_SMBUS_QUICK | I2C_FUNC_SMBUS_BYTE |
I2C_FUNC_SMBUS_BYTE_DATA | I2C_FUNC_SMBUS_WORD_DATA |
I2C_FUNC_SMBUS_BLOCK_DATA;
}
static const struct i2c_algorithm smbus_algorithm = {
.smbus_xfer = ali1535_access,
.functionality = ali1535_func,
};
static struct i2c_adapter ali1535_adapter = {
.owner = THIS_MODULE,
.class = I2C_CLASS_HWMON | I2C_CLASS_SPD,
.algo = &smbus_algorithm,
};
static const struct pci_device_id ali1535_ids[] = {
{ PCI_DEVICE(PCI_VENDOR_ID_AL, PCI_DEVICE_ID_AL_M7101) },
{ },
};
MODULE_DEVICE_TABLE(pci, ali1535_ids);
static int ali1535_probe(struct pci_dev *dev, const struct pci_device_id *id)
{
if (ali1535_setup(dev)) {
dev_warn(&dev->dev,
"ALI1535 not detected, module not inserted.\n");
return -ENODEV;
}
/* set up the sysfs linkage to our parent device */
ali1535_adapter.dev.parent = &dev->dev;
snprintf(ali1535_adapter.name, sizeof(ali1535_adapter.name),
"SMBus ALI1535 adapter at %04x", ali1535_offset);
return i2c_add_adapter(&ali1535_adapter);
}
static void ali1535_remove(struct pci_dev *dev)
{
i2c_del_adapter(&ali1535_adapter);
release_region(ali1535_smba, ALI1535_SMB_IOSIZE);
}
static struct pci_driver ali1535_driver = {
.name = "ali1535_smbus",
.id_table = ali1535_ids,
.probe = ali1535_probe,
.remove = ali1535_remove,
};
module_pci_driver(ali1535_driver);
MODULE_AUTHOR("Frodo Looijaard <frodol@dds.nl>, "
"Philip Edelbrock <phil@netroedge.com>, "
"Mark D. Studebaker <mdsxyz123@yahoo.com> "
"and Dan Eaton <dan.eaton@rocketlogix.com>");
MODULE_DESCRIPTION("ALI1535 SMBus driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
duniel/ido-kernel | drivers/net/wireless/iwlwifi/iwl-notif-wait.c | 2357 | 6326 | /******************************************************************************
*
* This file is provided under a dual BSD/GPLv2 license. When using or
* redistributing this file, you may do so under either license.
*
* GPL LICENSE SUMMARY
*
* Copyright(c) 2007 - 2013 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110,
* USA
*
* The full GNU General Public License is included in this distribution
* in the file called COPYING.
*
* Contact Information:
* Intel Linux Wireless <ilw@linux.intel.com>
* Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*
* BSD LICENSE
*
* Copyright(c) 2005 - 2013 Intel Corporation. All rights reserved.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*****************************************************************************/
#include <linux/sched.h>
#include <linux/export.h>
#include "iwl-drv.h"
#include "iwl-notif-wait.h"
void iwl_notification_wait_init(struct iwl_notif_wait_data *notif_wait)
{
spin_lock_init(¬if_wait->notif_wait_lock);
INIT_LIST_HEAD(¬if_wait->notif_waits);
init_waitqueue_head(¬if_wait->notif_waitq);
}
IWL_EXPORT_SYMBOL(iwl_notification_wait_init);
void iwl_notification_wait_notify(struct iwl_notif_wait_data *notif_wait,
struct iwl_rx_packet *pkt)
{
bool triggered = false;
if (!list_empty(¬if_wait->notif_waits)) {
struct iwl_notification_wait *w;
spin_lock(¬if_wait->notif_wait_lock);
list_for_each_entry(w, ¬if_wait->notif_waits, list) {
int i;
bool found = false;
/*
* If it already finished (triggered) or has been
* aborted then don't evaluate it again to avoid races,
* Otherwise the function could be called again even
* though it returned true before
*/
if (w->triggered || w->aborted)
continue;
for (i = 0; i < w->n_cmds; i++) {
if (w->cmds[i] == pkt->hdr.cmd) {
found = true;
break;
}
}
if (!found)
continue;
if (!w->fn || w->fn(notif_wait, pkt, w->fn_data)) {
w->triggered = true;
triggered = true;
}
}
spin_unlock(¬if_wait->notif_wait_lock);
}
if (triggered)
wake_up_all(¬if_wait->notif_waitq);
}
IWL_EXPORT_SYMBOL(iwl_notification_wait_notify);
void iwl_abort_notification_waits(struct iwl_notif_wait_data *notif_wait)
{
struct iwl_notification_wait *wait_entry;
spin_lock(¬if_wait->notif_wait_lock);
list_for_each_entry(wait_entry, ¬if_wait->notif_waits, list)
wait_entry->aborted = true;
spin_unlock(¬if_wait->notif_wait_lock);
wake_up_all(¬if_wait->notif_waitq);
}
IWL_EXPORT_SYMBOL(iwl_abort_notification_waits);
void
iwl_init_notification_wait(struct iwl_notif_wait_data *notif_wait,
struct iwl_notification_wait *wait_entry,
const u8 *cmds, int n_cmds,
bool (*fn)(struct iwl_notif_wait_data *notif_wait,
struct iwl_rx_packet *pkt, void *data),
void *fn_data)
{
if (WARN_ON(n_cmds > MAX_NOTIF_CMDS))
n_cmds = MAX_NOTIF_CMDS;
wait_entry->fn = fn;
wait_entry->fn_data = fn_data;
wait_entry->n_cmds = n_cmds;
memcpy(wait_entry->cmds, cmds, n_cmds);
wait_entry->triggered = false;
wait_entry->aborted = false;
spin_lock_bh(¬if_wait->notif_wait_lock);
list_add(&wait_entry->list, ¬if_wait->notif_waits);
spin_unlock_bh(¬if_wait->notif_wait_lock);
}
IWL_EXPORT_SYMBOL(iwl_init_notification_wait);
int iwl_wait_notification(struct iwl_notif_wait_data *notif_wait,
struct iwl_notification_wait *wait_entry,
unsigned long timeout)
{
int ret;
ret = wait_event_timeout(notif_wait->notif_waitq,
wait_entry->triggered || wait_entry->aborted,
timeout);
spin_lock_bh(¬if_wait->notif_wait_lock);
list_del(&wait_entry->list);
spin_unlock_bh(¬if_wait->notif_wait_lock);
if (wait_entry->aborted)
return -EIO;
/* return value is always >= 0 */
if (ret <= 0)
return -ETIMEDOUT;
return 0;
}
IWL_EXPORT_SYMBOL(iwl_wait_notification);
void iwl_remove_notification(struct iwl_notif_wait_data *notif_wait,
struct iwl_notification_wait *wait_entry)
{
spin_lock_bh(¬if_wait->notif_wait_lock);
list_del(&wait_entry->list);
spin_unlock_bh(¬if_wait->notif_wait_lock);
}
IWL_EXPORT_SYMBOL(iwl_remove_notification);
| gpl-2.0 |
btolfa/kernel_tion_pro28 | sound/pci/echoaudio/echoaudio_dsp.c | 3125 | 30624 | /****************************************************************************
Copyright Echo Digital Audio Corporation (c) 1998 - 2004
All rights reserved
www.echoaudio.com
This file is part of Echo Digital Audio's generic driver library.
Echo Digital Audio's generic driver library 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 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.
*************************************************************************
Translation from C++ and adaptation for use in ALSA-Driver
were made by Giuliano Pochini <pochini@shiny.it>
****************************************************************************/
#if PAGE_SIZE < 4096
#error PAGE_SIZE is < 4k
#endif
static int restore_dsp_rettings(struct echoaudio *chip);
/* Some vector commands involve the DSP reading or writing data to and from the
comm page; if you send one of these commands to the DSP, it will complete the
command and then write a non-zero value to the Handshake field in the
comm page. This function waits for the handshake to show up. */
static int wait_handshake(struct echoaudio *chip)
{
int i;
/* Wait up to 20ms for the handshake from the DSP */
for (i = 0; i < HANDSHAKE_TIMEOUT; i++) {
/* Look for the handshake value */
barrier();
if (chip->comm_page->handshake) {
return 0;
}
udelay(1);
}
snd_printk(KERN_ERR "wait_handshake(): Timeout waiting for DSP\n");
return -EBUSY;
}
/* Much of the interaction between the DSP and the driver is done via vector
commands; send_vector writes a vector command to the DSP. Typically, this
causes the DSP to read or write fields in the comm page.
PCI posting is not required thanks to the handshake logic. */
static int send_vector(struct echoaudio *chip, u32 command)
{
int i;
wmb(); /* Flush all pending writes before sending the command */
/* Wait up to 100ms for the "vector busy" bit to be off */
for (i = 0; i < VECTOR_BUSY_TIMEOUT; i++) {
if (!(get_dsp_register(chip, CHI32_VECTOR_REG) &
CHI32_VECTOR_BUSY)) {
set_dsp_register(chip, CHI32_VECTOR_REG, command);
/*if (i) DE_ACT(("send_vector time: %d\n", i));*/
return 0;
}
udelay(1);
}
DE_ACT((KERN_ERR "timeout on send_vector\n"));
return -EBUSY;
}
/* write_dsp writes a 32-bit value to the DSP; this is used almost
exclusively for loading the DSP. */
static int write_dsp(struct echoaudio *chip, u32 data)
{
u32 status, i;
for (i = 0; i < 10000000; i++) { /* timeout = 10s */
status = get_dsp_register(chip, CHI32_STATUS_REG);
if ((status & CHI32_STATUS_HOST_WRITE_EMPTY) != 0) {
set_dsp_register(chip, CHI32_DATA_REG, data);
wmb(); /* write it immediately */
return 0;
}
udelay(1);
cond_resched();
}
chip->bad_board = TRUE; /* Set TRUE until DSP re-loaded */
DE_ACT((KERN_ERR "write_dsp: Set bad_board to TRUE\n"));
return -EIO;
}
/* read_dsp reads a 32-bit value from the DSP; this is used almost
exclusively for loading the DSP and checking the status of the ASIC. */
static int read_dsp(struct echoaudio *chip, u32 *data)
{
u32 status, i;
for (i = 0; i < READ_DSP_TIMEOUT; i++) {
status = get_dsp_register(chip, CHI32_STATUS_REG);
if ((status & CHI32_STATUS_HOST_READ_FULL) != 0) {
*data = get_dsp_register(chip, CHI32_DATA_REG);
return 0;
}
udelay(1);
cond_resched();
}
chip->bad_board = TRUE; /* Set TRUE until DSP re-loaded */
DE_INIT((KERN_ERR "read_dsp: Set bad_board to TRUE\n"));
return -EIO;
}
/****************************************************************************
Firmware loading functions
****************************************************************************/
/* This function is used to read back the serial number from the DSP;
this is triggered by the SET_COMMPAGE_ADDR command.
Only some early Echogals products have serial numbers in the ROM;
the serial number is not used, but you still need to do this as
part of the DSP load process. */
static int read_sn(struct echoaudio *chip)
{
int i;
u32 sn[6];
for (i = 0; i < 5; i++) {
if (read_dsp(chip, &sn[i])) {
snd_printk(KERN_ERR "Failed to read serial number\n");
return -EIO;
}
}
DE_INIT(("Read serial number %08x %08x %08x %08x %08x\n",
sn[0], sn[1], sn[2], sn[3], sn[4]));
return 0;
}
#ifndef ECHOCARD_HAS_ASIC
/* This card has no ASIC, just return ok */
static inline int check_asic_status(struct echoaudio *chip)
{
chip->asic_loaded = TRUE;
return 0;
}
#endif /* !ECHOCARD_HAS_ASIC */
#ifdef ECHOCARD_HAS_ASIC
/* Load ASIC code - done after the DSP is loaded */
static int load_asic_generic(struct echoaudio *chip, u32 cmd, short asic)
{
const struct firmware *fw;
int err;
u32 i, size;
u8 *code;
err = get_firmware(&fw, chip, asic);
if (err < 0) {
snd_printk(KERN_WARNING "Firmware not found !\n");
return err;
}
code = (u8 *)fw->data;
size = fw->size;
/* Send the "Here comes the ASIC" command */
if (write_dsp(chip, cmd) < 0)
goto la_error;
/* Write length of ASIC file in bytes */
if (write_dsp(chip, size) < 0)
goto la_error;
for (i = 0; i < size; i++) {
if (write_dsp(chip, code[i]) < 0)
goto la_error;
}
DE_INIT(("ASIC loaded\n"));
free_firmware(fw);
return 0;
la_error:
DE_INIT(("failed on write_dsp\n"));
free_firmware(fw);
return -EIO;
}
#endif /* ECHOCARD_HAS_ASIC */
#ifdef DSP_56361
/* Install the resident loader for 56361 DSPs; The resident loader is on
the EPROM on the board for 56301 DSP. The resident loader is a tiny little
program that is used to load the real DSP code. */
static int install_resident_loader(struct echoaudio *chip)
{
u32 address;
int index, words, i;
u16 *code;
u32 status;
const struct firmware *fw;
/* 56361 cards only! This check is required by the old 56301-based
Mona and Gina24 */
if (chip->device_id != DEVICE_ID_56361)
return 0;
/* Look to see if the resident loader is present. If the resident
loader is already installed, host flag 5 will be on. */
status = get_dsp_register(chip, CHI32_STATUS_REG);
if (status & CHI32_STATUS_REG_HF5) {
DE_INIT(("Resident loader already installed; status is 0x%x\n",
status));
return 0;
}
i = get_firmware(&fw, chip, FW_361_LOADER);
if (i < 0) {
snd_printk(KERN_WARNING "Firmware not found !\n");
return i;
}
/* The DSP code is an array of 16 bit words. The array is divided up
into sections. The first word of each section is the size in words,
followed by the section type.
Since DSP addresses and data are 24 bits wide, they each take up two
16 bit words in the array.
This is a lot like the other loader loop, but it's not a loop, you
don't write the memory type, and you don't write a zero at the end. */
/* Set DSP format bits for 24 bit mode */
set_dsp_register(chip, CHI32_CONTROL_REG,
get_dsp_register(chip, CHI32_CONTROL_REG) | 0x900);
code = (u16 *)fw->data;
/* Skip the header section; the first word in the array is the size
of the first section, so the first real section of code is pointed
to by Code[0]. */
index = code[0];
/* Skip the section size, LRS block type, and DSP memory type */
index += 3;
/* Get the number of DSP words to write */
words = code[index++];
/* Get the DSP address for this block; 24 bits, so build from two words */
address = ((u32)code[index] << 16) + code[index + 1];
index += 2;
/* Write the count to the DSP */
if (write_dsp(chip, words)) {
DE_INIT(("install_resident_loader: Failed to write word count!\n"));
goto irl_error;
}
/* Write the DSP address */
if (write_dsp(chip, address)) {
DE_INIT(("install_resident_loader: Failed to write DSP address!\n"));
goto irl_error;
}
/* Write out this block of code to the DSP */
for (i = 0; i < words; i++) {
u32 data;
data = ((u32)code[index] << 16) + code[index + 1];
if (write_dsp(chip, data)) {
DE_INIT(("install_resident_loader: Failed to write DSP code\n"));
goto irl_error;
}
index += 2;
}
/* Wait for flag 5 to come up */
for (i = 0; i < 200; i++) { /* Timeout is 50us * 200 = 10ms */
udelay(50);
status = get_dsp_register(chip, CHI32_STATUS_REG);
if (status & CHI32_STATUS_REG_HF5)
break;
}
if (i == 200) {
DE_INIT(("Resident loader failed to set HF5\n"));
goto irl_error;
}
DE_INIT(("Resident loader successfully installed\n"));
free_firmware(fw);
return 0;
irl_error:
free_firmware(fw);
return -EIO;
}
#endif /* DSP_56361 */
static int load_dsp(struct echoaudio *chip, u16 *code)
{
u32 address, data;
int index, words, i;
if (chip->dsp_code == code) {
DE_INIT(("DSP is already loaded!\n"));
return 0;
}
chip->bad_board = TRUE; /* Set TRUE until DSP loaded */
chip->dsp_code = NULL; /* Current DSP code not loaded */
chip->asic_loaded = FALSE; /* Loading the DSP code will reset the ASIC */
DE_INIT(("load_dsp: Set bad_board to TRUE\n"));
/* If this board requires a resident loader, install it. */
#ifdef DSP_56361
if ((i = install_resident_loader(chip)) < 0)
return i;
#endif
/* Send software reset command */
if (send_vector(chip, DSP_VC_RESET) < 0) {
DE_INIT(("LoadDsp: send_vector DSP_VC_RESET failed, Critical Failure\n"));
return -EIO;
}
/* Delay 10us */
udelay(10);
/* Wait 10ms for HF3 to indicate that software reset is complete */
for (i = 0; i < 1000; i++) { /* Timeout is 10us * 1000 = 10ms */
if (get_dsp_register(chip, CHI32_STATUS_REG) &
CHI32_STATUS_REG_HF3)
break;
udelay(10);
}
if (i == 1000) {
DE_INIT(("load_dsp: Timeout waiting for CHI32_STATUS_REG_HF3\n"));
return -EIO;
}
/* Set DSP format bits for 24 bit mode now that soft reset is done */
set_dsp_register(chip, CHI32_CONTROL_REG,
get_dsp_register(chip, CHI32_CONTROL_REG) | 0x900);
/* Main loader loop */
index = code[0];
for (;;) {
int block_type, mem_type;
/* Total Block Size */
index++;
/* Block Type */
block_type = code[index];
if (block_type == 4) /* We're finished */
break;
index++;
/* Memory Type P=0,X=1,Y=2 */
mem_type = code[index++];
/* Block Code Size */
words = code[index++];
if (words == 0) /* We're finished */
break;
/* Start Address */
address = ((u32)code[index] << 16) + code[index + 1];
index += 2;
if (write_dsp(chip, words) < 0) {
DE_INIT(("load_dsp: failed to write number of DSP words\n"));
return -EIO;
}
if (write_dsp(chip, address) < 0) {
DE_INIT(("load_dsp: failed to write DSP address\n"));
return -EIO;
}
if (write_dsp(chip, mem_type) < 0) {
DE_INIT(("load_dsp: failed to write DSP memory type\n"));
return -EIO;
}
/* Code */
for (i = 0; i < words; i++, index+=2) {
data = ((u32)code[index] << 16) + code[index + 1];
if (write_dsp(chip, data) < 0) {
DE_INIT(("load_dsp: failed to write DSP data\n"));
return -EIO;
}
}
}
if (write_dsp(chip, 0) < 0) { /* We're done!!! */
DE_INIT(("load_dsp: Failed to write final zero\n"));
return -EIO;
}
udelay(10);
for (i = 0; i < 5000; i++) { /* Timeout is 100us * 5000 = 500ms */
/* Wait for flag 4 - indicates that the DSP loaded OK */
if (get_dsp_register(chip, CHI32_STATUS_REG) &
CHI32_STATUS_REG_HF4) {
set_dsp_register(chip, CHI32_CONTROL_REG,
get_dsp_register(chip, CHI32_CONTROL_REG) & ~0x1b00);
if (write_dsp(chip, DSP_FNC_SET_COMMPAGE_ADDR) < 0) {
DE_INIT(("load_dsp: Failed to write DSP_FNC_SET_COMMPAGE_ADDR\n"));
return -EIO;
}
if (write_dsp(chip, chip->comm_page_phys) < 0) {
DE_INIT(("load_dsp: Failed to write comm page address\n"));
return -EIO;
}
/* Get the serial number via slave mode.
This is triggered by the SET_COMMPAGE_ADDR command.
We don't actually use the serial number but we have to
get it as part of the DSP init voodoo. */
if (read_sn(chip) < 0) {
DE_INIT(("load_dsp: Failed to read serial number\n"));
return -EIO;
}
chip->dsp_code = code; /* Show which DSP code loaded */
chip->bad_board = FALSE; /* DSP OK */
DE_INIT(("load_dsp: OK!\n"));
return 0;
}
udelay(100);
}
DE_INIT(("load_dsp: DSP load timed out waiting for HF4\n"));
return -EIO;
}
/* load_firmware takes care of loading the DSP and any ASIC code. */
static int load_firmware(struct echoaudio *chip)
{
const struct firmware *fw;
int box_type, err;
if (snd_BUG_ON(!chip->dsp_code_to_load || !chip->comm_page))
return -EPERM;
/* See if the ASIC is present and working - only if the DSP is already loaded */
if (chip->dsp_code) {
if ((box_type = check_asic_status(chip)) >= 0)
return box_type;
/* ASIC check failed; force the DSP to reload */
chip->dsp_code = NULL;
}
err = get_firmware(&fw, chip, chip->dsp_code_to_load);
if (err < 0)
return err;
err = load_dsp(chip, (u16 *)fw->data);
free_firmware(fw);
if (err < 0)
return err;
if ((box_type = load_asic(chip)) < 0)
return box_type; /* error */
return box_type;
}
/****************************************************************************
Mixer functions
****************************************************************************/
#if defined(ECHOCARD_HAS_INPUT_NOMINAL_LEVEL) || \
defined(ECHOCARD_HAS_OUTPUT_NOMINAL_LEVEL)
/* Set the nominal level for an input or output bus (true = -10dBV, false = +4dBu) */
static int set_nominal_level(struct echoaudio *chip, u16 index, char consumer)
{
if (snd_BUG_ON(index >= num_busses_out(chip) + num_busses_in(chip)))
return -EINVAL;
/* Wait for the handshake (OK even if ASIC is not loaded) */
if (wait_handshake(chip))
return -EIO;
chip->nominal_level[index] = consumer;
if (consumer)
chip->comm_page->nominal_level_mask |= cpu_to_le32(1 << index);
else
chip->comm_page->nominal_level_mask &= ~cpu_to_le32(1 << index);
return 0;
}
#endif /* ECHOCARD_HAS_*_NOMINAL_LEVEL */
/* Set the gain for a single physical output channel (dB). */
static int set_output_gain(struct echoaudio *chip, u16 channel, s8 gain)
{
if (snd_BUG_ON(channel >= num_busses_out(chip)))
return -EINVAL;
if (wait_handshake(chip))
return -EIO;
/* Save the new value */
chip->output_gain[channel] = gain;
chip->comm_page->line_out_level[channel] = gain;
return 0;
}
#ifdef ECHOCARD_HAS_MONITOR
/* Set the monitor level from an input bus to an output bus. */
static int set_monitor_gain(struct echoaudio *chip, u16 output, u16 input,
s8 gain)
{
if (snd_BUG_ON(output >= num_busses_out(chip) ||
input >= num_busses_in(chip)))
return -EINVAL;
if (wait_handshake(chip))
return -EIO;
chip->monitor_gain[output][input] = gain;
chip->comm_page->monitors[monitor_index(chip, output, input)] = gain;
return 0;
}
#endif /* ECHOCARD_HAS_MONITOR */
/* Tell the DSP to read and update output, nominal & monitor levels in comm page. */
static int update_output_line_level(struct echoaudio *chip)
{
if (wait_handshake(chip))
return -EIO;
clear_handshake(chip);
return send_vector(chip, DSP_VC_UPDATE_OUTVOL);
}
/* Tell the DSP to read and update input levels in comm page */
static int update_input_line_level(struct echoaudio *chip)
{
if (wait_handshake(chip))
return -EIO;
clear_handshake(chip);
return send_vector(chip, DSP_VC_UPDATE_INGAIN);
}
/* set_meters_on turns the meters on or off. If meters are turned on, the DSP
will write the meter and clock detect values to the comm page at about 30Hz */
static void set_meters_on(struct echoaudio *chip, char on)
{
if (on && !chip->meters_enabled) {
send_vector(chip, DSP_VC_METERS_ON);
chip->meters_enabled = 1;
} else if (!on && chip->meters_enabled) {
send_vector(chip, DSP_VC_METERS_OFF);
chip->meters_enabled = 0;
memset((s8 *)chip->comm_page->vu_meter, ECHOGAIN_MUTED,
DSP_MAXPIPES);
memset((s8 *)chip->comm_page->peak_meter, ECHOGAIN_MUTED,
DSP_MAXPIPES);
}
}
/* Fill out an the given array using the current values in the comm page.
Meters are written in the comm page by the DSP in this order:
Output busses
Input busses
Output pipes (vmixer cards only)
This function assumes there are no more than 16 in/out busses or pipes
Meters is an array [3][16][2] of long. */
static void get_audio_meters(struct echoaudio *chip, long *meters)
{
int i, m, n;
m = 0;
n = 0;
for (i = 0; i < num_busses_out(chip); i++, m++) {
meters[n++] = chip->comm_page->vu_meter[m];
meters[n++] = chip->comm_page->peak_meter[m];
}
for (; n < 32; n++)
meters[n] = 0;
#ifdef ECHOCARD_ECHO3G
m = E3G_MAX_OUTPUTS; /* Skip unused meters */
#endif
for (i = 0; i < num_busses_in(chip); i++, m++) {
meters[n++] = chip->comm_page->vu_meter[m];
meters[n++] = chip->comm_page->peak_meter[m];
}
for (; n < 64; n++)
meters[n] = 0;
#ifdef ECHOCARD_HAS_VMIXER
for (i = 0; i < num_pipes_out(chip); i++, m++) {
meters[n++] = chip->comm_page->vu_meter[m];
meters[n++] = chip->comm_page->peak_meter[m];
}
#endif
for (; n < 96; n++)
meters[n] = 0;
}
static int restore_dsp_rettings(struct echoaudio *chip)
{
int i, o, err;
DE_INIT(("restore_dsp_settings\n"));
if ((err = check_asic_status(chip)) < 0)
return err;
/* Gina20/Darla20 only. Should be harmless for other cards. */
chip->comm_page->gd_clock_state = GD_CLOCK_UNDEF;
chip->comm_page->gd_spdif_status = GD_SPDIF_STATUS_UNDEF;
chip->comm_page->handshake = 0xffffffff;
/* Restore output busses */
for (i = 0; i < num_busses_out(chip); i++) {
err = set_output_gain(chip, i, chip->output_gain[i]);
if (err < 0)
return err;
}
#ifdef ECHOCARD_HAS_VMIXER
for (i = 0; i < num_pipes_out(chip); i++)
for (o = 0; o < num_busses_out(chip); o++) {
err = set_vmixer_gain(chip, o, i,
chip->vmixer_gain[o][i]);
if (err < 0)
return err;
}
if (update_vmixer_level(chip) < 0)
return -EIO;
#endif /* ECHOCARD_HAS_VMIXER */
#ifdef ECHOCARD_HAS_MONITOR
for (o = 0; o < num_busses_out(chip); o++)
for (i = 0; i < num_busses_in(chip); i++) {
err = set_monitor_gain(chip, o, i,
chip->monitor_gain[o][i]);
if (err < 0)
return err;
}
#endif /* ECHOCARD_HAS_MONITOR */
#ifdef ECHOCARD_HAS_INPUT_GAIN
for (i = 0; i < num_busses_in(chip); i++) {
err = set_input_gain(chip, i, chip->input_gain[i]);
if (err < 0)
return err;
}
#endif /* ECHOCARD_HAS_INPUT_GAIN */
err = update_output_line_level(chip);
if (err < 0)
return err;
err = update_input_line_level(chip);
if (err < 0)
return err;
err = set_sample_rate(chip, chip->sample_rate);
if (err < 0)
return err;
if (chip->meters_enabled) {
err = send_vector(chip, DSP_VC_METERS_ON);
if (err < 0)
return err;
}
#ifdef ECHOCARD_HAS_DIGITAL_MODE_SWITCH
if (set_digital_mode(chip, chip->digital_mode) < 0)
return -EIO;
#endif
#ifdef ECHOCARD_HAS_DIGITAL_IO
if (set_professional_spdif(chip, chip->professional_spdif) < 0)
return -EIO;
#endif
#ifdef ECHOCARD_HAS_PHANTOM_POWER
if (set_phantom_power(chip, chip->phantom_power) < 0)
return -EIO;
#endif
#ifdef ECHOCARD_HAS_EXTERNAL_CLOCK
/* set_input_clock() also restores automute setting */
if (set_input_clock(chip, chip->input_clock) < 0)
return -EIO;
#endif
#ifdef ECHOCARD_HAS_OUTPUT_CLOCK_SWITCH
if (set_output_clock(chip, chip->output_clock) < 0)
return -EIO;
#endif
if (wait_handshake(chip) < 0)
return -EIO;
clear_handshake(chip);
if (send_vector(chip, DSP_VC_UPDATE_FLAGS) < 0)
return -EIO;
DE_INIT(("restore_dsp_rettings done\n"));
return 0;
}
/****************************************************************************
Transport functions
****************************************************************************/
/* set_audio_format() sets the format of the audio data in host memory for
this pipe. Note that _MS_ (mono-to-stereo) playback modes are not used by ALSA
but they are here because they are just mono while capturing */
static void set_audio_format(struct echoaudio *chip, u16 pipe_index,
const struct audioformat *format)
{
u16 dsp_format;
dsp_format = DSP_AUDIOFORM_SS_16LE;
/* Look for super-interleave (no big-endian and 8 bits) */
if (format->interleave > 2) {
switch (format->bits_per_sample) {
case 16:
dsp_format = DSP_AUDIOFORM_SUPER_INTERLEAVE_16LE;
break;
case 24:
dsp_format = DSP_AUDIOFORM_SUPER_INTERLEAVE_24LE;
break;
case 32:
dsp_format = DSP_AUDIOFORM_SUPER_INTERLEAVE_32LE;
break;
}
dsp_format |= format->interleave;
} else if (format->data_are_bigendian) {
/* For big-endian data, only 32 bit samples are supported */
switch (format->interleave) {
case 1:
dsp_format = DSP_AUDIOFORM_MM_32BE;
break;
#ifdef ECHOCARD_HAS_STEREO_BIG_ENDIAN32
case 2:
dsp_format = DSP_AUDIOFORM_SS_32BE;
break;
#endif
}
} else if (format->interleave == 1 &&
format->bits_per_sample == 32 && !format->mono_to_stereo) {
/* 32 bit little-endian mono->mono case */
dsp_format = DSP_AUDIOFORM_MM_32LE;
} else {
/* Handle the other little-endian formats */
switch (format->bits_per_sample) {
case 8:
if (format->interleave == 2)
dsp_format = DSP_AUDIOFORM_SS_8;
else
dsp_format = DSP_AUDIOFORM_MS_8;
break;
default:
case 16:
if (format->interleave == 2)
dsp_format = DSP_AUDIOFORM_SS_16LE;
else
dsp_format = DSP_AUDIOFORM_MS_16LE;
break;
case 24:
if (format->interleave == 2)
dsp_format = DSP_AUDIOFORM_SS_24LE;
else
dsp_format = DSP_AUDIOFORM_MS_24LE;
break;
case 32:
if (format->interleave == 2)
dsp_format = DSP_AUDIOFORM_SS_32LE;
else
dsp_format = DSP_AUDIOFORM_MS_32LE;
break;
}
}
DE_ACT(("set_audio_format[%d] = %x\n", pipe_index, dsp_format));
chip->comm_page->audio_format[pipe_index] = cpu_to_le16(dsp_format);
}
/* start_transport starts transport for a set of pipes.
The bits 1 in channel_mask specify what pipes to start. Only the bit of the
first channel must be set, regardless its interleave.
Same thing for pause_ and stop_ -trasport below. */
static int start_transport(struct echoaudio *chip, u32 channel_mask,
u32 cyclic_mask)
{
DE_ACT(("start_transport %x\n", channel_mask));
if (wait_handshake(chip))
return -EIO;
chip->comm_page->cmd_start |= cpu_to_le32(channel_mask);
if (chip->comm_page->cmd_start) {
clear_handshake(chip);
send_vector(chip, DSP_VC_START_TRANSFER);
if (wait_handshake(chip))
return -EIO;
/* Keep track of which pipes are transporting */
chip->active_mask |= channel_mask;
chip->comm_page->cmd_start = 0;
return 0;
}
DE_ACT(("start_transport: No pipes to start!\n"));
return -EINVAL;
}
static int pause_transport(struct echoaudio *chip, u32 channel_mask)
{
DE_ACT(("pause_transport %x\n", channel_mask));
if (wait_handshake(chip))
return -EIO;
chip->comm_page->cmd_stop |= cpu_to_le32(channel_mask);
chip->comm_page->cmd_reset = 0;
if (chip->comm_page->cmd_stop) {
clear_handshake(chip);
send_vector(chip, DSP_VC_STOP_TRANSFER);
if (wait_handshake(chip))
return -EIO;
/* Keep track of which pipes are transporting */
chip->active_mask &= ~channel_mask;
chip->comm_page->cmd_stop = 0;
chip->comm_page->cmd_reset = 0;
return 0;
}
DE_ACT(("pause_transport: No pipes to stop!\n"));
return 0;
}
static int stop_transport(struct echoaudio *chip, u32 channel_mask)
{
DE_ACT(("stop_transport %x\n", channel_mask));
if (wait_handshake(chip))
return -EIO;
chip->comm_page->cmd_stop |= cpu_to_le32(channel_mask);
chip->comm_page->cmd_reset |= cpu_to_le32(channel_mask);
if (chip->comm_page->cmd_reset) {
clear_handshake(chip);
send_vector(chip, DSP_VC_STOP_TRANSFER);
if (wait_handshake(chip))
return -EIO;
/* Keep track of which pipes are transporting */
chip->active_mask &= ~channel_mask;
chip->comm_page->cmd_stop = 0;
chip->comm_page->cmd_reset = 0;
return 0;
}
DE_ACT(("stop_transport: No pipes to stop!\n"));
return 0;
}
static inline int is_pipe_allocated(struct echoaudio *chip, u16 pipe_index)
{
return (chip->pipe_alloc_mask & (1 << pipe_index));
}
/* Stops everything and turns off the DSP. All pipes should be already
stopped and unallocated. */
static int rest_in_peace(struct echoaudio *chip)
{
DE_ACT(("rest_in_peace() open=%x\n", chip->pipe_alloc_mask));
/* Stops all active pipes (just to be sure) */
stop_transport(chip, chip->active_mask);
set_meters_on(chip, FALSE);
#ifdef ECHOCARD_HAS_MIDI
enable_midi_input(chip, FALSE);
#endif
/* Go to sleep */
if (chip->dsp_code) {
/* Make load_firmware do a complete reload */
chip->dsp_code = NULL;
/* Put the DSP to sleep */
return send_vector(chip, DSP_VC_GO_COMATOSE);
}
return 0;
}
/* Fills the comm page with default values */
static int init_dsp_comm_page(struct echoaudio *chip)
{
/* Check if the compiler added extra padding inside the structure */
if (offsetof(struct comm_page, midi_output) != 0xbe0) {
DE_INIT(("init_dsp_comm_page() - Invalid struct comm_page structure\n"));
return -EPERM;
}
/* Init all the basic stuff */
chip->card_name = ECHOCARD_NAME;
chip->bad_board = TRUE; /* Set TRUE until DSP loaded */
chip->dsp_code = NULL; /* Current DSP code not loaded */
chip->asic_loaded = FALSE;
memset(chip->comm_page, 0, sizeof(struct comm_page));
/* Init the comm page */
chip->comm_page->comm_size =
cpu_to_le32(sizeof(struct comm_page));
chip->comm_page->handshake = 0xffffffff;
chip->comm_page->midi_out_free_count =
cpu_to_le32(DSP_MIDI_OUT_FIFO_SIZE);
chip->comm_page->sample_rate = cpu_to_le32(44100);
/* Set line levels so we don't blast any inputs on startup */
memset(chip->comm_page->monitors, ECHOGAIN_MUTED, MONITOR_ARRAY_SIZE);
memset(chip->comm_page->vmixer, ECHOGAIN_MUTED, VMIXER_ARRAY_SIZE);
return 0;
}
/* This function initializes the chip structure with default values, ie. all
* muted and internal clock source. Then it copies the settings to the DSP.
* This MUST be called after the DSP is up and running !
*/
static int init_line_levels(struct echoaudio *chip)
{
DE_INIT(("init_line_levels\n"));
memset(chip->output_gain, ECHOGAIN_MUTED, sizeof(chip->output_gain));
memset(chip->input_gain, ECHOGAIN_MUTED, sizeof(chip->input_gain));
memset(chip->monitor_gain, ECHOGAIN_MUTED, sizeof(chip->monitor_gain));
memset(chip->vmixer_gain, ECHOGAIN_MUTED, sizeof(chip->vmixer_gain));
chip->input_clock = ECHO_CLOCK_INTERNAL;
chip->output_clock = ECHO_CLOCK_WORD;
chip->sample_rate = 44100;
return restore_dsp_rettings(chip);
}
/* This is low level part of the interrupt handler.
It returns -1 if the IRQ is not ours, or N>=0 if it is, where N is the number
of midi data in the input queue. */
static int service_irq(struct echoaudio *chip)
{
int st;
/* Read the DSP status register and see if this DSP generated this interrupt */
if (get_dsp_register(chip, CHI32_STATUS_REG) & CHI32_STATUS_IRQ) {
st = 0;
#ifdef ECHOCARD_HAS_MIDI
/* Get and parse midi data if present */
if (chip->comm_page->midi_input[0]) /* The count is at index 0 */
st = midi_service_irq(chip); /* Returns how many midi bytes we received */
#endif
/* Clear the hardware interrupt */
chip->comm_page->midi_input[0] = 0;
send_vector(chip, DSP_VC_ACK_INT);
return st;
}
return -1;
}
/******************************************************************************
Functions for opening and closing pipes
******************************************************************************/
/* allocate_pipes is used to reserve audio pipes for your exclusive use.
The call will fail if some pipes are already allocated. */
static int allocate_pipes(struct echoaudio *chip, struct audiopipe *pipe,
int pipe_index, int interleave)
{
int i;
u32 channel_mask;
char is_cyclic;
DE_ACT(("allocate_pipes: ch=%d int=%d\n", pipe_index, interleave));
if (chip->bad_board)
return -EIO;
is_cyclic = 1; /* This driver uses cyclic buffers only */
for (channel_mask = i = 0; i < interleave; i++)
channel_mask |= 1 << (pipe_index + i);
if (chip->pipe_alloc_mask & channel_mask) {
DE_ACT(("allocate_pipes: channel already open\n"));
return -EAGAIN;
}
chip->comm_page->position[pipe_index] = 0;
chip->pipe_alloc_mask |= channel_mask;
if (is_cyclic)
chip->pipe_cyclic_mask |= channel_mask;
pipe->index = pipe_index;
pipe->interleave = interleave;
pipe->state = PIPE_STATE_STOPPED;
/* The counter register is where the DSP writes the 32 bit DMA
position for a pipe. The DSP is constantly updating this value as
it moves data. The DMA counter is in units of bytes, not samples. */
pipe->dma_counter = &chip->comm_page->position[pipe_index];
*pipe->dma_counter = 0;
DE_ACT(("allocate_pipes: ok\n"));
return pipe_index;
}
static int free_pipes(struct echoaudio *chip, struct audiopipe *pipe)
{
u32 channel_mask;
int i;
DE_ACT(("free_pipes: Pipe %d\n", pipe->index));
if (snd_BUG_ON(!is_pipe_allocated(chip, pipe->index)))
return -EINVAL;
if (snd_BUG_ON(pipe->state != PIPE_STATE_STOPPED))
return -EINVAL;
for (channel_mask = i = 0; i < pipe->interleave; i++)
channel_mask |= 1 << (pipe->index + i);
chip->pipe_alloc_mask &= ~channel_mask;
chip->pipe_cyclic_mask &= ~channel_mask;
return 0;
}
/******************************************************************************
Functions for managing the scatter-gather list
******************************************************************************/
static int sglist_init(struct echoaudio *chip, struct audiopipe *pipe)
{
pipe->sglist_head = 0;
memset(pipe->sgpage.area, 0, PAGE_SIZE);
chip->comm_page->sglist_addr[pipe->index].addr =
cpu_to_le32(pipe->sgpage.addr);
return 0;
}
static int sglist_add_mapping(struct echoaudio *chip, struct audiopipe *pipe,
dma_addr_t address, size_t length)
{
int head = pipe->sglist_head;
struct sg_entry *list = (struct sg_entry *)pipe->sgpage.area;
if (head < MAX_SGLIST_ENTRIES - 1) {
list[head].addr = cpu_to_le32(address);
list[head].size = cpu_to_le32(length);
pipe->sglist_head++;
} else {
DE_ACT(("SGlist: too many fragments\n"));
return -ENOMEM;
}
return 0;
}
static inline int sglist_add_irq(struct echoaudio *chip, struct audiopipe *pipe)
{
return sglist_add_mapping(chip, pipe, 0, 0);
}
static inline int sglist_wrap(struct echoaudio *chip, struct audiopipe *pipe)
{
return sglist_add_mapping(chip, pipe, pipe->sgpage.addr, 0);
}
| gpl-2.0 |
ubuntu-touchCAF/android_kernel_motorola_msm8226 | arch/hexagon/kernel/setup.c | 3125 | 3666 | /*
* Arch related setup for Hexagon
*
* Copyright (c) 2010-2011, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include <linux/init.h>
#include <linux/bootmem.h>
#include <linux/mmzone.h>
#include <linux/mm.h>
#include <linux/seq_file.h>
#include <linux/console.h>
#include <linux/of_fdt.h>
#include <asm/io.h>
#include <asm/sections.h>
#include <asm/setup.h>
#include <asm/processor.h>
#include <asm/hexagon_vm.h>
#include <asm/vm_mmu.h>
#include <asm/time.h>
#ifdef CONFIG_OF
#include <asm/prom.h>
#endif
char cmd_line[COMMAND_LINE_SIZE];
static char default_command_line[COMMAND_LINE_SIZE] __initdata = CONFIG_CMDLINE;
int on_simulator;
void __cpuinit calibrate_delay(void)
{
loops_per_jiffy = thread_freq_mhz * 1000000 / HZ;
}
/*
* setup_arch - high level architectural setup routine
* @cmdline_p: pointer to pointer to command-line arguments
*/
void __init setup_arch(char **cmdline_p)
{
char *p = &external_cmdline_buffer;
/*
* These will eventually be pulled in via either some hypervisor
* or devicetree description. Hardwiring for now.
*/
pcycle_freq_mhz = 600;
thread_freq_mhz = 100;
sleep_clk_freq = 32000;
/*
* Set up event bindings to handle exceptions and interrupts.
*/
__vmsetvec(_K_VM_event_vector);
/*
* Simulator has a few differences from the hardware.
* For now, check uninitialized-but-mapped memory
* prior to invoking setup_arch_memory().
*/
if (*(int *)((unsigned long)_end + 8) == 0x1f1f1f1f)
on_simulator = 1;
else
on_simulator = 0;
if (p[0] != '\0')
strlcpy(boot_command_line, p, COMMAND_LINE_SIZE);
else
strlcpy(boot_command_line, default_command_line,
COMMAND_LINE_SIZE);
/*
* boot_command_line and the value set up by setup_arch
* are both picked up by the init code. If no reason to
* make them different, pass the same pointer back.
*/
strlcpy(cmd_line, boot_command_line, COMMAND_LINE_SIZE);
*cmdline_p = cmd_line;
parse_early_param();
setup_arch_memory();
#ifdef CONFIG_SMP
smp_start_cpus();
#endif
}
/*
* Functions for dumping CPU info via /proc
* Probably should move to kernel/proc.c or something.
*/
static void *c_start(struct seq_file *m, loff_t *pos)
{
return *pos < nr_cpu_ids ? (void *)((unsigned long) *pos + 1) : NULL;
}
static void *c_next(struct seq_file *m, void *v, loff_t *pos)
{
++*pos;
return c_start(m, pos);
}
static void c_stop(struct seq_file *m, void *v)
{
}
/*
* Eventually this will dump information about
* CPU properties like ISA level, TLB size, etc.
*/
static int show_cpuinfo(struct seq_file *m, void *v)
{
int cpu = (unsigned long) v - 1;
seq_printf(m, "processor\t: %d\n", cpu);
seq_printf(m, "model name\t: Hexagon Virtual Machine\n");
seq_printf(m, "BogoMips\t: %lu.%02lu\n",
(loops_per_jiffy * HZ) / 500000,
((loops_per_jiffy * HZ) / 5000) % 100);
seq_printf(m, "\n");
return 0;
}
const struct seq_operations cpuinfo_op = {
.start = &c_start,
.next = &c_next,
.stop = &c_stop,
.show = &show_cpuinfo,
};
| gpl-2.0 |
regiesoriano/rs_kernel_msm | fs/ext4/dir.c | 3637 | 17332 | /*
* linux/fs/ext4/dir.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card (card@masi.ibp.fr)
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/dir.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* ext4 directory handling functions
*
* Big-endian to little-endian byte-swapping/bitmaps by
* David S. Miller (davem@caip.rutgers.edu), 1995
*
* Hash Tree Directory indexing (c) 2001 Daniel Phillips
*
*/
#include <linux/fs.h>
#include <linux/jbd2.h>
#include <linux/buffer_head.h>
#include <linux/slab.h>
#include <linux/rbtree.h>
#include "ext4.h"
static unsigned char ext4_filetype_table[] = {
DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
};
static int ext4_dx_readdir(struct file *filp,
void *dirent, filldir_t filldir);
static unsigned char get_dtype(struct super_block *sb, int filetype)
{
if (!EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_FILETYPE) ||
(filetype >= EXT4_FT_MAX))
return DT_UNKNOWN;
return (ext4_filetype_table[filetype]);
}
/**
* Check if the given dir-inode refers to an htree-indexed directory
* (or a directory which chould potentially get coverted to use htree
* indexing).
*
* Return 1 if it is a dx dir, 0 if not
*/
static int is_dx_dir(struct inode *inode)
{
struct super_block *sb = inode->i_sb;
if (EXT4_HAS_COMPAT_FEATURE(inode->i_sb,
EXT4_FEATURE_COMPAT_DIR_INDEX) &&
((ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) ||
((inode->i_size >> sb->s_blocksize_bits) == 1)))
return 1;
return 0;
}
/*
* Return 0 if the directory entry is OK, and 1 if there is a problem
*
* Note: this is the opposite of what ext2 and ext3 historically returned...
*/
int __ext4_check_dir_entry(const char *function, unsigned int line,
struct inode *dir, struct file *filp,
struct ext4_dir_entry_2 *de,
struct buffer_head *bh,
unsigned int offset)
{
const char *error_msg = NULL;
const int rlen = ext4_rec_len_from_disk(de->rec_len,
dir->i_sb->s_blocksize);
if (unlikely(rlen < EXT4_DIR_REC_LEN(1)))
error_msg = "rec_len is smaller than minimal";
else if (unlikely(rlen % 4 != 0))
error_msg = "rec_len % 4 != 0";
else if (unlikely(rlen < EXT4_DIR_REC_LEN(de->name_len)))
error_msg = "rec_len is too small for name_len";
else if (unlikely(((char *) de - bh->b_data) + rlen >
dir->i_sb->s_blocksize))
error_msg = "directory entry across blocks";
else if (unlikely(le32_to_cpu(de->inode) >
le32_to_cpu(EXT4_SB(dir->i_sb)->s_es->s_inodes_count)))
error_msg = "inode out of bounds";
else
return 0;
if (filp)
ext4_error_file(filp, function, line, bh->b_blocknr,
"bad entry in directory: %s - offset=%u(%u), "
"inode=%u, rec_len=%d, name_len=%d",
error_msg, (unsigned) (offset % bh->b_size),
offset, le32_to_cpu(de->inode),
rlen, de->name_len);
else
ext4_error_inode(dir, function, line, bh->b_blocknr,
"bad entry in directory: %s - offset=%u(%u), "
"inode=%u, rec_len=%d, name_len=%d",
error_msg, (unsigned) (offset % bh->b_size),
offset, le32_to_cpu(de->inode),
rlen, de->name_len);
return 1;
}
static int ext4_readdir(struct file *filp,
void *dirent, filldir_t filldir)
{
int error = 0;
unsigned int offset;
int i, stored;
struct ext4_dir_entry_2 *de;
int err;
struct inode *inode = filp->f_path.dentry->d_inode;
struct super_block *sb = inode->i_sb;
int ret = 0;
int dir_has_error = 0;
if (is_dx_dir(inode)) {
err = ext4_dx_readdir(filp, dirent, filldir);
if (err != ERR_BAD_DX_DIR) {
ret = err;
goto out;
}
/*
* We don't set the inode dirty flag since it's not
* critical that it get flushed back to the disk.
*/
ext4_clear_inode_flag(filp->f_path.dentry->d_inode,
EXT4_INODE_INDEX);
}
stored = 0;
offset = filp->f_pos & (sb->s_blocksize - 1);
while (!error && !stored && filp->f_pos < inode->i_size) {
struct ext4_map_blocks map;
struct buffer_head *bh = NULL;
map.m_lblk = filp->f_pos >> EXT4_BLOCK_SIZE_BITS(sb);
map.m_len = 1;
err = ext4_map_blocks(NULL, inode, &map, 0);
if (err > 0) {
pgoff_t index = map.m_pblk >>
(PAGE_CACHE_SHIFT - inode->i_blkbits);
if (!ra_has_index(&filp->f_ra, index))
page_cache_sync_readahead(
sb->s_bdev->bd_inode->i_mapping,
&filp->f_ra, filp,
index, 1);
filp->f_ra.prev_pos = (loff_t)index << PAGE_CACHE_SHIFT;
bh = ext4_bread(NULL, inode, map.m_lblk, 0, &err);
}
/*
* We ignore I/O errors on directories so users have a chance
* of recovering data when there's a bad sector
*/
if (!bh) {
if (!dir_has_error) {
EXT4_ERROR_FILE(filp, 0,
"directory contains a "
"hole at offset %llu",
(unsigned long long) filp->f_pos);
dir_has_error = 1;
}
/* corrupt size? Maybe no more blocks to read */
if (filp->f_pos > inode->i_blocks << 9)
break;
filp->f_pos += sb->s_blocksize - offset;
continue;
}
revalidate:
/* If the dir block has changed since the last call to
* readdir(2), then we might be pointing to an invalid
* dirent right now. Scan from the start of the block
* to make sure. */
if (filp->f_version != inode->i_version) {
for (i = 0; i < sb->s_blocksize && i < offset; ) {
de = (struct ext4_dir_entry_2 *)
(bh->b_data + i);
/* It's too expensive to do a full
* dirent test each time round this
* loop, but we do have to test at
* least that it is non-zero. A
* failure will be detected in the
* dirent test below. */
if (ext4_rec_len_from_disk(de->rec_len,
sb->s_blocksize) < EXT4_DIR_REC_LEN(1))
break;
i += ext4_rec_len_from_disk(de->rec_len,
sb->s_blocksize);
}
offset = i;
filp->f_pos = (filp->f_pos & ~(sb->s_blocksize - 1))
| offset;
filp->f_version = inode->i_version;
}
while (!error && filp->f_pos < inode->i_size
&& offset < sb->s_blocksize) {
de = (struct ext4_dir_entry_2 *) (bh->b_data + offset);
if (ext4_check_dir_entry(inode, filp, de,
bh, offset)) {
/*
* On error, skip the f_pos to the next block
*/
filp->f_pos = (filp->f_pos |
(sb->s_blocksize - 1)) + 1;
brelse(bh);
ret = stored;
goto out;
}
offset += ext4_rec_len_from_disk(de->rec_len,
sb->s_blocksize);
if (le32_to_cpu(de->inode)) {
/* We might block in the next section
* if the data destination is
* currently swapped out. So, use a
* version stamp to detect whether or
* not the directory has been modified
* during the copy operation.
*/
u64 version = filp->f_version;
error = filldir(dirent, de->name,
de->name_len,
filp->f_pos,
le32_to_cpu(de->inode),
get_dtype(sb, de->file_type));
if (error)
break;
if (version != filp->f_version)
goto revalidate;
stored++;
}
filp->f_pos += ext4_rec_len_from_disk(de->rec_len,
sb->s_blocksize);
}
offset = 0;
brelse(bh);
}
out:
return ret;
}
static inline int is_32bit_api(void)
{
#ifdef CONFIG_COMPAT
return is_compat_task();
#else
return (BITS_PER_LONG == 32);
#endif
}
/*
* These functions convert from the major/minor hash to an f_pos
* value for dx directories
*
* Upper layer (for example NFS) should specify FMODE_32BITHASH or
* FMODE_64BITHASH explicitly. On the other hand, we allow ext4 to be mounted
* directly on both 32-bit and 64-bit nodes, under such case, neither
* FMODE_32BITHASH nor FMODE_64BITHASH is specified.
*/
static inline loff_t hash2pos(struct file *filp, __u32 major, __u32 minor)
{
if ((filp->f_mode & FMODE_32BITHASH) ||
(!(filp->f_mode & FMODE_64BITHASH) && is_32bit_api()))
return major >> 1;
else
return ((__u64)(major >> 1) << 32) | (__u64)minor;
}
static inline __u32 pos2maj_hash(struct file *filp, loff_t pos)
{
if ((filp->f_mode & FMODE_32BITHASH) ||
(!(filp->f_mode & FMODE_64BITHASH) && is_32bit_api()))
return (pos << 1) & 0xffffffff;
else
return ((pos >> 32) << 1) & 0xffffffff;
}
static inline __u32 pos2min_hash(struct file *filp, loff_t pos)
{
if ((filp->f_mode & FMODE_32BITHASH) ||
(!(filp->f_mode & FMODE_64BITHASH) && is_32bit_api()))
return 0;
else
return pos & 0xffffffff;
}
/*
* Return 32- or 64-bit end-of-file for dx directories
*/
static inline loff_t ext4_get_htree_eof(struct file *filp)
{
if ((filp->f_mode & FMODE_32BITHASH) ||
(!(filp->f_mode & FMODE_64BITHASH) && is_32bit_api()))
return EXT4_HTREE_EOF_32BIT;
else
return EXT4_HTREE_EOF_64BIT;
}
/*
* ext4_dir_llseek() based on generic_file_llseek() to handle both
* non-htree and htree directories, where the "offset" is in terms
* of the filename hash value instead of the byte offset.
*
* NOTE: offsets obtained *before* ext4_set_inode_flag(dir, EXT4_INODE_INDEX)
* will be invalid once the directory was converted into a dx directory
*/
loff_t ext4_dir_llseek(struct file *file, loff_t offset, int origin)
{
struct inode *inode = file->f_mapping->host;
loff_t ret = -EINVAL;
int dx_dir = is_dx_dir(inode);
mutex_lock(&inode->i_mutex);
/* NOTE: relative offsets with dx directories might not work
* as expected, as it is difficult to figure out the
* correct offset between dx hashes */
switch (origin) {
case SEEK_END:
if (unlikely(offset > 0))
goto out_err; /* not supported for directories */
/* so only negative offsets are left, does that have a
* meaning for directories at all? */
if (dx_dir)
offset += ext4_get_htree_eof(file);
else
offset += inode->i_size;
break;
case SEEK_CUR:
/*
* Here we special-case the lseek(fd, 0, SEEK_CUR)
* position-querying operation. Avoid rewriting the "same"
* f_pos value back to the file because a concurrent read(),
* write() or lseek() might have altered it
*/
if (offset == 0) {
offset = file->f_pos;
goto out_ok;
}
offset += file->f_pos;
break;
}
if (unlikely(offset < 0))
goto out_err;
if (!dx_dir) {
if (offset > inode->i_sb->s_maxbytes)
goto out_err;
} else if (offset > ext4_get_htree_eof(file))
goto out_err;
/* Special lock needed here? */
if (offset != file->f_pos) {
file->f_pos = offset;
file->f_version = 0;
}
out_ok:
ret = offset;
out_err:
mutex_unlock(&inode->i_mutex);
return ret;
}
/*
* This structure holds the nodes of the red-black tree used to store
* the directory entry in hash order.
*/
struct fname {
__u32 hash;
__u32 minor_hash;
struct rb_node rb_hash;
struct fname *next;
__u32 inode;
__u8 name_len;
__u8 file_type;
char name[0];
};
/*
* This functoin implements a non-recursive way of freeing all of the
* nodes in the red-black tree.
*/
static void free_rb_tree_fname(struct rb_root *root)
{
struct rb_node *n = root->rb_node;
struct rb_node *parent;
struct fname *fname;
while (n) {
/* Do the node's children first */
if (n->rb_left) {
n = n->rb_left;
continue;
}
if (n->rb_right) {
n = n->rb_right;
continue;
}
/*
* The node has no children; free it, and then zero
* out parent's link to it. Finally go to the
* beginning of the loop and try to free the parent
* node.
*/
parent = rb_parent(n);
fname = rb_entry(n, struct fname, rb_hash);
while (fname) {
struct fname *old = fname;
fname = fname->next;
kfree(old);
}
if (!parent)
*root = RB_ROOT;
else if (parent->rb_left == n)
parent->rb_left = NULL;
else if (parent->rb_right == n)
parent->rb_right = NULL;
n = parent;
}
}
static struct dir_private_info *ext4_htree_create_dir_info(struct file *filp,
loff_t pos)
{
struct dir_private_info *p;
p = kzalloc(sizeof(struct dir_private_info), GFP_KERNEL);
if (!p)
return NULL;
p->curr_hash = pos2maj_hash(filp, pos);
p->curr_minor_hash = pos2min_hash(filp, pos);
return p;
}
void ext4_htree_free_dir_info(struct dir_private_info *p)
{
free_rb_tree_fname(&p->root);
kfree(p);
}
/*
* Given a directory entry, enter it into the fname rb tree.
*/
int ext4_htree_store_dirent(struct file *dir_file, __u32 hash,
__u32 minor_hash,
struct ext4_dir_entry_2 *dirent)
{
struct rb_node **p, *parent = NULL;
struct fname *fname, *new_fn;
struct dir_private_info *info;
int len;
info = dir_file->private_data;
p = &info->root.rb_node;
/* Create and allocate the fname structure */
len = sizeof(struct fname) + dirent->name_len + 1;
new_fn = kzalloc(len, GFP_KERNEL);
if (!new_fn)
return -ENOMEM;
new_fn->hash = hash;
new_fn->minor_hash = minor_hash;
new_fn->inode = le32_to_cpu(dirent->inode);
new_fn->name_len = dirent->name_len;
new_fn->file_type = dirent->file_type;
memcpy(new_fn->name, dirent->name, dirent->name_len);
new_fn->name[dirent->name_len] = 0;
while (*p) {
parent = *p;
fname = rb_entry(parent, struct fname, rb_hash);
/*
* If the hash and minor hash match up, then we put
* them on a linked list. This rarely happens...
*/
if ((new_fn->hash == fname->hash) &&
(new_fn->minor_hash == fname->minor_hash)) {
new_fn->next = fname->next;
fname->next = new_fn;
return 0;
}
if (new_fn->hash < fname->hash)
p = &(*p)->rb_left;
else if (new_fn->hash > fname->hash)
p = &(*p)->rb_right;
else if (new_fn->minor_hash < fname->minor_hash)
p = &(*p)->rb_left;
else /* if (new_fn->minor_hash > fname->minor_hash) */
p = &(*p)->rb_right;
}
rb_link_node(&new_fn->rb_hash, parent, p);
rb_insert_color(&new_fn->rb_hash, &info->root);
return 0;
}
/*
* This is a helper function for ext4_dx_readdir. It calls filldir
* for all entres on the fname linked list. (Normally there is only
* one entry on the linked list, unless there are 62 bit hash collisions.)
*/
static int call_filldir(struct file *filp, void *dirent,
filldir_t filldir, struct fname *fname)
{
struct dir_private_info *info = filp->private_data;
loff_t curr_pos;
struct inode *inode = filp->f_path.dentry->d_inode;
struct super_block *sb;
int error;
sb = inode->i_sb;
if (!fname) {
ext4_msg(sb, KERN_ERR, "%s:%d: inode #%lu: comm %s: "
"called with null fname?!?", __func__, __LINE__,
inode->i_ino, current->comm);
return 0;
}
curr_pos = hash2pos(filp, fname->hash, fname->minor_hash);
while (fname) {
error = filldir(dirent, fname->name,
fname->name_len, curr_pos,
fname->inode,
get_dtype(sb, fname->file_type));
if (error) {
filp->f_pos = curr_pos;
info->extra_fname = fname;
return error;
}
fname = fname->next;
}
return 0;
}
static int ext4_dx_readdir(struct file *filp,
void *dirent, filldir_t filldir)
{
struct dir_private_info *info = filp->private_data;
struct inode *inode = filp->f_path.dentry->d_inode;
struct fname *fname;
int ret;
if (!info) {
info = ext4_htree_create_dir_info(filp, filp->f_pos);
if (!info)
return -ENOMEM;
filp->private_data = info;
}
if (filp->f_pos == ext4_get_htree_eof(filp))
return 0; /* EOF */
/* Some one has messed with f_pos; reset the world */
if (info->last_pos != filp->f_pos) {
free_rb_tree_fname(&info->root);
info->curr_node = NULL;
info->extra_fname = NULL;
info->curr_hash = pos2maj_hash(filp, filp->f_pos);
info->curr_minor_hash = pos2min_hash(filp, filp->f_pos);
}
/*
* If there are any leftover names on the hash collision
* chain, return them first.
*/
if (info->extra_fname) {
if (call_filldir(filp, dirent, filldir, info->extra_fname))
goto finished;
info->extra_fname = NULL;
goto next_node;
} else if (!info->curr_node)
info->curr_node = rb_first(&info->root);
while (1) {
/*
* Fill the rbtree if we have no more entries,
* or the inode has changed since we last read in the
* cached entries.
*/
if ((!info->curr_node) ||
(filp->f_version != inode->i_version)) {
info->curr_node = NULL;
free_rb_tree_fname(&info->root);
filp->f_version = inode->i_version;
ret = ext4_htree_fill_tree(filp, info->curr_hash,
info->curr_minor_hash,
&info->next_hash);
if (ret < 0)
return ret;
if (ret == 0) {
filp->f_pos = ext4_get_htree_eof(filp);
break;
}
info->curr_node = rb_first(&info->root);
}
fname = rb_entry(info->curr_node, struct fname, rb_hash);
info->curr_hash = fname->hash;
info->curr_minor_hash = fname->minor_hash;
if (call_filldir(filp, dirent, filldir, fname))
break;
next_node:
info->curr_node = rb_next(info->curr_node);
if (info->curr_node) {
fname = rb_entry(info->curr_node, struct fname,
rb_hash);
info->curr_hash = fname->hash;
info->curr_minor_hash = fname->minor_hash;
} else {
if (info->next_hash == ~0) {
filp->f_pos = ext4_get_htree_eof(filp);
break;
}
info->curr_hash = info->next_hash;
info->curr_minor_hash = 0;
}
}
finished:
info->last_pos = filp->f_pos;
return 0;
}
static int ext4_release_dir(struct inode *inode, struct file *filp)
{
if (filp->private_data)
ext4_htree_free_dir_info(filp->private_data);
return 0;
}
const struct file_operations ext4_dir_operations = {
.llseek = ext4_dir_llseek,
.read = generic_read_dir,
.readdir = ext4_readdir,
.unlocked_ioctl = ext4_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = ext4_compat_ioctl,
#endif
.fsync = ext4_sync_file,
.release = ext4_release_dir,
};
| gpl-2.0 |
helldevs/kernel_lge_hammerhead | arch/powerpc/kvm/e500_emulate.c | 4405 | 5501 | /*
* Copyright (C) 2008-2011 Freescale Semiconductor, Inc. All rights reserved.
*
* Author: Yu Liu, <yu.liu@freescale.com>
*
* Description:
* This file is derived from arch/powerpc/kvm/44x_emulate.c,
* by Hollis Blanchard <hollisb@us.ibm.com>.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2, as
* published by the Free Software Foundation.
*/
#include <asm/kvm_ppc.h>
#include <asm/disassemble.h>
#include <asm/kvm_e500.h>
#include "booke.h"
#include "e500_tlb.h"
#define XOP_TLBIVAX 786
#define XOP_TLBSX 914
#define XOP_TLBRE 946
#define XOP_TLBWE 978
int kvmppc_core_emulate_op(struct kvm_run *run, struct kvm_vcpu *vcpu,
unsigned int inst, int *advance)
{
int emulated = EMULATE_DONE;
int ra;
int rb;
switch (get_op(inst)) {
case 31:
switch (get_xop(inst)) {
case XOP_TLBRE:
emulated = kvmppc_e500_emul_tlbre(vcpu);
break;
case XOP_TLBWE:
emulated = kvmppc_e500_emul_tlbwe(vcpu);
break;
case XOP_TLBSX:
rb = get_rb(inst);
emulated = kvmppc_e500_emul_tlbsx(vcpu,rb);
break;
case XOP_TLBIVAX:
ra = get_ra(inst);
rb = get_rb(inst);
emulated = kvmppc_e500_emul_tlbivax(vcpu, ra, rb);
break;
default:
emulated = EMULATE_FAIL;
}
break;
default:
emulated = EMULATE_FAIL;
}
if (emulated == EMULATE_FAIL)
emulated = kvmppc_booke_emulate_op(run, vcpu, inst, advance);
return emulated;
}
int kvmppc_core_emulate_mtspr(struct kvm_vcpu *vcpu, int sprn, int rs)
{
struct kvmppc_vcpu_e500 *vcpu_e500 = to_e500(vcpu);
int emulated = EMULATE_DONE;
ulong spr_val = kvmppc_get_gpr(vcpu, rs);
switch (sprn) {
case SPRN_PID:
kvmppc_set_pid(vcpu, spr_val);
break;
case SPRN_PID1:
if (spr_val != 0)
return EMULATE_FAIL;
vcpu_e500->pid[1] = spr_val; break;
case SPRN_PID2:
if (spr_val != 0)
return EMULATE_FAIL;
vcpu_e500->pid[2] = spr_val; break;
case SPRN_MAS0:
vcpu->arch.shared->mas0 = spr_val; break;
case SPRN_MAS1:
vcpu->arch.shared->mas1 = spr_val; break;
case SPRN_MAS2:
vcpu->arch.shared->mas2 = spr_val; break;
case SPRN_MAS3:
vcpu->arch.shared->mas7_3 &= ~(u64)0xffffffff;
vcpu->arch.shared->mas7_3 |= spr_val;
break;
case SPRN_MAS4:
vcpu->arch.shared->mas4 = spr_val; break;
case SPRN_MAS6:
vcpu->arch.shared->mas6 = spr_val; break;
case SPRN_MAS7:
vcpu->arch.shared->mas7_3 &= (u64)0xffffffff;
vcpu->arch.shared->mas7_3 |= (u64)spr_val << 32;
break;
case SPRN_L1CSR0:
vcpu_e500->l1csr0 = spr_val;
vcpu_e500->l1csr0 &= ~(L1CSR0_DCFI | L1CSR0_CLFC);
break;
case SPRN_L1CSR1:
vcpu_e500->l1csr1 = spr_val; break;
case SPRN_HID0:
vcpu_e500->hid0 = spr_val; break;
case SPRN_HID1:
vcpu_e500->hid1 = spr_val; break;
case SPRN_MMUCSR0:
emulated = kvmppc_e500_emul_mt_mmucsr0(vcpu_e500,
spr_val);
break;
/* extra exceptions */
case SPRN_IVOR32:
vcpu->arch.ivor[BOOKE_IRQPRIO_SPE_UNAVAIL] = spr_val;
break;
case SPRN_IVOR33:
vcpu->arch.ivor[BOOKE_IRQPRIO_SPE_FP_DATA] = spr_val;
break;
case SPRN_IVOR34:
vcpu->arch.ivor[BOOKE_IRQPRIO_SPE_FP_ROUND] = spr_val;
break;
case SPRN_IVOR35:
vcpu->arch.ivor[BOOKE_IRQPRIO_PERFORMANCE_MONITOR] = spr_val;
break;
default:
emulated = kvmppc_booke_emulate_mtspr(vcpu, sprn, rs);
}
return emulated;
}
int kvmppc_core_emulate_mfspr(struct kvm_vcpu *vcpu, int sprn, int rt)
{
struct kvmppc_vcpu_e500 *vcpu_e500 = to_e500(vcpu);
int emulated = EMULATE_DONE;
unsigned long val;
switch (sprn) {
case SPRN_PID:
kvmppc_set_gpr(vcpu, rt, vcpu_e500->pid[0]); break;
case SPRN_PID1:
kvmppc_set_gpr(vcpu, rt, vcpu_e500->pid[1]); break;
case SPRN_PID2:
kvmppc_set_gpr(vcpu, rt, vcpu_e500->pid[2]); break;
case SPRN_MAS0:
kvmppc_set_gpr(vcpu, rt, vcpu->arch.shared->mas0); break;
case SPRN_MAS1:
kvmppc_set_gpr(vcpu, rt, vcpu->arch.shared->mas1); break;
case SPRN_MAS2:
kvmppc_set_gpr(vcpu, rt, vcpu->arch.shared->mas2); break;
case SPRN_MAS3:
val = (u32)vcpu->arch.shared->mas7_3;
kvmppc_set_gpr(vcpu, rt, val);
break;
case SPRN_MAS4:
kvmppc_set_gpr(vcpu, rt, vcpu->arch.shared->mas4); break;
case SPRN_MAS6:
kvmppc_set_gpr(vcpu, rt, vcpu->arch.shared->mas6); break;
case SPRN_MAS7:
val = vcpu->arch.shared->mas7_3 >> 32;
kvmppc_set_gpr(vcpu, rt, val);
break;
case SPRN_TLB0CFG:
kvmppc_set_gpr(vcpu, rt, vcpu_e500->tlb0cfg); break;
case SPRN_TLB1CFG:
kvmppc_set_gpr(vcpu, rt, vcpu_e500->tlb1cfg); break;
case SPRN_L1CSR0:
kvmppc_set_gpr(vcpu, rt, vcpu_e500->l1csr0); break;
case SPRN_L1CSR1:
kvmppc_set_gpr(vcpu, rt, vcpu_e500->l1csr1); break;
case SPRN_HID0:
kvmppc_set_gpr(vcpu, rt, vcpu_e500->hid0); break;
case SPRN_HID1:
kvmppc_set_gpr(vcpu, rt, vcpu_e500->hid1); break;
case SPRN_SVR:
kvmppc_set_gpr(vcpu, rt, vcpu_e500->svr); break;
case SPRN_MMUCSR0:
kvmppc_set_gpr(vcpu, rt, 0); break;
case SPRN_MMUCFG:
kvmppc_set_gpr(vcpu, rt, mfspr(SPRN_MMUCFG)); break;
/* extra exceptions */
case SPRN_IVOR32:
kvmppc_set_gpr(vcpu, rt, vcpu->arch.ivor[BOOKE_IRQPRIO_SPE_UNAVAIL]);
break;
case SPRN_IVOR33:
kvmppc_set_gpr(vcpu, rt, vcpu->arch.ivor[BOOKE_IRQPRIO_SPE_FP_DATA]);
break;
case SPRN_IVOR34:
kvmppc_set_gpr(vcpu, rt, vcpu->arch.ivor[BOOKE_IRQPRIO_SPE_FP_ROUND]);
break;
case SPRN_IVOR35:
kvmppc_set_gpr(vcpu, rt, vcpu->arch.ivor[BOOKE_IRQPRIO_PERFORMANCE_MONITOR]);
break;
default:
emulated = kvmppc_booke_emulate_mfspr(vcpu, sprn, rt);
}
return emulated;
}
| gpl-2.0 |
championswimmer/android_kernel_sony_huashan | net/sched/sch_generic.c | 4405 | 22163 | /*
* net/sched/sch_generic.c Generic packet scheduler routines.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
* Jamal Hadi Salim, <hadi@cyberus.ca> 990601
* - Ingress support
*/
#include <linux/bitops.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <linux/rtnetlink.h>
#include <linux/init.h>
#include <linux/rcupdate.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <net/pkt_sched.h>
#include <net/dst.h>
/* Main transmission queue. */
/* Modifications to data participating in scheduling must be protected with
* qdisc_lock(qdisc) spinlock.
*
* The idea is the following:
* - enqueue, dequeue are serialized via qdisc root lock
* - ingress filtering is also serialized via qdisc root lock
* - updates to tree and tree walking are only done under the rtnl mutex.
*/
static inline int dev_requeue_skb(struct sk_buff *skb, struct Qdisc *q)
{
skb_dst_force(skb);
q->gso_skb = skb;
q->qstats.requeues++;
q->q.qlen++; /* it's still part of the queue */
__netif_schedule(q);
return 0;
}
static inline struct sk_buff *dequeue_skb(struct Qdisc *q)
{
struct sk_buff *skb = q->gso_skb;
if (unlikely(skb)) {
struct net_device *dev = qdisc_dev(q);
struct netdev_queue *txq;
/* check the reason of requeuing without tx lock first */
txq = netdev_get_tx_queue(dev, skb_get_queue_mapping(skb));
if (!netif_xmit_frozen_or_stopped(txq)) {
q->gso_skb = NULL;
q->q.qlen--;
} else
skb = NULL;
} else {
skb = q->dequeue(q);
}
return skb;
}
static inline int handle_dev_cpu_collision(struct sk_buff *skb,
struct netdev_queue *dev_queue,
struct Qdisc *q)
{
int ret;
if (unlikely(dev_queue->xmit_lock_owner == smp_processor_id())) {
/*
* Same CPU holding the lock. It may be a transient
* configuration error, when hard_start_xmit() recurses. We
* detect it by checking xmit owner and drop the packet when
* deadloop is detected. Return OK to try the next skb.
*/
kfree_skb(skb);
if (net_ratelimit())
pr_warning("Dead loop on netdevice %s, fix it urgently!\n",
dev_queue->dev->name);
ret = qdisc_qlen(q);
} else {
/*
* Another cpu is holding lock, requeue & delay xmits for
* some time.
*/
__this_cpu_inc(softnet_data.cpu_collision);
ret = dev_requeue_skb(skb, q);
}
return ret;
}
/*
* Transmit one skb, and handle the return status as required. Holding the
* __QDISC_STATE_RUNNING bit guarantees that only one CPU can execute this
* function.
*
* Returns to the caller:
* 0 - queue is empty or throttled.
* >0 - queue is not empty.
*/
int sch_direct_xmit(struct sk_buff *skb, struct Qdisc *q,
struct net_device *dev, struct netdev_queue *txq,
spinlock_t *root_lock)
{
int ret = NETDEV_TX_BUSY;
/* And release qdisc */
spin_unlock(root_lock);
HARD_TX_LOCK(dev, txq, smp_processor_id());
if (!netif_xmit_frozen_or_stopped(txq))
ret = dev_hard_start_xmit(skb, dev, txq);
HARD_TX_UNLOCK(dev, txq);
spin_lock(root_lock);
if (dev_xmit_complete(ret)) {
/* Driver sent out skb successfully or skb was consumed */
ret = qdisc_qlen(q);
} else if (ret == NETDEV_TX_LOCKED) {
/* Driver try lock failed */
ret = handle_dev_cpu_collision(skb, txq, q);
} else {
/* Driver returned NETDEV_TX_BUSY - requeue skb */
if (unlikely (ret != NETDEV_TX_BUSY && net_ratelimit()))
pr_warning("BUG %s code %d qlen %d\n",
dev->name, ret, q->q.qlen);
ret = dev_requeue_skb(skb, q);
}
if (ret && netif_xmit_frozen_or_stopped(txq))
ret = 0;
return ret;
}
/*
* NOTE: Called under qdisc_lock(q) with locally disabled BH.
*
* __QDISC_STATE_RUNNING guarantees only one CPU can process
* this qdisc at a time. qdisc_lock(q) serializes queue accesses for
* this queue.
*
* netif_tx_lock serializes accesses to device driver.
*
* qdisc_lock(q) and netif_tx_lock are mutually exclusive,
* if one is grabbed, another must be free.
*
* Note, that this procedure can be called by a watchdog timer
*
* Returns to the caller:
* 0 - queue is empty or throttled.
* >0 - queue is not empty.
*
*/
static inline int qdisc_restart(struct Qdisc *q)
{
struct netdev_queue *txq;
struct net_device *dev;
spinlock_t *root_lock;
struct sk_buff *skb;
/* Dequeue packet */
skb = dequeue_skb(q);
if (unlikely(!skb))
return 0;
WARN_ON_ONCE(skb_dst_is_noref(skb));
root_lock = qdisc_lock(q);
dev = qdisc_dev(q);
txq = netdev_get_tx_queue(dev, skb_get_queue_mapping(skb));
return sch_direct_xmit(skb, q, dev, txq, root_lock);
}
void __qdisc_run(struct Qdisc *q)
{
int quota = weight_p;
while (qdisc_restart(q)) {
/*
* Ordered by possible occurrence: Postpone processing if
* 1. we've exceeded packet quota
* 2. another process needs the CPU;
*/
if (--quota <= 0 || need_resched()) {
__netif_schedule(q);
break;
}
}
qdisc_run_end(q);
}
unsigned long dev_trans_start(struct net_device *dev)
{
unsigned long val, res = dev->trans_start;
unsigned int i;
for (i = 0; i < dev->num_tx_queues; i++) {
val = netdev_get_tx_queue(dev, i)->trans_start;
if (val && time_after(val, res))
res = val;
}
dev->trans_start = res;
return res;
}
EXPORT_SYMBOL(dev_trans_start);
static void dev_watchdog(unsigned long arg)
{
struct net_device *dev = (struct net_device *)arg;
netif_tx_lock(dev);
if (!qdisc_tx_is_noop(dev)) {
if (netif_device_present(dev) &&
netif_running(dev) &&
netif_carrier_ok(dev)) {
int some_queue_timedout = 0;
unsigned int i;
unsigned long trans_start;
for (i = 0; i < dev->num_tx_queues; i++) {
struct netdev_queue *txq;
txq = netdev_get_tx_queue(dev, i);
/*
* old device drivers set dev->trans_start
*/
trans_start = txq->trans_start ? : dev->trans_start;
if (netif_xmit_stopped(txq) &&
time_after(jiffies, (trans_start +
dev->watchdog_timeo))) {
some_queue_timedout = 1;
txq->trans_timeout++;
break;
}
}
if (some_queue_timedout) {
WARN_ONCE(1, KERN_INFO "NETDEV WATCHDOG: %s (%s): transmit queue %u timed out\n",
dev->name, netdev_drivername(dev), i);
dev->netdev_ops->ndo_tx_timeout(dev);
}
if (!mod_timer(&dev->watchdog_timer,
round_jiffies(jiffies +
dev->watchdog_timeo)))
dev_hold(dev);
}
}
netif_tx_unlock(dev);
dev_put(dev);
}
void __netdev_watchdog_up(struct net_device *dev)
{
if (dev->netdev_ops->ndo_tx_timeout) {
if (dev->watchdog_timeo <= 0)
dev->watchdog_timeo = 5*HZ;
if (!mod_timer(&dev->watchdog_timer,
round_jiffies(jiffies + dev->watchdog_timeo)))
dev_hold(dev);
}
}
static void dev_watchdog_up(struct net_device *dev)
{
__netdev_watchdog_up(dev);
}
static void dev_watchdog_down(struct net_device *dev)
{
netif_tx_lock_bh(dev);
if (del_timer(&dev->watchdog_timer))
dev_put(dev);
netif_tx_unlock_bh(dev);
}
/**
* netif_carrier_on - set carrier
* @dev: network device
*
* Device has detected that carrier.
*/
void netif_carrier_on(struct net_device *dev)
{
if (test_and_clear_bit(__LINK_STATE_NOCARRIER, &dev->state)) {
if (dev->reg_state == NETREG_UNINITIALIZED)
return;
linkwatch_fire_event(dev);
if (netif_running(dev))
__netdev_watchdog_up(dev);
}
}
EXPORT_SYMBOL(netif_carrier_on);
/**
* netif_carrier_off - clear carrier
* @dev: network device
*
* Device has detected loss of carrier.
*/
void netif_carrier_off(struct net_device *dev)
{
if (!test_and_set_bit(__LINK_STATE_NOCARRIER, &dev->state)) {
if (dev->reg_state == NETREG_UNINITIALIZED)
return;
linkwatch_fire_event(dev);
}
}
EXPORT_SYMBOL(netif_carrier_off);
/**
* netif_notify_peers - notify network peers about existence of @dev
* @dev: network device
*
* Generate traffic such that interested network peers are aware of
* @dev, such as by generating a gratuitous ARP. This may be used when
* a device wants to inform the rest of the network about some sort of
* reconfiguration such as a failover event or virtual machine
* migration.
*/
void netif_notify_peers(struct net_device *dev)
{
rtnl_lock();
call_netdevice_notifiers(NETDEV_NOTIFY_PEERS, dev);
rtnl_unlock();
}
EXPORT_SYMBOL(netif_notify_peers);
/* "NOOP" scheduler: the best scheduler, recommended for all interfaces
under all circumstances. It is difficult to invent anything faster or
cheaper.
*/
static int noop_enqueue(struct sk_buff *skb, struct Qdisc * qdisc)
{
kfree_skb(skb);
return NET_XMIT_CN;
}
static struct sk_buff *noop_dequeue(struct Qdisc * qdisc)
{
return NULL;
}
struct Qdisc_ops noop_qdisc_ops __read_mostly = {
.id = "noop",
.priv_size = 0,
.enqueue = noop_enqueue,
.dequeue = noop_dequeue,
.peek = noop_dequeue,
.owner = THIS_MODULE,
};
static struct netdev_queue noop_netdev_queue = {
.qdisc = &noop_qdisc,
.qdisc_sleeping = &noop_qdisc,
};
struct Qdisc noop_qdisc = {
.enqueue = noop_enqueue,
.dequeue = noop_dequeue,
.flags = TCQ_F_BUILTIN,
.ops = &noop_qdisc_ops,
.list = LIST_HEAD_INIT(noop_qdisc.list),
.q.lock = __SPIN_LOCK_UNLOCKED(noop_qdisc.q.lock),
.dev_queue = &noop_netdev_queue,
.busylock = __SPIN_LOCK_UNLOCKED(noop_qdisc.busylock),
};
EXPORT_SYMBOL(noop_qdisc);
static struct Qdisc_ops noqueue_qdisc_ops __read_mostly = {
.id = "noqueue",
.priv_size = 0,
.enqueue = noop_enqueue,
.dequeue = noop_dequeue,
.peek = noop_dequeue,
.owner = THIS_MODULE,
};
static struct Qdisc noqueue_qdisc;
static struct netdev_queue noqueue_netdev_queue = {
.qdisc = &noqueue_qdisc,
.qdisc_sleeping = &noqueue_qdisc,
};
static struct Qdisc noqueue_qdisc = {
.enqueue = NULL,
.dequeue = noop_dequeue,
.flags = TCQ_F_BUILTIN,
.ops = &noqueue_qdisc_ops,
.list = LIST_HEAD_INIT(noqueue_qdisc.list),
.q.lock = __SPIN_LOCK_UNLOCKED(noqueue_qdisc.q.lock),
.dev_queue = &noqueue_netdev_queue,
.busylock = __SPIN_LOCK_UNLOCKED(noqueue_qdisc.busylock),
};
static const u8 prio2band[TC_PRIO_MAX + 1] = {
1, 2, 2, 2, 1, 2, 0, 0 , 1, 1, 1, 1, 1, 1, 1, 1
};
/* 3-band FIFO queue: old style, but should be a bit faster than
generic prio+fifo combination.
*/
#define PFIFO_FAST_BANDS 3
/*
* Private data for a pfifo_fast scheduler containing:
* - queues for the three band
* - bitmap indicating which of the bands contain skbs
*/
struct pfifo_fast_priv {
u32 bitmap;
struct sk_buff_head q[PFIFO_FAST_BANDS];
};
/*
* Convert a bitmap to the first band number where an skb is queued, where:
* bitmap=0 means there are no skbs on any band.
* bitmap=1 means there is an skb on band 0.
* bitmap=7 means there are skbs on all 3 bands, etc.
*/
static const int bitmap2band[] = {-1, 0, 1, 0, 2, 0, 1, 0};
static inline struct sk_buff_head *band2list(struct pfifo_fast_priv *priv,
int band)
{
return priv->q + band;
}
static int pfifo_fast_enqueue(struct sk_buff *skb, struct Qdisc *qdisc)
{
if (skb_queue_len(&qdisc->q) < qdisc_dev(qdisc)->tx_queue_len) {
int band = prio2band[skb->priority & TC_PRIO_MAX];
struct pfifo_fast_priv *priv = qdisc_priv(qdisc);
struct sk_buff_head *list = band2list(priv, band);
priv->bitmap |= (1 << band);
qdisc->q.qlen++;
return __qdisc_enqueue_tail(skb, qdisc, list);
}
return qdisc_drop(skb, qdisc);
}
static struct sk_buff *pfifo_fast_dequeue(struct Qdisc *qdisc)
{
struct pfifo_fast_priv *priv = qdisc_priv(qdisc);
int band = bitmap2band[priv->bitmap];
if (likely(band >= 0)) {
struct sk_buff_head *list = band2list(priv, band);
struct sk_buff *skb = __qdisc_dequeue_head(qdisc, list);
qdisc->q.qlen--;
if (skb_queue_empty(list))
priv->bitmap &= ~(1 << band);
return skb;
}
return NULL;
}
static struct sk_buff *pfifo_fast_peek(struct Qdisc *qdisc)
{
struct pfifo_fast_priv *priv = qdisc_priv(qdisc);
int band = bitmap2band[priv->bitmap];
if (band >= 0) {
struct sk_buff_head *list = band2list(priv, band);
return skb_peek(list);
}
return NULL;
}
static void pfifo_fast_reset(struct Qdisc *qdisc)
{
int prio;
struct pfifo_fast_priv *priv = qdisc_priv(qdisc);
for (prio = 0; prio < PFIFO_FAST_BANDS; prio++)
__qdisc_reset_queue(qdisc, band2list(priv, prio));
priv->bitmap = 0;
qdisc->qstats.backlog = 0;
qdisc->q.qlen = 0;
}
static int pfifo_fast_dump(struct Qdisc *qdisc, struct sk_buff *skb)
{
struct tc_prio_qopt opt = { .bands = PFIFO_FAST_BANDS };
memcpy(&opt.priomap, prio2band, TC_PRIO_MAX + 1);
NLA_PUT(skb, TCA_OPTIONS, sizeof(opt), &opt);
return skb->len;
nla_put_failure:
return -1;
}
static int pfifo_fast_init(struct Qdisc *qdisc, struct nlattr *opt)
{
int prio;
struct pfifo_fast_priv *priv = qdisc_priv(qdisc);
for (prio = 0; prio < PFIFO_FAST_BANDS; prio++)
skb_queue_head_init(band2list(priv, prio));
/* Can by-pass the queue discipline */
qdisc->flags |= TCQ_F_CAN_BYPASS;
return 0;
}
struct Qdisc_ops pfifo_fast_ops __read_mostly = {
.id = "pfifo_fast",
.priv_size = sizeof(struct pfifo_fast_priv),
.enqueue = pfifo_fast_enqueue,
.dequeue = pfifo_fast_dequeue,
.peek = pfifo_fast_peek,
.init = pfifo_fast_init,
.reset = pfifo_fast_reset,
.dump = pfifo_fast_dump,
.owner = THIS_MODULE,
};
EXPORT_SYMBOL(pfifo_fast_ops);
struct Qdisc *qdisc_alloc(struct netdev_queue *dev_queue,
struct Qdisc_ops *ops)
{
void *p;
struct Qdisc *sch;
unsigned int size = QDISC_ALIGN(sizeof(*sch)) + ops->priv_size;
int err = -ENOBUFS;
p = kzalloc_node(size, GFP_KERNEL,
netdev_queue_numa_node_read(dev_queue));
if (!p)
goto errout;
sch = (struct Qdisc *) QDISC_ALIGN((unsigned long) p);
/* if we got non aligned memory, ask more and do alignment ourself */
if (sch != p) {
kfree(p);
p = kzalloc_node(size + QDISC_ALIGNTO - 1, GFP_KERNEL,
netdev_queue_numa_node_read(dev_queue));
if (!p)
goto errout;
sch = (struct Qdisc *) QDISC_ALIGN((unsigned long) p);
sch->padded = (char *) sch - (char *) p;
}
INIT_LIST_HEAD(&sch->list);
skb_queue_head_init(&sch->q);
spin_lock_init(&sch->busylock);
sch->ops = ops;
sch->enqueue = ops->enqueue;
sch->dequeue = ops->dequeue;
sch->dev_queue = dev_queue;
dev_hold(qdisc_dev(sch));
atomic_set(&sch->refcnt, 1);
return sch;
errout:
return ERR_PTR(err);
}
struct Qdisc *qdisc_create_dflt(struct netdev_queue *dev_queue,
struct Qdisc_ops *ops, unsigned int parentid)
{
struct Qdisc *sch;
sch = qdisc_alloc(dev_queue, ops);
if (IS_ERR(sch))
goto errout;
sch->parent = parentid;
if (!ops->init || ops->init(sch, NULL) == 0)
return sch;
qdisc_destroy(sch);
errout:
return NULL;
}
EXPORT_SYMBOL(qdisc_create_dflt);
/* Under qdisc_lock(qdisc) and BH! */
void qdisc_reset(struct Qdisc *qdisc)
{
const struct Qdisc_ops *ops = qdisc->ops;
if (ops->reset)
ops->reset(qdisc);
if (qdisc->gso_skb) {
kfree_skb(qdisc->gso_skb);
qdisc->gso_skb = NULL;
qdisc->q.qlen = 0;
}
}
EXPORT_SYMBOL(qdisc_reset);
static void qdisc_rcu_free(struct rcu_head *head)
{
struct Qdisc *qdisc = container_of(head, struct Qdisc, rcu_head);
kfree((char *) qdisc - qdisc->padded);
}
void qdisc_destroy(struct Qdisc *qdisc)
{
const struct Qdisc_ops *ops = qdisc->ops;
if (qdisc->flags & TCQ_F_BUILTIN ||
!atomic_dec_and_test(&qdisc->refcnt))
return;
#ifdef CONFIG_NET_SCHED
qdisc_list_del(qdisc);
qdisc_put_stab(rtnl_dereference(qdisc->stab));
#endif
gen_kill_estimator(&qdisc->bstats, &qdisc->rate_est);
if (ops->reset)
ops->reset(qdisc);
if (ops->destroy)
ops->destroy(qdisc);
module_put(ops->owner);
dev_put(qdisc_dev(qdisc));
kfree_skb(qdisc->gso_skb);
/*
* gen_estimator est_timer() might access qdisc->q.lock,
* wait a RCU grace period before freeing qdisc.
*/
call_rcu(&qdisc->rcu_head, qdisc_rcu_free);
}
EXPORT_SYMBOL(qdisc_destroy);
/* Attach toplevel qdisc to device queue. */
struct Qdisc *dev_graft_qdisc(struct netdev_queue *dev_queue,
struct Qdisc *qdisc)
{
struct Qdisc *oqdisc = dev_queue->qdisc_sleeping;
spinlock_t *root_lock;
root_lock = qdisc_lock(oqdisc);
spin_lock_bh(root_lock);
/* Prune old scheduler */
if (oqdisc && atomic_read(&oqdisc->refcnt) <= 1)
qdisc_reset(oqdisc);
/* ... and graft new one */
if (qdisc == NULL)
qdisc = &noop_qdisc;
dev_queue->qdisc_sleeping = qdisc;
rcu_assign_pointer(dev_queue->qdisc, &noop_qdisc);
spin_unlock_bh(root_lock);
return oqdisc;
}
EXPORT_SYMBOL(dev_graft_qdisc);
static void attach_one_default_qdisc(struct net_device *dev,
struct netdev_queue *dev_queue,
void *_unused)
{
struct Qdisc *qdisc = &noqueue_qdisc;
if (dev->tx_queue_len) {
qdisc = qdisc_create_dflt(dev_queue,
&pfifo_fast_ops, TC_H_ROOT);
if (!qdisc) {
netdev_info(dev, "activation failed\n");
return;
}
}
dev_queue->qdisc_sleeping = qdisc;
}
static void attach_default_qdiscs(struct net_device *dev)
{
struct netdev_queue *txq;
struct Qdisc *qdisc;
txq = netdev_get_tx_queue(dev, 0);
if (!netif_is_multiqueue(dev) || dev->tx_queue_len == 0) {
netdev_for_each_tx_queue(dev, attach_one_default_qdisc, NULL);
dev->qdisc = txq->qdisc_sleeping;
atomic_inc(&dev->qdisc->refcnt);
} else {
qdisc = qdisc_create_dflt(txq, &mq_qdisc_ops, TC_H_ROOT);
if (qdisc) {
qdisc->ops->attach(qdisc);
dev->qdisc = qdisc;
}
}
}
static void transition_one_qdisc(struct net_device *dev,
struct netdev_queue *dev_queue,
void *_need_watchdog)
{
struct Qdisc *new_qdisc = dev_queue->qdisc_sleeping;
int *need_watchdog_p = _need_watchdog;
if (!(new_qdisc->flags & TCQ_F_BUILTIN))
clear_bit(__QDISC_STATE_DEACTIVATED, &new_qdisc->state);
rcu_assign_pointer(dev_queue->qdisc, new_qdisc);
if (need_watchdog_p && new_qdisc != &noqueue_qdisc) {
dev_queue->trans_start = 0;
*need_watchdog_p = 1;
}
}
void dev_activate(struct net_device *dev)
{
int need_watchdog;
/* No queueing discipline is attached to device;
create default one i.e. pfifo_fast for devices,
which need queueing and noqueue_qdisc for
virtual interfaces
*/
if (dev->qdisc == &noop_qdisc)
attach_default_qdiscs(dev);
if (!netif_carrier_ok(dev))
/* Delay activation until next carrier-on event */
return;
need_watchdog = 0;
netdev_for_each_tx_queue(dev, transition_one_qdisc, &need_watchdog);
if (dev_ingress_queue(dev))
transition_one_qdisc(dev, dev_ingress_queue(dev), NULL);
if (need_watchdog) {
dev->trans_start = jiffies;
dev_watchdog_up(dev);
}
}
EXPORT_SYMBOL(dev_activate);
static void dev_deactivate_queue(struct net_device *dev,
struct netdev_queue *dev_queue,
void *_qdisc_default)
{
struct Qdisc *qdisc_default = _qdisc_default;
struct Qdisc *qdisc;
qdisc = dev_queue->qdisc;
if (qdisc) {
spin_lock_bh(qdisc_lock(qdisc));
if (!(qdisc->flags & TCQ_F_BUILTIN))
set_bit(__QDISC_STATE_DEACTIVATED, &qdisc->state);
rcu_assign_pointer(dev_queue->qdisc, qdisc_default);
qdisc_reset(qdisc);
spin_unlock_bh(qdisc_lock(qdisc));
}
}
static bool some_qdisc_is_busy(struct net_device *dev)
{
unsigned int i;
for (i = 0; i < dev->num_tx_queues; i++) {
struct netdev_queue *dev_queue;
spinlock_t *root_lock;
struct Qdisc *q;
int val;
dev_queue = netdev_get_tx_queue(dev, i);
q = dev_queue->qdisc_sleeping;
root_lock = qdisc_lock(q);
spin_lock_bh(root_lock);
val = (qdisc_is_running(q) ||
test_bit(__QDISC_STATE_SCHED, &q->state));
spin_unlock_bh(root_lock);
if (val)
return true;
}
return false;
}
/**
* dev_deactivate_many - deactivate transmissions on several devices
* @head: list of devices to deactivate
*
* This function returns only when all outstanding transmissions
* have completed, unless all devices are in dismantle phase.
*/
void dev_deactivate_many(struct list_head *head)
{
struct net_device *dev;
bool sync_needed = false;
list_for_each_entry(dev, head, unreg_list) {
netdev_for_each_tx_queue(dev, dev_deactivate_queue,
&noop_qdisc);
if (dev_ingress_queue(dev))
dev_deactivate_queue(dev, dev_ingress_queue(dev),
&noop_qdisc);
dev_watchdog_down(dev);
sync_needed |= !dev->dismantle;
}
/* Wait for outstanding qdisc-less dev_queue_xmit calls.
* This is avoided if all devices are in dismantle phase :
* Caller will call synchronize_net() for us
*/
if (sync_needed)
synchronize_net();
/* Wait for outstanding qdisc_run calls. */
list_for_each_entry(dev, head, unreg_list)
while (some_qdisc_is_busy(dev))
yield();
}
void dev_deactivate(struct net_device *dev)
{
LIST_HEAD(single);
list_add(&dev->unreg_list, &single);
dev_deactivate_many(&single);
list_del(&single);
}
EXPORT_SYMBOL(dev_deactivate);
static void dev_init_scheduler_queue(struct net_device *dev,
struct netdev_queue *dev_queue,
void *_qdisc)
{
struct Qdisc *qdisc = _qdisc;
dev_queue->qdisc = qdisc;
dev_queue->qdisc_sleeping = qdisc;
}
void dev_init_scheduler(struct net_device *dev)
{
dev->qdisc = &noop_qdisc;
netdev_for_each_tx_queue(dev, dev_init_scheduler_queue, &noop_qdisc);
if (dev_ingress_queue(dev))
dev_init_scheduler_queue(dev, dev_ingress_queue(dev), &noop_qdisc);
setup_timer(&dev->watchdog_timer, dev_watchdog, (unsigned long)dev);
}
static void shutdown_scheduler_queue(struct net_device *dev,
struct netdev_queue *dev_queue,
void *_qdisc_default)
{
struct Qdisc *qdisc = dev_queue->qdisc_sleeping;
struct Qdisc *qdisc_default = _qdisc_default;
if (qdisc) {
rcu_assign_pointer(dev_queue->qdisc, qdisc_default);
dev_queue->qdisc_sleeping = qdisc_default;
qdisc_destroy(qdisc);
}
}
void dev_shutdown(struct net_device *dev)
{
netdev_for_each_tx_queue(dev, shutdown_scheduler_queue, &noop_qdisc);
if (dev_ingress_queue(dev))
shutdown_scheduler_queue(dev, dev_ingress_queue(dev), &noop_qdisc);
qdisc_destroy(dev->qdisc);
dev->qdisc = &noop_qdisc;
WARN_ON(timer_pending(&dev->watchdog_timer));
}
| gpl-2.0 |
xperiafan13-rom/FenomenalMOD-CAF | drivers/gpu/drm/nouveau/nv10_gpio.c | 4917 | 3189 | /*
* Copyright (C) 2009 Francisco Jerez.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#include "drmP.h"
#include "nouveau_drv.h"
#include "nouveau_hw.h"
#include "nouveau_gpio.h"
int
nv10_gpio_sense(struct drm_device *dev, int line)
{
if (line < 2) {
line = line * 16;
line = NVReadCRTC(dev, 0, NV_PCRTC_GPIO) >> line;
return !!(line & 0x0100);
} else
if (line < 10) {
line = (line - 2) * 4;
line = NVReadCRTC(dev, 0, NV_PCRTC_GPIO_EXT) >> line;
return !!(line & 0x04);
} else
if (line < 14) {
line = (line - 10) * 4;
line = NVReadCRTC(dev, 0, NV_PCRTC_850) >> line;
return !!(line & 0x04);
}
return -EINVAL;
}
int
nv10_gpio_drive(struct drm_device *dev, int line, int dir, int out)
{
u32 reg, mask, data;
if (line < 2) {
line = line * 16;
reg = NV_PCRTC_GPIO;
mask = 0x00000011;
data = (dir << 4) | out;
} else
if (line < 10) {
line = (line - 2) * 4;
reg = NV_PCRTC_GPIO_EXT;
mask = 0x00000003;
data = (dir << 1) | out;
} else
if (line < 14) {
line = (line - 10) * 4;
reg = NV_PCRTC_850;
mask = 0x00000003;
data = (dir << 1) | out;
} else {
return -EINVAL;
}
mask = NVReadCRTC(dev, 0, reg) & ~(mask << line);
NVWriteCRTC(dev, 0, reg, mask | (data << line));
return 0;
}
void
nv10_gpio_irq_enable(struct drm_device *dev, int line, bool on)
{
u32 mask = 0x00010001 << line;
nv_wr32(dev, 0x001104, mask);
nv_mask(dev, 0x001144, mask, on ? mask : 0);
}
static void
nv10_gpio_isr(struct drm_device *dev)
{
u32 intr = nv_rd32(dev, 0x1104);
u32 hi = (intr & 0x0000ffff) >> 0;
u32 lo = (intr & 0xffff0000) >> 16;
nouveau_gpio_isr(dev, 0, hi | lo);
nv_wr32(dev, 0x001104, intr);
}
int
nv10_gpio_init(struct drm_device *dev)
{
nv_wr32(dev, 0x001140, 0x00000000);
nv_wr32(dev, 0x001100, 0xffffffff);
nv_wr32(dev, 0x001144, 0x00000000);
nv_wr32(dev, 0x001104, 0xffffffff);
nouveau_irq_register(dev, 28, nv10_gpio_isr); /* PBUS */
return 0;
}
void
nv10_gpio_fini(struct drm_device *dev)
{
nv_wr32(dev, 0x001140, 0x00000000);
nv_wr32(dev, 0x001144, 0x00000000);
nouveau_irq_unregister(dev, 28);
}
| gpl-2.0 |
MattCrystal/petulant-spice | drivers/staging/wlags49_h2/wl_enc.c | 5173 | 6467 |
/*******************************************************************************
* Agere Systems Inc.
* Wireless device driver for Linux (wlags49).
*
* Copyright (c) 1998-2003 Agere Systems Inc.
* All rights reserved.
* http://www.agere.com
*
* Initially developed by TriplePoint, Inc.
* http://www.triplepoint.com
*
*------------------------------------------------------------------------------
*
* This file defines functions related to WEP key coding/decoding.
*
*------------------------------------------------------------------------------
*
* SOFTWARE LICENSE
*
* This software is provided subject to the following terms and conditions,
* which you should read carefully before using the software. Using this
* software indicates your acceptance of these terms and conditions. If you do
* not agree with these terms and conditions, do not use the software.
*
* Copyright © 2003 Agere Systems Inc.
* All rights reserved.
*
* Redistribution and use in source or binary forms, with or without
* modifications, 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 as comments in the code as
* well as in the documentation and/or other materials provided with the
* distribution.
*
* . Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following Disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* . Neither the name of Agere Systems Inc. nor the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* Disclaimer
*
* THIS SOFTWARE IS PROVIDED AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, INFRINGEMENT AND THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ANY
* USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE IS SOLELY AT THE USERS OWN
* RISK. IN NO EVENT SHALL AGERE SYSTEMS INC. 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, INCLUDING, BUT NOT LIMITED TO, 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 files
******************************************************************************/
#include <linux/string.h>
#include <wl_version.h>
#include <debug.h>
#include <hcf.h>
#include <wl_enc.h>
/*******************************************************************************
* global definitions
******************************************************************************/
#if DBG
extern dbg_info_t *DbgInfo;
#endif /* DBG */
/*******************************************************************************
* wl_wep_code()
*******************************************************************************
*
* DESCRIPTION:
*
* This function encodes a set of wep keys for privacy
*
* PARAMETERS:
*
* szCrypt -
* szDest -
* Data -
* nLen -
*
* RETURNS:
*
* OK
*
******************************************************************************/
int wl_wep_code( char *szCrypt, char *szDest, void *Data, int nLen )
{
int i;
int t;
int k ;
char bits;
char *szData = (char *) Data;
/*------------------------------------------------------------------------*/
for( i = bits = 0 ; i < MACADDRESS_STR_LEN; i++ ) {
bits ^= szCrypt[i];
bits += szCrypt[i];
}
for( i = t = *szDest = 0; i < nLen; i++, t++ ) {
k = szData[i] ^ ( bits + i );
switch( i % 3 ) {
case 0 :
szDest[t] = ((k & 0xFC) >> 2) + CH_START ;
szDest[t+1] = ((k & 0x03) << 4) + CH_START ;
szDest[t+2] = '\0';
break;
case 1 :
szDest[t] += (( k & 0xF0 ) >> 4 );
szDest[t+1] = (( k & 0x0F ) << 2 ) + CH_START ;
szDest[t+2] = '\0';
break;
case 2 :
szDest[t] += (( k & 0xC0 ) >> 6 );
szDest[t+1] = ( k & 0x3F ) + CH_START ;
szDest[t+2] = '\0';
t++;
break;
}
}
return( strlen( szDest )) ;
}
/*============================================================================*/
/*******************************************************************************
* wl_wep_decode()
*******************************************************************************
*
* DESCRIPTION:
*
* This function decodes a set of WEP keys for use by the card.
*
* PARAMETERS:
*
* szCrypt -
* szDest -
* Data -
*
* RETURNS:
*
* OK
*
******************************************************************************/
int wl_wep_decode( char *szCrypt, void *Dest, char *szData )
{
int i;
int t;
int nLen;
char bits;
char *szDest = Dest;
/*------------------------------------------------------------------------*/
for( i = bits = 0 ; i < 12; i++ ) {
bits ^= szCrypt[i] ;
bits += szCrypt[i] ;
}
nLen = ( strlen( szData ) * 3) / 4 ;
for( i = t = 0; i < nLen; i++, t++ ) {
switch( i % 3 ) {
case 0 :
szDest[i] = ((( szData[t]-CH_START ) & 0x3f ) << 2 ) +
((( szData[t+1]-CH_START ) & 0x30 ) >> 4 );
break;
case 1 :
szDest[i] = ((( szData[t]-CH_START ) & 0x0f ) << 4 ) +
((( szData[t+1]-CH_START ) & 0x3c ) >> 2 );
break;
case 2 :
szDest[i] = ((( szData[t]-CH_START ) & 0x03 ) << 6 ) +
(( szData[t+1]-CH_START ) & 0x3f );
t++;
break;
}
szDest[i] ^= ( bits + i ) ;
}
return( i ) ;
}
/*============================================================================*/
| gpl-2.0 |
BlissRoms-Kernels/kernel_motorola_BlissPure | drivers/media/usb/dvb-usb-v2/mxl111sf-phy.c | 7733 | 8740 | /*
* mxl111sf-phy.c - driver for the MaxLinear MXL111SF
*
* Copyright (C) 2010 Michael Krufky <mkrufky@kernellabs.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 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 "mxl111sf-phy.h"
#include "mxl111sf-reg.h"
int mxl111sf_init_tuner_demod(struct mxl111sf_state *state)
{
struct mxl111sf_reg_ctrl_info mxl_111_overwrite_default[] = {
{0x07, 0xff, 0x0c},
{0x58, 0xff, 0x9d},
{0x09, 0xff, 0x00},
{0x06, 0xff, 0x06},
{0xc8, 0xff, 0x40}, /* ED_LE_WIN_OLD = 0 */
{0x8d, 0x01, 0x01}, /* NEGATE_Q */
{0x32, 0xff, 0xac}, /* DIG_RFREFSELECT = 12 */
{0x42, 0xff, 0x43}, /* DIG_REG_AMP = 4 */
{0x74, 0xff, 0xc4}, /* SSPUR_FS_PRIO = 4 */
{0x71, 0xff, 0xe6}, /* SPUR_ROT_PRIO_VAL = 1 */
{0x83, 0xff, 0x64}, /* INF_FILT1_THD_SC = 100 */
{0x85, 0xff, 0x64}, /* INF_FILT2_THD_SC = 100 */
{0x88, 0xff, 0xf0}, /* INF_THD = 240 */
{0x6f, 0xf0, 0xb0}, /* DFE_DLY = 11 */
{0x00, 0xff, 0x01}, /* Change to page 1 */
{0x81, 0xff, 0x11}, /* DSM_FERR_BYPASS = 1 */
{0xf4, 0xff, 0x07}, /* DIG_FREQ_CORR = 1 */
{0xd4, 0x1f, 0x0f}, /* SPUR_TEST_NOISE_TH = 15 */
{0xd6, 0xff, 0x0c}, /* SPUR_TEST_NOISE_PAPR = 12 */
{0x00, 0xff, 0x00}, /* Change to page 0 */
{0, 0, 0}
};
mxl_debug("()");
return mxl111sf_ctrl_program_regs(state, mxl_111_overwrite_default);
}
int mxl1x1sf_soft_reset(struct mxl111sf_state *state)
{
int ret;
mxl_debug("()");
ret = mxl111sf_write_reg(state, 0xff, 0x00); /* AIC */
if (mxl_fail(ret))
goto fail;
ret = mxl111sf_write_reg(state, 0x02, 0x01); /* get out of reset */
mxl_fail(ret);
fail:
return ret;
}
int mxl1x1sf_set_device_mode(struct mxl111sf_state *state, int mode)
{
int ret;
mxl_debug("(%s)", MXL_SOC_MODE == mode ?
"MXL_SOC_MODE" : "MXL_TUNER_MODE");
/* set device mode */
ret = mxl111sf_write_reg(state, 0x03,
MXL_SOC_MODE == mode ? 0x01 : 0x00);
if (mxl_fail(ret))
goto fail;
ret = mxl111sf_write_reg_mask(state,
0x7d, 0x40, MXL_SOC_MODE == mode ?
0x00 : /* enable impulse noise filter,
INF_BYP = 0 */
0x40); /* disable impulse noise filter,
INF_BYP = 1 */
if (mxl_fail(ret))
goto fail;
state->device_mode = mode;
fail:
return ret;
}
/* power up tuner */
int mxl1x1sf_top_master_ctrl(struct mxl111sf_state *state, int onoff)
{
mxl_debug("(%d)", onoff);
return mxl111sf_write_reg(state, 0x01, onoff ? 0x01 : 0x00);
}
int mxl111sf_disable_656_port(struct mxl111sf_state *state)
{
mxl_debug("()");
return mxl111sf_write_reg_mask(state, 0x12, 0x04, 0x00);
}
int mxl111sf_enable_usb_output(struct mxl111sf_state *state)
{
mxl_debug("()");
return mxl111sf_write_reg_mask(state, 0x17, 0x40, 0x00);
}
/* initialize TSIF as input port of MxL1X1SF for MPEG2 data transfer */
int mxl111sf_config_mpeg_in(struct mxl111sf_state *state,
unsigned int parallel_serial,
unsigned int msb_lsb_1st,
unsigned int clock_phase,
unsigned int mpeg_valid_pol,
unsigned int mpeg_sync_pol)
{
int ret;
u8 mode, tmp;
mxl_debug("(%u,%u,%u,%u,%u)", parallel_serial, msb_lsb_1st,
clock_phase, mpeg_valid_pol, mpeg_sync_pol);
/* Enable PIN MUX */
ret = mxl111sf_write_reg(state, V6_PIN_MUX_MODE_REG, V6_ENABLE_PIN_MUX);
mxl_fail(ret);
/* Configure MPEG Clock phase */
mxl111sf_read_reg(state, V6_MPEG_IN_CLK_INV_REG, &mode);
if (clock_phase == TSIF_NORMAL)
mode &= ~V6_INVERTED_CLK_PHASE;
else
mode |= V6_INVERTED_CLK_PHASE;
ret = mxl111sf_write_reg(state, V6_MPEG_IN_CLK_INV_REG, mode);
mxl_fail(ret);
/* Configure data input mode, MPEG Valid polarity, MPEG Sync polarity
* Get current configuration */
ret = mxl111sf_read_reg(state, V6_MPEG_IN_CTRL_REG, &mode);
mxl_fail(ret);
/* Data Input mode */
if (parallel_serial == TSIF_INPUT_PARALLEL) {
/* Disable serial mode */
mode &= ~V6_MPEG_IN_DATA_SERIAL;
/* Enable Parallel mode */
mode |= V6_MPEG_IN_DATA_PARALLEL;
} else {
/* Disable Parallel mode */
mode &= ~V6_MPEG_IN_DATA_PARALLEL;
/* Enable Serial Mode */
mode |= V6_MPEG_IN_DATA_SERIAL;
/* If serial interface is chosen, configure
MSB or LSB order in transmission */
ret = mxl111sf_read_reg(state,
V6_MPEG_INOUT_BIT_ORDER_CTRL_REG,
&tmp);
mxl_fail(ret);
if (msb_lsb_1st == MPEG_SER_MSB_FIRST_ENABLED)
tmp |= V6_MPEG_SER_MSB_FIRST;
else
tmp &= ~V6_MPEG_SER_MSB_FIRST;
ret = mxl111sf_write_reg(state,
V6_MPEG_INOUT_BIT_ORDER_CTRL_REG,
tmp);
mxl_fail(ret);
}
/* MPEG Sync polarity */
if (mpeg_sync_pol == TSIF_NORMAL)
mode &= ~V6_INVERTED_MPEG_SYNC;
else
mode |= V6_INVERTED_MPEG_SYNC;
/* MPEG Valid polarity */
if (mpeg_valid_pol == 0)
mode &= ~V6_INVERTED_MPEG_VALID;
else
mode |= V6_INVERTED_MPEG_VALID;
ret = mxl111sf_write_reg(state, V6_MPEG_IN_CTRL_REG, mode);
mxl_fail(ret);
return ret;
}
int mxl111sf_init_i2s_port(struct mxl111sf_state *state, u8 sample_size)
{
static struct mxl111sf_reg_ctrl_info init_i2s[] = {
{0x1b, 0xff, 0x1e}, /* pin mux mode, Choose 656/I2S input */
{0x15, 0x60, 0x60}, /* Enable I2S */
{0x17, 0xe0, 0x20}, /* Input, MPEG MODE USB,
Inverted 656 Clock, I2S_SOFT_RESET,
0 : Normal operation, 1 : Reset State */
#if 0
{0x12, 0x01, 0x00}, /* AUDIO_IRQ_CLR (Overflow Indicator) */
#endif
{0x00, 0xff, 0x02}, /* Change to Control Page */
{0x26, 0x0d, 0x0d}, /* I2S_MODE & BT656_SRC_SEL for FPGA only */
{0x00, 0xff, 0x00},
{0, 0, 0}
};
int ret;
mxl_debug("(0x%02x)", sample_size);
ret = mxl111sf_ctrl_program_regs(state, init_i2s);
if (mxl_fail(ret))
goto fail;
ret = mxl111sf_write_reg(state, V6_I2S_NUM_SAMPLES_REG, sample_size);
mxl_fail(ret);
fail:
return ret;
}
int mxl111sf_disable_i2s_port(struct mxl111sf_state *state)
{
static struct mxl111sf_reg_ctrl_info disable_i2s[] = {
{0x15, 0x40, 0x00},
{0, 0, 0}
};
mxl_debug("()");
return mxl111sf_ctrl_program_regs(state, disable_i2s);
}
int mxl111sf_config_i2s(struct mxl111sf_state *state,
u8 msb_start_pos, u8 data_width)
{
int ret;
u8 tmp;
mxl_debug("(0x%02x, 0x%02x)", msb_start_pos, data_width);
ret = mxl111sf_read_reg(state, V6_I2S_STREAM_START_BIT_REG, &tmp);
if (mxl_fail(ret))
goto fail;
tmp &= 0xe0;
tmp |= msb_start_pos;
ret = mxl111sf_write_reg(state, V6_I2S_STREAM_START_BIT_REG, tmp);
if (mxl_fail(ret))
goto fail;
ret = mxl111sf_read_reg(state, V6_I2S_STREAM_END_BIT_REG, &tmp);
if (mxl_fail(ret))
goto fail;
tmp &= 0xe0;
tmp |= data_width;
ret = mxl111sf_write_reg(state, V6_I2S_STREAM_END_BIT_REG, tmp);
mxl_fail(ret);
fail:
return ret;
}
int mxl111sf_config_spi(struct mxl111sf_state *state, int onoff)
{
u8 val;
int ret;
mxl_debug("(%d)", onoff);
ret = mxl111sf_write_reg(state, 0x00, 0x02);
if (mxl_fail(ret))
goto fail;
ret = mxl111sf_read_reg(state, V8_SPI_MODE_REG, &val);
if (mxl_fail(ret))
goto fail;
if (onoff)
val |= 0x04;
else
val &= ~0x04;
ret = mxl111sf_write_reg(state, V8_SPI_MODE_REG, val);
if (mxl_fail(ret))
goto fail;
ret = mxl111sf_write_reg(state, 0x00, 0x00);
mxl_fail(ret);
fail:
return ret;
}
int mxl111sf_idac_config(struct mxl111sf_state *state,
u8 control_mode, u8 current_setting,
u8 current_value, u8 hysteresis_value)
{
int ret;
u8 val;
/* current value will be set for both automatic & manual IDAC control */
val = current_value;
if (control_mode == IDAC_MANUAL_CONTROL) {
/* enable manual control of IDAC */
val |= IDAC_MANUAL_CONTROL_BIT_MASK;
if (current_setting == IDAC_CURRENT_SINKING_ENABLE)
/* enable current sinking in manual mode */
val |= IDAC_CURRENT_SINKING_BIT_MASK;
else
/* disable current sinking in manual mode */
val &= ~IDAC_CURRENT_SINKING_BIT_MASK;
} else {
/* disable manual control of IDAC */
val &= ~IDAC_MANUAL_CONTROL_BIT_MASK;
/* set hysteresis value reg: 0x0B<5:0> */
ret = mxl111sf_write_reg(state, V6_IDAC_HYSTERESIS_REG,
(hysteresis_value & 0x3F));
mxl_fail(ret);
}
ret = mxl111sf_write_reg(state, V6_IDAC_SETTINGS_REG, val);
mxl_fail(ret);
return ret;
}
/*
* Local variables:
* c-basic-offset: 8
* End:
*/
| gpl-2.0 |
davidmueller13/android_kernel_lge_msm8974-old | arch/hexagon/kernel/syscalltab.c | 7733 | 1028 | /*
* System call table for Hexagon
*
* Copyright (c) 2010-2011, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include <linux/syscalls.h>
#include <linux/signal.h>
#include <linux/unistd.h>
#include <asm/syscall.h>
#undef __SYSCALL
#define __SYSCALL(nr, call) [nr] = (call),
void *sys_call_table[__NR_syscalls] = {
#include <asm/unistd.h>
};
| gpl-2.0 |
Warmachine28/oneplus_8974 | drivers/gpio/gpio-ks8695.c | 7733 | 7550 | /*
* arch/arm/mach-ks8695/gpio.c
*
* Copyright (C) 2006 Andrew Victor
* Updated to GPIOLIB, Copyright 2008 Simtec Electronics
* Daniel Silverstone <dsilvers@simtec.co.uk>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* 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/gpio.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/init.h>
#include <linux/debugfs.h>
#include <linux/seq_file.h>
#include <linux/module.h>
#include <linux/io.h>
#include <mach/hardware.h>
#include <asm/mach/irq.h>
#include <mach/regs-gpio.h>
#include <mach/gpio-ks8695.h>
/*
* Configure a GPIO line for either GPIO function, or its internal
* function (Interrupt, Timer, etc).
*/
static void ks8695_gpio_mode(unsigned int pin, short gpio)
{
unsigned int enable[] = { IOPC_IOEINT0EN, IOPC_IOEINT1EN, IOPC_IOEINT2EN, IOPC_IOEINT3EN, IOPC_IOTIM0EN, IOPC_IOTIM1EN };
unsigned long x, flags;
if (pin > KS8695_GPIO_5) /* only GPIO 0..5 have internal functions */
return;
local_irq_save(flags);
x = __raw_readl(KS8695_GPIO_VA + KS8695_IOPC);
if (gpio) /* GPIO: set bit to 0 */
x &= ~enable[pin];
else /* Internal function: set bit to 1 */
x |= enable[pin];
__raw_writel(x, KS8695_GPIO_VA + KS8695_IOPC);
local_irq_restore(flags);
}
static unsigned short gpio_irq[] = { KS8695_IRQ_EXTERN0, KS8695_IRQ_EXTERN1, KS8695_IRQ_EXTERN2, KS8695_IRQ_EXTERN3 };
/*
* Configure GPIO pin as external interrupt source.
*/
int ks8695_gpio_interrupt(unsigned int pin, unsigned int type)
{
unsigned long x, flags;
if (pin > KS8695_GPIO_3) /* only GPIO 0..3 can generate IRQ */
return -EINVAL;
local_irq_save(flags);
/* set pin as input */
x = __raw_readl(KS8695_GPIO_VA + KS8695_IOPM);
x &= ~IOPM(pin);
__raw_writel(x, KS8695_GPIO_VA + KS8695_IOPM);
local_irq_restore(flags);
/* Set IRQ triggering type */
irq_set_irq_type(gpio_irq[pin], type);
/* enable interrupt mode */
ks8695_gpio_mode(pin, 0);
return 0;
}
EXPORT_SYMBOL(ks8695_gpio_interrupt);
/* .... Generic GPIO interface .............................................. */
/*
* Configure the GPIO line as an input.
*/
static int ks8695_gpio_direction_input(struct gpio_chip *gc, unsigned int pin)
{
unsigned long x, flags;
if (pin > KS8695_GPIO_15)
return -EINVAL;
/* set pin to GPIO mode */
ks8695_gpio_mode(pin, 1);
local_irq_save(flags);
/* set pin as input */
x = __raw_readl(KS8695_GPIO_VA + KS8695_IOPM);
x &= ~IOPM(pin);
__raw_writel(x, KS8695_GPIO_VA + KS8695_IOPM);
local_irq_restore(flags);
return 0;
}
/*
* Configure the GPIO line as an output, with default state.
*/
static int ks8695_gpio_direction_output(struct gpio_chip *gc,
unsigned int pin, int state)
{
unsigned long x, flags;
if (pin > KS8695_GPIO_15)
return -EINVAL;
/* set pin to GPIO mode */
ks8695_gpio_mode(pin, 1);
local_irq_save(flags);
/* set line state */
x = __raw_readl(KS8695_GPIO_VA + KS8695_IOPD);
if (state)
x |= IOPD(pin);
else
x &= ~IOPD(pin);
__raw_writel(x, KS8695_GPIO_VA + KS8695_IOPD);
/* set pin as output */
x = __raw_readl(KS8695_GPIO_VA + KS8695_IOPM);
x |= IOPM(pin);
__raw_writel(x, KS8695_GPIO_VA + KS8695_IOPM);
local_irq_restore(flags);
return 0;
}
/*
* Set the state of an output GPIO line.
*/
static void ks8695_gpio_set_value(struct gpio_chip *gc,
unsigned int pin, int state)
{
unsigned long x, flags;
if (pin > KS8695_GPIO_15)
return;
local_irq_save(flags);
/* set output line state */
x = __raw_readl(KS8695_GPIO_VA + KS8695_IOPD);
if (state)
x |= IOPD(pin);
else
x &= ~IOPD(pin);
__raw_writel(x, KS8695_GPIO_VA + KS8695_IOPD);
local_irq_restore(flags);
}
/*
* Read the state of a GPIO line.
*/
static int ks8695_gpio_get_value(struct gpio_chip *gc, unsigned int pin)
{
unsigned long x;
if (pin > KS8695_GPIO_15)
return -EINVAL;
x = __raw_readl(KS8695_GPIO_VA + KS8695_IOPD);
return (x & IOPD(pin)) != 0;
}
/*
* Map GPIO line to IRQ number.
*/
static int ks8695_gpio_to_irq(struct gpio_chip *gc, unsigned int pin)
{
if (pin > KS8695_GPIO_3) /* only GPIO 0..3 can generate IRQ */
return -EINVAL;
return gpio_irq[pin];
}
/*
* Map IRQ number to GPIO line.
*/
int irq_to_gpio(unsigned int irq)
{
if ((irq < KS8695_IRQ_EXTERN0) || (irq > KS8695_IRQ_EXTERN3))
return -EINVAL;
return (irq - KS8695_IRQ_EXTERN0);
}
EXPORT_SYMBOL(irq_to_gpio);
/* GPIOLIB interface */
static struct gpio_chip ks8695_gpio_chip = {
.label = "KS8695",
.direction_input = ks8695_gpio_direction_input,
.direction_output = ks8695_gpio_direction_output,
.get = ks8695_gpio_get_value,
.set = ks8695_gpio_set_value,
.to_irq = ks8695_gpio_to_irq,
.base = 0,
.ngpio = 16,
.can_sleep = 0,
};
/* Register the GPIOs */
void ks8695_register_gpios(void)
{
if (gpiochip_add(&ks8695_gpio_chip))
printk(KERN_ERR "Unable to register core GPIOs\n");
}
/* .... Debug interface ..................................................... */
#ifdef CONFIG_DEBUG_FS
static int ks8695_gpio_show(struct seq_file *s, void *unused)
{
unsigned int enable[] = { IOPC_IOEINT0EN, IOPC_IOEINT1EN, IOPC_IOEINT2EN, IOPC_IOEINT3EN, IOPC_IOTIM0EN, IOPC_IOTIM1EN };
unsigned int intmask[] = { IOPC_IOEINT0TM, IOPC_IOEINT1TM, IOPC_IOEINT2TM, IOPC_IOEINT3TM };
unsigned long mode, ctrl, data;
int i;
mode = __raw_readl(KS8695_GPIO_VA + KS8695_IOPM);
ctrl = __raw_readl(KS8695_GPIO_VA + KS8695_IOPC);
data = __raw_readl(KS8695_GPIO_VA + KS8695_IOPD);
seq_printf(s, "Pin\tI/O\tFunction\tState\n\n");
for (i = KS8695_GPIO_0; i <= KS8695_GPIO_15 ; i++) {
seq_printf(s, "%i:\t", i);
seq_printf(s, "%s\t", (mode & IOPM(i)) ? "Output" : "Input");
if (i <= KS8695_GPIO_3) {
if (ctrl & enable[i]) {
seq_printf(s, "EXT%i ", i);
switch ((ctrl & intmask[i]) >> (4 * i)) {
case IOPC_TM_LOW:
seq_printf(s, "(Low)"); break;
case IOPC_TM_HIGH:
seq_printf(s, "(High)"); break;
case IOPC_TM_RISING:
seq_printf(s, "(Rising)"); break;
case IOPC_TM_FALLING:
seq_printf(s, "(Falling)"); break;
case IOPC_TM_EDGE:
seq_printf(s, "(Edges)"); break;
}
}
else
seq_printf(s, "GPIO\t");
}
else if (i <= KS8695_GPIO_5) {
if (ctrl & enable[i])
seq_printf(s, "TOUT%i\t", i - KS8695_GPIO_4);
else
seq_printf(s, "GPIO\t");
}
else
seq_printf(s, "GPIO\t");
seq_printf(s, "\t");
seq_printf(s, "%i\n", (data & IOPD(i)) ? 1 : 0);
}
return 0;
}
static int ks8695_gpio_open(struct inode *inode, struct file *file)
{
return single_open(file, ks8695_gpio_show, NULL);
}
static const struct file_operations ks8695_gpio_operations = {
.open = ks8695_gpio_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int __init ks8695_gpio_debugfs_init(void)
{
/* /sys/kernel/debug/ks8695_gpio */
(void) debugfs_create_file("ks8695_gpio", S_IFREG | S_IRUGO, NULL, NULL, &ks8695_gpio_operations);
return 0;
}
postcore_initcall(ks8695_gpio_debugfs_init);
#endif
| gpl-2.0 |
MoKee/android_kernel_samsung_piranha | arch/arm/mach-omap2/clkt_iclk.c | 7989 | 2049 | /*
* OMAP2/3 interface clock control
*
* Copyright (C) 2011 Nokia Corporation
* Paul Walmsley
*
* 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.
*/
#undef DEBUG
#include <linux/kernel.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <plat/clock.h>
#include <plat/prcm.h>
#include "clock.h"
#include "clock2xxx.h"
#include "cm2xxx_3xxx.h"
#include "cm-regbits-24xx.h"
/* Private functions */
/* XXX */
void omap2_clkt_iclk_allow_idle(struct clk *clk)
{
u32 v, r;
r = ((__force u32)clk->enable_reg ^ (CM_AUTOIDLE ^ CM_ICLKEN));
v = __raw_readl((__force void __iomem *)r);
v |= (1 << clk->enable_bit);
__raw_writel(v, (__force void __iomem *)r);
}
/* XXX */
void omap2_clkt_iclk_deny_idle(struct clk *clk)
{
u32 v, r;
r = ((__force u32)clk->enable_reg ^ (CM_AUTOIDLE ^ CM_ICLKEN));
v = __raw_readl((__force void __iomem *)r);
v &= ~(1 << clk->enable_bit);
__raw_writel(v, (__force void __iomem *)r);
}
/* Public data */
const struct clkops clkops_omap2_iclk_dflt_wait = {
.enable = omap2_dflt_clk_enable,
.disable = omap2_dflt_clk_disable,
.find_companion = omap2_clk_dflt_find_companion,
.find_idlest = omap2_clk_dflt_find_idlest,
.allow_idle = omap2_clkt_iclk_allow_idle,
.deny_idle = omap2_clkt_iclk_deny_idle,
};
const struct clkops clkops_omap2_iclk_dflt = {
.enable = omap2_dflt_clk_enable,
.disable = omap2_dflt_clk_disable,
.allow_idle = omap2_clkt_iclk_allow_idle,
.deny_idle = omap2_clkt_iclk_deny_idle,
};
const struct clkops clkops_omap2_iclk_idle_only = {
.allow_idle = omap2_clkt_iclk_allow_idle,
.deny_idle = omap2_clkt_iclk_deny_idle,
};
const struct clkops clkops_omap2_mdmclk_dflt_wait = {
.enable = omap2_dflt_clk_enable,
.disable = omap2_dflt_clk_disable,
.find_companion = omap2_clk_dflt_find_companion,
.find_idlest = omap2_clk_dflt_find_idlest,
.allow_idle = omap2_clkt_iclk_allow_idle,
.deny_idle = omap2_clkt_iclk_deny_idle,
};
| gpl-2.0 |
ench0/hlte-kernel | arch/arm/mach-omap2/clkt_iclk.c | 7989 | 2049 | /*
* OMAP2/3 interface clock control
*
* Copyright (C) 2011 Nokia Corporation
* Paul Walmsley
*
* 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.
*/
#undef DEBUG
#include <linux/kernel.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <plat/clock.h>
#include <plat/prcm.h>
#include "clock.h"
#include "clock2xxx.h"
#include "cm2xxx_3xxx.h"
#include "cm-regbits-24xx.h"
/* Private functions */
/* XXX */
void omap2_clkt_iclk_allow_idle(struct clk *clk)
{
u32 v, r;
r = ((__force u32)clk->enable_reg ^ (CM_AUTOIDLE ^ CM_ICLKEN));
v = __raw_readl((__force void __iomem *)r);
v |= (1 << clk->enable_bit);
__raw_writel(v, (__force void __iomem *)r);
}
/* XXX */
void omap2_clkt_iclk_deny_idle(struct clk *clk)
{
u32 v, r;
r = ((__force u32)clk->enable_reg ^ (CM_AUTOIDLE ^ CM_ICLKEN));
v = __raw_readl((__force void __iomem *)r);
v &= ~(1 << clk->enable_bit);
__raw_writel(v, (__force void __iomem *)r);
}
/* Public data */
const struct clkops clkops_omap2_iclk_dflt_wait = {
.enable = omap2_dflt_clk_enable,
.disable = omap2_dflt_clk_disable,
.find_companion = omap2_clk_dflt_find_companion,
.find_idlest = omap2_clk_dflt_find_idlest,
.allow_idle = omap2_clkt_iclk_allow_idle,
.deny_idle = omap2_clkt_iclk_deny_idle,
};
const struct clkops clkops_omap2_iclk_dflt = {
.enable = omap2_dflt_clk_enable,
.disable = omap2_dflt_clk_disable,
.allow_idle = omap2_clkt_iclk_allow_idle,
.deny_idle = omap2_clkt_iclk_deny_idle,
};
const struct clkops clkops_omap2_iclk_idle_only = {
.allow_idle = omap2_clkt_iclk_allow_idle,
.deny_idle = omap2_clkt_iclk_deny_idle,
};
const struct clkops clkops_omap2_mdmclk_dflt_wait = {
.enable = omap2_dflt_clk_enable,
.disable = omap2_dflt_clk_disable,
.find_companion = omap2_clk_dflt_find_companion,
.find_idlest = omap2_clk_dflt_find_idlest,
.allow_idle = omap2_clkt_iclk_allow_idle,
.deny_idle = omap2_clkt_iclk_deny_idle,
};
| gpl-2.0 |
wimpknocker/android_kernel_samsung_viennalte | drivers/tty/serial/8250/8250_hub6.c | 12341 | 1184 | /*
* Copyright (C) 2005 Russell King.
* Data taken from include/asm-i386/serial.h
*
* 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/serial_8250.h>
#define HUB6(card,port) \
{ \
.iobase = 0x302, \
.irq = 3, \
.uartclk = 1843200, \
.iotype = UPIO_HUB6, \
.flags = UPF_BOOT_AUTOCONF, \
.hub6 = (card) << 6 | (port) << 3 | 1, \
}
static struct plat_serial8250_port hub6_data[] = {
HUB6(0, 0),
HUB6(0, 1),
HUB6(0, 2),
HUB6(0, 3),
HUB6(0, 4),
HUB6(0, 5),
HUB6(1, 0),
HUB6(1, 1),
HUB6(1, 2),
HUB6(1, 3),
HUB6(1, 4),
HUB6(1, 5),
{ },
};
static struct platform_device hub6_device = {
.name = "serial8250",
.id = PLAT8250_DEV_HUB6,
.dev = {
.platform_data = hub6_data,
},
};
static int __init hub6_init(void)
{
return platform_device_register(&hub6_device);
}
module_init(hub6_init);
MODULE_AUTHOR("Russell King");
MODULE_DESCRIPTION("8250 serial probe module for Hub6 cards");
MODULE_LICENSE("GPL");
| gpl-2.0 |
ehigh2014/linux | arch/sh/drivers/pci/ops-sh4.c | 12341 | 2527 | /*
* Generic SH-4 / SH-4A PCIC operations (SH7751, SH7780).
*
* Copyright (C) 2002 - 2009 Paul Mundt
*
* This file is subject to the terms and conditions of the GNU General Public
* License v2. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/pci.h>
#include <linux/io.h>
#include <linux/spinlock.h>
#include <asm/addrspace.h>
#include "pci-sh4.h"
/*
* Direct access to PCI hardware...
*/
#define CONFIG_CMD(bus, devfn, where) \
(0x80000000 | (bus->number << 16) | (devfn << 8) | (where & ~3))
/*
* Functions for accessing PCI configuration space with type 1 accesses
*/
static int sh4_pci_read(struct pci_bus *bus, unsigned int devfn,
int where, int size, u32 *val)
{
struct pci_channel *chan = bus->sysdata;
unsigned long flags;
u32 data;
/*
* PCIPDR may only be accessed as 32 bit words,
* so we must do byte alignment by hand
*/
raw_spin_lock_irqsave(&pci_config_lock, flags);
pci_write_reg(chan, CONFIG_CMD(bus, devfn, where), SH4_PCIPAR);
data = pci_read_reg(chan, SH4_PCIPDR);
raw_spin_unlock_irqrestore(&pci_config_lock, flags);
switch (size) {
case 1:
*val = (data >> ((where & 3) << 3)) & 0xff;
break;
case 2:
*val = (data >> ((where & 2) << 3)) & 0xffff;
break;
case 4:
*val = data;
break;
default:
return PCIBIOS_FUNC_NOT_SUPPORTED;
}
return PCIBIOS_SUCCESSFUL;
}
/*
* Since SH4 only does 32bit access we'll have to do a read,
* mask,write operation.
* We'll allow an odd byte offset, though it should be illegal.
*/
static int sh4_pci_write(struct pci_bus *bus, unsigned int devfn,
int where, int size, u32 val)
{
struct pci_channel *chan = bus->sysdata;
unsigned long flags;
int shift;
u32 data;
raw_spin_lock_irqsave(&pci_config_lock, flags);
pci_write_reg(chan, CONFIG_CMD(bus, devfn, where), SH4_PCIPAR);
data = pci_read_reg(chan, SH4_PCIPDR);
raw_spin_unlock_irqrestore(&pci_config_lock, flags);
switch (size) {
case 1:
shift = (where & 3) << 3;
data &= ~(0xff << shift);
data |= ((val & 0xff) << shift);
break;
case 2:
shift = (where & 2) << 3;
data &= ~(0xffff << shift);
data |= ((val & 0xffff) << shift);
break;
case 4:
data = val;
break;
default:
return PCIBIOS_FUNC_NOT_SUPPORTED;
}
pci_write_reg(chan, data, SH4_PCIPDR);
return PCIBIOS_SUCCESSFUL;
}
struct pci_ops sh4_pci_ops = {
.read = sh4_pci_read,
.write = sh4_pci_write,
};
int __attribute__((weak)) pci_fixup_pcic(struct pci_channel *chan)
{
/* Nothing to do. */
return 0;
}
| gpl-2.0 |
jeboo/kernel_JB_I9100official | arch/sh/drivers/pci/ops-sh4.c | 12341 | 2527 | /*
* Generic SH-4 / SH-4A PCIC operations (SH7751, SH7780).
*
* Copyright (C) 2002 - 2009 Paul Mundt
*
* This file is subject to the terms and conditions of the GNU General Public
* License v2. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/pci.h>
#include <linux/io.h>
#include <linux/spinlock.h>
#include <asm/addrspace.h>
#include "pci-sh4.h"
/*
* Direct access to PCI hardware...
*/
#define CONFIG_CMD(bus, devfn, where) \
(0x80000000 | (bus->number << 16) | (devfn << 8) | (where & ~3))
/*
* Functions for accessing PCI configuration space with type 1 accesses
*/
static int sh4_pci_read(struct pci_bus *bus, unsigned int devfn,
int where, int size, u32 *val)
{
struct pci_channel *chan = bus->sysdata;
unsigned long flags;
u32 data;
/*
* PCIPDR may only be accessed as 32 bit words,
* so we must do byte alignment by hand
*/
raw_spin_lock_irqsave(&pci_config_lock, flags);
pci_write_reg(chan, CONFIG_CMD(bus, devfn, where), SH4_PCIPAR);
data = pci_read_reg(chan, SH4_PCIPDR);
raw_spin_unlock_irqrestore(&pci_config_lock, flags);
switch (size) {
case 1:
*val = (data >> ((where & 3) << 3)) & 0xff;
break;
case 2:
*val = (data >> ((where & 2) << 3)) & 0xffff;
break;
case 4:
*val = data;
break;
default:
return PCIBIOS_FUNC_NOT_SUPPORTED;
}
return PCIBIOS_SUCCESSFUL;
}
/*
* Since SH4 only does 32bit access we'll have to do a read,
* mask,write operation.
* We'll allow an odd byte offset, though it should be illegal.
*/
static int sh4_pci_write(struct pci_bus *bus, unsigned int devfn,
int where, int size, u32 val)
{
struct pci_channel *chan = bus->sysdata;
unsigned long flags;
int shift;
u32 data;
raw_spin_lock_irqsave(&pci_config_lock, flags);
pci_write_reg(chan, CONFIG_CMD(bus, devfn, where), SH4_PCIPAR);
data = pci_read_reg(chan, SH4_PCIPDR);
raw_spin_unlock_irqrestore(&pci_config_lock, flags);
switch (size) {
case 1:
shift = (where & 3) << 3;
data &= ~(0xff << shift);
data |= ((val & 0xff) << shift);
break;
case 2:
shift = (where & 2) << 3;
data &= ~(0xffff << shift);
data |= ((val & 0xffff) << shift);
break;
case 4:
data = val;
break;
default:
return PCIBIOS_FUNC_NOT_SUPPORTED;
}
pci_write_reg(chan, data, SH4_PCIPDR);
return PCIBIOS_SUCCESSFUL;
}
struct pci_ops sh4_pci_ops = {
.read = sh4_pci_read,
.write = sh4_pci_write,
};
int __attribute__((weak)) pci_fixup_pcic(struct pci_channel *chan)
{
/* Nothing to do. */
return 0;
}
| gpl-2.0 |
AOSP-TEAM/android_kernel_samsung_i9100g | arch/arm/mach-omap2/board-zoom2.c | 54 | 2348 | /*
* Copyright (C) 2009 Texas Instruments Inc.
* Mikkel Christensen <mlc@ti.com>
*
* Modified from mach-omap2/board-ldp.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/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/input.h>
#include <linux/gpio.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <plat/common.h>
#include <plat/board.h>
#include <mach/board-zoom.h>
#include "mux.h"
#include "sdram-micron-mt46h32m32lf-6.h"
static void __init omap_zoom2_init_irq(void)
{
omap2_init_common_hw(mt46h32m32lf6_sdrc_params,
mt46h32m32lf6_sdrc_params);
omap_init_irq();
}
/* REVISIT: These audio entries can be removed once MFD code is merged */
#if 0
static struct twl4030_madc_platform_data zoom2_madc_data = {
.irq_line = 1,
};
static struct twl4030_codec_audio_data zoom2_audio_data = {
.audio_mclk = 26000000,
};
static struct twl4030_codec_data zoom2_codec_data = {
.audio_mclk = 26000000,
.audio = &zoom2_audio_data,
};
static struct twl4030_platform_data zoom2_twldata = {
.irq_base = TWL4030_IRQ_BASE,
.irq_end = TWL4030_IRQ_END,
/* platform_data for children goes here */
.bci = &zoom2_bci_data,
.madc = &zoom2_madc_data,
.usb = &zoom2_usb_data,
.gpio = &zoom2_gpio_data,
.keypad = &zoom2_kp_twl4030_data,
.codec = &zoom2_codec_data,
.vmmc1 = &zoom2_vmmc1,
.vmmc2 = &zoom2_vmmc2,
.vsim = &zoom2_vsim,
};
#endif
#ifdef CONFIG_OMAP_MUX
static struct omap_board_mux board_mux[] __initdata = {
{ .reg_offset = OMAP_MUX_TERMINATOR },
};
#else
#define board_mux NULL
#endif
static void __init omap_zoom2_init(void)
{
omap3_mux_init(board_mux, OMAP_PACKAGE_CBB);
zoom_peripherals_init();
zoom_debugboard_init();
zoom_display_init(OMAP_DSS_VENC_TYPE_COMPOSITE);
}
static void __init omap_zoom2_map_io(void)
{
omap2_set_globals_343x();
omap34xx_map_common_io();
}
MACHINE_START(OMAP_ZOOM2, "OMAP Zoom2 board")
.phys_io = ZOOM_UART_BASE,
.io_pg_offst = (ZOOM_UART_VIRT >> 18) & 0xfffc,
.boot_params = 0x80000100,
.map_io = omap_zoom2_map_io,
.init_irq = omap_zoom2_init_irq,
.init_machine = omap_zoom2_init,
.timer = &omap_timer,
MACHINE_END
| gpl-2.0 |
lizhm82/devkit8000-kernel | arch/sparc/prom/ranges.c | 54 | 3706 | /*
* ranges.c: Handle ranges in newer proms for obio/sbus.
*
* Copyright (C) 1995 David S. Miller (davem@caip.rutgers.edu)
* Copyright (C) 1997 Jakub Jelinek (jj@sunsite.mff.cuni.cz)
*/
#include <linux/init.h>
#include <linux/module.h>
#include <asm/openprom.h>
#include <asm/oplib.h>
#include <asm/types.h>
#include <asm/system.h>
struct linux_prom_ranges promlib_obio_ranges[PROMREG_MAX];
int num_obio_ranges;
/* Adjust register values based upon the ranges parameters. */
static void
prom_adjust_regs(struct linux_prom_registers *regp, int nregs,
struct linux_prom_ranges *rangep, int nranges)
{
int regc, rngc;
for (regc = 0; regc < nregs; regc++) {
for (rngc = 0; rngc < nranges; rngc++)
if (regp[regc].which_io == rangep[rngc].ot_child_space)
break; /* Fount it */
if (rngc == nranges) /* oops */
prom_printf("adjust_regs: Could not find range with matching bus type...\n");
regp[regc].which_io = rangep[rngc].ot_parent_space;
regp[regc].phys_addr -= rangep[rngc].ot_child_base;
regp[regc].phys_addr += rangep[rngc].ot_parent_base;
}
}
void
prom_adjust_ranges(struct linux_prom_ranges *ranges1, int nranges1,
struct linux_prom_ranges *ranges2, int nranges2)
{
int rng1c, rng2c;
for(rng1c=0; rng1c < nranges1; rng1c++) {
for(rng2c=0; rng2c < nranges2; rng2c++)
if(ranges1[rng1c].ot_parent_space == ranges2[rng2c].ot_child_space &&
ranges1[rng1c].ot_parent_base >= ranges2[rng2c].ot_child_base &&
ranges2[rng2c].ot_child_base + ranges2[rng2c].or_size - ranges1[rng1c].ot_parent_base > 0U)
break;
if(rng2c == nranges2) /* oops */
prom_printf("adjust_ranges: Could not find matching bus type...\n");
else if (ranges1[rng1c].ot_parent_base + ranges1[rng1c].or_size > ranges2[rng2c].ot_child_base + ranges2[rng2c].or_size)
ranges1[rng1c].or_size =
ranges2[rng2c].ot_child_base + ranges2[rng2c].or_size - ranges1[rng1c].ot_parent_base;
ranges1[rng1c].ot_parent_space = ranges2[rng2c].ot_parent_space;
ranges1[rng1c].ot_parent_base += ranges2[rng2c].ot_parent_base;
}
}
/* Apply probed obio ranges to registers passed, if no ranges return. */
void
prom_apply_obio_ranges(struct linux_prom_registers *regs, int nregs)
{
if(num_obio_ranges)
prom_adjust_regs(regs, nregs, promlib_obio_ranges, num_obio_ranges);
}
EXPORT_SYMBOL(prom_apply_obio_ranges);
void __init prom_ranges_init(void)
{
phandle node, obio_node;
int success;
num_obio_ranges = 0;
/* Check for obio and sbus ranges. */
node = prom_getchild(prom_root_node);
obio_node = prom_searchsiblings(node, "obio");
if(obio_node) {
success = prom_getproperty(obio_node, "ranges",
(char *) promlib_obio_ranges,
sizeof(promlib_obio_ranges));
if(success != -1)
num_obio_ranges = (success/sizeof(struct linux_prom_ranges));
}
if(num_obio_ranges)
prom_printf("PROMLIB: obio_ranges %d\n", num_obio_ranges);
}
void prom_apply_generic_ranges(phandle node, phandle parent,
struct linux_prom_registers *regs, int nregs)
{
int success;
int num_ranges;
struct linux_prom_ranges ranges[PROMREG_MAX];
success = prom_getproperty(node, "ranges",
(char *) ranges,
sizeof (ranges));
if (success != -1) {
num_ranges = (success/sizeof(struct linux_prom_ranges));
if (parent) {
struct linux_prom_ranges parent_ranges[PROMREG_MAX];
int num_parent_ranges;
success = prom_getproperty(parent, "ranges",
(char *) parent_ranges,
sizeof (parent_ranges));
if (success != -1) {
num_parent_ranges = (success/sizeof(struct linux_prom_ranges));
prom_adjust_ranges (ranges, num_ranges, parent_ranges, num_parent_ranges);
}
}
prom_adjust_regs(regs, nregs, ranges, num_ranges);
}
}
| gpl-2.0 |
arkas/Callisto_kernel_2.6.35 | drivers/usb/gadget/u_ether.c | 54 | 25076 | /*
* u_ether.c -- Ethernet-over-USB link layer utilities for Gadget stack
*
* Copyright (C) 2003-2005,2008 David Brownell
* Copyright (C) 2003-2004 Robert Schwebel, Benedikt Spranger
* Copyright (C) 2008 Nokia Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 VERBOSE_DEBUG */
#include <linux/kernel.h>
#include <linux/gfp.h>
#include <linux/device.h>
#include <linux/ctype.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include "u_ether.h"
/*
* This component encapsulates the Ethernet link glue needed to provide
* one (!) network link through the USB gadget stack, normally "usb0".
*
* The control and data models are handled by the function driver which
* connects to this code; such as CDC Ethernet (ECM or EEM),
* "CDC Subset", or RNDIS. That includes all descriptor and endpoint
* management.
*
* Link level addressing is handled by this component using module
* parameters; if no such parameters are provided, random link level
* addresses are used. Each end of the link uses one address. The
* host end address is exported in various ways, and is often recorded
* in configuration databases.
*
* The driver which assembles each configuration using such a link is
* responsible for ensuring that each configuration includes at most one
* instance of is network link. (The network layer provides ways for
* this single "physical" link to be used by multiple virtual links.)
*/
#define UETH__VERSION "29-May-2008"
struct eth_dev {
/* lock is held while accessing port_usb
* or updating its backlink port_usb->ioport
*/
spinlock_t lock;
struct gether *port_usb;
struct net_device *net;
struct usb_gadget *gadget;
spinlock_t req_lock; /* guard {rx,tx}_reqs */
struct list_head tx_reqs, rx_reqs;
atomic_t tx_qlen;
struct sk_buff_head rx_frames;
unsigned header_len;
struct sk_buff *(*wrap)(struct gether *, struct sk_buff *skb);
int (*unwrap)(struct gether *,
struct sk_buff *skb,
struct sk_buff_head *list);
struct work_struct work;
unsigned long todo;
#define WORK_RX_MEMORY 0
bool zlp;
u8 host_mac[ETH_ALEN];
};
/*-------------------------------------------------------------------------*/
#define RX_EXTRA 20 /* bytes guarding against rx overflows */
#define DEFAULT_QLEN 2 /* double buffering by default */
#ifdef CONFIG_USB_GADGET_DUALSPEED
static unsigned qmult = 5;
module_param(qmult, uint, S_IRUGO|S_IWUSR);
MODULE_PARM_DESC(qmult, "queue length multiplier at high speed");
#else /* full speed (low speed doesn't do bulk) */
#define qmult 1
#endif
/* for dual-speed hardware, use deeper queues at highspeed */
static inline int qlen(struct usb_gadget *gadget)
{
if (gadget_is_dualspeed(gadget) && gadget->speed == USB_SPEED_HIGH)
return qmult * DEFAULT_QLEN;
else
return DEFAULT_QLEN;
}
/*-------------------------------------------------------------------------*/
/* REVISIT there must be a better way than having two sets
* of debug calls ...
*/
#undef DBG
#undef VDBG
#undef ERROR
#undef INFO
#define xprintk(d, level, fmt, args...) \
printk(level "%s: " fmt , (d)->net->name , ## args)
#ifdef DEBUG
#undef DEBUG
#define DBG(dev, fmt, args...) \
xprintk(dev , KERN_DEBUG , fmt , ## args)
#else
#define DBG(dev, fmt, args...) \
do { } while (0)
#endif /* DEBUG */
#ifdef VERBOSE_DEBUG
#define VDBG DBG
#else
#define VDBG(dev, fmt, args...) \
do { } while (0)
#endif /* DEBUG */
#define ERROR(dev, fmt, args...) \
xprintk(dev , KERN_ERR , fmt , ## args)
#define INFO(dev, fmt, args...) \
xprintk(dev , KERN_INFO , fmt , ## args)
/*-------------------------------------------------------------------------*/
/* NETWORK DRIVER HOOKUP (to the layer above this driver) */
static int ueth_change_mtu(struct net_device *net, int new_mtu)
{
struct eth_dev *dev = netdev_priv(net);
unsigned long flags;
int status = 0;
/* don't change MTU on "live" link (peer won't know) */
spin_lock_irqsave(&dev->lock, flags);
if (dev->port_usb)
status = -EBUSY;
else if (new_mtu <= ETH_HLEN || new_mtu > ETH_FRAME_LEN)
status = -ERANGE;
else
net->mtu = new_mtu;
spin_unlock_irqrestore(&dev->lock, flags);
return status;
}
static void eth_get_drvinfo(struct net_device *net, struct ethtool_drvinfo *p)
{
struct eth_dev *dev = netdev_priv(net);
strlcpy(p->driver, "g_ether", sizeof p->driver);
strlcpy(p->version, UETH__VERSION, sizeof p->version);
strlcpy(p->fw_version, dev->gadget->name, sizeof p->fw_version);
strlcpy(p->bus_info, dev_name(&dev->gadget->dev), sizeof p->bus_info);
}
/* REVISIT can also support:
* - WOL (by tracking suspends and issuing remote wakeup)
* - msglevel (implies updated messaging)
* - ... probably more ethtool ops
*/
static const struct ethtool_ops ops = {
.get_drvinfo = eth_get_drvinfo,
.get_link = ethtool_op_get_link,
};
static void defer_kevent(struct eth_dev *dev, int flag)
{
if (test_and_set_bit(flag, &dev->todo))
return;
if (!schedule_work(&dev->work))
ERROR(dev, "kevent %d may have been dropped\n", flag);
else
DBG(dev, "kevent %d scheduled\n", flag);
}
static void rx_complete(struct usb_ep *ep, struct usb_request *req);
static int
rx_submit(struct eth_dev *dev, struct usb_request *req, gfp_t gfp_flags)
{
struct sk_buff *skb;
int retval = -ENOMEM;
size_t size = 0;
struct usb_ep *out;
unsigned long flags;
spin_lock_irqsave(&dev->lock, flags);
if (dev->port_usb)
out = dev->port_usb->out_ep;
else
out = NULL;
spin_unlock_irqrestore(&dev->lock, flags);
if (!out)
return -ENOTCONN;
/* Padding up to RX_EXTRA handles minor disagreements with host.
* Normally we use the USB "terminate on short read" convention;
* so allow up to (N*maxpacket), since that memory is normally
* already allocated. Some hardware doesn't deal well with short
* reads (e.g. DMA must be N*maxpacket), so for now don't trim a
* byte off the end (to force hardware errors on overflow).
*
* RNDIS uses internal framing, and explicitly allows senders to
* pad to end-of-packet. That's potentially nice for speed, but
* means receivers can't recover lost synch on their own (because
* new packets don't only start after a short RX).
*/
size += sizeof(struct ethhdr) + dev->net->mtu + RX_EXTRA;
size += dev->port_usb->header_len;
size += out->maxpacket - 1;
size -= size % out->maxpacket;
skb = alloc_skb(size + NET_IP_ALIGN, gfp_flags);
if (skb == NULL) {
DBG(dev, "no rx skb\n");
goto enomem;
}
/* Some platforms perform better when IP packets are aligned,
* but on at least one, checksumming fails otherwise. Note:
* RNDIS headers involve variable numbers of LE32 values.
*/
skb_reserve(skb, NET_IP_ALIGN);
req->buf = skb->data;
req->length = size;
req->complete = rx_complete;
req->context = skb;
retval = usb_ep_queue(out, req, gfp_flags);
if (retval == -ENOMEM)
enomem:
defer_kevent(dev, WORK_RX_MEMORY);
if (retval) {
DBG(dev, "rx submit --> %d\n", retval);
if (skb)
dev_kfree_skb_any(skb);
spin_lock_irqsave(&dev->req_lock, flags);
list_add(&req->list, &dev->rx_reqs);
spin_unlock_irqrestore(&dev->req_lock, flags);
}
return retval;
}
static void rx_complete(struct usb_ep *ep, struct usb_request *req)
{
struct sk_buff *skb = req->context, *skb2;
struct eth_dev *dev = ep->driver_data;
int status = req->status;
switch (status) {
/* normal completion */
case 0:
skb_put(skb, req->actual);
if (dev->unwrap) {
unsigned long flags;
spin_lock_irqsave(&dev->lock, flags);
if (dev->port_usb) {
status = dev->unwrap(dev->port_usb,
skb,
&dev->rx_frames);
} else {
dev_kfree_skb_any(skb);
status = -ENOTCONN;
}
spin_unlock_irqrestore(&dev->lock, flags);
} else {
skb_queue_tail(&dev->rx_frames, skb);
}
skb = NULL;
skb2 = skb_dequeue(&dev->rx_frames);
while (skb2) {
if (status < 0
|| ETH_HLEN > skb2->len
|| skb2->len > ETH_FRAME_LEN) {
dev->net->stats.rx_errors++;
dev->net->stats.rx_length_errors++;
DBG(dev, "rx length %d\n", skb2->len);
dev_kfree_skb_any(skb2);
goto next_frame;
}
skb2->protocol = eth_type_trans(skb2, dev->net);
dev->net->stats.rx_packets++;
dev->net->stats.rx_bytes += skb2->len;
/* no buffer copies needed, unless hardware can't
* use skb buffers.
*/
status = netif_rx(skb2);
next_frame:
skb2 = skb_dequeue(&dev->rx_frames);
}
break;
/* software-driven interface shutdown */
case -ECONNRESET: /* unlink */
case -ESHUTDOWN: /* disconnect etc */
VDBG(dev, "rx shutdown, code %d\n", status);
goto quiesce;
/* for hardware automagic (such as pxa) */
case -ECONNABORTED: /* endpoint reset */
DBG(dev, "rx %s reset\n", ep->name);
defer_kevent(dev, WORK_RX_MEMORY);
quiesce:
dev_kfree_skb_any(skb);
goto clean;
/* data overrun */
case -EOVERFLOW:
dev->net->stats.rx_over_errors++;
/* FALLTHROUGH */
default:
dev->net->stats.rx_errors++;
DBG(dev, "rx status %d\n", status);
break;
}
if (skb)
dev_kfree_skb_any(skb);
if (!netif_running(dev->net)) {
clean:
spin_lock(&dev->req_lock);
list_add(&req->list, &dev->rx_reqs);
spin_unlock(&dev->req_lock);
req = NULL;
}
if (req)
rx_submit(dev, req, GFP_ATOMIC);
}
static int prealloc(struct list_head *list, struct usb_ep *ep, unsigned n)
{
unsigned i;
struct usb_request *req;
if (!n)
return -ENOMEM;
/* queue/recycle up to N requests */
i = n;
list_for_each_entry(req, list, list) {
if (i-- == 0)
goto extra;
}
while (i--) {
req = usb_ep_alloc_request(ep, GFP_ATOMIC);
if (!req)
return list_empty(list) ? -ENOMEM : 0;
list_add(&req->list, list);
}
return 0;
extra:
/* free extras */
for (;;) {
struct list_head *next;
next = req->list.next;
list_del(&req->list);
usb_ep_free_request(ep, req);
if (next == list)
break;
req = container_of(next, struct usb_request, list);
}
return 0;
}
static int alloc_requests(struct eth_dev *dev, struct gether *link, unsigned n)
{
int status;
spin_lock(&dev->req_lock);
status = prealloc(&dev->tx_reqs, link->in_ep, n);
if (status < 0)
goto fail;
status = prealloc(&dev->rx_reqs, link->out_ep, n);
if (status < 0)
goto fail;
goto done;
fail:
DBG(dev, "can't alloc requests\n");
done:
spin_unlock(&dev->req_lock);
return status;
}
static void rx_fill(struct eth_dev *dev, gfp_t gfp_flags)
{
struct usb_request *req;
unsigned long flags;
/* fill unused rxq slots with some skb */
spin_lock_irqsave(&dev->req_lock, flags);
while (!list_empty(&dev->rx_reqs)) {
req = container_of(dev->rx_reqs.next,
struct usb_request, list);
list_del_init(&req->list);
spin_unlock_irqrestore(&dev->req_lock, flags);
if (rx_submit(dev, req, gfp_flags) < 0) {
defer_kevent(dev, WORK_RX_MEMORY);
return;
}
spin_lock_irqsave(&dev->req_lock, flags);
}
spin_unlock_irqrestore(&dev->req_lock, flags);
}
static void eth_work(struct work_struct *work)
{
struct eth_dev *dev = container_of(work, struct eth_dev, work);
if (test_and_clear_bit(WORK_RX_MEMORY, &dev->todo)) {
if (netif_running(dev->net))
rx_fill(dev, GFP_KERNEL);
}
if (dev->todo)
DBG(dev, "work done, flags = 0x%lx\n", dev->todo);
}
static void tx_complete(struct usb_ep *ep, struct usb_request *req)
{
struct sk_buff *skb = req->context;
struct eth_dev *dev = ep->driver_data;
switch (req->status) {
default:
dev->net->stats.tx_errors++;
VDBG(dev, "tx err %d\n", req->status);
/* FALLTHROUGH */
case -ECONNRESET: /* unlink */
case -ESHUTDOWN: /* disconnect etc */
break;
case 0:
dev->net->stats.tx_bytes += skb->len;
}
dev->net->stats.tx_packets++;
spin_lock(&dev->req_lock);
list_add(&req->list, &dev->tx_reqs);
spin_unlock(&dev->req_lock);
dev_kfree_skb_any(skb);
atomic_dec(&dev->tx_qlen);
if (netif_carrier_ok(dev->net))
netif_wake_queue(dev->net);
}
static inline int is_promisc(u16 cdc_filter)
{
return cdc_filter & USB_CDC_PACKET_TYPE_PROMISCUOUS;
}
static netdev_tx_t eth_start_xmit(struct sk_buff *skb,
struct net_device *net)
{
struct eth_dev *dev = netdev_priv(net);
int length = skb->len;
int retval;
struct usb_request *req = NULL;
unsigned long flags;
struct usb_ep *in;
u16 cdc_filter;
spin_lock_irqsave(&dev->lock, flags);
if (dev->port_usb) {
in = dev->port_usb->in_ep;
cdc_filter = dev->port_usb->cdc_filter;
} else {
in = NULL;
cdc_filter = 0;
}
spin_unlock_irqrestore(&dev->lock, flags);
if (!in) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
/* apply outgoing CDC or RNDIS filters */
if (!is_promisc(cdc_filter)) {
u8 *dest = skb->data;
if (is_multicast_ether_addr(dest)) {
u16 type;
/* ignores USB_CDC_PACKET_TYPE_MULTICAST and host
* SET_ETHERNET_MULTICAST_FILTERS requests
*/
if (is_broadcast_ether_addr(dest))
type = USB_CDC_PACKET_TYPE_BROADCAST;
else
type = USB_CDC_PACKET_TYPE_ALL_MULTICAST;
if (!(cdc_filter & type)) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
}
/* ignores USB_CDC_PACKET_TYPE_DIRECTED */
}
spin_lock_irqsave(&dev->req_lock, flags);
/*
* this freelist can be empty if an interrupt triggered disconnect()
* and reconfigured the gadget (shutting down this queue) after the
* network stack decided to xmit but before we got the spinlock.
*/
if (list_empty(&dev->tx_reqs)) {
spin_unlock_irqrestore(&dev->req_lock, flags);
return NETDEV_TX_BUSY;
}
req = container_of(dev->tx_reqs.next, struct usb_request, list);
list_del(&req->list);
/* temporarily stop TX queue when the freelist empties */
if (list_empty(&dev->tx_reqs))
netif_stop_queue(net);
spin_unlock_irqrestore(&dev->req_lock, flags);
/* no buffer copies needed, unless the network stack did it
* or the hardware can't use skb buffers.
* or there's not enough space for extra headers we need
*/
if (dev->wrap) {
unsigned long flags;
spin_lock_irqsave(&dev->lock, flags);
if (dev->port_usb)
skb = dev->wrap(dev->port_usb, skb);
spin_unlock_irqrestore(&dev->lock, flags);
if (!skb)
goto drop;
length = skb->len;
}
req->buf = skb->data;
req->context = skb;
req->complete = tx_complete;
/* use zlp framing on tx for strict CDC-Ether conformance,
* though any robust network rx path ignores extra padding.
* and some hardware doesn't like to write zlps.
*/
req->zero = 1;
if (!dev->zlp && (length % in->maxpacket) == 0)
length++;
req->length = length;
/* throttle highspeed IRQ rate back slightly */
if (gadget_is_dualspeed(dev->gadget))
req->no_interrupt = (dev->gadget->speed == USB_SPEED_HIGH)
? ((atomic_read(&dev->tx_qlen) % qmult) != 0)
: 0;
retval = usb_ep_queue(in, req, GFP_ATOMIC);
switch (retval) {
default:
DBG(dev, "tx queue err %d\n", retval);
break;
case 0:
net->trans_start = jiffies;
atomic_inc(&dev->tx_qlen);
}
if (retval) {
dev_kfree_skb_any(skb);
drop:
dev->net->stats.tx_dropped++;
spin_lock_irqsave(&dev->req_lock, flags);
if (list_empty(&dev->tx_reqs))
netif_start_queue(net);
list_add(&req->list, &dev->tx_reqs);
spin_unlock_irqrestore(&dev->req_lock, flags);
}
return NETDEV_TX_OK;
}
/*-------------------------------------------------------------------------*/
static void eth_start(struct eth_dev *dev, gfp_t gfp_flags)
{
DBG(dev, "%s\n", __func__);
/* fill the rx queue */
rx_fill(dev, gfp_flags);
/* and open the tx floodgates */
atomic_set(&dev->tx_qlen, 0);
netif_wake_queue(dev->net);
}
static int eth_open(struct net_device *net)
{
struct eth_dev *dev = netdev_priv(net);
struct gether *link;
DBG(dev, "%s\n", __func__);
if (netif_carrier_ok(dev->net))
eth_start(dev, GFP_KERNEL);
spin_lock_irq(&dev->lock);
link = dev->port_usb;
if (link && link->open)
link->open(link);
spin_unlock_irq(&dev->lock);
return 0;
}
static int eth_stop(struct net_device *net)
{
struct eth_dev *dev = netdev_priv(net);
unsigned long flags;
VDBG(dev, "%s\n", __func__);
netif_stop_queue(net);
DBG(dev, "stop stats: rx/tx %ld/%ld, errs %ld/%ld\n",
dev->net->stats.rx_packets, dev->net->stats.tx_packets,
dev->net->stats.rx_errors, dev->net->stats.tx_errors
);
/* ensure there are no more active requests */
spin_lock_irqsave(&dev->lock, flags);
if (dev->port_usb) {
struct gether *link = dev->port_usb;
if (link->close)
link->close(link);
/* NOTE: we have no abort-queue primitive we could use
* to cancel all pending I/O. Instead, we disable then
* reenable the endpoints ... this idiom may leave toggle
* wrong, but that's a self-correcting error.
*
* REVISIT: we *COULD* just let the transfers complete at
* their own pace; the network stack can handle old packets.
* For the moment we leave this here, since it works.
*/
usb_ep_disable(link->in_ep);
usb_ep_disable(link->out_ep);
if (netif_carrier_ok(net)) {
DBG(dev, "host still using in/out endpoints\n");
usb_ep_enable(link->in_ep, link->in);
usb_ep_enable(link->out_ep, link->out);
}
}
spin_unlock_irqrestore(&dev->lock, flags);
return 0;
}
/*-------------------------------------------------------------------------*/
/* initial value, changed by "ifconfig usb0 hw ether xx:xx:xx:xx:xx:xx" */
static char *dev_addr;
module_param(dev_addr, charp, S_IRUGO);
MODULE_PARM_DESC(dev_addr, "Device Ethernet Address");
/* this address is invisible to ifconfig */
static char *host_addr;
module_param(host_addr, charp, S_IRUGO);
MODULE_PARM_DESC(host_addr, "Host Ethernet Address");
static int get_ether_addr(const char *str, u8 *dev_addr)
{
if (str) {
unsigned i;
for (i = 0; i < 6; i++) {
unsigned char num;
if ((*str == '.') || (*str == ':'))
str++;
num = hex_to_bin(*str++) << 4;
num |= hex_to_bin(*str++);
dev_addr [i] = num;
}
if (is_valid_ether_addr(dev_addr))
return 0;
}
random_ether_addr(dev_addr);
return 1;
}
static struct eth_dev *the_dev;
static const struct net_device_ops eth_netdev_ops = {
.ndo_open = eth_open,
.ndo_stop = eth_stop,
.ndo_start_xmit = eth_start_xmit,
.ndo_change_mtu = ueth_change_mtu,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
};
static struct device_type gadget_type = {
.name = "gadget",
};
/**
* gether_setup - initialize one ethernet-over-usb link
* @g: gadget to associated with these links
* @ethaddr: NULL, or a buffer in which the ethernet address of the
* host side of the link is recorded
* Context: may sleep
*
* This sets up the single network link that may be exported by a
* gadget driver using this framework. The link layer addresses are
* set up using module parameters.
*
* Returns negative errno, or zero on success
*/
int gether_setup(struct usb_gadget *g, u8 ethaddr[ETH_ALEN])
{
struct eth_dev *dev;
struct net_device *net;
int status;
if (the_dev)
return -EBUSY;
net = alloc_etherdev(sizeof *dev);
if (!net)
return -ENOMEM;
dev = netdev_priv(net);
spin_lock_init(&dev->lock);
spin_lock_init(&dev->req_lock);
INIT_WORK(&dev->work, eth_work);
INIT_LIST_HEAD(&dev->tx_reqs);
INIT_LIST_HEAD(&dev->rx_reqs);
skb_queue_head_init(&dev->rx_frames);
/* network device setup */
dev->net = net;
strcpy(net->name, "usb%d");
if (get_ether_addr(dev_addr, net->dev_addr))
dev_warn(&g->dev,
"using random %s ethernet address\n", "self");
if (get_ether_addr(host_addr, dev->host_mac))
dev_warn(&g->dev,
"using random %s ethernet address\n", "host");
if (ethaddr)
memcpy(ethaddr, dev->host_mac, ETH_ALEN);
net->netdev_ops = ð_netdev_ops;
SET_ETHTOOL_OPS(net, &ops);
/* two kinds of host-initiated state changes:
* - iff DATA transfer is active, carrier is "on"
* - tx queueing enabled if open *and* carrier is "on"
*/
netif_stop_queue(net);
netif_carrier_off(net);
dev->gadget = g;
SET_NETDEV_DEV(net, &g->dev);
SET_NETDEV_DEVTYPE(net, &gadget_type);
status = register_netdev(net);
if (status < 0) {
dev_dbg(&g->dev, "register_netdev failed, %d\n", status);
free_netdev(net);
} else {
INFO(dev, "MAC %pM\n", net->dev_addr);
INFO(dev, "HOST MAC %pM\n", dev->host_mac);
the_dev = dev;
}
return status;
}
/**
* gether_cleanup - remove Ethernet-over-USB device
* Context: may sleep
*
* This is called to free all resources allocated by @gether_setup().
*/
void gether_cleanup(void)
{
if (!the_dev)
return;
unregister_netdev(the_dev->net);
free_netdev(the_dev->net);
/* assuming we used keventd, it must quiesce too */
flush_scheduled_work();
the_dev = NULL;
}
/**
* gether_connect - notify network layer that USB link is active
* @link: the USB link, set up with endpoints, descriptors matching
* current device speed, and any framing wrapper(s) set up.
* Context: irqs blocked
*
* This is called to activate endpoints and let the network layer know
* the connection is active ("carrier detect"). It may cause the I/O
* queues to open and start letting network packets flow, but will in
* any case activate the endpoints so that they respond properly to the
* USB host.
*
* Verify net_device pointer returned using IS_ERR(). If it doesn't
* indicate some error code (negative errno), ep->driver_data values
* have been overwritten.
*/
struct net_device *gether_connect(struct gether *link)
{
struct eth_dev *dev = the_dev;
int result = 0;
if (!dev)
return ERR_PTR(-EINVAL);
link->in_ep->driver_data = dev;
result = usb_ep_enable(link->in_ep, link->in);
if (result != 0) {
DBG(dev, "enable %s --> %d\n",
link->in_ep->name, result);
goto fail0;
}
link->out_ep->driver_data = dev;
result = usb_ep_enable(link->out_ep, link->out);
if (result != 0) {
DBG(dev, "enable %s --> %d\n",
link->out_ep->name, result);
goto fail1;
}
if (result == 0)
result = alloc_requests(dev, link, qlen(dev->gadget));
if (result == 0) {
dev->zlp = link->is_zlp_ok;
DBG(dev, "qlen %d\n", qlen(dev->gadget));
dev->header_len = link->header_len;
dev->unwrap = link->unwrap;
dev->wrap = link->wrap;
spin_lock(&dev->lock);
dev->port_usb = link;
link->ioport = dev;
if (netif_running(dev->net)) {
if (link->open)
link->open(link);
} else {
if (link->close)
link->close(link);
}
spin_unlock(&dev->lock);
netif_carrier_on(dev->net);
if (netif_running(dev->net))
eth_start(dev, GFP_ATOMIC);
/* on error, disable any endpoints */
} else {
(void) usb_ep_disable(link->out_ep);
fail1:
(void) usb_ep_disable(link->in_ep);
}
fail0:
/* caller is responsible for cleanup on error */
if (result < 0)
return ERR_PTR(result);
return dev->net;
}
/**
* gether_disconnect - notify network layer that USB link is inactive
* @link: the USB link, on which gether_connect() was called
* Context: irqs blocked
*
* This is called to deactivate endpoints and let the network layer know
* the connection went inactive ("no carrier").
*
* On return, the state is as if gether_connect() had never been called.
* The endpoints are inactive, and accordingly without active USB I/O.
* Pointers to endpoint descriptors and endpoint private data are nulled.
*/
void gether_disconnect(struct gether *link)
{
struct eth_dev *dev = link->ioport;
struct usb_request *req;
if (!dev)
return;
DBG(dev, "%s\n", __func__);
netif_stop_queue(dev->net);
netif_carrier_off(dev->net);
/* disable endpoints, forcing (synchronous) completion
* of all pending i/o. then free the request objects
* and forget about the endpoints.
*/
usb_ep_disable(link->in_ep);
spin_lock(&dev->req_lock);
while (!list_empty(&dev->tx_reqs)) {
req = container_of(dev->tx_reqs.next,
struct usb_request, list);
list_del(&req->list);
spin_unlock(&dev->req_lock);
usb_ep_free_request(link->in_ep, req);
spin_lock(&dev->req_lock);
}
spin_unlock(&dev->req_lock);
link->in_ep->driver_data = NULL;
link->in = NULL;
usb_ep_disable(link->out_ep);
spin_lock(&dev->req_lock);
while (!list_empty(&dev->rx_reqs)) {
req = container_of(dev->rx_reqs.next,
struct usb_request, list);
list_del(&req->list);
spin_unlock(&dev->req_lock);
usb_ep_free_request(link->out_ep, req);
spin_lock(&dev->req_lock);
}
spin_unlock(&dev->req_lock);
link->out_ep->driver_data = NULL;
link->out = NULL;
/* finish forgetting about this USB link episode */
dev->header_len = 0;
dev->unwrap = NULL;
dev->wrap = NULL;
spin_lock(&dev->lock);
dev->port_usb = NULL;
link->ioport = NULL;
spin_unlock(&dev->lock);
}
| gpl-2.0 |
RadioWar/WIFIPineApple-MKV | package/uboot-lantiq/files/board/arcadyan/arcadyan_bootstrap.c | 310 | 1370 | /*
* (C) Copyright 2010 Industrie Dial Face S.p.A.
* Luigi 'Comio' Mantellini, luigi.mantellini@idf-hit.com
*
* (C) Copyright 2007
* Vlad Lungu vlad.lungu@windriver.com
*
* See file CREDITS for list of people who contributed to this
* project.
*
* 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 <common.h>
#include <command.h>
#include <asm/mipsregs.h>
#include <asm/io.h>
phys_size_t bootstrap_initdram(int board_type)
{
/* Sdram is setup by assembler code */
/* If memory could be changed, we should return the true value here */
return CONFIG_SYS_MAX_RAM;
}
int bootstrap_checkboard(void)
{
return 0;
}
int bootstrap_misc_init_r(void)
{
set_io_port_base(0);
return 0;
}
| gpl-2.0 |
Marvell-Semi/PXA168_kernel | arch/arm64/kernel/suspend.c | 310 | 4151 | #include <linux/percpu.h>
#include <linux/slab.h>
#include <asm/cacheflush.h>
#include <asm/debug-monitors.h>
#include <asm/pgtable.h>
#include <asm/memory.h>
#include <asm/mmu_context.h>
#include <asm/smp_plat.h>
#include <asm/suspend.h>
#include <asm/tlbflush.h>
extern int __cpu_suspend_enter(unsigned long arg, int (*fn)(unsigned long));
/*
* This is called by __cpu_suspend_enter() to save the state, and do whatever
* flushing is required to ensure that when the CPU goes to sleep we have
* the necessary data available when the caches are not searched.
*
* ptr: CPU context virtual address
* save_ptr: address of the location where the context physical address
* must be saved
*/
void notrace __cpu_suspend_save(struct cpu_suspend_ctx *ptr,
phys_addr_t *save_ptr)
{
*save_ptr = virt_to_phys(ptr);
cpu_do_suspend(ptr);
/*
* Only flush the context that must be retrieved with the MMU
* off. VA primitives ensure the flush is applied to all
* cache levels so context is pushed to DRAM.
*/
__flush_dcache_area(ptr, sizeof(*ptr));
__flush_dcache_area(save_ptr, sizeof(*save_ptr));
}
/*
* This hook is provided so that cpu_suspend code can restore HW
* breakpoints as early as possible in the resume path, before reenabling
* debug exceptions. Code cannot be run from a CPU PM notifier since by the
* time the notifier runs debug exceptions might have been enabled already,
* with HW breakpoints registers content still in an unknown state.
*/
void (*hw_breakpoint_restore)(void *);
void __init cpu_suspend_set_dbg_restorer(void (*hw_bp_restore)(void *))
{
/* Prevent multiple restore hook initializations */
if (WARN_ON(hw_breakpoint_restore))
return;
hw_breakpoint_restore = hw_bp_restore;
}
/*
* __cpu_suspend
*
* arg: argument to pass to the finisher function
* fn: finisher function pointer
*
*/
int __cpu_suspend(unsigned long arg, int (*fn)(unsigned long))
{
struct mm_struct *mm = current->active_mm;
int ret;
unsigned long flags;
/*
* From this point debug exceptions are disabled to prevent
* updates to mdscr register (saved and restored along with
* general purpose registers) from kernel debuggers.
*/
local_dbg_save(flags);
/*
* mm context saved on the stack, it will be restored when
* the cpu comes out of reset through the identity mapped
* page tables, so that the thread address space is properly
* set-up on function return.
*/
ret = __cpu_suspend_enter(arg, fn);
if (ret == 0) {
/*
* We are resuming from reset with TTBR0_EL1 set to the
* idmap to enable the MMU; restore the active_mm mappings in
* TTBR0_EL1 unless the active_mm == &init_mm, in which case
* the thread entered __cpu_suspend with TTBR0_EL1 set to
* reserved TTBR0 page tables and should be restored as such.
*/
if (mm == &init_mm)
cpu_set_reserved_ttbr0();
else
cpu_switch_mm(mm->pgd, mm);
flush_tlb_all();
/*
* Restore per-cpu offset before any kernel
* subsystem relying on it has a chance to run.
*/
set_my_cpu_offset(per_cpu_offset(smp_processor_id()));
/*
* Restore HW breakpoint registers to sane values
* before debug exceptions are possibly reenabled
* through local_dbg_restore.
*/
if (hw_breakpoint_restore)
hw_breakpoint_restore(NULL);
}
/*
* Restore pstate flags. OS lock and mdscr have been already
* restored, so from this point onwards, debugging is fully
* renabled if it was enabled when core started shutdown.
*/
local_dbg_restore(flags);
return ret;
}
struct sleep_save_sp sleep_save_sp;
phys_addr_t sleep_idmap_phys;
static int __init cpu_suspend_init(void)
{
void *ctx_ptr;
/* ctx_ptr is an array of physical addresses */
ctx_ptr = kcalloc(mpidr_hash_size(), sizeof(phys_addr_t), GFP_KERNEL);
if (WARN_ON(!ctx_ptr))
return -ENOMEM;
sleep_save_sp.save_ptr_stash = ctx_ptr;
sleep_save_sp.save_ptr_stash_phys = virt_to_phys(ctx_ptr);
sleep_idmap_phys = virt_to_phys(idmap_pg_dir);
__flush_dcache_area(&sleep_save_sp, sizeof(struct sleep_save_sp));
__flush_dcache_area(&sleep_idmap_phys, sizeof(sleep_idmap_phys));
return 0;
}
early_initcall(cpu_suspend_init);
| gpl-2.0 |
jvaughan/san-francisco-kernel | arch/mips/ar7/gpio.c | 566 | 1329 | /*
* Copyright (C) 2007 Felix Fietkau <nbd@openwrt.org>
* Copyright (C) 2007 Eugene Konev <ejka@openwrt.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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/module.h>
#include <asm/mach-ar7/gpio.h>
static const char *ar7_gpio_list[AR7_GPIO_MAX];
int gpio_request(unsigned gpio, const char *label)
{
if (gpio >= AR7_GPIO_MAX)
return -EINVAL;
if (ar7_gpio_list[gpio])
return -EBUSY;
if (label)
ar7_gpio_list[gpio] = label;
else
ar7_gpio_list[gpio] = "busy";
return 0;
}
EXPORT_SYMBOL(gpio_request);
void gpio_free(unsigned gpio)
{
BUG_ON(!ar7_gpio_list[gpio]);
ar7_gpio_list[gpio] = NULL;
}
EXPORT_SYMBOL(gpio_free);
| gpl-2.0 |
LGBean/arm_kernel_2.6.32 | fs/ext4/symlink.c | 822 | 1338 | /*
* linux/fs/ext4/symlink.c
*
* Only fast symlinks left here - the rest is done by generic code. AV, 1999
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card (card@masi.ibp.fr)
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/symlink.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* ext4 symlink handling code
*/
#include <linux/fs.h>
#include <linux/jbd2.h>
#include <linux/namei.h>
#include "ext4.h"
#include "xattr.h"
static void *ext4_follow_link(struct dentry *dentry, struct nameidata *nd)
{
struct ext4_inode_info *ei = EXT4_I(dentry->d_inode);
nd_set_link(nd, (char *) ei->i_data);
return NULL;
}
const struct inode_operations ext4_symlink_inode_operations = {
.readlink = generic_readlink,
.follow_link = page_follow_link_light,
.put_link = page_put_link,
#ifdef CONFIG_EXT4_FS_XATTR
.setxattr = generic_setxattr,
.getxattr = generic_getxattr,
.listxattr = ext4_listxattr,
.removexattr = generic_removexattr,
#endif
};
const struct inode_operations ext4_fast_symlink_inode_operations = {
.readlink = generic_readlink,
.follow_link = ext4_follow_link,
#ifdef CONFIG_EXT4_FS_XATTR
.setxattr = generic_setxattr,
.getxattr = generic_getxattr,
.listxattr = ext4_listxattr,
.removexattr = generic_removexattr,
#endif
};
| gpl-2.0 |
CurtisMJ/g800f_custom_kernel | fs/ceph/snap.c | 822 | 26456 | #include <linux/ceph/ceph_debug.h>
#include <linux/sort.h>
#include <linux/slab.h>
#include "super.h"
#include "mds_client.h"
#include <linux/ceph/decode.h>
/*
* Snapshots in ceph are driven in large part by cooperation from the
* client. In contrast to local file systems or file servers that
* implement snapshots at a single point in the system, ceph's
* distributed access to storage requires clients to help decide
* whether a write logically occurs before or after a recently created
* snapshot.
*
* This provides a perfect instantanous client-wide snapshot. Between
* clients, however, snapshots may appear to be applied at slightly
* different points in time, depending on delays in delivering the
* snapshot notification.
*
* Snapshots are _not_ file system-wide. Instead, each snapshot
* applies to the subdirectory nested beneath some directory. This
* effectively divides the hierarchy into multiple "realms," where all
* of the files contained by each realm share the same set of
* snapshots. An individual realm's snap set contains snapshots
* explicitly created on that realm, as well as any snaps in its
* parent's snap set _after_ the point at which the parent became it's
* parent (due to, say, a rename). Similarly, snaps from prior parents
* during the time intervals during which they were the parent are included.
*
* The client is spared most of this detail, fortunately... it must only
* maintains a hierarchy of realms reflecting the current parent/child
* realm relationship, and for each realm has an explicit list of snaps
* inherited from prior parents.
*
* A snap_realm struct is maintained for realms containing every inode
* with an open cap in the system. (The needed snap realm information is
* provided by the MDS whenever a cap is issued, i.e., on open.) A 'seq'
* version number is used to ensure that as realm parameters change (new
* snapshot, new parent, etc.) the client's realm hierarchy is updated.
*
* The realm hierarchy drives the generation of a 'snap context' for each
* realm, which simply lists the resulting set of snaps for the realm. This
* is attached to any writes sent to OSDs.
*/
/*
* Unfortunately error handling is a bit mixed here. If we get a snap
* update, but don't have enough memory to update our realm hierarchy,
* it's not clear what we can do about it (besides complaining to the
* console).
*/
/*
* increase ref count for the realm
*
* caller must hold snap_rwsem for write.
*/
void ceph_get_snap_realm(struct ceph_mds_client *mdsc,
struct ceph_snap_realm *realm)
{
dout("get_realm %p %d -> %d\n", realm,
atomic_read(&realm->nref), atomic_read(&realm->nref)+1);
/*
* since we _only_ increment realm refs or empty the empty
* list with snap_rwsem held, adjusting the empty list here is
* safe. we do need to protect against concurrent empty list
* additions, however.
*/
if (atomic_read(&realm->nref) == 0) {
spin_lock(&mdsc->snap_empty_lock);
list_del_init(&realm->empty_item);
spin_unlock(&mdsc->snap_empty_lock);
}
atomic_inc(&realm->nref);
}
static void __insert_snap_realm(struct rb_root *root,
struct ceph_snap_realm *new)
{
struct rb_node **p = &root->rb_node;
struct rb_node *parent = NULL;
struct ceph_snap_realm *r = NULL;
while (*p) {
parent = *p;
r = rb_entry(parent, struct ceph_snap_realm, node);
if (new->ino < r->ino)
p = &(*p)->rb_left;
else if (new->ino > r->ino)
p = &(*p)->rb_right;
else
BUG();
}
rb_link_node(&new->node, parent, p);
rb_insert_color(&new->node, root);
}
/*
* create and get the realm rooted at @ino and bump its ref count.
*
* caller must hold snap_rwsem for write.
*/
static struct ceph_snap_realm *ceph_create_snap_realm(
struct ceph_mds_client *mdsc,
u64 ino)
{
struct ceph_snap_realm *realm;
realm = kzalloc(sizeof(*realm), GFP_NOFS);
if (!realm)
return ERR_PTR(-ENOMEM);
atomic_set(&realm->nref, 0); /* tree does not take a ref */
realm->ino = ino;
INIT_LIST_HEAD(&realm->children);
INIT_LIST_HEAD(&realm->child_item);
INIT_LIST_HEAD(&realm->empty_item);
INIT_LIST_HEAD(&realm->dirty_item);
INIT_LIST_HEAD(&realm->inodes_with_caps);
spin_lock_init(&realm->inodes_with_caps_lock);
__insert_snap_realm(&mdsc->snap_realms, realm);
dout("create_snap_realm %llx %p\n", realm->ino, realm);
return realm;
}
/*
* lookup the realm rooted at @ino.
*
* caller must hold snap_rwsem for write.
*/
struct ceph_snap_realm *ceph_lookup_snap_realm(struct ceph_mds_client *mdsc,
u64 ino)
{
struct rb_node *n = mdsc->snap_realms.rb_node;
struct ceph_snap_realm *r;
while (n) {
r = rb_entry(n, struct ceph_snap_realm, node);
if (ino < r->ino)
n = n->rb_left;
else if (ino > r->ino)
n = n->rb_right;
else {
dout("lookup_snap_realm %llx %p\n", r->ino, r);
return r;
}
}
return NULL;
}
static void __put_snap_realm(struct ceph_mds_client *mdsc,
struct ceph_snap_realm *realm);
/*
* called with snap_rwsem (write)
*/
static void __destroy_snap_realm(struct ceph_mds_client *mdsc,
struct ceph_snap_realm *realm)
{
dout("__destroy_snap_realm %p %llx\n", realm, realm->ino);
rb_erase(&realm->node, &mdsc->snap_realms);
if (realm->parent) {
list_del_init(&realm->child_item);
__put_snap_realm(mdsc, realm->parent);
}
kfree(realm->prior_parent_snaps);
kfree(realm->snaps);
ceph_put_snap_context(realm->cached_context);
kfree(realm);
}
/*
* caller holds snap_rwsem (write)
*/
static void __put_snap_realm(struct ceph_mds_client *mdsc,
struct ceph_snap_realm *realm)
{
dout("__put_snap_realm %llx %p %d -> %d\n", realm->ino, realm,
atomic_read(&realm->nref), atomic_read(&realm->nref)-1);
if (atomic_dec_and_test(&realm->nref))
__destroy_snap_realm(mdsc, realm);
}
/*
* caller needn't hold any locks
*/
void ceph_put_snap_realm(struct ceph_mds_client *mdsc,
struct ceph_snap_realm *realm)
{
dout("put_snap_realm %llx %p %d -> %d\n", realm->ino, realm,
atomic_read(&realm->nref), atomic_read(&realm->nref)-1);
if (!atomic_dec_and_test(&realm->nref))
return;
if (down_write_trylock(&mdsc->snap_rwsem)) {
__destroy_snap_realm(mdsc, realm);
up_write(&mdsc->snap_rwsem);
} else {
spin_lock(&mdsc->snap_empty_lock);
list_add(&realm->empty_item, &mdsc->snap_empty);
spin_unlock(&mdsc->snap_empty_lock);
}
}
/*
* Clean up any realms whose ref counts have dropped to zero. Note
* that this does not include realms who were created but not yet
* used.
*
* Called under snap_rwsem (write)
*/
static void __cleanup_empty_realms(struct ceph_mds_client *mdsc)
{
struct ceph_snap_realm *realm;
spin_lock(&mdsc->snap_empty_lock);
while (!list_empty(&mdsc->snap_empty)) {
realm = list_first_entry(&mdsc->snap_empty,
struct ceph_snap_realm, empty_item);
list_del(&realm->empty_item);
spin_unlock(&mdsc->snap_empty_lock);
__destroy_snap_realm(mdsc, realm);
spin_lock(&mdsc->snap_empty_lock);
}
spin_unlock(&mdsc->snap_empty_lock);
}
void ceph_cleanup_empty_realms(struct ceph_mds_client *mdsc)
{
down_write(&mdsc->snap_rwsem);
__cleanup_empty_realms(mdsc);
up_write(&mdsc->snap_rwsem);
}
/*
* adjust the parent realm of a given @realm. adjust child list, and parent
* pointers, and ref counts appropriately.
*
* return true if parent was changed, 0 if unchanged, <0 on error.
*
* caller must hold snap_rwsem for write.
*/
static int adjust_snap_realm_parent(struct ceph_mds_client *mdsc,
struct ceph_snap_realm *realm,
u64 parentino)
{
struct ceph_snap_realm *parent;
if (realm->parent_ino == parentino)
return 0;
parent = ceph_lookup_snap_realm(mdsc, parentino);
if (!parent) {
parent = ceph_create_snap_realm(mdsc, parentino);
if (IS_ERR(parent))
return PTR_ERR(parent);
}
dout("adjust_snap_realm_parent %llx %p: %llx %p -> %llx %p\n",
realm->ino, realm, realm->parent_ino, realm->parent,
parentino, parent);
if (realm->parent) {
list_del_init(&realm->child_item);
ceph_put_snap_realm(mdsc, realm->parent);
}
realm->parent_ino = parentino;
realm->parent = parent;
ceph_get_snap_realm(mdsc, parent);
list_add(&realm->child_item, &parent->children);
return 1;
}
static int cmpu64_rev(const void *a, const void *b)
{
if (*(u64 *)a < *(u64 *)b)
return 1;
if (*(u64 *)a > *(u64 *)b)
return -1;
return 0;
}
/*
* build the snap context for a given realm.
*/
static int build_snap_context(struct ceph_snap_realm *realm)
{
struct ceph_snap_realm *parent = realm->parent;
struct ceph_snap_context *snapc;
int err = 0;
int i;
int num = realm->num_prior_parent_snaps + realm->num_snaps;
/*
* build parent context, if it hasn't been built.
* conservatively estimate that all parent snaps might be
* included by us.
*/
if (parent) {
if (!parent->cached_context) {
err = build_snap_context(parent);
if (err)
goto fail;
}
num += parent->cached_context->num_snaps;
}
/* do i actually need to update? not if my context seq
matches realm seq, and my parents' does to. (this works
because we rebuild_snap_realms() works _downward_ in
hierarchy after each update.) */
if (realm->cached_context &&
realm->cached_context->seq == realm->seq &&
(!parent ||
realm->cached_context->seq >= parent->cached_context->seq)) {
dout("build_snap_context %llx %p: %p seq %lld (%d snaps)"
" (unchanged)\n",
realm->ino, realm, realm->cached_context,
realm->cached_context->seq,
realm->cached_context->num_snaps);
return 0;
}
/* alloc new snap context */
err = -ENOMEM;
if (num > (SIZE_MAX - sizeof(*snapc)) / sizeof(u64))
goto fail;
snapc = kzalloc(sizeof(*snapc) + num*sizeof(u64), GFP_NOFS);
if (!snapc)
goto fail;
atomic_set(&snapc->nref, 1);
/* build (reverse sorted) snap vector */
num = 0;
snapc->seq = realm->seq;
if (parent) {
/* include any of parent's snaps occurring _after_ my
parent became my parent */
for (i = 0; i < parent->cached_context->num_snaps; i++)
if (parent->cached_context->snaps[i] >=
realm->parent_since)
snapc->snaps[num++] =
parent->cached_context->snaps[i];
if (parent->cached_context->seq > snapc->seq)
snapc->seq = parent->cached_context->seq;
}
memcpy(snapc->snaps + num, realm->snaps,
sizeof(u64)*realm->num_snaps);
num += realm->num_snaps;
memcpy(snapc->snaps + num, realm->prior_parent_snaps,
sizeof(u64)*realm->num_prior_parent_snaps);
num += realm->num_prior_parent_snaps;
sort(snapc->snaps, num, sizeof(u64), cmpu64_rev, NULL);
snapc->num_snaps = num;
dout("build_snap_context %llx %p: %p seq %lld (%d snaps)\n",
realm->ino, realm, snapc, snapc->seq, snapc->num_snaps);
if (realm->cached_context)
ceph_put_snap_context(realm->cached_context);
realm->cached_context = snapc;
return 0;
fail:
/*
* if we fail, clear old (incorrect) cached_context... hopefully
* we'll have better luck building it later
*/
if (realm->cached_context) {
ceph_put_snap_context(realm->cached_context);
realm->cached_context = NULL;
}
pr_err("build_snap_context %llx %p fail %d\n", realm->ino,
realm, err);
return err;
}
/*
* rebuild snap context for the given realm and all of its children.
*/
static void rebuild_snap_realms(struct ceph_snap_realm *realm)
{
struct ceph_snap_realm *child;
dout("rebuild_snap_realms %llx %p\n", realm->ino, realm);
build_snap_context(realm);
list_for_each_entry(child, &realm->children, child_item)
rebuild_snap_realms(child);
}
/*
* helper to allocate and decode an array of snapids. free prior
* instance, if any.
*/
static int dup_array(u64 **dst, __le64 *src, int num)
{
int i;
kfree(*dst);
if (num) {
*dst = kcalloc(num, sizeof(u64), GFP_NOFS);
if (!*dst)
return -ENOMEM;
for (i = 0; i < num; i++)
(*dst)[i] = get_unaligned_le64(src + i);
} else {
*dst = NULL;
}
return 0;
}
/*
* When a snapshot is applied, the size/mtime inode metadata is queued
* in a ceph_cap_snap (one for each snapshot) until writeback
* completes and the metadata can be flushed back to the MDS.
*
* However, if a (sync) write is currently in-progress when we apply
* the snapshot, we have to wait until the write succeeds or fails
* (and a final size/mtime is known). In this case the
* cap_snap->writing = 1, and is said to be "pending." When the write
* finishes, we __ceph_finish_cap_snap().
*
* Caller must hold snap_rwsem for read (i.e., the realm topology won't
* change).
*/
void ceph_queue_cap_snap(struct ceph_inode_info *ci)
{
struct inode *inode = &ci->vfs_inode;
struct ceph_cap_snap *capsnap;
int used, dirty;
capsnap = kzalloc(sizeof(*capsnap), GFP_NOFS);
if (!capsnap) {
pr_err("ENOMEM allocating ceph_cap_snap on %p\n", inode);
return;
}
spin_lock(&ci->i_ceph_lock);
used = __ceph_caps_used(ci);
dirty = __ceph_caps_dirty(ci);
/*
* If there is a write in progress, treat that as a dirty Fw,
* even though it hasn't completed yet; by the time we finish
* up this capsnap it will be.
*/
if (used & CEPH_CAP_FILE_WR)
dirty |= CEPH_CAP_FILE_WR;
if (__ceph_have_pending_cap_snap(ci)) {
/* there is no point in queuing multiple "pending" cap_snaps,
as no new writes are allowed to start when pending, so any
writes in progress now were started before the previous
cap_snap. lucky us. */
dout("queue_cap_snap %p already pending\n", inode);
kfree(capsnap);
} else if (dirty & (CEPH_CAP_AUTH_EXCL|CEPH_CAP_XATTR_EXCL|
CEPH_CAP_FILE_EXCL|CEPH_CAP_FILE_WR)) {
struct ceph_snap_context *snapc = ci->i_head_snapc;
/*
* if we are a sync write, we may need to go to the snaprealm
* to get the current snapc.
*/
if (!snapc)
snapc = ci->i_snap_realm->cached_context;
dout("queue_cap_snap %p cap_snap %p queuing under %p %s\n",
inode, capsnap, snapc, ceph_cap_string(dirty));
ihold(inode);
atomic_set(&capsnap->nref, 1);
capsnap->ci = ci;
INIT_LIST_HEAD(&capsnap->ci_item);
INIT_LIST_HEAD(&capsnap->flushing_item);
capsnap->follows = snapc->seq;
capsnap->issued = __ceph_caps_issued(ci, NULL);
capsnap->dirty = dirty;
capsnap->mode = inode->i_mode;
capsnap->uid = inode->i_uid;
capsnap->gid = inode->i_gid;
if (dirty & CEPH_CAP_XATTR_EXCL) {
__ceph_build_xattrs_blob(ci);
capsnap->xattr_blob =
ceph_buffer_get(ci->i_xattrs.blob);
capsnap->xattr_version = ci->i_xattrs.version;
} else {
capsnap->xattr_blob = NULL;
capsnap->xattr_version = 0;
}
/* dirty page count moved from _head to this cap_snap;
all subsequent writes page dirties occur _after_ this
snapshot. */
capsnap->dirty_pages = ci->i_wrbuffer_ref_head;
ci->i_wrbuffer_ref_head = 0;
capsnap->context = snapc;
ci->i_head_snapc =
ceph_get_snap_context(ci->i_snap_realm->cached_context);
dout(" new snapc is %p\n", ci->i_head_snapc);
list_add_tail(&capsnap->ci_item, &ci->i_cap_snaps);
if (used & CEPH_CAP_FILE_WR) {
dout("queue_cap_snap %p cap_snap %p snapc %p"
" seq %llu used WR, now pending\n", inode,
capsnap, snapc, snapc->seq);
capsnap->writing = 1;
} else {
/* note mtime, size NOW. */
__ceph_finish_cap_snap(ci, capsnap);
}
} else {
dout("queue_cap_snap %p nothing dirty|writing\n", inode);
kfree(capsnap);
}
spin_unlock(&ci->i_ceph_lock);
}
/*
* Finalize the size, mtime for a cap_snap.. that is, settle on final values
* to be used for the snapshot, to be flushed back to the mds.
*
* If capsnap can now be flushed, add to snap_flush list, and return 1.
*
* Caller must hold i_ceph_lock.
*/
int __ceph_finish_cap_snap(struct ceph_inode_info *ci,
struct ceph_cap_snap *capsnap)
{
struct inode *inode = &ci->vfs_inode;
struct ceph_mds_client *mdsc = ceph_sb_to_client(inode->i_sb)->mdsc;
BUG_ON(capsnap->writing);
capsnap->size = inode->i_size;
capsnap->mtime = inode->i_mtime;
capsnap->atime = inode->i_atime;
capsnap->ctime = inode->i_ctime;
capsnap->time_warp_seq = ci->i_time_warp_seq;
if (capsnap->dirty_pages) {
dout("finish_cap_snap %p cap_snap %p snapc %p %llu %s s=%llu "
"still has %d dirty pages\n", inode, capsnap,
capsnap->context, capsnap->context->seq,
ceph_cap_string(capsnap->dirty), capsnap->size,
capsnap->dirty_pages);
return 0;
}
dout("finish_cap_snap %p cap_snap %p snapc %p %llu %s s=%llu\n",
inode, capsnap, capsnap->context,
capsnap->context->seq, ceph_cap_string(capsnap->dirty),
capsnap->size);
spin_lock(&mdsc->snap_flush_lock);
list_add_tail(&ci->i_snap_flush_item, &mdsc->snap_flush_list);
spin_unlock(&mdsc->snap_flush_lock);
return 1; /* caller may want to ceph_flush_snaps */
}
/*
* Queue cap_snaps for snap writeback for this realm and its children.
* Called under snap_rwsem, so realm topology won't change.
*/
static void queue_realm_cap_snaps(struct ceph_snap_realm *realm)
{
struct ceph_inode_info *ci;
struct inode *lastinode = NULL;
struct ceph_snap_realm *child;
dout("queue_realm_cap_snaps %p %llx inodes\n", realm, realm->ino);
spin_lock(&realm->inodes_with_caps_lock);
list_for_each_entry(ci, &realm->inodes_with_caps,
i_snap_realm_item) {
struct inode *inode = igrab(&ci->vfs_inode);
if (!inode)
continue;
spin_unlock(&realm->inodes_with_caps_lock);
if (lastinode)
iput(lastinode);
lastinode = inode;
ceph_queue_cap_snap(ci);
spin_lock(&realm->inodes_with_caps_lock);
}
spin_unlock(&realm->inodes_with_caps_lock);
if (lastinode)
iput(lastinode);
list_for_each_entry(child, &realm->children, child_item) {
dout("queue_realm_cap_snaps %p %llx queue child %p %llx\n",
realm, realm->ino, child, child->ino);
list_del_init(&child->dirty_item);
list_add(&child->dirty_item, &realm->dirty_item);
}
list_del_init(&realm->dirty_item);
dout("queue_realm_cap_snaps %p %llx done\n", realm, realm->ino);
}
/*
* Parse and apply a snapblob "snap trace" from the MDS. This specifies
* the snap realm parameters from a given realm and all of its ancestors,
* up to the root.
*
* Caller must hold snap_rwsem for write.
*/
int ceph_update_snap_trace(struct ceph_mds_client *mdsc,
void *p, void *e, bool deletion)
{
struct ceph_mds_snap_realm *ri; /* encoded */
__le64 *snaps; /* encoded */
__le64 *prior_parent_snaps; /* encoded */
struct ceph_snap_realm *realm;
int invalidate = 0;
int err = -ENOMEM;
LIST_HEAD(dirty_realms);
dout("update_snap_trace deletion=%d\n", deletion);
more:
ceph_decode_need(&p, e, sizeof(*ri), bad);
ri = p;
p += sizeof(*ri);
ceph_decode_need(&p, e, sizeof(u64)*(le32_to_cpu(ri->num_snaps) +
le32_to_cpu(ri->num_prior_parent_snaps)), bad);
snaps = p;
p += sizeof(u64) * le32_to_cpu(ri->num_snaps);
prior_parent_snaps = p;
p += sizeof(u64) * le32_to_cpu(ri->num_prior_parent_snaps);
realm = ceph_lookup_snap_realm(mdsc, le64_to_cpu(ri->ino));
if (!realm) {
realm = ceph_create_snap_realm(mdsc, le64_to_cpu(ri->ino));
if (IS_ERR(realm)) {
err = PTR_ERR(realm);
goto fail;
}
}
/* ensure the parent is correct */
err = adjust_snap_realm_parent(mdsc, realm, le64_to_cpu(ri->parent));
if (err < 0)
goto fail;
invalidate += err;
if (le64_to_cpu(ri->seq) > realm->seq) {
dout("update_snap_trace updating %llx %p %lld -> %lld\n",
realm->ino, realm, realm->seq, le64_to_cpu(ri->seq));
/* update realm parameters, snap lists */
realm->seq = le64_to_cpu(ri->seq);
realm->created = le64_to_cpu(ri->created);
realm->parent_since = le64_to_cpu(ri->parent_since);
realm->num_snaps = le32_to_cpu(ri->num_snaps);
err = dup_array(&realm->snaps, snaps, realm->num_snaps);
if (err < 0)
goto fail;
realm->num_prior_parent_snaps =
le32_to_cpu(ri->num_prior_parent_snaps);
err = dup_array(&realm->prior_parent_snaps, prior_parent_snaps,
realm->num_prior_parent_snaps);
if (err < 0)
goto fail;
/* queue realm for cap_snap creation */
list_add(&realm->dirty_item, &dirty_realms);
invalidate = 1;
} else if (!realm->cached_context) {
dout("update_snap_trace %llx %p seq %lld new\n",
realm->ino, realm, realm->seq);
invalidate = 1;
} else {
dout("update_snap_trace %llx %p seq %lld unchanged\n",
realm->ino, realm, realm->seq);
}
dout("done with %llx %p, invalidated=%d, %p %p\n", realm->ino,
realm, invalidate, p, e);
if (p < e)
goto more;
/* invalidate when we reach the _end_ (root) of the trace */
if (invalidate)
rebuild_snap_realms(realm);
/*
* queue cap snaps _after_ we've built the new snap contexts,
* so that i_head_snapc can be set appropriately.
*/
while (!list_empty(&dirty_realms)) {
realm = list_first_entry(&dirty_realms, struct ceph_snap_realm,
dirty_item);
queue_realm_cap_snaps(realm);
}
__cleanup_empty_realms(mdsc);
return 0;
bad:
err = -EINVAL;
fail:
pr_err("update_snap_trace error %d\n", err);
return err;
}
/*
* Send any cap_snaps that are queued for flush. Try to carry
* s_mutex across multiple snap flushes to avoid locking overhead.
*
* Caller holds no locks.
*/
static void flush_snaps(struct ceph_mds_client *mdsc)
{
struct ceph_inode_info *ci;
struct inode *inode;
struct ceph_mds_session *session = NULL;
dout("flush_snaps\n");
spin_lock(&mdsc->snap_flush_lock);
while (!list_empty(&mdsc->snap_flush_list)) {
ci = list_first_entry(&mdsc->snap_flush_list,
struct ceph_inode_info, i_snap_flush_item);
inode = &ci->vfs_inode;
ihold(inode);
spin_unlock(&mdsc->snap_flush_lock);
spin_lock(&ci->i_ceph_lock);
__ceph_flush_snaps(ci, &session, 0);
spin_unlock(&ci->i_ceph_lock);
iput(inode);
spin_lock(&mdsc->snap_flush_lock);
}
spin_unlock(&mdsc->snap_flush_lock);
if (session) {
mutex_unlock(&session->s_mutex);
ceph_put_mds_session(session);
}
dout("flush_snaps done\n");
}
/*
* Handle a snap notification from the MDS.
*
* This can take two basic forms: the simplest is just a snap creation
* or deletion notification on an existing realm. This should update the
* realm and its children.
*
* The more difficult case is realm creation, due to snap creation at a
* new point in the file hierarchy, or due to a rename that moves a file or
* directory into another realm.
*/
void ceph_handle_snap(struct ceph_mds_client *mdsc,
struct ceph_mds_session *session,
struct ceph_msg *msg)
{
struct super_block *sb = mdsc->fsc->sb;
int mds = session->s_mds;
u64 split;
int op;
int trace_len;
struct ceph_snap_realm *realm = NULL;
void *p = msg->front.iov_base;
void *e = p + msg->front.iov_len;
struct ceph_mds_snap_head *h;
int num_split_inos, num_split_realms;
__le64 *split_inos = NULL, *split_realms = NULL;
int i;
int locked_rwsem = 0;
/* decode */
if (msg->front.iov_len < sizeof(*h))
goto bad;
h = p;
op = le32_to_cpu(h->op);
split = le64_to_cpu(h->split); /* non-zero if we are splitting an
* existing realm */
num_split_inos = le32_to_cpu(h->num_split_inos);
num_split_realms = le32_to_cpu(h->num_split_realms);
trace_len = le32_to_cpu(h->trace_len);
p += sizeof(*h);
dout("handle_snap from mds%d op %s split %llx tracelen %d\n", mds,
ceph_snap_op_name(op), split, trace_len);
mutex_lock(&session->s_mutex);
session->s_seq++;
mutex_unlock(&session->s_mutex);
down_write(&mdsc->snap_rwsem);
locked_rwsem = 1;
if (op == CEPH_SNAP_OP_SPLIT) {
struct ceph_mds_snap_realm *ri;
/*
* A "split" breaks part of an existing realm off into
* a new realm. The MDS provides a list of inodes
* (with caps) and child realms that belong to the new
* child.
*/
split_inos = p;
p += sizeof(u64) * num_split_inos;
split_realms = p;
p += sizeof(u64) * num_split_realms;
ceph_decode_need(&p, e, sizeof(*ri), bad);
/* we will peek at realm info here, but will _not_
* advance p, as the realm update will occur below in
* ceph_update_snap_trace. */
ri = p;
realm = ceph_lookup_snap_realm(mdsc, split);
if (!realm) {
realm = ceph_create_snap_realm(mdsc, split);
if (IS_ERR(realm))
goto out;
}
ceph_get_snap_realm(mdsc, realm);
dout("splitting snap_realm %llx %p\n", realm->ino, realm);
for (i = 0; i < num_split_inos; i++) {
struct ceph_vino vino = {
.ino = le64_to_cpu(split_inos[i]),
.snap = CEPH_NOSNAP,
};
struct inode *inode = ceph_find_inode(sb, vino);
struct ceph_inode_info *ci;
struct ceph_snap_realm *oldrealm;
if (!inode)
continue;
ci = ceph_inode(inode);
spin_lock(&ci->i_ceph_lock);
if (!ci->i_snap_realm)
goto skip_inode;
/*
* If this inode belongs to a realm that was
* created after our new realm, we experienced
* a race (due to another split notifications
* arriving from a different MDS). So skip
* this inode.
*/
if (ci->i_snap_realm->created >
le64_to_cpu(ri->created)) {
dout(" leaving %p in newer realm %llx %p\n",
inode, ci->i_snap_realm->ino,
ci->i_snap_realm);
goto skip_inode;
}
dout(" will move %p to split realm %llx %p\n",
inode, realm->ino, realm);
/*
* Move the inode to the new realm
*/
spin_lock(&realm->inodes_with_caps_lock);
list_del_init(&ci->i_snap_realm_item);
list_add(&ci->i_snap_realm_item,
&realm->inodes_with_caps);
oldrealm = ci->i_snap_realm;
ci->i_snap_realm = realm;
spin_unlock(&realm->inodes_with_caps_lock);
spin_unlock(&ci->i_ceph_lock);
ceph_get_snap_realm(mdsc, realm);
ceph_put_snap_realm(mdsc, oldrealm);
iput(inode);
continue;
skip_inode:
spin_unlock(&ci->i_ceph_lock);
iput(inode);
}
/* we may have taken some of the old realm's children. */
for (i = 0; i < num_split_realms; i++) {
struct ceph_snap_realm *child =
ceph_lookup_snap_realm(mdsc,
le64_to_cpu(split_realms[i]));
if (!child)
continue;
adjust_snap_realm_parent(mdsc, child, realm->ino);
}
}
/*
* update using the provided snap trace. if we are deleting a
* snap, we can avoid queueing cap_snaps.
*/
ceph_update_snap_trace(mdsc, p, e,
op == CEPH_SNAP_OP_DESTROY);
if (op == CEPH_SNAP_OP_SPLIT)
/* we took a reference when we created the realm, above */
ceph_put_snap_realm(mdsc, realm);
__cleanup_empty_realms(mdsc);
up_write(&mdsc->snap_rwsem);
flush_snaps(mdsc);
return;
bad:
pr_err("corrupt snap message from mds%d\n", mds);
ceph_msg_dump(msg);
out:
if (locked_rwsem)
up_write(&mdsc->snap_rwsem);
return;
}
| gpl-2.0 |
daniel-ortiz/linux | arch/arm/mach-omap2/vp44xx_data.c | 1334 | 3309 | /*
* OMAP3 Voltage Processor (VP) data
*
* Copyright (C) 2007, 2010 Texas Instruments, Inc.
* Rajendra Nayak <rnayak@ti.com>
* Lesly A M <x0080970@ti.com>
* Thara Gopinath <thara@ti.com>
*
* Copyright (C) 2008, 2011 Nokia Corporation
* Kalle Jokiniemi
* Paul Walmsley
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/io.h>
#include <linux/err.h>
#include <linux/init.h>
#include "common.h"
#include "prm44xx.h"
#include "prm-regbits-44xx.h"
#include "voltage.h"
#include "vp.h"
static const struct omap_vp_ops omap4_vp_ops = {
.check_txdone = omap_prm_vp_check_txdone,
.clear_txdone = omap_prm_vp_clear_txdone,
};
/*
* VP data common to 44xx chips
* XXX This stuff presumably belongs in the vp44xx.c or vp.c file.
*/
static const struct omap_vp_common omap4_vp_common = {
.vpconfig_erroroffset_mask = OMAP4430_ERROROFFSET_MASK,
.vpconfig_errorgain_mask = OMAP4430_ERRORGAIN_MASK,
.vpconfig_initvoltage_mask = OMAP4430_INITVOLTAGE_MASK,
.vpconfig_timeouten = OMAP4430_TIMEOUTEN_MASK,
.vpconfig_initvdd = OMAP4430_INITVDD_MASK,
.vpconfig_forceupdate = OMAP4430_FORCEUPDATE_MASK,
.vpconfig_vpenable = OMAP4430_VPENABLE_MASK,
.vstepmin_smpswaittimemin_shift = OMAP4430_SMPSWAITTIMEMIN_SHIFT,
.vstepmax_smpswaittimemax_shift = OMAP4430_SMPSWAITTIMEMAX_SHIFT,
.vstepmin_stepmin_shift = OMAP4430_VSTEPMIN_SHIFT,
.vstepmax_stepmax_shift = OMAP4430_VSTEPMAX_SHIFT,
.vlimitto_vddmin_shift = OMAP4430_VDDMIN_SHIFT,
.vlimitto_vddmax_shift = OMAP4430_VDDMAX_SHIFT,
.vlimitto_timeout_shift = OMAP4430_TIMEOUT_SHIFT,
.vpvoltage_mask = OMAP4430_VPVOLTAGE_MASK,
.ops = &omap4_vp_ops,
};
struct omap_vp_instance omap4_vp_mpu = {
.id = OMAP4_VP_VDD_MPU_ID,
.common = &omap4_vp_common,
.vpconfig = OMAP4_PRM_VP_MPU_CONFIG_OFFSET,
.vstepmin = OMAP4_PRM_VP_MPU_VSTEPMIN_OFFSET,
.vstepmax = OMAP4_PRM_VP_MPU_VSTEPMAX_OFFSET,
.vlimitto = OMAP4_PRM_VP_MPU_VLIMITTO_OFFSET,
.vstatus = OMAP4_PRM_VP_MPU_STATUS_OFFSET,
.voltage = OMAP4_PRM_VP_MPU_VOLTAGE_OFFSET,
};
struct omap_vp_instance omap4_vp_iva = {
.id = OMAP4_VP_VDD_IVA_ID,
.common = &omap4_vp_common,
.vpconfig = OMAP4_PRM_VP_IVA_CONFIG_OFFSET,
.vstepmin = OMAP4_PRM_VP_IVA_VSTEPMIN_OFFSET,
.vstepmax = OMAP4_PRM_VP_IVA_VSTEPMAX_OFFSET,
.vlimitto = OMAP4_PRM_VP_IVA_VLIMITTO_OFFSET,
.vstatus = OMAP4_PRM_VP_IVA_STATUS_OFFSET,
.voltage = OMAP4_PRM_VP_IVA_VOLTAGE_OFFSET,
};
struct omap_vp_instance omap4_vp_core = {
.id = OMAP4_VP_VDD_CORE_ID,
.common = &omap4_vp_common,
.vpconfig = OMAP4_PRM_VP_CORE_CONFIG_OFFSET,
.vstepmin = OMAP4_PRM_VP_CORE_VSTEPMIN_OFFSET,
.vstepmax = OMAP4_PRM_VP_CORE_VSTEPMAX_OFFSET,
.vlimitto = OMAP4_PRM_VP_CORE_VLIMITTO_OFFSET,
.vstatus = OMAP4_PRM_VP_CORE_STATUS_OFFSET,
.voltage = OMAP4_PRM_VP_CORE_VOLTAGE_OFFSET,
};
struct omap_vp_param omap4_mpu_vp_data = {
.vddmin = OMAP4_VP_MPU_VLIMITTO_VDDMIN,
.vddmax = OMAP4_VP_MPU_VLIMITTO_VDDMAX,
};
struct omap_vp_param omap4_iva_vp_data = {
.vddmin = OMAP4_VP_IVA_VLIMITTO_VDDMIN,
.vddmax = OMAP4_VP_IVA_VLIMITTO_VDDMAX,
};
struct omap_vp_param omap4_core_vp_data = {
.vddmin = OMAP4_VP_CORE_VLIMITTO_VDDMIN,
.vddmax = OMAP4_VP_CORE_VLIMITTO_VDDMAX,
};
| gpl-2.0 |
posthumanik/golden_cm10.2_kernel | drivers/net/wireless/iwlegacy/iwl-core.c | 2358 | 74697 | /******************************************************************************
*
* GPL LICENSE SUMMARY
*
* Copyright(c) 2008 - 2011 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110,
* USA
*
* The full GNU General Public License is included in this distribution
* in the file called LICENSE.GPL.
*
* Contact Information:
* Intel Linux Wireless <ilw@linux.intel.com>
* Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*****************************************************************************/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/etherdevice.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <net/mac80211.h>
#include "iwl-eeprom.h"
#include "iwl-dev.h"
#include "iwl-debug.h"
#include "iwl-core.h"
#include "iwl-io.h"
#include "iwl-power.h"
#include "iwl-sta.h"
#include "iwl-helpers.h"
MODULE_DESCRIPTION("iwl-legacy: common functions for 3945 and 4965");
MODULE_VERSION(IWLWIFI_VERSION);
MODULE_AUTHOR(DRV_COPYRIGHT " " DRV_AUTHOR);
MODULE_LICENSE("GPL");
/*
* set bt_coex_active to true, uCode will do kill/defer
* every time the priority line is asserted (BT is sending signals on the
* priority line in the PCIx).
* set bt_coex_active to false, uCode will ignore the BT activity and
* perform the normal operation
*
* User might experience transmit issue on some platform due to WiFi/BT
* co-exist problem. The possible behaviors are:
* Able to scan and finding all the available AP
* Not able to associate with any AP
* On those platforms, WiFi communication can be restored by set
* "bt_coex_active" module parameter to "false"
*
* default: bt_coex_active = true (BT_COEX_ENABLE)
*/
static bool bt_coex_active = true;
module_param(bt_coex_active, bool, S_IRUGO);
MODULE_PARM_DESC(bt_coex_active, "enable wifi/bluetooth co-exist");
u32 iwlegacy_debug_level;
EXPORT_SYMBOL(iwlegacy_debug_level);
const u8 iwlegacy_bcast_addr[ETH_ALEN] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
EXPORT_SYMBOL(iwlegacy_bcast_addr);
/* This function both allocates and initializes hw and priv. */
struct ieee80211_hw *iwl_legacy_alloc_all(struct iwl_cfg *cfg)
{
struct iwl_priv *priv;
/* mac80211 allocates memory for this device instance, including
* space for this driver's private structure */
struct ieee80211_hw *hw;
hw = ieee80211_alloc_hw(sizeof(struct iwl_priv),
cfg->ops->ieee80211_ops);
if (hw == NULL) {
pr_err("%s: Can not allocate network device\n",
cfg->name);
goto out;
}
priv = hw->priv;
priv->hw = hw;
out:
return hw;
}
EXPORT_SYMBOL(iwl_legacy_alloc_all);
#define MAX_BIT_RATE_40_MHZ 150 /* Mbps */
#define MAX_BIT_RATE_20_MHZ 72 /* Mbps */
static void iwl_legacy_init_ht_hw_capab(const struct iwl_priv *priv,
struct ieee80211_sta_ht_cap *ht_info,
enum ieee80211_band band)
{
u16 max_bit_rate = 0;
u8 rx_chains_num = priv->hw_params.rx_chains_num;
u8 tx_chains_num = priv->hw_params.tx_chains_num;
ht_info->cap = 0;
memset(&ht_info->mcs, 0, sizeof(ht_info->mcs));
ht_info->ht_supported = true;
ht_info->cap |= IEEE80211_HT_CAP_SGI_20;
max_bit_rate = MAX_BIT_RATE_20_MHZ;
if (priv->hw_params.ht40_channel & BIT(band)) {
ht_info->cap |= IEEE80211_HT_CAP_SUP_WIDTH_20_40;
ht_info->cap |= IEEE80211_HT_CAP_SGI_40;
ht_info->mcs.rx_mask[4] = 0x01;
max_bit_rate = MAX_BIT_RATE_40_MHZ;
}
if (priv->cfg->mod_params->amsdu_size_8K)
ht_info->cap |= IEEE80211_HT_CAP_MAX_AMSDU;
ht_info->ampdu_factor = CFG_HT_RX_AMPDU_FACTOR_DEF;
ht_info->ampdu_density = CFG_HT_MPDU_DENSITY_DEF;
ht_info->mcs.rx_mask[0] = 0xFF;
if (rx_chains_num >= 2)
ht_info->mcs.rx_mask[1] = 0xFF;
if (rx_chains_num >= 3)
ht_info->mcs.rx_mask[2] = 0xFF;
/* Highest supported Rx data rate */
max_bit_rate *= rx_chains_num;
WARN_ON(max_bit_rate & ~IEEE80211_HT_MCS_RX_HIGHEST_MASK);
ht_info->mcs.rx_highest = cpu_to_le16(max_bit_rate);
/* Tx MCS capabilities */
ht_info->mcs.tx_params = IEEE80211_HT_MCS_TX_DEFINED;
if (tx_chains_num != rx_chains_num) {
ht_info->mcs.tx_params |= IEEE80211_HT_MCS_TX_RX_DIFF;
ht_info->mcs.tx_params |= ((tx_chains_num - 1) <<
IEEE80211_HT_MCS_TX_MAX_STREAMS_SHIFT);
}
}
/**
* iwl_legacy_init_geos - Initialize mac80211's geo/channel info based from eeprom
*/
int iwl_legacy_init_geos(struct iwl_priv *priv)
{
struct iwl_channel_info *ch;
struct ieee80211_supported_band *sband;
struct ieee80211_channel *channels;
struct ieee80211_channel *geo_ch;
struct ieee80211_rate *rates;
int i = 0;
s8 max_tx_power = 0;
if (priv->bands[IEEE80211_BAND_2GHZ].n_bitrates ||
priv->bands[IEEE80211_BAND_5GHZ].n_bitrates) {
IWL_DEBUG_INFO(priv, "Geography modes already initialized.\n");
set_bit(STATUS_GEO_CONFIGURED, &priv->status);
return 0;
}
channels = kzalloc(sizeof(struct ieee80211_channel) *
priv->channel_count, GFP_KERNEL);
if (!channels)
return -ENOMEM;
rates = kzalloc((sizeof(struct ieee80211_rate) * IWL_RATE_COUNT_LEGACY),
GFP_KERNEL);
if (!rates) {
kfree(channels);
return -ENOMEM;
}
/* 5.2GHz channels start after the 2.4GHz channels */
sband = &priv->bands[IEEE80211_BAND_5GHZ];
sband->channels = &channels[ARRAY_SIZE(iwlegacy_eeprom_band_1)];
/* just OFDM */
sband->bitrates = &rates[IWL_FIRST_OFDM_RATE];
sband->n_bitrates = IWL_RATE_COUNT_LEGACY - IWL_FIRST_OFDM_RATE;
if (priv->cfg->sku & IWL_SKU_N)
iwl_legacy_init_ht_hw_capab(priv, &sband->ht_cap,
IEEE80211_BAND_5GHZ);
sband = &priv->bands[IEEE80211_BAND_2GHZ];
sband->channels = channels;
/* OFDM & CCK */
sband->bitrates = rates;
sband->n_bitrates = IWL_RATE_COUNT_LEGACY;
if (priv->cfg->sku & IWL_SKU_N)
iwl_legacy_init_ht_hw_capab(priv, &sband->ht_cap,
IEEE80211_BAND_2GHZ);
priv->ieee_channels = channels;
priv->ieee_rates = rates;
for (i = 0; i < priv->channel_count; i++) {
ch = &priv->channel_info[i];
if (!iwl_legacy_is_channel_valid(ch))
continue;
sband = &priv->bands[ch->band];
geo_ch = &sband->channels[sband->n_channels++];
geo_ch->center_freq =
ieee80211_channel_to_frequency(ch->channel, ch->band);
geo_ch->max_power = ch->max_power_avg;
geo_ch->max_antenna_gain = 0xff;
geo_ch->hw_value = ch->channel;
if (iwl_legacy_is_channel_valid(ch)) {
if (!(ch->flags & EEPROM_CHANNEL_IBSS))
geo_ch->flags |= IEEE80211_CHAN_NO_IBSS;
if (!(ch->flags & EEPROM_CHANNEL_ACTIVE))
geo_ch->flags |= IEEE80211_CHAN_PASSIVE_SCAN;
if (ch->flags & EEPROM_CHANNEL_RADAR)
geo_ch->flags |= IEEE80211_CHAN_RADAR;
geo_ch->flags |= ch->ht40_extension_channel;
if (ch->max_power_avg > max_tx_power)
max_tx_power = ch->max_power_avg;
} else {
geo_ch->flags |= IEEE80211_CHAN_DISABLED;
}
IWL_DEBUG_INFO(priv, "Channel %d Freq=%d[%sGHz] %s flag=0x%X\n",
ch->channel, geo_ch->center_freq,
iwl_legacy_is_channel_a_band(ch) ? "5.2" : "2.4",
geo_ch->flags & IEEE80211_CHAN_DISABLED ?
"restricted" : "valid",
geo_ch->flags);
}
priv->tx_power_device_lmt = max_tx_power;
priv->tx_power_user_lmt = max_tx_power;
priv->tx_power_next = max_tx_power;
if ((priv->bands[IEEE80211_BAND_5GHZ].n_channels == 0) &&
priv->cfg->sku & IWL_SKU_A) {
IWL_INFO(priv, "Incorrectly detected BG card as ABG. "
"Please send your PCI ID 0x%04X:0x%04X to maintainer.\n",
priv->pci_dev->device,
priv->pci_dev->subsystem_device);
priv->cfg->sku &= ~IWL_SKU_A;
}
IWL_INFO(priv, "Tunable channels: %d 802.11bg, %d 802.11a channels\n",
priv->bands[IEEE80211_BAND_2GHZ].n_channels,
priv->bands[IEEE80211_BAND_5GHZ].n_channels);
set_bit(STATUS_GEO_CONFIGURED, &priv->status);
return 0;
}
EXPORT_SYMBOL(iwl_legacy_init_geos);
/*
* iwl_legacy_free_geos - undo allocations in iwl_legacy_init_geos
*/
void iwl_legacy_free_geos(struct iwl_priv *priv)
{
kfree(priv->ieee_channels);
kfree(priv->ieee_rates);
clear_bit(STATUS_GEO_CONFIGURED, &priv->status);
}
EXPORT_SYMBOL(iwl_legacy_free_geos);
static bool iwl_legacy_is_channel_extension(struct iwl_priv *priv,
enum ieee80211_band band,
u16 channel, u8 extension_chan_offset)
{
const struct iwl_channel_info *ch_info;
ch_info = iwl_legacy_get_channel_info(priv, band, channel);
if (!iwl_legacy_is_channel_valid(ch_info))
return false;
if (extension_chan_offset == IEEE80211_HT_PARAM_CHA_SEC_ABOVE)
return !(ch_info->ht40_extension_channel &
IEEE80211_CHAN_NO_HT40PLUS);
else if (extension_chan_offset == IEEE80211_HT_PARAM_CHA_SEC_BELOW)
return !(ch_info->ht40_extension_channel &
IEEE80211_CHAN_NO_HT40MINUS);
return false;
}
bool iwl_legacy_is_ht40_tx_allowed(struct iwl_priv *priv,
struct iwl_rxon_context *ctx,
struct ieee80211_sta_ht_cap *ht_cap)
{
if (!ctx->ht.enabled || !ctx->ht.is_40mhz)
return false;
/*
* We do not check for IEEE80211_HT_CAP_SUP_WIDTH_20_40
* the bit will not set if it is pure 40MHz case
*/
if (ht_cap && !ht_cap->ht_supported)
return false;
#ifdef CONFIG_IWLWIFI_LEGACY_DEBUGFS
if (priv->disable_ht40)
return false;
#endif
return iwl_legacy_is_channel_extension(priv, priv->band,
le16_to_cpu(ctx->staging.channel),
ctx->ht.extension_chan_offset);
}
EXPORT_SYMBOL(iwl_legacy_is_ht40_tx_allowed);
static u16 iwl_legacy_adjust_beacon_interval(u16 beacon_val, u16 max_beacon_val)
{
u16 new_val;
u16 beacon_factor;
/*
* If mac80211 hasn't given us a beacon interval, program
* the default into the device.
*/
if (!beacon_val)
return DEFAULT_BEACON_INTERVAL;
/*
* If the beacon interval we obtained from the peer
* is too large, we'll have to wake up more often
* (and in IBSS case, we'll beacon too much)
*
* For example, if max_beacon_val is 4096, and the
* requested beacon interval is 7000, we'll have to
* use 3500 to be able to wake up on the beacons.
*
* This could badly influence beacon detection stats.
*/
beacon_factor = (beacon_val + max_beacon_val) / max_beacon_val;
new_val = beacon_val / beacon_factor;
if (!new_val)
new_val = max_beacon_val;
return new_val;
}
int
iwl_legacy_send_rxon_timing(struct iwl_priv *priv, struct iwl_rxon_context *ctx)
{
u64 tsf;
s32 interval_tm, rem;
struct ieee80211_conf *conf = NULL;
u16 beacon_int;
struct ieee80211_vif *vif = ctx->vif;
conf = iwl_legacy_ieee80211_get_hw_conf(priv->hw);
lockdep_assert_held(&priv->mutex);
memset(&ctx->timing, 0, sizeof(struct iwl_rxon_time_cmd));
ctx->timing.timestamp = cpu_to_le64(priv->timestamp);
ctx->timing.listen_interval = cpu_to_le16(conf->listen_interval);
beacon_int = vif ? vif->bss_conf.beacon_int : 0;
/*
* TODO: For IBSS we need to get atim_window from mac80211,
* for now just always use 0
*/
ctx->timing.atim_window = 0;
beacon_int = iwl_legacy_adjust_beacon_interval(beacon_int,
priv->hw_params.max_beacon_itrvl * TIME_UNIT);
ctx->timing.beacon_interval = cpu_to_le16(beacon_int);
tsf = priv->timestamp; /* tsf is modifed by do_div: copy it */
interval_tm = beacon_int * TIME_UNIT;
rem = do_div(tsf, interval_tm);
ctx->timing.beacon_init_val = cpu_to_le32(interval_tm - rem);
ctx->timing.dtim_period = vif ? (vif->bss_conf.dtim_period ?: 1) : 1;
IWL_DEBUG_ASSOC(priv,
"beacon interval %d beacon timer %d beacon tim %d\n",
le16_to_cpu(ctx->timing.beacon_interval),
le32_to_cpu(ctx->timing.beacon_init_val),
le16_to_cpu(ctx->timing.atim_window));
return iwl_legacy_send_cmd_pdu(priv, ctx->rxon_timing_cmd,
sizeof(ctx->timing), &ctx->timing);
}
EXPORT_SYMBOL(iwl_legacy_send_rxon_timing);
void
iwl_legacy_set_rxon_hwcrypto(struct iwl_priv *priv,
struct iwl_rxon_context *ctx,
int hw_decrypt)
{
struct iwl_legacy_rxon_cmd *rxon = &ctx->staging;
if (hw_decrypt)
rxon->filter_flags &= ~RXON_FILTER_DIS_DECRYPT_MSK;
else
rxon->filter_flags |= RXON_FILTER_DIS_DECRYPT_MSK;
}
EXPORT_SYMBOL(iwl_legacy_set_rxon_hwcrypto);
/* validate RXON structure is valid */
int
iwl_legacy_check_rxon_cmd(struct iwl_priv *priv, struct iwl_rxon_context *ctx)
{
struct iwl_legacy_rxon_cmd *rxon = &ctx->staging;
bool error = false;
if (rxon->flags & RXON_FLG_BAND_24G_MSK) {
if (rxon->flags & RXON_FLG_TGJ_NARROW_BAND_MSK) {
IWL_WARN(priv, "check 2.4G: wrong narrow\n");
error = true;
}
if (rxon->flags & RXON_FLG_RADAR_DETECT_MSK) {
IWL_WARN(priv, "check 2.4G: wrong radar\n");
error = true;
}
} else {
if (!(rxon->flags & RXON_FLG_SHORT_SLOT_MSK)) {
IWL_WARN(priv, "check 5.2G: not short slot!\n");
error = true;
}
if (rxon->flags & RXON_FLG_CCK_MSK) {
IWL_WARN(priv, "check 5.2G: CCK!\n");
error = true;
}
}
if ((rxon->node_addr[0] | rxon->bssid_addr[0]) & 0x1) {
IWL_WARN(priv, "mac/bssid mcast!\n");
error = true;
}
/* make sure basic rates 6Mbps and 1Mbps are supported */
if ((rxon->ofdm_basic_rates & IWL_RATE_6M_MASK) == 0 &&
(rxon->cck_basic_rates & IWL_RATE_1M_MASK) == 0) {
IWL_WARN(priv, "neither 1 nor 6 are basic\n");
error = true;
}
if (le16_to_cpu(rxon->assoc_id) > 2007) {
IWL_WARN(priv, "aid > 2007\n");
error = true;
}
if ((rxon->flags & (RXON_FLG_CCK_MSK | RXON_FLG_SHORT_SLOT_MSK))
== (RXON_FLG_CCK_MSK | RXON_FLG_SHORT_SLOT_MSK)) {
IWL_WARN(priv, "CCK and short slot\n");
error = true;
}
if ((rxon->flags & (RXON_FLG_CCK_MSK | RXON_FLG_AUTO_DETECT_MSK))
== (RXON_FLG_CCK_MSK | RXON_FLG_AUTO_DETECT_MSK)) {
IWL_WARN(priv, "CCK and auto detect");
error = true;
}
if ((rxon->flags & (RXON_FLG_AUTO_DETECT_MSK |
RXON_FLG_TGG_PROTECT_MSK)) ==
RXON_FLG_TGG_PROTECT_MSK) {
IWL_WARN(priv, "TGg but no auto-detect\n");
error = true;
}
if (error)
IWL_WARN(priv, "Tuning to channel %d\n",
le16_to_cpu(rxon->channel));
if (error) {
IWL_ERR(priv, "Invalid RXON\n");
return -EINVAL;
}
return 0;
}
EXPORT_SYMBOL(iwl_legacy_check_rxon_cmd);
/**
* iwl_legacy_full_rxon_required - check if full RXON (vs RXON_ASSOC) cmd is needed
* @priv: staging_rxon is compared to active_rxon
*
* If the RXON structure is changing enough to require a new tune,
* or is clearing the RXON_FILTER_ASSOC_MSK, then return 1 to indicate that
* a new tune (full RXON command, rather than RXON_ASSOC cmd) is required.
*/
int iwl_legacy_full_rxon_required(struct iwl_priv *priv,
struct iwl_rxon_context *ctx)
{
const struct iwl_legacy_rxon_cmd *staging = &ctx->staging;
const struct iwl_legacy_rxon_cmd *active = &ctx->active;
#define CHK(cond) \
if ((cond)) { \
IWL_DEBUG_INFO(priv, "need full RXON - " #cond "\n"); \
return 1; \
}
#define CHK_NEQ(c1, c2) \
if ((c1) != (c2)) { \
IWL_DEBUG_INFO(priv, "need full RXON - " \
#c1 " != " #c2 " - %d != %d\n", \
(c1), (c2)); \
return 1; \
}
/* These items are only settable from the full RXON command */
CHK(!iwl_legacy_is_associated_ctx(ctx));
CHK(compare_ether_addr(staging->bssid_addr, active->bssid_addr));
CHK(compare_ether_addr(staging->node_addr, active->node_addr));
CHK(compare_ether_addr(staging->wlap_bssid_addr,
active->wlap_bssid_addr));
CHK_NEQ(staging->dev_type, active->dev_type);
CHK_NEQ(staging->channel, active->channel);
CHK_NEQ(staging->air_propagation, active->air_propagation);
CHK_NEQ(staging->ofdm_ht_single_stream_basic_rates,
active->ofdm_ht_single_stream_basic_rates);
CHK_NEQ(staging->ofdm_ht_dual_stream_basic_rates,
active->ofdm_ht_dual_stream_basic_rates);
CHK_NEQ(staging->assoc_id, active->assoc_id);
/* flags, filter_flags, ofdm_basic_rates, and cck_basic_rates can
* be updated with the RXON_ASSOC command -- however only some
* flag transitions are allowed using RXON_ASSOC */
/* Check if we are not switching bands */
CHK_NEQ(staging->flags & RXON_FLG_BAND_24G_MSK,
active->flags & RXON_FLG_BAND_24G_MSK);
/* Check if we are switching association toggle */
CHK_NEQ(staging->filter_flags & RXON_FILTER_ASSOC_MSK,
active->filter_flags & RXON_FILTER_ASSOC_MSK);
#undef CHK
#undef CHK_NEQ
return 0;
}
EXPORT_SYMBOL(iwl_legacy_full_rxon_required);
u8 iwl_legacy_get_lowest_plcp(struct iwl_priv *priv,
struct iwl_rxon_context *ctx)
{
/*
* Assign the lowest rate -- should really get this from
* the beacon skb from mac80211.
*/
if (ctx->staging.flags & RXON_FLG_BAND_24G_MSK)
return IWL_RATE_1M_PLCP;
else
return IWL_RATE_6M_PLCP;
}
EXPORT_SYMBOL(iwl_legacy_get_lowest_plcp);
static void _iwl_legacy_set_rxon_ht(struct iwl_priv *priv,
struct iwl_ht_config *ht_conf,
struct iwl_rxon_context *ctx)
{
struct iwl_legacy_rxon_cmd *rxon = &ctx->staging;
if (!ctx->ht.enabled) {
rxon->flags &= ~(RXON_FLG_CHANNEL_MODE_MSK |
RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK |
RXON_FLG_HT40_PROT_MSK |
RXON_FLG_HT_PROT_MSK);
return;
}
rxon->flags |= cpu_to_le32(ctx->ht.protection <<
RXON_FLG_HT_OPERATING_MODE_POS);
/* Set up channel bandwidth:
* 20 MHz only, 20/40 mixed or pure 40 if ht40 ok */
/* clear the HT channel mode before set the mode */
rxon->flags &= ~(RXON_FLG_CHANNEL_MODE_MSK |
RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK);
if (iwl_legacy_is_ht40_tx_allowed(priv, ctx, NULL)) {
/* pure ht40 */
if (ctx->ht.protection ==
IEEE80211_HT_OP_MODE_PROTECTION_20MHZ) {
rxon->flags |= RXON_FLG_CHANNEL_MODE_PURE_40;
/* Note: control channel is opposite of extension channel */
switch (ctx->ht.extension_chan_offset) {
case IEEE80211_HT_PARAM_CHA_SEC_ABOVE:
rxon->flags &=
~RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK;
break;
case IEEE80211_HT_PARAM_CHA_SEC_BELOW:
rxon->flags |=
RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK;
break;
}
} else {
/* Note: control channel is opposite of extension channel */
switch (ctx->ht.extension_chan_offset) {
case IEEE80211_HT_PARAM_CHA_SEC_ABOVE:
rxon->flags &=
~(RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK);
rxon->flags |= RXON_FLG_CHANNEL_MODE_MIXED;
break;
case IEEE80211_HT_PARAM_CHA_SEC_BELOW:
rxon->flags |=
RXON_FLG_CTRL_CHANNEL_LOC_HI_MSK;
rxon->flags |= RXON_FLG_CHANNEL_MODE_MIXED;
break;
case IEEE80211_HT_PARAM_CHA_SEC_NONE:
default:
/* channel location only valid if in Mixed mode */
IWL_ERR(priv,
"invalid extension channel offset\n");
break;
}
}
} else {
rxon->flags |= RXON_FLG_CHANNEL_MODE_LEGACY;
}
if (priv->cfg->ops->hcmd->set_rxon_chain)
priv->cfg->ops->hcmd->set_rxon_chain(priv, ctx);
IWL_DEBUG_ASSOC(priv, "rxon flags 0x%X operation mode :0x%X "
"extension channel offset 0x%x\n",
le32_to_cpu(rxon->flags), ctx->ht.protection,
ctx->ht.extension_chan_offset);
}
void iwl_legacy_set_rxon_ht(struct iwl_priv *priv, struct iwl_ht_config *ht_conf)
{
struct iwl_rxon_context *ctx;
for_each_context(priv, ctx)
_iwl_legacy_set_rxon_ht(priv, ht_conf, ctx);
}
EXPORT_SYMBOL(iwl_legacy_set_rxon_ht);
/* Return valid, unused, channel for a passive scan to reset the RF */
u8 iwl_legacy_get_single_channel_number(struct iwl_priv *priv,
enum ieee80211_band band)
{
const struct iwl_channel_info *ch_info;
int i;
u8 channel = 0;
u8 min, max;
struct iwl_rxon_context *ctx;
if (band == IEEE80211_BAND_5GHZ) {
min = 14;
max = priv->channel_count;
} else {
min = 0;
max = 14;
}
for (i = min; i < max; i++) {
bool busy = false;
for_each_context(priv, ctx) {
busy = priv->channel_info[i].channel ==
le16_to_cpu(ctx->staging.channel);
if (busy)
break;
}
if (busy)
continue;
channel = priv->channel_info[i].channel;
ch_info = iwl_legacy_get_channel_info(priv, band, channel);
if (iwl_legacy_is_channel_valid(ch_info))
break;
}
return channel;
}
EXPORT_SYMBOL(iwl_legacy_get_single_channel_number);
/**
* iwl_legacy_set_rxon_channel - Set the band and channel values in staging RXON
* @ch: requested channel as a pointer to struct ieee80211_channel
* NOTE: Does not commit to the hardware; it sets appropriate bit fields
* in the staging RXON flag structure based on the ch->band
*/
int
iwl_legacy_set_rxon_channel(struct iwl_priv *priv, struct ieee80211_channel *ch,
struct iwl_rxon_context *ctx)
{
enum ieee80211_band band = ch->band;
u16 channel = ch->hw_value;
if ((le16_to_cpu(ctx->staging.channel) == channel) &&
(priv->band == band))
return 0;
ctx->staging.channel = cpu_to_le16(channel);
if (band == IEEE80211_BAND_5GHZ)
ctx->staging.flags &= ~RXON_FLG_BAND_24G_MSK;
else
ctx->staging.flags |= RXON_FLG_BAND_24G_MSK;
priv->band = band;
IWL_DEBUG_INFO(priv, "Staging channel set to %d [%d]\n", channel, band);
return 0;
}
EXPORT_SYMBOL(iwl_legacy_set_rxon_channel);
void iwl_legacy_set_flags_for_band(struct iwl_priv *priv,
struct iwl_rxon_context *ctx,
enum ieee80211_band band,
struct ieee80211_vif *vif)
{
if (band == IEEE80211_BAND_5GHZ) {
ctx->staging.flags &=
~(RXON_FLG_BAND_24G_MSK | RXON_FLG_AUTO_DETECT_MSK
| RXON_FLG_CCK_MSK);
ctx->staging.flags |= RXON_FLG_SHORT_SLOT_MSK;
} else {
/* Copied from iwl_post_associate() */
if (vif && vif->bss_conf.use_short_slot)
ctx->staging.flags |= RXON_FLG_SHORT_SLOT_MSK;
else
ctx->staging.flags &= ~RXON_FLG_SHORT_SLOT_MSK;
ctx->staging.flags |= RXON_FLG_BAND_24G_MSK;
ctx->staging.flags |= RXON_FLG_AUTO_DETECT_MSK;
ctx->staging.flags &= ~RXON_FLG_CCK_MSK;
}
}
EXPORT_SYMBOL(iwl_legacy_set_flags_for_band);
/*
* initialize rxon structure with default values from eeprom
*/
void iwl_legacy_connection_init_rx_config(struct iwl_priv *priv,
struct iwl_rxon_context *ctx)
{
const struct iwl_channel_info *ch_info;
memset(&ctx->staging, 0, sizeof(ctx->staging));
if (!ctx->vif) {
ctx->staging.dev_type = ctx->unused_devtype;
} else
switch (ctx->vif->type) {
case NL80211_IFTYPE_STATION:
ctx->staging.dev_type = ctx->station_devtype;
ctx->staging.filter_flags = RXON_FILTER_ACCEPT_GRP_MSK;
break;
case NL80211_IFTYPE_ADHOC:
ctx->staging.dev_type = ctx->ibss_devtype;
ctx->staging.flags = RXON_FLG_SHORT_PREAMBLE_MSK;
ctx->staging.filter_flags = RXON_FILTER_BCON_AWARE_MSK |
RXON_FILTER_ACCEPT_GRP_MSK;
break;
default:
IWL_ERR(priv, "Unsupported interface type %d\n",
ctx->vif->type);
break;
}
#if 0
/* TODO: Figure out when short_preamble would be set and cache from
* that */
if (!hw_to_local(priv->hw)->short_preamble)
ctx->staging.flags &= ~RXON_FLG_SHORT_PREAMBLE_MSK;
else
ctx->staging.flags |= RXON_FLG_SHORT_PREAMBLE_MSK;
#endif
ch_info = iwl_legacy_get_channel_info(priv, priv->band,
le16_to_cpu(ctx->active.channel));
if (!ch_info)
ch_info = &priv->channel_info[0];
ctx->staging.channel = cpu_to_le16(ch_info->channel);
priv->band = ch_info->band;
iwl_legacy_set_flags_for_band(priv, ctx, priv->band, ctx->vif);
ctx->staging.ofdm_basic_rates =
(IWL_OFDM_RATES_MASK >> IWL_FIRST_OFDM_RATE) & 0xFF;
ctx->staging.cck_basic_rates =
(IWL_CCK_RATES_MASK >> IWL_FIRST_CCK_RATE) & 0xF;
/* clear both MIX and PURE40 mode flag */
ctx->staging.flags &= ~(RXON_FLG_CHANNEL_MODE_MIXED |
RXON_FLG_CHANNEL_MODE_PURE_40);
if (ctx->vif)
memcpy(ctx->staging.node_addr, ctx->vif->addr, ETH_ALEN);
ctx->staging.ofdm_ht_single_stream_basic_rates = 0xff;
ctx->staging.ofdm_ht_dual_stream_basic_rates = 0xff;
}
EXPORT_SYMBOL(iwl_legacy_connection_init_rx_config);
void iwl_legacy_set_rate(struct iwl_priv *priv)
{
const struct ieee80211_supported_band *hw = NULL;
struct ieee80211_rate *rate;
struct iwl_rxon_context *ctx;
int i;
hw = iwl_get_hw_mode(priv, priv->band);
if (!hw) {
IWL_ERR(priv, "Failed to set rate: unable to get hw mode\n");
return;
}
priv->active_rate = 0;
for (i = 0; i < hw->n_bitrates; i++) {
rate = &(hw->bitrates[i]);
if (rate->hw_value < IWL_RATE_COUNT_LEGACY)
priv->active_rate |= (1 << rate->hw_value);
}
IWL_DEBUG_RATE(priv, "Set active_rate = %0x\n", priv->active_rate);
for_each_context(priv, ctx) {
ctx->staging.cck_basic_rates =
(IWL_CCK_BASIC_RATES_MASK >> IWL_FIRST_CCK_RATE) & 0xF;
ctx->staging.ofdm_basic_rates =
(IWL_OFDM_BASIC_RATES_MASK >> IWL_FIRST_OFDM_RATE) & 0xFF;
}
}
EXPORT_SYMBOL(iwl_legacy_set_rate);
void iwl_legacy_chswitch_done(struct iwl_priv *priv, bool is_success)
{
struct iwl_rxon_context *ctx = &priv->contexts[IWL_RXON_CTX_BSS];
if (test_bit(STATUS_EXIT_PENDING, &priv->status))
return;
if (test_and_clear_bit(STATUS_CHANNEL_SWITCH_PENDING, &priv->status))
ieee80211_chswitch_done(ctx->vif, is_success);
}
EXPORT_SYMBOL(iwl_legacy_chswitch_done);
void iwl_legacy_rx_csa(struct iwl_priv *priv, struct iwl_rx_mem_buffer *rxb)
{
struct iwl_rx_packet *pkt = rxb_addr(rxb);
struct iwl_csa_notification *csa = &(pkt->u.csa_notif);
struct iwl_rxon_context *ctx = &priv->contexts[IWL_RXON_CTX_BSS];
struct iwl_legacy_rxon_cmd *rxon = (void *)&ctx->active;
if (!test_bit(STATUS_CHANNEL_SWITCH_PENDING, &priv->status))
return;
if (!le32_to_cpu(csa->status) && csa->channel == priv->switch_channel) {
rxon->channel = csa->channel;
ctx->staging.channel = csa->channel;
IWL_DEBUG_11H(priv, "CSA notif: channel %d\n",
le16_to_cpu(csa->channel));
iwl_legacy_chswitch_done(priv, true);
} else {
IWL_ERR(priv, "CSA notif (fail) : channel %d\n",
le16_to_cpu(csa->channel));
iwl_legacy_chswitch_done(priv, false);
}
}
EXPORT_SYMBOL(iwl_legacy_rx_csa);
#ifdef CONFIG_IWLWIFI_LEGACY_DEBUG
void iwl_legacy_print_rx_config_cmd(struct iwl_priv *priv,
struct iwl_rxon_context *ctx)
{
struct iwl_legacy_rxon_cmd *rxon = &ctx->staging;
IWL_DEBUG_RADIO(priv, "RX CONFIG:\n");
iwl_print_hex_dump(priv, IWL_DL_RADIO, (u8 *) rxon, sizeof(*rxon));
IWL_DEBUG_RADIO(priv, "u16 channel: 0x%x\n",
le16_to_cpu(rxon->channel));
IWL_DEBUG_RADIO(priv, "u32 flags: 0x%08X\n", le32_to_cpu(rxon->flags));
IWL_DEBUG_RADIO(priv, "u32 filter_flags: 0x%08x\n",
le32_to_cpu(rxon->filter_flags));
IWL_DEBUG_RADIO(priv, "u8 dev_type: 0x%x\n", rxon->dev_type);
IWL_DEBUG_RADIO(priv, "u8 ofdm_basic_rates: 0x%02x\n",
rxon->ofdm_basic_rates);
IWL_DEBUG_RADIO(priv, "u8 cck_basic_rates: 0x%02x\n",
rxon->cck_basic_rates);
IWL_DEBUG_RADIO(priv, "u8[6] node_addr: %pM\n", rxon->node_addr);
IWL_DEBUG_RADIO(priv, "u8[6] bssid_addr: %pM\n", rxon->bssid_addr);
IWL_DEBUG_RADIO(priv, "u16 assoc_id: 0x%x\n",
le16_to_cpu(rxon->assoc_id));
}
EXPORT_SYMBOL(iwl_legacy_print_rx_config_cmd);
#endif
/**
* iwl_legacy_irq_handle_error - called for HW or SW error interrupt from card
*/
void iwl_legacy_irq_handle_error(struct iwl_priv *priv)
{
/* Set the FW error flag -- cleared on iwl_down */
set_bit(STATUS_FW_ERROR, &priv->status);
/* Cancel currently queued command. */
clear_bit(STATUS_HCMD_ACTIVE, &priv->status);
IWL_ERR(priv, "Loaded firmware version: %s\n",
priv->hw->wiphy->fw_version);
priv->cfg->ops->lib->dump_nic_error_log(priv);
if (priv->cfg->ops->lib->dump_fh)
priv->cfg->ops->lib->dump_fh(priv, NULL, false);
priv->cfg->ops->lib->dump_nic_event_log(priv, false, NULL, false);
#ifdef CONFIG_IWLWIFI_LEGACY_DEBUG
if (iwl_legacy_get_debug_level(priv) & IWL_DL_FW_ERRORS)
iwl_legacy_print_rx_config_cmd(priv,
&priv->contexts[IWL_RXON_CTX_BSS]);
#endif
wake_up(&priv->wait_command_queue);
/* Keep the restart process from trying to send host
* commands by clearing the INIT status bit */
clear_bit(STATUS_READY, &priv->status);
if (!test_bit(STATUS_EXIT_PENDING, &priv->status)) {
IWL_DEBUG(priv, IWL_DL_FW_ERRORS,
"Restarting adapter due to uCode error.\n");
if (priv->cfg->mod_params->restart_fw)
queue_work(priv->workqueue, &priv->restart);
}
}
EXPORT_SYMBOL(iwl_legacy_irq_handle_error);
static int iwl_legacy_apm_stop_master(struct iwl_priv *priv)
{
int ret = 0;
/* stop device's busmaster DMA activity */
iwl_legacy_set_bit(priv, CSR_RESET, CSR_RESET_REG_FLAG_STOP_MASTER);
ret = iwl_poll_bit(priv, CSR_RESET, CSR_RESET_REG_FLAG_MASTER_DISABLED,
CSR_RESET_REG_FLAG_MASTER_DISABLED, 100);
if (ret)
IWL_WARN(priv, "Master Disable Timed Out, 100 usec\n");
IWL_DEBUG_INFO(priv, "stop master\n");
return ret;
}
void iwl_legacy_apm_stop(struct iwl_priv *priv)
{
IWL_DEBUG_INFO(priv, "Stop card, put in low power state\n");
/* Stop device's DMA activity */
iwl_legacy_apm_stop_master(priv);
/* Reset the entire device */
iwl_legacy_set_bit(priv, CSR_RESET, CSR_RESET_REG_FLAG_SW_RESET);
udelay(10);
/*
* Clear "initialization complete" bit to move adapter from
* D0A* (powered-up Active) --> D0U* (Uninitialized) state.
*/
iwl_legacy_clear_bit(priv, CSR_GP_CNTRL,
CSR_GP_CNTRL_REG_FLAG_INIT_DONE);
}
EXPORT_SYMBOL(iwl_legacy_apm_stop);
/*
* Start up NIC's basic functionality after it has been reset
* (e.g. after platform boot, or shutdown via iwl_legacy_apm_stop())
* NOTE: This does not load uCode nor start the embedded processor
*/
int iwl_legacy_apm_init(struct iwl_priv *priv)
{
int ret = 0;
u16 lctl;
IWL_DEBUG_INFO(priv, "Init card's basic functions\n");
/*
* Use "set_bit" below rather than "write", to preserve any hardware
* bits already set by default after reset.
*/
/* Disable L0S exit timer (platform NMI Work/Around) */
iwl_legacy_set_bit(priv, CSR_GIO_CHICKEN_BITS,
CSR_GIO_CHICKEN_BITS_REG_BIT_DIS_L0S_EXIT_TIMER);
/*
* Disable L0s without affecting L1;
* don't wait for ICH L0s (ICH bug W/A)
*/
iwl_legacy_set_bit(priv, CSR_GIO_CHICKEN_BITS,
CSR_GIO_CHICKEN_BITS_REG_BIT_L1A_NO_L0S_RX);
/* Set FH wait threshold to maximum (HW error during stress W/A) */
iwl_legacy_set_bit(priv, CSR_DBG_HPET_MEM_REG,
CSR_DBG_HPET_MEM_REG_VAL);
/*
* Enable HAP INTA (interrupt from management bus) to
* wake device's PCI Express link L1a -> L0s
* NOTE: This is no-op for 3945 (non-existent bit)
*/
iwl_legacy_set_bit(priv, CSR_HW_IF_CONFIG_REG,
CSR_HW_IF_CONFIG_REG_BIT_HAP_WAKE_L1A);
/*
* HW bug W/A for instability in PCIe bus L0->L0S->L1 transition.
* Check if BIOS (or OS) enabled L1-ASPM on this device.
* If so (likely), disable L0S, so device moves directly L0->L1;
* costs negligible amount of power savings.
* If not (unlikely), enable L0S, so there is at least some
* power savings, even without L1.
*/
if (priv->cfg->base_params->set_l0s) {
lctl = iwl_legacy_pcie_link_ctl(priv);
if ((lctl & PCI_CFG_LINK_CTRL_VAL_L1_EN) ==
PCI_CFG_LINK_CTRL_VAL_L1_EN) {
/* L1-ASPM enabled; disable(!) L0S */
iwl_legacy_set_bit(priv, CSR_GIO_REG,
CSR_GIO_REG_VAL_L0S_ENABLED);
IWL_DEBUG_POWER(priv, "L1 Enabled; Disabling L0S\n");
} else {
/* L1-ASPM disabled; enable(!) L0S */
iwl_legacy_clear_bit(priv, CSR_GIO_REG,
CSR_GIO_REG_VAL_L0S_ENABLED);
IWL_DEBUG_POWER(priv, "L1 Disabled; Enabling L0S\n");
}
}
/* Configure analog phase-lock-loop before activating to D0A */
if (priv->cfg->base_params->pll_cfg_val)
iwl_legacy_set_bit(priv, CSR_ANA_PLL_CFG,
priv->cfg->base_params->pll_cfg_val);
/*
* Set "initialization complete" bit to move adapter from
* D0U* --> D0A* (powered-up active) state.
*/
iwl_legacy_set_bit(priv, CSR_GP_CNTRL, CSR_GP_CNTRL_REG_FLAG_INIT_DONE);
/*
* Wait for clock stabilization; once stabilized, access to
* device-internal resources is supported, e.g. iwl_legacy_write_prph()
* and accesses to uCode SRAM.
*/
ret = iwl_poll_bit(priv, CSR_GP_CNTRL,
CSR_GP_CNTRL_REG_FLAG_MAC_CLOCK_READY,
CSR_GP_CNTRL_REG_FLAG_MAC_CLOCK_READY, 25000);
if (ret < 0) {
IWL_DEBUG_INFO(priv, "Failed to init the card\n");
goto out;
}
/*
* Enable DMA and BSM (if used) clocks, wait for them to stabilize.
* BSM (Boostrap State Machine) is only in 3945 and 4965.
*
* Write to "CLK_EN_REG"; "1" bits enable clocks, while "0" bits
* do not disable clocks. This preserves any hardware bits already
* set by default in "CLK_CTRL_REG" after reset.
*/
if (priv->cfg->base_params->use_bsm)
iwl_legacy_write_prph(priv, APMG_CLK_EN_REG,
APMG_CLK_VAL_DMA_CLK_RQT | APMG_CLK_VAL_BSM_CLK_RQT);
else
iwl_legacy_write_prph(priv, APMG_CLK_EN_REG,
APMG_CLK_VAL_DMA_CLK_RQT);
udelay(20);
/* Disable L1-Active */
iwl_legacy_set_bits_prph(priv, APMG_PCIDEV_STT_REG,
APMG_PCIDEV_STT_VAL_L1_ACT_DIS);
out:
return ret;
}
EXPORT_SYMBOL(iwl_legacy_apm_init);
int iwl_legacy_set_tx_power(struct iwl_priv *priv, s8 tx_power, bool force)
{
int ret;
s8 prev_tx_power;
bool defer;
struct iwl_rxon_context *ctx = &priv->contexts[IWL_RXON_CTX_BSS];
lockdep_assert_held(&priv->mutex);
if (priv->tx_power_user_lmt == tx_power && !force)
return 0;
if (!priv->cfg->ops->lib->send_tx_power)
return -EOPNOTSUPP;
/* 0 dBm mean 1 milliwatt */
if (tx_power < 0) {
IWL_WARN(priv,
"Requested user TXPOWER %d below 1 mW.\n",
tx_power);
return -EINVAL;
}
if (tx_power > priv->tx_power_device_lmt) {
IWL_WARN(priv,
"Requested user TXPOWER %d above upper limit %d.\n",
tx_power, priv->tx_power_device_lmt);
return -EINVAL;
}
if (!iwl_legacy_is_ready_rf(priv))
return -EIO;
/* scan complete and commit_rxon use tx_power_next value,
* it always need to be updated for newest request */
priv->tx_power_next = tx_power;
/* do not set tx power when scanning or channel changing */
defer = test_bit(STATUS_SCANNING, &priv->status) ||
memcmp(&ctx->active, &ctx->staging, sizeof(ctx->staging));
if (defer && !force) {
IWL_DEBUG_INFO(priv, "Deferring tx power set\n");
return 0;
}
prev_tx_power = priv->tx_power_user_lmt;
priv->tx_power_user_lmt = tx_power;
ret = priv->cfg->ops->lib->send_tx_power(priv);
/* if fail to set tx_power, restore the orig. tx power */
if (ret) {
priv->tx_power_user_lmt = prev_tx_power;
priv->tx_power_next = prev_tx_power;
}
return ret;
}
EXPORT_SYMBOL(iwl_legacy_set_tx_power);
void iwl_legacy_send_bt_config(struct iwl_priv *priv)
{
struct iwl_bt_cmd bt_cmd = {
.lead_time = BT_LEAD_TIME_DEF,
.max_kill = BT_MAX_KILL_DEF,
.kill_ack_mask = 0,
.kill_cts_mask = 0,
};
if (!bt_coex_active)
bt_cmd.flags = BT_COEX_DISABLE;
else
bt_cmd.flags = BT_COEX_ENABLE;
IWL_DEBUG_INFO(priv, "BT coex %s\n",
(bt_cmd.flags == BT_COEX_DISABLE) ? "disable" : "active");
if (iwl_legacy_send_cmd_pdu(priv, REPLY_BT_CONFIG,
sizeof(struct iwl_bt_cmd), &bt_cmd))
IWL_ERR(priv, "failed to send BT Coex Config\n");
}
EXPORT_SYMBOL(iwl_legacy_send_bt_config);
int iwl_legacy_send_statistics_request(struct iwl_priv *priv, u8 flags, bool clear)
{
struct iwl_statistics_cmd statistics_cmd = {
.configuration_flags =
clear ? IWL_STATS_CONF_CLEAR_STATS : 0,
};
if (flags & CMD_ASYNC)
return iwl_legacy_send_cmd_pdu_async(priv, REPLY_STATISTICS_CMD,
sizeof(struct iwl_statistics_cmd),
&statistics_cmd, NULL);
else
return iwl_legacy_send_cmd_pdu(priv, REPLY_STATISTICS_CMD,
sizeof(struct iwl_statistics_cmd),
&statistics_cmd);
}
EXPORT_SYMBOL(iwl_legacy_send_statistics_request);
void iwl_legacy_rx_pm_sleep_notif(struct iwl_priv *priv,
struct iwl_rx_mem_buffer *rxb)
{
#ifdef CONFIG_IWLWIFI_LEGACY_DEBUG
struct iwl_rx_packet *pkt = rxb_addr(rxb);
struct iwl_sleep_notification *sleep = &(pkt->u.sleep_notif);
IWL_DEBUG_RX(priv, "sleep mode: %d, src: %d\n",
sleep->pm_sleep_mode, sleep->pm_wakeup_src);
#endif
}
EXPORT_SYMBOL(iwl_legacy_rx_pm_sleep_notif);
void iwl_legacy_rx_pm_debug_statistics_notif(struct iwl_priv *priv,
struct iwl_rx_mem_buffer *rxb)
{
struct iwl_rx_packet *pkt = rxb_addr(rxb);
u32 len = le32_to_cpu(pkt->len_n_flags) & FH_RSCSR_FRAME_SIZE_MSK;
IWL_DEBUG_RADIO(priv, "Dumping %d bytes of unhandled "
"notification for %s:\n", len,
iwl_legacy_get_cmd_string(pkt->hdr.cmd));
iwl_print_hex_dump(priv, IWL_DL_RADIO, pkt->u.raw, len);
}
EXPORT_SYMBOL(iwl_legacy_rx_pm_debug_statistics_notif);
void iwl_legacy_rx_reply_error(struct iwl_priv *priv,
struct iwl_rx_mem_buffer *rxb)
{
struct iwl_rx_packet *pkt = rxb_addr(rxb);
IWL_ERR(priv, "Error Reply type 0x%08X cmd %s (0x%02X) "
"seq 0x%04X ser 0x%08X\n",
le32_to_cpu(pkt->u.err_resp.error_type),
iwl_legacy_get_cmd_string(pkt->u.err_resp.cmd_id),
pkt->u.err_resp.cmd_id,
le16_to_cpu(pkt->u.err_resp.bad_cmd_seq_num),
le32_to_cpu(pkt->u.err_resp.error_info));
}
EXPORT_SYMBOL(iwl_legacy_rx_reply_error);
void iwl_legacy_clear_isr_stats(struct iwl_priv *priv)
{
memset(&priv->isr_stats, 0, sizeof(priv->isr_stats));
}
int iwl_legacy_mac_conf_tx(struct ieee80211_hw *hw, u16 queue,
const struct ieee80211_tx_queue_params *params)
{
struct iwl_priv *priv = hw->priv;
struct iwl_rxon_context *ctx;
unsigned long flags;
int q;
IWL_DEBUG_MAC80211(priv, "enter\n");
if (!iwl_legacy_is_ready_rf(priv)) {
IWL_DEBUG_MAC80211(priv, "leave - RF not ready\n");
return -EIO;
}
if (queue >= AC_NUM) {
IWL_DEBUG_MAC80211(priv, "leave - queue >= AC_NUM %d\n", queue);
return 0;
}
q = AC_NUM - 1 - queue;
spin_lock_irqsave(&priv->lock, flags);
for_each_context(priv, ctx) {
ctx->qos_data.def_qos_parm.ac[q].cw_min =
cpu_to_le16(params->cw_min);
ctx->qos_data.def_qos_parm.ac[q].cw_max =
cpu_to_le16(params->cw_max);
ctx->qos_data.def_qos_parm.ac[q].aifsn = params->aifs;
ctx->qos_data.def_qos_parm.ac[q].edca_txop =
cpu_to_le16((params->txop * 32));
ctx->qos_data.def_qos_parm.ac[q].reserved1 = 0;
}
spin_unlock_irqrestore(&priv->lock, flags);
IWL_DEBUG_MAC80211(priv, "leave\n");
return 0;
}
EXPORT_SYMBOL(iwl_legacy_mac_conf_tx);
int iwl_legacy_mac_tx_last_beacon(struct ieee80211_hw *hw)
{
struct iwl_priv *priv = hw->priv;
return priv->ibss_manager == IWL_IBSS_MANAGER;
}
EXPORT_SYMBOL_GPL(iwl_legacy_mac_tx_last_beacon);
static int
iwl_legacy_set_mode(struct iwl_priv *priv, struct iwl_rxon_context *ctx)
{
iwl_legacy_connection_init_rx_config(priv, ctx);
if (priv->cfg->ops->hcmd->set_rxon_chain)
priv->cfg->ops->hcmd->set_rxon_chain(priv, ctx);
return iwl_legacy_commit_rxon(priv, ctx);
}
static int iwl_legacy_setup_interface(struct iwl_priv *priv,
struct iwl_rxon_context *ctx)
{
struct ieee80211_vif *vif = ctx->vif;
int err;
lockdep_assert_held(&priv->mutex);
/*
* This variable will be correct only when there's just
* a single context, but all code using it is for hardware
* that supports only one context.
*/
priv->iw_mode = vif->type;
ctx->is_active = true;
err = iwl_legacy_set_mode(priv, ctx);
if (err) {
if (!ctx->always_active)
ctx->is_active = false;
return err;
}
return 0;
}
int
iwl_legacy_mac_add_interface(struct ieee80211_hw *hw, struct ieee80211_vif *vif)
{
struct iwl_priv *priv = hw->priv;
struct iwl_vif_priv *vif_priv = (void *)vif->drv_priv;
struct iwl_rxon_context *tmp, *ctx = NULL;
int err;
IWL_DEBUG_MAC80211(priv, "enter: type %d, addr %pM\n",
vif->type, vif->addr);
mutex_lock(&priv->mutex);
if (!iwl_legacy_is_ready_rf(priv)) {
IWL_WARN(priv, "Try to add interface when device not ready\n");
err = -EINVAL;
goto out;
}
for_each_context(priv, tmp) {
u32 possible_modes =
tmp->interface_modes | tmp->exclusive_interface_modes;
if (tmp->vif) {
/* check if this busy context is exclusive */
if (tmp->exclusive_interface_modes &
BIT(tmp->vif->type)) {
err = -EINVAL;
goto out;
}
continue;
}
if (!(possible_modes & BIT(vif->type)))
continue;
/* have maybe usable context w/o interface */
ctx = tmp;
break;
}
if (!ctx) {
err = -EOPNOTSUPP;
goto out;
}
vif_priv->ctx = ctx;
ctx->vif = vif;
err = iwl_legacy_setup_interface(priv, ctx);
if (!err)
goto out;
ctx->vif = NULL;
priv->iw_mode = NL80211_IFTYPE_STATION;
out:
mutex_unlock(&priv->mutex);
IWL_DEBUG_MAC80211(priv, "leave\n");
return err;
}
EXPORT_SYMBOL(iwl_legacy_mac_add_interface);
static void iwl_legacy_teardown_interface(struct iwl_priv *priv,
struct ieee80211_vif *vif,
bool mode_change)
{
struct iwl_rxon_context *ctx = iwl_legacy_rxon_ctx_from_vif(vif);
lockdep_assert_held(&priv->mutex);
if (priv->scan_vif == vif) {
iwl_legacy_scan_cancel_timeout(priv, 200);
iwl_legacy_force_scan_end(priv);
}
if (!mode_change) {
iwl_legacy_set_mode(priv, ctx);
if (!ctx->always_active)
ctx->is_active = false;
}
}
void iwl_legacy_mac_remove_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct iwl_priv *priv = hw->priv;
struct iwl_rxon_context *ctx = iwl_legacy_rxon_ctx_from_vif(vif);
IWL_DEBUG_MAC80211(priv, "enter\n");
mutex_lock(&priv->mutex);
WARN_ON(ctx->vif != vif);
ctx->vif = NULL;
iwl_legacy_teardown_interface(priv, vif, false);
memset(priv->bssid, 0, ETH_ALEN);
mutex_unlock(&priv->mutex);
IWL_DEBUG_MAC80211(priv, "leave\n");
}
EXPORT_SYMBOL(iwl_legacy_mac_remove_interface);
int iwl_legacy_alloc_txq_mem(struct iwl_priv *priv)
{
if (!priv->txq)
priv->txq = kzalloc(
sizeof(struct iwl_tx_queue) *
priv->cfg->base_params->num_of_queues,
GFP_KERNEL);
if (!priv->txq) {
IWL_ERR(priv, "Not enough memory for txq\n");
return -ENOMEM;
}
return 0;
}
EXPORT_SYMBOL(iwl_legacy_alloc_txq_mem);
void iwl_legacy_txq_mem(struct iwl_priv *priv)
{
kfree(priv->txq);
priv->txq = NULL;
}
EXPORT_SYMBOL(iwl_legacy_txq_mem);
#ifdef CONFIG_IWLWIFI_LEGACY_DEBUGFS
#define IWL_TRAFFIC_DUMP_SIZE (IWL_TRAFFIC_ENTRY_SIZE * IWL_TRAFFIC_ENTRIES)
void iwl_legacy_reset_traffic_log(struct iwl_priv *priv)
{
priv->tx_traffic_idx = 0;
priv->rx_traffic_idx = 0;
if (priv->tx_traffic)
memset(priv->tx_traffic, 0, IWL_TRAFFIC_DUMP_SIZE);
if (priv->rx_traffic)
memset(priv->rx_traffic, 0, IWL_TRAFFIC_DUMP_SIZE);
}
int iwl_legacy_alloc_traffic_mem(struct iwl_priv *priv)
{
u32 traffic_size = IWL_TRAFFIC_DUMP_SIZE;
if (iwlegacy_debug_level & IWL_DL_TX) {
if (!priv->tx_traffic) {
priv->tx_traffic =
kzalloc(traffic_size, GFP_KERNEL);
if (!priv->tx_traffic)
return -ENOMEM;
}
}
if (iwlegacy_debug_level & IWL_DL_RX) {
if (!priv->rx_traffic) {
priv->rx_traffic =
kzalloc(traffic_size, GFP_KERNEL);
if (!priv->rx_traffic)
return -ENOMEM;
}
}
iwl_legacy_reset_traffic_log(priv);
return 0;
}
EXPORT_SYMBOL(iwl_legacy_alloc_traffic_mem);
void iwl_legacy_free_traffic_mem(struct iwl_priv *priv)
{
kfree(priv->tx_traffic);
priv->tx_traffic = NULL;
kfree(priv->rx_traffic);
priv->rx_traffic = NULL;
}
EXPORT_SYMBOL(iwl_legacy_free_traffic_mem);
void iwl_legacy_dbg_log_tx_data_frame(struct iwl_priv *priv,
u16 length, struct ieee80211_hdr *header)
{
__le16 fc;
u16 len;
if (likely(!(iwlegacy_debug_level & IWL_DL_TX)))
return;
if (!priv->tx_traffic)
return;
fc = header->frame_control;
if (ieee80211_is_data(fc)) {
len = (length > IWL_TRAFFIC_ENTRY_SIZE)
? IWL_TRAFFIC_ENTRY_SIZE : length;
memcpy((priv->tx_traffic +
(priv->tx_traffic_idx * IWL_TRAFFIC_ENTRY_SIZE)),
header, len);
priv->tx_traffic_idx =
(priv->tx_traffic_idx + 1) % IWL_TRAFFIC_ENTRIES;
}
}
EXPORT_SYMBOL(iwl_legacy_dbg_log_tx_data_frame);
void iwl_legacy_dbg_log_rx_data_frame(struct iwl_priv *priv,
u16 length, struct ieee80211_hdr *header)
{
__le16 fc;
u16 len;
if (likely(!(iwlegacy_debug_level & IWL_DL_RX)))
return;
if (!priv->rx_traffic)
return;
fc = header->frame_control;
if (ieee80211_is_data(fc)) {
len = (length > IWL_TRAFFIC_ENTRY_SIZE)
? IWL_TRAFFIC_ENTRY_SIZE : length;
memcpy((priv->rx_traffic +
(priv->rx_traffic_idx * IWL_TRAFFIC_ENTRY_SIZE)),
header, len);
priv->rx_traffic_idx =
(priv->rx_traffic_idx + 1) % IWL_TRAFFIC_ENTRIES;
}
}
EXPORT_SYMBOL(iwl_legacy_dbg_log_rx_data_frame);
const char *iwl_legacy_get_mgmt_string(int cmd)
{
switch (cmd) {
IWL_CMD(MANAGEMENT_ASSOC_REQ);
IWL_CMD(MANAGEMENT_ASSOC_RESP);
IWL_CMD(MANAGEMENT_REASSOC_REQ);
IWL_CMD(MANAGEMENT_REASSOC_RESP);
IWL_CMD(MANAGEMENT_PROBE_REQ);
IWL_CMD(MANAGEMENT_PROBE_RESP);
IWL_CMD(MANAGEMENT_BEACON);
IWL_CMD(MANAGEMENT_ATIM);
IWL_CMD(MANAGEMENT_DISASSOC);
IWL_CMD(MANAGEMENT_AUTH);
IWL_CMD(MANAGEMENT_DEAUTH);
IWL_CMD(MANAGEMENT_ACTION);
default:
return "UNKNOWN";
}
}
const char *iwl_legacy_get_ctrl_string(int cmd)
{
switch (cmd) {
IWL_CMD(CONTROL_BACK_REQ);
IWL_CMD(CONTROL_BACK);
IWL_CMD(CONTROL_PSPOLL);
IWL_CMD(CONTROL_RTS);
IWL_CMD(CONTROL_CTS);
IWL_CMD(CONTROL_ACK);
IWL_CMD(CONTROL_CFEND);
IWL_CMD(CONTROL_CFENDACK);
default:
return "UNKNOWN";
}
}
void iwl_legacy_clear_traffic_stats(struct iwl_priv *priv)
{
memset(&priv->tx_stats, 0, sizeof(struct traffic_stats));
memset(&priv->rx_stats, 0, sizeof(struct traffic_stats));
}
/*
* if CONFIG_IWLWIFI_LEGACY_DEBUGFS defined,
* iwl_legacy_update_stats function will
* record all the MGMT, CTRL and DATA pkt for both TX and Rx pass
* Use debugFs to display the rx/rx_statistics
* if CONFIG_IWLWIFI_LEGACY_DEBUGFS not being defined, then no MGMT and CTRL
* information will be recorded, but DATA pkt still will be recorded
* for the reason of iwl_led.c need to control the led blinking based on
* number of tx and rx data.
*
*/
void
iwl_legacy_update_stats(struct iwl_priv *priv, bool is_tx, __le16 fc, u16 len)
{
struct traffic_stats *stats;
if (is_tx)
stats = &priv->tx_stats;
else
stats = &priv->rx_stats;
if (ieee80211_is_mgmt(fc)) {
switch (fc & cpu_to_le16(IEEE80211_FCTL_STYPE)) {
case cpu_to_le16(IEEE80211_STYPE_ASSOC_REQ):
stats->mgmt[MANAGEMENT_ASSOC_REQ]++;
break;
case cpu_to_le16(IEEE80211_STYPE_ASSOC_RESP):
stats->mgmt[MANAGEMENT_ASSOC_RESP]++;
break;
case cpu_to_le16(IEEE80211_STYPE_REASSOC_REQ):
stats->mgmt[MANAGEMENT_REASSOC_REQ]++;
break;
case cpu_to_le16(IEEE80211_STYPE_REASSOC_RESP):
stats->mgmt[MANAGEMENT_REASSOC_RESP]++;
break;
case cpu_to_le16(IEEE80211_STYPE_PROBE_REQ):
stats->mgmt[MANAGEMENT_PROBE_REQ]++;
break;
case cpu_to_le16(IEEE80211_STYPE_PROBE_RESP):
stats->mgmt[MANAGEMENT_PROBE_RESP]++;
break;
case cpu_to_le16(IEEE80211_STYPE_BEACON):
stats->mgmt[MANAGEMENT_BEACON]++;
break;
case cpu_to_le16(IEEE80211_STYPE_ATIM):
stats->mgmt[MANAGEMENT_ATIM]++;
break;
case cpu_to_le16(IEEE80211_STYPE_DISASSOC):
stats->mgmt[MANAGEMENT_DISASSOC]++;
break;
case cpu_to_le16(IEEE80211_STYPE_AUTH):
stats->mgmt[MANAGEMENT_AUTH]++;
break;
case cpu_to_le16(IEEE80211_STYPE_DEAUTH):
stats->mgmt[MANAGEMENT_DEAUTH]++;
break;
case cpu_to_le16(IEEE80211_STYPE_ACTION):
stats->mgmt[MANAGEMENT_ACTION]++;
break;
}
} else if (ieee80211_is_ctl(fc)) {
switch (fc & cpu_to_le16(IEEE80211_FCTL_STYPE)) {
case cpu_to_le16(IEEE80211_STYPE_BACK_REQ):
stats->ctrl[CONTROL_BACK_REQ]++;
break;
case cpu_to_le16(IEEE80211_STYPE_BACK):
stats->ctrl[CONTROL_BACK]++;
break;
case cpu_to_le16(IEEE80211_STYPE_PSPOLL):
stats->ctrl[CONTROL_PSPOLL]++;
break;
case cpu_to_le16(IEEE80211_STYPE_RTS):
stats->ctrl[CONTROL_RTS]++;
break;
case cpu_to_le16(IEEE80211_STYPE_CTS):
stats->ctrl[CONTROL_CTS]++;
break;
case cpu_to_le16(IEEE80211_STYPE_ACK):
stats->ctrl[CONTROL_ACK]++;
break;
case cpu_to_le16(IEEE80211_STYPE_CFEND):
stats->ctrl[CONTROL_CFEND]++;
break;
case cpu_to_le16(IEEE80211_STYPE_CFENDACK):
stats->ctrl[CONTROL_CFENDACK]++;
break;
}
} else {
/* data */
stats->data_cnt++;
stats->data_bytes += len;
}
}
EXPORT_SYMBOL(iwl_legacy_update_stats);
#endif
static void _iwl_legacy_force_rf_reset(struct iwl_priv *priv)
{
if (test_bit(STATUS_EXIT_PENDING, &priv->status))
return;
if (!iwl_legacy_is_any_associated(priv)) {
IWL_DEBUG_SCAN(priv, "force reset rejected: not associated\n");
return;
}
/*
* There is no easy and better way to force reset the radio,
* the only known method is switching channel which will force to
* reset and tune the radio.
* Use internal short scan (single channel) operation to should
* achieve this objective.
* Driver should reset the radio when number of consecutive missed
* beacon, or any other uCode error condition detected.
*/
IWL_DEBUG_INFO(priv, "perform radio reset.\n");
iwl_legacy_internal_short_hw_scan(priv);
}
int iwl_legacy_force_reset(struct iwl_priv *priv, int mode, bool external)
{
struct iwl_force_reset *force_reset;
if (test_bit(STATUS_EXIT_PENDING, &priv->status))
return -EINVAL;
if (mode >= IWL_MAX_FORCE_RESET) {
IWL_DEBUG_INFO(priv, "invalid reset request.\n");
return -EINVAL;
}
force_reset = &priv->force_reset[mode];
force_reset->reset_request_count++;
if (!external) {
if (force_reset->last_force_reset_jiffies &&
time_after(force_reset->last_force_reset_jiffies +
force_reset->reset_duration, jiffies)) {
IWL_DEBUG_INFO(priv, "force reset rejected\n");
force_reset->reset_reject_count++;
return -EAGAIN;
}
}
force_reset->reset_success_count++;
force_reset->last_force_reset_jiffies = jiffies;
IWL_DEBUG_INFO(priv, "perform force reset (%d)\n", mode);
switch (mode) {
case IWL_RF_RESET:
_iwl_legacy_force_rf_reset(priv);
break;
case IWL_FW_RESET:
/*
* if the request is from external(ex: debugfs),
* then always perform the request in regardless the module
* parameter setting
* if the request is from internal (uCode error or driver
* detect failure), then fw_restart module parameter
* need to be check before performing firmware reload
*/
if (!external && !priv->cfg->mod_params->restart_fw) {
IWL_DEBUG_INFO(priv, "Cancel firmware reload based on "
"module parameter setting\n");
break;
}
IWL_ERR(priv, "On demand firmware reload\n");
/* Set the FW error flag -- cleared on iwl_down */
set_bit(STATUS_FW_ERROR, &priv->status);
wake_up(&priv->wait_command_queue);
/*
* Keep the restart process from trying to send host
* commands by clearing the INIT status bit
*/
clear_bit(STATUS_READY, &priv->status);
queue_work(priv->workqueue, &priv->restart);
break;
}
return 0;
}
int
iwl_legacy_mac_change_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
enum nl80211_iftype newtype, bool newp2p)
{
struct iwl_priv *priv = hw->priv;
struct iwl_rxon_context *ctx = iwl_legacy_rxon_ctx_from_vif(vif);
struct iwl_rxon_context *tmp;
u32 interface_modes;
int err;
newtype = ieee80211_iftype_p2p(newtype, newp2p);
mutex_lock(&priv->mutex);
if (!ctx->vif || !iwl_legacy_is_ready_rf(priv)) {
/*
* Huh? But wait ... this can maybe happen when
* we're in the middle of a firmware restart!
*/
err = -EBUSY;
goto out;
}
interface_modes = ctx->interface_modes | ctx->exclusive_interface_modes;
if (!(interface_modes & BIT(newtype))) {
err = -EBUSY;
goto out;
}
if (ctx->exclusive_interface_modes & BIT(newtype)) {
for_each_context(priv, tmp) {
if (ctx == tmp)
continue;
if (!tmp->vif)
continue;
/*
* The current mode switch would be exclusive, but
* another context is active ... refuse the switch.
*/
err = -EBUSY;
goto out;
}
}
/* success */
iwl_legacy_teardown_interface(priv, vif, true);
vif->type = newtype;
vif->p2p = newp2p;
err = iwl_legacy_setup_interface(priv, ctx);
WARN_ON(err);
/*
* We've switched internally, but submitting to the
* device may have failed for some reason. Mask this
* error, because otherwise mac80211 will not switch
* (and set the interface type back) and we'll be
* out of sync with it.
*/
err = 0;
out:
mutex_unlock(&priv->mutex);
return err;
}
EXPORT_SYMBOL(iwl_legacy_mac_change_interface);
/*
* On every watchdog tick we check (latest) time stamp. If it does not
* change during timeout period and queue is not empty we reset firmware.
*/
static int iwl_legacy_check_stuck_queue(struct iwl_priv *priv, int cnt)
{
struct iwl_tx_queue *txq = &priv->txq[cnt];
struct iwl_queue *q = &txq->q;
unsigned long timeout;
int ret;
if (q->read_ptr == q->write_ptr) {
txq->time_stamp = jiffies;
return 0;
}
timeout = txq->time_stamp +
msecs_to_jiffies(priv->cfg->base_params->wd_timeout);
if (time_after(jiffies, timeout)) {
IWL_ERR(priv, "Queue %d stuck for %u ms.\n",
q->id, priv->cfg->base_params->wd_timeout);
ret = iwl_legacy_force_reset(priv, IWL_FW_RESET, false);
return (ret == -EAGAIN) ? 0 : 1;
}
return 0;
}
/*
* Making watchdog tick be a quarter of timeout assure we will
* discover the queue hung between timeout and 1.25*timeout
*/
#define IWL_WD_TICK(timeout) ((timeout) / 4)
/*
* Watchdog timer callback, we check each tx queue for stuck, if if hung
* we reset the firmware. If everything is fine just rearm the timer.
*/
void iwl_legacy_bg_watchdog(unsigned long data)
{
struct iwl_priv *priv = (struct iwl_priv *)data;
int cnt;
unsigned long timeout;
if (test_bit(STATUS_EXIT_PENDING, &priv->status))
return;
timeout = priv->cfg->base_params->wd_timeout;
if (timeout == 0)
return;
/* monitor and check for stuck cmd queue */
if (iwl_legacy_check_stuck_queue(priv, priv->cmd_queue))
return;
/* monitor and check for other stuck queues */
if (iwl_legacy_is_any_associated(priv)) {
for (cnt = 0; cnt < priv->hw_params.max_txq_num; cnt++) {
/* skip as we already checked the command queue */
if (cnt == priv->cmd_queue)
continue;
if (iwl_legacy_check_stuck_queue(priv, cnt))
return;
}
}
mod_timer(&priv->watchdog, jiffies +
msecs_to_jiffies(IWL_WD_TICK(timeout)));
}
EXPORT_SYMBOL(iwl_legacy_bg_watchdog);
void iwl_legacy_setup_watchdog(struct iwl_priv *priv)
{
unsigned int timeout = priv->cfg->base_params->wd_timeout;
if (timeout)
mod_timer(&priv->watchdog,
jiffies + msecs_to_jiffies(IWL_WD_TICK(timeout)));
else
del_timer(&priv->watchdog);
}
EXPORT_SYMBOL(iwl_legacy_setup_watchdog);
/*
* extended beacon time format
* time in usec will be changed into a 32-bit value in extended:internal format
* the extended part is the beacon counts
* the internal part is the time in usec within one beacon interval
*/
u32
iwl_legacy_usecs_to_beacons(struct iwl_priv *priv,
u32 usec, u32 beacon_interval)
{
u32 quot;
u32 rem;
u32 interval = beacon_interval * TIME_UNIT;
if (!interval || !usec)
return 0;
quot = (usec / interval) &
(iwl_legacy_beacon_time_mask_high(priv,
priv->hw_params.beacon_time_tsf_bits) >>
priv->hw_params.beacon_time_tsf_bits);
rem = (usec % interval) & iwl_legacy_beacon_time_mask_low(priv,
priv->hw_params.beacon_time_tsf_bits);
return (quot << priv->hw_params.beacon_time_tsf_bits) + rem;
}
EXPORT_SYMBOL(iwl_legacy_usecs_to_beacons);
/* base is usually what we get from ucode with each received frame,
* the same as HW timer counter counting down
*/
__le32 iwl_legacy_add_beacon_time(struct iwl_priv *priv, u32 base,
u32 addon, u32 beacon_interval)
{
u32 base_low = base & iwl_legacy_beacon_time_mask_low(priv,
priv->hw_params.beacon_time_tsf_bits);
u32 addon_low = addon & iwl_legacy_beacon_time_mask_low(priv,
priv->hw_params.beacon_time_tsf_bits);
u32 interval = beacon_interval * TIME_UNIT;
u32 res = (base & iwl_legacy_beacon_time_mask_high(priv,
priv->hw_params.beacon_time_tsf_bits)) +
(addon & iwl_legacy_beacon_time_mask_high(priv,
priv->hw_params.beacon_time_tsf_bits));
if (base_low > addon_low)
res += base_low - addon_low;
else if (base_low < addon_low) {
res += interval + base_low - addon_low;
res += (1 << priv->hw_params.beacon_time_tsf_bits);
} else
res += (1 << priv->hw_params.beacon_time_tsf_bits);
return cpu_to_le32(res);
}
EXPORT_SYMBOL(iwl_legacy_add_beacon_time);
#ifdef CONFIG_PM
int iwl_legacy_pci_suspend(struct device *device)
{
struct pci_dev *pdev = to_pci_dev(device);
struct iwl_priv *priv = pci_get_drvdata(pdev);
/*
* This function is called when system goes into suspend state
* mac80211 will call iwl_mac_stop() from the mac80211 suspend function
* first but since iwl_mac_stop() has no knowledge of who the caller is,
* it will not call apm_ops.stop() to stop the DMA operation.
* Calling apm_ops.stop here to make sure we stop the DMA.
*/
iwl_legacy_apm_stop(priv);
return 0;
}
EXPORT_SYMBOL(iwl_legacy_pci_suspend);
int iwl_legacy_pci_resume(struct device *device)
{
struct pci_dev *pdev = to_pci_dev(device);
struct iwl_priv *priv = pci_get_drvdata(pdev);
bool hw_rfkill = false;
/*
* We disable the RETRY_TIMEOUT register (0x41) to keep
* PCI Tx retries from interfering with C3 CPU state.
*/
pci_write_config_byte(pdev, PCI_CFG_RETRY_TIMEOUT, 0x00);
iwl_legacy_enable_interrupts(priv);
if (!(iwl_read32(priv, CSR_GP_CNTRL) &
CSR_GP_CNTRL_REG_FLAG_HW_RF_KILL_SW))
hw_rfkill = true;
if (hw_rfkill)
set_bit(STATUS_RF_KILL_HW, &priv->status);
else
clear_bit(STATUS_RF_KILL_HW, &priv->status);
wiphy_rfkill_set_hw_state(priv->hw->wiphy, hw_rfkill);
return 0;
}
EXPORT_SYMBOL(iwl_legacy_pci_resume);
const struct dev_pm_ops iwl_legacy_pm_ops = {
.suspend = iwl_legacy_pci_suspend,
.resume = iwl_legacy_pci_resume,
.freeze = iwl_legacy_pci_suspend,
.thaw = iwl_legacy_pci_resume,
.poweroff = iwl_legacy_pci_suspend,
.restore = iwl_legacy_pci_resume,
};
EXPORT_SYMBOL(iwl_legacy_pm_ops);
#endif /* CONFIG_PM */
static void
iwl_legacy_update_qos(struct iwl_priv *priv, struct iwl_rxon_context *ctx)
{
if (test_bit(STATUS_EXIT_PENDING, &priv->status))
return;
if (!ctx->is_active)
return;
ctx->qos_data.def_qos_parm.qos_flags = 0;
if (ctx->qos_data.qos_active)
ctx->qos_data.def_qos_parm.qos_flags |=
QOS_PARAM_FLG_UPDATE_EDCA_MSK;
if (ctx->ht.enabled)
ctx->qos_data.def_qos_parm.qos_flags |= QOS_PARAM_FLG_TGN_MSK;
IWL_DEBUG_QOS(priv, "send QoS cmd with Qos active=%d FLAGS=0x%X\n",
ctx->qos_data.qos_active,
ctx->qos_data.def_qos_parm.qos_flags);
iwl_legacy_send_cmd_pdu_async(priv, ctx->qos_cmd,
sizeof(struct iwl_qosparam_cmd),
&ctx->qos_data.def_qos_parm, NULL);
}
/**
* iwl_legacy_mac_config - mac80211 config callback
*/
int iwl_legacy_mac_config(struct ieee80211_hw *hw, u32 changed)
{
struct iwl_priv *priv = hw->priv;
const struct iwl_channel_info *ch_info;
struct ieee80211_conf *conf = &hw->conf;
struct ieee80211_channel *channel = conf->channel;
struct iwl_ht_config *ht_conf = &priv->current_ht_config;
struct iwl_rxon_context *ctx;
unsigned long flags = 0;
int ret = 0;
u16 ch;
int scan_active = 0;
bool ht_changed[NUM_IWL_RXON_CTX] = {};
if (WARN_ON(!priv->cfg->ops->legacy))
return -EOPNOTSUPP;
mutex_lock(&priv->mutex);
IWL_DEBUG_MAC80211(priv, "enter to channel %d changed 0x%X\n",
channel->hw_value, changed);
if (unlikely(test_bit(STATUS_SCANNING, &priv->status))) {
scan_active = 1;
IWL_DEBUG_MAC80211(priv, "scan active\n");
}
if (changed & (IEEE80211_CONF_CHANGE_SMPS |
IEEE80211_CONF_CHANGE_CHANNEL)) {
/* mac80211 uses static for non-HT which is what we want */
priv->current_ht_config.smps = conf->smps_mode;
/*
* Recalculate chain counts.
*
* If monitor mode is enabled then mac80211 will
* set up the SM PS mode to OFF if an HT channel is
* configured.
*/
if (priv->cfg->ops->hcmd->set_rxon_chain)
for_each_context(priv, ctx)
priv->cfg->ops->hcmd->set_rxon_chain(priv, ctx);
}
/* during scanning mac80211 will delay channel setting until
* scan finish with changed = 0
*/
if (!changed || (changed & IEEE80211_CONF_CHANGE_CHANNEL)) {
if (scan_active)
goto set_ch_out;
ch = channel->hw_value;
ch_info = iwl_legacy_get_channel_info(priv, channel->band, ch);
if (!iwl_legacy_is_channel_valid(ch_info)) {
IWL_DEBUG_MAC80211(priv, "leave - invalid channel\n");
ret = -EINVAL;
goto set_ch_out;
}
if (priv->iw_mode == NL80211_IFTYPE_ADHOC &&
!iwl_legacy_is_channel_ibss(ch_info)) {
IWL_DEBUG_MAC80211(priv, "leave - not IBSS channel\n");
ret = -EINVAL;
goto set_ch_out;
}
spin_lock_irqsave(&priv->lock, flags);
for_each_context(priv, ctx) {
/* Configure HT40 channels */
if (ctx->ht.enabled != conf_is_ht(conf)) {
ctx->ht.enabled = conf_is_ht(conf);
ht_changed[ctx->ctxid] = true;
}
if (ctx->ht.enabled) {
if (conf_is_ht40_minus(conf)) {
ctx->ht.extension_chan_offset =
IEEE80211_HT_PARAM_CHA_SEC_BELOW;
ctx->ht.is_40mhz = true;
} else if (conf_is_ht40_plus(conf)) {
ctx->ht.extension_chan_offset =
IEEE80211_HT_PARAM_CHA_SEC_ABOVE;
ctx->ht.is_40mhz = true;
} else {
ctx->ht.extension_chan_offset =
IEEE80211_HT_PARAM_CHA_SEC_NONE;
ctx->ht.is_40mhz = false;
}
} else
ctx->ht.is_40mhz = false;
/*
* Default to no protection. Protection mode will
* later be set from BSS config in iwl_ht_conf
*/
ctx->ht.protection =
IEEE80211_HT_OP_MODE_PROTECTION_NONE;
/* if we are switching from ht to 2.4 clear flags
* from any ht related info since 2.4 does not
* support ht */
if ((le16_to_cpu(ctx->staging.channel) != ch))
ctx->staging.flags = 0;
iwl_legacy_set_rxon_channel(priv, channel, ctx);
iwl_legacy_set_rxon_ht(priv, ht_conf);
iwl_legacy_set_flags_for_band(priv, ctx, channel->band,
ctx->vif);
}
spin_unlock_irqrestore(&priv->lock, flags);
if (priv->cfg->ops->legacy->update_bcast_stations)
ret =
priv->cfg->ops->legacy->update_bcast_stations(priv);
set_ch_out:
/* The list of supported rates and rate mask can be different
* for each band; since the band may have changed, reset
* the rate mask to what mac80211 lists */
iwl_legacy_set_rate(priv);
}
if (changed & (IEEE80211_CONF_CHANGE_PS |
IEEE80211_CONF_CHANGE_IDLE)) {
ret = iwl_legacy_power_update_mode(priv, false);
if (ret)
IWL_DEBUG_MAC80211(priv, "Error setting sleep level\n");
}
if (changed & IEEE80211_CONF_CHANGE_POWER) {
IWL_DEBUG_MAC80211(priv, "TX Power old=%d new=%d\n",
priv->tx_power_user_lmt, conf->power_level);
iwl_legacy_set_tx_power(priv, conf->power_level, false);
}
if (!iwl_legacy_is_ready(priv)) {
IWL_DEBUG_MAC80211(priv, "leave - not ready\n");
goto out;
}
if (scan_active)
goto out;
for_each_context(priv, ctx) {
if (memcmp(&ctx->active, &ctx->staging, sizeof(ctx->staging)))
iwl_legacy_commit_rxon(priv, ctx);
else
IWL_DEBUG_INFO(priv,
"Not re-sending same RXON configuration.\n");
if (ht_changed[ctx->ctxid])
iwl_legacy_update_qos(priv, ctx);
}
out:
IWL_DEBUG_MAC80211(priv, "leave\n");
mutex_unlock(&priv->mutex);
return ret;
}
EXPORT_SYMBOL(iwl_legacy_mac_config);
void iwl_legacy_mac_reset_tsf(struct ieee80211_hw *hw)
{
struct iwl_priv *priv = hw->priv;
unsigned long flags;
/* IBSS can only be the IWL_RXON_CTX_BSS context */
struct iwl_rxon_context *ctx = &priv->contexts[IWL_RXON_CTX_BSS];
if (WARN_ON(!priv->cfg->ops->legacy))
return;
mutex_lock(&priv->mutex);
IWL_DEBUG_MAC80211(priv, "enter\n");
spin_lock_irqsave(&priv->lock, flags);
memset(&priv->current_ht_config, 0, sizeof(struct iwl_ht_config));
spin_unlock_irqrestore(&priv->lock, flags);
spin_lock_irqsave(&priv->lock, flags);
/* new association get rid of ibss beacon skb */
if (priv->beacon_skb)
dev_kfree_skb(priv->beacon_skb);
priv->beacon_skb = NULL;
priv->timestamp = 0;
spin_unlock_irqrestore(&priv->lock, flags);
iwl_legacy_scan_cancel_timeout(priv, 100);
if (!iwl_legacy_is_ready_rf(priv)) {
IWL_DEBUG_MAC80211(priv, "leave - not ready\n");
mutex_unlock(&priv->mutex);
return;
}
/* we are restarting association process
* clear RXON_FILTER_ASSOC_MSK bit
*/
ctx->staging.filter_flags &= ~RXON_FILTER_ASSOC_MSK;
iwl_legacy_commit_rxon(priv, ctx);
iwl_legacy_set_rate(priv);
mutex_unlock(&priv->mutex);
IWL_DEBUG_MAC80211(priv, "leave\n");
}
EXPORT_SYMBOL(iwl_legacy_mac_reset_tsf);
static void iwl_legacy_ht_conf(struct iwl_priv *priv,
struct ieee80211_vif *vif)
{
struct iwl_ht_config *ht_conf = &priv->current_ht_config;
struct ieee80211_sta *sta;
struct ieee80211_bss_conf *bss_conf = &vif->bss_conf;
struct iwl_rxon_context *ctx = iwl_legacy_rxon_ctx_from_vif(vif);
IWL_DEBUG_ASSOC(priv, "enter:\n");
if (!ctx->ht.enabled)
return;
ctx->ht.protection =
bss_conf->ht_operation_mode & IEEE80211_HT_OP_MODE_PROTECTION;
ctx->ht.non_gf_sta_present =
!!(bss_conf->ht_operation_mode &
IEEE80211_HT_OP_MODE_NON_GF_STA_PRSNT);
ht_conf->single_chain_sufficient = false;
switch (vif->type) {
case NL80211_IFTYPE_STATION:
rcu_read_lock();
sta = ieee80211_find_sta(vif, bss_conf->bssid);
if (sta) {
struct ieee80211_sta_ht_cap *ht_cap = &sta->ht_cap;
int maxstreams;
maxstreams = (ht_cap->mcs.tx_params &
IEEE80211_HT_MCS_TX_MAX_STREAMS_MASK)
>> IEEE80211_HT_MCS_TX_MAX_STREAMS_SHIFT;
maxstreams += 1;
if ((ht_cap->mcs.rx_mask[1] == 0) &&
(ht_cap->mcs.rx_mask[2] == 0))
ht_conf->single_chain_sufficient = true;
if (maxstreams <= 1)
ht_conf->single_chain_sufficient = true;
} else {
/*
* If at all, this can only happen through a race
* when the AP disconnects us while we're still
* setting up the connection, in that case mac80211
* will soon tell us about that.
*/
ht_conf->single_chain_sufficient = true;
}
rcu_read_unlock();
break;
case NL80211_IFTYPE_ADHOC:
ht_conf->single_chain_sufficient = true;
break;
default:
break;
}
IWL_DEBUG_ASSOC(priv, "leave\n");
}
static inline void iwl_legacy_set_no_assoc(struct iwl_priv *priv,
struct ieee80211_vif *vif)
{
struct iwl_rxon_context *ctx = iwl_legacy_rxon_ctx_from_vif(vif);
/*
* inform the ucode that there is no longer an
* association and that no more packets should be
* sent
*/
ctx->staging.filter_flags &= ~RXON_FILTER_ASSOC_MSK;
ctx->staging.assoc_id = 0;
iwl_legacy_commit_rxon(priv, ctx);
}
static void iwl_legacy_beacon_update(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct iwl_priv *priv = hw->priv;
unsigned long flags;
__le64 timestamp;
struct sk_buff *skb = ieee80211_beacon_get(hw, vif);
if (!skb)
return;
IWL_DEBUG_MAC80211(priv, "enter\n");
lockdep_assert_held(&priv->mutex);
if (!priv->beacon_ctx) {
IWL_ERR(priv, "update beacon but no beacon context!\n");
dev_kfree_skb(skb);
return;
}
spin_lock_irqsave(&priv->lock, flags);
if (priv->beacon_skb)
dev_kfree_skb(priv->beacon_skb);
priv->beacon_skb = skb;
timestamp = ((struct ieee80211_mgmt *)skb->data)->u.beacon.timestamp;
priv->timestamp = le64_to_cpu(timestamp);
IWL_DEBUG_MAC80211(priv, "leave\n");
spin_unlock_irqrestore(&priv->lock, flags);
if (!iwl_legacy_is_ready_rf(priv)) {
IWL_DEBUG_MAC80211(priv, "leave - RF not ready\n");
return;
}
priv->cfg->ops->legacy->post_associate(priv);
}
void iwl_legacy_mac_bss_info_changed(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_bss_conf *bss_conf,
u32 changes)
{
struct iwl_priv *priv = hw->priv;
struct iwl_rxon_context *ctx = iwl_legacy_rxon_ctx_from_vif(vif);
int ret;
if (WARN_ON(!priv->cfg->ops->legacy))
return;
IWL_DEBUG_MAC80211(priv, "changes = 0x%X\n", changes);
mutex_lock(&priv->mutex);
if (!iwl_legacy_is_alive(priv)) {
mutex_unlock(&priv->mutex);
return;
}
if (changes & BSS_CHANGED_QOS) {
unsigned long flags;
spin_lock_irqsave(&priv->lock, flags);
ctx->qos_data.qos_active = bss_conf->qos;
iwl_legacy_update_qos(priv, ctx);
spin_unlock_irqrestore(&priv->lock, flags);
}
if (changes & BSS_CHANGED_BEACON_ENABLED) {
/*
* the add_interface code must make sure we only ever
* have a single interface that could be beaconing at
* any time.
*/
if (vif->bss_conf.enable_beacon)
priv->beacon_ctx = ctx;
else
priv->beacon_ctx = NULL;
}
if (changes & BSS_CHANGED_BSSID) {
IWL_DEBUG_MAC80211(priv, "BSSID %pM\n", bss_conf->bssid);
/*
* If there is currently a HW scan going on in the
* background then we need to cancel it else the RXON
* below/in post_associate will fail.
*/
if (iwl_legacy_scan_cancel_timeout(priv, 100)) {
IWL_WARN(priv,
"Aborted scan still in progress after 100ms\n");
IWL_DEBUG_MAC80211(priv,
"leaving - scan abort failed.\n");
mutex_unlock(&priv->mutex);
return;
}
/* mac80211 only sets assoc when in STATION mode */
if (vif->type == NL80211_IFTYPE_ADHOC || bss_conf->assoc) {
memcpy(ctx->staging.bssid_addr,
bss_conf->bssid, ETH_ALEN);
/* currently needed in a few places */
memcpy(priv->bssid, bss_conf->bssid, ETH_ALEN);
} else {
ctx->staging.filter_flags &=
~RXON_FILTER_ASSOC_MSK;
}
}
/*
* This needs to be after setting the BSSID in case
* mac80211 decides to do both changes at once because
* it will invoke post_associate.
*/
if (vif->type == NL80211_IFTYPE_ADHOC && changes & BSS_CHANGED_BEACON)
iwl_legacy_beacon_update(hw, vif);
if (changes & BSS_CHANGED_ERP_PREAMBLE) {
IWL_DEBUG_MAC80211(priv, "ERP_PREAMBLE %d\n",
bss_conf->use_short_preamble);
if (bss_conf->use_short_preamble)
ctx->staging.flags |= RXON_FLG_SHORT_PREAMBLE_MSK;
else
ctx->staging.flags &= ~RXON_FLG_SHORT_PREAMBLE_MSK;
}
if (changes & BSS_CHANGED_ERP_CTS_PROT) {
IWL_DEBUG_MAC80211(priv,
"ERP_CTS %d\n", bss_conf->use_cts_prot);
if (bss_conf->use_cts_prot &&
(priv->band != IEEE80211_BAND_5GHZ))
ctx->staging.flags |= RXON_FLG_TGG_PROTECT_MSK;
else
ctx->staging.flags &= ~RXON_FLG_TGG_PROTECT_MSK;
if (bss_conf->use_cts_prot)
ctx->staging.flags |= RXON_FLG_SELF_CTS_EN;
else
ctx->staging.flags &= ~RXON_FLG_SELF_CTS_EN;
}
if (changes & BSS_CHANGED_BASIC_RATES) {
/* XXX use this information
*
* To do that, remove code from iwl_legacy_set_rate() and put something
* like this here:
*
if (A-band)
ctx->staging.ofdm_basic_rates =
bss_conf->basic_rates;
else
ctx->staging.ofdm_basic_rates =
bss_conf->basic_rates >> 4;
ctx->staging.cck_basic_rates =
bss_conf->basic_rates & 0xF;
*/
}
if (changes & BSS_CHANGED_HT) {
iwl_legacy_ht_conf(priv, vif);
if (priv->cfg->ops->hcmd->set_rxon_chain)
priv->cfg->ops->hcmd->set_rxon_chain(priv, ctx);
}
if (changes & BSS_CHANGED_ASSOC) {
IWL_DEBUG_MAC80211(priv, "ASSOC %d\n", bss_conf->assoc);
if (bss_conf->assoc) {
priv->timestamp = bss_conf->timestamp;
if (!iwl_legacy_is_rfkill(priv))
priv->cfg->ops->legacy->post_associate(priv);
} else
iwl_legacy_set_no_assoc(priv, vif);
}
if (changes && iwl_legacy_is_associated_ctx(ctx) && bss_conf->aid) {
IWL_DEBUG_MAC80211(priv, "Changes (%#x) while associated\n",
changes);
ret = iwl_legacy_send_rxon_assoc(priv, ctx);
if (!ret) {
/* Sync active_rxon with latest change. */
memcpy((void *)&ctx->active,
&ctx->staging,
sizeof(struct iwl_legacy_rxon_cmd));
}
}
if (changes & BSS_CHANGED_BEACON_ENABLED) {
if (vif->bss_conf.enable_beacon) {
memcpy(ctx->staging.bssid_addr,
bss_conf->bssid, ETH_ALEN);
memcpy(priv->bssid, bss_conf->bssid, ETH_ALEN);
priv->cfg->ops->legacy->config_ap(priv);
} else
iwl_legacy_set_no_assoc(priv, vif);
}
if (changes & BSS_CHANGED_IBSS) {
ret = priv->cfg->ops->legacy->manage_ibss_station(priv, vif,
bss_conf->ibss_joined);
if (ret)
IWL_ERR(priv, "failed to %s IBSS station %pM\n",
bss_conf->ibss_joined ? "add" : "remove",
bss_conf->bssid);
}
mutex_unlock(&priv->mutex);
IWL_DEBUG_MAC80211(priv, "leave\n");
}
EXPORT_SYMBOL(iwl_legacy_mac_bss_info_changed);
irqreturn_t iwl_legacy_isr(int irq, void *data)
{
struct iwl_priv *priv = data;
u32 inta, inta_mask;
u32 inta_fh;
unsigned long flags;
if (!priv)
return IRQ_NONE;
spin_lock_irqsave(&priv->lock, flags);
/* Disable (but don't clear!) interrupts here to avoid
* back-to-back ISRs and sporadic interrupts from our NIC.
* If we have something to service, the tasklet will re-enable ints.
* If we *don't* have something, we'll re-enable before leaving here. */
inta_mask = iwl_read32(priv, CSR_INT_MASK); /* just for debug */
iwl_write32(priv, CSR_INT_MASK, 0x00000000);
/* Discover which interrupts are active/pending */
inta = iwl_read32(priv, CSR_INT);
inta_fh = iwl_read32(priv, CSR_FH_INT_STATUS);
/* Ignore interrupt if there's nothing in NIC to service.
* This may be due to IRQ shared with another device,
* or due to sporadic interrupts thrown from our NIC. */
if (!inta && !inta_fh) {
IWL_DEBUG_ISR(priv,
"Ignore interrupt, inta == 0, inta_fh == 0\n");
goto none;
}
if ((inta == 0xFFFFFFFF) || ((inta & 0xFFFFFFF0) == 0xa5a5a5a0)) {
/* Hardware disappeared. It might have already raised
* an interrupt */
IWL_WARN(priv, "HARDWARE GONE?? INTA == 0x%08x\n", inta);
goto unplugged;
}
IWL_DEBUG_ISR(priv, "ISR inta 0x%08x, enabled 0x%08x, fh 0x%08x\n",
inta, inta_mask, inta_fh);
inta &= ~CSR_INT_BIT_SCD;
/* iwl_irq_tasklet() will service interrupts and re-enable them */
if (likely(inta || inta_fh))
tasklet_schedule(&priv->irq_tasklet);
unplugged:
spin_unlock_irqrestore(&priv->lock, flags);
return IRQ_HANDLED;
none:
/* re-enable interrupts here since we don't have anything to service. */
/* only Re-enable if disabled by irq */
if (test_bit(STATUS_INT_ENABLED, &priv->status))
iwl_legacy_enable_interrupts(priv);
spin_unlock_irqrestore(&priv->lock, flags);
return IRQ_NONE;
}
EXPORT_SYMBOL(iwl_legacy_isr);
/*
* iwl_legacy_tx_cmd_protection: Set rts/cts. 3945 and 4965 only share this
* function.
*/
void iwl_legacy_tx_cmd_protection(struct iwl_priv *priv,
struct ieee80211_tx_info *info,
__le16 fc, __le32 *tx_flags)
{
if (info->control.rates[0].flags & IEEE80211_TX_RC_USE_RTS_CTS) {
*tx_flags |= TX_CMD_FLG_RTS_MSK;
*tx_flags &= ~TX_CMD_FLG_CTS_MSK;
*tx_flags |= TX_CMD_FLG_FULL_TXOP_PROT_MSK;
if (!ieee80211_is_mgmt(fc))
return;
switch (fc & cpu_to_le16(IEEE80211_FCTL_STYPE)) {
case cpu_to_le16(IEEE80211_STYPE_AUTH):
case cpu_to_le16(IEEE80211_STYPE_DEAUTH):
case cpu_to_le16(IEEE80211_STYPE_ASSOC_REQ):
case cpu_to_le16(IEEE80211_STYPE_REASSOC_REQ):
*tx_flags &= ~TX_CMD_FLG_RTS_MSK;
*tx_flags |= TX_CMD_FLG_CTS_MSK;
break;
}
} else if (info->control.rates[0].flags &
IEEE80211_TX_RC_USE_CTS_PROTECT) {
*tx_flags &= ~TX_CMD_FLG_RTS_MSK;
*tx_flags |= TX_CMD_FLG_CTS_MSK;
*tx_flags |= TX_CMD_FLG_FULL_TXOP_PROT_MSK;
}
}
EXPORT_SYMBOL(iwl_legacy_tx_cmd_protection);
| gpl-2.0 |
JoeGlancy/linux | arch/tile/lib/memcpy_64.c | 2358 | 8600 | /*
* Copyright 2011 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/types.h>
#include <linux/string.h>
#include <linux/module.h>
/* EXPORT_SYMBOL() is in arch/tile/lib/exports.c since this should be asm. */
/* Must be 8 bytes in size. */
#define op_t uint64_t
/* Threshold value for when to enter the unrolled loops. */
#define OP_T_THRES 16
#if CHIP_L2_LINE_SIZE() != 64
#error "Assumes 64 byte line size"
#endif
/* How many cache lines ahead should we prefetch? */
#define PREFETCH_LINES_AHEAD 4
/*
* Provide "base versions" of load and store for the normal code path.
* The kernel provides other versions for userspace copies.
*/
#define ST(p, v) (*(p) = (v))
#define LD(p) (*(p))
#ifndef USERCOPY_FUNC
#define ST1 ST
#define ST2 ST
#define ST4 ST
#define ST8 ST
#define LD1 LD
#define LD2 LD
#define LD4 LD
#define LD8 LD
#define RETVAL dstv
void *memcpy(void *__restrict dstv, const void *__restrict srcv, size_t n)
#else
/*
* Special kernel version will provide implementation of the LDn/STn
* macros to return a count of uncopied bytes due to mm fault.
*/
#define RETVAL 0
int __attribute__((optimize("omit-frame-pointer")))
USERCOPY_FUNC(void *__restrict dstv, const void *__restrict srcv, size_t n)
#endif
{
char *__restrict dst1 = (char *)dstv;
const char *__restrict src1 = (const char *)srcv;
const char *__restrict src1_end;
const char *__restrict prefetch;
op_t *__restrict dst8; /* 8-byte pointer to destination memory. */
op_t final; /* Final bytes to write to trailing word, if any */
long i;
if (n < 16) {
for (; n; n--)
ST1(dst1++, LD1(src1++));
return RETVAL;
}
/*
* Locate the end of source memory we will copy. Don't
* prefetch past this.
*/
src1_end = src1 + n - 1;
/* Prefetch ahead a few cache lines, but not past the end. */
prefetch = src1;
for (i = 0; i < PREFETCH_LINES_AHEAD; i++) {
__insn_prefetch(prefetch);
prefetch += CHIP_L2_LINE_SIZE();
prefetch = (prefetch < src1_end) ? prefetch : src1;
}
/* Copy bytes until dst is word-aligned. */
for (; (uintptr_t)dst1 & (sizeof(op_t) - 1); n--)
ST1(dst1++, LD1(src1++));
/* 8-byte pointer to destination memory. */
dst8 = (op_t *)dst1;
if (__builtin_expect((uintptr_t)src1 & (sizeof(op_t) - 1), 0)) {
/* Unaligned copy. */
op_t tmp0 = 0, tmp1 = 0, tmp2, tmp3;
const op_t *src8 = (const op_t *) ((uintptr_t)src1 &
-sizeof(op_t));
const void *srci = (void *)src1;
int m;
m = (CHIP_L2_LINE_SIZE() << 2) -
(((uintptr_t)dst8) & ((CHIP_L2_LINE_SIZE() << 2) - 1));
m = (n < m) ? n : m;
m /= sizeof(op_t);
/* Copy until 'dst' is cache-line-aligned. */
n -= (sizeof(op_t) * m);
switch (m % 4) {
case 0:
if (__builtin_expect(!m, 0))
goto _M0;
tmp1 = LD8(src8++);
tmp2 = LD8(src8++);
goto _8B3;
case 2:
m += 2;
tmp3 = LD8(src8++);
tmp0 = LD8(src8++);
goto _8B1;
case 3:
m += 1;
tmp2 = LD8(src8++);
tmp3 = LD8(src8++);
goto _8B2;
case 1:
m--;
tmp0 = LD8(src8++);
tmp1 = LD8(src8++);
if (__builtin_expect(!m, 0))
goto _8B0;
}
do {
tmp2 = LD8(src8++);
tmp0 = __insn_dblalign(tmp0, tmp1, srci);
ST8(dst8++, tmp0);
_8B3:
tmp3 = LD8(src8++);
tmp1 = __insn_dblalign(tmp1, tmp2, srci);
ST8(dst8++, tmp1);
_8B2:
tmp0 = LD8(src8++);
tmp2 = __insn_dblalign(tmp2, tmp3, srci);
ST8(dst8++, tmp2);
_8B1:
tmp1 = LD8(src8++);
tmp3 = __insn_dblalign(tmp3, tmp0, srci);
ST8(dst8++, tmp3);
m -= 4;
} while (m);
_8B0:
tmp0 = __insn_dblalign(tmp0, tmp1, srci);
ST8(dst8++, tmp0);
src8--;
_M0:
if (__builtin_expect(n >= CHIP_L2_LINE_SIZE(), 0)) {
op_t tmp4, tmp5, tmp6, tmp7, tmp8;
prefetch = ((const char *)src8) +
CHIP_L2_LINE_SIZE() * PREFETCH_LINES_AHEAD;
for (tmp0 = LD8(src8++); n >= CHIP_L2_LINE_SIZE();
n -= CHIP_L2_LINE_SIZE()) {
/* Prefetch and advance to next line to
prefetch, but don't go past the end. */
__insn_prefetch(prefetch);
/* Make sure prefetch got scheduled
earlier. */
__asm__ ("" : : : "memory");
prefetch += CHIP_L2_LINE_SIZE();
prefetch = (prefetch < src1_end) ? prefetch :
(const char *) src8;
tmp1 = LD8(src8++);
tmp2 = LD8(src8++);
tmp3 = LD8(src8++);
tmp4 = LD8(src8++);
tmp5 = LD8(src8++);
tmp6 = LD8(src8++);
tmp7 = LD8(src8++);
tmp8 = LD8(src8++);
tmp0 = __insn_dblalign(tmp0, tmp1, srci);
tmp1 = __insn_dblalign(tmp1, tmp2, srci);
tmp2 = __insn_dblalign(tmp2, tmp3, srci);
tmp3 = __insn_dblalign(tmp3, tmp4, srci);
tmp4 = __insn_dblalign(tmp4, tmp5, srci);
tmp5 = __insn_dblalign(tmp5, tmp6, srci);
tmp6 = __insn_dblalign(tmp6, tmp7, srci);
tmp7 = __insn_dblalign(tmp7, tmp8, srci);
__insn_wh64(dst8);
ST8(dst8++, tmp0);
ST8(dst8++, tmp1);
ST8(dst8++, tmp2);
ST8(dst8++, tmp3);
ST8(dst8++, tmp4);
ST8(dst8++, tmp5);
ST8(dst8++, tmp6);
ST8(dst8++, tmp7);
tmp0 = tmp8;
}
src8--;
}
/* Copy the rest 8-byte chunks. */
if (n >= sizeof(op_t)) {
tmp0 = LD8(src8++);
for (; n >= sizeof(op_t); n -= sizeof(op_t)) {
tmp1 = LD8(src8++);
tmp0 = __insn_dblalign(tmp0, tmp1, srci);
ST8(dst8++, tmp0);
tmp0 = tmp1;
}
src8--;
}
if (n == 0)
return RETVAL;
tmp0 = LD8(src8++);
tmp1 = ((const char *)src8 <= src1_end)
? LD8((op_t *)src8) : 0;
final = __insn_dblalign(tmp0, tmp1, srci);
} else {
/* Aligned copy. */
const op_t *__restrict src8 = (const op_t *)src1;
/* src8 and dst8 are both word-aligned. */
if (n >= CHIP_L2_LINE_SIZE()) {
/* Copy until 'dst' is cache-line-aligned. */
for (; (uintptr_t)dst8 & (CHIP_L2_LINE_SIZE() - 1);
n -= sizeof(op_t))
ST8(dst8++, LD8(src8++));
for (; n >= CHIP_L2_LINE_SIZE(); ) {
op_t tmp0, tmp1, tmp2, tmp3;
op_t tmp4, tmp5, tmp6, tmp7;
/*
* Prefetch and advance to next line
* to prefetch, but don't go past the
* end.
*/
__insn_prefetch(prefetch);
/* Make sure prefetch got scheduled
earlier. */
__asm__ ("" : : : "memory");
prefetch += CHIP_L2_LINE_SIZE();
prefetch = (prefetch < src1_end) ? prefetch :
(const char *)src8;
/*
* Do all the loads before wh64. This
* is necessary if [src8, src8+7] and
* [dst8, dst8+7] share the same cache
* line and dst8 <= src8, as can be
* the case when called from memmove,
* or with code tested on x86 whose
* memcpy always works with forward
* copies.
*/
tmp0 = LD8(src8++);
tmp1 = LD8(src8++);
tmp2 = LD8(src8++);
tmp3 = LD8(src8++);
tmp4 = LD8(src8++);
tmp5 = LD8(src8++);
tmp6 = LD8(src8++);
tmp7 = LD8(src8++);
/* wh64 and wait for tmp7 load completion. */
__asm__ ("move %0, %0; wh64 %1\n"
: : "r"(tmp7), "r"(dst8));
ST8(dst8++, tmp0);
ST8(dst8++, tmp1);
ST8(dst8++, tmp2);
ST8(dst8++, tmp3);
ST8(dst8++, tmp4);
ST8(dst8++, tmp5);
ST8(dst8++, tmp6);
ST8(dst8++, tmp7);
n -= CHIP_L2_LINE_SIZE();
}
#if CHIP_L2_LINE_SIZE() != 64
# error "Fix code that assumes particular L2 cache line size."
#endif
}
for (; n >= sizeof(op_t); n -= sizeof(op_t))
ST8(dst8++, LD8(src8++));
if (__builtin_expect(n == 0, 1))
return RETVAL;
final = LD8(src8);
}
/* n != 0 if we get here. Write out any trailing bytes. */
dst1 = (char *)dst8;
#ifndef __BIG_ENDIAN__
if (n & 4) {
ST4((uint32_t *)dst1, final);
dst1 += 4;
final >>= 32;
n &= 3;
}
if (n & 2) {
ST2((uint16_t *)dst1, final);
dst1 += 2;
final >>= 16;
n &= 1;
}
if (n)
ST1((uint8_t *)dst1, final);
#else
if (n & 4) {
ST4((uint32_t *)dst1, final >> 32);
dst1 += 4;
}
else
{
final >>= 32;
}
if (n & 2) {
ST2((uint16_t *)dst1, final >> 16);
dst1 += 2;
}
else
{
final >>= 16;
}
if (n & 1)
ST1((uint8_t *)dst1, final >> 8);
#endif
return RETVAL;
}
#ifdef USERCOPY_FUNC
#undef ST1
#undef ST2
#undef ST4
#undef ST8
#undef LD1
#undef LD2
#undef LD4
#undef LD8
#undef USERCOPY_FUNC
#endif
| gpl-2.0 |
walter79/android_kernel_sony_tsubasa | block/blk-ioc.c | 4150 | 11872 | /*
* Functions related to io context handling
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/bio.h>
#include <linux/blkdev.h>
#include <linux/bootmem.h> /* for max_pfn/max_low_pfn */
#include <linux/slab.h>
#include "blk.h"
/*
* For io context allocations
*/
static struct kmem_cache *iocontext_cachep;
/**
* get_io_context - increment reference count to io_context
* @ioc: io_context to get
*
* Increment reference count to @ioc.
*/
void get_io_context(struct io_context *ioc)
{
BUG_ON(atomic_long_read(&ioc->refcount) <= 0);
atomic_long_inc(&ioc->refcount);
}
EXPORT_SYMBOL(get_io_context);
static void icq_free_icq_rcu(struct rcu_head *head)
{
struct io_cq *icq = container_of(head, struct io_cq, __rcu_head);
kmem_cache_free(icq->__rcu_icq_cache, icq);
}
/* Exit an icq. Called with both ioc and q locked. */
static void ioc_exit_icq(struct io_cq *icq)
{
struct elevator_type *et = icq->q->elevator->type;
if (icq->flags & ICQ_EXITED)
return;
if (et->ops.elevator_exit_icq_fn)
et->ops.elevator_exit_icq_fn(icq);
icq->flags |= ICQ_EXITED;
}
/* Release an icq. Called with both ioc and q locked. */
static void ioc_destroy_icq(struct io_cq *icq)
{
struct io_context *ioc = icq->ioc;
struct request_queue *q = icq->q;
struct elevator_type *et = q->elevator->type;
lockdep_assert_held(&ioc->lock);
lockdep_assert_held(q->queue_lock);
radix_tree_delete(&ioc->icq_tree, icq->q->id);
hlist_del_init(&icq->ioc_node);
list_del_init(&icq->q_node);
/*
* Both setting lookup hint to and clearing it from @icq are done
* under queue_lock. If it's not pointing to @icq now, it never
* will. Hint assignment itself can race safely.
*/
if (rcu_dereference_raw(ioc->icq_hint) == icq)
rcu_assign_pointer(ioc->icq_hint, NULL);
ioc_exit_icq(icq);
/*
* @icq->q might have gone away by the time RCU callback runs
* making it impossible to determine icq_cache. Record it in @icq.
*/
icq->__rcu_icq_cache = et->icq_cache;
call_rcu(&icq->__rcu_head, icq_free_icq_rcu);
}
/*
* Slow path for ioc release in put_io_context(). Performs double-lock
* dancing to unlink all icq's and then frees ioc.
*/
static void ioc_release_fn(struct work_struct *work)
{
struct io_context *ioc = container_of(work, struct io_context,
release_work);
unsigned long flags;
/*
* Exiting icq may call into put_io_context() through elevator
* which will trigger lockdep warning. The ioc's are guaranteed to
* be different, use a different locking subclass here. Use
* irqsave variant as there's no spin_lock_irq_nested().
*/
spin_lock_irqsave_nested(&ioc->lock, flags, 1);
while (!hlist_empty(&ioc->icq_list)) {
struct io_cq *icq = hlist_entry(ioc->icq_list.first,
struct io_cq, ioc_node);
struct request_queue *q = icq->q;
if (spin_trylock(q->queue_lock)) {
ioc_destroy_icq(icq);
spin_unlock(q->queue_lock);
} else {
spin_unlock_irqrestore(&ioc->lock, flags);
cpu_relax();
spin_lock_irqsave_nested(&ioc->lock, flags, 1);
}
}
spin_unlock_irqrestore(&ioc->lock, flags);
kmem_cache_free(iocontext_cachep, ioc);
}
/**
* put_io_context - put a reference of io_context
* @ioc: io_context to put
*
* Decrement reference count of @ioc and release it if the count reaches
* zero.
*/
void put_io_context(struct io_context *ioc)
{
unsigned long flags;
bool free_ioc = false;
if (ioc == NULL)
return;
BUG_ON(atomic_long_read(&ioc->refcount) <= 0);
/*
* Releasing ioc requires reverse order double locking and we may
* already be holding a queue_lock. Do it asynchronously from wq.
*/
if (atomic_long_dec_and_test(&ioc->refcount)) {
spin_lock_irqsave(&ioc->lock, flags);
if (!hlist_empty(&ioc->icq_list))
schedule_work(&ioc->release_work);
else
free_ioc = true;
spin_unlock_irqrestore(&ioc->lock, flags);
}
if (free_ioc)
kmem_cache_free(iocontext_cachep, ioc);
}
EXPORT_SYMBOL(put_io_context);
/* Called by the exiting task */
void exit_io_context(struct task_struct *task)
{
struct io_context *ioc;
struct io_cq *icq;
struct hlist_node *n;
unsigned long flags;
task_lock(task);
ioc = task->io_context;
task->io_context = NULL;
task_unlock(task);
if (!atomic_dec_and_test(&ioc->nr_tasks)) {
put_io_context(ioc);
return;
}
/*
* Need ioc lock to walk icq_list and q lock to exit icq. Perform
* reverse double locking. Read comment in ioc_release_fn() for
* explanation on the nested locking annotation.
*/
retry:
spin_lock_irqsave_nested(&ioc->lock, flags, 1);
hlist_for_each_entry(icq, n, &ioc->icq_list, ioc_node) {
if (icq->flags & ICQ_EXITED)
continue;
if (spin_trylock(icq->q->queue_lock)) {
ioc_exit_icq(icq);
spin_unlock(icq->q->queue_lock);
} else {
spin_unlock_irqrestore(&ioc->lock, flags);
cpu_relax();
goto retry;
}
}
spin_unlock_irqrestore(&ioc->lock, flags);
put_io_context(ioc);
}
/**
* ioc_clear_queue - break any ioc association with the specified queue
* @q: request_queue being cleared
*
* Walk @q->icq_list and exit all io_cq's. Must be called with @q locked.
*/
void ioc_clear_queue(struct request_queue *q)
{
lockdep_assert_held(q->queue_lock);
while (!list_empty(&q->icq_list)) {
struct io_cq *icq = list_entry(q->icq_list.next,
struct io_cq, q_node);
struct io_context *ioc = icq->ioc;
spin_lock(&ioc->lock);
ioc_destroy_icq(icq);
spin_unlock(&ioc->lock);
}
}
void create_io_context_slowpath(struct task_struct *task, gfp_t gfp_flags,
int node)
{
struct io_context *ioc;
ioc = kmem_cache_alloc_node(iocontext_cachep, gfp_flags | __GFP_ZERO,
node);
if (unlikely(!ioc))
return;
/* initialize */
atomic_long_set(&ioc->refcount, 1);
atomic_set(&ioc->nr_tasks, 1);
spin_lock_init(&ioc->lock);
INIT_RADIX_TREE(&ioc->icq_tree, GFP_ATOMIC | __GFP_HIGH);
INIT_HLIST_HEAD(&ioc->icq_list);
INIT_WORK(&ioc->release_work, ioc_release_fn);
/*
* Try to install. ioc shouldn't be installed if someone else
* already did or @task, which isn't %current, is exiting. Note
* that we need to allow ioc creation on exiting %current as exit
* path may issue IOs from e.g. exit_files(). The exit path is
* responsible for not issuing IO after exit_io_context().
*/
task_lock(task);
if (!task->io_context &&
(task == current || !(task->flags & PF_EXITING)))
task->io_context = ioc;
else
kmem_cache_free(iocontext_cachep, ioc);
task_unlock(task);
}
/**
* get_task_io_context - get io_context of a task
* @task: task of interest
* @gfp_flags: allocation flags, used if allocation is necessary
* @node: allocation node, used if allocation is necessary
*
* Return io_context of @task. If it doesn't exist, it is created with
* @gfp_flags and @node. The returned io_context has its reference count
* incremented.
*
* This function always goes through task_lock() and it's better to use
* %current->io_context + get_io_context() for %current.
*/
struct io_context *get_task_io_context(struct task_struct *task,
gfp_t gfp_flags, int node)
{
struct io_context *ioc;
might_sleep_if(gfp_flags & __GFP_WAIT);
do {
task_lock(task);
ioc = task->io_context;
if (likely(ioc)) {
get_io_context(ioc);
task_unlock(task);
return ioc;
}
task_unlock(task);
} while (create_io_context(task, gfp_flags, node));
return NULL;
}
EXPORT_SYMBOL(get_task_io_context);
/**
* ioc_lookup_icq - lookup io_cq from ioc
* @ioc: the associated io_context
* @q: the associated request_queue
*
* Look up io_cq associated with @ioc - @q pair from @ioc. Must be called
* with @q->queue_lock held.
*/
struct io_cq *ioc_lookup_icq(struct io_context *ioc, struct request_queue *q)
{
struct io_cq *icq;
lockdep_assert_held(q->queue_lock);
/*
* icq's are indexed from @ioc using radix tree and hint pointer,
* both of which are protected with RCU. All removals are done
* holding both q and ioc locks, and we're holding q lock - if we
* find a icq which points to us, it's guaranteed to be valid.
*/
rcu_read_lock();
icq = rcu_dereference(ioc->icq_hint);
if (icq && icq->q == q)
goto out;
icq = radix_tree_lookup(&ioc->icq_tree, q->id);
if (icq && icq->q == q)
rcu_assign_pointer(ioc->icq_hint, icq); /* allowed to race */
else
icq = NULL;
out:
rcu_read_unlock();
return icq;
}
EXPORT_SYMBOL(ioc_lookup_icq);
/**
* ioc_create_icq - create and link io_cq
* @q: request_queue of interest
* @gfp_mask: allocation mask
*
* Make sure io_cq linking %current->io_context and @q exists. If either
* io_context and/or icq don't exist, they will be created using @gfp_mask.
*
* The caller is responsible for ensuring @ioc won't go away and @q is
* alive and will stay alive until this function returns.
*/
struct io_cq *ioc_create_icq(struct request_queue *q, gfp_t gfp_mask)
{
struct elevator_type *et = q->elevator->type;
struct io_context *ioc;
struct io_cq *icq;
/* allocate stuff */
ioc = create_io_context(current, gfp_mask, q->node);
if (!ioc)
return NULL;
icq = kmem_cache_alloc_node(et->icq_cache, gfp_mask | __GFP_ZERO,
q->node);
if (!icq)
return NULL;
if (radix_tree_preload(gfp_mask) < 0) {
kmem_cache_free(et->icq_cache, icq);
return NULL;
}
icq->ioc = ioc;
icq->q = q;
INIT_LIST_HEAD(&icq->q_node);
INIT_HLIST_NODE(&icq->ioc_node);
/* lock both q and ioc and try to link @icq */
spin_lock_irq(q->queue_lock);
spin_lock(&ioc->lock);
if (likely(!radix_tree_insert(&ioc->icq_tree, q->id, icq))) {
hlist_add_head(&icq->ioc_node, &ioc->icq_list);
list_add(&icq->q_node, &q->icq_list);
if (et->ops.elevator_init_icq_fn)
et->ops.elevator_init_icq_fn(icq);
} else {
kmem_cache_free(et->icq_cache, icq);
icq = ioc_lookup_icq(ioc, q);
if (!icq)
printk(KERN_ERR "cfq: icq link failed!\n");
}
spin_unlock(&ioc->lock);
spin_unlock_irq(q->queue_lock);
radix_tree_preload_end();
return icq;
}
void ioc_set_icq_flags(struct io_context *ioc, unsigned int flags)
{
struct io_cq *icq;
struct hlist_node *n;
hlist_for_each_entry(icq, n, &ioc->icq_list, ioc_node)
icq->flags |= flags;
}
/**
* ioc_ioprio_changed - notify ioprio change
* @ioc: io_context of interest
* @ioprio: new ioprio
*
* @ioc's ioprio has changed to @ioprio. Set %ICQ_IOPRIO_CHANGED for all
* icq's. iosched is responsible for checking the bit and applying it on
* request issue path.
*/
void ioc_ioprio_changed(struct io_context *ioc, int ioprio)
{
unsigned long flags;
spin_lock_irqsave(&ioc->lock, flags);
ioc->ioprio = ioprio;
ioc_set_icq_flags(ioc, ICQ_IOPRIO_CHANGED);
spin_unlock_irqrestore(&ioc->lock, flags);
}
/**
* ioc_cgroup_changed - notify cgroup change
* @ioc: io_context of interest
*
* @ioc's cgroup has changed. Set %ICQ_CGROUP_CHANGED for all icq's.
* iosched is responsible for checking the bit and applying it on request
* issue path.
*/
void ioc_cgroup_changed(struct io_context *ioc)
{
unsigned long flags;
spin_lock_irqsave(&ioc->lock, flags);
ioc_set_icq_flags(ioc, ICQ_CGROUP_CHANGED);
spin_unlock_irqrestore(&ioc->lock, flags);
}
EXPORT_SYMBOL(ioc_cgroup_changed);
/**
* icq_get_changed - fetch and clear icq changed mask
* @icq: icq of interest
*
* Fetch and clear ICQ_*_CHANGED bits from @icq. Grabs and releases
* @icq->ioc->lock.
*/
unsigned icq_get_changed(struct io_cq *icq)
{
unsigned int changed = 0;
unsigned long flags;
if (unlikely(icq->flags & ICQ_CHANGED_MASK)) {
spin_lock_irqsave(&icq->ioc->lock, flags);
changed = icq->flags & ICQ_CHANGED_MASK;
icq->flags &= ~ICQ_CHANGED_MASK;
spin_unlock_irqrestore(&icq->ioc->lock, flags);
}
return changed;
}
EXPORT_SYMBOL(icq_get_changed);
static int __init blk_ioc_init(void)
{
iocontext_cachep = kmem_cache_create("blkdev_ioc",
sizeof(struct io_context), 0, SLAB_PANIC, NULL);
return 0;
}
subsys_initcall(blk_ioc_init);
| gpl-2.0 |
TeamBliss-Devices/android_kernel_samsung_v2wifixx | drivers/infiniband/hw/ehca/ipz_pt_fn.c | 8246 | 7730 | /*
* IBM eServer eHCA Infiniband device driver for Linux on POWER
*
* internal queue handling
*
* Authors: Waleri Fomin <fomin@de.ibm.com>
* Reinhard Ernst <rernst@de.ibm.com>
* Christoph Raisch <raisch@de.ibm.com>
*
* Copyright (c) 2005 IBM Corporation
*
* This source code is distributed under a dual license of GPL v2.0 and OpenIB
* BSD.
*
* OpenIB BSD License
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <linux/slab.h>
#include "ehca_tools.h"
#include "ipz_pt_fn.h"
#include "ehca_classes.h"
#define PAGES_PER_KPAGE (PAGE_SIZE >> EHCA_PAGESHIFT)
struct kmem_cache *small_qp_cache;
void *ipz_qpageit_get_inc(struct ipz_queue *queue)
{
void *ret = ipz_qeit_get(queue);
queue->current_q_offset += queue->pagesize;
if (queue->current_q_offset > queue->queue_length) {
queue->current_q_offset -= queue->pagesize;
ret = NULL;
}
if (((u64)ret) % queue->pagesize) {
ehca_gen_err("ERROR!! not at PAGE-Boundary");
return NULL;
}
return ret;
}
void *ipz_qeit_eq_get_inc(struct ipz_queue *queue)
{
void *ret = ipz_qeit_get(queue);
u64 last_entry_in_q = queue->queue_length - queue->qe_size;
queue->current_q_offset += queue->qe_size;
if (queue->current_q_offset > last_entry_in_q) {
queue->current_q_offset = 0;
queue->toggle_state = (~queue->toggle_state) & 1;
}
return ret;
}
int ipz_queue_abs_to_offset(struct ipz_queue *queue, u64 addr, u64 *q_offset)
{
int i;
for (i = 0; i < queue->queue_length / queue->pagesize; i++) {
u64 page = (u64)virt_to_abs(queue->queue_pages[i]);
if (addr >= page && addr < page + queue->pagesize) {
*q_offset = addr - page + i * queue->pagesize;
return 0;
}
}
return -EINVAL;
}
#if PAGE_SHIFT < EHCA_PAGESHIFT
#error Kernel pages must be at least as large than eHCA pages (4K) !
#endif
/*
* allocate pages for queue:
* outer loop allocates whole kernel pages (page aligned) and
* inner loop divides a kernel page into smaller hca queue pages
*/
static int alloc_queue_pages(struct ipz_queue *queue, const u32 nr_of_pages)
{
int k, f = 0;
u8 *kpage;
while (f < nr_of_pages) {
kpage = (u8 *)get_zeroed_page(GFP_KERNEL);
if (!kpage)
goto out;
for (k = 0; k < PAGES_PER_KPAGE && f < nr_of_pages; k++) {
queue->queue_pages[f] = (struct ipz_page *)kpage;
kpage += EHCA_PAGESIZE;
f++;
}
}
return 1;
out:
for (f = 0; f < nr_of_pages && queue->queue_pages[f];
f += PAGES_PER_KPAGE)
free_page((unsigned long)(queue->queue_pages)[f]);
return 0;
}
static int alloc_small_queue_page(struct ipz_queue *queue, struct ehca_pd *pd)
{
int order = ilog2(queue->pagesize) - 9;
struct ipz_small_queue_page *page;
unsigned long bit;
mutex_lock(&pd->lock);
if (!list_empty(&pd->free[order]))
page = list_entry(pd->free[order].next,
struct ipz_small_queue_page, list);
else {
page = kmem_cache_zalloc(small_qp_cache, GFP_KERNEL);
if (!page)
goto out;
page->page = get_zeroed_page(GFP_KERNEL);
if (!page->page) {
kmem_cache_free(small_qp_cache, page);
goto out;
}
list_add(&page->list, &pd->free[order]);
}
bit = find_first_zero_bit(page->bitmap, IPZ_SPAGE_PER_KPAGE >> order);
__set_bit(bit, page->bitmap);
page->fill++;
if (page->fill == IPZ_SPAGE_PER_KPAGE >> order)
list_move(&page->list, &pd->full[order]);
mutex_unlock(&pd->lock);
queue->queue_pages[0] = (void *)(page->page | (bit << (order + 9)));
queue->small_page = page;
queue->offset = bit << (order + 9);
return 1;
out:
ehca_err(pd->ib_pd.device, "failed to allocate small queue page");
mutex_unlock(&pd->lock);
return 0;
}
static void free_small_queue_page(struct ipz_queue *queue, struct ehca_pd *pd)
{
int order = ilog2(queue->pagesize) - 9;
struct ipz_small_queue_page *page = queue->small_page;
unsigned long bit;
int free_page = 0;
bit = ((unsigned long)queue->queue_pages[0] & ~PAGE_MASK)
>> (order + 9);
mutex_lock(&pd->lock);
__clear_bit(bit, page->bitmap);
page->fill--;
if (page->fill == 0) {
list_del(&page->list);
free_page = 1;
}
if (page->fill == (IPZ_SPAGE_PER_KPAGE >> order) - 1)
/* the page was full until we freed the chunk */
list_move_tail(&page->list, &pd->free[order]);
mutex_unlock(&pd->lock);
if (free_page) {
free_page(page->page);
kmem_cache_free(small_qp_cache, page);
}
}
int ipz_queue_ctor(struct ehca_pd *pd, struct ipz_queue *queue,
const u32 nr_of_pages, const u32 pagesize,
const u32 qe_size, const u32 nr_of_sg,
int is_small)
{
if (pagesize > PAGE_SIZE) {
ehca_gen_err("FATAL ERROR: pagesize=%x "
"is greater than kernel page size", pagesize);
return 0;
}
/* init queue fields */
queue->queue_length = nr_of_pages * pagesize;
queue->pagesize = pagesize;
queue->qe_size = qe_size;
queue->act_nr_of_sg = nr_of_sg;
queue->current_q_offset = 0;
queue->toggle_state = 1;
queue->small_page = NULL;
/* allocate queue page pointers */
queue->queue_pages = kzalloc(nr_of_pages * sizeof(void *), GFP_KERNEL);
if (!queue->queue_pages) {
queue->queue_pages = vzalloc(nr_of_pages * sizeof(void *));
if (!queue->queue_pages) {
ehca_gen_err("Couldn't allocate queue page list");
return 0;
}
}
/* allocate actual queue pages */
if (is_small) {
if (!alloc_small_queue_page(queue, pd))
goto ipz_queue_ctor_exit0;
} else
if (!alloc_queue_pages(queue, nr_of_pages))
goto ipz_queue_ctor_exit0;
return 1;
ipz_queue_ctor_exit0:
ehca_gen_err("Couldn't alloc pages queue=%p "
"nr_of_pages=%x", queue, nr_of_pages);
if (is_vmalloc_addr(queue->queue_pages))
vfree(queue->queue_pages);
else
kfree(queue->queue_pages);
return 0;
}
int ipz_queue_dtor(struct ehca_pd *pd, struct ipz_queue *queue)
{
int i, nr_pages;
if (!queue || !queue->queue_pages) {
ehca_gen_dbg("queue or queue_pages is NULL");
return 0;
}
if (queue->small_page)
free_small_queue_page(queue, pd);
else {
nr_pages = queue->queue_length / queue->pagesize;
for (i = 0; i < nr_pages; i += PAGES_PER_KPAGE)
free_page((unsigned long)queue->queue_pages[i]);
}
if (is_vmalloc_addr(queue->queue_pages))
vfree(queue->queue_pages);
else
kfree(queue->queue_pages);
return 1;
}
int ehca_init_small_qp_cache(void)
{
small_qp_cache = kmem_cache_create("ehca_cache_small_qp",
sizeof(struct ipz_small_queue_page),
0, SLAB_HWCACHE_ALIGN, NULL);
if (!small_qp_cache)
return -ENOMEM;
return 0;
}
void ehca_cleanup_small_qp_cache(void)
{
kmem_cache_destroy(small_qp_cache);
}
| gpl-2.0 |
MoKee/android_kernel_sony_fuji-common | net/rose/rose_out.c | 9782 | 2840 | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Copyright (C) Jonathan Naylor G4KLX (g4klx@g4klx.demon.co.uk)
*/
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/kernel.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/gfp.h>
#include <net/ax25.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <net/sock.h>
#include <linux/fcntl.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <net/rose.h>
/*
* This procedure is passed a buffer descriptor for an iframe. It builds
* the rest of the control part of the frame and then writes it out.
*/
static void rose_send_iframe(struct sock *sk, struct sk_buff *skb)
{
struct rose_sock *rose = rose_sk(sk);
if (skb == NULL)
return;
skb->data[2] |= (rose->vr << 5) & 0xE0;
skb->data[2] |= (rose->vs << 1) & 0x0E;
rose_start_idletimer(sk);
rose_transmit_link(skb, rose->neighbour);
}
void rose_kick(struct sock *sk)
{
struct rose_sock *rose = rose_sk(sk);
struct sk_buff *skb, *skbn;
unsigned short start, end;
if (rose->state != ROSE_STATE_3)
return;
if (rose->condition & ROSE_COND_PEER_RX_BUSY)
return;
if (!skb_peek(&sk->sk_write_queue))
return;
start = (skb_peek(&rose->ack_queue) == NULL) ? rose->va : rose->vs;
end = (rose->va + sysctl_rose_window_size) % ROSE_MODULUS;
if (start == end)
return;
rose->vs = start;
/*
* Transmit data until either we're out of data to send or
* the window is full.
*/
skb = skb_dequeue(&sk->sk_write_queue);
do {
if ((skbn = skb_clone(skb, GFP_ATOMIC)) == NULL) {
skb_queue_head(&sk->sk_write_queue, skb);
break;
}
skb_set_owner_w(skbn, sk);
/*
* Transmit the frame copy.
*/
rose_send_iframe(sk, skbn);
rose->vs = (rose->vs + 1) % ROSE_MODULUS;
/*
* Requeue the original data frame.
*/
skb_queue_tail(&rose->ack_queue, skb);
} while (rose->vs != end &&
(skb = skb_dequeue(&sk->sk_write_queue)) != NULL);
rose->vl = rose->vr;
rose->condition &= ~ROSE_COND_ACK_PENDING;
rose_stop_timer(sk);
}
/*
* The following routines are taken from page 170 of the 7th ARRL Computer
* Networking Conference paper, as is the whole state machine.
*/
void rose_enquiry_response(struct sock *sk)
{
struct rose_sock *rose = rose_sk(sk);
if (rose->condition & ROSE_COND_OWN_RX_BUSY)
rose_write_internal(sk, ROSE_RNR);
else
rose_write_internal(sk, ROSE_RR);
rose->vl = rose->vr;
rose->condition &= ~ROSE_COND_ACK_PENDING;
rose_stop_timer(sk);
}
| gpl-2.0 |
TeslaOS/android_kernel_sony_msm8x27 | drivers/misc/altera-stapl/altera-jtag.c | 10038 | 22108 | /*
* altera-jtag.c
*
* altera FPGA driver
*
* Copyright (C) Altera Corporation 1998-2001
* Copyright (C) 2010 NetUP Inc.
* Copyright (C) 2010 Igor M. Liplianin <liplianin@netup.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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/delay.h>
#include <linux/firmware.h>
#include <linux/slab.h>
#include <misc/altera.h>
#include "altera-exprt.h"
#include "altera-jtag.h"
#define alt_jtag_io(a, b, c)\
astate->config->jtag_io(astate->config->dev, a, b, c);
#define alt_malloc(a) kzalloc(a, GFP_KERNEL);
/*
* This structure shows, for each JTAG state, which state is reached after
* a single TCK clock cycle with TMS high or TMS low, respectively. This
* describes all possible state transitions in the JTAG state machine.
*/
struct altera_jtag_machine {
enum altera_jtag_state tms_high;
enum altera_jtag_state tms_low;
};
static const struct altera_jtag_machine altera_transitions[] = {
/* RESET */ { RESET, IDLE },
/* IDLE */ { DRSELECT, IDLE },
/* DRSELECT */ { IRSELECT, DRCAPTURE },
/* DRCAPTURE */ { DREXIT1, DRSHIFT },
/* DRSHIFT */ { DREXIT1, DRSHIFT },
/* DREXIT1 */ { DRUPDATE, DRPAUSE },
/* DRPAUSE */ { DREXIT2, DRPAUSE },
/* DREXIT2 */ { DRUPDATE, DRSHIFT },
/* DRUPDATE */ { DRSELECT, IDLE },
/* IRSELECT */ { RESET, IRCAPTURE },
/* IRCAPTURE */ { IREXIT1, IRSHIFT },
/* IRSHIFT */ { IREXIT1, IRSHIFT },
/* IREXIT1 */ { IRUPDATE, IRPAUSE },
/* IRPAUSE */ { IREXIT2, IRPAUSE },
/* IREXIT2 */ { IRUPDATE, IRSHIFT },
/* IRUPDATE */ { DRSELECT, IDLE }
};
/*
* This table contains the TMS value to be used to take the NEXT STEP on
* the path to the desired state. The array index is the current state,
* and the bit position is the desired endstate. To find out which state
* is used as the intermediate state, look up the TMS value in the
* altera_transitions[] table.
*/
static const u16 altera_jtag_path_map[16] = {
/* RST RTI SDRS CDR SDR E1DR PDR E2DR */
0x0001, 0xFFFD, 0xFE01, 0xFFE7, 0xFFEF, 0xFF0F, 0xFFBF, 0xFFFF,
/* UDR SIRS CIR SIR E1IR PIR E2IR UIR */
0xFEFD, 0x0001, 0xF3FF, 0xF7FF, 0x87FF, 0xDFFF, 0xFFFF, 0x7FFD
};
/* Flag bits for alt_jtag_io() function */
#define TMS_HIGH 1
#define TMS_LOW 0
#define TDI_HIGH 1
#define TDI_LOW 0
#define READ_TDO 1
#define IGNORE_TDO 0
int altera_jinit(struct altera_state *astate)
{
struct altera_jtag *js = &astate->js;
/* initial JTAG state is unknown */
js->jtag_state = ILLEGAL_JTAG_STATE;
/* initialize to default state */
js->drstop_state = IDLE;
js->irstop_state = IDLE;
js->dr_pre = 0;
js->dr_post = 0;
js->ir_pre = 0;
js->ir_post = 0;
js->dr_length = 0;
js->ir_length = 0;
js->dr_pre_data = NULL;
js->dr_post_data = NULL;
js->ir_pre_data = NULL;
js->ir_post_data = NULL;
js->dr_buffer = NULL;
js->ir_buffer = NULL;
return 0;
}
int altera_set_drstop(struct altera_jtag *js, enum altera_jtag_state state)
{
js->drstop_state = state;
return 0;
}
int altera_set_irstop(struct altera_jtag *js, enum altera_jtag_state state)
{
js->irstop_state = state;
return 0;
}
int altera_set_dr_pre(struct altera_jtag *js,
u32 count, u32 start_index,
u8 *preamble_data)
{
int status = 0;
u32 i;
u32 j;
if (count > js->dr_pre) {
kfree(js->dr_pre_data);
js->dr_pre_data = (u8 *)alt_malloc((count + 7) >> 3);
if (js->dr_pre_data == NULL)
status = -ENOMEM;
else
js->dr_pre = count;
} else
js->dr_pre = count;
if (status == 0) {
for (i = 0; i < count; ++i) {
j = i + start_index;
if (preamble_data == NULL)
js->dr_pre_data[i >> 3] |= (1 << (i & 7));
else {
if (preamble_data[j >> 3] & (1 << (j & 7)))
js->dr_pre_data[i >> 3] |=
(1 << (i & 7));
else
js->dr_pre_data[i >> 3] &=
~(u32)(1 << (i & 7));
}
}
}
return status;
}
int altera_set_ir_pre(struct altera_jtag *js, u32 count, u32 start_index,
u8 *preamble_data)
{
int status = 0;
u32 i;
u32 j;
if (count > js->ir_pre) {
kfree(js->ir_pre_data);
js->ir_pre_data = (u8 *)alt_malloc((count + 7) >> 3);
if (js->ir_pre_data == NULL)
status = -ENOMEM;
else
js->ir_pre = count;
} else
js->ir_pre = count;
if (status == 0) {
for (i = 0; i < count; ++i) {
j = i + start_index;
if (preamble_data == NULL)
js->ir_pre_data[i >> 3] |= (1 << (i & 7));
else {
if (preamble_data[j >> 3] & (1 << (j & 7)))
js->ir_pre_data[i >> 3] |=
(1 << (i & 7));
else
js->ir_pre_data[i >> 3] &=
~(u32)(1 << (i & 7));
}
}
}
return status;
}
int altera_set_dr_post(struct altera_jtag *js, u32 count, u32 start_index,
u8 *postamble_data)
{
int status = 0;
u32 i;
u32 j;
if (count > js->dr_post) {
kfree(js->dr_post_data);
js->dr_post_data = (u8 *)alt_malloc((count + 7) >> 3);
if (js->dr_post_data == NULL)
status = -ENOMEM;
else
js->dr_post = count;
} else
js->dr_post = count;
if (status == 0) {
for (i = 0; i < count; ++i) {
j = i + start_index;
if (postamble_data == NULL)
js->dr_post_data[i >> 3] |= (1 << (i & 7));
else {
if (postamble_data[j >> 3] & (1 << (j & 7)))
js->dr_post_data[i >> 3] |=
(1 << (i & 7));
else
js->dr_post_data[i >> 3] &=
~(u32)(1 << (i & 7));
}
}
}
return status;
}
int altera_set_ir_post(struct altera_jtag *js, u32 count, u32 start_index,
u8 *postamble_data)
{
int status = 0;
u32 i;
u32 j;
if (count > js->ir_post) {
kfree(js->ir_post_data);
js->ir_post_data = (u8 *)alt_malloc((count + 7) >> 3);
if (js->ir_post_data == NULL)
status = -ENOMEM;
else
js->ir_post = count;
} else
js->ir_post = count;
if (status != 0)
return status;
for (i = 0; i < count; ++i) {
j = i + start_index;
if (postamble_data == NULL)
js->ir_post_data[i >> 3] |= (1 << (i & 7));
else {
if (postamble_data[j >> 3] & (1 << (j & 7)))
js->ir_post_data[i >> 3] |= (1 << (i & 7));
else
js->ir_post_data[i >> 3] &=
~(u32)(1 << (i & 7));
}
}
return status;
}
static void altera_jreset_idle(struct altera_state *astate)
{
struct altera_jtag *js = &astate->js;
int i;
/* Go to Test Logic Reset (no matter what the starting state may be) */
for (i = 0; i < 5; ++i)
alt_jtag_io(TMS_HIGH, TDI_LOW, IGNORE_TDO);
/* Now step to Run Test / Idle */
alt_jtag_io(TMS_LOW, TDI_LOW, IGNORE_TDO);
js->jtag_state = IDLE;
}
int altera_goto_jstate(struct altera_state *astate,
enum altera_jtag_state state)
{
struct altera_jtag *js = &astate->js;
int tms;
int count = 0;
int status = 0;
if (js->jtag_state == ILLEGAL_JTAG_STATE)
/* initialize JTAG chain to known state */
altera_jreset_idle(astate);
if (js->jtag_state == state) {
/*
* We are already in the desired state.
* If it is a stable state, loop here.
* Otherwise do nothing (no clock cycles).
*/
if ((state == IDLE) || (state == DRSHIFT) ||
(state == DRPAUSE) || (state == IRSHIFT) ||
(state == IRPAUSE)) {
alt_jtag_io(TMS_LOW, TDI_LOW, IGNORE_TDO);
} else if (state == RESET)
alt_jtag_io(TMS_HIGH, TDI_LOW, IGNORE_TDO);
} else {
while ((js->jtag_state != state) && (count < 9)) {
/* Get TMS value to take a step toward desired state */
tms = (altera_jtag_path_map[js->jtag_state] &
(1 << state))
? TMS_HIGH : TMS_LOW;
/* Take a step */
alt_jtag_io(tms, TDI_LOW, IGNORE_TDO);
if (tms)
js->jtag_state =
altera_transitions[js->jtag_state].tms_high;
else
js->jtag_state =
altera_transitions[js->jtag_state].tms_low;
++count;
}
}
if (js->jtag_state != state)
status = -EREMOTEIO;
return status;
}
int altera_wait_cycles(struct altera_state *astate,
s32 cycles,
enum altera_jtag_state wait_state)
{
struct altera_jtag *js = &astate->js;
int tms;
s32 count;
int status = 0;
if (js->jtag_state != wait_state)
status = altera_goto_jstate(astate, wait_state);
if (status == 0) {
/*
* Set TMS high to loop in RESET state
* Set TMS low to loop in any other stable state
*/
tms = (wait_state == RESET) ? TMS_HIGH : TMS_LOW;
for (count = 0L; count < cycles; count++)
alt_jtag_io(tms, TDI_LOW, IGNORE_TDO);
}
return status;
}
int altera_wait_msecs(struct altera_state *astate,
s32 microseconds, enum altera_jtag_state wait_state)
/*
* Causes JTAG hardware to sit in the specified stable
* state for the specified duration of real time. If
* no JTAG operations have been performed yet, then only
* a delay is performed. This permits the WAIT USECS
* statement to be used in VECTOR programs without causing
* any JTAG operations.
* Returns 0 for success, else appropriate error code.
*/
{
struct altera_jtag *js = &astate->js;
int status = 0;
if ((js->jtag_state != ILLEGAL_JTAG_STATE) &&
(js->jtag_state != wait_state))
status = altera_goto_jstate(astate, wait_state);
if (status == 0)
/* Wait for specified time interval */
udelay(microseconds);
return status;
}
static void altera_concatenate_data(u8 *buffer,
u8 *preamble_data,
u32 preamble_count,
u8 *target_data,
u32 start_index,
u32 target_count,
u8 *postamble_data,
u32 postamble_count)
/*
* Copies preamble data, target data, and postamble data
* into one buffer for IR or DR scans.
*/
{
u32 i, j, k;
for (i = 0L; i < preamble_count; ++i) {
if (preamble_data[i >> 3L] & (1L << (i & 7L)))
buffer[i >> 3L] |= (1L << (i & 7L));
else
buffer[i >> 3L] &= ~(u32)(1L << (i & 7L));
}
j = start_index;
k = preamble_count + target_count;
for (; i < k; ++i, ++j) {
if (target_data[j >> 3L] & (1L << (j & 7L)))
buffer[i >> 3L] |= (1L << (i & 7L));
else
buffer[i >> 3L] &= ~(u32)(1L << (i & 7L));
}
j = 0L;
k = preamble_count + target_count + postamble_count;
for (; i < k; ++i, ++j) {
if (postamble_data[j >> 3L] & (1L << (j & 7L)))
buffer[i >> 3L] |= (1L << (i & 7L));
else
buffer[i >> 3L] &= ~(u32)(1L << (i & 7L));
}
}
static int alt_jtag_drscan(struct altera_state *astate,
int start_state,
int count,
u8 *tdi,
u8 *tdo)
{
int i = 0;
int tdo_bit = 0;
int status = 1;
/* First go to DRSHIFT state */
switch (start_state) {
case 0: /* IDLE */
alt_jtag_io(1, 0, 0); /* DRSELECT */
alt_jtag_io(0, 0, 0); /* DRCAPTURE */
alt_jtag_io(0, 0, 0); /* DRSHIFT */
break;
case 1: /* DRPAUSE */
alt_jtag_io(1, 0, 0); /* DREXIT2 */
alt_jtag_io(1, 0, 0); /* DRUPDATE */
alt_jtag_io(1, 0, 0); /* DRSELECT */
alt_jtag_io(0, 0, 0); /* DRCAPTURE */
alt_jtag_io(0, 0, 0); /* DRSHIFT */
break;
case 2: /* IRPAUSE */
alt_jtag_io(1, 0, 0); /* IREXIT2 */
alt_jtag_io(1, 0, 0); /* IRUPDATE */
alt_jtag_io(1, 0, 0); /* DRSELECT */
alt_jtag_io(0, 0, 0); /* DRCAPTURE */
alt_jtag_io(0, 0, 0); /* DRSHIFT */
break;
default:
status = 0;
}
if (status) {
/* loop in the SHIFT-DR state */
for (i = 0; i < count; i++) {
tdo_bit = alt_jtag_io(
(i == count - 1),
tdi[i >> 3] & (1 << (i & 7)),
(tdo != NULL));
if (tdo != NULL) {
if (tdo_bit)
tdo[i >> 3] |= (1 << (i & 7));
else
tdo[i >> 3] &= ~(u32)(1 << (i & 7));
}
}
alt_jtag_io(0, 0, 0); /* DRPAUSE */
}
return status;
}
static int alt_jtag_irscan(struct altera_state *astate,
int start_state,
int count,
u8 *tdi,
u8 *tdo)
{
int i = 0;
int tdo_bit = 0;
int status = 1;
/* First go to IRSHIFT state */
switch (start_state) {
case 0: /* IDLE */
alt_jtag_io(1, 0, 0); /* DRSELECT */
alt_jtag_io(1, 0, 0); /* IRSELECT */
alt_jtag_io(0, 0, 0); /* IRCAPTURE */
alt_jtag_io(0, 0, 0); /* IRSHIFT */
break;
case 1: /* DRPAUSE */
alt_jtag_io(1, 0, 0); /* DREXIT2 */
alt_jtag_io(1, 0, 0); /* DRUPDATE */
alt_jtag_io(1, 0, 0); /* DRSELECT */
alt_jtag_io(1, 0, 0); /* IRSELECT */
alt_jtag_io(0, 0, 0); /* IRCAPTURE */
alt_jtag_io(0, 0, 0); /* IRSHIFT */
break;
case 2: /* IRPAUSE */
alt_jtag_io(1, 0, 0); /* IREXIT2 */
alt_jtag_io(1, 0, 0); /* IRUPDATE */
alt_jtag_io(1, 0, 0); /* DRSELECT */
alt_jtag_io(1, 0, 0); /* IRSELECT */
alt_jtag_io(0, 0, 0); /* IRCAPTURE */
alt_jtag_io(0, 0, 0); /* IRSHIFT */
break;
default:
status = 0;
}
if (status) {
/* loop in the SHIFT-IR state */
for (i = 0; i < count; i++) {
tdo_bit = alt_jtag_io(
(i == count - 1),
tdi[i >> 3] & (1 << (i & 7)),
(tdo != NULL));
if (tdo != NULL) {
if (tdo_bit)
tdo[i >> 3] |= (1 << (i & 7));
else
tdo[i >> 3] &= ~(u32)(1 << (i & 7));
}
}
alt_jtag_io(0, 0, 0); /* IRPAUSE */
}
return status;
}
static void altera_extract_target_data(u8 *buffer,
u8 *target_data,
u32 start_index,
u32 preamble_count,
u32 target_count)
/*
* Copies target data from scan buffer, filtering out
* preamble and postamble data.
*/
{
u32 i;
u32 j;
u32 k;
j = preamble_count;
k = start_index + target_count;
for (i = start_index; i < k; ++i, ++j) {
if (buffer[j >> 3] & (1 << (j & 7)))
target_data[i >> 3] |= (1 << (i & 7));
else
target_data[i >> 3] &= ~(u32)(1 << (i & 7));
}
}
int altera_irscan(struct altera_state *astate,
u32 count,
u8 *tdi_data,
u32 start_index)
/* Shifts data into instruction register */
{
struct altera_jtag *js = &astate->js;
int start_code = 0;
u32 alloc_chars = 0;
u32 shift_count = js->ir_pre + count + js->ir_post;
int status = 0;
enum altera_jtag_state start_state = ILLEGAL_JTAG_STATE;
switch (js->jtag_state) {
case ILLEGAL_JTAG_STATE:
case RESET:
case IDLE:
start_code = 0;
start_state = IDLE;
break;
case DRSELECT:
case DRCAPTURE:
case DRSHIFT:
case DREXIT1:
case DRPAUSE:
case DREXIT2:
case DRUPDATE:
start_code = 1;
start_state = DRPAUSE;
break;
case IRSELECT:
case IRCAPTURE:
case IRSHIFT:
case IREXIT1:
case IRPAUSE:
case IREXIT2:
case IRUPDATE:
start_code = 2;
start_state = IRPAUSE;
break;
default:
status = -EREMOTEIO;
break;
}
if (status == 0)
if (js->jtag_state != start_state)
status = altera_goto_jstate(astate, start_state);
if (status == 0) {
if (shift_count > js->ir_length) {
alloc_chars = (shift_count + 7) >> 3;
kfree(js->ir_buffer);
js->ir_buffer = (u8 *)alt_malloc(alloc_chars);
if (js->ir_buffer == NULL)
status = -ENOMEM;
else
js->ir_length = alloc_chars * 8;
}
}
if (status == 0) {
/*
* Copy preamble data, IR data,
* and postamble data into a buffer
*/
altera_concatenate_data(js->ir_buffer,
js->ir_pre_data,
js->ir_pre,
tdi_data,
start_index,
count,
js->ir_post_data,
js->ir_post);
/* Do the IRSCAN */
alt_jtag_irscan(astate,
start_code,
shift_count,
js->ir_buffer,
NULL);
/* alt_jtag_irscan() always ends in IRPAUSE state */
js->jtag_state = IRPAUSE;
}
if (status == 0)
if (js->irstop_state != IRPAUSE)
status = altera_goto_jstate(astate, js->irstop_state);
return status;
}
int altera_swap_ir(struct altera_state *astate,
u32 count,
u8 *in_data,
u32 in_index,
u8 *out_data,
u32 out_index)
/* Shifts data into instruction register, capturing output data */
{
struct altera_jtag *js = &astate->js;
int start_code = 0;
u32 alloc_chars = 0;
u32 shift_count = js->ir_pre + count + js->ir_post;
int status = 0;
enum altera_jtag_state start_state = ILLEGAL_JTAG_STATE;
switch (js->jtag_state) {
case ILLEGAL_JTAG_STATE:
case RESET:
case IDLE:
start_code = 0;
start_state = IDLE;
break;
case DRSELECT:
case DRCAPTURE:
case DRSHIFT:
case DREXIT1:
case DRPAUSE:
case DREXIT2:
case DRUPDATE:
start_code = 1;
start_state = DRPAUSE;
break;
case IRSELECT:
case IRCAPTURE:
case IRSHIFT:
case IREXIT1:
case IRPAUSE:
case IREXIT2:
case IRUPDATE:
start_code = 2;
start_state = IRPAUSE;
break;
default:
status = -EREMOTEIO;
break;
}
if (status == 0)
if (js->jtag_state != start_state)
status = altera_goto_jstate(astate, start_state);
if (status == 0) {
if (shift_count > js->ir_length) {
alloc_chars = (shift_count + 7) >> 3;
kfree(js->ir_buffer);
js->ir_buffer = (u8 *)alt_malloc(alloc_chars);
if (js->ir_buffer == NULL)
status = -ENOMEM;
else
js->ir_length = alloc_chars * 8;
}
}
if (status == 0) {
/*
* Copy preamble data, IR data,
* and postamble data into a buffer
*/
altera_concatenate_data(js->ir_buffer,
js->ir_pre_data,
js->ir_pre,
in_data,
in_index,
count,
js->ir_post_data,
js->ir_post);
/* Do the IRSCAN */
alt_jtag_irscan(astate,
start_code,
shift_count,
js->ir_buffer,
js->ir_buffer);
/* alt_jtag_irscan() always ends in IRPAUSE state */
js->jtag_state = IRPAUSE;
}
if (status == 0)
if (js->irstop_state != IRPAUSE)
status = altera_goto_jstate(astate, js->irstop_state);
if (status == 0)
/* Now extract the returned data from the buffer */
altera_extract_target_data(js->ir_buffer,
out_data, out_index,
js->ir_pre, count);
return status;
}
int altera_drscan(struct altera_state *astate,
u32 count,
u8 *tdi_data,
u32 start_index)
/* Shifts data into data register (ignoring output data) */
{
struct altera_jtag *js = &astate->js;
int start_code = 0;
u32 alloc_chars = 0;
u32 shift_count = js->dr_pre + count + js->dr_post;
int status = 0;
enum altera_jtag_state start_state = ILLEGAL_JTAG_STATE;
switch (js->jtag_state) {
case ILLEGAL_JTAG_STATE:
case RESET:
case IDLE:
start_code = 0;
start_state = IDLE;
break;
case DRSELECT:
case DRCAPTURE:
case DRSHIFT:
case DREXIT1:
case DRPAUSE:
case DREXIT2:
case DRUPDATE:
start_code = 1;
start_state = DRPAUSE;
break;
case IRSELECT:
case IRCAPTURE:
case IRSHIFT:
case IREXIT1:
case IRPAUSE:
case IREXIT2:
case IRUPDATE:
start_code = 2;
start_state = IRPAUSE;
break;
default:
status = -EREMOTEIO;
break;
}
if (status == 0)
if (js->jtag_state != start_state)
status = altera_goto_jstate(astate, start_state);
if (status == 0) {
if (shift_count > js->dr_length) {
alloc_chars = (shift_count + 7) >> 3;
kfree(js->dr_buffer);
js->dr_buffer = (u8 *)alt_malloc(alloc_chars);
if (js->dr_buffer == NULL)
status = -ENOMEM;
else
js->dr_length = alloc_chars * 8;
}
}
if (status == 0) {
/*
* Copy preamble data, DR data,
* and postamble data into a buffer
*/
altera_concatenate_data(js->dr_buffer,
js->dr_pre_data,
js->dr_pre,
tdi_data,
start_index,
count,
js->dr_post_data,
js->dr_post);
/* Do the DRSCAN */
alt_jtag_drscan(astate, start_code, shift_count,
js->dr_buffer, NULL);
/* alt_jtag_drscan() always ends in DRPAUSE state */
js->jtag_state = DRPAUSE;
}
if (status == 0)
if (js->drstop_state != DRPAUSE)
status = altera_goto_jstate(astate, js->drstop_state);
return status;
}
int altera_swap_dr(struct altera_state *astate, u32 count,
u8 *in_data, u32 in_index,
u8 *out_data, u32 out_index)
/* Shifts data into data register, capturing output data */
{
struct altera_jtag *js = &astate->js;
int start_code = 0;
u32 alloc_chars = 0;
u32 shift_count = js->dr_pre + count + js->dr_post;
int status = 0;
enum altera_jtag_state start_state = ILLEGAL_JTAG_STATE;
switch (js->jtag_state) {
case ILLEGAL_JTAG_STATE:
case RESET:
case IDLE:
start_code = 0;
start_state = IDLE;
break;
case DRSELECT:
case DRCAPTURE:
case DRSHIFT:
case DREXIT1:
case DRPAUSE:
case DREXIT2:
case DRUPDATE:
start_code = 1;
start_state = DRPAUSE;
break;
case IRSELECT:
case IRCAPTURE:
case IRSHIFT:
case IREXIT1:
case IRPAUSE:
case IREXIT2:
case IRUPDATE:
start_code = 2;
start_state = IRPAUSE;
break;
default:
status = -EREMOTEIO;
break;
}
if (status == 0)
if (js->jtag_state != start_state)
status = altera_goto_jstate(astate, start_state);
if (status == 0) {
if (shift_count > js->dr_length) {
alloc_chars = (shift_count + 7) >> 3;
kfree(js->dr_buffer);
js->dr_buffer = (u8 *)alt_malloc(alloc_chars);
if (js->dr_buffer == NULL)
status = -ENOMEM;
else
js->dr_length = alloc_chars * 8;
}
}
if (status == 0) {
/*
* Copy preamble data, DR data,
* and postamble data into a buffer
*/
altera_concatenate_data(js->dr_buffer,
js->dr_pre_data,
js->dr_pre,
in_data,
in_index,
count,
js->dr_post_data,
js->dr_post);
/* Do the DRSCAN */
alt_jtag_drscan(astate,
start_code,
shift_count,
js->dr_buffer,
js->dr_buffer);
/* alt_jtag_drscan() always ends in DRPAUSE state */
js->jtag_state = DRPAUSE;
}
if (status == 0)
if (js->drstop_state != DRPAUSE)
status = altera_goto_jstate(astate, js->drstop_state);
if (status == 0)
/* Now extract the returned data from the buffer */
altera_extract_target_data(js->dr_buffer,
out_data,
out_index,
js->dr_pre,
count);
return status;
}
void altera_free_buffers(struct altera_state *astate)
{
struct altera_jtag *js = &astate->js;
/* If the JTAG interface was used, reset it to TLR */
if (js->jtag_state != ILLEGAL_JTAG_STATE)
altera_jreset_idle(astate);
kfree(js->dr_pre_data);
js->dr_pre_data = NULL;
kfree(js->dr_post_data);
js->dr_post_data = NULL;
kfree(js->dr_buffer);
js->dr_buffer = NULL;
kfree(js->ir_pre_data);
js->ir_pre_data = NULL;
kfree(js->ir_post_data);
js->ir_post_data = NULL;
kfree(js->ir_buffer);
js->ir_buffer = NULL;
}
| gpl-2.0 |
tinyclub/preempt-rt-linux | Documentation/connector/ucon.c | 12086 | 5237 | /*
* ucon.c
*
* Copyright (c) 2004+ Evgeniy Polyakov <zbr@ioremap.net>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <asm/types.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/poll.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <arpa/inet.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <getopt.h>
#include <linux/connector.h>
#define DEBUG
#define NETLINK_CONNECTOR 11
/* Hopefully your userspace connector.h matches this kernel */
#define CN_TEST_IDX CN_NETLINK_USERS + 3
#define CN_TEST_VAL 0x456
#ifdef DEBUG
#define ulog(f, a...) fprintf(stdout, f, ##a)
#else
#define ulog(f, a...) do {} while (0)
#endif
static int need_exit;
static __u32 seq;
static int netlink_send(int s, struct cn_msg *msg)
{
struct nlmsghdr *nlh;
unsigned int size;
int err;
char buf[128];
struct cn_msg *m;
size = NLMSG_SPACE(sizeof(struct cn_msg) + msg->len);
nlh = (struct nlmsghdr *)buf;
nlh->nlmsg_seq = seq++;
nlh->nlmsg_pid = getpid();
nlh->nlmsg_type = NLMSG_DONE;
nlh->nlmsg_len = NLMSG_LENGTH(size - sizeof(*nlh));
nlh->nlmsg_flags = 0;
m = NLMSG_DATA(nlh);
#if 0
ulog("%s: [%08x.%08x] len=%u, seq=%u, ack=%u.\n",
__func__, msg->id.idx, msg->id.val, msg->len, msg->seq, msg->ack);
#endif
memcpy(m, msg, sizeof(*m) + msg->len);
err = send(s, nlh, size, 0);
if (err == -1)
ulog("Failed to send: %s [%d].\n",
strerror(errno), errno);
return err;
}
static void usage(void)
{
printf(
"Usage: ucon [options] [output file]\n"
"\n"
"\t-h\tthis help screen\n"
"\t-s\tsend buffers to the test module\n"
"\n"
"The default behavior of ucon is to subscribe to the test module\n"
"and wait for state messages. Any ones received are dumped to the\n"
"specified output file (or stdout). The test module is assumed to\n"
"have an id of {%u.%u}\n"
"\n"
"If you get no output, then verify the cn_test module id matches\n"
"the expected id above.\n"
, CN_TEST_IDX, CN_TEST_VAL
);
}
int main(int argc, char *argv[])
{
int s;
char buf[1024];
int len;
struct nlmsghdr *reply;
struct sockaddr_nl l_local;
struct cn_msg *data;
FILE *out;
time_t tm;
struct pollfd pfd;
bool send_msgs = false;
while ((s = getopt(argc, argv, "hs")) != -1) {
switch (s) {
case 's':
send_msgs = true;
break;
case 'h':
usage();
return 0;
default:
/* getopt() outputs an error for us */
usage();
return 1;
}
}
if (argc != optind) {
out = fopen(argv[optind], "a+");
if (!out) {
ulog("Unable to open %s for writing: %s\n",
argv[1], strerror(errno));
out = stdout;
}
} else
out = stdout;
memset(buf, 0, sizeof(buf));
s = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_CONNECTOR);
if (s == -1) {
perror("socket");
return -1;
}
l_local.nl_family = AF_NETLINK;
l_local.nl_groups = -1; /* bitmask of requested groups */
l_local.nl_pid = 0;
ulog("subscribing to %u.%u\n", CN_TEST_IDX, CN_TEST_VAL);
if (bind(s, (struct sockaddr *)&l_local, sizeof(struct sockaddr_nl)) == -1) {
perror("bind");
close(s);
return -1;
}
#if 0
{
int on = 0x57; /* Additional group number */
setsockopt(s, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &on, sizeof(on));
}
#endif
if (send_msgs) {
int i, j;
memset(buf, 0, sizeof(buf));
data = (struct cn_msg *)buf;
data->id.idx = CN_TEST_IDX;
data->id.val = CN_TEST_VAL;
data->seq = seq++;
data->ack = 0;
data->len = 0;
for (j=0; j<10; ++j) {
for (i=0; i<1000; ++i) {
len = netlink_send(s, data);
}
ulog("%d messages have been sent to %08x.%08x.\n", i, data->id.idx, data->id.val);
}
return 0;
}
pfd.fd = s;
while (!need_exit) {
pfd.events = POLLIN;
pfd.revents = 0;
switch (poll(&pfd, 1, -1)) {
case 0:
need_exit = 1;
break;
case -1:
if (errno != EINTR) {
need_exit = 1;
break;
}
continue;
}
if (need_exit)
break;
memset(buf, 0, sizeof(buf));
len = recv(s, buf, sizeof(buf), 0);
if (len == -1) {
perror("recv buf");
close(s);
return -1;
}
reply = (struct nlmsghdr *)buf;
switch (reply->nlmsg_type) {
case NLMSG_ERROR:
fprintf(out, "Error message received.\n");
fflush(out);
break;
case NLMSG_DONE:
data = (struct cn_msg *)NLMSG_DATA(reply);
time(&tm);
fprintf(out, "%.24s : [%x.%x] [%08u.%08u].\n",
ctime(&tm), data->id.idx, data->id.val, data->seq, data->ack);
fflush(out);
break;
default:
break;
}
}
close(s);
return 0;
}
| gpl-2.0 |
Rashed97/android_kernel_samsung_lt03lte | Documentation/connector/ucon.c | 12086 | 5237 | /*
* ucon.c
*
* Copyright (c) 2004+ Evgeniy Polyakov <zbr@ioremap.net>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <asm/types.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/poll.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <arpa/inet.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <getopt.h>
#include <linux/connector.h>
#define DEBUG
#define NETLINK_CONNECTOR 11
/* Hopefully your userspace connector.h matches this kernel */
#define CN_TEST_IDX CN_NETLINK_USERS + 3
#define CN_TEST_VAL 0x456
#ifdef DEBUG
#define ulog(f, a...) fprintf(stdout, f, ##a)
#else
#define ulog(f, a...) do {} while (0)
#endif
static int need_exit;
static __u32 seq;
static int netlink_send(int s, struct cn_msg *msg)
{
struct nlmsghdr *nlh;
unsigned int size;
int err;
char buf[128];
struct cn_msg *m;
size = NLMSG_SPACE(sizeof(struct cn_msg) + msg->len);
nlh = (struct nlmsghdr *)buf;
nlh->nlmsg_seq = seq++;
nlh->nlmsg_pid = getpid();
nlh->nlmsg_type = NLMSG_DONE;
nlh->nlmsg_len = NLMSG_LENGTH(size - sizeof(*nlh));
nlh->nlmsg_flags = 0;
m = NLMSG_DATA(nlh);
#if 0
ulog("%s: [%08x.%08x] len=%u, seq=%u, ack=%u.\n",
__func__, msg->id.idx, msg->id.val, msg->len, msg->seq, msg->ack);
#endif
memcpy(m, msg, sizeof(*m) + msg->len);
err = send(s, nlh, size, 0);
if (err == -1)
ulog("Failed to send: %s [%d].\n",
strerror(errno), errno);
return err;
}
static void usage(void)
{
printf(
"Usage: ucon [options] [output file]\n"
"\n"
"\t-h\tthis help screen\n"
"\t-s\tsend buffers to the test module\n"
"\n"
"The default behavior of ucon is to subscribe to the test module\n"
"and wait for state messages. Any ones received are dumped to the\n"
"specified output file (or stdout). The test module is assumed to\n"
"have an id of {%u.%u}\n"
"\n"
"If you get no output, then verify the cn_test module id matches\n"
"the expected id above.\n"
, CN_TEST_IDX, CN_TEST_VAL
);
}
int main(int argc, char *argv[])
{
int s;
char buf[1024];
int len;
struct nlmsghdr *reply;
struct sockaddr_nl l_local;
struct cn_msg *data;
FILE *out;
time_t tm;
struct pollfd pfd;
bool send_msgs = false;
while ((s = getopt(argc, argv, "hs")) != -1) {
switch (s) {
case 's':
send_msgs = true;
break;
case 'h':
usage();
return 0;
default:
/* getopt() outputs an error for us */
usage();
return 1;
}
}
if (argc != optind) {
out = fopen(argv[optind], "a+");
if (!out) {
ulog("Unable to open %s for writing: %s\n",
argv[1], strerror(errno));
out = stdout;
}
} else
out = stdout;
memset(buf, 0, sizeof(buf));
s = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_CONNECTOR);
if (s == -1) {
perror("socket");
return -1;
}
l_local.nl_family = AF_NETLINK;
l_local.nl_groups = -1; /* bitmask of requested groups */
l_local.nl_pid = 0;
ulog("subscribing to %u.%u\n", CN_TEST_IDX, CN_TEST_VAL);
if (bind(s, (struct sockaddr *)&l_local, sizeof(struct sockaddr_nl)) == -1) {
perror("bind");
close(s);
return -1;
}
#if 0
{
int on = 0x57; /* Additional group number */
setsockopt(s, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &on, sizeof(on));
}
#endif
if (send_msgs) {
int i, j;
memset(buf, 0, sizeof(buf));
data = (struct cn_msg *)buf;
data->id.idx = CN_TEST_IDX;
data->id.val = CN_TEST_VAL;
data->seq = seq++;
data->ack = 0;
data->len = 0;
for (j=0; j<10; ++j) {
for (i=0; i<1000; ++i) {
len = netlink_send(s, data);
}
ulog("%d messages have been sent to %08x.%08x.\n", i, data->id.idx, data->id.val);
}
return 0;
}
pfd.fd = s;
while (!need_exit) {
pfd.events = POLLIN;
pfd.revents = 0;
switch (poll(&pfd, 1, -1)) {
case 0:
need_exit = 1;
break;
case -1:
if (errno != EINTR) {
need_exit = 1;
break;
}
continue;
}
if (need_exit)
break;
memset(buf, 0, sizeof(buf));
len = recv(s, buf, sizeof(buf), 0);
if (len == -1) {
perror("recv buf");
close(s);
return -1;
}
reply = (struct nlmsghdr *)buf;
switch (reply->nlmsg_type) {
case NLMSG_ERROR:
fprintf(out, "Error message received.\n");
fflush(out);
break;
case NLMSG_DONE:
data = (struct cn_msg *)NLMSG_DATA(reply);
time(&tm);
fprintf(out, "%.24s : [%x.%x] [%08u.%08u].\n",
ctime(&tm), data->id.idx, data->id.val, data->seq, data->ack);
fflush(out);
break;
default:
break;
}
}
close(s);
return 0;
}
| gpl-2.0 |
weizhenwei/mi1_kernel | arch/sh/drivers/pci/pci-sh7751.c | 12342 | 5481 | /*
* Low-Level PCI Support for the SH7751
*
* Copyright (C) 2003 - 2009 Paul Mundt
* Copyright (C) 2001 Dustin McIntire
*
* With cleanup by Paul van Gool <pvangool@mimotech.com>, 2003.
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/io.h>
#include "pci-sh4.h"
#include <asm/addrspace.h>
#include <asm/sizes.h>
static int __init __area_sdram_check(struct pci_channel *chan,
unsigned int area)
{
unsigned long word;
word = __raw_readl(SH7751_BCR1);
/* check BCR for SDRAM in area */
if (((word >> area) & 1) == 0) {
printk("PCI: Area %d is not configured for SDRAM. BCR1=0x%lx\n",
area, word);
return 0;
}
pci_write_reg(chan, word, SH4_PCIBCR1);
word = __raw_readw(SH7751_BCR2);
/* check BCR2 for 32bit SDRAM interface*/
if (((word >> (area << 1)) & 0x3) != 0x3) {
printk("PCI: Area %d is not 32 bit SDRAM. BCR2=0x%lx\n",
area, word);
return 0;
}
pci_write_reg(chan, word, SH4_PCIBCR2);
return 1;
}
static struct resource sh7751_pci_resources[] = {
{
.name = "SH7751_IO",
.start = 0x1000,
.end = SZ_4M - 1,
.flags = IORESOURCE_IO
}, {
.name = "SH7751_mem",
.start = SH7751_PCI_MEMORY_BASE,
.end = SH7751_PCI_MEMORY_BASE + SH7751_PCI_MEM_SIZE - 1,
.flags = IORESOURCE_MEM
},
};
static struct pci_channel sh7751_pci_controller = {
.pci_ops = &sh4_pci_ops,
.resources = sh7751_pci_resources,
.nr_resources = ARRAY_SIZE(sh7751_pci_resources),
.mem_offset = 0x00000000,
.io_offset = 0x00000000,
.io_map_base = SH7751_PCI_IO_BASE,
};
static struct sh4_pci_address_map sh7751_pci_map = {
.window0 = {
.base = SH7751_CS3_BASE_ADDR,
.size = 0x04000000,
},
};
static int __init sh7751_pci_init(void)
{
struct pci_channel *chan = &sh7751_pci_controller;
unsigned int id;
u32 word, reg;
printk(KERN_NOTICE "PCI: Starting initialization.\n");
chan->reg_base = 0xfe200000;
/* check for SH7751/SH7751R hardware */
id = pci_read_reg(chan, SH7751_PCICONF0);
if (id != ((SH7751_DEVICE_ID << 16) | SH7751_VENDOR_ID) &&
id != ((SH7751R_DEVICE_ID << 16) | SH7751_VENDOR_ID)) {
pr_debug("PCI: This is not an SH7751(R) (%x)\n", id);
return -ENODEV;
}
/* Set the BCR's to enable PCI access */
reg = __raw_readl(SH7751_BCR1);
reg |= 0x80000;
__raw_writel(reg, SH7751_BCR1);
/* Turn the clocks back on (not done in reset)*/
pci_write_reg(chan, 0, SH4_PCICLKR);
/* Clear Powerdown IRQ's (not done in reset) */
word = SH4_PCIPINT_D3 | SH4_PCIPINT_D0;
pci_write_reg(chan, word, SH4_PCIPINT);
/* set the command/status bits to:
* Wait Cycle Control + Parity Enable + Bus Master +
* Mem space enable
*/
word = SH7751_PCICONF1_WCC | SH7751_PCICONF1_PER |
SH7751_PCICONF1_BUM | SH7751_PCICONF1_MES;
pci_write_reg(chan, word, SH7751_PCICONF1);
/* define this host as the host bridge */
word = PCI_BASE_CLASS_BRIDGE << 24;
pci_write_reg(chan, word, SH7751_PCICONF2);
/* Set IO and Mem windows to local address
* Make PCI and local address the same for easy 1 to 1 mapping
*/
word = sh7751_pci_map.window0.size - 1;
pci_write_reg(chan, word, SH4_PCILSR0);
/* Set the values on window 0 PCI config registers */
word = P2SEGADDR(sh7751_pci_map.window0.base);
pci_write_reg(chan, word, SH4_PCILAR0);
pci_write_reg(chan, word, SH7751_PCICONF5);
/* Set the local 16MB PCI memory space window to
* the lowest PCI mapped address
*/
word = chan->resources[1].start & SH4_PCIMBR_MASK;
pr_debug("PCI: Setting upper bits of Memory window to 0x%x\n", word);
pci_write_reg(chan, word , SH4_PCIMBR);
/* Make sure the MSB's of IO window are set to access PCI space
* correctly */
word = chan->resources[0].start & SH4_PCIIOBR_MASK;
pr_debug("PCI: Setting upper bits of IO window to 0x%x\n", word);
pci_write_reg(chan, word, SH4_PCIIOBR);
/* Set PCI WCRx, BCRx's, copy from BSC locations */
/* check BCR for SDRAM in specified area */
switch (sh7751_pci_map.window0.base) {
case SH7751_CS0_BASE_ADDR: word = __area_sdram_check(chan, 0); break;
case SH7751_CS1_BASE_ADDR: word = __area_sdram_check(chan, 1); break;
case SH7751_CS2_BASE_ADDR: word = __area_sdram_check(chan, 2); break;
case SH7751_CS3_BASE_ADDR: word = __area_sdram_check(chan, 3); break;
case SH7751_CS4_BASE_ADDR: word = __area_sdram_check(chan, 4); break;
case SH7751_CS5_BASE_ADDR: word = __area_sdram_check(chan, 5); break;
case SH7751_CS6_BASE_ADDR: word = __area_sdram_check(chan, 6); break;
}
if (!word)
return -1;
/* configure the wait control registers */
word = __raw_readl(SH7751_WCR1);
pci_write_reg(chan, word, SH4_PCIWCR1);
word = __raw_readl(SH7751_WCR2);
pci_write_reg(chan, word, SH4_PCIWCR2);
word = __raw_readl(SH7751_WCR3);
pci_write_reg(chan, word, SH4_PCIWCR3);
word = __raw_readl(SH7751_MCR);
pci_write_reg(chan, word, SH4_PCIMCR);
/* NOTE: I'm ignoring the PCI error IRQs for now..
* TODO: add support for the internal error interrupts and
* DMA interrupts...
*/
pci_fixup_pcic(chan);
/* SH7751 init done, set central function init complete */
/* use round robin mode to stop a device starving/overruning */
word = SH4_PCICR_PREFIX | SH4_PCICR_CFIN | SH4_PCICR_ARBM;
pci_write_reg(chan, word, SH4_PCICR);
return register_pci_controller(chan);
}
arch_initcall(sh7751_pci_init);
| gpl-2.0 |
ipodtouchdude/linux-amlogic | drivers/misc/sgi-xp/xp_sn2.c | 14134 | 4676 | /*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
* Copyright (c) 2008 Silicon Graphics, Inc. All Rights Reserved.
*/
/*
* Cross Partition (XP) sn2-based functions.
*
* Architecture specific implementation of common functions.
*/
#include <linux/module.h>
#include <linux/device.h>
#include <asm/sn/bte.h>
#include <asm/sn/sn_sal.h>
#include "xp.h"
/*
* The export of xp_nofault_PIOR needs to happen here since it is defined
* in drivers/misc/sgi-xp/xp_nofault.S. The target of the nofault read is
* defined here.
*/
EXPORT_SYMBOL_GPL(xp_nofault_PIOR);
u64 xp_nofault_PIOR_target;
EXPORT_SYMBOL_GPL(xp_nofault_PIOR_target);
/*
* Register a nofault code region which performs a cross-partition PIO read.
* If the PIO read times out, the MCA handler will consume the error and
* return to a kernel-provided instruction to indicate an error. This PIO read
* exists because it is guaranteed to timeout if the destination is down
* (amo operations do not timeout on at least some CPUs on Shubs <= v1.2,
* which unfortunately we have to work around).
*/
static enum xp_retval
xp_register_nofault_code_sn2(void)
{
int ret;
u64 func_addr;
u64 err_func_addr;
func_addr = *(u64 *)xp_nofault_PIOR;
err_func_addr = *(u64 *)xp_error_PIOR;
ret = sn_register_nofault_code(func_addr, err_func_addr, err_func_addr,
1, 1);
if (ret != 0) {
dev_err(xp, "can't register nofault code, error=%d\n", ret);
return xpSalError;
}
/*
* Setup the nofault PIO read target. (There is no special reason why
* SH_IPI_ACCESS was selected.)
*/
if (is_shub1())
xp_nofault_PIOR_target = SH1_IPI_ACCESS;
else if (is_shub2())
xp_nofault_PIOR_target = SH2_IPI_ACCESS0;
return xpSuccess;
}
static void
xp_unregister_nofault_code_sn2(void)
{
u64 func_addr = *(u64 *)xp_nofault_PIOR;
u64 err_func_addr = *(u64 *)xp_error_PIOR;
/* unregister the PIO read nofault code region */
(void)sn_register_nofault_code(func_addr, err_func_addr,
err_func_addr, 1, 0);
}
/*
* Convert a virtual memory address to a physical memory address.
*/
static unsigned long
xp_pa_sn2(void *addr)
{
return __pa(addr);
}
/*
* Convert a global physical to a socket physical address.
*/
static unsigned long
xp_socket_pa_sn2(unsigned long gpa)
{
return gpa;
}
/*
* Wrapper for bte_copy().
*
* dst_pa - physical address of the destination of the transfer.
* src_pa - physical address of the source of the transfer.
* len - number of bytes to transfer from source to destination.
*
* Note: xp_remote_memcpy_sn2() should never be called while holding a spinlock.
*/
static enum xp_retval
xp_remote_memcpy_sn2(unsigned long dst_pa, const unsigned long src_pa,
size_t len)
{
bte_result_t ret;
ret = bte_copy(src_pa, dst_pa, len, (BTE_NOTIFY | BTE_WACQUIRE), NULL);
if (ret == BTE_SUCCESS)
return xpSuccess;
if (is_shub2()) {
dev_err(xp, "bte_copy() on shub2 failed, error=0x%x dst_pa="
"0x%016lx src_pa=0x%016lx len=%ld\\n", ret, dst_pa,
src_pa, len);
} else {
dev_err(xp, "bte_copy() failed, error=%d dst_pa=0x%016lx "
"src_pa=0x%016lx len=%ld\\n", ret, dst_pa, src_pa, len);
}
return xpBteCopyError;
}
static int
xp_cpu_to_nasid_sn2(int cpuid)
{
return cpuid_to_nasid(cpuid);
}
static enum xp_retval
xp_expand_memprotect_sn2(unsigned long phys_addr, unsigned long size)
{
u64 nasid_array = 0;
int ret;
ret = sn_change_memprotect(phys_addr, size, SN_MEMPROT_ACCESS_CLASS_1,
&nasid_array);
if (ret != 0) {
dev_err(xp, "sn_change_memprotect(,, "
"SN_MEMPROT_ACCESS_CLASS_1,) failed ret=%d\n", ret);
return xpSalError;
}
return xpSuccess;
}
static enum xp_retval
xp_restrict_memprotect_sn2(unsigned long phys_addr, unsigned long size)
{
u64 nasid_array = 0;
int ret;
ret = sn_change_memprotect(phys_addr, size, SN_MEMPROT_ACCESS_CLASS_0,
&nasid_array);
if (ret != 0) {
dev_err(xp, "sn_change_memprotect(,, "
"SN_MEMPROT_ACCESS_CLASS_0,) failed ret=%d\n", ret);
return xpSalError;
}
return xpSuccess;
}
enum xp_retval
xp_init_sn2(void)
{
BUG_ON(!is_shub());
xp_max_npartitions = XP_MAX_NPARTITIONS_SN2;
xp_partition_id = sn_partition_id;
xp_region_size = sn_region_size;
xp_pa = xp_pa_sn2;
xp_socket_pa = xp_socket_pa_sn2;
xp_remote_memcpy = xp_remote_memcpy_sn2;
xp_cpu_to_nasid = xp_cpu_to_nasid_sn2;
xp_expand_memprotect = xp_expand_memprotect_sn2;
xp_restrict_memprotect = xp_restrict_memprotect_sn2;
return xp_register_nofault_code_sn2();
}
void
xp_exit_sn2(void)
{
BUG_ON(!is_shub());
xp_unregister_nofault_code_sn2();
}
| gpl-2.0 |
lijinc/linux-source-3.11.0 | arch/arm/mach-at91/at91sam9rl.c | 55 | 9086 | /*
* arch/arm/mach-at91/at91sam9rl.c
*
* Copyright (C) 2005 SAN People
* Copyright (C) 2007 Atmel Corporation
*
* 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/proc-fns.h>
#include <asm/irq.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/system_misc.h>
#include <mach/cpu.h>
#include <mach/at91_dbgu.h>
#include <mach/at91sam9rl.h>
#include <mach/at91_pmc.h>
#include "at91_aic.h"
#include "at91_rstc.h"
#include "soc.h"
#include "generic.h"
#include "clock.h"
#include "sam9_smc.h"
/* --------------------------------------------------------------------
* Clocks
* -------------------------------------------------------------------- */
/*
* The peripheral clocks.
*/
static struct clk pioA_clk = {
.name = "pioA_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_PIOA,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk pioB_clk = {
.name = "pioB_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_PIOB,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk pioC_clk = {
.name = "pioC_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_PIOC,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk pioD_clk = {
.name = "pioD_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_PIOD,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk usart0_clk = {
.name = "usart0_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_US0,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk usart1_clk = {
.name = "usart1_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_US1,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk usart2_clk = {
.name = "usart2_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_US2,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk usart3_clk = {
.name = "usart3_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_US3,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk mmc_clk = {
.name = "mci_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_MCI,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk twi0_clk = {
.name = "twi0_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_TWI0,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk twi1_clk = {
.name = "twi1_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_TWI1,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk spi_clk = {
.name = "spi_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_SPI,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk ssc0_clk = {
.name = "ssc0_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_SSC0,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk ssc1_clk = {
.name = "ssc1_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_SSC1,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk tc0_clk = {
.name = "tc0_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_TC0,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk tc1_clk = {
.name = "tc1_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_TC1,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk tc2_clk = {
.name = "tc2_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_TC2,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk pwm_clk = {
.name = "pwm_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_PWMC,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk tsc_clk = {
.name = "tsc_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_TSC,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk dma_clk = {
.name = "dma_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_DMA,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk udphs_clk = {
.name = "udphs_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_UDPHS,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk lcdc_clk = {
.name = "lcdc_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_LCDC,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk ac97_clk = {
.name = "ac97_clk",
.pmc_mask = 1 << AT91SAM9RL_ID_AC97C,
.type = CLK_TYPE_PERIPHERAL,
};
static struct clk *periph_clocks[] __initdata = {
&pioA_clk,
&pioB_clk,
&pioC_clk,
&pioD_clk,
&usart0_clk,
&usart1_clk,
&usart2_clk,
&usart3_clk,
&mmc_clk,
&twi0_clk,
&twi1_clk,
&spi_clk,
&ssc0_clk,
&ssc1_clk,
&tc0_clk,
&tc1_clk,
&tc2_clk,
&pwm_clk,
&tsc_clk,
&dma_clk,
&udphs_clk,
&lcdc_clk,
&ac97_clk,
// irq0
};
static struct clk_lookup periph_clocks_lookups[] = {
CLKDEV_CON_DEV_ID("hclk", "at91sam9rl-lcdfb.0", &lcdc_clk),
CLKDEV_CON_DEV_ID("hclk", "atmel_usba_udc", &utmi_clk),
CLKDEV_CON_DEV_ID("pclk", "atmel_usba_udc", &udphs_clk),
CLKDEV_CON_DEV_ID("t0_clk", "atmel_tcb.0", &tc0_clk),
CLKDEV_CON_DEV_ID("t1_clk", "atmel_tcb.0", &tc1_clk),
CLKDEV_CON_DEV_ID("t2_clk", "atmel_tcb.0", &tc2_clk),
CLKDEV_CON_DEV_ID("pclk", "at91rm9200_ssc.0", &ssc0_clk),
CLKDEV_CON_DEV_ID("pclk", "at91rm9200_ssc.1", &ssc1_clk),
CLKDEV_CON_DEV_ID("pclk", "fffc0000.ssc", &ssc0_clk),
CLKDEV_CON_DEV_ID("pclk", "fffc4000.ssc", &ssc1_clk),
CLKDEV_CON_DEV_ID(NULL, "i2c-at91sam9g20.0", &twi0_clk),
CLKDEV_CON_DEV_ID(NULL, "i2c-at91sam9g20.1", &twi1_clk),
CLKDEV_CON_ID("pioA", &pioA_clk),
CLKDEV_CON_ID("pioB", &pioB_clk),
CLKDEV_CON_ID("pioC", &pioC_clk),
CLKDEV_CON_ID("pioD", &pioD_clk),
};
static struct clk_lookup usart_clocks_lookups[] = {
CLKDEV_CON_DEV_ID("usart", "atmel_usart.0", &mck),
CLKDEV_CON_DEV_ID("usart", "atmel_usart.1", &usart0_clk),
CLKDEV_CON_DEV_ID("usart", "atmel_usart.2", &usart1_clk),
CLKDEV_CON_DEV_ID("usart", "atmel_usart.3", &usart2_clk),
CLKDEV_CON_DEV_ID("usart", "atmel_usart.4", &usart3_clk),
};
/*
* The two programmable clocks.
* You must configure pin multiplexing to bring these signals out.
*/
static struct clk pck0 = {
.name = "pck0",
.pmc_mask = AT91_PMC_PCK0,
.type = CLK_TYPE_PROGRAMMABLE,
.id = 0,
};
static struct clk pck1 = {
.name = "pck1",
.pmc_mask = AT91_PMC_PCK1,
.type = CLK_TYPE_PROGRAMMABLE,
.id = 1,
};
static void __init at91sam9rl_register_clocks(void)
{
int i;
for (i = 0; i < ARRAY_SIZE(periph_clocks); i++)
clk_register(periph_clocks[i]);
clkdev_add_table(periph_clocks_lookups,
ARRAY_SIZE(periph_clocks_lookups));
clkdev_add_table(usart_clocks_lookups,
ARRAY_SIZE(usart_clocks_lookups));
clk_register(&pck0);
clk_register(&pck1);
}
/* --------------------------------------------------------------------
* GPIO
* -------------------------------------------------------------------- */
static struct at91_gpio_bank at91sam9rl_gpio[] __initdata = {
{
.id = AT91SAM9RL_ID_PIOA,
.regbase = AT91SAM9RL_BASE_PIOA,
}, {
.id = AT91SAM9RL_ID_PIOB,
.regbase = AT91SAM9RL_BASE_PIOB,
}, {
.id = AT91SAM9RL_ID_PIOC,
.regbase = AT91SAM9RL_BASE_PIOC,
}, {
.id = AT91SAM9RL_ID_PIOD,
.regbase = AT91SAM9RL_BASE_PIOD,
}
};
/* --------------------------------------------------------------------
* AT91SAM9RL processor initialization
* -------------------------------------------------------------------- */
static void __init at91sam9rl_map_io(void)
{
unsigned long sram_size;
switch (at91_soc_initdata.cidr & AT91_CIDR_SRAMSIZ) {
case AT91_CIDR_SRAMSIZ_32K:
sram_size = 2 * SZ_16K;
break;
case AT91_CIDR_SRAMSIZ_16K:
default:
sram_size = SZ_16K;
}
/* Map SRAM */
at91_init_sram(0, AT91SAM9RL_SRAM_BASE, sram_size);
}
static void __init at91sam9rl_ioremap_registers(void)
{
at91_ioremap_shdwc(AT91SAM9RL_BASE_SHDWC);
at91_ioremap_rstc(AT91SAM9RL_BASE_RSTC);
at91_ioremap_ramc(0, AT91SAM9RL_BASE_SDRAMC, 512);
at91sam926x_ioremap_pit(AT91SAM9RL_BASE_PIT);
at91sam9_ioremap_smc(0, AT91SAM9RL_BASE_SMC);
at91_ioremap_matrix(AT91SAM9RL_BASE_MATRIX);
}
static void __init at91sam9rl_initialize(void)
{
arm_pm_idle = at91sam9_idle;
arm_pm_restart = at91sam9_alt_restart;
at91_sysirq_mask_rtc(AT91SAM9RL_BASE_RTC);
at91_sysirq_mask_rtt(AT91SAM9RL_BASE_RTT);
/* Register GPIO subsystem */
at91_gpio_init(at91sam9rl_gpio, 4);
}
/* --------------------------------------------------------------------
* Interrupt initialization
* -------------------------------------------------------------------- */
/*
* The default interrupt priority levels (0 = lowest, 7 = highest).
*/
static unsigned int at91sam9rl_default_irq_priority[NR_AIC_IRQS] __initdata = {
7, /* Advanced Interrupt Controller */
7, /* System Peripherals */
1, /* Parallel IO Controller A */
1, /* Parallel IO Controller B */
1, /* Parallel IO Controller C */
1, /* Parallel IO Controller D */
5, /* USART 0 */
5, /* USART 1 */
5, /* USART 2 */
5, /* USART 3 */
0, /* Multimedia Card Interface */
6, /* Two-Wire Interface 0 */
6, /* Two-Wire Interface 1 */
5, /* Serial Peripheral Interface */
4, /* Serial Synchronous Controller 0 */
4, /* Serial Synchronous Controller 1 */
0, /* Timer Counter 0 */
0, /* Timer Counter 1 */
0, /* Timer Counter 2 */
0,
0, /* Touch Screen Controller */
0, /* DMA Controller */
2, /* USB Device High speed port */
2, /* LCD Controller */
6, /* AC97 Controller */
0,
0,
0,
0,
0,
0,
0, /* Advanced Interrupt Controller */
};
AT91_SOC_START(at91sam9rl)
.map_io = at91sam9rl_map_io,
.default_irq_priority = at91sam9rl_default_irq_priority,
.extern_irq = (1 << AT91SAM9RL_ID_IRQ0),
.ioremap_registers = at91sam9rl_ioremap_registers,
.register_clocks = at91sam9rl_register_clocks,
.init = at91sam9rl_initialize,
AT91_SOC_END
| gpl-2.0 |
openwrt-es/linux | drivers/rtc/rtc-au1xxx.c | 55 | 3149 | /*
* Au1xxx counter0 (aka Time-Of-Year counter) RTC interface driver.
*
* Copyright (C) 2008 Manuel Lauss <mano@roarinelk.homelinux.net>
*
* 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.
*/
/* All current Au1xxx SoCs have 2 counters fed by an external 32.768 kHz
* crystal. Counter 0, which keeps counting during sleep/powerdown, is
* used to count seconds since the beginning of the unix epoch.
*
* The counters must be configured and enabled by bootloader/board code;
* no checks as to whether they really get a proper 32.768kHz clock are
* made as this would take far too long.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/rtc.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <asm/mach-au1x00/au1000.h>
/* 32kHz clock enabled and detected */
#define CNTR_OK (SYS_CNTRL_E0 | SYS_CNTRL_32S)
static int au1xtoy_rtc_read_time(struct device *dev, struct rtc_time *tm)
{
unsigned long t;
t = alchemy_rdsys(AU1000_SYS_TOYREAD);
rtc_time64_to_tm(t, tm);
return 0;
}
static int au1xtoy_rtc_set_time(struct device *dev, struct rtc_time *tm)
{
unsigned long t;
t = rtc_tm_to_time64(tm);
alchemy_wrsys(t, AU1000_SYS_TOYWRITE);
/* wait for the pending register write to succeed. This can
* take up to 6 seconds...
*/
while (alchemy_rdsys(AU1000_SYS_CNTRCTRL) & SYS_CNTRL_C0S)
msleep(1);
return 0;
}
static const struct rtc_class_ops au1xtoy_rtc_ops = {
.read_time = au1xtoy_rtc_read_time,
.set_time = au1xtoy_rtc_set_time,
};
static int au1xtoy_rtc_probe(struct platform_device *pdev)
{
struct rtc_device *rtcdev;
unsigned long t;
t = alchemy_rdsys(AU1000_SYS_CNTRCTRL);
if (!(t & CNTR_OK)) {
dev_err(&pdev->dev, "counters not working; aborting.\n");
return -ENODEV;
}
/* set counter0 tickrate to 1Hz if necessary */
if (alchemy_rdsys(AU1000_SYS_TOYTRIM) != 32767) {
/* wait until hardware gives access to TRIM register */
t = 0x00100000;
while ((alchemy_rdsys(AU1000_SYS_CNTRCTRL) & SYS_CNTRL_T0S) && --t)
msleep(1);
if (!t) {
/* timed out waiting for register access; assume
* counters are unusable.
*/
dev_err(&pdev->dev, "timeout waiting for access\n");
return -ETIMEDOUT;
}
/* set 1Hz TOY tick rate */
alchemy_wrsys(32767, AU1000_SYS_TOYTRIM);
}
/* wait until the hardware allows writes to the counter reg */
while (alchemy_rdsys(AU1000_SYS_CNTRCTRL) & SYS_CNTRL_C0S)
msleep(1);
rtcdev = devm_rtc_allocate_device(&pdev->dev);
if (IS_ERR(rtcdev))
return PTR_ERR(rtcdev);
rtcdev->ops = &au1xtoy_rtc_ops;
rtcdev->range_max = U32_MAX;
platform_set_drvdata(pdev, rtcdev);
return devm_rtc_register_device(rtcdev);
}
static struct platform_driver au1xrtc_driver = {
.driver = {
.name = "rtc-au1xxx",
},
};
module_platform_driver_probe(au1xrtc_driver, au1xtoy_rtc_probe);
MODULE_DESCRIPTION("Au1xxx TOY-counter-based RTC driver");
MODULE_AUTHOR("Manuel Lauss <manuel.lauss@gmail.com>");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:rtc-au1xxx");
| gpl-2.0 |
TeamWin/kernel_samsung_lt02ltetmo | arch/arm/mach-msm/devices-8064.c | 55 | 90260 | /* Copyright (c) 2011-2013, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/platform_device.h>
#include <linux/msm_rotator.h>
#include <linux/gpio.h>
#include <linux/clkdev.h>
#include <linux/dma-mapping.h>
#include <linux/coresight.h>
#include <mach/irqs-8064.h>
#include <mach/board.h>
#include <mach/msm_iomap.h>
#include <mach/usbdiag.h>
#include <mach/msm_sps.h>
#include <mach/dma.h>
#include <mach/msm_dsps.h>
#include <mach/clk-provider.h>
#include <sound/msm-dai-q6.h>
#include <sound/apr_audio.h>
#include <mach/msm_tsif.h>
#include <mach/msm_tspp.h>
#include <mach/msm_bus_board.h>
#include <mach/rpm.h>
#include <mach/mdm2.h>
#include <mach/msm_smd.h>
#include <mach/msm_dcvs.h>
#include <mach/msm_rtb.h>
#include <linux/msm_ion.h>
#include "clock.h"
#include "pm.h"
#include "devices.h"
#include "footswitch.h"
#include "msm_watchdog.h"
#include "rpm_stats.h"
#include "rpm_log.h"
#include "board-8064.h"
#include <mach/mpm.h>
#include <mach/iommu_domains.h>
#include <mach/msm_cache_dump.h>
/* Address of GSBI blocks */
#define MSM_GSBI1_PHYS 0x12440000
#define MSM_GSBI2_PHYS 0x12480000
#define MSM_GSBI3_PHYS 0x16200000
#define MSM_GSBI4_PHYS 0x16300000
#define MSM_GSBI5_PHYS 0x1A200000
#define MSM_GSBI6_PHYS 0x16500000
#define MSM_GSBI7_PHYS 0x16600000
/* GSBI UART devices */
#define MSM_UART1DM_PHYS (MSM_GSBI1_PHYS + 0x10000)
#define MSM_UART3DM_PHYS (MSM_GSBI3_PHYS + 0x40000)
#define MSM_UART4DM_PHYS (MSM_GSBI4_PHYS + 0x40000)
#define MSM_UART6DM_PHYS (MSM_GSBI6_PHYS + 0x40000)
#define MSM_UART7DM_PHYS (MSM_GSBI7_PHYS + 0x40000)
/* GSBI QUP devices */
#define MSM_GSBI1_QUP_PHYS (MSM_GSBI1_PHYS + 0x20000)
#define MSM_GSBI2_QUP_PHYS (MSM_GSBI2_PHYS + 0x20000)
#define MSM_GSBI3_QUP_PHYS (MSM_GSBI3_PHYS + 0x80000)
#define MSM_GSBI4_QUP_PHYS (MSM_GSBI4_PHYS + 0x80000)
#define MSM_GSBI5_QUP_PHYS (MSM_GSBI5_PHYS + 0x80000)
#define MSM_GSBI6_QUP_PHYS (MSM_GSBI6_PHYS + 0x80000)
#define MSM_GSBI7_QUP_PHYS (MSM_GSBI7_PHYS + 0x80000)
#define MSM_QUP_SIZE SZ_4K
/* BT HS UART Configuration for BRCM BT*/
#ifdef CONFIG_SERIAL_MSM_HS
#define INT_UART1DM_IRQ GSBI6_UARTDM_IRQ
#define DMOV_HSUART1_TX_CHAN 8
#define DMOV_HSUART1_TX_CRCI 6
#define DMOV_HSUART1_RX_CHAN 7
#define DMOV_HSUART1_RX_CRCI 11
#endif
/* Address of SSBI CMD */
#define MSM_PMIC1_SSBI_CMD_PHYS 0x00500000
#define MSM_PMIC2_SSBI_CMD_PHYS 0x00C00000
#define MSM_PMIC_SSBI_SIZE SZ_4K
/* Address of HS USBOTG1 */
#define MSM_HSUSB1_PHYS 0x12500000
#define MSM_HSUSB1_SIZE SZ_4K
/* Address of HS USB3 */
#define MSM_HSUSB3_PHYS 0x12520000
#define MSM_HSUSB3_SIZE SZ_4K
/* Address of HS USB4 */
#define MSM_HSUSB4_PHYS 0x12530000
#define MSM_HSUSB4_SIZE SZ_4K
/* Address of PCIE20 PARF */
#define PCIE20_PARF_PHYS 0x1b600000
#define PCIE20_PARF_SIZE SZ_128
/* Address of PCIE20 ELBI */
#define PCIE20_ELBI_PHYS 0x1b502000
#define PCIE20_ELBI_SIZE SZ_256
/* Address of PCIE20 */
#define PCIE20_PHYS 0x1b500000
#define PCIE20_SIZE SZ_4K
#define MSM8064_RPM_MASTER_STATS_BASE 0x10BB00
#define MSM8064_PC_CNTR_PHYS (APQ8064_IMEM_PHYS + 0x664)
#define MSM8064_PC_CNTR_SIZE 0x40
#define GPIO_CAM_SPI_MOSI 51
#define GPIO_CAM_SPI_MISO 52
#define GPIO_CAM_SPI_SSN 53
#define GPIO_CAM_SPI_SCLK 54
static struct resource msm8064_resources_pccntr[] = {
{
.start = MSM8064_PC_CNTR_PHYS,
.end = MSM8064_PC_CNTR_PHYS + MSM8064_PC_CNTR_SIZE,
.flags = IORESOURCE_MEM,
},
};
struct platform_device msm8064_pc_cntr = {
.name = "pc-cntr",
.id = -1,
.num_resources = ARRAY_SIZE(msm8064_resources_pccntr),
.resource = msm8064_resources_pccntr,
};
static struct msm_pm_sleep_status_data msm_pm_slp_sts_data = {
.base_addr = MSM_ACC0_BASE + 0x08,
.cpu_offset = MSM_ACC1_BASE - MSM_ACC0_BASE,
.mask = 1UL << 13,
};
struct platform_device msm8064_cpu_slp_status = {
.name = "cpu_slp_status",
.id = -1,
.dev = {
.platform_data = &msm_pm_slp_sts_data,
},
};
static struct msm_watchdog_pdata msm_watchdog_pdata = {
.pet_time = 10000,
.bark_time = 20000,
.has_secure = true,
.needs_expired_enable = true,
.base = MSM_TMR0_BASE + WDT0_OFFSET,
};
static struct resource msm_watchdog_resources[] = {
{
.start = WDT0_ACCSCSSNBARK_INT,
.end = WDT0_ACCSCSSNBARK_INT,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm8064_device_watchdog = {
.name = "msm_watchdog",
.id = -1,
.dev = {
.platform_data = &msm_watchdog_pdata,
},
.num_resources = ARRAY_SIZE(msm_watchdog_resources),
.resource = msm_watchdog_resources,
};
static struct resource msm_dmov_resource[] = {
{
.start = ADM_0_SCSS_1_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.start = 0x18320000,
.end = 0x18320000 + SZ_1M - 1,
.flags = IORESOURCE_MEM,
},
};
static struct msm_dmov_pdata msm_dmov_pdata = {
.sd = 1,
.sd_size = 0x800,
};
struct platform_device apq8064_device_dmov = {
.name = "msm_dmov",
.id = -1,
.resource = msm_dmov_resource,
.num_resources = ARRAY_SIZE(msm_dmov_resource),
.dev = {
.platform_data = &msm_dmov_pdata,
},
};
static struct resource resources_uart_gsbi1[] = {
{
.start = APQ8064_GSBI1_UARTDM_IRQ,
.end = APQ8064_GSBI1_UARTDM_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.start = MSM_UART1DM_PHYS,
.end = MSM_UART1DM_PHYS + PAGE_SIZE - 1,
.name = "uartdm_resource",
.flags = IORESOURCE_MEM,
},
{
.start = MSM_GSBI1_PHYS,
.end = MSM_GSBI1_PHYS + PAGE_SIZE - 1,
.name = "gsbi_resource",
.flags = IORESOURCE_MEM,
},
};
struct platform_device apq8064_device_uart_gsbi1 = {
.name = "msm_serial_hsl",
.id = 1,
.num_resources = ARRAY_SIZE(resources_uart_gsbi1),
.resource = resources_uart_gsbi1,
};
static struct resource resources_uart_gsbi3[] = {
{
.start = GSBI3_UARTDM_IRQ,
.end = GSBI3_UARTDM_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.start = MSM_UART3DM_PHYS,
.end = MSM_UART3DM_PHYS + PAGE_SIZE - 1,
.name = "uartdm_resource",
.flags = IORESOURCE_MEM,
},
{
.start = MSM_GSBI3_PHYS,
.end = MSM_GSBI3_PHYS + PAGE_SIZE - 1,
.name = "gsbi_resource",
.flags = IORESOURCE_MEM,
},
};
#ifdef CONFIG_FELICA
struct platform_device apq8064_device_uart_gsbi3 = {
.name = "msm_serial_hsl",
.id = 2,
.num_resources = ARRAY_SIZE(resources_uart_gsbi3),
.resource = resources_uart_gsbi3,
};
#else
struct platform_device apq8064_device_uart_gsbi3 = {
.name = "msm_serial_hsl",
.id = 0,
.num_resources = ARRAY_SIZE(resources_uart_gsbi3),
.resource = resources_uart_gsbi3,
};
#endif /* CONFIG_FELICA */
static struct resource resources_qup_i2c_gsbi3[] = {
{
.name = "gsbi_qup_i2c_addr",
.start = MSM_GSBI3_PHYS,
.end = MSM_GSBI3_PHYS + 4 - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_phys_addr",
.start = MSM_GSBI3_QUP_PHYS,
.end = MSM_GSBI3_QUP_PHYS + MSM_QUP_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_err_intr",
.start = GSBI3_QUP_IRQ,
.end = GSBI3_QUP_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.name = "i2c_clk",
.start = 9,
.end = 9,
.flags = IORESOURCE_IO,
},
{
.name = "i2c_sda",
.start = 8,
.end = 8,
.flags = IORESOURCE_IO,
},
};
static struct resource resources_qup_i2c_gsbi1[] = {
{
.name = "gsbi_qup_i2c_addr",
.start = MSM_GSBI1_PHYS,
.end = MSM_GSBI1_PHYS + 4 - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_phys_addr",
.start = MSM_GSBI1_QUP_PHYS,
.end = MSM_GSBI1_QUP_PHYS + MSM_QUP_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_err_intr",
.start = APQ8064_GSBI1_QUP_IRQ,
.end = APQ8064_GSBI1_QUP_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.name = "i2c_clk",
.start = 21,
.end = 21,
.flags = IORESOURCE_IO,
},
{
.name = "i2c_sda",
.start = 20,
.end = 20,
.flags = IORESOURCE_IO,
},
};
struct platform_device apq8064_device_qup_i2c_gsbi1 = {
.name = "qup_i2c",
.id = 0,
.num_resources = ARRAY_SIZE(resources_qup_i2c_gsbi1),
.resource = resources_qup_i2c_gsbi1,
};
struct platform_device apq8064_device_qup_i2c_gsbi3 = {
.name = "qup_i2c",
.id = 3,
.num_resources = ARRAY_SIZE(resources_qup_i2c_gsbi3),
.resource = resources_qup_i2c_gsbi3,
};
static struct resource resources_uart_gsbi4[] = {
{
.start = GSBI4_UARTDM_IRQ,
.end = GSBI4_UARTDM_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.start = MSM_UART4DM_PHYS,
.end = MSM_UART4DM_PHYS + PAGE_SIZE - 1,
.name = "uartdm_resource",
.flags = IORESOURCE_MEM,
},
{
.start = MSM_GSBI4_PHYS,
.end = MSM_GSBI4_PHYS + PAGE_SIZE - 1,
.name = "gsbi_resource",
.flags = IORESOURCE_MEM,
},
};
struct platform_device apq8064_device_uart_gsbi4 = {
.name = "msm_serial_hsl",
.id = 0,
.num_resources = ARRAY_SIZE(resources_uart_gsbi4),
.resource = resources_uart_gsbi4,
};
/* GSBI 4 used into UARTDM Mode for 8064 SGLTE */
static struct resource msm_uart_dm4_resources[] = {
{
.start = MSM_UART4DM_PHYS,
.end = MSM_UART4DM_PHYS + PAGE_SIZE - 1,
.name = "uartdm_resource",
.flags = IORESOURCE_MEM,
},
{
.start = GSBI4_UARTDM_IRQ,
.end = GSBI4_UARTDM_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.start = MSM_GSBI4_PHYS,
.end = MSM_GSBI4_PHYS + 4 - 1,
.name = "gsbi_resource",
.flags = IORESOURCE_MEM,
},
{
.start = DMOV_APQ8064_HSUART_GSBI4_TX_CHAN,
.end = DMOV_APQ8064_HSUART_GSBI4_RX_CHAN,
.name = "uartdm_channels",
.flags = IORESOURCE_DMA,
},
{
.start = DMOV_APQ8064_HSUART_GSBI4_TX_CRCI,
.end = DMOV_APQ8064_HSUART_GSBI4_RX_CRCI,
.name = "uartdm_crci",
.flags = IORESOURCE_DMA,
},
};
static u64 msm_uart_dm4_dma_mask = DMA_BIT_MASK(32);
struct platform_device apq8064_device_uartdm_gsbi4 = {
.name = "msm_serial_hs",
.id = 1,
.num_resources = ARRAY_SIZE(msm_uart_dm4_resources),
.resource = msm_uart_dm4_resources,
.dev = {
.dma_mask = &msm_uart_dm4_dma_mask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
};
static struct resource resources_qup_i2c_gsbi4[] = {
{
.name = "gsbi_qup_i2c_addr",
.start = MSM_GSBI4_PHYS,
.end = MSM_GSBI4_PHYS + 4 - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_phys_addr",
.start = MSM_GSBI4_QUP_PHYS,
.end = MSM_GSBI4_QUP_PHYS + MSM_QUP_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_err_intr",
.start = GSBI4_QUP_IRQ,
.end = GSBI4_QUP_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.name = "i2c_clk",
.start = 13,
.end = 13,
.flags = IORESOURCE_IO,
},
{
.name = "i2c_sda",
.start = 12,
.end = 12,
.flags = IORESOURCE_IO,
},
};
struct platform_device apq8064_device_qup_i2c_gsbi4 = {
.name = "qup_i2c",
.id = 4,
.num_resources = ARRAY_SIZE(resources_qup_i2c_gsbi4),
.resource = resources_qup_i2c_gsbi4,
};
static struct resource resources_qup_i2c_gsbi2[] = {
{
.name = "gsbi_qup_i2c_addr",
.start = MSM_GSBI2_PHYS,
.end = MSM_GSBI2_PHYS + 4 - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_phys_addr",
.start = MSM_GSBI2_QUP_PHYS,
.end = MSM_GSBI2_QUP_PHYS + MSM_QUP_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_err_intr",
.start = APQ8064_GSBI2_QUP_IRQ,
.end = APQ8064_GSBI2_QUP_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.name = "i2c_clk",
.start = 25,
.end = 25,
.flags = IORESOURCE_IO,
},
{
.name = "i2c_sda",
.start = 24,
.end = 24,
.flags = IORESOURCE_IO,
},
};
struct platform_device apq8064_device_qup_i2c_gsbi2 = {
.name = "qup_i2c",
.id = 2,
.num_resources = ARRAY_SIZE(resources_qup_i2c_gsbi2),
.resource = resources_qup_i2c_gsbi2,
};
#ifdef CONFIG_ISDBTMM
static struct resource resources_qup_spi_gsbi4[] = {
{
.name = "spi_base",
.start = MSM_GSBI4_QUP_PHYS,
.end = MSM_GSBI4_QUP_PHYS + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "gsbi_base",
.start = MSM_GSBI4_PHYS,
.end = MSM_GSBI4_PHYS + 4 - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "spi_irq_in",
.start = GSBI4_QUP_IRQ,
.end = GSBI4_QUP_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.name = "spidm_channels",
.start = 10,
.end = 11,
.flags = IORESOURCE_DMA,
},
{
.name = "spidm_crci",
.start = 7,
.end = 8,
.flags = IORESOURCE_DMA,
},
};
struct platform_device apq8064_device_qup_spi_gsbi4 = {
.name = "spi_qsd",
.id = 1,
.num_resources = ARRAY_SIZE(resources_qup_spi_gsbi4),
.resource = resources_qup_spi_gsbi4,
};
#endif
#if defined(CONFIG_TDMB) || defined(CONFIG_TDMB_MODULE)
static struct resource resources_qup_spi_gsbi4[] = {
{
.name = "spi_base",
.start = MSM_GSBI4_QUP_PHYS,
.end = MSM_GSBI4_QUP_PHYS + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "gsbi_base",
.start = MSM_GSBI4_PHYS,
.end = MSM_GSBI4_PHYS + 4 - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "spi_irq_in",
.start = GSBI4_QUP_IRQ,
.end = GSBI4_QUP_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.start = 10,
.end = 11,
.flags = IORESOURCE_DMA,
},
{
.start = 7,
.end = 8,
.flags = IORESOURCE_DMA,
},
};
struct platform_device apq8064_device_qup_spi_gsbi4 = {
.name = "spi_qsd",
.id = 1,
.num_resources = ARRAY_SIZE(resources_qup_spi_gsbi4),
.resource = resources_qup_spi_gsbi4,
};
#endif
static struct resource resources_qup_spi_gsbi5[] = {
{
.name = "spi_base",
.start = MSM_GSBI5_QUP_PHYS,
.end = MSM_GSBI5_QUP_PHYS + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "gsbi_base",
.start = MSM_GSBI5_PHYS,
.end = MSM_GSBI5_PHYS + 4 - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "spi_irq_in",
.start = GSBI5_QUP_IRQ,
.end = GSBI5_QUP_IRQ,
.flags = IORESOURCE_IRQ,
},
#if defined(CONFIG_MACH_JACTIVE_ATT) || defined(CONFIG_MACH_JACTIVE_EUR)
{
.name = "spi_clk",
.start = 54,
.end = 54,
.flags = IORESOURCE_IO,
},
{
.name = "spi_cs",
.start = 53,
.end = 53,
.flags = IORESOURCE_IO,
},
{
.name = "spi_miso",
.start = 52,
.end = 52,
.flags = IORESOURCE_IO,
},
{
.name = "spi_mosi",
.start = 51,
.end = 51,
.flags = IORESOURCE_IO,
},
#else
{
.name = "spidm_channels",
.start = 3,
.end = 4,
.flags = IORESOURCE_DMA,
},
{
.name = "spidm_crci",
.start = 9,
.end = 10,
.flags = IORESOURCE_DMA,
},
#endif
};
struct platform_device apq8064_device_qup_spi_gsbi5 = {
.name = "spi_qsd",
.id = 0,
.num_resources = ARRAY_SIZE(resources_qup_spi_gsbi5),
.resource = resources_qup_spi_gsbi5,
};
static struct resource resources_qup_i2c_gsbi5[] = {
{
.name = "gsbi_qup_i2c_addr",
.start = MSM_GSBI5_PHYS,
.end = MSM_GSBI5_PHYS + 4 - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_phys_addr",
.start = MSM_GSBI5_QUP_PHYS,
.end = MSM_GSBI5_QUP_PHYS + MSM_QUP_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_err_intr",
.start = GSBI5_QUP_IRQ,
.end = GSBI5_QUP_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.name = "i2c_clk",
.start = 54,
.end = 54,
.flags = IORESOURCE_IO,
},
{
.name = "i2c_sda",
.start = 53,
.end = 53,
.flags = IORESOURCE_IO,
},
};
struct platform_device mpq8064_device_qup_i2c_gsbi5 = {
.name = "qup_i2c",
.id = 5,
.num_resources = ARRAY_SIZE(resources_qup_i2c_gsbi5),
.resource = resources_qup_i2c_gsbi5,
};
/* GSBI 6 used into UARTDM Mode */
static struct resource msm_uart_dm6_resources[] = {
{
.start = MSM_UART6DM_PHYS,
.end = MSM_UART6DM_PHYS + PAGE_SIZE - 1,
.name = "uartdm_resource",
.flags = IORESOURCE_MEM,
},
{
.start = GSBI6_UARTDM_IRQ,
.end = GSBI6_UARTDM_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.start = MSM_GSBI6_PHYS,
.end = MSM_GSBI6_PHYS + 4 - 1,
.name = "gsbi_resource",
.flags = IORESOURCE_MEM,
},
{
.start = DMOV_MPQ8064_HSUART_GSBI6_TX_CHAN,
.end = DMOV_MPQ8064_HSUART_GSBI6_RX_CHAN,
.name = "uartdm_channels",
.flags = IORESOURCE_DMA,
},
{
.start = DMOV_MPQ8064_HSUART_GSBI6_TX_CRCI,
.end = DMOV_MPQ8064_HSUART_GSBI6_RX_CRCI,
.name = "uartdm_crci",
.flags = IORESOURCE_DMA,
},
};
static u64 msm_uart_dm6_dma_mask = DMA_BIT_MASK(32);
struct platform_device mpq8064_device_uartdm_gsbi6 = {
.name = "msm_serial_hs",
.id = 0,
.num_resources = ARRAY_SIZE(msm_uart_dm6_resources),
.resource = msm_uart_dm6_resources,
.dev = {
.dma_mask = &msm_uart_dm6_dma_mask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
};
/* BT HS UART Configuration for BRCM BT*/
#ifdef CONFIG_SERIAL_MSM_HS
static struct resource msm_uart1_dm_resources[] = {
{
.start = MSM_UART6DM_PHYS,
.end = MSM_UART6DM_PHYS + PAGE_SIZE - 1,
.name = " uartdm_resource",
.flags = IORESOURCE_MEM,
},
{
.start = INT_UART1DM_IRQ,
.end = INT_UART1DM_IRQ,
.flags = IORESOURCE_IRQ,
},
{
/* GSBI6 is UARTDM1 */
.start = MSM_GSBI6_PHYS,
.end = MSM_GSBI6_PHYS + 4 - 1,
.name = "gsbi_resource",
.flags = IORESOURCE_MEM,
},
{
.start = DMOV_HSUART1_TX_CHAN,
.end = DMOV_HSUART1_RX_CHAN,
.name = "uartdm_channels",
.flags = IORESOURCE_DMA,
},
{
.start = DMOV_HSUART1_TX_CRCI,
.end = DMOV_HSUART1_RX_CRCI,
.name = "uartdm_crci",
.flags = IORESOURCE_DMA,
},
};
/* GSBI 6 used into UARTDM Mode */
static u64 msm_uart_dm1_dma_mask = DMA_BIT_MASK(32);
struct platform_device msm_device_uart_dm1 = {
.name = "msm_serial_hs",
.id = 0,
.num_resources = ARRAY_SIZE(msm_uart1_dm_resources),
.resource = msm_uart1_dm_resources,
.dev = {
.dma_mask = &msm_uart_dm1_dma_mask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
};
#endif
static struct resource resources_uart_gsbi7[] = {
{
.start = GSBI7_UARTDM_IRQ,
.end = GSBI7_UARTDM_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.start = MSM_UART7DM_PHYS,
.end = MSM_UART7DM_PHYS + PAGE_SIZE - 1,
.name = "uartdm_resource",
.flags = IORESOURCE_MEM,
},
{
.start = MSM_GSBI7_PHYS,
.end = MSM_GSBI7_PHYS + PAGE_SIZE - 1,
.name = "gsbi_resource",
.flags = IORESOURCE_MEM,
},
{
.start = 83, /* UART_RX */
.end = 83,
.name = "wakeup_gpio",
.flags = IORESOURCE_IO,
},
};
struct platform_device apq8064_device_uart_gsbi7 = {
.name = "msm_serial_hsl",
.id = 0,
.num_resources = ARRAY_SIZE(resources_uart_gsbi7),
.resource = resources_uart_gsbi7,
};
static struct resource resources_qup_i2c_gsbi7[] = {
{
.name = "gsbi_qup_i2c_addr",
.start = MSM_GSBI7_PHYS,
.end = MSM_GSBI7_PHYS + 4 - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_phys_addr",
.start = MSM_GSBI7_QUP_PHYS,
.end = MSM_GSBI7_QUP_PHYS + MSM_QUP_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_err_intr",
.start = GSBI7_QUP_IRQ,
.end = GSBI7_QUP_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.name = "i2c_clk",
.start = 85,
.end = 85,
.flags = IORESOURCE_IO,
},
{
.name = "i2c_sda",
.start = 84,
.end = 84,
.flags = IORESOURCE_IO,
},
};
struct platform_device apq8064_device_qup_i2c_gsbi7 = {
.name = "qup_i2c",
.id = 7,
.num_resources = ARRAY_SIZE(resources_qup_i2c_gsbi7),
.resource = resources_qup_i2c_gsbi7,
};
struct platform_device apq_pcm = {
.name = "msm-pcm-dsp",
.id = -1,
};
struct platform_device apq_pcm_routing = {
.name = "msm-pcm-routing",
.id = -1,
};
struct platform_device apq_cpudai0 = {
.name = "msm-dai-q6",
.id = 0x4000,
};
struct platform_device apq_cpudai1 = {
.name = "msm-dai-q6",
.id = 0x4001,
};
struct platform_device mpq_cpudai_sec_i2s_rx = {
.name = "msm-dai-q6",
.id = 4,
};
struct platform_device apq_cpudai_hdmi_rx = {
.name = "msm-dai-q6-hdmi",
.id = 8,
};
struct platform_device apq_cpudai_bt_rx = {
.name = "msm-dai-q6",
.id = 0x3000,
};
struct platform_device apq_cpudai_bt_tx = {
.name = "msm-dai-q6",
.id = 0x3001,
};
struct platform_device apq_cpudai_fm_rx = {
.name = "msm-dai-q6",
.id = 0x3004,
};
struct platform_device apq_cpudai_fm_tx = {
.name = "msm-dai-q6",
.id = 0x3005,
};
struct platform_device apq_cpudai_slim_4_rx = {
.name = "msm-dai-q6",
.id = 0x4008,
};
struct platform_device apq_cpudai_slim_4_tx = {
.name = "msm-dai-q6",
.id = 0x4009,
};
#define MSM_TSIF0_PHYS (0x18200000)
#define MSM_TSIF1_PHYS (0x18201000)
#define MSM_TSIF_SIZE (0x200)
#define TSIF_0_CLK GPIO_CFG(55, 1, GPIO_CFG_INPUT, \
GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA)
#define TSIF_0_EN GPIO_CFG(56, 1, GPIO_CFG_INPUT, \
GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA)
#define TSIF_0_DATA GPIO_CFG(57, 1, GPIO_CFG_INPUT, \
GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA)
#define TSIF_0_SYNC GPIO_CFG(62, 1, GPIO_CFG_INPUT, \
GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA)
#define TSIF_1_CLK GPIO_CFG(59, 1, GPIO_CFG_INPUT, \
GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA)
#define TSIF_1_EN GPIO_CFG(60, 1, GPIO_CFG_INPUT, \
GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA)
#define TSIF_1_DATA GPIO_CFG(61, 1, GPIO_CFG_INPUT, \
GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA)
#define TSIF_1_SYNC GPIO_CFG(58, 1, GPIO_CFG_INPUT, \
GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA)
static const struct msm_gpio tsif0_gpios[] = {
{ .gpio_cfg = TSIF_0_CLK, .label = "tsif_clk", },
{ .gpio_cfg = TSIF_0_EN, .label = "tsif_en", },
{ .gpio_cfg = TSIF_0_DATA, .label = "tsif_data", },
{ .gpio_cfg = TSIF_0_SYNC, .label = "tsif_sync", },
};
static const struct msm_gpio tsif1_gpios[] = {
{ .gpio_cfg = TSIF_1_CLK, .label = "tsif_clk", },
{ .gpio_cfg = TSIF_1_EN, .label = "tsif_en", },
{ .gpio_cfg = TSIF_1_DATA, .label = "tsif_data", },
{ .gpio_cfg = TSIF_1_SYNC, .label = "tsif_sync", },
};
struct msm_tsif_platform_data tsif1_8064_platform_data = {
.num_gpios = ARRAY_SIZE(tsif1_gpios),
.gpios = tsif1_gpios,
.tsif_pclk = "iface_clk",
.tsif_ref_clk = "ref_clk",
};
struct resource tsif1_8064_resources[] = {
[0] = {
.flags = IORESOURCE_IRQ,
.start = TSIF2_IRQ,
.end = TSIF2_IRQ,
},
[1] = {
.flags = IORESOURCE_MEM,
.start = MSM_TSIF1_PHYS,
.end = MSM_TSIF1_PHYS + MSM_TSIF_SIZE - 1,
},
[2] = {
.flags = IORESOURCE_DMA,
.start = DMOV8064_TSIF_CHAN,
.end = DMOV8064_TSIF_CRCI,
},
};
struct msm_tsif_platform_data tsif0_8064_platform_data = {
.num_gpios = ARRAY_SIZE(tsif0_gpios),
.gpios = tsif0_gpios,
.tsif_pclk = "iface_clk",
.tsif_ref_clk = "ref_clk",
};
struct resource tsif0_8064_resources[] = {
[0] = {
.flags = IORESOURCE_IRQ,
.start = TSIF1_IRQ,
.end = TSIF1_IRQ,
},
[1] = {
.flags = IORESOURCE_MEM,
.start = MSM_TSIF0_PHYS,
.end = MSM_TSIF0_PHYS + MSM_TSIF_SIZE - 1,
},
[2] = {
.flags = IORESOURCE_DMA,
.start = DMOV_TSIF_CHAN,
.end = DMOV_TSIF_CRCI,
},
};
struct platform_device msm_8064_device_tsif[2] = {
{
.name = "msm_tsif",
.id = 0,
.num_resources = ARRAY_SIZE(tsif0_8064_resources),
.resource = tsif0_8064_resources,
.dev = {
.platform_data = &tsif0_8064_platform_data
},
},
{
.name = "msm_tsif",
.id = 1,
.num_resources = ARRAY_SIZE(tsif1_8064_resources),
.resource = tsif1_8064_resources,
.dev = {
.platform_data = &tsif1_8064_platform_data
},
}
};
#define MSM_TSPP_PHYS (0x18202000)
#define MSM_TSPP_SIZE (0x1000)
#define MSM_TSPP_BAM_PHYS (0x18204000)
#define MSM_TSPP_BAM_SIZE (0x2000)
static const struct msm_gpio tspp_gpios[] = {
{ .gpio_cfg = TSIF_0_CLK, .label = "tsif_clk", },
{ .gpio_cfg = TSIF_0_EN, .label = "tsif_en", },
{ .gpio_cfg = TSIF_0_DATA, .label = "tsif_data", },
{ .gpio_cfg = TSIF_0_SYNC, .label = "tsif_sync", },
{ .gpio_cfg = TSIF_1_CLK, .label = "tsif_clk", },
{ .gpio_cfg = TSIF_1_EN, .label = "tsif_en", },
{ .gpio_cfg = TSIF_1_DATA, .label = "tsif_data", },
{ .gpio_cfg = TSIF_1_SYNC, .label = "tsif_sync", },
};
static struct resource tspp_resources[] = {
[0] = {
.name = "TSIF_TSPP_IRQ",
.flags = IORESOURCE_IRQ,
.start = TSIF_TSPP_IRQ,
.end = TSIF_TSPP_IRQ,
},
[1] = {
.name = "TSIF0_IRQ",
.flags = IORESOURCE_IRQ,
.start = TSIF1_IRQ,
.end = TSIF1_IRQ,
},
[2] = {
.name = "TSIF1_IRQ",
.flags = IORESOURCE_IRQ,
.start = TSIF2_IRQ,
.end = TSIF2_IRQ,
},
[3] = {
.name = "TSIF_BAM_IRQ",
.flags = IORESOURCE_IRQ,
.start = TSIF_BAM_IRQ,
.end = TSIF_BAM_IRQ,
},
[4] = {
.name = "MSM_TSIF0_PHYS",
.flags = IORESOURCE_MEM,
.start = MSM_TSIF0_PHYS,
.end = MSM_TSIF0_PHYS + MSM_TSIF_SIZE - 1,
},
[5] = {
.name = "MSM_TSIF1_PHYS",
.flags = IORESOURCE_MEM,
.start = MSM_TSIF1_PHYS,
.end = MSM_TSIF1_PHYS + MSM_TSIF_SIZE - 1,
},
[6] = {
.name = "MSM_TSPP_PHYS",
.flags = IORESOURCE_MEM,
.start = MSM_TSPP_PHYS,
.end = MSM_TSPP_PHYS + MSM_TSPP_SIZE - 1,
},
[7] = {
.name = "MSM_TSPP_BAM_PHYS",
.flags = IORESOURCE_MEM,
.start = MSM_TSPP_BAM_PHYS,
.end = MSM_TSPP_BAM_PHYS + MSM_TSPP_BAM_SIZE - 1,
},
};
static struct msm_tspp_platform_data tspp_platform_data = {
.num_gpios = ARRAY_SIZE(tspp_gpios),
.gpios = tspp_gpios,
.tsif_pclk = "iface_clk",
.tsif_ref_clk = "ref_clk",
};
struct platform_device msm_8064_device_tspp = {
.name = "msm_tspp",
.id = 0,
.num_resources = ARRAY_SIZE(tspp_resources),
.resource = tspp_resources,
.dev = {
.platform_data = &tspp_platform_data
},
};
/*
* Machine specific data for AUX PCM Interface
* which the driver will be unware of.
*/
struct msm_dai_auxpcm_pdata apq_auxpcm_pdata = {
.clk = "pcm_clk",
.mode_8k = {
.mode = AFE_PCM_CFG_MODE_PCM,
.sync = AFE_PCM_CFG_SYNC_INT,
.frame = AFE_PCM_CFG_FRM_256BPF,
.quant = AFE_PCM_CFG_QUANT_LINEAR_NOPAD,
.slot = 0,
.data = AFE_PCM_CFG_CDATAOE_MASTER,
.pcm_clk_rate = 2048000,
},
.mode_16k = {
.mode = AFE_PCM_CFG_MODE_PCM,
.sync = AFE_PCM_CFG_SYNC_INT,
.frame = AFE_PCM_CFG_FRM_256BPF,
.quant = AFE_PCM_CFG_QUANT_LINEAR_NOPAD,
.slot = 0,
.data = AFE_PCM_CFG_CDATAOE_MASTER,
.pcm_clk_rate = 4096000,
}
};
struct platform_device apq_cpudai_auxpcm_rx = {
.name = "msm-dai-q6",
.id = 2,
.dev = {
.platform_data = &apq_auxpcm_pdata,
},
};
struct platform_device apq_cpudai_auxpcm_tx = {
.name = "msm-dai-q6",
.id = 3,
.dev = {
.platform_data = &apq_auxpcm_pdata,
},
};
struct msm_mi2s_pdata mpq_mi2s_tx_data = {
.rx_sd_lines = 0,
.tx_sd_lines = MSM_MI2S_SD0 | MSM_MI2S_SD1 | MSM_MI2S_SD2 |
MSM_MI2S_SD3,
};
struct platform_device mpq_cpudai_mi2s_tx = {
.name = "msm-dai-q6-mi2s",
.id = -1, /*MI2S_TX */
.dev = {
.platform_data = &mpq_mi2s_tx_data,
},
};
struct platform_device apq_cpu_fe = {
.name = "msm-dai-fe",
.id = -1,
};
struct platform_device apq_stub_codec = {
.name = "msm-stub-codec",
.id = 1,
};
struct platform_device apq_voice = {
.name = "msm-pcm-voice",
.id = -1,
};
struct platform_device apq_voip = {
.name = "msm-voip-dsp",
.id = -1,
};
struct platform_device apq_lpa_pcm = {
.name = "msm-pcm-lpa",
.id = -1,
};
struct platform_device apq_compr_dsp = {
.name = "msm-compr-dsp",
.id = -1,
};
struct platform_device apq_multi_ch_pcm = {
.name = "msm-multi-ch-pcm-dsp",
.id = -1,
};
struct platform_device apq_lowlatency_pcm = {
.name = "msm-lowlatency-pcm-dsp",
.id = -1,
};
struct platform_device apq_pcm_hostless = {
.name = "msm-pcm-hostless",
.id = -1,
};
struct platform_device apq_cpudai_afe_01_rx = {
.name = "msm-dai-q6",
.id = 0xE0,
};
struct platform_device apq_cpudai_afe_01_tx = {
.name = "msm-dai-q6",
.id = 0xF0,
};
struct platform_device apq_cpudai_afe_02_rx = {
.name = "msm-dai-q6",
.id = 0xF1,
};
struct platform_device apq_cpudai_afe_02_tx = {
.name = "msm-dai-q6",
.id = 0xE1,
};
struct platform_device apq_pcm_afe = {
.name = "msm-pcm-afe",
.id = -1,
};
struct platform_device apq_cpudai_stub = {
.name = "msm-dai-stub",
.id = -1,
};
struct platform_device apq_cpudai_slimbus_1_rx = {
.name = "msm-dai-q6",
.id = 0x4002,
};
struct platform_device apq_cpudai_slimbus_1_tx = {
.name = "msm-dai-q6",
.id = 0x4003,
};
struct platform_device apq_cpudai_slimbus_2_rx = {
.name = "msm-dai-q6",
.id = 0x4004,
};
struct platform_device apq_cpudai_slimbus_2_tx = {
.name = "msm-dai-q6",
.id = 0x4005,
};
struct platform_device apq_cpudai_slimbus_3_rx = {
.name = "msm-dai-q6",
.id = 0x4006,
};
struct platform_device apq_cpudai_slimbus_3_tx = {
.name = "msm-dai-q6",
.id = 0x4007,
};
static struct resource resources_ssbi_pmic1[] = {
{
.start = MSM_PMIC1_SSBI_CMD_PHYS,
.end = MSM_PMIC1_SSBI_CMD_PHYS + MSM_PMIC_SSBI_SIZE - 1,
.flags = IORESOURCE_MEM,
},
};
#define LPASS_SLIMBUS_PHYS 0x28080000
#define LPASS_SLIMBUS_BAM_PHYS 0x28084000
#define LPASS_SLIMBUS_SLEW (MSM8960_TLMM_PHYS + 0x207C)
/* Board info for the slimbus slave device */
static struct resource slimbus_res[] = {
{
.start = LPASS_SLIMBUS_PHYS,
.end = LPASS_SLIMBUS_PHYS + 8191,
.flags = IORESOURCE_MEM,
.name = "slimbus_physical",
},
{
.start = LPASS_SLIMBUS_BAM_PHYS,
.end = LPASS_SLIMBUS_BAM_PHYS + 8191,
.flags = IORESOURCE_MEM,
.name = "slimbus_bam_physical",
},
{
.start = LPASS_SLIMBUS_SLEW,
.end = LPASS_SLIMBUS_SLEW + 4 - 1,
.flags = IORESOURCE_MEM,
.name = "slimbus_slew_reg",
},
{
.start = SLIMBUS0_CORE_EE1_IRQ,
.end = SLIMBUS0_CORE_EE1_IRQ,
.flags = IORESOURCE_IRQ,
.name = "slimbus_irq",
},
{
.start = SLIMBUS0_BAM_EE1_IRQ,
.end = SLIMBUS0_BAM_EE1_IRQ,
.flags = IORESOURCE_IRQ,
.name = "slimbus_bam_irq",
},
};
struct platform_device apq8064_slim_ctrl = {
.name = "msm_slim_ctrl",
.id = 1,
.num_resources = ARRAY_SIZE(slimbus_res),
.resource = slimbus_res,
.dev = {
.coherent_dma_mask = 0xffffffffULL,
},
};
struct platform_device apq8064_device_ssbi_pmic1 = {
.name = "msm_ssbi",
.id = 0,
.resource = resources_ssbi_pmic1,
.num_resources = ARRAY_SIZE(resources_ssbi_pmic1),
};
static struct resource resources_ssbi_pmic2[] = {
{
.start = MSM_PMIC2_SSBI_CMD_PHYS,
.end = MSM_PMIC2_SSBI_CMD_PHYS + MSM_PMIC_SSBI_SIZE - 1,
.flags = IORESOURCE_MEM,
},
};
struct platform_device apq8064_device_ssbi_pmic2 = {
.name = "msm_ssbi",
.id = 1,
.resource = resources_ssbi_pmic2,
.num_resources = ARRAY_SIZE(resources_ssbi_pmic2),
};
static struct resource resources_otg[] = {
{
.start = MSM_HSUSB1_PHYS,
.end = MSM_HSUSB1_PHYS + MSM_HSUSB1_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.start = USB1_HS_IRQ,
.end = USB1_HS_IRQ,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device apq8064_device_otg = {
.name = "msm_otg",
.id = -1,
.num_resources = ARRAY_SIZE(resources_otg),
.resource = resources_otg,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
static struct resource resources_hsusb[] = {
{
.start = MSM_HSUSB1_PHYS,
.end = MSM_HSUSB1_PHYS + MSM_HSUSB1_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.start = USB1_HS_IRQ,
.end = USB1_HS_IRQ,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device apq8064_device_gadget_peripheral = {
.name = "msm_hsusb",
.id = -1,
.num_resources = ARRAY_SIZE(resources_hsusb),
.resource = resources_hsusb,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
static struct resource resources_hsusb_host[] = {
{
.start = MSM_HSUSB1_PHYS,
.end = MSM_HSUSB1_PHYS + MSM_HSUSB1_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.start = USB1_HS_IRQ,
.end = USB1_HS_IRQ,
.flags = IORESOURCE_IRQ,
},
};
static struct resource resources_hsic_host[] = {
{
.start = 0x12510000,
.end = 0x12510000 + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
{
.start = USB2_HSIC_IRQ,
.end = USB2_HSIC_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.start = MSM_GPIO_TO_INT(49),
.end = MSM_GPIO_TO_INT(49),
.name = "peripheral_status_irq",
.flags = IORESOURCE_IRQ,
},
{
.start = 47,
.end = 47,
.name = "wakeup",
.flags = IORESOURCE_IO,
},
};
static u64 dma_mask = DMA_BIT_MASK(32);
struct platform_device apq8064_device_hsusb_host = {
.name = "msm_hsusb_host",
.id = -1,
.num_resources = ARRAY_SIZE(resources_hsusb_host),
.resource = resources_hsusb_host,
.dev = {
.dma_mask = &dma_mask,
.coherent_dma_mask = 0xffffffff,
},
};
struct platform_device apq8064_device_hsic_host = {
.name = "msm_hsic_host",
.id = -1,
.num_resources = ARRAY_SIZE(resources_hsic_host),
.resource = resources_hsic_host,
.dev = {
.dma_mask = &dma_mask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
};
static struct resource resources_ehci_host3[] = {
{
.start = MSM_HSUSB3_PHYS,
.end = MSM_HSUSB3_PHYS + MSM_HSUSB3_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.start = USB3_HS_IRQ,
.end = USB3_HS_IRQ,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device apq8064_device_ehci_host3 = {
.name = "msm_ehci_host",
.id = 0,
.num_resources = ARRAY_SIZE(resources_ehci_host3),
.resource = resources_ehci_host3,
.dev = {
.dma_mask = &dma_mask,
.coherent_dma_mask = 0xffffffff,
},
};
static struct resource resources_ehci_host4[] = {
{
.start = MSM_HSUSB4_PHYS,
.end = MSM_HSUSB4_PHYS + MSM_HSUSB4_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.start = USB4_HS_IRQ,
.end = USB4_HS_IRQ,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device apq8064_device_ehci_host4 = {
.name = "msm_ehci_host",
.id = 1,
.num_resources = ARRAY_SIZE(resources_ehci_host4),
.resource = resources_ehci_host4,
.dev = {
.dma_mask = &dma_mask,
.coherent_dma_mask = 0xffffffff,
},
};
struct platform_device apq8064_device_acpuclk = {
.name = "acpuclk-8064",
.id = -1,
};
#define SHARED_IMEM_TZ_BASE 0x2a03f720
static struct resource tzlog_resources[] = {
{
.start = SHARED_IMEM_TZ_BASE,
.end = SHARED_IMEM_TZ_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
};
struct platform_device apq_device_tz_log = {
.name = "tz_log",
.id = 0,
.num_resources = ARRAY_SIZE(tzlog_resources),
.resource = tzlog_resources,
};
/* MSM Video core device */
#ifdef CONFIG_MSM_BUS_SCALING
static struct msm_bus_vectors vidc_init_vectors[] = {
{
.src = MSM_BUS_MASTER_VIDEO_ENC,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = 0,
},
{
.src = MSM_BUS_MASTER_VIDEO_DEC,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = 0,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = 0,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = 0,
},
};
static struct msm_bus_vectors vidc_venc_vga_vectors[] = {
{
.src = MSM_BUS_MASTER_VIDEO_ENC,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 54525952,
.ib = 436207616,
},
{
.src = MSM_BUS_MASTER_VIDEO_DEC,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 72351744,
.ib = 289406976,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 500000,
.ib = 1000000,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 500000,
.ib = 1000000,
},
};
static struct msm_bus_vectors vidc_vdec_vga_vectors[] = {
{
.src = MSM_BUS_MASTER_VIDEO_ENC,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 40894464,
.ib = 327155712,
},
{
.src = MSM_BUS_MASTER_VIDEO_DEC,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 48234496,
.ib = 192937984,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 500000,
.ib = 2000000,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 500000,
.ib = 2000000,
},
};
static struct msm_bus_vectors vidc_venc_720p_vectors[] = {
{
.src = MSM_BUS_MASTER_VIDEO_ENC,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 163577856,
.ib = 1308622848,
},
{
.src = MSM_BUS_MASTER_VIDEO_DEC,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 219152384,
.ib = 876609536,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 1750000,
.ib = 3500000,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 1750000,
.ib = 3500000,
},
};
static struct msm_bus_vectors vidc_vdec_720p_vectors[] = {
{
.src = MSM_BUS_MASTER_VIDEO_ENC,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 121634816,
.ib = 973078528,
},
{
.src = MSM_BUS_MASTER_VIDEO_DEC,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 155189248,
.ib = 620756992,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 1750000,
.ib = 7000000,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 1750000,
.ib = 7000000,
},
};
static struct msm_bus_vectors vidc_venc_1080p_vectors[] = {
{
.src = MSM_BUS_MASTER_VIDEO_ENC,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 372244480,
.ib = 2560000000U,
},
{
.src = MSM_BUS_MASTER_VIDEO_DEC,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 501219328,
.ib = 2560000000U,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 2500000,
.ib = 5000000,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 2500000,
.ib = 5000000,
},
};
static struct msm_bus_vectors vidc_vdec_1080p_vectors[] = {
{
.src = MSM_BUS_MASTER_VIDEO_ENC,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 222298112,
.ib = 2560000000U,
},
{
.src = MSM_BUS_MASTER_VIDEO_DEC,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 330301440,
.ib = 2560000000U,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 2500000,
.ib = 700000000,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 2500000,
.ib = 10000000,
},
};
static struct msm_bus_vectors vidc_venc_1080p_turbo_vectors[] = {
{
.src = MSM_BUS_MASTER_VIDEO_ENC,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 372244480,
.ib = 3522000000U,
},
{
.src = MSM_BUS_MASTER_VIDEO_DEC,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 501219328,
.ib = 3522000000U,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 2500000,
.ib = 5000000,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 2500000,
.ib = 5000000,
},
};
static struct msm_bus_vectors vidc_vdec_1080p_turbo_vectors[] = {
{
.src = MSM_BUS_MASTER_VIDEO_ENC,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 222298112,
.ib = 3522000000U,
},
{
.src = MSM_BUS_MASTER_VIDEO_DEC,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 330301440,
.ib = 3522000000U,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 2500000,
.ib = 700000000,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 2500000,
.ib = 10000000,
},
};
static struct msm_bus_paths vidc_bus_client_config[] = {
{
ARRAY_SIZE(vidc_init_vectors),
vidc_init_vectors,
},
{
ARRAY_SIZE(vidc_venc_vga_vectors),
vidc_venc_vga_vectors,
},
{
ARRAY_SIZE(vidc_vdec_vga_vectors),
vidc_vdec_vga_vectors,
},
{
ARRAY_SIZE(vidc_venc_720p_vectors),
vidc_venc_720p_vectors,
},
{
ARRAY_SIZE(vidc_vdec_720p_vectors),
vidc_vdec_720p_vectors,
},
{
ARRAY_SIZE(vidc_venc_1080p_vectors),
vidc_venc_1080p_vectors,
},
{
ARRAY_SIZE(vidc_vdec_1080p_vectors),
vidc_vdec_1080p_vectors,
},
{
ARRAY_SIZE(vidc_venc_1080p_turbo_vectors),
vidc_venc_1080p_turbo_vectors,
},
{
ARRAY_SIZE(vidc_vdec_1080p_turbo_vectors),
vidc_vdec_1080p_turbo_vectors,
},
};
static struct msm_bus_scale_pdata vidc_bus_client_data = {
vidc_bus_client_config,
ARRAY_SIZE(vidc_bus_client_config),
.name = "vidc",
};
#endif
#define APQ8064_VIDC_BASE_PHYS 0x04400000
#define APQ8064_VIDC_BASE_SIZE 0x00100000
static struct resource apq8064_device_vidc_resources[] = {
{
.start = APQ8064_VIDC_BASE_PHYS,
.end = APQ8064_VIDC_BASE_PHYS + APQ8064_VIDC_BASE_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.start = VCODEC_IRQ,
.end = VCODEC_IRQ,
.flags = IORESOURCE_IRQ,
},
};
struct msm_vidc_platform_data apq8064_vidc_platform_data = {
#ifdef CONFIG_MSM_BUS_SCALING
.vidc_bus_client_pdata = &vidc_bus_client_data,
#endif
#ifdef CONFIG_MSM_MULTIMEDIA_USE_ION
.memtype = ION_CP_MM_HEAP_ID,
.enable_ion = 1,
.cp_enabled = 1,
#else
.memtype = MEMTYPE_EBI1,
.enable_ion = 0,
#endif
.disable_dmx = 0,
.disable_fullhd = 0,
.cont_mode_dpb_count = 18,
.fw_addr = 0x9fe00000,
.enable_sec_metadata = 1,
};
struct platform_device apq8064_msm_device_vidc = {
.name = "msm_vidc",
.id = 0,
.num_resources = ARRAY_SIZE(apq8064_device_vidc_resources),
.resource = apq8064_device_vidc_resources,
.dev = {
.platform_data = &apq8064_vidc_platform_data,
},
};
#define MSM_SDC1_BASE 0x12400000
#define MSM_SDC1_DML_BASE (MSM_SDC1_BASE + 0x800)
#define MSM_SDC1_BAM_BASE (MSM_SDC1_BASE + 0x2000)
#define MSM_SDC2_BASE 0x12140000
#define MSM_SDC2_DML_BASE (MSM_SDC2_BASE + 0x800)
#define MSM_SDC2_BAM_BASE (MSM_SDC2_BASE + 0x2000)
#define MSM_SDC3_BASE 0x12180000
#define MSM_SDC3_DML_BASE (MSM_SDC3_BASE + 0x800)
#define MSM_SDC3_BAM_BASE (MSM_SDC3_BASE + 0x2000)
#define MSM_SDC4_BASE 0x121C0000
#define MSM_SDC4_DML_BASE (MSM_SDC4_BASE + 0x800)
#define MSM_SDC4_BAM_BASE (MSM_SDC4_BASE + 0x2000)
static struct resource resources_sdc1[] = {
{
.name = "core_mem",
.flags = IORESOURCE_MEM,
.start = MSM_SDC1_BASE,
.end = MSM_SDC1_DML_BASE - 1,
},
{
.name = "core_irq",
.flags = IORESOURCE_IRQ,
.start = SDC1_IRQ_0,
.end = SDC1_IRQ_0
},
#ifdef CONFIG_MMC_MSM_SPS_SUPPORT
{
.name = "dml_mem",
.start = MSM_SDC1_DML_BASE,
.end = MSM_SDC1_BAM_BASE - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "bam_mem",
.start = MSM_SDC1_BAM_BASE,
.end = MSM_SDC1_BAM_BASE + (2 * SZ_4K) - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "bam_irq",
.start = SDC1_BAM_IRQ,
.end = SDC1_BAM_IRQ,
.flags = IORESOURCE_IRQ,
},
#endif
};
static struct resource resources_sdc2[] = {
{
.name = "core_mem",
.flags = IORESOURCE_MEM,
.start = MSM_SDC2_BASE,
.end = MSM_SDC2_DML_BASE - 1,
},
{
.name = "core_irq",
.flags = IORESOURCE_IRQ,
.start = SDC2_IRQ_0,
.end = SDC2_IRQ_0
},
#ifdef CONFIG_MMC_MSM_SPS_SUPPORT
{
.name = "dml_mem",
.start = MSM_SDC2_DML_BASE,
.end = MSM_SDC2_BAM_BASE - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "bam_mem",
.start = MSM_SDC2_BAM_BASE,
.end = MSM_SDC2_BAM_BASE + (2 * SZ_4K) - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "bam_irq",
.start = SDC2_BAM_IRQ,
.end = SDC2_BAM_IRQ,
.flags = IORESOURCE_IRQ,
},
#endif
};
static struct resource resources_sdc3[] = {
{
.name = "core_mem",
.flags = IORESOURCE_MEM,
.start = MSM_SDC3_BASE,
.end = MSM_SDC3_DML_BASE - 1,
},
{
.name = "core_irq",
.flags = IORESOURCE_IRQ,
.start = SDC3_IRQ_0,
.end = SDC3_IRQ_0
},
#ifdef CONFIG_MMC_MSM_SPS_SUPPORT
{
.name = "dml_mem",
.start = MSM_SDC3_DML_BASE,
.end = MSM_SDC3_BAM_BASE - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "bam_mem",
.start = MSM_SDC3_BAM_BASE,
.end = MSM_SDC3_BAM_BASE + (2 * SZ_4K) - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "bam_irq",
.start = SDC3_BAM_IRQ,
.end = SDC3_BAM_IRQ,
.flags = IORESOURCE_IRQ,
},
#endif
};
static struct resource resources_sdc4[] = {
{
.name = "core_mem",
.flags = IORESOURCE_MEM,
.start = MSM_SDC4_BASE,
.end = MSM_SDC4_DML_BASE - 1,
},
{
.name = "core_irq",
.flags = IORESOURCE_IRQ,
.start = SDC4_IRQ_0,
.end = SDC4_IRQ_0
},
#ifdef CONFIG_MMC_MSM_SPS_SUPPORT
{
.name = "dml_mem",
.start = MSM_SDC4_DML_BASE,
.end = MSM_SDC4_BAM_BASE - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "bam_mem",
.start = MSM_SDC4_BAM_BASE,
.end = MSM_SDC4_BAM_BASE + (2 * SZ_4K) - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "bam_irq",
.start = SDC4_BAM_IRQ,
.end = SDC4_BAM_IRQ,
.flags = IORESOURCE_IRQ,
},
#endif
};
struct platform_device apq8064_device_sdc1 = {
.name = "msm_sdcc",
.id = 1,
.num_resources = ARRAY_SIZE(resources_sdc1),
.resource = resources_sdc1,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
struct platform_device apq8064_device_sdc2 = {
.name = "msm_sdcc",
.id = 2,
.num_resources = ARRAY_SIZE(resources_sdc2),
.resource = resources_sdc2,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
struct platform_device apq8064_device_sdc3 = {
.name = "msm_sdcc",
.id = 3,
.num_resources = ARRAY_SIZE(resources_sdc3),
.resource = resources_sdc3,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
struct platform_device apq8064_device_sdc4 = {
.name = "msm_sdcc",
.id = 4,
.num_resources = ARRAY_SIZE(resources_sdc4),
.resource = resources_sdc4,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
static struct platform_device *apq8064_sdcc_devices[] __initdata = {
&apq8064_device_sdc1,
&apq8064_device_sdc2,
&apq8064_device_sdc3,
&apq8064_device_sdc4,
};
int __init apq8064_add_sdcc(unsigned int controller,
struct mmc_platform_data *plat)
{
struct platform_device *pdev;
if (!plat)
return 0;
if (controller < 1 || controller > 4)
return -EINVAL;
pdev = apq8064_sdcc_devices[controller-1];
pdev->dev.platform_data = plat;
return platform_device_register(pdev);
}
static struct resource resources_sps[] = {
{
.name = "pipe_mem",
.start = 0x12800000,
.end = 0x12800000 + 0x4000 - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "bamdma_dma",
.start = 0x12240000,
.end = 0x12240000 + 0x1000 - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "bamdma_bam",
.start = 0x12244000,
.end = 0x12244000 + 0x4000 - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "bamdma_irq",
.start = SPS_BAM_DMA_IRQ,
.end = SPS_BAM_DMA_IRQ,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm_bus_8064_sys_fabric = {
.name = "msm_bus_fabric",
.id = MSM_BUS_FAB_SYSTEM,
};
struct platform_device msm_bus_8064_apps_fabric = {
.name = "msm_bus_fabric",
.id = MSM_BUS_FAB_APPSS,
};
struct platform_device msm_bus_8064_mm_fabric = {
.name = "msm_bus_fabric",
.id = MSM_BUS_FAB_MMSS,
};
struct platform_device msm_bus_8064_sys_fpb = {
.name = "msm_bus_fabric",
.id = MSM_BUS_FAB_SYSTEM_FPB,
};
struct platform_device msm_bus_8064_cpss_fpb = {
.name = "msm_bus_fabric",
.id = MSM_BUS_FAB_CPSS_FPB,
};
static struct msm_sps_platform_data msm_sps_pdata = {
.bamdma_restricted_pipes = 0x06,
};
struct platform_device msm_device_sps_apq8064 = {
.name = "msm_sps",
.id = -1,
.num_resources = ARRAY_SIZE(resources_sps),
.resource = resources_sps,
.dev.platform_data = &msm_sps_pdata,
};
static struct resource smd_resource[] = {
{
.name = "a9_m2a_0",
.start = INT_A9_M2A_0,
.flags = IORESOURCE_IRQ,
},
{
.name = "a9_m2a_5",
.start = INT_A9_M2A_5,
.flags = IORESOURCE_IRQ,
},
{
.name = "adsp_a11",
.start = INT_ADSP_A11,
.flags = IORESOURCE_IRQ,
},
{
.name = "adsp_a11_smsm",
.start = INT_ADSP_A11_SMSM,
.flags = IORESOURCE_IRQ,
},
{
.name = "dsps_a11",
.start = INT_DSPS_A11,
.flags = IORESOURCE_IRQ,
},
{
.name = "dsps_a11_smsm",
.start = INT_DSPS_A11_SMSM,
.flags = IORESOURCE_IRQ,
},
{
.name = "wcnss_a11",
.start = INT_WCNSS_A11,
.flags = IORESOURCE_IRQ,
},
{
.name = "wcnss_a11_smsm",
.start = INT_WCNSS_A11_SMSM,
.flags = IORESOURCE_IRQ,
},
};
static struct smd_subsystem_config smd_config_list[] = {
{
.irq_config_id = SMD_MODEM,
.subsys_name = "gss",
.edge = SMD_APPS_MODEM,
.smd_int.irq_name = "a9_m2a_0",
.smd_int.flags = IRQF_TRIGGER_RISING,
.smd_int.irq_id = -1,
.smd_int.device_name = "smd_dev",
.smd_int.dev_id = 0,
.smd_int.out_bit_pos = 1 << 3,
.smd_int.out_base = (void __iomem *)MSM_APCS_GCC_BASE,
.smd_int.out_offset = 0x8,
.smsm_int.irq_name = "a9_m2a_5",
.smsm_int.flags = IRQF_TRIGGER_RISING,
.smsm_int.irq_id = -1,
.smsm_int.device_name = "smd_smsm",
.smsm_int.dev_id = 0,
.smsm_int.out_bit_pos = 1 << 4,
.smsm_int.out_base = (void __iomem *)MSM_APCS_GCC_BASE,
.smsm_int.out_offset = 0x8,
},
{
.irq_config_id = SMD_Q6,
.subsys_name = "q6",
.edge = SMD_APPS_QDSP,
.smd_int.irq_name = "adsp_a11",
.smd_int.flags = IRQF_TRIGGER_RISING,
.smd_int.irq_id = -1,
.smd_int.device_name = "smd_dev",
.smd_int.dev_id = 0,
.smd_int.out_bit_pos = 1 << 15,
.smd_int.out_base = (void __iomem *)MSM_APCS_GCC_BASE,
.smd_int.out_offset = 0x8,
.smsm_int.irq_name = "adsp_a11_smsm",
.smsm_int.flags = IRQF_TRIGGER_RISING,
.smsm_int.irq_id = -1,
.smsm_int.device_name = "smd_smsm",
.smsm_int.dev_id = 0,
.smsm_int.out_bit_pos = 1 << 14,
.smsm_int.out_base = (void __iomem *)MSM_APCS_GCC_BASE,
.smsm_int.out_offset = 0x8,
},
{
.irq_config_id = SMD_DSPS,
.subsys_name = "dsps",
.edge = SMD_APPS_DSPS,
.smd_int.irq_name = "dsps_a11",
.smd_int.flags = IRQF_TRIGGER_RISING,
.smd_int.irq_id = -1,
.smd_int.device_name = "smd_dev",
.smd_int.dev_id = 0,
.smd_int.out_bit_pos = 1,
.smd_int.out_base = (void __iomem *)MSM_SIC_NON_SECURE_BASE,
.smd_int.out_offset = 0x4080,
.smsm_int.irq_name = "dsps_a11_smsm",
.smsm_int.flags = IRQF_TRIGGER_RISING,
.smsm_int.irq_id = -1,
.smsm_int.device_name = "smd_smsm",
.smsm_int.dev_id = 0,
.smsm_int.out_bit_pos = 1,
.smsm_int.out_base = (void __iomem *)MSM_SIC_NON_SECURE_BASE,
.smsm_int.out_offset = 0x4094,
},
{
.irq_config_id = SMD_WCNSS,
.subsys_name = "wcnss",
.edge = SMD_APPS_WCNSS,
.smd_int.irq_name = "wcnss_a11",
.smd_int.flags = IRQF_TRIGGER_RISING,
.smd_int.irq_id = -1,
.smd_int.device_name = "smd_dev",
.smd_int.dev_id = 0,
.smd_int.out_bit_pos = 1 << 25,
.smd_int.out_base = (void __iomem *)MSM_APCS_GCC_BASE,
.smd_int.out_offset = 0x8,
.smsm_int.irq_name = "wcnss_a11_smsm",
.smsm_int.flags = IRQF_TRIGGER_RISING,
.smsm_int.irq_id = -1,
.smsm_int.device_name = "smd_smsm",
.smsm_int.dev_id = 0,
.smsm_int.out_bit_pos = 1 << 23,
.smsm_int.out_base = (void __iomem *)MSM_APCS_GCC_BASE,
.smsm_int.out_offset = 0x8,
},
};
static struct smd_subsystem_restart_config smd_ssr_config = {
.disable_smsm_reset_handshake = 1,
};
static struct smd_platform smd_platform_data = {
.num_ss_configs = ARRAY_SIZE(smd_config_list),
.smd_ss_configs = smd_config_list,
.smd_ssr_config = &smd_ssr_config,
};
struct platform_device msm_device_smd_apq8064 = {
.name = "msm_smd",
.id = -1,
.resource = smd_resource,
.num_resources = ARRAY_SIZE(smd_resource),
.dev = {
.platform_data = &smd_platform_data,
},
};
static struct resource resources_msm_pcie[] = {
{
.name = "pcie_parf",
.start = PCIE20_PARF_PHYS,
.end = PCIE20_PARF_PHYS + PCIE20_PARF_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "pcie_elbi",
.start = PCIE20_ELBI_PHYS,
.end = PCIE20_ELBI_PHYS + PCIE20_ELBI_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "pcie20",
.start = PCIE20_PHYS,
.end = PCIE20_PHYS + PCIE20_SIZE - 1,
.flags = IORESOURCE_MEM,
},
};
struct platform_device msm_device_pcie = {
.name = "msm_pcie",
.id = -1,
.num_resources = ARRAY_SIZE(resources_msm_pcie),
.resource = resources_msm_pcie,
};
#ifdef CONFIG_HW_RANDOM_MSM
/* PRNG device */
#define MSM_PRNG_PHYS 0x1A500000
static struct resource rng_resources = {
.flags = IORESOURCE_MEM,
.start = MSM_PRNG_PHYS,
.end = MSM_PRNG_PHYS + SZ_512 - 1,
};
struct platform_device apq8064_device_rng = {
.name = "msm_rng",
.id = 0,
.num_resources = 1,
.resource = &rng_resources,
};
#endif
static struct resource msm_gss_resources[] = {
{
.start = 0x10000000,
.end = 0x10000000 + SZ_256 - 1,
.flags = IORESOURCE_MEM,
},
{
.start = 0x10008000,
.end = 0x10008000 + SZ_256 - 1,
.flags = IORESOURCE_MEM,
},
};
struct platform_device msm_gss = {
.name = "pil_gss",
.id = -1,
.num_resources = ARRAY_SIZE(msm_gss_resources),
.resource = msm_gss_resources,
};
static struct fs_driver_data gfx3d_fs_data = {
.clks = (struct fs_clk_data[]){
{ .name = "core_clk", .reset_rate = 27000000 },
{ .name = "iface_clk" },
{ .name = "bus_clk" },
{ 0 }
},
.bus_port0 = MSM_BUS_MASTER_GRAPHICS_3D,
.bus_port1 = MSM_BUS_MASTER_GRAPHICS_3D_PORT1,
};
static struct fs_driver_data ijpeg_fs_data = {
.clks = (struct fs_clk_data[]){
{ .name = "core_clk" },
{ .name = "iface_clk" },
{ .name = "bus_clk" },
{ 0 }
},
.bus_port0 = MSM_BUS_MASTER_JPEG_ENC,
};
static struct fs_driver_data mdp_fs_data = {
.clks = (struct fs_clk_data[]){
{ .name = "core_clk" },
{ .name = "iface_clk" },
{ .name = "bus_clk" },
{ .name = "vsync_clk" },
{ .name = "lut_clk" },
{ .name = "tv_src_clk" },
{ .name = "tv_clk" },
{ .name = "reset1_clk" },
{ .name = "reset2_clk" },
{ 0 }
},
.bus_port0 = MSM_BUS_MASTER_MDP_PORT0,
.bus_port1 = MSM_BUS_MASTER_MDP_PORT1,
};
static struct fs_driver_data rot_fs_data = {
.clks = (struct fs_clk_data[]){
{ .name = "core_clk" },
{ .name = "iface_clk" },
{ .name = "bus_clk" },
{ 0 }
},
.bus_port0 = MSM_BUS_MASTER_ROTATOR,
};
static struct fs_driver_data ved_fs_data = {
.clks = (struct fs_clk_data[]){
{ .name = "core_clk" },
{ .name = "iface_clk" },
{ .name = "bus_clk" },
{ 0 }
},
.bus_port0 = MSM_BUS_MASTER_VIDEO_ENC,
.bus_port1 = MSM_BUS_MASTER_VIDEO_DEC,
};
static struct fs_driver_data vfe_fs_data = {
.clks = (struct fs_clk_data[]){
{ .name = "core_clk" },
{ .name = "iface_clk" },
{ .name = "bus_clk" },
{ 0 }
},
.bus_port0 = MSM_BUS_MASTER_VFE,
};
static struct fs_driver_data vpe_fs_data = {
.clks = (struct fs_clk_data[]){
{ .name = "core_clk" },
{ .name = "iface_clk" },
{ .name = "bus_clk" },
{ 0 }
},
.bus_port0 = MSM_BUS_MASTER_VPE,
};
static struct fs_driver_data vcap_fs_data = {
.clks = (struct fs_clk_data[]){
{ .name = "core_clk" },
{ .name = "iface_clk" },
{ .name = "bus_clk" },
{ 0 },
},
.bus_port0 = MSM_BUS_MASTER_VIDEO_CAP,
};
struct platform_device *apq8064_footswitch[] __initdata = {
FS_8X60(FS_MDP, "vdd", "mdp.0", &mdp_fs_data),
FS_8X60(FS_ROT, "vdd", "msm_rotator.0", &rot_fs_data),
FS_8X60(FS_IJPEG, "vdd", "msm_gemini.0", &ijpeg_fs_data),
FS_8X60(FS_VFE, "vdd", "msm_vfe.0", &vfe_fs_data),
FS_8X60(FS_VPE, "vdd", "msm_vpe.0", &vpe_fs_data),
FS_8X60(FS_GFX3D, "vdd", "kgsl-3d0.0", &gfx3d_fs_data),
FS_8X60(FS_VED, "vdd", "msm_vidc.0", &ved_fs_data),
FS_8X60(FS_VCAP, "vdd", "msm_vcap.0", &vcap_fs_data),
};
unsigned apq8064_num_footswitch __initdata = ARRAY_SIZE(apq8064_footswitch);
struct msm_rpm_platform_data apq8064_rpm_data __initdata = {
.reg_base_addrs = {
[MSM_RPM_PAGE_STATUS] = MSM_RPM_BASE,
[MSM_RPM_PAGE_CTRL] = MSM_RPM_BASE + 0x400,
[MSM_RPM_PAGE_REQ] = MSM_RPM_BASE + 0x600,
[MSM_RPM_PAGE_ACK] = MSM_RPM_BASE + 0xa00,
},
.irq_ack = RPM_APCC_CPU0_GP_HIGH_IRQ,
.irq_err = RPM_APCC_CPU0_GP_LOW_IRQ,
.irq_wakeup = RPM_APCC_CPU0_WAKE_UP_IRQ,
.ipc_rpm_reg = MSM_APCS_GCC_BASE + 0x008,
.ipc_rpm_val = 4,
.target_id = {
MSM_RPM_MAP(8064, NOTIFICATION_CONFIGURED_0, NOTIFICATION, 4),
MSM_RPM_MAP(8064, NOTIFICATION_REGISTERED_0, NOTIFICATION, 4),
MSM_RPM_MAP(8064, INVALIDATE_0, INVALIDATE, 8),
MSM_RPM_MAP(8064, TRIGGER_TIMED_TO, TRIGGER_TIMED, 1),
MSM_RPM_MAP(8064, TRIGGER_TIMED_SCLK_COUNT, TRIGGER_TIMED, 1),
MSM_RPM_MAP(8064, RPM_CTL, RPM_CTL, 1),
MSM_RPM_MAP(8064, CXO_CLK, CXO_CLK, 1),
MSM_RPM_MAP(8064, PXO_CLK, PXO_CLK, 1),
MSM_RPM_MAP(8064, APPS_FABRIC_CLK, APPS_FABRIC_CLK, 1),
MSM_RPM_MAP(8064, SYSTEM_FABRIC_CLK, SYSTEM_FABRIC_CLK, 1),
MSM_RPM_MAP(8064, MM_FABRIC_CLK, MM_FABRIC_CLK, 1),
MSM_RPM_MAP(8064, DAYTONA_FABRIC_CLK, DAYTONA_FABRIC_CLK, 1),
MSM_RPM_MAP(8064, SFPB_CLK, SFPB_CLK, 1),
MSM_RPM_MAP(8064, CFPB_CLK, CFPB_CLK, 1),
MSM_RPM_MAP(8064, MMFPB_CLK, MMFPB_CLK, 1),
MSM_RPM_MAP(8064, EBI1_CLK, EBI1_CLK, 1),
MSM_RPM_MAP(8064, APPS_FABRIC_CFG_HALT_0,
APPS_FABRIC_CFG_HALT, 2),
MSM_RPM_MAP(8064, APPS_FABRIC_CFG_CLKMOD_0,
APPS_FABRIC_CFG_CLKMOD, 3),
MSM_RPM_MAP(8064, APPS_FABRIC_CFG_IOCTL,
APPS_FABRIC_CFG_IOCTL, 1),
MSM_RPM_MAP(8064, APPS_FABRIC_ARB_0, APPS_FABRIC_ARB, 12),
MSM_RPM_MAP(8064, SYS_FABRIC_CFG_HALT_0,
SYS_FABRIC_CFG_HALT, 2),
MSM_RPM_MAP(8064, SYS_FABRIC_CFG_CLKMOD_0,
SYS_FABRIC_CFG_CLKMOD, 3),
MSM_RPM_MAP(8064, SYS_FABRIC_CFG_IOCTL,
SYS_FABRIC_CFG_IOCTL, 1),
MSM_RPM_MAP(8064, SYSTEM_FABRIC_ARB_0, SYSTEM_FABRIC_ARB, 30),
MSM_RPM_MAP(8064, MMSS_FABRIC_CFG_HALT_0,
MMSS_FABRIC_CFG_HALT, 2),
MSM_RPM_MAP(8064, MMSS_FABRIC_CFG_CLKMOD_0,
MMSS_FABRIC_CFG_CLKMOD, 3),
MSM_RPM_MAP(8064, MMSS_FABRIC_CFG_IOCTL,
MMSS_FABRIC_CFG_IOCTL, 1),
MSM_RPM_MAP(8064, MM_FABRIC_ARB_0, MM_FABRIC_ARB, 21),
MSM_RPM_MAP(8064, PM8921_S1_0, PM8921_S1, 2),
MSM_RPM_MAP(8064, PM8921_S2_0, PM8921_S2, 2),
MSM_RPM_MAP(8064, PM8921_S3_0, PM8921_S3, 2),
MSM_RPM_MAP(8064, PM8921_S4_0, PM8921_S4, 2),
MSM_RPM_MAP(8064, PM8921_S5_0, PM8921_S5, 2),
MSM_RPM_MAP(8064, PM8921_S6_0, PM8921_S6, 2),
MSM_RPM_MAP(8064, PM8921_S7_0, PM8921_S7, 2),
MSM_RPM_MAP(8064, PM8921_S8_0, PM8921_S8, 2),
MSM_RPM_MAP(8064, PM8921_L1_0, PM8921_L1, 2),
MSM_RPM_MAP(8064, PM8921_L2_0, PM8921_L2, 2),
MSM_RPM_MAP(8064, PM8921_L3_0, PM8921_L3, 2),
MSM_RPM_MAP(8064, PM8921_L4_0, PM8921_L4, 2),
MSM_RPM_MAP(8064, PM8921_L5_0, PM8921_L5, 2),
MSM_RPM_MAP(8064, PM8921_L6_0, PM8921_L6, 2),
MSM_RPM_MAP(8064, PM8921_L7_0, PM8921_L7, 2),
MSM_RPM_MAP(8064, PM8921_L8_0, PM8921_L8, 2),
MSM_RPM_MAP(8064, PM8921_L9_0, PM8921_L9, 2),
MSM_RPM_MAP(8064, PM8921_L10_0, PM8921_L10, 2),
MSM_RPM_MAP(8064, PM8921_L11_0, PM8921_L11, 2),
MSM_RPM_MAP(8064, PM8921_L12_0, PM8921_L12, 2),
MSM_RPM_MAP(8064, PM8921_L13_0, PM8921_L13, 2),
MSM_RPM_MAP(8064, PM8921_L14_0, PM8921_L14, 2),
MSM_RPM_MAP(8064, PM8921_L15_0, PM8921_L15, 2),
MSM_RPM_MAP(8064, PM8921_L16_0, PM8921_L16, 2),
MSM_RPM_MAP(8064, PM8921_L17_0, PM8921_L17, 2),
MSM_RPM_MAP(8064, PM8921_L18_0, PM8921_L18, 2),
MSM_RPM_MAP(8064, PM8921_L19_0, PM8921_L19, 2),
MSM_RPM_MAP(8064, PM8921_L20_0, PM8921_L20, 2),
MSM_RPM_MAP(8064, PM8921_L21_0, PM8921_L21, 2),
MSM_RPM_MAP(8064, PM8921_L22_0, PM8921_L22, 2),
MSM_RPM_MAP(8064, PM8921_L23_0, PM8921_L23, 2),
MSM_RPM_MAP(8064, PM8921_L24_0, PM8921_L24, 2),
MSM_RPM_MAP(8064, PM8921_L25_0, PM8921_L25, 2),
MSM_RPM_MAP(8064, PM8921_L26_0, PM8921_L26, 2),
MSM_RPM_MAP(8064, PM8921_L27_0, PM8921_L27, 2),
MSM_RPM_MAP(8064, PM8921_L28_0, PM8921_L28, 2),
MSM_RPM_MAP(8064, PM8921_L29_0, PM8921_L29, 2),
MSM_RPM_MAP(8064, PM8921_CLK1_0, PM8921_CLK1, 2),
MSM_RPM_MAP(8064, PM8921_CLK2_0, PM8921_CLK2, 2),
MSM_RPM_MAP(8064, PM8921_LVS1, PM8921_LVS1, 1),
MSM_RPM_MAP(8064, PM8921_LVS2, PM8921_LVS2, 1),
MSM_RPM_MAP(8064, PM8921_LVS3, PM8921_LVS3, 1),
MSM_RPM_MAP(8064, PM8921_LVS4, PM8921_LVS4, 1),
MSM_RPM_MAP(8064, PM8921_LVS5, PM8921_LVS5, 1),
MSM_RPM_MAP(8064, PM8921_LVS6, PM8921_LVS6, 1),
MSM_RPM_MAP(8064, PM8921_LVS7, PM8921_LVS7, 1),
MSM_RPM_MAP(8064, PM8821_S1_0, PM8821_S1, 2),
MSM_RPM_MAP(8064, PM8821_S2_0, PM8821_S2, 2),
MSM_RPM_MAP(8064, PM8821_L1_0, PM8821_L1, 2),
MSM_RPM_MAP(8064, NCP_0, NCP, 2),
MSM_RPM_MAP(8064, CXO_BUFFERS, CXO_BUFFERS, 1),
MSM_RPM_MAP(8064, USB_OTG_SWITCH, USB_OTG_SWITCH, 1),
MSM_RPM_MAP(8064, HDMI_SWITCH, HDMI_SWITCH, 1),
MSM_RPM_MAP(8064, DDR_DMM_0, DDR_DMM, 2),
MSM_RPM_MAP(8064, QDSS_CLK, QDSS_CLK, 1),
MSM_RPM_MAP(8064, VDDMIN_GPIO, VDDMIN_GPIO, 1),
},
.target_status = {
MSM_RPM_STATUS_ID_MAP(8064, VERSION_MAJOR),
MSM_RPM_STATUS_ID_MAP(8064, VERSION_MINOR),
MSM_RPM_STATUS_ID_MAP(8064, VERSION_BUILD),
MSM_RPM_STATUS_ID_MAP(8064, SUPPORTED_RESOURCES_0),
MSM_RPM_STATUS_ID_MAP(8064, SUPPORTED_RESOURCES_1),
MSM_RPM_STATUS_ID_MAP(8064, SUPPORTED_RESOURCES_2),
MSM_RPM_STATUS_ID_MAP(8064, RESERVED_SUPPORTED_RESOURCES_0),
MSM_RPM_STATUS_ID_MAP(8064, SEQUENCE),
MSM_RPM_STATUS_ID_MAP(8064, RPM_CTL),
MSM_RPM_STATUS_ID_MAP(8064, CXO_CLK),
MSM_RPM_STATUS_ID_MAP(8064, PXO_CLK),
MSM_RPM_STATUS_ID_MAP(8064, APPS_FABRIC_CLK),
MSM_RPM_STATUS_ID_MAP(8064, SYSTEM_FABRIC_CLK),
MSM_RPM_STATUS_ID_MAP(8064, MM_FABRIC_CLK),
MSM_RPM_STATUS_ID_MAP(8064, DAYTONA_FABRIC_CLK),
MSM_RPM_STATUS_ID_MAP(8064, SFPB_CLK),
MSM_RPM_STATUS_ID_MAP(8064, CFPB_CLK),
MSM_RPM_STATUS_ID_MAP(8064, MMFPB_CLK),
MSM_RPM_STATUS_ID_MAP(8064, EBI1_CLK),
MSM_RPM_STATUS_ID_MAP(8064, APPS_FABRIC_CFG_HALT),
MSM_RPM_STATUS_ID_MAP(8064, APPS_FABRIC_CFG_CLKMOD),
MSM_RPM_STATUS_ID_MAP(8064, APPS_FABRIC_CFG_IOCTL),
MSM_RPM_STATUS_ID_MAP(8064, APPS_FABRIC_ARB),
MSM_RPM_STATUS_ID_MAP(8064, SYS_FABRIC_CFG_HALT),
MSM_RPM_STATUS_ID_MAP(8064, SYS_FABRIC_CFG_CLKMOD),
MSM_RPM_STATUS_ID_MAP(8064, SYS_FABRIC_CFG_IOCTL),
MSM_RPM_STATUS_ID_MAP(8064, SYSTEM_FABRIC_ARB),
MSM_RPM_STATUS_ID_MAP(8064, MMSS_FABRIC_CFG_HALT),
MSM_RPM_STATUS_ID_MAP(8064, MMSS_FABRIC_CFG_CLKMOD),
MSM_RPM_STATUS_ID_MAP(8064, MMSS_FABRIC_CFG_IOCTL),
MSM_RPM_STATUS_ID_MAP(8064, MM_FABRIC_ARB),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_S1_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_S1_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_S2_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_S2_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_S3_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_S3_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_S4_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_S4_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_S5_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_S5_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_S6_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_S6_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_S7_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_S7_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_S8_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_S8_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L1_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L1_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L2_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L2_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L3_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L3_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L4_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L4_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L5_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L5_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L6_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L6_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L7_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L7_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L8_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L8_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L9_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L9_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L10_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L10_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L11_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L11_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L12_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L12_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L13_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L13_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L14_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L14_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L15_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L15_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L16_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L16_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L17_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L17_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L18_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L18_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L19_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L19_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L20_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L20_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L21_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L21_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L22_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L22_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L23_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L23_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L24_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L24_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L25_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L25_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L26_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L26_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L27_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L27_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L28_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L28_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L29_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_L29_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_CLK1_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_CLK1_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_CLK2_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_CLK2_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_LVS1),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_LVS2),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_LVS3),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_LVS4),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_LVS5),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_LVS6),
MSM_RPM_STATUS_ID_MAP(8064, PM8921_LVS7),
MSM_RPM_STATUS_ID_MAP(8064, NCP_0),
MSM_RPM_STATUS_ID_MAP(8064, NCP_1),
MSM_RPM_STATUS_ID_MAP(8064, CXO_BUFFERS),
MSM_RPM_STATUS_ID_MAP(8064, USB_OTG_SWITCH),
MSM_RPM_STATUS_ID_MAP(8064, HDMI_SWITCH),
MSM_RPM_STATUS_ID_MAP(8064, DDR_DMM_0),
MSM_RPM_STATUS_ID_MAP(8064, DDR_DMM_1),
MSM_RPM_STATUS_ID_MAP(8064, EBI1_CH0_RANGE),
MSM_RPM_STATUS_ID_MAP(8064, EBI1_CH1_RANGE),
MSM_RPM_STATUS_ID_MAP(8064, PM8821_S1_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8821_S1_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8821_S2_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8821_S2_1),
MSM_RPM_STATUS_ID_MAP(8064, PM8821_L1_0),
MSM_RPM_STATUS_ID_MAP(8064, PM8821_L1_1),
MSM_RPM_STATUS_ID_MAP(8064, VDDMIN_GPIO),
},
.target_ctrl_id = {
MSM_RPM_CTRL_MAP(8064, VERSION_MAJOR),
MSM_RPM_CTRL_MAP(8064, VERSION_MINOR),
MSM_RPM_CTRL_MAP(8064, VERSION_BUILD),
MSM_RPM_CTRL_MAP(8064, REQ_CTX_0),
MSM_RPM_CTRL_MAP(8064, REQ_SEL_0),
MSM_RPM_CTRL_MAP(8064, ACK_CTX_0),
MSM_RPM_CTRL_MAP(8064, ACK_SEL_0),
},
.sel_invalidate = MSM_RPM_8064_SEL_INVALIDATE,
.sel_notification = MSM_RPM_8064_SEL_NOTIFICATION,
.sel_last = MSM_RPM_8064_SEL_LAST,
.ver = {3, 0, 0},
};
struct platform_device apq8064_rpm_device = {
.name = "msm_rpm",
.id = -1,
};
static struct msm_rpmstats_platform_data msm_rpm_stat_pdata = {
.phys_addr_base = 0x0010DD04,
.phys_size = SZ_256,
};
struct platform_device apq8064_rpm_stat_device = {
.name = "msm_rpm_stat",
.id = -1,
.dev = {
.platform_data = &msm_rpm_stat_pdata,
},
};
static struct resource resources_rpm_master_stats[] = {
{
.start = MSM8064_RPM_MASTER_STATS_BASE,
.end = MSM8064_RPM_MASTER_STATS_BASE + SZ_256,
.flags = IORESOURCE_MEM,
},
};
static char *master_names[] = {
"KPSS",
"MPSS",
"LPASS",
"RIVA",
"DSPS",
};
static struct msm_rpm_master_stats_platform_data msm_rpm_master_stat_pdata = {
.masters = master_names,
.nomasters = ARRAY_SIZE(master_names),
};
struct platform_device apq8064_rpm_master_stat_device = {
.name = "msm_rpm_master_stat",
.id = -1,
.num_resources = ARRAY_SIZE(resources_rpm_master_stats),
.resource = resources_rpm_master_stats,
.dev = {
.platform_data = &msm_rpm_master_stat_pdata,
},
};
static struct msm_rpm_log_platform_data msm_rpm_log_pdata = {
.phys_addr_base = 0x0010C000,
.reg_offsets = {
[MSM_RPM_LOG_PAGE_INDICES] = 0x00000080,
[MSM_RPM_LOG_PAGE_BUFFER] = 0x000000A0,
},
.phys_size = SZ_8K,
.log_len = 6144, /* log's buffer length in bytes */
.log_len_mask = (6144 >> 2) - 1, /* length mask in units of u32 */
};
struct platform_device apq8064_rpm_log_device = {
.name = "msm_rpm_log",
.id = -1,
.dev = {
.platform_data = &msm_rpm_log_pdata,
},
};
/* Sensors DSPS platform data */
#define PPSS_DSPS_TCM_CODE_BASE 0x12000000
#define PPSS_DSPS_TCM_CODE_SIZE 0x28000
#define PPSS_DSPS_TCM_BUF_BASE 0x12040000
#define PPSS_DSPS_TCM_BUF_SIZE 0x4000
#define PPSS_DSPS_PIPE_BASE 0x12800000
#define PPSS_DSPS_PIPE_SIZE 0x4000
#define PPSS_DSPS_DDR_BASE 0x8fe00000
#define PPSS_DSPS_DDR_SIZE 0x100000
#define PPSS_SMEM_BASE 0x80000000
#define PPSS_SMEM_SIZE 0x200000
#define PPSS_REG_PHYS_BASE 0x12080000
#define PPSS_WDOG_UNMASKED_INT_EN 0x1808
static struct dsps_clk_info dsps_clks[] = {};
static struct dsps_regulator_info dsps_regs[] = {};
/*
* Note: GPIOs field is intialized in run-time at the function
* apq8064_init_dsps().
*/
struct msm_dsps_platform_data msm_dsps_pdata_8064 = {
.clks = dsps_clks,
.clks_num = ARRAY_SIZE(dsps_clks),
.gpios = NULL,
.gpios_num = 0,
.regs = dsps_regs,
.regs_num = ARRAY_SIZE(dsps_regs),
.dsps_pwr_ctl_en = 1,
.tcm_code_start = PPSS_DSPS_TCM_CODE_BASE,
.tcm_code_size = PPSS_DSPS_TCM_CODE_SIZE,
.tcm_buf_start = PPSS_DSPS_TCM_BUF_BASE,
.tcm_buf_size = PPSS_DSPS_TCM_BUF_SIZE,
.pipe_start = PPSS_DSPS_PIPE_BASE,
.pipe_size = PPSS_DSPS_PIPE_SIZE,
.ddr_start = PPSS_DSPS_DDR_BASE,
.ddr_size = PPSS_DSPS_DDR_SIZE,
.smem_start = PPSS_SMEM_BASE,
.smem_size = PPSS_SMEM_SIZE,
.ppss_wdog_unmasked_int_en_reg = PPSS_WDOG_UNMASKED_INT_EN,
.signature = DSPS_SIGNATURE,
};
static struct resource msm_dsps_resources[] = {
{
.start = PPSS_REG_PHYS_BASE,
.end = PPSS_REG_PHYS_BASE + SZ_8K - 1,
.name = "ppss_reg",
.flags = IORESOURCE_MEM,
},
{
.start = PPSS_WDOG_TIMER_IRQ,
.end = PPSS_WDOG_TIMER_IRQ,
.name = "ppss_wdog",
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm_dsps_device_8064 = {
.name = "msm_dsps",
.id = 0,
.num_resources = ARRAY_SIZE(msm_dsps_resources),
.resource = msm_dsps_resources,
.dev.platform_data = &msm_dsps_pdata_8064,
};
#ifdef CONFIG_MSM_MPM
static uint16_t msm_mpm_irqs_m2a[MSM_MPM_NR_MPM_IRQS] __initdata = {
[1] = MSM_GPIO_TO_INT(26),
[2] = MSM_GPIO_TO_INT(88),
[4] = MSM_GPIO_TO_INT(73),
[5] = MSM_GPIO_TO_INT(74),
[6] = MSM_GPIO_TO_INT(75),
[7] = MSM_GPIO_TO_INT(76),
[8] = MSM_GPIO_TO_INT(77),
[9] = MSM_GPIO_TO_INT(36),
[10] = MSM_GPIO_TO_INT(84),
[11] = MSM_GPIO_TO_INT(7),
[12] = MSM_GPIO_TO_INT(11),
[13] = MSM_GPIO_TO_INT(52),
[14] = MSM_GPIO_TO_INT(15),
[15] = MSM_GPIO_TO_INT(83),
[16] = USB3_HS_IRQ,
[19] = MSM_GPIO_TO_INT(61),
[20] = MSM_GPIO_TO_INT(58),
[23] = MSM_GPIO_TO_INT(65),
[24] = MSM_GPIO_TO_INT(63),
[25] = USB1_HS_IRQ,
[27] = HDMI_IRQ,
[29] = MSM_GPIO_TO_INT(22),
[30] = MSM_GPIO_TO_INT(72),
[31] = USB4_HS_IRQ,
[33] = MSM_GPIO_TO_INT(44),
[34] = MSM_GPIO_TO_INT(39),
[35] = MSM_GPIO_TO_INT(19),
[36] = MSM_GPIO_TO_INT(23),
[37] = MSM_GPIO_TO_INT(41),
[38] = MSM_GPIO_TO_INT(30),
[41] = MSM_GPIO_TO_INT(42),
[42] = MSM_GPIO_TO_INT(56),
[43] = MSM_GPIO_TO_INT(55),
[44] = MSM_GPIO_TO_INT(50),
[45] = MSM_GPIO_TO_INT(49),
[46] = MSM_GPIO_TO_INT(47),
[47] = MSM_GPIO_TO_INT(45),
[48] = MSM_GPIO_TO_INT(38),
[49] = MSM_GPIO_TO_INT(34),
[50] = MSM_GPIO_TO_INT(32),
[51] = MSM_GPIO_TO_INT(29),
[52] = MSM_GPIO_TO_INT(18),
[53] = MSM_GPIO_TO_INT(10),
[54] = MSM_GPIO_TO_INT(81),
[55] = MSM_GPIO_TO_INT(6),
[56] = MSM_GPIO_TO_INT(82),
};
static uint16_t msm_mpm_bypassed_apps_irqs[] __initdata = {
TLMM_MSM_SUMMARY_IRQ,
RPM_APCC_CPU0_GP_HIGH_IRQ,
RPM_APCC_CPU0_GP_MEDIUM_IRQ,
RPM_APCC_CPU0_GP_LOW_IRQ,
RPM_APCC_CPU0_WAKE_UP_IRQ,
RPM_APCC_CPU1_GP_HIGH_IRQ,
RPM_APCC_CPU1_GP_MEDIUM_IRQ,
RPM_APCC_CPU1_GP_LOW_IRQ,
RPM_APCC_CPU1_WAKE_UP_IRQ,
MSS_TO_APPS_IRQ_0,
MSS_TO_APPS_IRQ_1,
MSS_TO_APPS_IRQ_2,
MSS_TO_APPS_IRQ_3,
MSS_TO_APPS_IRQ_4,
MSS_TO_APPS_IRQ_5,
MSS_TO_APPS_IRQ_6,
MSS_TO_APPS_IRQ_7,
MSS_TO_APPS_IRQ_8,
MSS_TO_APPS_IRQ_9,
LPASS_SCSS_GP_LOW_IRQ,
LPASS_SCSS_GP_MEDIUM_IRQ,
LPASS_SCSS_GP_HIGH_IRQ,
SPS_MTI_30,
SPS_MTI_31,
RIVA_APSS_SPARE_IRQ,
RIVA_APPS_WLAN_SMSM_IRQ,
RIVA_APPS_WLAN_RX_DATA_AVAIL_IRQ,
RIVA_APPS_WLAN_DATA_XFER_DONE_IRQ,
PM8821_SEC_IRQ_N,
};
struct msm_mpm_device_data apq8064_mpm_dev_data __initdata = {
.irqs_m2a = msm_mpm_irqs_m2a,
.irqs_m2a_size = ARRAY_SIZE(msm_mpm_irqs_m2a),
.bypassed_apps_irqs = msm_mpm_bypassed_apps_irqs,
.bypassed_apps_irqs_size = ARRAY_SIZE(msm_mpm_bypassed_apps_irqs),
.mpm_request_reg_base = MSM_RPM_BASE + 0x9d8,
.mpm_status_reg_base = MSM_RPM_BASE + 0xdf8,
.mpm_apps_ipc_reg = MSM_APCS_GCC_BASE + 0x008,
.mpm_apps_ipc_val = BIT(1),
.mpm_ipc_irq = RPM_APCC_CPU0_GP_MEDIUM_IRQ,
};
#endif
/* AP2MDM_SOFT_RESET is implemented by the PON_RESET_N gpio */
#define MDM2AP_ERRFATAL 19
#define AP2MDM_ERRFATAL 18
#define MDM2AP_STATUS 49
#define AP2MDM_STATUS 48
#define AP2MDM_SOFT_RESET 27
#define I2S_AP2MDM_SOFT_RESET 0
#define AP2MDM_WAKEUP 35
#define I2S_AP2MDM_WAKEUP 44
#ifdef CONFIG_MSM_HSIC_GPIO_REV06
#define MDM2AP_PBLRDY 31
#else
#define MDM2AP_PBLRDY 46
#endif
#define AMDM2AP_PBLRDY_DSDA2 31
#define I2S_MDM2AP_PBLRDY 81
/* Gpios for second MDM */
#define BMDM2AP_ERRFATAL 81
#define AP2BMDM_ERRFATAL 18
#define BMDM2AP_STATUS 32
#define AP2BMDM_STATUS 56
#define AP2BMDM_SOFT_RESET 3
#define AP2BMDM_WAKEUP 29
#define SGLTE2_QSC2AP_STATUS 51
#define SGLTE2_QSC2AP_ERRFATAL 52
#define SGLTE2_PM2QSC_SOFT_RESET PM8921_GPIO_PM_TO_SYS(23)
#define SGLTE2_PM2QSC_KEYPADPWR PM8921_GPIO_PM_TO_SYS(21)
static struct resource mdm_resources[] = {
{
.start = MDM2AP_ERRFATAL,
.end = MDM2AP_ERRFATAL,
.name = "MDM2AP_ERRFATAL",
.flags = IORESOURCE_IO,
},
{
.start = AP2MDM_ERRFATAL,
.end = AP2MDM_ERRFATAL,
.name = "AP2MDM_ERRFATAL",
.flags = IORESOURCE_IO,
},
{
.start = MDM2AP_STATUS,
.end = MDM2AP_STATUS,
.name = "MDM2AP_STATUS",
.flags = IORESOURCE_IO,
},
{
.start = AP2MDM_STATUS,
.end = AP2MDM_STATUS,
.name = "AP2MDM_STATUS",
.flags = IORESOURCE_IO,
},
{
.start = AP2MDM_SOFT_RESET,
.end = AP2MDM_SOFT_RESET,
.name = "AP2MDM_SOFT_RESET",
.flags = IORESOURCE_IO,
},
{
.start = AP2MDM_WAKEUP,
.end = AP2MDM_WAKEUP,
.name = "AP2MDM_WAKEUP",
.flags = IORESOURCE_IO,
},
{
.start = MDM2AP_PBLRDY,
.end = MDM2AP_PBLRDY,
.name = "MDM2AP_PBLRDY",
.flags = IORESOURCE_IO,
},
};
static struct resource mdm_dsda2_amdm_resources[] = {
{
.start = MDM2AP_ERRFATAL,
.end = MDM2AP_ERRFATAL,
.name = "MDM2AP_ERRFATAL",
.flags = IORESOURCE_IO,
},
{
.start = AP2MDM_ERRFATAL,
.end = AP2MDM_ERRFATAL,
.name = "AP2MDM_ERRFATAL",
.flags = IORESOURCE_IO,
},
{
.start = MDM2AP_STATUS,
.end = MDM2AP_STATUS,
.name = "MDM2AP_STATUS",
.flags = IORESOURCE_IO,
},
{
.start = AP2MDM_STATUS,
.end = AP2MDM_STATUS,
.name = "AP2MDM_STATUS",
.flags = IORESOURCE_IO,
},
{
.start = AP2MDM_SOFT_RESET,
.end = AP2MDM_SOFT_RESET,
.name = "AP2MDM_SOFT_RESET",
.flags = IORESOURCE_IO,
},
{
.start = AP2MDM_WAKEUP,
.end = AP2MDM_WAKEUP,
.name = "AP2MDM_WAKEUP",
.flags = IORESOURCE_IO,
},
{
.start = AMDM2AP_PBLRDY_DSDA2,
.end = AMDM2AP_PBLRDY_DSDA2,
.name = "MDM2AP_PBLRDY",
.flags = IORESOURCE_IO,
},
};
static struct resource mdm_dsda2_bmdm_resources[] = {
{
.start = BMDM2AP_ERRFATAL,
.end = BMDM2AP_ERRFATAL,
.name = "MDM2AP_ERRFATAL",
.flags = IORESOURCE_IO,
},
{
.start = AP2BMDM_ERRFATAL,
.end = AP2BMDM_ERRFATAL,
.name = "AP2MDM_ERRFATAL",
.flags = IORESOURCE_IO,
},
{
.start = BMDM2AP_STATUS,
.end = BMDM2AP_STATUS,
.name = "MDM2AP_STATUS",
.flags = IORESOURCE_IO,
},
{
.start = AP2BMDM_STATUS,
.end = AP2BMDM_STATUS,
.name = "AP2MDM_STATUS",
.flags = IORESOURCE_IO,
},
{
.start = AP2BMDM_SOFT_RESET,
.end = AP2BMDM_SOFT_RESET,
.name = "AP2MDM_SOFT_RESET",
.flags = IORESOURCE_IO,
},
{
.start = AP2BMDM_WAKEUP,
.end = AP2BMDM_WAKEUP,
.name = "AP2MDM_WAKEUP",
.flags = IORESOURCE_IO,
},
};
static struct resource i2s_mdm_resources[] = {
{
.start = MDM2AP_ERRFATAL,
.end = MDM2AP_ERRFATAL,
.name = "MDM2AP_ERRFATAL",
.flags = IORESOURCE_IO,
},
{
.start = AP2MDM_ERRFATAL,
.end = AP2MDM_ERRFATAL,
.name = "AP2MDM_ERRFATAL",
.flags = IORESOURCE_IO,
},
{
.start = MDM2AP_STATUS,
.end = MDM2AP_STATUS,
.name = "MDM2AP_STATUS",
.flags = IORESOURCE_IO,
},
{
.start = AP2MDM_STATUS,
.end = AP2MDM_STATUS,
.name = "AP2MDM_STATUS",
.flags = IORESOURCE_IO,
},
{
.start = I2S_AP2MDM_SOFT_RESET,
.end = I2S_AP2MDM_SOFT_RESET,
.name = "AP2MDM_SOFT_RESET",
.flags = IORESOURCE_IO,
},
{
.start = I2S_AP2MDM_WAKEUP,
.end = I2S_AP2MDM_WAKEUP,
.name = "AP2MDM_WAKEUP",
.flags = IORESOURCE_IO,
},
{
.start = I2S_MDM2AP_PBLRDY,
.end = I2S_MDM2AP_PBLRDY,
.name = "MDM2AP_PBLRDY",
.flags = IORESOURCE_IO,
},
};
static struct resource sglte2_qsc_resources[] = {
{
.start = SGLTE2_QSC2AP_ERRFATAL,
.end = SGLTE2_QSC2AP_ERRFATAL,
.name = "MDM2AP_ERRFATAL",
.flags = IORESOURCE_IO,
},
{
.start = AP2MDM_ERRFATAL,
.end = AP2MDM_ERRFATAL,
.name = "AP2MDM_ERRFATAL",
.flags = IORESOURCE_IO,
},
{
.start = SGLTE2_QSC2AP_STATUS,
.end = SGLTE2_QSC2AP_STATUS,
.name = "MDM2AP_STATUS",
.flags = IORESOURCE_IO,
},
{
.start = AP2MDM_STATUS,
.end = AP2MDM_STATUS,
.name = "AP2MDM_STATUS",
.flags = IORESOURCE_IO,
},
{
.start = SGLTE2_PM2QSC_KEYPADPWR,
.end = SGLTE2_PM2QSC_KEYPADPWR,
.name = "AP2MDM_KPDPWR_N",
.flags = IORESOURCE_IO,
},
{
.start = SGLTE2_PM2QSC_SOFT_RESET,
.end = SGLTE2_PM2QSC_SOFT_RESET,
.name = "AP2MDM_SOFT_RESET",
.flags = IORESOURCE_IO,
},
};
struct platform_device mdm_8064_device = {
.name = "mdm2_modem",
.id = -1,
.num_resources = ARRAY_SIZE(mdm_resources),
.resource = mdm_resources,
};
struct platform_device amdm_8064_device = {
.name = "mdm2_modem",
.id = 0,
.num_resources = ARRAY_SIZE(mdm_dsda2_amdm_resources),
.resource = mdm_dsda2_amdm_resources,
};
struct platform_device bmdm_8064_device = {
.name = "mdm2_modem",
.id = 1,
.num_resources = ARRAY_SIZE(mdm_dsda2_bmdm_resources),
.resource = mdm_dsda2_bmdm_resources,
};
struct platform_device i2s_mdm_8064_device = {
.name = "mdm2_modem",
.id = -1,
.num_resources = ARRAY_SIZE(i2s_mdm_resources),
.resource = i2s_mdm_resources,
};
struct platform_device sglte_mdm_8064_device = {
.name = "mdm2_modem",
.id = 0,
.num_resources = ARRAY_SIZE(mdm_resources),
.resource = mdm_resources,
};
struct platform_device sglte2_qsc_8064_device = {
.name = "mdm2_modem",
.id = 1,
.num_resources = ARRAY_SIZE(sglte2_qsc_resources),
.resource = sglte2_qsc_resources,
};
static struct msm_dcvs_sync_rule apq8064_dcvs_sync_rules[] = {
{1026000, 400000},
{384000, 200000},
{0, 128000},
};
static struct msm_dcvs_platform_data apq8064_dcvs_data = {
.sync_rules = apq8064_dcvs_sync_rules,
.num_sync_rules = ARRAY_SIZE(apq8064_dcvs_sync_rules),
.gpu_max_nom_khz = 320000,
};
struct platform_device apq8064_dcvs_device = {
.name = "dcvs",
.id = -1,
.dev = {
.platform_data = &apq8064_dcvs_data,
},
};
static struct msm_dcvs_core_info apq8064_core_info = {
.num_cores = 4,
.sensors = (int[]){7, 8, 9, 10},
.thermal_poll_ms = 60000,
.core_param = {
.core_type = MSM_DCVS_CORE_TYPE_CPU,
},
.algo_param = {
.disable_pc_threshold = 1458000,
.em_win_size_min_us = 100000,
.em_win_size_max_us = 300000,
.em_max_util_pct = 97,
.group_id = 1,
.max_freq_chg_time_us = 100000,
.slack_mode_dynamic = 0,
.slack_weight_thresh_pct = 3,
.slack_time_min_us = 45000,
.slack_time_max_us = 45000,
.ss_no_corr_below_freq = 0,
.ss_win_size_min_us = 1000000,
.ss_win_size_max_us = 1000000,
.ss_util_pct = 95,
},
.energy_coeffs = {
.active_coeff_a = 336,
.active_coeff_b = 0,
.active_coeff_c = 0,
.leakage_coeff_a = -17720,
.leakage_coeff_b = 37,
.leakage_coeff_c = 3329,
.leakage_coeff_d = -277,
},
.power_param = {
.current_temp = 25,
.num_freq = 0, /* set at runtime */
}
};
#define APQ8064_LPM_LATENCY 1000 /* >100 usec for WFI */
static struct msm_gov_platform_data gov_platform_data = {
.info = &apq8064_core_info,
.latency = APQ8064_LPM_LATENCY,
};
struct platform_device apq8064_msm_gov_device = {
.name = "msm_dcvs_gov",
.id = -1,
.dev = {
.platform_data = &gov_platform_data,
},
};
static struct msm_mpd_algo_param apq8064_mpd_algo_param = {
.em_win_size_min_us = 10000,
.em_win_size_max_us = 100000,
.em_max_util_pct = 90,
.online_util_pct_min = 60,
.slack_time_min_us = 50000,
.slack_time_max_us = 100000,
};
struct platform_device apq8064_msm_mpd_device = {
.name = "msm_mpdecision",
.id = -1,
.dev = {
.platform_data = &apq8064_mpd_algo_param,
},
};
#ifdef CONFIG_MSM_VCAP
#define VCAP_HW_BASE 0x05900000
static struct msm_bus_vectors vcap_init_vectors[] = {
{
.src = MSM_BUS_MASTER_VIDEO_CAP,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = 0,
},
};
static struct msm_bus_vectors vcap_480_vectors[] = {
{
.src = MSM_BUS_MASTER_VIDEO_CAP,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 480 * 720 * 3 * 60,
.ib = 480 * 720 * 3 * 60 * 1.5,
},
};
static struct msm_bus_vectors vcap_576_vectors[] = {
{
.src = MSM_BUS_MASTER_VIDEO_CAP,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 576 * 720 * 3 * 60,
.ib = 576 * 720 * 3 * 60 * 1.5,
},
};
static struct msm_bus_vectors vcap_720_vectors[] = {
{
.src = MSM_BUS_MASTER_VIDEO_CAP,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 1280 * 720 * 3 * 60,
.ib = 1280 * 720 * 3 * 60 * 1.5,
},
};
static struct msm_bus_vectors vcap_1080_vectors[] = {
{
.src = MSM_BUS_MASTER_VIDEO_CAP,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 1920 * 1080 * 3 * 60,
.ib = 1920 * 1080 * 3 * 60 * 1.5,
},
};
static struct msm_bus_paths vcap_bus_usecases[] = {
{
ARRAY_SIZE(vcap_init_vectors),
vcap_init_vectors,
},
{
ARRAY_SIZE(vcap_480_vectors),
vcap_480_vectors,
},
{
ARRAY_SIZE(vcap_576_vectors),
vcap_576_vectors,
},
{
ARRAY_SIZE(vcap_720_vectors),
vcap_720_vectors,
},
{
ARRAY_SIZE(vcap_1080_vectors),
vcap_1080_vectors,
},
};
static struct msm_bus_scale_pdata vcap_axi_client_pdata = {
vcap_bus_usecases,
ARRAY_SIZE(vcap_bus_usecases),
};
static struct resource msm_vcap_resources[] = {
{
.name = "vcap",
.start = VCAP_HW_BASE,
.end = VCAP_HW_BASE + SZ_1M - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "vc_irq",
.start = VCAP_VC,
.end = VCAP_VC,
.flags = IORESOURCE_IRQ,
},
{
.name = "vp_irq",
.start = VCAP_VP,
.end = VCAP_VP,
.flags = IORESOURCE_IRQ,
},
};
static unsigned vcap_gpios[] = {
2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 18, 19, 20, 21,
22, 23, 24, 25, 26, 80, 82,
83, 84, 85, 86, 87,
};
static struct vcap_platform_data vcap_pdata = {
.gpios = vcap_gpios,
.num_gpios = ARRAY_SIZE(vcap_gpios),
.bus_client_pdata = &vcap_axi_client_pdata
};
struct platform_device msm8064_device_vcap = {
.name = "msm_vcap",
.id = 0,
.resource = msm_vcap_resources,
.num_resources = ARRAY_SIZE(msm_vcap_resources),
.dev = {
.platform_data = &vcap_pdata,
},
};
#endif
static struct resource msm_cache_erp_resources[] = {
{
.name = "l1_irq",
.start = SC_SICCPUXEXTFAULTIRPTREQ,
.flags = IORESOURCE_IRQ,
},
{
.name = "l2_irq",
.start = APCC_QGICL2IRPTREQ,
.flags = IORESOURCE_IRQ,
}
};
struct platform_device apq8064_device_cache_erp = {
.name = "msm_cache_erp",
.id = -1,
.num_resources = ARRAY_SIZE(msm_cache_erp_resources),
.resource = msm_cache_erp_resources,
};
#define CORESIGHT_PHYS_BASE 0x01A00000
#define CORESIGHT_FUNNEL_PHYS_BASE (CORESIGHT_PHYS_BASE + 0x4000)
#define CORESIGHT_ETM2_PHYS_BASE (CORESIGHT_PHYS_BASE + 0x1E000)
#define CORESIGHT_ETM3_PHYS_BASE (CORESIGHT_PHYS_BASE + 0x1F000)
static struct resource coresight_funnel_resources[] = {
{
.start = CORESIGHT_FUNNEL_PHYS_BASE,
.end = CORESIGHT_FUNNEL_PHYS_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
};
static const int coresight_funnel_outports[] = { 0, 1 };
static const int coresight_funnel_child_ids[] = { 0, 1 };
static const int coresight_funnel_child_ports[] = { 0, 0 };
static struct coresight_platform_data coresight_funnel_pdata = {
.id = 2,
.name = "coresight-funnel",
.nr_inports = 8,
.outports = coresight_funnel_outports,
.child_ids = coresight_funnel_child_ids,
.child_ports = coresight_funnel_child_ports,
.nr_outports = ARRAY_SIZE(coresight_funnel_outports),
};
struct platform_device apq8064_coresight_funnel_device = {
.name = "coresight-funnel",
.id = 0,
.num_resources = ARRAY_SIZE(coresight_funnel_resources),
.resource = coresight_funnel_resources,
.dev = {
.platform_data = &coresight_funnel_pdata,
},
};
static struct resource coresight_etm2_resources[] = {
{
.start = CORESIGHT_ETM2_PHYS_BASE,
.end = CORESIGHT_ETM2_PHYS_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
};
static const int coresight_etm2_outports[] = { 0 };
static const int coresight_etm2_child_ids[] = { 2 };
static const int coresight_etm2_child_ports[] = { 4 };
static struct coresight_platform_data coresight_etm2_pdata = {
.id = 6,
.name = "coresight-etm2",
.nr_inports = 0,
.outports = coresight_etm2_outports,
.child_ids = coresight_etm2_child_ids,
.child_ports = coresight_etm2_child_ports,
.nr_outports = ARRAY_SIZE(coresight_etm2_outports),
};
struct platform_device coresight_etm2_device = {
.name = "coresight-etm",
.id = 2,
.num_resources = ARRAY_SIZE(coresight_etm2_resources),
.resource = coresight_etm2_resources,
.dev = {
.platform_data = &coresight_etm2_pdata,
},
};
static struct resource coresight_etm3_resources[] = {
{
.start = CORESIGHT_ETM3_PHYS_BASE,
.end = CORESIGHT_ETM3_PHYS_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
};
static const int coresight_etm3_outports[] = { 0 };
static const int coresight_etm3_child_ids[] = { 2 };
static const int coresight_etm3_child_ports[] = { 5 };
static struct coresight_platform_data coresight_etm3_pdata = {
.id = 7,
.name = "coresight-etm3",
.nr_inports = 0,
.outports = coresight_etm3_outports,
.child_ids = coresight_etm3_child_ids,
.child_ports = coresight_etm3_child_ports,
.nr_outports = ARRAY_SIZE(coresight_etm3_outports),
};
struct platform_device coresight_etm3_device = {
.name = "coresight-etm",
.id = 3,
.num_resources = ARRAY_SIZE(coresight_etm3_resources),
.resource = coresight_etm3_resources,
.dev = {
.platform_data = &coresight_etm3_pdata,
},
};
struct msm_iommu_domain_name apq8064_iommu_ctx_names[] = {
/* Camera */
{
.name = "ijpeg_src",
.domain = CAMERA_DOMAIN,
},
/* Camera */
{
.name = "ijpeg_dst",
.domain = CAMERA_DOMAIN,
},
/* Camera */
{
.name = "jpegd_src",
.domain = CAMERA_DOMAIN,
},
/* Camera */
{
.name = "jpegd_dst",
.domain = CAMERA_DOMAIN,
},
/* Rotator src*/
{
.name = "rot_src",
.domain = ROTATOR_SRC_DOMAIN,
},
/* Rotator dst */
{
.name = "rot_dst",
.domain = ROTATOR_DST_DOMAIN,
},
/* Video */
{
.name = "vcodec_a_mm1",
.domain = VIDEO_DOMAIN,
},
/* Video */
{
.name = "vcodec_b_mm2",
.domain = VIDEO_DOMAIN,
},
/* Video */
{
.name = "vcodec_a_stream",
.domain = VIDEO_DOMAIN,
},
};
static struct mem_pool apq8064_video_pools[] = {
/*
* Video hardware has the following requirements:
* 1. All video addresses used by the video hardware must be at a higher
* address than video firmware address.
* 2. Video hardware can only access a range of 256MB from the base of
* the video firmware.
*/
[VIDEO_FIRMWARE_POOL] =
/* Low addresses, intended for video firmware */
{
.paddr = SZ_128K,
.size = SZ_16M - SZ_128K,
},
[VIDEO_MAIN_POOL] =
/* Main video pool */
{
.paddr = SZ_16M,
.size = SZ_256M - SZ_16M,
},
[GEN_POOL] =
/* Remaining address space up to 2G */
{
.paddr = SZ_256M,
.size = SZ_2G - SZ_256M,
},
};
static struct mem_pool apq8064_camera_pools[] = {
[GEN_POOL] =
/* One address space for camera */
{
.paddr = SZ_128K,
.size = SZ_2G - SZ_128K,
},
};
static struct mem_pool apq8064_display_read_pools[] = {
[GEN_POOL] =
/* One address space for display reads */
{
.paddr = SZ_128K,
.size = SZ_2G - SZ_128K,
},
};
static struct mem_pool apq8064_display_write_pools[] = {
[GEN_POOL] =
/* One address space for display writes */
{
.paddr = SZ_128K,
.size = SZ_2G - SZ_128K,
},
};
static struct mem_pool apq8064_rotator_src_pools[] = {
[GEN_POOL] =
/* One address space for rotator src */
{
.paddr = SZ_128K,
.size = SZ_2G - SZ_128K,
},
};
static struct mem_pool apq8064_rotator_dst_pools[] = {
[GEN_POOL] =
/* One address space for rotator dst */
{
.paddr = SZ_128K,
.size = SZ_2G - SZ_128K,
},
};
static struct msm_iommu_domain apq8064_iommu_domains[] = {
[VIDEO_DOMAIN] = {
.iova_pools = apq8064_video_pools,
.npools = ARRAY_SIZE(apq8064_video_pools),
},
[CAMERA_DOMAIN] = {
.iova_pools = apq8064_camera_pools,
.npools = ARRAY_SIZE(apq8064_camera_pools),
},
[DISPLAY_READ_DOMAIN] = {
.iova_pools = apq8064_display_read_pools,
.npools = ARRAY_SIZE(apq8064_display_read_pools),
},
[DISPLAY_WRITE_DOMAIN] = {
.iova_pools = apq8064_display_write_pools,
.npools = ARRAY_SIZE(apq8064_display_write_pools),
},
[ROTATOR_SRC_DOMAIN] = {
.iova_pools = apq8064_rotator_src_pools,
.npools = ARRAY_SIZE(apq8064_rotator_src_pools),
},
[ROTATOR_DST_DOMAIN] = {
.iova_pools = apq8064_rotator_dst_pools,
.npools = ARRAY_SIZE(apq8064_rotator_dst_pools),
},
};
struct iommu_domains_pdata apq8064_iommu_domain_pdata = {
.domains = apq8064_iommu_domains,
.ndomains = ARRAY_SIZE(apq8064_iommu_domains),
.domain_names = apq8064_iommu_ctx_names,
.nnames = ARRAY_SIZE(apq8064_iommu_ctx_names),
.domain_alloc_flags = 0,
};
struct platform_device apq8064_iommu_domain_device = {
.name = "iommu_domains",
.id = -1,
.dev = {
.platform_data = &apq8064_iommu_domain_pdata,
}
};
struct msm_rtb_platform_data apq8064_rtb_pdata = {
.size = SZ_1M,
};
static int __init msm_rtb_set_buffer_size(char *p)
{
int s;
s = memparse(p, NULL);
apq8064_rtb_pdata.size = ALIGN(s, SZ_4K);
return 0;
}
early_param("msm_rtb_size", msm_rtb_set_buffer_size);
struct platform_device apq8064_rtb_device = {
.name = "msm_rtb",
.id = -1,
.dev = {
.platform_data = &apq8064_rtb_pdata,
},
};
#define APQ8064_L1_SIZE SZ_1M
/*
* The actual L2 size is smaller but we need a larger buffer
* size to store other dump information
*/
#define APQ8064_L2_SIZE SZ_8M
struct msm_cache_dump_platform_data apq8064_cache_dump_pdata = {
.l2_size = APQ8064_L2_SIZE,
.l1_size = APQ8064_L1_SIZE,
};
struct platform_device apq8064_cache_dump_device = {
.name = "msm_cache_dump",
.id = -1,
.dev = {
.platform_data = &apq8064_cache_dump_pdata,
},
};
| gpl-2.0 |
mahirkukreja/delos3geurkernel | arch/arm/mach-msm/acpuclock.c | 311 | 1528 | /* Copyright (c) 2011, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/cpu.h>
#include <linux/smp.h>
#include "acpuclock.h"
static struct acpuclk_data *acpuclk_data;
unsigned long acpuclk_get_rate(int cpu)
{
if (!acpuclk_data->get_rate)
return 0;
return acpuclk_data->get_rate(cpu);
}
int acpuclk_set_rate(int cpu, unsigned long rate, enum setrate_reason reason)
{
if (!acpuclk_data->set_rate)
return 0;
return acpuclk_data->set_rate(cpu, rate, reason);
}
uint32_t acpuclk_get_switch_time(void)
{
return acpuclk_data->switch_time_us;
}
unsigned long acpuclk_power_collapse(void)
{
unsigned long rate = acpuclk_get_rate(smp_processor_id());
acpuclk_set_rate(smp_processor_id(), acpuclk_data->power_collapse_khz,
SETRATE_PC);
return rate;
}
unsigned long acpuclk_wait_for_irq(void)
{
unsigned long rate = acpuclk_get_rate(smp_processor_id());
acpuclk_set_rate(smp_processor_id(), acpuclk_data->wait_for_irq_khz,
SETRATE_SWFI);
return rate;
}
void __devinit acpuclk_register(struct acpuclk_data *data)
{
acpuclk_data = data;
}
| gpl-2.0 |
Daniil2017/HTC-desire-A8181-kernel | kernel/trace/trace_workqueue.c | 567 | 7414 | /*
* Workqueue statistical tracer.
*
* Copyright (C) 2008 Frederic Weisbecker <fweisbec@gmail.com>
*
*/
#include <trace/events/workqueue.h>
#include <linux/list.h>
#include <linux/percpu.h>
#include <linux/kref.h>
#include "trace_stat.h"
#include "trace.h"
/* A cpu workqueue thread */
struct cpu_workqueue_stats {
struct list_head list;
struct kref kref;
int cpu;
pid_t pid;
/* Can be inserted from interrupt or user context, need to be atomic */
atomic_t inserted;
/*
* Don't need to be atomic, works are serialized in a single workqueue thread
* on a single CPU.
*/
unsigned int executed;
};
/* List of workqueue threads on one cpu */
struct workqueue_global_stats {
struct list_head list;
spinlock_t lock;
};
/* Don't need a global lock because allocated before the workqueues, and
* never freed.
*/
static DEFINE_PER_CPU(struct workqueue_global_stats, all_workqueue_stat);
#define workqueue_cpu_stat(cpu) (&per_cpu(all_workqueue_stat, cpu))
static void cpu_workqueue_stat_free(struct kref *kref)
{
kfree(container_of(kref, struct cpu_workqueue_stats, kref));
}
/* Insertion of a work */
static void
probe_workqueue_insertion(struct task_struct *wq_thread,
struct work_struct *work)
{
int cpu = cpumask_first(&wq_thread->cpus_allowed);
struct cpu_workqueue_stats *node;
unsigned long flags;
spin_lock_irqsave(&workqueue_cpu_stat(cpu)->lock, flags);
list_for_each_entry(node, &workqueue_cpu_stat(cpu)->list, list) {
if (node->pid == wq_thread->pid) {
atomic_inc(&node->inserted);
goto found;
}
}
pr_debug("trace_workqueue: entry not found\n");
found:
spin_unlock_irqrestore(&workqueue_cpu_stat(cpu)->lock, flags);
}
/* Execution of a work */
static void
probe_workqueue_execution(struct task_struct *wq_thread,
struct work_struct *work)
{
int cpu = cpumask_first(&wq_thread->cpus_allowed);
struct cpu_workqueue_stats *node;
unsigned long flags;
spin_lock_irqsave(&workqueue_cpu_stat(cpu)->lock, flags);
list_for_each_entry(node, &workqueue_cpu_stat(cpu)->list, list) {
if (node->pid == wq_thread->pid) {
node->executed++;
goto found;
}
}
pr_debug("trace_workqueue: entry not found\n");
found:
spin_unlock_irqrestore(&workqueue_cpu_stat(cpu)->lock, flags);
}
/* Creation of a cpu workqueue thread */
static void probe_workqueue_creation(struct task_struct *wq_thread, int cpu)
{
struct cpu_workqueue_stats *cws;
unsigned long flags;
WARN_ON(cpu < 0);
/* Workqueues are sometimes created in atomic context */
cws = kzalloc(sizeof(struct cpu_workqueue_stats), GFP_ATOMIC);
if (!cws) {
pr_warning("trace_workqueue: not enough memory\n");
return;
}
INIT_LIST_HEAD(&cws->list);
kref_init(&cws->kref);
cws->cpu = cpu;
cws->pid = wq_thread->pid;
spin_lock_irqsave(&workqueue_cpu_stat(cpu)->lock, flags);
list_add_tail(&cws->list, &workqueue_cpu_stat(cpu)->list);
spin_unlock_irqrestore(&workqueue_cpu_stat(cpu)->lock, flags);
}
/* Destruction of a cpu workqueue thread */
static void probe_workqueue_destruction(struct task_struct *wq_thread)
{
/* Workqueue only execute on one cpu */
int cpu = cpumask_first(&wq_thread->cpus_allowed);
struct cpu_workqueue_stats *node, *next;
unsigned long flags;
spin_lock_irqsave(&workqueue_cpu_stat(cpu)->lock, flags);
list_for_each_entry_safe(node, next, &workqueue_cpu_stat(cpu)->list,
list) {
if (node->pid == wq_thread->pid) {
list_del(&node->list);
kref_put(&node->kref, cpu_workqueue_stat_free);
goto found;
}
}
pr_debug("trace_workqueue: don't find workqueue to destroy\n");
found:
spin_unlock_irqrestore(&workqueue_cpu_stat(cpu)->lock, flags);
}
static struct cpu_workqueue_stats *workqueue_stat_start_cpu(int cpu)
{
unsigned long flags;
struct cpu_workqueue_stats *ret = NULL;
spin_lock_irqsave(&workqueue_cpu_stat(cpu)->lock, flags);
if (!list_empty(&workqueue_cpu_stat(cpu)->list)) {
ret = list_entry(workqueue_cpu_stat(cpu)->list.next,
struct cpu_workqueue_stats, list);
kref_get(&ret->kref);
}
spin_unlock_irqrestore(&workqueue_cpu_stat(cpu)->lock, flags);
return ret;
}
static void *workqueue_stat_start(struct tracer_stat *trace)
{
int cpu;
void *ret = NULL;
for_each_possible_cpu(cpu) {
ret = workqueue_stat_start_cpu(cpu);
if (ret)
return ret;
}
return NULL;
}
static void *workqueue_stat_next(void *prev, int idx)
{
struct cpu_workqueue_stats *prev_cws = prev;
struct cpu_workqueue_stats *ret;
int cpu = prev_cws->cpu;
unsigned long flags;
spin_lock_irqsave(&workqueue_cpu_stat(cpu)->lock, flags);
if (list_is_last(&prev_cws->list, &workqueue_cpu_stat(cpu)->list)) {
spin_unlock_irqrestore(&workqueue_cpu_stat(cpu)->lock, flags);
do {
cpu = cpumask_next(cpu, cpu_possible_mask);
if (cpu >= nr_cpu_ids)
return NULL;
} while (!(ret = workqueue_stat_start_cpu(cpu)));
return ret;
} else {
ret = list_entry(prev_cws->list.next,
struct cpu_workqueue_stats, list);
kref_get(&ret->kref);
}
spin_unlock_irqrestore(&workqueue_cpu_stat(cpu)->lock, flags);
return ret;
}
static int workqueue_stat_show(struct seq_file *s, void *p)
{
struct cpu_workqueue_stats *cws = p;
struct pid *pid;
struct task_struct *tsk;
pid = find_get_pid(cws->pid);
if (pid) {
tsk = get_pid_task(pid, PIDTYPE_PID);
if (tsk) {
seq_printf(s, "%3d %6d %6u %s\n", cws->cpu,
atomic_read(&cws->inserted), cws->executed,
tsk->comm);
put_task_struct(tsk);
}
put_pid(pid);
}
return 0;
}
static void workqueue_stat_release(void *stat)
{
struct cpu_workqueue_stats *node = stat;
kref_put(&node->kref, cpu_workqueue_stat_free);
}
static int workqueue_stat_headers(struct seq_file *s)
{
seq_printf(s, "# CPU INSERTED EXECUTED NAME\n");
seq_printf(s, "# | | | |\n");
return 0;
}
struct tracer_stat workqueue_stats __read_mostly = {
.name = "workqueues",
.stat_start = workqueue_stat_start,
.stat_next = workqueue_stat_next,
.stat_show = workqueue_stat_show,
.stat_release = workqueue_stat_release,
.stat_headers = workqueue_stat_headers
};
int __init stat_workqueue_init(void)
{
if (register_stat_tracer(&workqueue_stats)) {
pr_warning("Unable to register workqueue stat tracer\n");
return 1;
}
return 0;
}
fs_initcall(stat_workqueue_init);
/*
* Workqueues are created very early, just after pre-smp initcalls.
* So we must register our tracepoints at this stage.
*/
int __init trace_workqueue_early_init(void)
{
int ret, cpu;
ret = register_trace_workqueue_insertion(probe_workqueue_insertion);
if (ret)
goto out;
ret = register_trace_workqueue_execution(probe_workqueue_execution);
if (ret)
goto no_insertion;
ret = register_trace_workqueue_creation(probe_workqueue_creation);
if (ret)
goto no_execution;
ret = register_trace_workqueue_destruction(probe_workqueue_destruction);
if (ret)
goto no_creation;
for_each_possible_cpu(cpu) {
spin_lock_init(&workqueue_cpu_stat(cpu)->lock);
INIT_LIST_HEAD(&workqueue_cpu_stat(cpu)->list);
}
return 0;
no_creation:
unregister_trace_workqueue_creation(probe_workqueue_creation);
no_execution:
unregister_trace_workqueue_execution(probe_workqueue_execution);
no_insertion:
unregister_trace_workqueue_insertion(probe_workqueue_insertion);
out:
pr_warning("trace_workqueue: unable to trace workqueues\n");
return 1;
}
early_initcall(trace_workqueue_early_init);
| gpl-2.0 |
ISTweak/android_kernel_htc_valentewx | net/core/pktgen.c | 823 | 93193 | /*
* Authors:
* Copyright 2001, 2002 by Robert Olsson <robert.olsson@its.uu.se>
* Uppsala University and
* Swedish University of Agricultural Sciences
*
* Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
* Ben Greear <greearb@candelatech.com>
* Jens Låås <jens.laas@data.slu.se>
*
* 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.
*
*
* A tool for loading the network with preconfigurated packets.
* The tool is implemented as a linux module. Parameters are output
* device, delay (to hard_xmit), number of packets, and whether
* to use multiple SKBs or just the same one.
* pktgen uses the installed interface's output routine.
*
* Additional hacking by:
*
* Jens.Laas@data.slu.se
* Improved by ANK. 010120.
* Improved by ANK even more. 010212.
* MAC address typo fixed. 010417 --ro
* Integrated. 020301 --DaveM
* Added multiskb option 020301 --DaveM
* Scaling of results. 020417--sigurdur@linpro.no
* Significant re-work of the module:
* * Convert to threaded model to more efficiently be able to transmit
* and receive on multiple interfaces at once.
* * Converted many counters to __u64 to allow longer runs.
* * Allow configuration of ranges, like min/max IP address, MACs,
* and UDP-ports, for both source and destination, and can
* set to use a random distribution or sequentially walk the range.
* * Can now change most values after starting.
* * Place 12-byte packet in UDP payload with magic number,
* sequence number, and timestamp.
* * Add receiver code that detects dropped pkts, re-ordered pkts, and
* latencies (with micro-second) precision.
* * Add IOCTL interface to easily get counters & configuration.
* --Ben Greear <greearb@candelatech.com>
*
* Renamed multiskb to clone_skb and cleaned up sending core for two distinct
* skb modes. A clone_skb=0 mode for Ben "ranges" work and a clone_skb != 0
* as a "fastpath" with a configurable number of clones after alloc's.
* clone_skb=0 means all packets are allocated this also means ranges time
* stamps etc can be used. clone_skb=100 means 1 malloc is followed by 100
* clones.
*
* Also moved to /proc/net/pktgen/
* --ro
*
* Sept 10: Fixed threading/locking. Lots of bone-headed and more clever
* mistakes. Also merged in DaveM's patch in the -pre6 patch.
* --Ben Greear <greearb@candelatech.com>
*
* Integrated to 2.5.x 021029 --Lucio Maciel (luciomaciel@zipmail.com.br)
*
*
* 021124 Finished major redesign and rewrite for new functionality.
* See Documentation/networking/pktgen.txt for how to use this.
*
* The new operation:
* For each CPU one thread/process is created at start. This process checks
* for running devices in the if_list and sends packets until count is 0 it
* also the thread checks the thread->control which is used for inter-process
* communication. controlling process "posts" operations to the threads this
* way. The if_lock should be possible to remove when add/rem_device is merged
* into this too.
*
* By design there should only be *one* "controlling" process. In practice
* multiple write accesses gives unpredictable result. Understood by "write"
* to /proc gives result code thats should be read be the "writer".
* For practical use this should be no problem.
*
* Note when adding devices to a specific CPU there good idea to also assign
* /proc/irq/XX/smp_affinity so TX-interrupts gets bound to the same CPU.
* --ro
*
* Fix refcount off by one if first packet fails, potential null deref,
* memleak 030710- KJP
*
* First "ranges" functionality for ipv6 030726 --ro
*
* Included flow support. 030802 ANK.
*
* Fixed unaligned access on IA-64 Grant Grundler <grundler@parisc-linux.org>
*
* Remove if fix from added Harald Welte <laforge@netfilter.org> 040419
* ia64 compilation fix from Aron Griffis <aron@hp.com> 040604
*
* New xmit() return, do_div and misc clean up by Stephen Hemminger
* <shemminger@osdl.org> 040923
*
* Randy Dunlap fixed u64 printk compiler waring
*
* Remove FCS from BW calculation. Lennert Buytenhek <buytenh@wantstofly.org>
* New time handling. Lennert Buytenhek <buytenh@wantstofly.org> 041213
*
* Corrections from Nikolai Malykh (nmalykh@bilim.com)
* Removed unused flags F_SET_SRCMAC & F_SET_SRCIP 041230
*
* interruptible_sleep_on_timeout() replaced Nishanth Aravamudan <nacc@us.ibm.com>
* 050103
*
* MPLS support by Steven Whitehouse <steve@chygwyn.com>
*
* 802.1Q/Q-in-Q support by Francesco Fondelli (FF) <francesco.fondelli@gmail.com>
*
* Fixed src_mac command to set source mac of packet to value specified in
* command by Adit Ranadive <adit.262@gmail.com>
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/sys.h>
#include <linux/types.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/mutex.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/unistd.h>
#include <linux/string.h>
#include <linux/ptrace.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/interrupt.h>
#include <linux/capability.h>
#include <linux/hrtimer.h>
#include <linux/freezer.h>
#include <linux/delay.h>
#include <linux/timer.h>
#include <linux/list.h>
#include <linux/init.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/inet.h>
#include <linux/inetdevice.h>
#include <linux/rtnetlink.h>
#include <linux/if_arp.h>
#include <linux/if_vlan.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/udp.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/wait.h>
#include <linux/etherdevice.h>
#include <linux/kthread.h>
#include <linux/prefetch.h>
#include <net/net_namespace.h>
#include <net/checksum.h>
#include <net/ipv6.h>
#include <net/addrconf.h>
#ifdef CONFIG_XFRM
#include <net/xfrm.h>
#endif
#include <asm/byteorder.h>
#include <linux/rcupdate.h>
#include <linux/bitops.h>
#include <linux/io.h>
#include <linux/timex.h>
#include <linux/uaccess.h>
#include <asm/dma.h>
#include <asm/div64.h> /* do_div */
#define VERSION "2.74"
#define IP_NAME_SZ 32
#define MAX_MPLS_LABELS 16 /* This is the max label stack depth */
#define MPLS_STACK_BOTTOM htonl(0x00000100)
#define func_enter() pr_debug("entering %s\n", __func__);
/* Device flag bits */
#define F_IPSRC_RND (1<<0) /* IP-Src Random */
#define F_IPDST_RND (1<<1) /* IP-Dst Random */
#define F_UDPSRC_RND (1<<2) /* UDP-Src Random */
#define F_UDPDST_RND (1<<3) /* UDP-Dst Random */
#define F_MACSRC_RND (1<<4) /* MAC-Src Random */
#define F_MACDST_RND (1<<5) /* MAC-Dst Random */
#define F_TXSIZE_RND (1<<6) /* Transmit size is random */
#define F_IPV6 (1<<7) /* Interface in IPV6 Mode */
#define F_MPLS_RND (1<<8) /* Random MPLS labels */
#define F_VID_RND (1<<9) /* Random VLAN ID */
#define F_SVID_RND (1<<10) /* Random SVLAN ID */
#define F_FLOW_SEQ (1<<11) /* Sequential flows */
#define F_IPSEC_ON (1<<12) /* ipsec on for flows */
#define F_QUEUE_MAP_RND (1<<13) /* queue map Random */
#define F_QUEUE_MAP_CPU (1<<14) /* queue map mirrors smp_processor_id() */
#define F_NODE (1<<15) /* Node memory alloc*/
/* Thread control flag bits */
#define T_STOP (1<<0) /* Stop run */
#define T_RUN (1<<1) /* Start run */
#define T_REMDEVALL (1<<2) /* Remove all devs */
#define T_REMDEV (1<<3) /* Remove one dev */
/* If lock -- can be removed after some work */
#define if_lock(t) spin_lock(&(t->if_lock));
#define if_unlock(t) spin_unlock(&(t->if_lock));
/* Used to help with determining the pkts on receive */
#define PKTGEN_MAGIC 0xbe9be955
#define PG_PROC_DIR "pktgen"
#define PGCTRL "pgctrl"
static struct proc_dir_entry *pg_proc_dir;
#define MAX_CFLOWS 65536
#define VLAN_TAG_SIZE(x) ((x)->vlan_id == 0xffff ? 0 : 4)
#define SVLAN_TAG_SIZE(x) ((x)->svlan_id == 0xffff ? 0 : 4)
struct flow_state {
__be32 cur_daddr;
int count;
#ifdef CONFIG_XFRM
struct xfrm_state *x;
#endif
__u32 flags;
};
/* flow flag bits */
#define F_INIT (1<<0) /* flow has been initialized */
struct pktgen_dev {
/*
* Try to keep frequent/infrequent used vars. separated.
*/
struct proc_dir_entry *entry; /* proc file */
struct pktgen_thread *pg_thread;/* the owner */
struct list_head list; /* chaining in the thread's run-queue */
int running; /* if false, the test will stop */
/* If min != max, then we will either do a linear iteration, or
* we will do a random selection from within the range.
*/
__u32 flags;
int removal_mark; /* non-zero => the device is marked for
* removal by worker thread */
int min_pkt_size; /* = ETH_ZLEN; */
int max_pkt_size; /* = ETH_ZLEN; */
int pkt_overhead; /* overhead for MPLS, VLANs, IPSEC etc */
int nfrags;
struct page *page;
u64 delay; /* nano-seconds */
__u64 count; /* Default No packets to send */
__u64 sofar; /* How many pkts we've sent so far */
__u64 tx_bytes; /* How many bytes we've transmitted */
__u64 errors; /* Errors when trying to transmit, */
/* runtime counters relating to clone_skb */
__u64 allocated_skbs;
__u32 clone_count;
int last_ok; /* Was last skb sent?
* Or a failed transmit of some sort?
* This will keep sequence numbers in order
*/
ktime_t next_tx;
ktime_t started_at;
ktime_t stopped_at;
u64 idle_acc; /* nano-seconds */
__u32 seq_num;
int clone_skb; /*
* Use multiple SKBs during packet gen.
* If this number is greater than 1, then
* that many copies of the same packet will be
* sent before a new packet is allocated.
* If you want to send 1024 identical packets
* before creating a new packet,
* set clone_skb to 1024.
*/
char dst_min[IP_NAME_SZ]; /* IP, ie 1.2.3.4 */
char dst_max[IP_NAME_SZ]; /* IP, ie 1.2.3.4 */
char src_min[IP_NAME_SZ]; /* IP, ie 1.2.3.4 */
char src_max[IP_NAME_SZ]; /* IP, ie 1.2.3.4 */
struct in6_addr in6_saddr;
struct in6_addr in6_daddr;
struct in6_addr cur_in6_daddr;
struct in6_addr cur_in6_saddr;
/* For ranges */
struct in6_addr min_in6_daddr;
struct in6_addr max_in6_daddr;
struct in6_addr min_in6_saddr;
struct in6_addr max_in6_saddr;
/* If we're doing ranges, random or incremental, then this
* defines the min/max for those ranges.
*/
__be32 saddr_min; /* inclusive, source IP address */
__be32 saddr_max; /* exclusive, source IP address */
__be32 daddr_min; /* inclusive, dest IP address */
__be32 daddr_max; /* exclusive, dest IP address */
__u16 udp_src_min; /* inclusive, source UDP port */
__u16 udp_src_max; /* exclusive, source UDP port */
__u16 udp_dst_min; /* inclusive, dest UDP port */
__u16 udp_dst_max; /* exclusive, dest UDP port */
/* DSCP + ECN */
__u8 tos; /* six MSB of (former) IPv4 TOS
are for dscp codepoint */
__u8 traffic_class; /* ditto for the (former) Traffic Class in IPv6
(see RFC 3260, sec. 4) */
/* MPLS */
unsigned nr_labels; /* Depth of stack, 0 = no MPLS */
__be32 labels[MAX_MPLS_LABELS];
/* VLAN/SVLAN (802.1Q/Q-in-Q) */
__u8 vlan_p;
__u8 vlan_cfi;
__u16 vlan_id; /* 0xffff means no vlan tag */
__u8 svlan_p;
__u8 svlan_cfi;
__u16 svlan_id; /* 0xffff means no svlan tag */
__u32 src_mac_count; /* How many MACs to iterate through */
__u32 dst_mac_count; /* How many MACs to iterate through */
unsigned char dst_mac[ETH_ALEN];
unsigned char src_mac[ETH_ALEN];
__u32 cur_dst_mac_offset;
__u32 cur_src_mac_offset;
__be32 cur_saddr;
__be32 cur_daddr;
__u16 ip_id;
__u16 cur_udp_dst;
__u16 cur_udp_src;
__u16 cur_queue_map;
__u32 cur_pkt_size;
__u32 last_pkt_size;
__u8 hh[14];
/* = {
0x00, 0x80, 0xC8, 0x79, 0xB3, 0xCB,
We fill in SRC address later
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x08, 0x00
};
*/
__u16 pad; /* pad out the hh struct to an even 16 bytes */
struct sk_buff *skb; /* skb we are to transmit next, used for when we
* are transmitting the same one multiple times
*/
struct net_device *odev; /* The out-going device.
* Note that the device should have it's
* pg_info pointer pointing back to this
* device.
* Set when the user specifies the out-going
* device name (not when the inject is
* started as it used to do.)
*/
char odevname[32];
struct flow_state *flows;
unsigned cflows; /* Concurrent flows (config) */
unsigned lflow; /* Flow length (config) */
unsigned nflows; /* accumulated flows (stats) */
unsigned curfl; /* current sequenced flow (state)*/
u16 queue_map_min;
u16 queue_map_max;
__u32 skb_priority; /* skb priority field */
int node; /* Memory node */
#ifdef CONFIG_XFRM
__u8 ipsmode; /* IPSEC mode (config) */
__u8 ipsproto; /* IPSEC type (config) */
#endif
char result[512];
};
struct pktgen_hdr {
__be32 pgh_magic;
__be32 seq_num;
__be32 tv_sec;
__be32 tv_usec;
};
static bool pktgen_exiting __read_mostly;
struct pktgen_thread {
spinlock_t if_lock; /* for list of devices */
struct list_head if_list; /* All device here */
struct list_head th_list;
struct task_struct *tsk;
char result[512];
/* Field for thread to receive "posted" events terminate,
stop ifs etc. */
u32 control;
int cpu;
wait_queue_head_t queue;
struct completion start_done;
};
#define REMOVE 1
#define FIND 0
static inline ktime_t ktime_now(void)
{
struct timespec ts;
ktime_get_ts(&ts);
return timespec_to_ktime(ts);
}
/* This works even if 32 bit because of careful byte order choice */
static inline int ktime_lt(const ktime_t cmp1, const ktime_t cmp2)
{
return cmp1.tv64 < cmp2.tv64;
}
static const char version[] =
"Packet Generator for packet performance testing. "
"Version: " VERSION "\n";
static int pktgen_remove_device(struct pktgen_thread *t, struct pktgen_dev *i);
static int pktgen_add_device(struct pktgen_thread *t, const char *ifname);
static struct pktgen_dev *pktgen_find_dev(struct pktgen_thread *t,
const char *ifname, bool exact);
static int pktgen_device_event(struct notifier_block *, unsigned long, void *);
static void pktgen_run_all_threads(void);
static void pktgen_reset_all_threads(void);
static void pktgen_stop_all_threads_ifs(void);
static void pktgen_stop(struct pktgen_thread *t);
static void pktgen_clear_counters(struct pktgen_dev *pkt_dev);
static unsigned int scan_ip6(const char *s, char ip[16]);
/* Module parameters, defaults. */
static int pg_count_d __read_mostly = 1000;
static int pg_delay_d __read_mostly;
static int pg_clone_skb_d __read_mostly;
static int debug __read_mostly;
static DEFINE_MUTEX(pktgen_thread_lock);
static LIST_HEAD(pktgen_threads);
static struct notifier_block pktgen_notifier_block = {
.notifier_call = pktgen_device_event,
};
/*
* /proc handling functions
*
*/
static int pgctrl_show(struct seq_file *seq, void *v)
{
seq_puts(seq, version);
return 0;
}
static ssize_t pgctrl_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
int err = 0;
char data[128];
if (!capable(CAP_NET_ADMIN)) {
err = -EPERM;
goto out;
}
if (count > sizeof(data))
count = sizeof(data);
if (copy_from_user(data, buf, count)) {
err = -EFAULT;
goto out;
}
data[count - 1] = 0; /* Make string */
if (!strcmp(data, "stop"))
pktgen_stop_all_threads_ifs();
else if (!strcmp(data, "start"))
pktgen_run_all_threads();
else if (!strcmp(data, "reset"))
pktgen_reset_all_threads();
else
pr_warning("Unknown command: %s\n", data);
err = count;
out:
return err;
}
static int pgctrl_open(struct inode *inode, struct file *file)
{
return single_open(file, pgctrl_show, PDE(inode)->data);
}
static const struct file_operations pktgen_fops = {
.owner = THIS_MODULE,
.open = pgctrl_open,
.read = seq_read,
.llseek = seq_lseek,
.write = pgctrl_write,
.release = single_release,
};
static int pktgen_if_show(struct seq_file *seq, void *v)
{
const struct pktgen_dev *pkt_dev = seq->private;
ktime_t stopped;
u64 idle;
seq_printf(seq,
"Params: count %llu min_pkt_size: %u max_pkt_size: %u\n",
(unsigned long long)pkt_dev->count, pkt_dev->min_pkt_size,
pkt_dev->max_pkt_size);
seq_printf(seq,
" frags: %d delay: %llu clone_skb: %d ifname: %s\n",
pkt_dev->nfrags, (unsigned long long) pkt_dev->delay,
pkt_dev->clone_skb, pkt_dev->odevname);
seq_printf(seq, " flows: %u flowlen: %u\n", pkt_dev->cflows,
pkt_dev->lflow);
seq_printf(seq,
" queue_map_min: %u queue_map_max: %u\n",
pkt_dev->queue_map_min,
pkt_dev->queue_map_max);
if (pkt_dev->skb_priority)
seq_printf(seq, " skb_priority: %u\n",
pkt_dev->skb_priority);
if (pkt_dev->flags & F_IPV6) {
seq_printf(seq,
" saddr: %pI6c min_saddr: %pI6c max_saddr: %pI6c\n"
" daddr: %pI6c min_daddr: %pI6c max_daddr: %pI6c\n",
&pkt_dev->in6_saddr,
&pkt_dev->min_in6_saddr, &pkt_dev->max_in6_saddr,
&pkt_dev->in6_daddr,
&pkt_dev->min_in6_daddr, &pkt_dev->max_in6_daddr);
} else {
seq_printf(seq,
" dst_min: %s dst_max: %s\n",
pkt_dev->dst_min, pkt_dev->dst_max);
seq_printf(seq,
" src_min: %s src_max: %s\n",
pkt_dev->src_min, pkt_dev->src_max);
}
seq_puts(seq, " src_mac: ");
seq_printf(seq, "%pM ",
is_zero_ether_addr(pkt_dev->src_mac) ?
pkt_dev->odev->dev_addr : pkt_dev->src_mac);
seq_printf(seq, "dst_mac: ");
seq_printf(seq, "%pM\n", pkt_dev->dst_mac);
seq_printf(seq,
" udp_src_min: %d udp_src_max: %d"
" udp_dst_min: %d udp_dst_max: %d\n",
pkt_dev->udp_src_min, pkt_dev->udp_src_max,
pkt_dev->udp_dst_min, pkt_dev->udp_dst_max);
seq_printf(seq,
" src_mac_count: %d dst_mac_count: %d\n",
pkt_dev->src_mac_count, pkt_dev->dst_mac_count);
if (pkt_dev->nr_labels) {
unsigned i;
seq_printf(seq, " mpls: ");
for (i = 0; i < pkt_dev->nr_labels; i++)
seq_printf(seq, "%08x%s", ntohl(pkt_dev->labels[i]),
i == pkt_dev->nr_labels-1 ? "\n" : ", ");
}
if (pkt_dev->vlan_id != 0xffff)
seq_printf(seq, " vlan_id: %u vlan_p: %u vlan_cfi: %u\n",
pkt_dev->vlan_id, pkt_dev->vlan_p,
pkt_dev->vlan_cfi);
if (pkt_dev->svlan_id != 0xffff)
seq_printf(seq, " svlan_id: %u vlan_p: %u vlan_cfi: %u\n",
pkt_dev->svlan_id, pkt_dev->svlan_p,
pkt_dev->svlan_cfi);
if (pkt_dev->tos)
seq_printf(seq, " tos: 0x%02x\n", pkt_dev->tos);
if (pkt_dev->traffic_class)
seq_printf(seq, " traffic_class: 0x%02x\n", pkt_dev->traffic_class);
if (pkt_dev->node >= 0)
seq_printf(seq, " node: %d\n", pkt_dev->node);
seq_printf(seq, " Flags: ");
if (pkt_dev->flags & F_IPV6)
seq_printf(seq, "IPV6 ");
if (pkt_dev->flags & F_IPSRC_RND)
seq_printf(seq, "IPSRC_RND ");
if (pkt_dev->flags & F_IPDST_RND)
seq_printf(seq, "IPDST_RND ");
if (pkt_dev->flags & F_TXSIZE_RND)
seq_printf(seq, "TXSIZE_RND ");
if (pkt_dev->flags & F_UDPSRC_RND)
seq_printf(seq, "UDPSRC_RND ");
if (pkt_dev->flags & F_UDPDST_RND)
seq_printf(seq, "UDPDST_RND ");
if (pkt_dev->flags & F_MPLS_RND)
seq_printf(seq, "MPLS_RND ");
if (pkt_dev->flags & F_QUEUE_MAP_RND)
seq_printf(seq, "QUEUE_MAP_RND ");
if (pkt_dev->flags & F_QUEUE_MAP_CPU)
seq_printf(seq, "QUEUE_MAP_CPU ");
if (pkt_dev->cflows) {
if (pkt_dev->flags & F_FLOW_SEQ)
seq_printf(seq, "FLOW_SEQ "); /*in sequence flows*/
else
seq_printf(seq, "FLOW_RND ");
}
#ifdef CONFIG_XFRM
if (pkt_dev->flags & F_IPSEC_ON)
seq_printf(seq, "IPSEC ");
#endif
if (pkt_dev->flags & F_MACSRC_RND)
seq_printf(seq, "MACSRC_RND ");
if (pkt_dev->flags & F_MACDST_RND)
seq_printf(seq, "MACDST_RND ");
if (pkt_dev->flags & F_VID_RND)
seq_printf(seq, "VID_RND ");
if (pkt_dev->flags & F_SVID_RND)
seq_printf(seq, "SVID_RND ");
if (pkt_dev->flags & F_NODE)
seq_printf(seq, "NODE_ALLOC ");
seq_puts(seq, "\n");
/* not really stopped, more like last-running-at */
stopped = pkt_dev->running ? ktime_now() : pkt_dev->stopped_at;
idle = pkt_dev->idle_acc;
do_div(idle, NSEC_PER_USEC);
seq_printf(seq,
"Current:\n pkts-sofar: %llu errors: %llu\n",
(unsigned long long)pkt_dev->sofar,
(unsigned long long)pkt_dev->errors);
seq_printf(seq,
" started: %lluus stopped: %lluus idle: %lluus\n",
(unsigned long long) ktime_to_us(pkt_dev->started_at),
(unsigned long long) ktime_to_us(stopped),
(unsigned long long) idle);
seq_printf(seq,
" seq_num: %d cur_dst_mac_offset: %d cur_src_mac_offset: %d\n",
pkt_dev->seq_num, pkt_dev->cur_dst_mac_offset,
pkt_dev->cur_src_mac_offset);
if (pkt_dev->flags & F_IPV6) {
seq_printf(seq, " cur_saddr: %pI6c cur_daddr: %pI6c\n",
&pkt_dev->cur_in6_saddr,
&pkt_dev->cur_in6_daddr);
} else
seq_printf(seq, " cur_saddr: 0x%x cur_daddr: 0x%x\n",
pkt_dev->cur_saddr, pkt_dev->cur_daddr);
seq_printf(seq, " cur_udp_dst: %d cur_udp_src: %d\n",
pkt_dev->cur_udp_dst, pkt_dev->cur_udp_src);
seq_printf(seq, " cur_queue_map: %u\n", pkt_dev->cur_queue_map);
seq_printf(seq, " flows: %u\n", pkt_dev->nflows);
if (pkt_dev->result[0])
seq_printf(seq, "Result: %s\n", pkt_dev->result);
else
seq_printf(seq, "Result: Idle\n");
return 0;
}
static int hex32_arg(const char __user *user_buffer, unsigned long maxlen,
__u32 *num)
{
int i = 0;
*num = 0;
for (; i < maxlen; i++) {
int value;
char c;
*num <<= 4;
if (get_user(c, &user_buffer[i]))
return -EFAULT;
value = hex_to_bin(c);
if (value >= 0)
*num |= value;
else
break;
}
return i;
}
static int count_trail_chars(const char __user * user_buffer,
unsigned int maxlen)
{
int i;
for (i = 0; i < maxlen; i++) {
char c;
if (get_user(c, &user_buffer[i]))
return -EFAULT;
switch (c) {
case '\"':
case '\n':
case '\r':
case '\t':
case ' ':
case '=':
break;
default:
goto done;
}
}
done:
return i;
}
static unsigned long num_arg(const char __user * user_buffer,
unsigned long maxlen, unsigned long *num)
{
int i;
*num = 0;
for (i = 0; i < maxlen; i++) {
char c;
if (get_user(c, &user_buffer[i]))
return -EFAULT;
if ((c >= '0') && (c <= '9')) {
*num *= 10;
*num += c - '0';
} else
break;
}
return i;
}
static int strn_len(const char __user * user_buffer, unsigned int maxlen)
{
int i;
for (i = 0; i < maxlen; i++) {
char c;
if (get_user(c, &user_buffer[i]))
return -EFAULT;
switch (c) {
case '\"':
case '\n':
case '\r':
case '\t':
case ' ':
goto done_str;
break;
default:
break;
}
}
done_str:
return i;
}
static ssize_t get_labels(const char __user *buffer, struct pktgen_dev *pkt_dev)
{
unsigned n = 0;
char c;
ssize_t i = 0;
int len;
pkt_dev->nr_labels = 0;
do {
__u32 tmp;
len = hex32_arg(&buffer[i], 8, &tmp);
if (len <= 0)
return len;
pkt_dev->labels[n] = htonl(tmp);
if (pkt_dev->labels[n] & MPLS_STACK_BOTTOM)
pkt_dev->flags |= F_MPLS_RND;
i += len;
if (get_user(c, &buffer[i]))
return -EFAULT;
i++;
n++;
if (n >= MAX_MPLS_LABELS)
return -E2BIG;
} while (c == ',');
pkt_dev->nr_labels = n;
return i;
}
static ssize_t pktgen_if_write(struct file *file,
const char __user * user_buffer, size_t count,
loff_t * offset)
{
struct seq_file *seq = file->private_data;
struct pktgen_dev *pkt_dev = seq->private;
int i, max, len;
char name[16], valstr[32];
unsigned long value = 0;
char *pg_result = NULL;
int tmp = 0;
char buf[128];
pg_result = &(pkt_dev->result[0]);
if (count < 1) {
pr_warning("wrong command format\n");
return -EINVAL;
}
max = count;
tmp = count_trail_chars(user_buffer, max);
if (tmp < 0) {
pr_warning("illegal format\n");
return tmp;
}
i = tmp;
/* Read variable name */
len = strn_len(&user_buffer[i], sizeof(name) - 1);
if (len < 0)
return len;
memset(name, 0, sizeof(name));
if (copy_from_user(name, &user_buffer[i], len))
return -EFAULT;
i += len;
max = count - i;
len = count_trail_chars(&user_buffer[i], max);
if (len < 0)
return len;
i += len;
if (debug) {
size_t copy = min_t(size_t, count, 1023);
char tb[copy + 1];
if (copy_from_user(tb, user_buffer, copy))
return -EFAULT;
tb[copy] = 0;
printk(KERN_DEBUG "pktgen: %s,%lu buffer -:%s:-\n", name,
(unsigned long)count, tb);
}
if (!strcmp(name, "min_pkt_size")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value < 14 + 20 + 8)
value = 14 + 20 + 8;
if (value != pkt_dev->min_pkt_size) {
pkt_dev->min_pkt_size = value;
pkt_dev->cur_pkt_size = value;
}
sprintf(pg_result, "OK: min_pkt_size=%u",
pkt_dev->min_pkt_size);
return count;
}
if (!strcmp(name, "max_pkt_size")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value < 14 + 20 + 8)
value = 14 + 20 + 8;
if (value != pkt_dev->max_pkt_size) {
pkt_dev->max_pkt_size = value;
pkt_dev->cur_pkt_size = value;
}
sprintf(pg_result, "OK: max_pkt_size=%u",
pkt_dev->max_pkt_size);
return count;
}
/* Shortcut for min = max */
if (!strcmp(name, "pkt_size")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value < 14 + 20 + 8)
value = 14 + 20 + 8;
if (value != pkt_dev->min_pkt_size) {
pkt_dev->min_pkt_size = value;
pkt_dev->max_pkt_size = value;
pkt_dev->cur_pkt_size = value;
}
sprintf(pg_result, "OK: pkt_size=%u", pkt_dev->min_pkt_size);
return count;
}
if (!strcmp(name, "debug")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
debug = value;
sprintf(pg_result, "OK: debug=%u", debug);
return count;
}
if (!strcmp(name, "frags")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
pkt_dev->nfrags = value;
sprintf(pg_result, "OK: frags=%u", pkt_dev->nfrags);
return count;
}
if (!strcmp(name, "delay")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value == 0x7FFFFFFF)
pkt_dev->delay = ULLONG_MAX;
else
pkt_dev->delay = (u64)value;
sprintf(pg_result, "OK: delay=%llu",
(unsigned long long) pkt_dev->delay);
return count;
}
if (!strcmp(name, "rate")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (!value)
return len;
pkt_dev->delay = pkt_dev->min_pkt_size*8*NSEC_PER_USEC/value;
if (debug)
pr_info("Delay set at: %llu ns\n", pkt_dev->delay);
sprintf(pg_result, "OK: rate=%lu", value);
return count;
}
if (!strcmp(name, "ratep")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (!value)
return len;
pkt_dev->delay = NSEC_PER_SEC/value;
if (debug)
pr_info("Delay set at: %llu ns\n", pkt_dev->delay);
sprintf(pg_result, "OK: rate=%lu", value);
return count;
}
if (!strcmp(name, "udp_src_min")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value != pkt_dev->udp_src_min) {
pkt_dev->udp_src_min = value;
pkt_dev->cur_udp_src = value;
}
sprintf(pg_result, "OK: udp_src_min=%u", pkt_dev->udp_src_min);
return count;
}
if (!strcmp(name, "udp_dst_min")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value != pkt_dev->udp_dst_min) {
pkt_dev->udp_dst_min = value;
pkt_dev->cur_udp_dst = value;
}
sprintf(pg_result, "OK: udp_dst_min=%u", pkt_dev->udp_dst_min);
return count;
}
if (!strcmp(name, "udp_src_max")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value != pkt_dev->udp_src_max) {
pkt_dev->udp_src_max = value;
pkt_dev->cur_udp_src = value;
}
sprintf(pg_result, "OK: udp_src_max=%u", pkt_dev->udp_src_max);
return count;
}
if (!strcmp(name, "udp_dst_max")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value != pkt_dev->udp_dst_max) {
pkt_dev->udp_dst_max = value;
pkt_dev->cur_udp_dst = value;
}
sprintf(pg_result, "OK: udp_dst_max=%u", pkt_dev->udp_dst_max);
return count;
}
if (!strcmp(name, "clone_skb")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
if ((value > 0) &&
(!(pkt_dev->odev->priv_flags & IFF_TX_SKB_SHARING)))
return -ENOTSUPP;
i += len;
pkt_dev->clone_skb = value;
sprintf(pg_result, "OK: clone_skb=%d", pkt_dev->clone_skb);
return count;
}
if (!strcmp(name, "count")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
pkt_dev->count = value;
sprintf(pg_result, "OK: count=%llu",
(unsigned long long)pkt_dev->count);
return count;
}
if (!strcmp(name, "src_mac_count")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (pkt_dev->src_mac_count != value) {
pkt_dev->src_mac_count = value;
pkt_dev->cur_src_mac_offset = 0;
}
sprintf(pg_result, "OK: src_mac_count=%d",
pkt_dev->src_mac_count);
return count;
}
if (!strcmp(name, "dst_mac_count")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (pkt_dev->dst_mac_count != value) {
pkt_dev->dst_mac_count = value;
pkt_dev->cur_dst_mac_offset = 0;
}
sprintf(pg_result, "OK: dst_mac_count=%d",
pkt_dev->dst_mac_count);
return count;
}
if (!strcmp(name, "node")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (node_possible(value)) {
pkt_dev->node = value;
sprintf(pg_result, "OK: node=%d", pkt_dev->node);
if (pkt_dev->page) {
put_page(pkt_dev->page);
pkt_dev->page = NULL;
}
}
else
sprintf(pg_result, "ERROR: node not possible");
return count;
}
if (!strcmp(name, "flag")) {
char f[32];
memset(f, 0, 32);
len = strn_len(&user_buffer[i], sizeof(f) - 1);
if (len < 0)
return len;
if (copy_from_user(f, &user_buffer[i], len))
return -EFAULT;
i += len;
if (strcmp(f, "IPSRC_RND") == 0)
pkt_dev->flags |= F_IPSRC_RND;
else if (strcmp(f, "!IPSRC_RND") == 0)
pkt_dev->flags &= ~F_IPSRC_RND;
else if (strcmp(f, "TXSIZE_RND") == 0)
pkt_dev->flags |= F_TXSIZE_RND;
else if (strcmp(f, "!TXSIZE_RND") == 0)
pkt_dev->flags &= ~F_TXSIZE_RND;
else if (strcmp(f, "IPDST_RND") == 0)
pkt_dev->flags |= F_IPDST_RND;
else if (strcmp(f, "!IPDST_RND") == 0)
pkt_dev->flags &= ~F_IPDST_RND;
else if (strcmp(f, "UDPSRC_RND") == 0)
pkt_dev->flags |= F_UDPSRC_RND;
else if (strcmp(f, "!UDPSRC_RND") == 0)
pkt_dev->flags &= ~F_UDPSRC_RND;
else if (strcmp(f, "UDPDST_RND") == 0)
pkt_dev->flags |= F_UDPDST_RND;
else if (strcmp(f, "!UDPDST_RND") == 0)
pkt_dev->flags &= ~F_UDPDST_RND;
else if (strcmp(f, "MACSRC_RND") == 0)
pkt_dev->flags |= F_MACSRC_RND;
else if (strcmp(f, "!MACSRC_RND") == 0)
pkt_dev->flags &= ~F_MACSRC_RND;
else if (strcmp(f, "MACDST_RND") == 0)
pkt_dev->flags |= F_MACDST_RND;
else if (strcmp(f, "!MACDST_RND") == 0)
pkt_dev->flags &= ~F_MACDST_RND;
else if (strcmp(f, "MPLS_RND") == 0)
pkt_dev->flags |= F_MPLS_RND;
else if (strcmp(f, "!MPLS_RND") == 0)
pkt_dev->flags &= ~F_MPLS_RND;
else if (strcmp(f, "VID_RND") == 0)
pkt_dev->flags |= F_VID_RND;
else if (strcmp(f, "!VID_RND") == 0)
pkt_dev->flags &= ~F_VID_RND;
else if (strcmp(f, "SVID_RND") == 0)
pkt_dev->flags |= F_SVID_RND;
else if (strcmp(f, "!SVID_RND") == 0)
pkt_dev->flags &= ~F_SVID_RND;
else if (strcmp(f, "FLOW_SEQ") == 0)
pkt_dev->flags |= F_FLOW_SEQ;
else if (strcmp(f, "QUEUE_MAP_RND") == 0)
pkt_dev->flags |= F_QUEUE_MAP_RND;
else if (strcmp(f, "!QUEUE_MAP_RND") == 0)
pkt_dev->flags &= ~F_QUEUE_MAP_RND;
else if (strcmp(f, "QUEUE_MAP_CPU") == 0)
pkt_dev->flags |= F_QUEUE_MAP_CPU;
else if (strcmp(f, "!QUEUE_MAP_CPU") == 0)
pkt_dev->flags &= ~F_QUEUE_MAP_CPU;
#ifdef CONFIG_XFRM
else if (strcmp(f, "IPSEC") == 0)
pkt_dev->flags |= F_IPSEC_ON;
#endif
else if (strcmp(f, "!IPV6") == 0)
pkt_dev->flags &= ~F_IPV6;
else if (strcmp(f, "NODE_ALLOC") == 0)
pkt_dev->flags |= F_NODE;
else if (strcmp(f, "!NODE_ALLOC") == 0)
pkt_dev->flags &= ~F_NODE;
else {
sprintf(pg_result,
"Flag -:%s:- unknown\nAvailable flags, (prepend ! to un-set flag):\n%s",
f,
"IPSRC_RND, IPDST_RND, UDPSRC_RND, UDPDST_RND, "
"MACSRC_RND, MACDST_RND, TXSIZE_RND, IPV6, MPLS_RND, VID_RND, SVID_RND, FLOW_SEQ, IPSEC, NODE_ALLOC\n");
return count;
}
sprintf(pg_result, "OK: flags=0x%x", pkt_dev->flags);
return count;
}
if (!strcmp(name, "dst_min") || !strcmp(name, "dst")) {
len = strn_len(&user_buffer[i], sizeof(pkt_dev->dst_min) - 1);
if (len < 0)
return len;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
if (strcmp(buf, pkt_dev->dst_min) != 0) {
memset(pkt_dev->dst_min, 0, sizeof(pkt_dev->dst_min));
strncpy(pkt_dev->dst_min, buf, len);
pkt_dev->daddr_min = in_aton(pkt_dev->dst_min);
pkt_dev->cur_daddr = pkt_dev->daddr_min;
}
if (debug)
printk(KERN_DEBUG "pktgen: dst_min set to: %s\n",
pkt_dev->dst_min);
i += len;
sprintf(pg_result, "OK: dst_min=%s", pkt_dev->dst_min);
return count;
}
if (!strcmp(name, "dst_max")) {
len = strn_len(&user_buffer[i], sizeof(pkt_dev->dst_max) - 1);
if (len < 0)
return len;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
if (strcmp(buf, pkt_dev->dst_max) != 0) {
memset(pkt_dev->dst_max, 0, sizeof(pkt_dev->dst_max));
strncpy(pkt_dev->dst_max, buf, len);
pkt_dev->daddr_max = in_aton(pkt_dev->dst_max);
pkt_dev->cur_daddr = pkt_dev->daddr_max;
}
if (debug)
printk(KERN_DEBUG "pktgen: dst_max set to: %s\n",
pkt_dev->dst_max);
i += len;
sprintf(pg_result, "OK: dst_max=%s", pkt_dev->dst_max);
return count;
}
if (!strcmp(name, "dst6")) {
len = strn_len(&user_buffer[i], sizeof(buf) - 1);
if (len < 0)
return len;
pkt_dev->flags |= F_IPV6;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
scan_ip6(buf, pkt_dev->in6_daddr.s6_addr);
snprintf(buf, sizeof(buf), "%pI6c", &pkt_dev->in6_daddr);
ipv6_addr_copy(&pkt_dev->cur_in6_daddr, &pkt_dev->in6_daddr);
if (debug)
printk(KERN_DEBUG "pktgen: dst6 set to: %s\n", buf);
i += len;
sprintf(pg_result, "OK: dst6=%s", buf);
return count;
}
if (!strcmp(name, "dst6_min")) {
len = strn_len(&user_buffer[i], sizeof(buf) - 1);
if (len < 0)
return len;
pkt_dev->flags |= F_IPV6;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
scan_ip6(buf, pkt_dev->min_in6_daddr.s6_addr);
snprintf(buf, sizeof(buf), "%pI6c", &pkt_dev->min_in6_daddr);
ipv6_addr_copy(&pkt_dev->cur_in6_daddr,
&pkt_dev->min_in6_daddr);
if (debug)
printk(KERN_DEBUG "pktgen: dst6_min set to: %s\n", buf);
i += len;
sprintf(pg_result, "OK: dst6_min=%s", buf);
return count;
}
if (!strcmp(name, "dst6_max")) {
len = strn_len(&user_buffer[i], sizeof(buf) - 1);
if (len < 0)
return len;
pkt_dev->flags |= F_IPV6;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
scan_ip6(buf, pkt_dev->max_in6_daddr.s6_addr);
snprintf(buf, sizeof(buf), "%pI6c", &pkt_dev->max_in6_daddr);
if (debug)
printk(KERN_DEBUG "pktgen: dst6_max set to: %s\n", buf);
i += len;
sprintf(pg_result, "OK: dst6_max=%s", buf);
return count;
}
if (!strcmp(name, "src6")) {
len = strn_len(&user_buffer[i], sizeof(buf) - 1);
if (len < 0)
return len;
pkt_dev->flags |= F_IPV6;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
scan_ip6(buf, pkt_dev->in6_saddr.s6_addr);
snprintf(buf, sizeof(buf), "%pI6c", &pkt_dev->in6_saddr);
ipv6_addr_copy(&pkt_dev->cur_in6_saddr, &pkt_dev->in6_saddr);
if (debug)
printk(KERN_DEBUG "pktgen: src6 set to: %s\n", buf);
i += len;
sprintf(pg_result, "OK: src6=%s", buf);
return count;
}
if (!strcmp(name, "src_min")) {
len = strn_len(&user_buffer[i], sizeof(pkt_dev->src_min) - 1);
if (len < 0)
return len;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
if (strcmp(buf, pkt_dev->src_min) != 0) {
memset(pkt_dev->src_min, 0, sizeof(pkt_dev->src_min));
strncpy(pkt_dev->src_min, buf, len);
pkt_dev->saddr_min = in_aton(pkt_dev->src_min);
pkt_dev->cur_saddr = pkt_dev->saddr_min;
}
if (debug)
printk(KERN_DEBUG "pktgen: src_min set to: %s\n",
pkt_dev->src_min);
i += len;
sprintf(pg_result, "OK: src_min=%s", pkt_dev->src_min);
return count;
}
if (!strcmp(name, "src_max")) {
len = strn_len(&user_buffer[i], sizeof(pkt_dev->src_max) - 1);
if (len < 0)
return len;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
if (strcmp(buf, pkt_dev->src_max) != 0) {
memset(pkt_dev->src_max, 0, sizeof(pkt_dev->src_max));
strncpy(pkt_dev->src_max, buf, len);
pkt_dev->saddr_max = in_aton(pkt_dev->src_max);
pkt_dev->cur_saddr = pkt_dev->saddr_max;
}
if (debug)
printk(KERN_DEBUG "pktgen: src_max set to: %s\n",
pkt_dev->src_max);
i += len;
sprintf(pg_result, "OK: src_max=%s", pkt_dev->src_max);
return count;
}
if (!strcmp(name, "dst_mac")) {
len = strn_len(&user_buffer[i], sizeof(valstr) - 1);
if (len < 0)
return len;
memset(valstr, 0, sizeof(valstr));
if (copy_from_user(valstr, &user_buffer[i], len))
return -EFAULT;
if (!mac_pton(valstr, pkt_dev->dst_mac))
return -EINVAL;
/* Set up Dest MAC */
memcpy(&pkt_dev->hh[0], pkt_dev->dst_mac, ETH_ALEN);
sprintf(pg_result, "OK: dstmac %pM", pkt_dev->dst_mac);
return count;
}
if (!strcmp(name, "src_mac")) {
len = strn_len(&user_buffer[i], sizeof(valstr) - 1);
if (len < 0)
return len;
memset(valstr, 0, sizeof(valstr));
if (copy_from_user(valstr, &user_buffer[i], len))
return -EFAULT;
if (!mac_pton(valstr, pkt_dev->src_mac))
return -EINVAL;
/* Set up Src MAC */
memcpy(&pkt_dev->hh[6], pkt_dev->src_mac, ETH_ALEN);
sprintf(pg_result, "OK: srcmac %pM", pkt_dev->src_mac);
return count;
}
if (!strcmp(name, "clear_counters")) {
pktgen_clear_counters(pkt_dev);
sprintf(pg_result, "OK: Clearing counters.\n");
return count;
}
if (!strcmp(name, "flows")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value > MAX_CFLOWS)
value = MAX_CFLOWS;
pkt_dev->cflows = value;
sprintf(pg_result, "OK: flows=%u", pkt_dev->cflows);
return count;
}
if (!strcmp(name, "flowlen")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
pkt_dev->lflow = value;
sprintf(pg_result, "OK: flowlen=%u", pkt_dev->lflow);
return count;
}
if (!strcmp(name, "queue_map_min")) {
len = num_arg(&user_buffer[i], 5, &value);
if (len < 0)
return len;
i += len;
pkt_dev->queue_map_min = value;
sprintf(pg_result, "OK: queue_map_min=%u", pkt_dev->queue_map_min);
return count;
}
if (!strcmp(name, "queue_map_max")) {
len = num_arg(&user_buffer[i], 5, &value);
if (len < 0)
return len;
i += len;
pkt_dev->queue_map_max = value;
sprintf(pg_result, "OK: queue_map_max=%u", pkt_dev->queue_map_max);
return count;
}
if (!strcmp(name, "mpls")) {
unsigned n, cnt;
len = get_labels(&user_buffer[i], pkt_dev);
if (len < 0)
return len;
i += len;
cnt = sprintf(pg_result, "OK: mpls=");
for (n = 0; n < pkt_dev->nr_labels; n++)
cnt += sprintf(pg_result + cnt,
"%08x%s", ntohl(pkt_dev->labels[n]),
n == pkt_dev->nr_labels-1 ? "" : ",");
if (pkt_dev->nr_labels && pkt_dev->vlan_id != 0xffff) {
pkt_dev->vlan_id = 0xffff; /* turn off VLAN/SVLAN */
pkt_dev->svlan_id = 0xffff;
if (debug)
printk(KERN_DEBUG "pktgen: VLAN/SVLAN auto turned off\n");
}
return count;
}
if (!strcmp(name, "vlan_id")) {
len = num_arg(&user_buffer[i], 4, &value);
if (len < 0)
return len;
i += len;
if (value <= 4095) {
pkt_dev->vlan_id = value; /* turn on VLAN */
if (debug)
printk(KERN_DEBUG "pktgen: VLAN turned on\n");
if (debug && pkt_dev->nr_labels)
printk(KERN_DEBUG "pktgen: MPLS auto turned off\n");
pkt_dev->nr_labels = 0; /* turn off MPLS */
sprintf(pg_result, "OK: vlan_id=%u", pkt_dev->vlan_id);
} else {
pkt_dev->vlan_id = 0xffff; /* turn off VLAN/SVLAN */
pkt_dev->svlan_id = 0xffff;
if (debug)
printk(KERN_DEBUG "pktgen: VLAN/SVLAN turned off\n");
}
return count;
}
if (!strcmp(name, "vlan_p")) {
len = num_arg(&user_buffer[i], 1, &value);
if (len < 0)
return len;
i += len;
if ((value <= 7) && (pkt_dev->vlan_id != 0xffff)) {
pkt_dev->vlan_p = value;
sprintf(pg_result, "OK: vlan_p=%u", pkt_dev->vlan_p);
} else {
sprintf(pg_result, "ERROR: vlan_p must be 0-7");
}
return count;
}
if (!strcmp(name, "vlan_cfi")) {
len = num_arg(&user_buffer[i], 1, &value);
if (len < 0)
return len;
i += len;
if ((value <= 1) && (pkt_dev->vlan_id != 0xffff)) {
pkt_dev->vlan_cfi = value;
sprintf(pg_result, "OK: vlan_cfi=%u", pkt_dev->vlan_cfi);
} else {
sprintf(pg_result, "ERROR: vlan_cfi must be 0-1");
}
return count;
}
if (!strcmp(name, "svlan_id")) {
len = num_arg(&user_buffer[i], 4, &value);
if (len < 0)
return len;
i += len;
if ((value <= 4095) && ((pkt_dev->vlan_id != 0xffff))) {
pkt_dev->svlan_id = value; /* turn on SVLAN */
if (debug)
printk(KERN_DEBUG "pktgen: SVLAN turned on\n");
if (debug && pkt_dev->nr_labels)
printk(KERN_DEBUG "pktgen: MPLS auto turned off\n");
pkt_dev->nr_labels = 0; /* turn off MPLS */
sprintf(pg_result, "OK: svlan_id=%u", pkt_dev->svlan_id);
} else {
pkt_dev->vlan_id = 0xffff; /* turn off VLAN/SVLAN */
pkt_dev->svlan_id = 0xffff;
if (debug)
printk(KERN_DEBUG "pktgen: VLAN/SVLAN turned off\n");
}
return count;
}
if (!strcmp(name, "svlan_p")) {
len = num_arg(&user_buffer[i], 1, &value);
if (len < 0)
return len;
i += len;
if ((value <= 7) && (pkt_dev->svlan_id != 0xffff)) {
pkt_dev->svlan_p = value;
sprintf(pg_result, "OK: svlan_p=%u", pkt_dev->svlan_p);
} else {
sprintf(pg_result, "ERROR: svlan_p must be 0-7");
}
return count;
}
if (!strcmp(name, "svlan_cfi")) {
len = num_arg(&user_buffer[i], 1, &value);
if (len < 0)
return len;
i += len;
if ((value <= 1) && (pkt_dev->svlan_id != 0xffff)) {
pkt_dev->svlan_cfi = value;
sprintf(pg_result, "OK: svlan_cfi=%u", pkt_dev->svlan_cfi);
} else {
sprintf(pg_result, "ERROR: svlan_cfi must be 0-1");
}
return count;
}
if (!strcmp(name, "tos")) {
__u32 tmp_value = 0;
len = hex32_arg(&user_buffer[i], 2, &tmp_value);
if (len < 0)
return len;
i += len;
if (len == 2) {
pkt_dev->tos = tmp_value;
sprintf(pg_result, "OK: tos=0x%02x", pkt_dev->tos);
} else {
sprintf(pg_result, "ERROR: tos must be 00-ff");
}
return count;
}
if (!strcmp(name, "traffic_class")) {
__u32 tmp_value = 0;
len = hex32_arg(&user_buffer[i], 2, &tmp_value);
if (len < 0)
return len;
i += len;
if (len == 2) {
pkt_dev->traffic_class = tmp_value;
sprintf(pg_result, "OK: traffic_class=0x%02x", pkt_dev->traffic_class);
} else {
sprintf(pg_result, "ERROR: traffic_class must be 00-ff");
}
return count;
}
if (!strcmp(name, "skb_priority")) {
len = num_arg(&user_buffer[i], 9, &value);
if (len < 0)
return len;
i += len;
pkt_dev->skb_priority = value;
sprintf(pg_result, "OK: skb_priority=%i",
pkt_dev->skb_priority);
return count;
}
sprintf(pkt_dev->result, "No such parameter \"%s\"", name);
return -EINVAL;
}
static int pktgen_if_open(struct inode *inode, struct file *file)
{
return single_open(file, pktgen_if_show, PDE(inode)->data);
}
static const struct file_operations pktgen_if_fops = {
.owner = THIS_MODULE,
.open = pktgen_if_open,
.read = seq_read,
.llseek = seq_lseek,
.write = pktgen_if_write,
.release = single_release,
};
static int pktgen_thread_show(struct seq_file *seq, void *v)
{
struct pktgen_thread *t = seq->private;
const struct pktgen_dev *pkt_dev;
BUG_ON(!t);
seq_printf(seq, "Running: ");
if_lock(t);
list_for_each_entry(pkt_dev, &t->if_list, list)
if (pkt_dev->running)
seq_printf(seq, "%s ", pkt_dev->odevname);
seq_printf(seq, "\nStopped: ");
list_for_each_entry(pkt_dev, &t->if_list, list)
if (!pkt_dev->running)
seq_printf(seq, "%s ", pkt_dev->odevname);
if (t->result[0])
seq_printf(seq, "\nResult: %s\n", t->result);
else
seq_printf(seq, "\nResult: NA\n");
if_unlock(t);
return 0;
}
static ssize_t pktgen_thread_write(struct file *file,
const char __user * user_buffer,
size_t count, loff_t * offset)
{
struct seq_file *seq = file->private_data;
struct pktgen_thread *t = seq->private;
int i, max, len, ret;
char name[40];
char *pg_result;
if (count < 1) {
// sprintf(pg_result, "Wrong command format");
return -EINVAL;
}
max = count;
len = count_trail_chars(user_buffer, max);
if (len < 0)
return len;
i = len;
/* Read variable name */
len = strn_len(&user_buffer[i], sizeof(name) - 1);
if (len < 0)
return len;
memset(name, 0, sizeof(name));
if (copy_from_user(name, &user_buffer[i], len))
return -EFAULT;
i += len;
max = count - i;
len = count_trail_chars(&user_buffer[i], max);
if (len < 0)
return len;
i += len;
if (debug)
printk(KERN_DEBUG "pktgen: t=%s, count=%lu\n",
name, (unsigned long)count);
if (!t) {
pr_err("ERROR: No thread\n");
ret = -EINVAL;
goto out;
}
pg_result = &(t->result[0]);
if (!strcmp(name, "add_device")) {
char f[32];
memset(f, 0, 32);
len = strn_len(&user_buffer[i], sizeof(f) - 1);
if (len < 0) {
ret = len;
goto out;
}
if (copy_from_user(f, &user_buffer[i], len))
return -EFAULT;
i += len;
mutex_lock(&pktgen_thread_lock);
ret = pktgen_add_device(t, f);
mutex_unlock(&pktgen_thread_lock);
if (!ret) {
ret = count;
sprintf(pg_result, "OK: add_device=%s", f);
} else
sprintf(pg_result, "ERROR: can not add device %s", f);
goto out;
}
if (!strcmp(name, "rem_device_all")) {
mutex_lock(&pktgen_thread_lock);
t->control |= T_REMDEVALL;
mutex_unlock(&pktgen_thread_lock);
schedule_timeout_interruptible(msecs_to_jiffies(125)); /* Propagate thread->control */
ret = count;
sprintf(pg_result, "OK: rem_device_all");
goto out;
}
if (!strcmp(name, "max_before_softirq")) {
sprintf(pg_result, "OK: Note! max_before_softirq is obsoleted -- Do not use");
ret = count;
goto out;
}
ret = -EINVAL;
out:
return ret;
}
static int pktgen_thread_open(struct inode *inode, struct file *file)
{
return single_open(file, pktgen_thread_show, PDE(inode)->data);
}
static const struct file_operations pktgen_thread_fops = {
.owner = THIS_MODULE,
.open = pktgen_thread_open,
.read = seq_read,
.llseek = seq_lseek,
.write = pktgen_thread_write,
.release = single_release,
};
/* Think find or remove for NN */
static struct pktgen_dev *__pktgen_NN_threads(const char *ifname, int remove)
{
struct pktgen_thread *t;
struct pktgen_dev *pkt_dev = NULL;
bool exact = (remove == FIND);
list_for_each_entry(t, &pktgen_threads, th_list) {
pkt_dev = pktgen_find_dev(t, ifname, exact);
if (pkt_dev) {
if (remove) {
if_lock(t);
pkt_dev->removal_mark = 1;
t->control |= T_REMDEV;
if_unlock(t);
}
break;
}
}
return pkt_dev;
}
/*
* mark a device for removal
*/
static void pktgen_mark_device(const char *ifname)
{
struct pktgen_dev *pkt_dev = NULL;
const int max_tries = 10, msec_per_try = 125;
int i = 0;
mutex_lock(&pktgen_thread_lock);
pr_debug("%s: marking %s for removal\n", __func__, ifname);
while (1) {
pkt_dev = __pktgen_NN_threads(ifname, REMOVE);
if (pkt_dev == NULL)
break; /* success */
mutex_unlock(&pktgen_thread_lock);
pr_debug("%s: waiting for %s to disappear....\n",
__func__, ifname);
schedule_timeout_interruptible(msecs_to_jiffies(msec_per_try));
mutex_lock(&pktgen_thread_lock);
if (++i >= max_tries) {
pr_err("%s: timed out after waiting %d msec for device %s to be removed\n",
__func__, msec_per_try * i, ifname);
break;
}
}
mutex_unlock(&pktgen_thread_lock);
}
static void pktgen_change_name(struct net_device *dev)
{
struct pktgen_thread *t;
list_for_each_entry(t, &pktgen_threads, th_list) {
struct pktgen_dev *pkt_dev;
list_for_each_entry(pkt_dev, &t->if_list, list) {
if (pkt_dev->odev != dev)
continue;
remove_proc_entry(pkt_dev->entry->name, pg_proc_dir);
pkt_dev->entry = proc_create_data(dev->name, 0600,
pg_proc_dir,
&pktgen_if_fops,
pkt_dev);
if (!pkt_dev->entry)
pr_err("can't move proc entry for '%s'\n",
dev->name);
break;
}
}
}
static int pktgen_device_event(struct notifier_block *unused,
unsigned long event, void *ptr)
{
struct net_device *dev = ptr;
if (!net_eq(dev_net(dev), &init_net) || pktgen_exiting)
return NOTIFY_DONE;
/* It is OK that we do not hold the group lock right now,
* as we run under the RTNL lock.
*/
switch (event) {
case NETDEV_CHANGENAME:
pktgen_change_name(dev);
break;
case NETDEV_UNREGISTER:
pktgen_mark_device(dev->name);
break;
}
return NOTIFY_DONE;
}
static struct net_device *pktgen_dev_get_by_name(struct pktgen_dev *pkt_dev,
const char *ifname)
{
char b[IFNAMSIZ+5];
int i;
for (i = 0; ifname[i] != '@'; i++) {
if (i == IFNAMSIZ)
break;
b[i] = ifname[i];
}
b[i] = 0;
return dev_get_by_name(&init_net, b);
}
/* Associate pktgen_dev with a device. */
static int pktgen_setup_dev(struct pktgen_dev *pkt_dev, const char *ifname)
{
struct net_device *odev;
int err;
/* Clean old setups */
if (pkt_dev->odev) {
dev_put(pkt_dev->odev);
pkt_dev->odev = NULL;
}
odev = pktgen_dev_get_by_name(pkt_dev, ifname);
if (!odev) {
pr_err("no such netdevice: \"%s\"\n", ifname);
return -ENODEV;
}
if (odev->type != ARPHRD_ETHER) {
pr_err("not an ethernet device: \"%s\"\n", ifname);
err = -EINVAL;
} else if (!netif_running(odev)) {
pr_err("device is down: \"%s\"\n", ifname);
err = -ENETDOWN;
} else {
pkt_dev->odev = odev;
return 0;
}
dev_put(odev);
return err;
}
/* Read pkt_dev from the interface and set up internal pktgen_dev
* structure to have the right information to create/send packets
*/
static void pktgen_setup_inject(struct pktgen_dev *pkt_dev)
{
int ntxq;
if (!pkt_dev->odev) {
pr_err("ERROR: pkt_dev->odev == NULL in setup_inject\n");
sprintf(pkt_dev->result,
"ERROR: pkt_dev->odev == NULL in setup_inject.\n");
return;
}
/* make sure that we don't pick a non-existing transmit queue */
ntxq = pkt_dev->odev->real_num_tx_queues;
if (ntxq <= pkt_dev->queue_map_min) {
pr_warning("WARNING: Requested queue_map_min (zero-based) (%d) exceeds valid range [0 - %d] for (%d) queues on %s, resetting\n",
pkt_dev->queue_map_min, (ntxq ?: 1) - 1, ntxq,
pkt_dev->odevname);
pkt_dev->queue_map_min = ntxq - 1;
}
if (pkt_dev->queue_map_max >= ntxq) {
pr_warning("WARNING: Requested queue_map_max (zero-based) (%d) exceeds valid range [0 - %d] for (%d) queues on %s, resetting\n",
pkt_dev->queue_map_max, (ntxq ?: 1) - 1, ntxq,
pkt_dev->odevname);
pkt_dev->queue_map_max = ntxq - 1;
}
/* Default to the interface's mac if not explicitly set. */
if (is_zero_ether_addr(pkt_dev->src_mac))
memcpy(&(pkt_dev->hh[6]), pkt_dev->odev->dev_addr, ETH_ALEN);
/* Set up Dest MAC */
memcpy(&(pkt_dev->hh[0]), pkt_dev->dst_mac, ETH_ALEN);
/* Set up pkt size */
pkt_dev->cur_pkt_size = pkt_dev->min_pkt_size;
if (pkt_dev->flags & F_IPV6) {
/*
* Skip this automatic address setting until locks or functions
* gets exported
*/
#ifdef NOTNOW
int i, set = 0, err = 1;
struct inet6_dev *idev;
for (i = 0; i < IN6_ADDR_HSIZE; i++)
if (pkt_dev->cur_in6_saddr.s6_addr[i]) {
set = 1;
break;
}
if (!set) {
/*
* Use linklevel address if unconfigured.
*
* use ipv6_get_lladdr if/when it's get exported
*/
rcu_read_lock();
idev = __in6_dev_get(pkt_dev->odev);
if (idev) {
struct inet6_ifaddr *ifp;
read_lock_bh(&idev->lock);
for (ifp = idev->addr_list; ifp;
ifp = ifp->if_next) {
if (ifp->scope == IFA_LINK &&
!(ifp->flags & IFA_F_TENTATIVE)) {
ipv6_addr_copy(&pkt_dev->
cur_in6_saddr,
&ifp->addr);
err = 0;
break;
}
}
read_unlock_bh(&idev->lock);
}
rcu_read_unlock();
if (err)
pr_err("ERROR: IPv6 link address not available\n");
}
#endif
} else {
pkt_dev->saddr_min = 0;
pkt_dev->saddr_max = 0;
if (strlen(pkt_dev->src_min) == 0) {
struct in_device *in_dev;
rcu_read_lock();
in_dev = __in_dev_get_rcu(pkt_dev->odev);
if (in_dev) {
if (in_dev->ifa_list) {
pkt_dev->saddr_min =
in_dev->ifa_list->ifa_address;
pkt_dev->saddr_max = pkt_dev->saddr_min;
}
}
rcu_read_unlock();
} else {
pkt_dev->saddr_min = in_aton(pkt_dev->src_min);
pkt_dev->saddr_max = in_aton(pkt_dev->src_max);
}
pkt_dev->daddr_min = in_aton(pkt_dev->dst_min);
pkt_dev->daddr_max = in_aton(pkt_dev->dst_max);
}
/* Initialize current values. */
pkt_dev->cur_dst_mac_offset = 0;
pkt_dev->cur_src_mac_offset = 0;
pkt_dev->cur_saddr = pkt_dev->saddr_min;
pkt_dev->cur_daddr = pkt_dev->daddr_min;
pkt_dev->cur_udp_dst = pkt_dev->udp_dst_min;
pkt_dev->cur_udp_src = pkt_dev->udp_src_min;
pkt_dev->nflows = 0;
}
static void spin(struct pktgen_dev *pkt_dev, ktime_t spin_until)
{
ktime_t start_time, end_time;
s64 remaining;
struct hrtimer_sleeper t;
hrtimer_init_on_stack(&t.timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
hrtimer_set_expires(&t.timer, spin_until);
remaining = ktime_to_ns(hrtimer_expires_remaining(&t.timer));
if (remaining <= 0) {
pkt_dev->next_tx = ktime_add_ns(spin_until, pkt_dev->delay);
return;
}
start_time = ktime_now();
if (remaining < 100000)
ndelay(remaining); /* really small just spin */
else {
/* see do_nanosleep */
hrtimer_init_sleeper(&t, current);
do {
set_current_state(TASK_INTERRUPTIBLE);
hrtimer_start_expires(&t.timer, HRTIMER_MODE_ABS);
if (!hrtimer_active(&t.timer))
t.task = NULL;
if (likely(t.task))
schedule();
hrtimer_cancel(&t.timer);
} while (t.task && pkt_dev->running && !signal_pending(current));
__set_current_state(TASK_RUNNING);
}
end_time = ktime_now();
pkt_dev->idle_acc += ktime_to_ns(ktime_sub(end_time, start_time));
pkt_dev->next_tx = ktime_add_ns(spin_until, pkt_dev->delay);
}
static inline void set_pkt_overhead(struct pktgen_dev *pkt_dev)
{
pkt_dev->pkt_overhead = 0;
pkt_dev->pkt_overhead += pkt_dev->nr_labels*sizeof(u32);
pkt_dev->pkt_overhead += VLAN_TAG_SIZE(pkt_dev);
pkt_dev->pkt_overhead += SVLAN_TAG_SIZE(pkt_dev);
}
static inline int f_seen(const struct pktgen_dev *pkt_dev, int flow)
{
return !!(pkt_dev->flows[flow].flags & F_INIT);
}
static inline int f_pick(struct pktgen_dev *pkt_dev)
{
int flow = pkt_dev->curfl;
if (pkt_dev->flags & F_FLOW_SEQ) {
if (pkt_dev->flows[flow].count >= pkt_dev->lflow) {
/* reset time */
pkt_dev->flows[flow].count = 0;
pkt_dev->flows[flow].flags = 0;
pkt_dev->curfl += 1;
if (pkt_dev->curfl >= pkt_dev->cflows)
pkt_dev->curfl = 0; /*reset */
}
} else {
flow = random32() % pkt_dev->cflows;
pkt_dev->curfl = flow;
if (pkt_dev->flows[flow].count > pkt_dev->lflow) {
pkt_dev->flows[flow].count = 0;
pkt_dev->flows[flow].flags = 0;
}
}
return pkt_dev->curfl;
}
#ifdef CONFIG_XFRM
/* If there was already an IPSEC SA, we keep it as is, else
* we go look for it ...
*/
#define DUMMY_MARK 0
static void get_ipsec_sa(struct pktgen_dev *pkt_dev, int flow)
{
struct xfrm_state *x = pkt_dev->flows[flow].x;
if (!x) {
/*slow path: we dont already have xfrm_state*/
x = xfrm_stateonly_find(&init_net, DUMMY_MARK,
(xfrm_address_t *)&pkt_dev->cur_daddr,
(xfrm_address_t *)&pkt_dev->cur_saddr,
AF_INET,
pkt_dev->ipsmode,
pkt_dev->ipsproto, 0);
if (x) {
pkt_dev->flows[flow].x = x;
set_pkt_overhead(pkt_dev);
pkt_dev->pkt_overhead += x->props.header_len;
}
}
}
#endif
static void set_cur_queue_map(struct pktgen_dev *pkt_dev)
{
if (pkt_dev->flags & F_QUEUE_MAP_CPU)
pkt_dev->cur_queue_map = smp_processor_id();
else if (pkt_dev->queue_map_min <= pkt_dev->queue_map_max) {
__u16 t;
if (pkt_dev->flags & F_QUEUE_MAP_RND) {
t = random32() %
(pkt_dev->queue_map_max -
pkt_dev->queue_map_min + 1)
+ pkt_dev->queue_map_min;
} else {
t = pkt_dev->cur_queue_map + 1;
if (t > pkt_dev->queue_map_max)
t = pkt_dev->queue_map_min;
}
pkt_dev->cur_queue_map = t;
}
pkt_dev->cur_queue_map = pkt_dev->cur_queue_map % pkt_dev->odev->real_num_tx_queues;
}
/* Increment/randomize headers according to flags and current values
* for IP src/dest, UDP src/dst port, MAC-Addr src/dst
*/
static void mod_cur_headers(struct pktgen_dev *pkt_dev)
{
__u32 imn;
__u32 imx;
int flow = 0;
if (pkt_dev->cflows)
flow = f_pick(pkt_dev);
/* Deal with source MAC */
if (pkt_dev->src_mac_count > 1) {
__u32 mc;
__u32 tmp;
if (pkt_dev->flags & F_MACSRC_RND)
mc = random32() % pkt_dev->src_mac_count;
else {
mc = pkt_dev->cur_src_mac_offset++;
if (pkt_dev->cur_src_mac_offset >=
pkt_dev->src_mac_count)
pkt_dev->cur_src_mac_offset = 0;
}
tmp = pkt_dev->src_mac[5] + (mc & 0xFF);
pkt_dev->hh[11] = tmp;
tmp = (pkt_dev->src_mac[4] + ((mc >> 8) & 0xFF) + (tmp >> 8));
pkt_dev->hh[10] = tmp;
tmp = (pkt_dev->src_mac[3] + ((mc >> 16) & 0xFF) + (tmp >> 8));
pkt_dev->hh[9] = tmp;
tmp = (pkt_dev->src_mac[2] + ((mc >> 24) & 0xFF) + (tmp >> 8));
pkt_dev->hh[8] = tmp;
tmp = (pkt_dev->src_mac[1] + (tmp >> 8));
pkt_dev->hh[7] = tmp;
}
/* Deal with Destination MAC */
if (pkt_dev->dst_mac_count > 1) {
__u32 mc;
__u32 tmp;
if (pkt_dev->flags & F_MACDST_RND)
mc = random32() % pkt_dev->dst_mac_count;
else {
mc = pkt_dev->cur_dst_mac_offset++;
if (pkt_dev->cur_dst_mac_offset >=
pkt_dev->dst_mac_count) {
pkt_dev->cur_dst_mac_offset = 0;
}
}
tmp = pkt_dev->dst_mac[5] + (mc & 0xFF);
pkt_dev->hh[5] = tmp;
tmp = (pkt_dev->dst_mac[4] + ((mc >> 8) & 0xFF) + (tmp >> 8));
pkt_dev->hh[4] = tmp;
tmp = (pkt_dev->dst_mac[3] + ((mc >> 16) & 0xFF) + (tmp >> 8));
pkt_dev->hh[3] = tmp;
tmp = (pkt_dev->dst_mac[2] + ((mc >> 24) & 0xFF) + (tmp >> 8));
pkt_dev->hh[2] = tmp;
tmp = (pkt_dev->dst_mac[1] + (tmp >> 8));
pkt_dev->hh[1] = tmp;
}
if (pkt_dev->flags & F_MPLS_RND) {
unsigned i;
for (i = 0; i < pkt_dev->nr_labels; i++)
if (pkt_dev->labels[i] & MPLS_STACK_BOTTOM)
pkt_dev->labels[i] = MPLS_STACK_BOTTOM |
((__force __be32)random32() &
htonl(0x000fffff));
}
if ((pkt_dev->flags & F_VID_RND) && (pkt_dev->vlan_id != 0xffff)) {
pkt_dev->vlan_id = random32() & (4096-1);
}
if ((pkt_dev->flags & F_SVID_RND) && (pkt_dev->svlan_id != 0xffff)) {
pkt_dev->svlan_id = random32() & (4096 - 1);
}
if (pkt_dev->udp_src_min < pkt_dev->udp_src_max) {
if (pkt_dev->flags & F_UDPSRC_RND)
pkt_dev->cur_udp_src = random32() %
(pkt_dev->udp_src_max - pkt_dev->udp_src_min)
+ pkt_dev->udp_src_min;
else {
pkt_dev->cur_udp_src++;
if (pkt_dev->cur_udp_src >= pkt_dev->udp_src_max)
pkt_dev->cur_udp_src = pkt_dev->udp_src_min;
}
}
if (pkt_dev->udp_dst_min < pkt_dev->udp_dst_max) {
if (pkt_dev->flags & F_UDPDST_RND) {
pkt_dev->cur_udp_dst = random32() %
(pkt_dev->udp_dst_max - pkt_dev->udp_dst_min)
+ pkt_dev->udp_dst_min;
} else {
pkt_dev->cur_udp_dst++;
if (pkt_dev->cur_udp_dst >= pkt_dev->udp_dst_max)
pkt_dev->cur_udp_dst = pkt_dev->udp_dst_min;
}
}
if (!(pkt_dev->flags & F_IPV6)) {
imn = ntohl(pkt_dev->saddr_min);
imx = ntohl(pkt_dev->saddr_max);
if (imn < imx) {
__u32 t;
if (pkt_dev->flags & F_IPSRC_RND)
t = random32() % (imx - imn) + imn;
else {
t = ntohl(pkt_dev->cur_saddr);
t++;
if (t > imx)
t = imn;
}
pkt_dev->cur_saddr = htonl(t);
}
if (pkt_dev->cflows && f_seen(pkt_dev, flow)) {
pkt_dev->cur_daddr = pkt_dev->flows[flow].cur_daddr;
} else {
imn = ntohl(pkt_dev->daddr_min);
imx = ntohl(pkt_dev->daddr_max);
if (imn < imx) {
__u32 t;
__be32 s;
if (pkt_dev->flags & F_IPDST_RND) {
t = random32() % (imx - imn) + imn;
s = htonl(t);
while (ipv4_is_loopback(s) ||
ipv4_is_multicast(s) ||
ipv4_is_lbcast(s) ||
ipv4_is_zeronet(s) ||
ipv4_is_local_multicast(s)) {
t = random32() % (imx - imn) + imn;
s = htonl(t);
}
pkt_dev->cur_daddr = s;
} else {
t = ntohl(pkt_dev->cur_daddr);
t++;
if (t > imx) {
t = imn;
}
pkt_dev->cur_daddr = htonl(t);
}
}
if (pkt_dev->cflows) {
pkt_dev->flows[flow].flags |= F_INIT;
pkt_dev->flows[flow].cur_daddr =
pkt_dev->cur_daddr;
#ifdef CONFIG_XFRM
if (pkt_dev->flags & F_IPSEC_ON)
get_ipsec_sa(pkt_dev, flow);
#endif
pkt_dev->nflows++;
}
}
} else { /* IPV6 * */
if (pkt_dev->min_in6_daddr.s6_addr32[0] == 0 &&
pkt_dev->min_in6_daddr.s6_addr32[1] == 0 &&
pkt_dev->min_in6_daddr.s6_addr32[2] == 0 &&
pkt_dev->min_in6_daddr.s6_addr32[3] == 0) ;
else {
int i;
/* Only random destinations yet */
for (i = 0; i < 4; i++) {
pkt_dev->cur_in6_daddr.s6_addr32[i] =
(((__force __be32)random32() |
pkt_dev->min_in6_daddr.s6_addr32[i]) &
pkt_dev->max_in6_daddr.s6_addr32[i]);
}
}
}
if (pkt_dev->min_pkt_size < pkt_dev->max_pkt_size) {
__u32 t;
if (pkt_dev->flags & F_TXSIZE_RND) {
t = random32() %
(pkt_dev->max_pkt_size - pkt_dev->min_pkt_size)
+ pkt_dev->min_pkt_size;
} else {
t = pkt_dev->cur_pkt_size + 1;
if (t > pkt_dev->max_pkt_size)
t = pkt_dev->min_pkt_size;
}
pkt_dev->cur_pkt_size = t;
}
set_cur_queue_map(pkt_dev);
pkt_dev->flows[flow].count++;
}
#ifdef CONFIG_XFRM
static int pktgen_output_ipsec(struct sk_buff *skb, struct pktgen_dev *pkt_dev)
{
struct xfrm_state *x = pkt_dev->flows[pkt_dev->curfl].x;
int err = 0;
if (!x)
return 0;
/* XXX: we dont support tunnel mode for now until
* we resolve the dst issue */
if (x->props.mode != XFRM_MODE_TRANSPORT)
return 0;
spin_lock(&x->lock);
err = x->outer_mode->output(x, skb);
if (err)
goto error;
err = x->type->output(x, skb);
if (err)
goto error;
x->curlft.bytes += skb->len;
x->curlft.packets++;
error:
spin_unlock(&x->lock);
return err;
}
static void free_SAs(struct pktgen_dev *pkt_dev)
{
if (pkt_dev->cflows) {
/* let go of the SAs if we have them */
int i;
for (i = 0; i < pkt_dev->cflows; i++) {
struct xfrm_state *x = pkt_dev->flows[i].x;
if (x) {
xfrm_state_put(x);
pkt_dev->flows[i].x = NULL;
}
}
}
}
static int process_ipsec(struct pktgen_dev *pkt_dev,
struct sk_buff *skb, __be16 protocol)
{
if (pkt_dev->flags & F_IPSEC_ON) {
struct xfrm_state *x = pkt_dev->flows[pkt_dev->curfl].x;
int nhead = 0;
if (x) {
int ret;
__u8 *eth;
nhead = x->props.header_len - skb_headroom(skb);
if (nhead > 0) {
ret = pskb_expand_head(skb, nhead, 0, GFP_ATOMIC);
if (ret < 0) {
pr_err("Error expanding ipsec packet %d\n",
ret);
goto err;
}
}
/* ipsec is not expecting ll header */
skb_pull(skb, ETH_HLEN);
ret = pktgen_output_ipsec(skb, pkt_dev);
if (ret) {
pr_err("Error creating ipsec packet %d\n", ret);
goto err;
}
/* restore ll */
eth = (__u8 *) skb_push(skb, ETH_HLEN);
memcpy(eth, pkt_dev->hh, 12);
*(u16 *) ð[12] = protocol;
}
}
return 1;
err:
kfree_skb(skb);
return 0;
}
#endif
static void mpls_push(__be32 *mpls, struct pktgen_dev *pkt_dev)
{
unsigned i;
for (i = 0; i < pkt_dev->nr_labels; i++)
*mpls++ = pkt_dev->labels[i] & ~MPLS_STACK_BOTTOM;
mpls--;
*mpls |= MPLS_STACK_BOTTOM;
}
static inline __be16 build_tci(unsigned int id, unsigned int cfi,
unsigned int prio)
{
return htons(id | (cfi << 12) | (prio << 13));
}
static void pktgen_finalize_skb(struct pktgen_dev *pkt_dev, struct sk_buff *skb,
int datalen)
{
struct timeval timestamp;
struct pktgen_hdr *pgh;
pgh = (struct pktgen_hdr *)skb_put(skb, sizeof(*pgh));
datalen -= sizeof(*pgh);
if (pkt_dev->nfrags <= 0) {
memset(skb_put(skb, datalen), 0, datalen);
} else {
int frags = pkt_dev->nfrags;
int i, len;
int frag_len;
if (frags > MAX_SKB_FRAGS)
frags = MAX_SKB_FRAGS;
len = datalen - frags * PAGE_SIZE;
if (len > 0) {
memset(skb_put(skb, len), 0, len);
datalen = frags * PAGE_SIZE;
}
i = 0;
frag_len = (datalen/frags) < PAGE_SIZE ?
(datalen/frags) : PAGE_SIZE;
while (datalen > 0) {
if (unlikely(!pkt_dev->page)) {
int node = numa_node_id();
if (pkt_dev->node >= 0 && (pkt_dev->flags & F_NODE))
node = pkt_dev->node;
pkt_dev->page = alloc_pages_node(node, GFP_KERNEL | __GFP_ZERO, 0);
if (!pkt_dev->page)
break;
}
skb_shinfo(skb)->frags[i].page = pkt_dev->page;
get_page(pkt_dev->page);
skb_shinfo(skb)->frags[i].page_offset = 0;
/*last fragment, fill rest of data*/
if (i == (frags - 1))
skb_shinfo(skb)->frags[i].size =
(datalen < PAGE_SIZE ? datalen : PAGE_SIZE);
else
skb_shinfo(skb)->frags[i].size = frag_len;
datalen -= skb_shinfo(skb)->frags[i].size;
skb->len += skb_shinfo(skb)->frags[i].size;
skb->data_len += skb_shinfo(skb)->frags[i].size;
i++;
skb_shinfo(skb)->nr_frags = i;
}
}
/* Stamp the time, and sequence number,
* convert them to network byte order
*/
pgh->pgh_magic = htonl(PKTGEN_MAGIC);
pgh->seq_num = htonl(pkt_dev->seq_num);
do_gettimeofday(×tamp);
pgh->tv_sec = htonl(timestamp.tv_sec);
pgh->tv_usec = htonl(timestamp.tv_usec);
}
static struct sk_buff *fill_packet_ipv4(struct net_device *odev,
struct pktgen_dev *pkt_dev)
{
struct sk_buff *skb = NULL;
__u8 *eth;
struct udphdr *udph;
int datalen, iplen;
struct iphdr *iph;
__be16 protocol = htons(ETH_P_IP);
__be32 *mpls;
__be16 *vlan_tci = NULL; /* Encapsulates priority and VLAN ID */
__be16 *vlan_encapsulated_proto = NULL; /* packet type ID field (or len) for VLAN tag */
__be16 *svlan_tci = NULL; /* Encapsulates priority and SVLAN ID */
__be16 *svlan_encapsulated_proto = NULL; /* packet type ID field (or len) for SVLAN tag */
u16 queue_map;
if (pkt_dev->nr_labels)
protocol = htons(ETH_P_MPLS_UC);
if (pkt_dev->vlan_id != 0xffff)
protocol = htons(ETH_P_8021Q);
/* Update any of the values, used when we're incrementing various
* fields.
*/
mod_cur_headers(pkt_dev);
queue_map = pkt_dev->cur_queue_map;
datalen = (odev->hard_header_len + 16) & ~0xf;
if (pkt_dev->flags & F_NODE) {
int node;
if (pkt_dev->node >= 0)
node = pkt_dev->node;
else
node = numa_node_id();
skb = __alloc_skb(NET_SKB_PAD + pkt_dev->cur_pkt_size + 64
+ datalen + pkt_dev->pkt_overhead, GFP_NOWAIT, 0, node);
if (likely(skb)) {
skb_reserve(skb, NET_SKB_PAD);
skb->dev = odev;
}
}
else
skb = __netdev_alloc_skb(odev,
pkt_dev->cur_pkt_size + 64
+ datalen + pkt_dev->pkt_overhead, GFP_NOWAIT);
if (!skb) {
sprintf(pkt_dev->result, "No memory");
return NULL;
}
prefetchw(skb->data);
skb_reserve(skb, datalen);
/* Reserve for ethernet and IP header */
eth = (__u8 *) skb_push(skb, 14);
mpls = (__be32 *)skb_put(skb, pkt_dev->nr_labels*sizeof(__u32));
if (pkt_dev->nr_labels)
mpls_push(mpls, pkt_dev);
if (pkt_dev->vlan_id != 0xffff) {
if (pkt_dev->svlan_id != 0xffff) {
svlan_tci = (__be16 *)skb_put(skb, sizeof(__be16));
*svlan_tci = build_tci(pkt_dev->svlan_id,
pkt_dev->svlan_cfi,
pkt_dev->svlan_p);
svlan_encapsulated_proto = (__be16 *)skb_put(skb, sizeof(__be16));
*svlan_encapsulated_proto = htons(ETH_P_8021Q);
}
vlan_tci = (__be16 *)skb_put(skb, sizeof(__be16));
*vlan_tci = build_tci(pkt_dev->vlan_id,
pkt_dev->vlan_cfi,
pkt_dev->vlan_p);
vlan_encapsulated_proto = (__be16 *)skb_put(skb, sizeof(__be16));
*vlan_encapsulated_proto = htons(ETH_P_IP);
}
skb->network_header = skb->tail;
skb->transport_header = skb->network_header + sizeof(struct iphdr);
skb_put(skb, sizeof(struct iphdr) + sizeof(struct udphdr));
skb_set_queue_mapping(skb, queue_map);
skb->priority = pkt_dev->skb_priority;
iph = ip_hdr(skb);
udph = udp_hdr(skb);
memcpy(eth, pkt_dev->hh, 12);
*(__be16 *) & eth[12] = protocol;
/* Eth + IPh + UDPh + mpls */
datalen = pkt_dev->cur_pkt_size - 14 - 20 - 8 -
pkt_dev->pkt_overhead;
if (datalen < sizeof(struct pktgen_hdr))
datalen = sizeof(struct pktgen_hdr);
udph->source = htons(pkt_dev->cur_udp_src);
udph->dest = htons(pkt_dev->cur_udp_dst);
udph->len = htons(datalen + 8); /* DATA + udphdr */
udph->check = 0; /* No checksum */
iph->ihl = 5;
iph->version = 4;
iph->ttl = 32;
iph->tos = pkt_dev->tos;
iph->protocol = IPPROTO_UDP; /* UDP */
iph->saddr = pkt_dev->cur_saddr;
iph->daddr = pkt_dev->cur_daddr;
iph->id = htons(pkt_dev->ip_id);
pkt_dev->ip_id++;
iph->frag_off = 0;
iplen = 20 + 8 + datalen;
iph->tot_len = htons(iplen);
iph->check = 0;
iph->check = ip_fast_csum((void *)iph, iph->ihl);
skb->protocol = protocol;
skb->mac_header = (skb->network_header - ETH_HLEN -
pkt_dev->pkt_overhead);
skb->dev = odev;
skb->pkt_type = PACKET_HOST;
pktgen_finalize_skb(pkt_dev, skb, datalen);
#ifdef CONFIG_XFRM
if (!process_ipsec(pkt_dev, skb, protocol))
return NULL;
#endif
return skb;
}
/*
* scan_ip6, fmt_ip taken from dietlibc-0.21
* Author Felix von Leitner <felix-dietlibc@fefe.de>
*
* Slightly modified for kernel.
* Should be candidate for net/ipv4/utils.c
* --ro
*/
static unsigned int scan_ip6(const char *s, char ip[16])
{
unsigned int i;
unsigned int len = 0;
unsigned long u;
char suffix[16];
unsigned int prefixlen = 0;
unsigned int suffixlen = 0;
__be32 tmp;
char *pos;
for (i = 0; i < 16; i++)
ip[i] = 0;
for (;;) {
if (*s == ':') {
len++;
if (s[1] == ':') { /* Found "::", skip to part 2 */
s += 2;
len++;
break;
}
s++;
}
u = simple_strtoul(s, &pos, 16);
i = pos - s;
if (!i)
return 0;
if (prefixlen == 12 && s[i] == '.') {
/* the last 4 bytes may be written as IPv4 address */
tmp = in_aton(s);
memcpy((struct in_addr *)(ip + 12), &tmp, sizeof(tmp));
return i + len;
}
ip[prefixlen++] = (u >> 8);
ip[prefixlen++] = (u & 255);
s += i;
len += i;
if (prefixlen == 16)
return len;
}
/* part 2, after "::" */
for (;;) {
if (*s == ':') {
if (suffixlen == 0)
break;
s++;
len++;
} else if (suffixlen != 0)
break;
u = simple_strtol(s, &pos, 16);
i = pos - s;
if (!i) {
if (*s)
len--;
break;
}
if (suffixlen + prefixlen <= 12 && s[i] == '.') {
tmp = in_aton(s);
memcpy((struct in_addr *)(suffix + suffixlen), &tmp,
sizeof(tmp));
suffixlen += 4;
len += strlen(s);
break;
}
suffix[suffixlen++] = (u >> 8);
suffix[suffixlen++] = (u & 255);
s += i;
len += i;
if (prefixlen + suffixlen == 16)
break;
}
for (i = 0; i < suffixlen; i++)
ip[16 - suffixlen + i] = suffix[i];
return len;
}
static struct sk_buff *fill_packet_ipv6(struct net_device *odev,
struct pktgen_dev *pkt_dev)
{
struct sk_buff *skb = NULL;
__u8 *eth;
struct udphdr *udph;
int datalen;
struct ipv6hdr *iph;
__be16 protocol = htons(ETH_P_IPV6);
__be32 *mpls;
__be16 *vlan_tci = NULL; /* Encapsulates priority and VLAN ID */
__be16 *vlan_encapsulated_proto = NULL; /* packet type ID field (or len) for VLAN tag */
__be16 *svlan_tci = NULL; /* Encapsulates priority and SVLAN ID */
__be16 *svlan_encapsulated_proto = NULL; /* packet type ID field (or len) for SVLAN tag */
u16 queue_map;
if (pkt_dev->nr_labels)
protocol = htons(ETH_P_MPLS_UC);
if (pkt_dev->vlan_id != 0xffff)
protocol = htons(ETH_P_8021Q);
/* Update any of the values, used when we're incrementing various
* fields.
*/
mod_cur_headers(pkt_dev);
queue_map = pkt_dev->cur_queue_map;
skb = __netdev_alloc_skb(odev,
pkt_dev->cur_pkt_size + 64
+ 16 + pkt_dev->pkt_overhead, GFP_NOWAIT);
if (!skb) {
sprintf(pkt_dev->result, "No memory");
return NULL;
}
prefetchw(skb->data);
skb_reserve(skb, 16);
/* Reserve for ethernet and IP header */
eth = (__u8 *) skb_push(skb, 14);
mpls = (__be32 *)skb_put(skb, pkt_dev->nr_labels*sizeof(__u32));
if (pkt_dev->nr_labels)
mpls_push(mpls, pkt_dev);
if (pkt_dev->vlan_id != 0xffff) {
if (pkt_dev->svlan_id != 0xffff) {
svlan_tci = (__be16 *)skb_put(skb, sizeof(__be16));
*svlan_tci = build_tci(pkt_dev->svlan_id,
pkt_dev->svlan_cfi,
pkt_dev->svlan_p);
svlan_encapsulated_proto = (__be16 *)skb_put(skb, sizeof(__be16));
*svlan_encapsulated_proto = htons(ETH_P_8021Q);
}
vlan_tci = (__be16 *)skb_put(skb, sizeof(__be16));
*vlan_tci = build_tci(pkt_dev->vlan_id,
pkt_dev->vlan_cfi,
pkt_dev->vlan_p);
vlan_encapsulated_proto = (__be16 *)skb_put(skb, sizeof(__be16));
*vlan_encapsulated_proto = htons(ETH_P_IPV6);
}
skb->network_header = skb->tail;
skb->transport_header = skb->network_header + sizeof(struct ipv6hdr);
skb_put(skb, sizeof(struct ipv6hdr) + sizeof(struct udphdr));
skb_set_queue_mapping(skb, queue_map);
skb->priority = pkt_dev->skb_priority;
iph = ipv6_hdr(skb);
udph = udp_hdr(skb);
memcpy(eth, pkt_dev->hh, 12);
*(__be16 *) ð[12] = protocol;
/* Eth + IPh + UDPh + mpls */
datalen = pkt_dev->cur_pkt_size - 14 -
sizeof(struct ipv6hdr) - sizeof(struct udphdr) -
pkt_dev->pkt_overhead;
if (datalen < 0 || datalen < sizeof(struct pktgen_hdr)) {
datalen = sizeof(struct pktgen_hdr);
if (net_ratelimit())
pr_info("increased datalen to %d\n", datalen);
}
udph->source = htons(pkt_dev->cur_udp_src);
udph->dest = htons(pkt_dev->cur_udp_dst);
udph->len = htons(datalen + sizeof(struct udphdr));
udph->check = 0; /* No checksum */
*(__be32 *) iph = htonl(0x60000000); /* Version + flow */
if (pkt_dev->traffic_class) {
/* Version + traffic class + flow (0) */
*(__be32 *)iph |= htonl(0x60000000 | (pkt_dev->traffic_class << 20));
}
iph->hop_limit = 32;
iph->payload_len = htons(sizeof(struct udphdr) + datalen);
iph->nexthdr = IPPROTO_UDP;
ipv6_addr_copy(&iph->daddr, &pkt_dev->cur_in6_daddr);
ipv6_addr_copy(&iph->saddr, &pkt_dev->cur_in6_saddr);
skb->mac_header = (skb->network_header - ETH_HLEN -
pkt_dev->pkt_overhead);
skb->protocol = protocol;
skb->dev = odev;
skb->pkt_type = PACKET_HOST;
pktgen_finalize_skb(pkt_dev, skb, datalen);
return skb;
}
static struct sk_buff *fill_packet(struct net_device *odev,
struct pktgen_dev *pkt_dev)
{
if (pkt_dev->flags & F_IPV6)
return fill_packet_ipv6(odev, pkt_dev);
else
return fill_packet_ipv4(odev, pkt_dev);
}
static void pktgen_clear_counters(struct pktgen_dev *pkt_dev)
{
pkt_dev->seq_num = 1;
pkt_dev->idle_acc = 0;
pkt_dev->sofar = 0;
pkt_dev->tx_bytes = 0;
pkt_dev->errors = 0;
}
/* Set up structure for sending pkts, clear counters */
static void pktgen_run(struct pktgen_thread *t)
{
struct pktgen_dev *pkt_dev;
int started = 0;
func_enter();
if_lock(t);
list_for_each_entry(pkt_dev, &t->if_list, list) {
/*
* setup odev and create initial packet.
*/
pktgen_setup_inject(pkt_dev);
if (pkt_dev->odev) {
pktgen_clear_counters(pkt_dev);
pkt_dev->running = 1; /* Cranke yeself! */
pkt_dev->skb = NULL;
pkt_dev->started_at =
pkt_dev->next_tx = ktime_now();
set_pkt_overhead(pkt_dev);
strcpy(pkt_dev->result, "Starting");
started++;
} else
strcpy(pkt_dev->result, "Error starting");
}
if_unlock(t);
if (started)
t->control &= ~(T_STOP);
}
static void pktgen_stop_all_threads_ifs(void)
{
struct pktgen_thread *t;
func_enter();
mutex_lock(&pktgen_thread_lock);
list_for_each_entry(t, &pktgen_threads, th_list)
t->control |= T_STOP;
mutex_unlock(&pktgen_thread_lock);
}
static int thread_is_running(const struct pktgen_thread *t)
{
const struct pktgen_dev *pkt_dev;
list_for_each_entry(pkt_dev, &t->if_list, list)
if (pkt_dev->running)
return 1;
return 0;
}
static int pktgen_wait_thread_run(struct pktgen_thread *t)
{
if_lock(t);
while (thread_is_running(t)) {
if_unlock(t);
msleep_interruptible(100);
if (signal_pending(current))
goto signal;
if_lock(t);
}
if_unlock(t);
return 1;
signal:
return 0;
}
static int pktgen_wait_all_threads_run(void)
{
struct pktgen_thread *t;
int sig = 1;
mutex_lock(&pktgen_thread_lock);
list_for_each_entry(t, &pktgen_threads, th_list) {
sig = pktgen_wait_thread_run(t);
if (sig == 0)
break;
}
if (sig == 0)
list_for_each_entry(t, &pktgen_threads, th_list)
t->control |= (T_STOP);
mutex_unlock(&pktgen_thread_lock);
return sig;
}
static void pktgen_run_all_threads(void)
{
struct pktgen_thread *t;
func_enter();
mutex_lock(&pktgen_thread_lock);
list_for_each_entry(t, &pktgen_threads, th_list)
t->control |= (T_RUN);
mutex_unlock(&pktgen_thread_lock);
/* Propagate thread->control */
schedule_timeout_interruptible(msecs_to_jiffies(125));
pktgen_wait_all_threads_run();
}
static void pktgen_reset_all_threads(void)
{
struct pktgen_thread *t;
func_enter();
mutex_lock(&pktgen_thread_lock);
list_for_each_entry(t, &pktgen_threads, th_list)
t->control |= (T_REMDEVALL);
mutex_unlock(&pktgen_thread_lock);
/* Propagate thread->control */
schedule_timeout_interruptible(msecs_to_jiffies(125));
pktgen_wait_all_threads_run();
}
static void show_results(struct pktgen_dev *pkt_dev, int nr_frags)
{
__u64 bps, mbps, pps;
char *p = pkt_dev->result;
ktime_t elapsed = ktime_sub(pkt_dev->stopped_at,
pkt_dev->started_at);
ktime_t idle = ns_to_ktime(pkt_dev->idle_acc);
p += sprintf(p, "OK: %llu(c%llu+d%llu) usec, %llu (%dbyte,%dfrags)\n",
(unsigned long long)ktime_to_us(elapsed),
(unsigned long long)ktime_to_us(ktime_sub(elapsed, idle)),
(unsigned long long)ktime_to_us(idle),
(unsigned long long)pkt_dev->sofar,
pkt_dev->cur_pkt_size, nr_frags);
pps = div64_u64(pkt_dev->sofar * NSEC_PER_SEC,
ktime_to_ns(elapsed));
bps = pps * 8 * pkt_dev->cur_pkt_size;
mbps = bps;
do_div(mbps, 1000000);
p += sprintf(p, " %llupps %lluMb/sec (%llubps) errors: %llu",
(unsigned long long)pps,
(unsigned long long)mbps,
(unsigned long long)bps,
(unsigned long long)pkt_dev->errors);
}
/* Set stopped-at timer, remove from running list, do counters & statistics */
static int pktgen_stop_device(struct pktgen_dev *pkt_dev)
{
int nr_frags = pkt_dev->skb ? skb_shinfo(pkt_dev->skb)->nr_frags : -1;
if (!pkt_dev->running) {
pr_warning("interface: %s is already stopped\n",
pkt_dev->odevname);
return -EINVAL;
}
kfree_skb(pkt_dev->skb);
pkt_dev->skb = NULL;
pkt_dev->stopped_at = ktime_now();
pkt_dev->running = 0;
show_results(pkt_dev, nr_frags);
return 0;
}
static struct pktgen_dev *next_to_run(struct pktgen_thread *t)
{
struct pktgen_dev *pkt_dev, *best = NULL;
if_lock(t);
list_for_each_entry(pkt_dev, &t->if_list, list) {
if (!pkt_dev->running)
continue;
if (best == NULL)
best = pkt_dev;
else if (ktime_lt(pkt_dev->next_tx, best->next_tx))
best = pkt_dev;
}
if_unlock(t);
return best;
}
static void pktgen_stop(struct pktgen_thread *t)
{
struct pktgen_dev *pkt_dev;
func_enter();
if_lock(t);
list_for_each_entry(pkt_dev, &t->if_list, list) {
pktgen_stop_device(pkt_dev);
}
if_unlock(t);
}
/*
* one of our devices needs to be removed - find it
* and remove it
*/
static void pktgen_rem_one_if(struct pktgen_thread *t)
{
struct list_head *q, *n;
struct pktgen_dev *cur;
func_enter();
if_lock(t);
list_for_each_safe(q, n, &t->if_list) {
cur = list_entry(q, struct pktgen_dev, list);
if (!cur->removal_mark)
continue;
kfree_skb(cur->skb);
cur->skb = NULL;
pktgen_remove_device(t, cur);
break;
}
if_unlock(t);
}
static void pktgen_rem_all_ifs(struct pktgen_thread *t)
{
struct list_head *q, *n;
struct pktgen_dev *cur;
func_enter();
/* Remove all devices, free mem */
if_lock(t);
list_for_each_safe(q, n, &t->if_list) {
cur = list_entry(q, struct pktgen_dev, list);
kfree_skb(cur->skb);
cur->skb = NULL;
pktgen_remove_device(t, cur);
}
if_unlock(t);
}
static void pktgen_rem_thread(struct pktgen_thread *t)
{
/* Remove from the thread list */
remove_proc_entry(t->tsk->comm, pg_proc_dir);
}
static void pktgen_resched(struct pktgen_dev *pkt_dev)
{
ktime_t idle_start = ktime_now();
schedule();
pkt_dev->idle_acc += ktime_to_ns(ktime_sub(ktime_now(), idle_start));
}
static void pktgen_wait_for_skb(struct pktgen_dev *pkt_dev)
{
ktime_t idle_start = ktime_now();
while (atomic_read(&(pkt_dev->skb->users)) != 1) {
if (signal_pending(current))
break;
if (need_resched())
pktgen_resched(pkt_dev);
else
cpu_relax();
}
pkt_dev->idle_acc += ktime_to_ns(ktime_sub(ktime_now(), idle_start));
}
static void pktgen_xmit(struct pktgen_dev *pkt_dev)
{
struct net_device *odev = pkt_dev->odev;
netdev_tx_t (*xmit)(struct sk_buff *, struct net_device *)
= odev->netdev_ops->ndo_start_xmit;
struct netdev_queue *txq;
u16 queue_map;
int ret;
/* If device is offline, then don't send */
if (unlikely(!netif_running(odev) || !netif_carrier_ok(odev))) {
pktgen_stop_device(pkt_dev);
return;
}
/* This is max DELAY, this has special meaning of
* "never transmit"
*/
if (unlikely(pkt_dev->delay == ULLONG_MAX)) {
pkt_dev->next_tx = ktime_add_ns(ktime_now(), ULONG_MAX);
return;
}
/* If no skb or clone count exhausted then get new one */
if (!pkt_dev->skb || (pkt_dev->last_ok &&
++pkt_dev->clone_count >= pkt_dev->clone_skb)) {
/* build a new pkt */
kfree_skb(pkt_dev->skb);
pkt_dev->skb = fill_packet(odev, pkt_dev);
if (pkt_dev->skb == NULL) {
pr_err("ERROR: couldn't allocate skb in fill_packet\n");
schedule();
pkt_dev->clone_count--; /* back out increment, OOM */
return;
}
pkt_dev->last_pkt_size = pkt_dev->skb->len;
pkt_dev->allocated_skbs++;
pkt_dev->clone_count = 0; /* reset counter */
}
if (pkt_dev->delay && pkt_dev->last_ok)
spin(pkt_dev, pkt_dev->next_tx);
queue_map = skb_get_queue_mapping(pkt_dev->skb);
txq = netdev_get_tx_queue(odev, queue_map);
__netif_tx_lock_bh(txq);
if (unlikely(netif_tx_queue_frozen_or_stopped(txq))) {
ret = NETDEV_TX_BUSY;
pkt_dev->last_ok = 0;
goto unlock;
}
atomic_inc(&(pkt_dev->skb->users));
ret = (*xmit)(pkt_dev->skb, odev);
switch (ret) {
case NETDEV_TX_OK:
txq_trans_update(txq);
pkt_dev->last_ok = 1;
pkt_dev->sofar++;
pkt_dev->seq_num++;
pkt_dev->tx_bytes += pkt_dev->last_pkt_size;
break;
case NET_XMIT_DROP:
case NET_XMIT_CN:
case NET_XMIT_POLICED:
/* skb has been consumed */
pkt_dev->errors++;
break;
default: /* Drivers are not supposed to return other values! */
if (net_ratelimit())
pr_info("%s xmit error: %d\n", pkt_dev->odevname, ret);
pkt_dev->errors++;
/* fallthru */
case NETDEV_TX_LOCKED:
case NETDEV_TX_BUSY:
/* Retry it next time */
atomic_dec(&(pkt_dev->skb->users));
pkt_dev->last_ok = 0;
}
unlock:
__netif_tx_unlock_bh(txq);
/* If pkt_dev->count is zero, then run forever */
if ((pkt_dev->count != 0) && (pkt_dev->sofar >= pkt_dev->count)) {
pktgen_wait_for_skb(pkt_dev);
/* Done with this */
pktgen_stop_device(pkt_dev);
}
}
/*
* Main loop of the thread goes here
*/
static int pktgen_thread_worker(void *arg)
{
DEFINE_WAIT(wait);
struct pktgen_thread *t = arg;
struct pktgen_dev *pkt_dev = NULL;
int cpu = t->cpu;
BUG_ON(smp_processor_id() != cpu);
init_waitqueue_head(&t->queue);
complete(&t->start_done);
pr_debug("starting pktgen/%d: pid=%d\n", cpu, task_pid_nr(current));
set_current_state(TASK_INTERRUPTIBLE);
set_freezable();
while (!kthread_should_stop()) {
pkt_dev = next_to_run(t);
if (unlikely(!pkt_dev && t->control == 0)) {
if (pktgen_exiting)
break;
wait_event_interruptible_timeout(t->queue,
t->control != 0,
HZ/10);
try_to_freeze();
continue;
}
__set_current_state(TASK_RUNNING);
if (likely(pkt_dev)) {
pktgen_xmit(pkt_dev);
if (need_resched())
pktgen_resched(pkt_dev);
else
cpu_relax();
}
if (t->control & T_STOP) {
pktgen_stop(t);
t->control &= ~(T_STOP);
}
if (t->control & T_RUN) {
pktgen_run(t);
t->control &= ~(T_RUN);
}
if (t->control & T_REMDEVALL) {
pktgen_rem_all_ifs(t);
t->control &= ~(T_REMDEVALL);
}
if (t->control & T_REMDEV) {
pktgen_rem_one_if(t);
t->control &= ~(T_REMDEV);
}
try_to_freeze();
set_current_state(TASK_INTERRUPTIBLE);
}
pr_debug("%s stopping all device\n", t->tsk->comm);
pktgen_stop(t);
pr_debug("%s removing all device\n", t->tsk->comm);
pktgen_rem_all_ifs(t);
pr_debug("%s removing thread\n", t->tsk->comm);
pktgen_rem_thread(t);
/* Wait for kthread_stop */
while (!kthread_should_stop()) {
set_current_state(TASK_INTERRUPTIBLE);
schedule();
}
__set_current_state(TASK_RUNNING);
return 0;
}
static struct pktgen_dev *pktgen_find_dev(struct pktgen_thread *t,
const char *ifname, bool exact)
{
struct pktgen_dev *p, *pkt_dev = NULL;
size_t len = strlen(ifname);
if_lock(t);
list_for_each_entry(p, &t->if_list, list)
if (strncmp(p->odevname, ifname, len) == 0) {
if (p->odevname[len]) {
if (exact || p->odevname[len] != '@')
continue;
}
pkt_dev = p;
break;
}
if_unlock(t);
pr_debug("find_dev(%s) returning %p\n", ifname, pkt_dev);
return pkt_dev;
}
/*
* Adds a dev at front of if_list.
*/
static int add_dev_to_thread(struct pktgen_thread *t,
struct pktgen_dev *pkt_dev)
{
int rv = 0;
if_lock(t);
if (pkt_dev->pg_thread) {
pr_err("ERROR: already assigned to a thread\n");
rv = -EBUSY;
goto out;
}
list_add(&pkt_dev->list, &t->if_list);
pkt_dev->pg_thread = t;
pkt_dev->running = 0;
out:
if_unlock(t);
return rv;
}
/* Called under thread lock */
static int pktgen_add_device(struct pktgen_thread *t, const char *ifname)
{
struct pktgen_dev *pkt_dev;
int err;
int node = cpu_to_node(t->cpu);
/* We don't allow a device to be on several threads */
pkt_dev = __pktgen_NN_threads(ifname, FIND);
if (pkt_dev) {
pr_err("ERROR: interface already used\n");
return -EBUSY;
}
pkt_dev = kzalloc_node(sizeof(struct pktgen_dev), GFP_KERNEL, node);
if (!pkt_dev)
return -ENOMEM;
strcpy(pkt_dev->odevname, ifname);
pkt_dev->flows = vzalloc_node(MAX_CFLOWS * sizeof(struct flow_state),
node);
if (pkt_dev->flows == NULL) {
kfree(pkt_dev);
return -ENOMEM;
}
pkt_dev->removal_mark = 0;
pkt_dev->min_pkt_size = ETH_ZLEN;
pkt_dev->max_pkt_size = ETH_ZLEN;
pkt_dev->nfrags = 0;
pkt_dev->delay = pg_delay_d;
pkt_dev->count = pg_count_d;
pkt_dev->sofar = 0;
pkt_dev->udp_src_min = 9; /* sink port */
pkt_dev->udp_src_max = 9;
pkt_dev->udp_dst_min = 9;
pkt_dev->udp_dst_max = 9;
pkt_dev->vlan_p = 0;
pkt_dev->vlan_cfi = 0;
pkt_dev->vlan_id = 0xffff;
pkt_dev->svlan_p = 0;
pkt_dev->svlan_cfi = 0;
pkt_dev->svlan_id = 0xffff;
pkt_dev->node = -1;
err = pktgen_setup_dev(pkt_dev, ifname);
if (err)
goto out1;
if (pkt_dev->odev->priv_flags & IFF_TX_SKB_SHARING)
pkt_dev->clone_skb = pg_clone_skb_d;
pkt_dev->entry = proc_create_data(ifname, 0600, pg_proc_dir,
&pktgen_if_fops, pkt_dev);
if (!pkt_dev->entry) {
pr_err("cannot create %s/%s procfs entry\n",
PG_PROC_DIR, ifname);
err = -EINVAL;
goto out2;
}
#ifdef CONFIG_XFRM
pkt_dev->ipsmode = XFRM_MODE_TRANSPORT;
pkt_dev->ipsproto = IPPROTO_ESP;
#endif
return add_dev_to_thread(t, pkt_dev);
out2:
dev_put(pkt_dev->odev);
out1:
#ifdef CONFIG_XFRM
free_SAs(pkt_dev);
#endif
vfree(pkt_dev->flows);
kfree(pkt_dev);
return err;
}
static int __init pktgen_create_thread(int cpu)
{
struct pktgen_thread *t;
struct proc_dir_entry *pe;
struct task_struct *p;
t = kzalloc_node(sizeof(struct pktgen_thread), GFP_KERNEL,
cpu_to_node(cpu));
if (!t) {
pr_err("ERROR: out of memory, can't create new thread\n");
return -ENOMEM;
}
spin_lock_init(&t->if_lock);
t->cpu = cpu;
INIT_LIST_HEAD(&t->if_list);
list_add_tail(&t->th_list, &pktgen_threads);
init_completion(&t->start_done);
p = kthread_create_on_node(pktgen_thread_worker,
t,
cpu_to_node(cpu),
"kpktgend_%d", cpu);
if (IS_ERR(p)) {
pr_err("kernel_thread() failed for cpu %d\n", t->cpu);
list_del(&t->th_list);
kfree(t);
return PTR_ERR(p);
}
kthread_bind(p, cpu);
t->tsk = p;
pe = proc_create_data(t->tsk->comm, 0600, pg_proc_dir,
&pktgen_thread_fops, t);
if (!pe) {
pr_err("cannot create %s/%s procfs entry\n",
PG_PROC_DIR, t->tsk->comm);
kthread_stop(p);
list_del(&t->th_list);
kfree(t);
return -EINVAL;
}
wake_up_process(p);
wait_for_completion(&t->start_done);
return 0;
}
/*
* Removes a device from the thread if_list.
*/
static void _rem_dev_from_if_list(struct pktgen_thread *t,
struct pktgen_dev *pkt_dev)
{
struct list_head *q, *n;
struct pktgen_dev *p;
list_for_each_safe(q, n, &t->if_list) {
p = list_entry(q, struct pktgen_dev, list);
if (p == pkt_dev)
list_del(&p->list);
}
}
static int pktgen_remove_device(struct pktgen_thread *t,
struct pktgen_dev *pkt_dev)
{
pr_debug("remove_device pkt_dev=%p\n", pkt_dev);
if (pkt_dev->running) {
pr_warning("WARNING: trying to remove a running interface, stopping it now\n");
pktgen_stop_device(pkt_dev);
}
/* Dis-associate from the interface */
if (pkt_dev->odev) {
dev_put(pkt_dev->odev);
pkt_dev->odev = NULL;
}
/* And update the thread if_list */
_rem_dev_from_if_list(t, pkt_dev);
if (pkt_dev->entry)
remove_proc_entry(pkt_dev->entry->name, pg_proc_dir);
#ifdef CONFIG_XFRM
free_SAs(pkt_dev);
#endif
vfree(pkt_dev->flows);
if (pkt_dev->page)
put_page(pkt_dev->page);
kfree(pkt_dev);
return 0;
}
static int __init pg_init(void)
{
int cpu;
struct proc_dir_entry *pe;
int ret = 0;
pr_info("%s", version);
pg_proc_dir = proc_mkdir(PG_PROC_DIR, init_net.proc_net);
if (!pg_proc_dir)
return -ENODEV;
pe = proc_create(PGCTRL, 0600, pg_proc_dir, &pktgen_fops);
if (pe == NULL) {
pr_err("ERROR: cannot create %s procfs entry\n", PGCTRL);
ret = -EINVAL;
goto remove_dir;
}
register_netdevice_notifier(&pktgen_notifier_block);
for_each_online_cpu(cpu) {
int err;
err = pktgen_create_thread(cpu);
if (err)
pr_warning("WARNING: Cannot create thread for cpu %d (%d)\n",
cpu, err);
}
if (list_empty(&pktgen_threads)) {
pr_err("ERROR: Initialization failed for all threads\n");
ret = -ENODEV;
goto unregister;
}
return 0;
unregister:
unregister_netdevice_notifier(&pktgen_notifier_block);
remove_proc_entry(PGCTRL, pg_proc_dir);
remove_dir:
proc_net_remove(&init_net, PG_PROC_DIR);
return ret;
}
static void __exit pg_cleanup(void)
{
struct pktgen_thread *t;
struct list_head *q, *n;
LIST_HEAD(list);
/* Stop all interfaces & threads */
pktgen_exiting = true;
mutex_lock(&pktgen_thread_lock);
list_splice_init(&pktgen_threads, &list);
mutex_unlock(&pktgen_thread_lock);
list_for_each_safe(q, n, &list) {
t = list_entry(q, struct pktgen_thread, th_list);
list_del(&t->th_list);
kthread_stop(t->tsk);
kfree(t);
}
/* Un-register us from receiving netdevice events */
unregister_netdevice_notifier(&pktgen_notifier_block);
/* Clean up proc file system */
remove_proc_entry(PGCTRL, pg_proc_dir);
proc_net_remove(&init_net, PG_PROC_DIR);
}
module_init(pg_init);
module_exit(pg_cleanup);
MODULE_AUTHOR("Robert Olsson <robert.olsson@its.uu.se>");
MODULE_DESCRIPTION("Packet Generator tool");
MODULE_LICENSE("GPL");
MODULE_VERSION(VERSION);
module_param(pg_count_d, int, 0);
MODULE_PARM_DESC(pg_count_d, "Default number of packets to inject");
module_param(pg_delay_d, int, 0);
MODULE_PARM_DESC(pg_delay_d, "Default delay between packets (nanoseconds)");
module_param(pg_clone_skb_d, int, 0);
MODULE_PARM_DESC(pg_clone_skb_d, "Default number of copies of the same packet");
module_param(debug, int, 0);
MODULE_PARM_DESC(debug, "Enable debugging of pktgen module");
| gpl-2.0 |
adrientetar/semc-7x30-kernel-ics | arch/arm/mach-s3c2412/gpio.c | 823 | 1257 | /* linux/arch/arm/mach-s3c2412/gpio.c
*
* Copyright (c) 2007 Simtec Electronics
* Ben Dooks <ben@simtec.co.uk>
*
* http://armlinux.simtec.co.uk/.
*
* S3C2412/S3C2413 specific GPIO support
*
* 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/types.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <mach/regs-gpio.h>
#include <mach/hardware.h>
int s3c2412_gpio_set_sleepcfg(unsigned int pin, unsigned int state)
{
void __iomem *base = S3C24XX_GPIO_BASE(pin);
unsigned long offs = S3C2410_GPIO_OFFSET(pin);
unsigned long flags;
unsigned long slpcon;
offs *= 2;
if (pin < S3C2410_GPIO_BANKB)
return -EINVAL;
if (pin >= S3C2410_GPIO_BANKF &&
pin <= S3C2410_GPIO_BANKG)
return -EINVAL;
if (pin > (S3C2410_GPIO_BANKH + 32))
return -EINVAL;
local_irq_save(flags);
slpcon = __raw_readl(base + 0x0C);
slpcon &= ~(3 << offs);
slpcon |= state << offs;
__raw_writel(slpcon, base + 0x0C);
local_irq_restore(flags);
return 0;
}
EXPORT_SYMBOL(s3c2412_gpio_set_sleepcfg);
| gpl-2.0 |
TLOIN-3X-WIP/android_kernel_samsung_msm8660-common | net/core/pktgen.c | 823 | 93193 | /*
* Authors:
* Copyright 2001, 2002 by Robert Olsson <robert.olsson@its.uu.se>
* Uppsala University and
* Swedish University of Agricultural Sciences
*
* Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
* Ben Greear <greearb@candelatech.com>
* Jens Låås <jens.laas@data.slu.se>
*
* 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.
*
*
* A tool for loading the network with preconfigurated packets.
* The tool is implemented as a linux module. Parameters are output
* device, delay (to hard_xmit), number of packets, and whether
* to use multiple SKBs or just the same one.
* pktgen uses the installed interface's output routine.
*
* Additional hacking by:
*
* Jens.Laas@data.slu.se
* Improved by ANK. 010120.
* Improved by ANK even more. 010212.
* MAC address typo fixed. 010417 --ro
* Integrated. 020301 --DaveM
* Added multiskb option 020301 --DaveM
* Scaling of results. 020417--sigurdur@linpro.no
* Significant re-work of the module:
* * Convert to threaded model to more efficiently be able to transmit
* and receive on multiple interfaces at once.
* * Converted many counters to __u64 to allow longer runs.
* * Allow configuration of ranges, like min/max IP address, MACs,
* and UDP-ports, for both source and destination, and can
* set to use a random distribution or sequentially walk the range.
* * Can now change most values after starting.
* * Place 12-byte packet in UDP payload with magic number,
* sequence number, and timestamp.
* * Add receiver code that detects dropped pkts, re-ordered pkts, and
* latencies (with micro-second) precision.
* * Add IOCTL interface to easily get counters & configuration.
* --Ben Greear <greearb@candelatech.com>
*
* Renamed multiskb to clone_skb and cleaned up sending core for two distinct
* skb modes. A clone_skb=0 mode for Ben "ranges" work and a clone_skb != 0
* as a "fastpath" with a configurable number of clones after alloc's.
* clone_skb=0 means all packets are allocated this also means ranges time
* stamps etc can be used. clone_skb=100 means 1 malloc is followed by 100
* clones.
*
* Also moved to /proc/net/pktgen/
* --ro
*
* Sept 10: Fixed threading/locking. Lots of bone-headed and more clever
* mistakes. Also merged in DaveM's patch in the -pre6 patch.
* --Ben Greear <greearb@candelatech.com>
*
* Integrated to 2.5.x 021029 --Lucio Maciel (luciomaciel@zipmail.com.br)
*
*
* 021124 Finished major redesign and rewrite for new functionality.
* See Documentation/networking/pktgen.txt for how to use this.
*
* The new operation:
* For each CPU one thread/process is created at start. This process checks
* for running devices in the if_list and sends packets until count is 0 it
* also the thread checks the thread->control which is used for inter-process
* communication. controlling process "posts" operations to the threads this
* way. The if_lock should be possible to remove when add/rem_device is merged
* into this too.
*
* By design there should only be *one* "controlling" process. In practice
* multiple write accesses gives unpredictable result. Understood by "write"
* to /proc gives result code thats should be read be the "writer".
* For practical use this should be no problem.
*
* Note when adding devices to a specific CPU there good idea to also assign
* /proc/irq/XX/smp_affinity so TX-interrupts gets bound to the same CPU.
* --ro
*
* Fix refcount off by one if first packet fails, potential null deref,
* memleak 030710- KJP
*
* First "ranges" functionality for ipv6 030726 --ro
*
* Included flow support. 030802 ANK.
*
* Fixed unaligned access on IA-64 Grant Grundler <grundler@parisc-linux.org>
*
* Remove if fix from added Harald Welte <laforge@netfilter.org> 040419
* ia64 compilation fix from Aron Griffis <aron@hp.com> 040604
*
* New xmit() return, do_div and misc clean up by Stephen Hemminger
* <shemminger@osdl.org> 040923
*
* Randy Dunlap fixed u64 printk compiler waring
*
* Remove FCS from BW calculation. Lennert Buytenhek <buytenh@wantstofly.org>
* New time handling. Lennert Buytenhek <buytenh@wantstofly.org> 041213
*
* Corrections from Nikolai Malykh (nmalykh@bilim.com)
* Removed unused flags F_SET_SRCMAC & F_SET_SRCIP 041230
*
* interruptible_sleep_on_timeout() replaced Nishanth Aravamudan <nacc@us.ibm.com>
* 050103
*
* MPLS support by Steven Whitehouse <steve@chygwyn.com>
*
* 802.1Q/Q-in-Q support by Francesco Fondelli (FF) <francesco.fondelli@gmail.com>
*
* Fixed src_mac command to set source mac of packet to value specified in
* command by Adit Ranadive <adit.262@gmail.com>
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/sys.h>
#include <linux/types.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/mutex.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/unistd.h>
#include <linux/string.h>
#include <linux/ptrace.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/interrupt.h>
#include <linux/capability.h>
#include <linux/hrtimer.h>
#include <linux/freezer.h>
#include <linux/delay.h>
#include <linux/timer.h>
#include <linux/list.h>
#include <linux/init.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/inet.h>
#include <linux/inetdevice.h>
#include <linux/rtnetlink.h>
#include <linux/if_arp.h>
#include <linux/if_vlan.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/udp.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/wait.h>
#include <linux/etherdevice.h>
#include <linux/kthread.h>
#include <linux/prefetch.h>
#include <net/net_namespace.h>
#include <net/checksum.h>
#include <net/ipv6.h>
#include <net/addrconf.h>
#ifdef CONFIG_XFRM
#include <net/xfrm.h>
#endif
#include <asm/byteorder.h>
#include <linux/rcupdate.h>
#include <linux/bitops.h>
#include <linux/io.h>
#include <linux/timex.h>
#include <linux/uaccess.h>
#include <asm/dma.h>
#include <asm/div64.h> /* do_div */
#define VERSION "2.74"
#define IP_NAME_SZ 32
#define MAX_MPLS_LABELS 16 /* This is the max label stack depth */
#define MPLS_STACK_BOTTOM htonl(0x00000100)
#define func_enter() pr_debug("entering %s\n", __func__);
/* Device flag bits */
#define F_IPSRC_RND (1<<0) /* IP-Src Random */
#define F_IPDST_RND (1<<1) /* IP-Dst Random */
#define F_UDPSRC_RND (1<<2) /* UDP-Src Random */
#define F_UDPDST_RND (1<<3) /* UDP-Dst Random */
#define F_MACSRC_RND (1<<4) /* MAC-Src Random */
#define F_MACDST_RND (1<<5) /* MAC-Dst Random */
#define F_TXSIZE_RND (1<<6) /* Transmit size is random */
#define F_IPV6 (1<<7) /* Interface in IPV6 Mode */
#define F_MPLS_RND (1<<8) /* Random MPLS labels */
#define F_VID_RND (1<<9) /* Random VLAN ID */
#define F_SVID_RND (1<<10) /* Random SVLAN ID */
#define F_FLOW_SEQ (1<<11) /* Sequential flows */
#define F_IPSEC_ON (1<<12) /* ipsec on for flows */
#define F_QUEUE_MAP_RND (1<<13) /* queue map Random */
#define F_QUEUE_MAP_CPU (1<<14) /* queue map mirrors smp_processor_id() */
#define F_NODE (1<<15) /* Node memory alloc*/
/* Thread control flag bits */
#define T_STOP (1<<0) /* Stop run */
#define T_RUN (1<<1) /* Start run */
#define T_REMDEVALL (1<<2) /* Remove all devs */
#define T_REMDEV (1<<3) /* Remove one dev */
/* If lock -- can be removed after some work */
#define if_lock(t) spin_lock(&(t->if_lock));
#define if_unlock(t) spin_unlock(&(t->if_lock));
/* Used to help with determining the pkts on receive */
#define PKTGEN_MAGIC 0xbe9be955
#define PG_PROC_DIR "pktgen"
#define PGCTRL "pgctrl"
static struct proc_dir_entry *pg_proc_dir;
#define MAX_CFLOWS 65536
#define VLAN_TAG_SIZE(x) ((x)->vlan_id == 0xffff ? 0 : 4)
#define SVLAN_TAG_SIZE(x) ((x)->svlan_id == 0xffff ? 0 : 4)
struct flow_state {
__be32 cur_daddr;
int count;
#ifdef CONFIG_XFRM
struct xfrm_state *x;
#endif
__u32 flags;
};
/* flow flag bits */
#define F_INIT (1<<0) /* flow has been initialized */
struct pktgen_dev {
/*
* Try to keep frequent/infrequent used vars. separated.
*/
struct proc_dir_entry *entry; /* proc file */
struct pktgen_thread *pg_thread;/* the owner */
struct list_head list; /* chaining in the thread's run-queue */
int running; /* if false, the test will stop */
/* If min != max, then we will either do a linear iteration, or
* we will do a random selection from within the range.
*/
__u32 flags;
int removal_mark; /* non-zero => the device is marked for
* removal by worker thread */
int min_pkt_size; /* = ETH_ZLEN; */
int max_pkt_size; /* = ETH_ZLEN; */
int pkt_overhead; /* overhead for MPLS, VLANs, IPSEC etc */
int nfrags;
struct page *page;
u64 delay; /* nano-seconds */
__u64 count; /* Default No packets to send */
__u64 sofar; /* How many pkts we've sent so far */
__u64 tx_bytes; /* How many bytes we've transmitted */
__u64 errors; /* Errors when trying to transmit, */
/* runtime counters relating to clone_skb */
__u64 allocated_skbs;
__u32 clone_count;
int last_ok; /* Was last skb sent?
* Or a failed transmit of some sort?
* This will keep sequence numbers in order
*/
ktime_t next_tx;
ktime_t started_at;
ktime_t stopped_at;
u64 idle_acc; /* nano-seconds */
__u32 seq_num;
int clone_skb; /*
* Use multiple SKBs during packet gen.
* If this number is greater than 1, then
* that many copies of the same packet will be
* sent before a new packet is allocated.
* If you want to send 1024 identical packets
* before creating a new packet,
* set clone_skb to 1024.
*/
char dst_min[IP_NAME_SZ]; /* IP, ie 1.2.3.4 */
char dst_max[IP_NAME_SZ]; /* IP, ie 1.2.3.4 */
char src_min[IP_NAME_SZ]; /* IP, ie 1.2.3.4 */
char src_max[IP_NAME_SZ]; /* IP, ie 1.2.3.4 */
struct in6_addr in6_saddr;
struct in6_addr in6_daddr;
struct in6_addr cur_in6_daddr;
struct in6_addr cur_in6_saddr;
/* For ranges */
struct in6_addr min_in6_daddr;
struct in6_addr max_in6_daddr;
struct in6_addr min_in6_saddr;
struct in6_addr max_in6_saddr;
/* If we're doing ranges, random or incremental, then this
* defines the min/max for those ranges.
*/
__be32 saddr_min; /* inclusive, source IP address */
__be32 saddr_max; /* exclusive, source IP address */
__be32 daddr_min; /* inclusive, dest IP address */
__be32 daddr_max; /* exclusive, dest IP address */
__u16 udp_src_min; /* inclusive, source UDP port */
__u16 udp_src_max; /* exclusive, source UDP port */
__u16 udp_dst_min; /* inclusive, dest UDP port */
__u16 udp_dst_max; /* exclusive, dest UDP port */
/* DSCP + ECN */
__u8 tos; /* six MSB of (former) IPv4 TOS
are for dscp codepoint */
__u8 traffic_class; /* ditto for the (former) Traffic Class in IPv6
(see RFC 3260, sec. 4) */
/* MPLS */
unsigned nr_labels; /* Depth of stack, 0 = no MPLS */
__be32 labels[MAX_MPLS_LABELS];
/* VLAN/SVLAN (802.1Q/Q-in-Q) */
__u8 vlan_p;
__u8 vlan_cfi;
__u16 vlan_id; /* 0xffff means no vlan tag */
__u8 svlan_p;
__u8 svlan_cfi;
__u16 svlan_id; /* 0xffff means no svlan tag */
__u32 src_mac_count; /* How many MACs to iterate through */
__u32 dst_mac_count; /* How many MACs to iterate through */
unsigned char dst_mac[ETH_ALEN];
unsigned char src_mac[ETH_ALEN];
__u32 cur_dst_mac_offset;
__u32 cur_src_mac_offset;
__be32 cur_saddr;
__be32 cur_daddr;
__u16 ip_id;
__u16 cur_udp_dst;
__u16 cur_udp_src;
__u16 cur_queue_map;
__u32 cur_pkt_size;
__u32 last_pkt_size;
__u8 hh[14];
/* = {
0x00, 0x80, 0xC8, 0x79, 0xB3, 0xCB,
We fill in SRC address later
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x08, 0x00
};
*/
__u16 pad; /* pad out the hh struct to an even 16 bytes */
struct sk_buff *skb; /* skb we are to transmit next, used for when we
* are transmitting the same one multiple times
*/
struct net_device *odev; /* The out-going device.
* Note that the device should have it's
* pg_info pointer pointing back to this
* device.
* Set when the user specifies the out-going
* device name (not when the inject is
* started as it used to do.)
*/
char odevname[32];
struct flow_state *flows;
unsigned cflows; /* Concurrent flows (config) */
unsigned lflow; /* Flow length (config) */
unsigned nflows; /* accumulated flows (stats) */
unsigned curfl; /* current sequenced flow (state)*/
u16 queue_map_min;
u16 queue_map_max;
__u32 skb_priority; /* skb priority field */
int node; /* Memory node */
#ifdef CONFIG_XFRM
__u8 ipsmode; /* IPSEC mode (config) */
__u8 ipsproto; /* IPSEC type (config) */
#endif
char result[512];
};
struct pktgen_hdr {
__be32 pgh_magic;
__be32 seq_num;
__be32 tv_sec;
__be32 tv_usec;
};
static bool pktgen_exiting __read_mostly;
struct pktgen_thread {
spinlock_t if_lock; /* for list of devices */
struct list_head if_list; /* All device here */
struct list_head th_list;
struct task_struct *tsk;
char result[512];
/* Field for thread to receive "posted" events terminate,
stop ifs etc. */
u32 control;
int cpu;
wait_queue_head_t queue;
struct completion start_done;
};
#define REMOVE 1
#define FIND 0
static inline ktime_t ktime_now(void)
{
struct timespec ts;
ktime_get_ts(&ts);
return timespec_to_ktime(ts);
}
/* This works even if 32 bit because of careful byte order choice */
static inline int ktime_lt(const ktime_t cmp1, const ktime_t cmp2)
{
return cmp1.tv64 < cmp2.tv64;
}
static const char version[] =
"Packet Generator for packet performance testing. "
"Version: " VERSION "\n";
static int pktgen_remove_device(struct pktgen_thread *t, struct pktgen_dev *i);
static int pktgen_add_device(struct pktgen_thread *t, const char *ifname);
static struct pktgen_dev *pktgen_find_dev(struct pktgen_thread *t,
const char *ifname, bool exact);
static int pktgen_device_event(struct notifier_block *, unsigned long, void *);
static void pktgen_run_all_threads(void);
static void pktgen_reset_all_threads(void);
static void pktgen_stop_all_threads_ifs(void);
static void pktgen_stop(struct pktgen_thread *t);
static void pktgen_clear_counters(struct pktgen_dev *pkt_dev);
static unsigned int scan_ip6(const char *s, char ip[16]);
/* Module parameters, defaults. */
static int pg_count_d __read_mostly = 1000;
static int pg_delay_d __read_mostly;
static int pg_clone_skb_d __read_mostly;
static int debug __read_mostly;
static DEFINE_MUTEX(pktgen_thread_lock);
static LIST_HEAD(pktgen_threads);
static struct notifier_block pktgen_notifier_block = {
.notifier_call = pktgen_device_event,
};
/*
* /proc handling functions
*
*/
static int pgctrl_show(struct seq_file *seq, void *v)
{
seq_puts(seq, version);
return 0;
}
static ssize_t pgctrl_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
int err = 0;
char data[128];
if (!capable(CAP_NET_ADMIN)) {
err = -EPERM;
goto out;
}
if (count > sizeof(data))
count = sizeof(data);
if (copy_from_user(data, buf, count)) {
err = -EFAULT;
goto out;
}
data[count - 1] = 0; /* Make string */
if (!strcmp(data, "stop"))
pktgen_stop_all_threads_ifs();
else if (!strcmp(data, "start"))
pktgen_run_all_threads();
else if (!strcmp(data, "reset"))
pktgen_reset_all_threads();
else
pr_warning("Unknown command: %s\n", data);
err = count;
out:
return err;
}
static int pgctrl_open(struct inode *inode, struct file *file)
{
return single_open(file, pgctrl_show, PDE(inode)->data);
}
static const struct file_operations pktgen_fops = {
.owner = THIS_MODULE,
.open = pgctrl_open,
.read = seq_read,
.llseek = seq_lseek,
.write = pgctrl_write,
.release = single_release,
};
static int pktgen_if_show(struct seq_file *seq, void *v)
{
const struct pktgen_dev *pkt_dev = seq->private;
ktime_t stopped;
u64 idle;
seq_printf(seq,
"Params: count %llu min_pkt_size: %u max_pkt_size: %u\n",
(unsigned long long)pkt_dev->count, pkt_dev->min_pkt_size,
pkt_dev->max_pkt_size);
seq_printf(seq,
" frags: %d delay: %llu clone_skb: %d ifname: %s\n",
pkt_dev->nfrags, (unsigned long long) pkt_dev->delay,
pkt_dev->clone_skb, pkt_dev->odevname);
seq_printf(seq, " flows: %u flowlen: %u\n", pkt_dev->cflows,
pkt_dev->lflow);
seq_printf(seq,
" queue_map_min: %u queue_map_max: %u\n",
pkt_dev->queue_map_min,
pkt_dev->queue_map_max);
if (pkt_dev->skb_priority)
seq_printf(seq, " skb_priority: %u\n",
pkt_dev->skb_priority);
if (pkt_dev->flags & F_IPV6) {
seq_printf(seq,
" saddr: %pI6c min_saddr: %pI6c max_saddr: %pI6c\n"
" daddr: %pI6c min_daddr: %pI6c max_daddr: %pI6c\n",
&pkt_dev->in6_saddr,
&pkt_dev->min_in6_saddr, &pkt_dev->max_in6_saddr,
&pkt_dev->in6_daddr,
&pkt_dev->min_in6_daddr, &pkt_dev->max_in6_daddr);
} else {
seq_printf(seq,
" dst_min: %s dst_max: %s\n",
pkt_dev->dst_min, pkt_dev->dst_max);
seq_printf(seq,
" src_min: %s src_max: %s\n",
pkt_dev->src_min, pkt_dev->src_max);
}
seq_puts(seq, " src_mac: ");
seq_printf(seq, "%pM ",
is_zero_ether_addr(pkt_dev->src_mac) ?
pkt_dev->odev->dev_addr : pkt_dev->src_mac);
seq_printf(seq, "dst_mac: ");
seq_printf(seq, "%pM\n", pkt_dev->dst_mac);
seq_printf(seq,
" udp_src_min: %d udp_src_max: %d"
" udp_dst_min: %d udp_dst_max: %d\n",
pkt_dev->udp_src_min, pkt_dev->udp_src_max,
pkt_dev->udp_dst_min, pkt_dev->udp_dst_max);
seq_printf(seq,
" src_mac_count: %d dst_mac_count: %d\n",
pkt_dev->src_mac_count, pkt_dev->dst_mac_count);
if (pkt_dev->nr_labels) {
unsigned i;
seq_printf(seq, " mpls: ");
for (i = 0; i < pkt_dev->nr_labels; i++)
seq_printf(seq, "%08x%s", ntohl(pkt_dev->labels[i]),
i == pkt_dev->nr_labels-1 ? "\n" : ", ");
}
if (pkt_dev->vlan_id != 0xffff)
seq_printf(seq, " vlan_id: %u vlan_p: %u vlan_cfi: %u\n",
pkt_dev->vlan_id, pkt_dev->vlan_p,
pkt_dev->vlan_cfi);
if (pkt_dev->svlan_id != 0xffff)
seq_printf(seq, " svlan_id: %u vlan_p: %u vlan_cfi: %u\n",
pkt_dev->svlan_id, pkt_dev->svlan_p,
pkt_dev->svlan_cfi);
if (pkt_dev->tos)
seq_printf(seq, " tos: 0x%02x\n", pkt_dev->tos);
if (pkt_dev->traffic_class)
seq_printf(seq, " traffic_class: 0x%02x\n", pkt_dev->traffic_class);
if (pkt_dev->node >= 0)
seq_printf(seq, " node: %d\n", pkt_dev->node);
seq_printf(seq, " Flags: ");
if (pkt_dev->flags & F_IPV6)
seq_printf(seq, "IPV6 ");
if (pkt_dev->flags & F_IPSRC_RND)
seq_printf(seq, "IPSRC_RND ");
if (pkt_dev->flags & F_IPDST_RND)
seq_printf(seq, "IPDST_RND ");
if (pkt_dev->flags & F_TXSIZE_RND)
seq_printf(seq, "TXSIZE_RND ");
if (pkt_dev->flags & F_UDPSRC_RND)
seq_printf(seq, "UDPSRC_RND ");
if (pkt_dev->flags & F_UDPDST_RND)
seq_printf(seq, "UDPDST_RND ");
if (pkt_dev->flags & F_MPLS_RND)
seq_printf(seq, "MPLS_RND ");
if (pkt_dev->flags & F_QUEUE_MAP_RND)
seq_printf(seq, "QUEUE_MAP_RND ");
if (pkt_dev->flags & F_QUEUE_MAP_CPU)
seq_printf(seq, "QUEUE_MAP_CPU ");
if (pkt_dev->cflows) {
if (pkt_dev->flags & F_FLOW_SEQ)
seq_printf(seq, "FLOW_SEQ "); /*in sequence flows*/
else
seq_printf(seq, "FLOW_RND ");
}
#ifdef CONFIG_XFRM
if (pkt_dev->flags & F_IPSEC_ON)
seq_printf(seq, "IPSEC ");
#endif
if (pkt_dev->flags & F_MACSRC_RND)
seq_printf(seq, "MACSRC_RND ");
if (pkt_dev->flags & F_MACDST_RND)
seq_printf(seq, "MACDST_RND ");
if (pkt_dev->flags & F_VID_RND)
seq_printf(seq, "VID_RND ");
if (pkt_dev->flags & F_SVID_RND)
seq_printf(seq, "SVID_RND ");
if (pkt_dev->flags & F_NODE)
seq_printf(seq, "NODE_ALLOC ");
seq_puts(seq, "\n");
/* not really stopped, more like last-running-at */
stopped = pkt_dev->running ? ktime_now() : pkt_dev->stopped_at;
idle = pkt_dev->idle_acc;
do_div(idle, NSEC_PER_USEC);
seq_printf(seq,
"Current:\n pkts-sofar: %llu errors: %llu\n",
(unsigned long long)pkt_dev->sofar,
(unsigned long long)pkt_dev->errors);
seq_printf(seq,
" started: %lluus stopped: %lluus idle: %lluus\n",
(unsigned long long) ktime_to_us(pkt_dev->started_at),
(unsigned long long) ktime_to_us(stopped),
(unsigned long long) idle);
seq_printf(seq,
" seq_num: %d cur_dst_mac_offset: %d cur_src_mac_offset: %d\n",
pkt_dev->seq_num, pkt_dev->cur_dst_mac_offset,
pkt_dev->cur_src_mac_offset);
if (pkt_dev->flags & F_IPV6) {
seq_printf(seq, " cur_saddr: %pI6c cur_daddr: %pI6c\n",
&pkt_dev->cur_in6_saddr,
&pkt_dev->cur_in6_daddr);
} else
seq_printf(seq, " cur_saddr: 0x%x cur_daddr: 0x%x\n",
pkt_dev->cur_saddr, pkt_dev->cur_daddr);
seq_printf(seq, " cur_udp_dst: %d cur_udp_src: %d\n",
pkt_dev->cur_udp_dst, pkt_dev->cur_udp_src);
seq_printf(seq, " cur_queue_map: %u\n", pkt_dev->cur_queue_map);
seq_printf(seq, " flows: %u\n", pkt_dev->nflows);
if (pkt_dev->result[0])
seq_printf(seq, "Result: %s\n", pkt_dev->result);
else
seq_printf(seq, "Result: Idle\n");
return 0;
}
static int hex32_arg(const char __user *user_buffer, unsigned long maxlen,
__u32 *num)
{
int i = 0;
*num = 0;
for (; i < maxlen; i++) {
int value;
char c;
*num <<= 4;
if (get_user(c, &user_buffer[i]))
return -EFAULT;
value = hex_to_bin(c);
if (value >= 0)
*num |= value;
else
break;
}
return i;
}
static int count_trail_chars(const char __user * user_buffer,
unsigned int maxlen)
{
int i;
for (i = 0; i < maxlen; i++) {
char c;
if (get_user(c, &user_buffer[i]))
return -EFAULT;
switch (c) {
case '\"':
case '\n':
case '\r':
case '\t':
case ' ':
case '=':
break;
default:
goto done;
}
}
done:
return i;
}
static unsigned long num_arg(const char __user * user_buffer,
unsigned long maxlen, unsigned long *num)
{
int i;
*num = 0;
for (i = 0; i < maxlen; i++) {
char c;
if (get_user(c, &user_buffer[i]))
return -EFAULT;
if ((c >= '0') && (c <= '9')) {
*num *= 10;
*num += c - '0';
} else
break;
}
return i;
}
static int strn_len(const char __user * user_buffer, unsigned int maxlen)
{
int i;
for (i = 0; i < maxlen; i++) {
char c;
if (get_user(c, &user_buffer[i]))
return -EFAULT;
switch (c) {
case '\"':
case '\n':
case '\r':
case '\t':
case ' ':
goto done_str;
break;
default:
break;
}
}
done_str:
return i;
}
static ssize_t get_labels(const char __user *buffer, struct pktgen_dev *pkt_dev)
{
unsigned n = 0;
char c;
ssize_t i = 0;
int len;
pkt_dev->nr_labels = 0;
do {
__u32 tmp;
len = hex32_arg(&buffer[i], 8, &tmp);
if (len <= 0)
return len;
pkt_dev->labels[n] = htonl(tmp);
if (pkt_dev->labels[n] & MPLS_STACK_BOTTOM)
pkt_dev->flags |= F_MPLS_RND;
i += len;
if (get_user(c, &buffer[i]))
return -EFAULT;
i++;
n++;
if (n >= MAX_MPLS_LABELS)
return -E2BIG;
} while (c == ',');
pkt_dev->nr_labels = n;
return i;
}
static ssize_t pktgen_if_write(struct file *file,
const char __user * user_buffer, size_t count,
loff_t * offset)
{
struct seq_file *seq = file->private_data;
struct pktgen_dev *pkt_dev = seq->private;
int i, max, len;
char name[16], valstr[32];
unsigned long value = 0;
char *pg_result = NULL;
int tmp = 0;
char buf[128];
pg_result = &(pkt_dev->result[0]);
if (count < 1) {
pr_warning("wrong command format\n");
return -EINVAL;
}
max = count;
tmp = count_trail_chars(user_buffer, max);
if (tmp < 0) {
pr_warning("illegal format\n");
return tmp;
}
i = tmp;
/* Read variable name */
len = strn_len(&user_buffer[i], sizeof(name) - 1);
if (len < 0)
return len;
memset(name, 0, sizeof(name));
if (copy_from_user(name, &user_buffer[i], len))
return -EFAULT;
i += len;
max = count - i;
len = count_trail_chars(&user_buffer[i], max);
if (len < 0)
return len;
i += len;
if (debug) {
size_t copy = min_t(size_t, count, 1023);
char tb[copy + 1];
if (copy_from_user(tb, user_buffer, copy))
return -EFAULT;
tb[copy] = 0;
printk(KERN_DEBUG "pktgen: %s,%lu buffer -:%s:-\n", name,
(unsigned long)count, tb);
}
if (!strcmp(name, "min_pkt_size")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value < 14 + 20 + 8)
value = 14 + 20 + 8;
if (value != pkt_dev->min_pkt_size) {
pkt_dev->min_pkt_size = value;
pkt_dev->cur_pkt_size = value;
}
sprintf(pg_result, "OK: min_pkt_size=%u",
pkt_dev->min_pkt_size);
return count;
}
if (!strcmp(name, "max_pkt_size")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value < 14 + 20 + 8)
value = 14 + 20 + 8;
if (value != pkt_dev->max_pkt_size) {
pkt_dev->max_pkt_size = value;
pkt_dev->cur_pkt_size = value;
}
sprintf(pg_result, "OK: max_pkt_size=%u",
pkt_dev->max_pkt_size);
return count;
}
/* Shortcut for min = max */
if (!strcmp(name, "pkt_size")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value < 14 + 20 + 8)
value = 14 + 20 + 8;
if (value != pkt_dev->min_pkt_size) {
pkt_dev->min_pkt_size = value;
pkt_dev->max_pkt_size = value;
pkt_dev->cur_pkt_size = value;
}
sprintf(pg_result, "OK: pkt_size=%u", pkt_dev->min_pkt_size);
return count;
}
if (!strcmp(name, "debug")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
debug = value;
sprintf(pg_result, "OK: debug=%u", debug);
return count;
}
if (!strcmp(name, "frags")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
pkt_dev->nfrags = value;
sprintf(pg_result, "OK: frags=%u", pkt_dev->nfrags);
return count;
}
if (!strcmp(name, "delay")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value == 0x7FFFFFFF)
pkt_dev->delay = ULLONG_MAX;
else
pkt_dev->delay = (u64)value;
sprintf(pg_result, "OK: delay=%llu",
(unsigned long long) pkt_dev->delay);
return count;
}
if (!strcmp(name, "rate")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (!value)
return len;
pkt_dev->delay = pkt_dev->min_pkt_size*8*NSEC_PER_USEC/value;
if (debug)
pr_info("Delay set at: %llu ns\n", pkt_dev->delay);
sprintf(pg_result, "OK: rate=%lu", value);
return count;
}
if (!strcmp(name, "ratep")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (!value)
return len;
pkt_dev->delay = NSEC_PER_SEC/value;
if (debug)
pr_info("Delay set at: %llu ns\n", pkt_dev->delay);
sprintf(pg_result, "OK: rate=%lu", value);
return count;
}
if (!strcmp(name, "udp_src_min")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value != pkt_dev->udp_src_min) {
pkt_dev->udp_src_min = value;
pkt_dev->cur_udp_src = value;
}
sprintf(pg_result, "OK: udp_src_min=%u", pkt_dev->udp_src_min);
return count;
}
if (!strcmp(name, "udp_dst_min")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value != pkt_dev->udp_dst_min) {
pkt_dev->udp_dst_min = value;
pkt_dev->cur_udp_dst = value;
}
sprintf(pg_result, "OK: udp_dst_min=%u", pkt_dev->udp_dst_min);
return count;
}
if (!strcmp(name, "udp_src_max")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value != pkt_dev->udp_src_max) {
pkt_dev->udp_src_max = value;
pkt_dev->cur_udp_src = value;
}
sprintf(pg_result, "OK: udp_src_max=%u", pkt_dev->udp_src_max);
return count;
}
if (!strcmp(name, "udp_dst_max")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value != pkt_dev->udp_dst_max) {
pkt_dev->udp_dst_max = value;
pkt_dev->cur_udp_dst = value;
}
sprintf(pg_result, "OK: udp_dst_max=%u", pkt_dev->udp_dst_max);
return count;
}
if (!strcmp(name, "clone_skb")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
if ((value > 0) &&
(!(pkt_dev->odev->priv_flags & IFF_TX_SKB_SHARING)))
return -ENOTSUPP;
i += len;
pkt_dev->clone_skb = value;
sprintf(pg_result, "OK: clone_skb=%d", pkt_dev->clone_skb);
return count;
}
if (!strcmp(name, "count")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
pkt_dev->count = value;
sprintf(pg_result, "OK: count=%llu",
(unsigned long long)pkt_dev->count);
return count;
}
if (!strcmp(name, "src_mac_count")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (pkt_dev->src_mac_count != value) {
pkt_dev->src_mac_count = value;
pkt_dev->cur_src_mac_offset = 0;
}
sprintf(pg_result, "OK: src_mac_count=%d",
pkt_dev->src_mac_count);
return count;
}
if (!strcmp(name, "dst_mac_count")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (pkt_dev->dst_mac_count != value) {
pkt_dev->dst_mac_count = value;
pkt_dev->cur_dst_mac_offset = 0;
}
sprintf(pg_result, "OK: dst_mac_count=%d",
pkt_dev->dst_mac_count);
return count;
}
if (!strcmp(name, "node")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (node_possible(value)) {
pkt_dev->node = value;
sprintf(pg_result, "OK: node=%d", pkt_dev->node);
if (pkt_dev->page) {
put_page(pkt_dev->page);
pkt_dev->page = NULL;
}
}
else
sprintf(pg_result, "ERROR: node not possible");
return count;
}
if (!strcmp(name, "flag")) {
char f[32];
memset(f, 0, 32);
len = strn_len(&user_buffer[i], sizeof(f) - 1);
if (len < 0)
return len;
if (copy_from_user(f, &user_buffer[i], len))
return -EFAULT;
i += len;
if (strcmp(f, "IPSRC_RND") == 0)
pkt_dev->flags |= F_IPSRC_RND;
else if (strcmp(f, "!IPSRC_RND") == 0)
pkt_dev->flags &= ~F_IPSRC_RND;
else if (strcmp(f, "TXSIZE_RND") == 0)
pkt_dev->flags |= F_TXSIZE_RND;
else if (strcmp(f, "!TXSIZE_RND") == 0)
pkt_dev->flags &= ~F_TXSIZE_RND;
else if (strcmp(f, "IPDST_RND") == 0)
pkt_dev->flags |= F_IPDST_RND;
else if (strcmp(f, "!IPDST_RND") == 0)
pkt_dev->flags &= ~F_IPDST_RND;
else if (strcmp(f, "UDPSRC_RND") == 0)
pkt_dev->flags |= F_UDPSRC_RND;
else if (strcmp(f, "!UDPSRC_RND") == 0)
pkt_dev->flags &= ~F_UDPSRC_RND;
else if (strcmp(f, "UDPDST_RND") == 0)
pkt_dev->flags |= F_UDPDST_RND;
else if (strcmp(f, "!UDPDST_RND") == 0)
pkt_dev->flags &= ~F_UDPDST_RND;
else if (strcmp(f, "MACSRC_RND") == 0)
pkt_dev->flags |= F_MACSRC_RND;
else if (strcmp(f, "!MACSRC_RND") == 0)
pkt_dev->flags &= ~F_MACSRC_RND;
else if (strcmp(f, "MACDST_RND") == 0)
pkt_dev->flags |= F_MACDST_RND;
else if (strcmp(f, "!MACDST_RND") == 0)
pkt_dev->flags &= ~F_MACDST_RND;
else if (strcmp(f, "MPLS_RND") == 0)
pkt_dev->flags |= F_MPLS_RND;
else if (strcmp(f, "!MPLS_RND") == 0)
pkt_dev->flags &= ~F_MPLS_RND;
else if (strcmp(f, "VID_RND") == 0)
pkt_dev->flags |= F_VID_RND;
else if (strcmp(f, "!VID_RND") == 0)
pkt_dev->flags &= ~F_VID_RND;
else if (strcmp(f, "SVID_RND") == 0)
pkt_dev->flags |= F_SVID_RND;
else if (strcmp(f, "!SVID_RND") == 0)
pkt_dev->flags &= ~F_SVID_RND;
else if (strcmp(f, "FLOW_SEQ") == 0)
pkt_dev->flags |= F_FLOW_SEQ;
else if (strcmp(f, "QUEUE_MAP_RND") == 0)
pkt_dev->flags |= F_QUEUE_MAP_RND;
else if (strcmp(f, "!QUEUE_MAP_RND") == 0)
pkt_dev->flags &= ~F_QUEUE_MAP_RND;
else if (strcmp(f, "QUEUE_MAP_CPU") == 0)
pkt_dev->flags |= F_QUEUE_MAP_CPU;
else if (strcmp(f, "!QUEUE_MAP_CPU") == 0)
pkt_dev->flags &= ~F_QUEUE_MAP_CPU;
#ifdef CONFIG_XFRM
else if (strcmp(f, "IPSEC") == 0)
pkt_dev->flags |= F_IPSEC_ON;
#endif
else if (strcmp(f, "!IPV6") == 0)
pkt_dev->flags &= ~F_IPV6;
else if (strcmp(f, "NODE_ALLOC") == 0)
pkt_dev->flags |= F_NODE;
else if (strcmp(f, "!NODE_ALLOC") == 0)
pkt_dev->flags &= ~F_NODE;
else {
sprintf(pg_result,
"Flag -:%s:- unknown\nAvailable flags, (prepend ! to un-set flag):\n%s",
f,
"IPSRC_RND, IPDST_RND, UDPSRC_RND, UDPDST_RND, "
"MACSRC_RND, MACDST_RND, TXSIZE_RND, IPV6, MPLS_RND, VID_RND, SVID_RND, FLOW_SEQ, IPSEC, NODE_ALLOC\n");
return count;
}
sprintf(pg_result, "OK: flags=0x%x", pkt_dev->flags);
return count;
}
if (!strcmp(name, "dst_min") || !strcmp(name, "dst")) {
len = strn_len(&user_buffer[i], sizeof(pkt_dev->dst_min) - 1);
if (len < 0)
return len;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
if (strcmp(buf, pkt_dev->dst_min) != 0) {
memset(pkt_dev->dst_min, 0, sizeof(pkt_dev->dst_min));
strncpy(pkt_dev->dst_min, buf, len);
pkt_dev->daddr_min = in_aton(pkt_dev->dst_min);
pkt_dev->cur_daddr = pkt_dev->daddr_min;
}
if (debug)
printk(KERN_DEBUG "pktgen: dst_min set to: %s\n",
pkt_dev->dst_min);
i += len;
sprintf(pg_result, "OK: dst_min=%s", pkt_dev->dst_min);
return count;
}
if (!strcmp(name, "dst_max")) {
len = strn_len(&user_buffer[i], sizeof(pkt_dev->dst_max) - 1);
if (len < 0)
return len;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
if (strcmp(buf, pkt_dev->dst_max) != 0) {
memset(pkt_dev->dst_max, 0, sizeof(pkt_dev->dst_max));
strncpy(pkt_dev->dst_max, buf, len);
pkt_dev->daddr_max = in_aton(pkt_dev->dst_max);
pkt_dev->cur_daddr = pkt_dev->daddr_max;
}
if (debug)
printk(KERN_DEBUG "pktgen: dst_max set to: %s\n",
pkt_dev->dst_max);
i += len;
sprintf(pg_result, "OK: dst_max=%s", pkt_dev->dst_max);
return count;
}
if (!strcmp(name, "dst6")) {
len = strn_len(&user_buffer[i], sizeof(buf) - 1);
if (len < 0)
return len;
pkt_dev->flags |= F_IPV6;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
scan_ip6(buf, pkt_dev->in6_daddr.s6_addr);
snprintf(buf, sizeof(buf), "%pI6c", &pkt_dev->in6_daddr);
ipv6_addr_copy(&pkt_dev->cur_in6_daddr, &pkt_dev->in6_daddr);
if (debug)
printk(KERN_DEBUG "pktgen: dst6 set to: %s\n", buf);
i += len;
sprintf(pg_result, "OK: dst6=%s", buf);
return count;
}
if (!strcmp(name, "dst6_min")) {
len = strn_len(&user_buffer[i], sizeof(buf) - 1);
if (len < 0)
return len;
pkt_dev->flags |= F_IPV6;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
scan_ip6(buf, pkt_dev->min_in6_daddr.s6_addr);
snprintf(buf, sizeof(buf), "%pI6c", &pkt_dev->min_in6_daddr);
ipv6_addr_copy(&pkt_dev->cur_in6_daddr,
&pkt_dev->min_in6_daddr);
if (debug)
printk(KERN_DEBUG "pktgen: dst6_min set to: %s\n", buf);
i += len;
sprintf(pg_result, "OK: dst6_min=%s", buf);
return count;
}
if (!strcmp(name, "dst6_max")) {
len = strn_len(&user_buffer[i], sizeof(buf) - 1);
if (len < 0)
return len;
pkt_dev->flags |= F_IPV6;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
scan_ip6(buf, pkt_dev->max_in6_daddr.s6_addr);
snprintf(buf, sizeof(buf), "%pI6c", &pkt_dev->max_in6_daddr);
if (debug)
printk(KERN_DEBUG "pktgen: dst6_max set to: %s\n", buf);
i += len;
sprintf(pg_result, "OK: dst6_max=%s", buf);
return count;
}
if (!strcmp(name, "src6")) {
len = strn_len(&user_buffer[i], sizeof(buf) - 1);
if (len < 0)
return len;
pkt_dev->flags |= F_IPV6;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
scan_ip6(buf, pkt_dev->in6_saddr.s6_addr);
snprintf(buf, sizeof(buf), "%pI6c", &pkt_dev->in6_saddr);
ipv6_addr_copy(&pkt_dev->cur_in6_saddr, &pkt_dev->in6_saddr);
if (debug)
printk(KERN_DEBUG "pktgen: src6 set to: %s\n", buf);
i += len;
sprintf(pg_result, "OK: src6=%s", buf);
return count;
}
if (!strcmp(name, "src_min")) {
len = strn_len(&user_buffer[i], sizeof(pkt_dev->src_min) - 1);
if (len < 0)
return len;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
if (strcmp(buf, pkt_dev->src_min) != 0) {
memset(pkt_dev->src_min, 0, sizeof(pkt_dev->src_min));
strncpy(pkt_dev->src_min, buf, len);
pkt_dev->saddr_min = in_aton(pkt_dev->src_min);
pkt_dev->cur_saddr = pkt_dev->saddr_min;
}
if (debug)
printk(KERN_DEBUG "pktgen: src_min set to: %s\n",
pkt_dev->src_min);
i += len;
sprintf(pg_result, "OK: src_min=%s", pkt_dev->src_min);
return count;
}
if (!strcmp(name, "src_max")) {
len = strn_len(&user_buffer[i], sizeof(pkt_dev->src_max) - 1);
if (len < 0)
return len;
if (copy_from_user(buf, &user_buffer[i], len))
return -EFAULT;
buf[len] = 0;
if (strcmp(buf, pkt_dev->src_max) != 0) {
memset(pkt_dev->src_max, 0, sizeof(pkt_dev->src_max));
strncpy(pkt_dev->src_max, buf, len);
pkt_dev->saddr_max = in_aton(pkt_dev->src_max);
pkt_dev->cur_saddr = pkt_dev->saddr_max;
}
if (debug)
printk(KERN_DEBUG "pktgen: src_max set to: %s\n",
pkt_dev->src_max);
i += len;
sprintf(pg_result, "OK: src_max=%s", pkt_dev->src_max);
return count;
}
if (!strcmp(name, "dst_mac")) {
len = strn_len(&user_buffer[i], sizeof(valstr) - 1);
if (len < 0)
return len;
memset(valstr, 0, sizeof(valstr));
if (copy_from_user(valstr, &user_buffer[i], len))
return -EFAULT;
if (!mac_pton(valstr, pkt_dev->dst_mac))
return -EINVAL;
/* Set up Dest MAC */
memcpy(&pkt_dev->hh[0], pkt_dev->dst_mac, ETH_ALEN);
sprintf(pg_result, "OK: dstmac %pM", pkt_dev->dst_mac);
return count;
}
if (!strcmp(name, "src_mac")) {
len = strn_len(&user_buffer[i], sizeof(valstr) - 1);
if (len < 0)
return len;
memset(valstr, 0, sizeof(valstr));
if (copy_from_user(valstr, &user_buffer[i], len))
return -EFAULT;
if (!mac_pton(valstr, pkt_dev->src_mac))
return -EINVAL;
/* Set up Src MAC */
memcpy(&pkt_dev->hh[6], pkt_dev->src_mac, ETH_ALEN);
sprintf(pg_result, "OK: srcmac %pM", pkt_dev->src_mac);
return count;
}
if (!strcmp(name, "clear_counters")) {
pktgen_clear_counters(pkt_dev);
sprintf(pg_result, "OK: Clearing counters.\n");
return count;
}
if (!strcmp(name, "flows")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
if (value > MAX_CFLOWS)
value = MAX_CFLOWS;
pkt_dev->cflows = value;
sprintf(pg_result, "OK: flows=%u", pkt_dev->cflows);
return count;
}
if (!strcmp(name, "flowlen")) {
len = num_arg(&user_buffer[i], 10, &value);
if (len < 0)
return len;
i += len;
pkt_dev->lflow = value;
sprintf(pg_result, "OK: flowlen=%u", pkt_dev->lflow);
return count;
}
if (!strcmp(name, "queue_map_min")) {
len = num_arg(&user_buffer[i], 5, &value);
if (len < 0)
return len;
i += len;
pkt_dev->queue_map_min = value;
sprintf(pg_result, "OK: queue_map_min=%u", pkt_dev->queue_map_min);
return count;
}
if (!strcmp(name, "queue_map_max")) {
len = num_arg(&user_buffer[i], 5, &value);
if (len < 0)
return len;
i += len;
pkt_dev->queue_map_max = value;
sprintf(pg_result, "OK: queue_map_max=%u", pkt_dev->queue_map_max);
return count;
}
if (!strcmp(name, "mpls")) {
unsigned n, cnt;
len = get_labels(&user_buffer[i], pkt_dev);
if (len < 0)
return len;
i += len;
cnt = sprintf(pg_result, "OK: mpls=");
for (n = 0; n < pkt_dev->nr_labels; n++)
cnt += sprintf(pg_result + cnt,
"%08x%s", ntohl(pkt_dev->labels[n]),
n == pkt_dev->nr_labels-1 ? "" : ",");
if (pkt_dev->nr_labels && pkt_dev->vlan_id != 0xffff) {
pkt_dev->vlan_id = 0xffff; /* turn off VLAN/SVLAN */
pkt_dev->svlan_id = 0xffff;
if (debug)
printk(KERN_DEBUG "pktgen: VLAN/SVLAN auto turned off\n");
}
return count;
}
if (!strcmp(name, "vlan_id")) {
len = num_arg(&user_buffer[i], 4, &value);
if (len < 0)
return len;
i += len;
if (value <= 4095) {
pkt_dev->vlan_id = value; /* turn on VLAN */
if (debug)
printk(KERN_DEBUG "pktgen: VLAN turned on\n");
if (debug && pkt_dev->nr_labels)
printk(KERN_DEBUG "pktgen: MPLS auto turned off\n");
pkt_dev->nr_labels = 0; /* turn off MPLS */
sprintf(pg_result, "OK: vlan_id=%u", pkt_dev->vlan_id);
} else {
pkt_dev->vlan_id = 0xffff; /* turn off VLAN/SVLAN */
pkt_dev->svlan_id = 0xffff;
if (debug)
printk(KERN_DEBUG "pktgen: VLAN/SVLAN turned off\n");
}
return count;
}
if (!strcmp(name, "vlan_p")) {
len = num_arg(&user_buffer[i], 1, &value);
if (len < 0)
return len;
i += len;
if ((value <= 7) && (pkt_dev->vlan_id != 0xffff)) {
pkt_dev->vlan_p = value;
sprintf(pg_result, "OK: vlan_p=%u", pkt_dev->vlan_p);
} else {
sprintf(pg_result, "ERROR: vlan_p must be 0-7");
}
return count;
}
if (!strcmp(name, "vlan_cfi")) {
len = num_arg(&user_buffer[i], 1, &value);
if (len < 0)
return len;
i += len;
if ((value <= 1) && (pkt_dev->vlan_id != 0xffff)) {
pkt_dev->vlan_cfi = value;
sprintf(pg_result, "OK: vlan_cfi=%u", pkt_dev->vlan_cfi);
} else {
sprintf(pg_result, "ERROR: vlan_cfi must be 0-1");
}
return count;
}
if (!strcmp(name, "svlan_id")) {
len = num_arg(&user_buffer[i], 4, &value);
if (len < 0)
return len;
i += len;
if ((value <= 4095) && ((pkt_dev->vlan_id != 0xffff))) {
pkt_dev->svlan_id = value; /* turn on SVLAN */
if (debug)
printk(KERN_DEBUG "pktgen: SVLAN turned on\n");
if (debug && pkt_dev->nr_labels)
printk(KERN_DEBUG "pktgen: MPLS auto turned off\n");
pkt_dev->nr_labels = 0; /* turn off MPLS */
sprintf(pg_result, "OK: svlan_id=%u", pkt_dev->svlan_id);
} else {
pkt_dev->vlan_id = 0xffff; /* turn off VLAN/SVLAN */
pkt_dev->svlan_id = 0xffff;
if (debug)
printk(KERN_DEBUG "pktgen: VLAN/SVLAN turned off\n");
}
return count;
}
if (!strcmp(name, "svlan_p")) {
len = num_arg(&user_buffer[i], 1, &value);
if (len < 0)
return len;
i += len;
if ((value <= 7) && (pkt_dev->svlan_id != 0xffff)) {
pkt_dev->svlan_p = value;
sprintf(pg_result, "OK: svlan_p=%u", pkt_dev->svlan_p);
} else {
sprintf(pg_result, "ERROR: svlan_p must be 0-7");
}
return count;
}
if (!strcmp(name, "svlan_cfi")) {
len = num_arg(&user_buffer[i], 1, &value);
if (len < 0)
return len;
i += len;
if ((value <= 1) && (pkt_dev->svlan_id != 0xffff)) {
pkt_dev->svlan_cfi = value;
sprintf(pg_result, "OK: svlan_cfi=%u", pkt_dev->svlan_cfi);
} else {
sprintf(pg_result, "ERROR: svlan_cfi must be 0-1");
}
return count;
}
if (!strcmp(name, "tos")) {
__u32 tmp_value = 0;
len = hex32_arg(&user_buffer[i], 2, &tmp_value);
if (len < 0)
return len;
i += len;
if (len == 2) {
pkt_dev->tos = tmp_value;
sprintf(pg_result, "OK: tos=0x%02x", pkt_dev->tos);
} else {
sprintf(pg_result, "ERROR: tos must be 00-ff");
}
return count;
}
if (!strcmp(name, "traffic_class")) {
__u32 tmp_value = 0;
len = hex32_arg(&user_buffer[i], 2, &tmp_value);
if (len < 0)
return len;
i += len;
if (len == 2) {
pkt_dev->traffic_class = tmp_value;
sprintf(pg_result, "OK: traffic_class=0x%02x", pkt_dev->traffic_class);
} else {
sprintf(pg_result, "ERROR: traffic_class must be 00-ff");
}
return count;
}
if (!strcmp(name, "skb_priority")) {
len = num_arg(&user_buffer[i], 9, &value);
if (len < 0)
return len;
i += len;
pkt_dev->skb_priority = value;
sprintf(pg_result, "OK: skb_priority=%i",
pkt_dev->skb_priority);
return count;
}
sprintf(pkt_dev->result, "No such parameter \"%s\"", name);
return -EINVAL;
}
static int pktgen_if_open(struct inode *inode, struct file *file)
{
return single_open(file, pktgen_if_show, PDE(inode)->data);
}
static const struct file_operations pktgen_if_fops = {
.owner = THIS_MODULE,
.open = pktgen_if_open,
.read = seq_read,
.llseek = seq_lseek,
.write = pktgen_if_write,
.release = single_release,
};
static int pktgen_thread_show(struct seq_file *seq, void *v)
{
struct pktgen_thread *t = seq->private;
const struct pktgen_dev *pkt_dev;
BUG_ON(!t);
seq_printf(seq, "Running: ");
if_lock(t);
list_for_each_entry(pkt_dev, &t->if_list, list)
if (pkt_dev->running)
seq_printf(seq, "%s ", pkt_dev->odevname);
seq_printf(seq, "\nStopped: ");
list_for_each_entry(pkt_dev, &t->if_list, list)
if (!pkt_dev->running)
seq_printf(seq, "%s ", pkt_dev->odevname);
if (t->result[0])
seq_printf(seq, "\nResult: %s\n", t->result);
else
seq_printf(seq, "\nResult: NA\n");
if_unlock(t);
return 0;
}
static ssize_t pktgen_thread_write(struct file *file,
const char __user * user_buffer,
size_t count, loff_t * offset)
{
struct seq_file *seq = file->private_data;
struct pktgen_thread *t = seq->private;
int i, max, len, ret;
char name[40];
char *pg_result;
if (count < 1) {
// sprintf(pg_result, "Wrong command format");
return -EINVAL;
}
max = count;
len = count_trail_chars(user_buffer, max);
if (len < 0)
return len;
i = len;
/* Read variable name */
len = strn_len(&user_buffer[i], sizeof(name) - 1);
if (len < 0)
return len;
memset(name, 0, sizeof(name));
if (copy_from_user(name, &user_buffer[i], len))
return -EFAULT;
i += len;
max = count - i;
len = count_trail_chars(&user_buffer[i], max);
if (len < 0)
return len;
i += len;
if (debug)
printk(KERN_DEBUG "pktgen: t=%s, count=%lu\n",
name, (unsigned long)count);
if (!t) {
pr_err("ERROR: No thread\n");
ret = -EINVAL;
goto out;
}
pg_result = &(t->result[0]);
if (!strcmp(name, "add_device")) {
char f[32];
memset(f, 0, 32);
len = strn_len(&user_buffer[i], sizeof(f) - 1);
if (len < 0) {
ret = len;
goto out;
}
if (copy_from_user(f, &user_buffer[i], len))
return -EFAULT;
i += len;
mutex_lock(&pktgen_thread_lock);
ret = pktgen_add_device(t, f);
mutex_unlock(&pktgen_thread_lock);
if (!ret) {
ret = count;
sprintf(pg_result, "OK: add_device=%s", f);
} else
sprintf(pg_result, "ERROR: can not add device %s", f);
goto out;
}
if (!strcmp(name, "rem_device_all")) {
mutex_lock(&pktgen_thread_lock);
t->control |= T_REMDEVALL;
mutex_unlock(&pktgen_thread_lock);
schedule_timeout_interruptible(msecs_to_jiffies(125)); /* Propagate thread->control */
ret = count;
sprintf(pg_result, "OK: rem_device_all");
goto out;
}
if (!strcmp(name, "max_before_softirq")) {
sprintf(pg_result, "OK: Note! max_before_softirq is obsoleted -- Do not use");
ret = count;
goto out;
}
ret = -EINVAL;
out:
return ret;
}
static int pktgen_thread_open(struct inode *inode, struct file *file)
{
return single_open(file, pktgen_thread_show, PDE(inode)->data);
}
static const struct file_operations pktgen_thread_fops = {
.owner = THIS_MODULE,
.open = pktgen_thread_open,
.read = seq_read,
.llseek = seq_lseek,
.write = pktgen_thread_write,
.release = single_release,
};
/* Think find or remove for NN */
static struct pktgen_dev *__pktgen_NN_threads(const char *ifname, int remove)
{
struct pktgen_thread *t;
struct pktgen_dev *pkt_dev = NULL;
bool exact = (remove == FIND);
list_for_each_entry(t, &pktgen_threads, th_list) {
pkt_dev = pktgen_find_dev(t, ifname, exact);
if (pkt_dev) {
if (remove) {
if_lock(t);
pkt_dev->removal_mark = 1;
t->control |= T_REMDEV;
if_unlock(t);
}
break;
}
}
return pkt_dev;
}
/*
* mark a device for removal
*/
static void pktgen_mark_device(const char *ifname)
{
struct pktgen_dev *pkt_dev = NULL;
const int max_tries = 10, msec_per_try = 125;
int i = 0;
mutex_lock(&pktgen_thread_lock);
pr_debug("%s: marking %s for removal\n", __func__, ifname);
while (1) {
pkt_dev = __pktgen_NN_threads(ifname, REMOVE);
if (pkt_dev == NULL)
break; /* success */
mutex_unlock(&pktgen_thread_lock);
pr_debug("%s: waiting for %s to disappear....\n",
__func__, ifname);
schedule_timeout_interruptible(msecs_to_jiffies(msec_per_try));
mutex_lock(&pktgen_thread_lock);
if (++i >= max_tries) {
pr_err("%s: timed out after waiting %d msec for device %s to be removed\n",
__func__, msec_per_try * i, ifname);
break;
}
}
mutex_unlock(&pktgen_thread_lock);
}
static void pktgen_change_name(struct net_device *dev)
{
struct pktgen_thread *t;
list_for_each_entry(t, &pktgen_threads, th_list) {
struct pktgen_dev *pkt_dev;
list_for_each_entry(pkt_dev, &t->if_list, list) {
if (pkt_dev->odev != dev)
continue;
remove_proc_entry(pkt_dev->entry->name, pg_proc_dir);
pkt_dev->entry = proc_create_data(dev->name, 0600,
pg_proc_dir,
&pktgen_if_fops,
pkt_dev);
if (!pkt_dev->entry)
pr_err("can't move proc entry for '%s'\n",
dev->name);
break;
}
}
}
static int pktgen_device_event(struct notifier_block *unused,
unsigned long event, void *ptr)
{
struct net_device *dev = ptr;
if (!net_eq(dev_net(dev), &init_net) || pktgen_exiting)
return NOTIFY_DONE;
/* It is OK that we do not hold the group lock right now,
* as we run under the RTNL lock.
*/
switch (event) {
case NETDEV_CHANGENAME:
pktgen_change_name(dev);
break;
case NETDEV_UNREGISTER:
pktgen_mark_device(dev->name);
break;
}
return NOTIFY_DONE;
}
static struct net_device *pktgen_dev_get_by_name(struct pktgen_dev *pkt_dev,
const char *ifname)
{
char b[IFNAMSIZ+5];
int i;
for (i = 0; ifname[i] != '@'; i++) {
if (i == IFNAMSIZ)
break;
b[i] = ifname[i];
}
b[i] = 0;
return dev_get_by_name(&init_net, b);
}
/* Associate pktgen_dev with a device. */
static int pktgen_setup_dev(struct pktgen_dev *pkt_dev, const char *ifname)
{
struct net_device *odev;
int err;
/* Clean old setups */
if (pkt_dev->odev) {
dev_put(pkt_dev->odev);
pkt_dev->odev = NULL;
}
odev = pktgen_dev_get_by_name(pkt_dev, ifname);
if (!odev) {
pr_err("no such netdevice: \"%s\"\n", ifname);
return -ENODEV;
}
if (odev->type != ARPHRD_ETHER) {
pr_err("not an ethernet device: \"%s\"\n", ifname);
err = -EINVAL;
} else if (!netif_running(odev)) {
pr_err("device is down: \"%s\"\n", ifname);
err = -ENETDOWN;
} else {
pkt_dev->odev = odev;
return 0;
}
dev_put(odev);
return err;
}
/* Read pkt_dev from the interface and set up internal pktgen_dev
* structure to have the right information to create/send packets
*/
static void pktgen_setup_inject(struct pktgen_dev *pkt_dev)
{
int ntxq;
if (!pkt_dev->odev) {
pr_err("ERROR: pkt_dev->odev == NULL in setup_inject\n");
sprintf(pkt_dev->result,
"ERROR: pkt_dev->odev == NULL in setup_inject.\n");
return;
}
/* make sure that we don't pick a non-existing transmit queue */
ntxq = pkt_dev->odev->real_num_tx_queues;
if (ntxq <= pkt_dev->queue_map_min) {
pr_warning("WARNING: Requested queue_map_min (zero-based) (%d) exceeds valid range [0 - %d] for (%d) queues on %s, resetting\n",
pkt_dev->queue_map_min, (ntxq ?: 1) - 1, ntxq,
pkt_dev->odevname);
pkt_dev->queue_map_min = ntxq - 1;
}
if (pkt_dev->queue_map_max >= ntxq) {
pr_warning("WARNING: Requested queue_map_max (zero-based) (%d) exceeds valid range [0 - %d] for (%d) queues on %s, resetting\n",
pkt_dev->queue_map_max, (ntxq ?: 1) - 1, ntxq,
pkt_dev->odevname);
pkt_dev->queue_map_max = ntxq - 1;
}
/* Default to the interface's mac if not explicitly set. */
if (is_zero_ether_addr(pkt_dev->src_mac))
memcpy(&(pkt_dev->hh[6]), pkt_dev->odev->dev_addr, ETH_ALEN);
/* Set up Dest MAC */
memcpy(&(pkt_dev->hh[0]), pkt_dev->dst_mac, ETH_ALEN);
/* Set up pkt size */
pkt_dev->cur_pkt_size = pkt_dev->min_pkt_size;
if (pkt_dev->flags & F_IPV6) {
/*
* Skip this automatic address setting until locks or functions
* gets exported
*/
#ifdef NOTNOW
int i, set = 0, err = 1;
struct inet6_dev *idev;
for (i = 0; i < IN6_ADDR_HSIZE; i++)
if (pkt_dev->cur_in6_saddr.s6_addr[i]) {
set = 1;
break;
}
if (!set) {
/*
* Use linklevel address if unconfigured.
*
* use ipv6_get_lladdr if/when it's get exported
*/
rcu_read_lock();
idev = __in6_dev_get(pkt_dev->odev);
if (idev) {
struct inet6_ifaddr *ifp;
read_lock_bh(&idev->lock);
for (ifp = idev->addr_list; ifp;
ifp = ifp->if_next) {
if (ifp->scope == IFA_LINK &&
!(ifp->flags & IFA_F_TENTATIVE)) {
ipv6_addr_copy(&pkt_dev->
cur_in6_saddr,
&ifp->addr);
err = 0;
break;
}
}
read_unlock_bh(&idev->lock);
}
rcu_read_unlock();
if (err)
pr_err("ERROR: IPv6 link address not available\n");
}
#endif
} else {
pkt_dev->saddr_min = 0;
pkt_dev->saddr_max = 0;
if (strlen(pkt_dev->src_min) == 0) {
struct in_device *in_dev;
rcu_read_lock();
in_dev = __in_dev_get_rcu(pkt_dev->odev);
if (in_dev) {
if (in_dev->ifa_list) {
pkt_dev->saddr_min =
in_dev->ifa_list->ifa_address;
pkt_dev->saddr_max = pkt_dev->saddr_min;
}
}
rcu_read_unlock();
} else {
pkt_dev->saddr_min = in_aton(pkt_dev->src_min);
pkt_dev->saddr_max = in_aton(pkt_dev->src_max);
}
pkt_dev->daddr_min = in_aton(pkt_dev->dst_min);
pkt_dev->daddr_max = in_aton(pkt_dev->dst_max);
}
/* Initialize current values. */
pkt_dev->cur_dst_mac_offset = 0;
pkt_dev->cur_src_mac_offset = 0;
pkt_dev->cur_saddr = pkt_dev->saddr_min;
pkt_dev->cur_daddr = pkt_dev->daddr_min;
pkt_dev->cur_udp_dst = pkt_dev->udp_dst_min;
pkt_dev->cur_udp_src = pkt_dev->udp_src_min;
pkt_dev->nflows = 0;
}
static void spin(struct pktgen_dev *pkt_dev, ktime_t spin_until)
{
ktime_t start_time, end_time;
s64 remaining;
struct hrtimer_sleeper t;
hrtimer_init_on_stack(&t.timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
hrtimer_set_expires(&t.timer, spin_until);
remaining = ktime_to_ns(hrtimer_expires_remaining(&t.timer));
if (remaining <= 0) {
pkt_dev->next_tx = ktime_add_ns(spin_until, pkt_dev->delay);
return;
}
start_time = ktime_now();
if (remaining < 100000)
ndelay(remaining); /* really small just spin */
else {
/* see do_nanosleep */
hrtimer_init_sleeper(&t, current);
do {
set_current_state(TASK_INTERRUPTIBLE);
hrtimer_start_expires(&t.timer, HRTIMER_MODE_ABS);
if (!hrtimer_active(&t.timer))
t.task = NULL;
if (likely(t.task))
schedule();
hrtimer_cancel(&t.timer);
} while (t.task && pkt_dev->running && !signal_pending(current));
__set_current_state(TASK_RUNNING);
}
end_time = ktime_now();
pkt_dev->idle_acc += ktime_to_ns(ktime_sub(end_time, start_time));
pkt_dev->next_tx = ktime_add_ns(spin_until, pkt_dev->delay);
}
static inline void set_pkt_overhead(struct pktgen_dev *pkt_dev)
{
pkt_dev->pkt_overhead = 0;
pkt_dev->pkt_overhead += pkt_dev->nr_labels*sizeof(u32);
pkt_dev->pkt_overhead += VLAN_TAG_SIZE(pkt_dev);
pkt_dev->pkt_overhead += SVLAN_TAG_SIZE(pkt_dev);
}
static inline int f_seen(const struct pktgen_dev *pkt_dev, int flow)
{
return !!(pkt_dev->flows[flow].flags & F_INIT);
}
static inline int f_pick(struct pktgen_dev *pkt_dev)
{
int flow = pkt_dev->curfl;
if (pkt_dev->flags & F_FLOW_SEQ) {
if (pkt_dev->flows[flow].count >= pkt_dev->lflow) {
/* reset time */
pkt_dev->flows[flow].count = 0;
pkt_dev->flows[flow].flags = 0;
pkt_dev->curfl += 1;
if (pkt_dev->curfl >= pkt_dev->cflows)
pkt_dev->curfl = 0; /*reset */
}
} else {
flow = random32() % pkt_dev->cflows;
pkt_dev->curfl = flow;
if (pkt_dev->flows[flow].count > pkt_dev->lflow) {
pkt_dev->flows[flow].count = 0;
pkt_dev->flows[flow].flags = 0;
}
}
return pkt_dev->curfl;
}
#ifdef CONFIG_XFRM
/* If there was already an IPSEC SA, we keep it as is, else
* we go look for it ...
*/
#define DUMMY_MARK 0
static void get_ipsec_sa(struct pktgen_dev *pkt_dev, int flow)
{
struct xfrm_state *x = pkt_dev->flows[flow].x;
if (!x) {
/*slow path: we dont already have xfrm_state*/
x = xfrm_stateonly_find(&init_net, DUMMY_MARK,
(xfrm_address_t *)&pkt_dev->cur_daddr,
(xfrm_address_t *)&pkt_dev->cur_saddr,
AF_INET,
pkt_dev->ipsmode,
pkt_dev->ipsproto, 0);
if (x) {
pkt_dev->flows[flow].x = x;
set_pkt_overhead(pkt_dev);
pkt_dev->pkt_overhead += x->props.header_len;
}
}
}
#endif
static void set_cur_queue_map(struct pktgen_dev *pkt_dev)
{
if (pkt_dev->flags & F_QUEUE_MAP_CPU)
pkt_dev->cur_queue_map = smp_processor_id();
else if (pkt_dev->queue_map_min <= pkt_dev->queue_map_max) {
__u16 t;
if (pkt_dev->flags & F_QUEUE_MAP_RND) {
t = random32() %
(pkt_dev->queue_map_max -
pkt_dev->queue_map_min + 1)
+ pkt_dev->queue_map_min;
} else {
t = pkt_dev->cur_queue_map + 1;
if (t > pkt_dev->queue_map_max)
t = pkt_dev->queue_map_min;
}
pkt_dev->cur_queue_map = t;
}
pkt_dev->cur_queue_map = pkt_dev->cur_queue_map % pkt_dev->odev->real_num_tx_queues;
}
/* Increment/randomize headers according to flags and current values
* for IP src/dest, UDP src/dst port, MAC-Addr src/dst
*/
static void mod_cur_headers(struct pktgen_dev *pkt_dev)
{
__u32 imn;
__u32 imx;
int flow = 0;
if (pkt_dev->cflows)
flow = f_pick(pkt_dev);
/* Deal with source MAC */
if (pkt_dev->src_mac_count > 1) {
__u32 mc;
__u32 tmp;
if (pkt_dev->flags & F_MACSRC_RND)
mc = random32() % pkt_dev->src_mac_count;
else {
mc = pkt_dev->cur_src_mac_offset++;
if (pkt_dev->cur_src_mac_offset >=
pkt_dev->src_mac_count)
pkt_dev->cur_src_mac_offset = 0;
}
tmp = pkt_dev->src_mac[5] + (mc & 0xFF);
pkt_dev->hh[11] = tmp;
tmp = (pkt_dev->src_mac[4] + ((mc >> 8) & 0xFF) + (tmp >> 8));
pkt_dev->hh[10] = tmp;
tmp = (pkt_dev->src_mac[3] + ((mc >> 16) & 0xFF) + (tmp >> 8));
pkt_dev->hh[9] = tmp;
tmp = (pkt_dev->src_mac[2] + ((mc >> 24) & 0xFF) + (tmp >> 8));
pkt_dev->hh[8] = tmp;
tmp = (pkt_dev->src_mac[1] + (tmp >> 8));
pkt_dev->hh[7] = tmp;
}
/* Deal with Destination MAC */
if (pkt_dev->dst_mac_count > 1) {
__u32 mc;
__u32 tmp;
if (pkt_dev->flags & F_MACDST_RND)
mc = random32() % pkt_dev->dst_mac_count;
else {
mc = pkt_dev->cur_dst_mac_offset++;
if (pkt_dev->cur_dst_mac_offset >=
pkt_dev->dst_mac_count) {
pkt_dev->cur_dst_mac_offset = 0;
}
}
tmp = pkt_dev->dst_mac[5] + (mc & 0xFF);
pkt_dev->hh[5] = tmp;
tmp = (pkt_dev->dst_mac[4] + ((mc >> 8) & 0xFF) + (tmp >> 8));
pkt_dev->hh[4] = tmp;
tmp = (pkt_dev->dst_mac[3] + ((mc >> 16) & 0xFF) + (tmp >> 8));
pkt_dev->hh[3] = tmp;
tmp = (pkt_dev->dst_mac[2] + ((mc >> 24) & 0xFF) + (tmp >> 8));
pkt_dev->hh[2] = tmp;
tmp = (pkt_dev->dst_mac[1] + (tmp >> 8));
pkt_dev->hh[1] = tmp;
}
if (pkt_dev->flags & F_MPLS_RND) {
unsigned i;
for (i = 0; i < pkt_dev->nr_labels; i++)
if (pkt_dev->labels[i] & MPLS_STACK_BOTTOM)
pkt_dev->labels[i] = MPLS_STACK_BOTTOM |
((__force __be32)random32() &
htonl(0x000fffff));
}
if ((pkt_dev->flags & F_VID_RND) && (pkt_dev->vlan_id != 0xffff)) {
pkt_dev->vlan_id = random32() & (4096-1);
}
if ((pkt_dev->flags & F_SVID_RND) && (pkt_dev->svlan_id != 0xffff)) {
pkt_dev->svlan_id = random32() & (4096 - 1);
}
if (pkt_dev->udp_src_min < pkt_dev->udp_src_max) {
if (pkt_dev->flags & F_UDPSRC_RND)
pkt_dev->cur_udp_src = random32() %
(pkt_dev->udp_src_max - pkt_dev->udp_src_min)
+ pkt_dev->udp_src_min;
else {
pkt_dev->cur_udp_src++;
if (pkt_dev->cur_udp_src >= pkt_dev->udp_src_max)
pkt_dev->cur_udp_src = pkt_dev->udp_src_min;
}
}
if (pkt_dev->udp_dst_min < pkt_dev->udp_dst_max) {
if (pkt_dev->flags & F_UDPDST_RND) {
pkt_dev->cur_udp_dst = random32() %
(pkt_dev->udp_dst_max - pkt_dev->udp_dst_min)
+ pkt_dev->udp_dst_min;
} else {
pkt_dev->cur_udp_dst++;
if (pkt_dev->cur_udp_dst >= pkt_dev->udp_dst_max)
pkt_dev->cur_udp_dst = pkt_dev->udp_dst_min;
}
}
if (!(pkt_dev->flags & F_IPV6)) {
imn = ntohl(pkt_dev->saddr_min);
imx = ntohl(pkt_dev->saddr_max);
if (imn < imx) {
__u32 t;
if (pkt_dev->flags & F_IPSRC_RND)
t = random32() % (imx - imn) + imn;
else {
t = ntohl(pkt_dev->cur_saddr);
t++;
if (t > imx)
t = imn;
}
pkt_dev->cur_saddr = htonl(t);
}
if (pkt_dev->cflows && f_seen(pkt_dev, flow)) {
pkt_dev->cur_daddr = pkt_dev->flows[flow].cur_daddr;
} else {
imn = ntohl(pkt_dev->daddr_min);
imx = ntohl(pkt_dev->daddr_max);
if (imn < imx) {
__u32 t;
__be32 s;
if (pkt_dev->flags & F_IPDST_RND) {
t = random32() % (imx - imn) + imn;
s = htonl(t);
while (ipv4_is_loopback(s) ||
ipv4_is_multicast(s) ||
ipv4_is_lbcast(s) ||
ipv4_is_zeronet(s) ||
ipv4_is_local_multicast(s)) {
t = random32() % (imx - imn) + imn;
s = htonl(t);
}
pkt_dev->cur_daddr = s;
} else {
t = ntohl(pkt_dev->cur_daddr);
t++;
if (t > imx) {
t = imn;
}
pkt_dev->cur_daddr = htonl(t);
}
}
if (pkt_dev->cflows) {
pkt_dev->flows[flow].flags |= F_INIT;
pkt_dev->flows[flow].cur_daddr =
pkt_dev->cur_daddr;
#ifdef CONFIG_XFRM
if (pkt_dev->flags & F_IPSEC_ON)
get_ipsec_sa(pkt_dev, flow);
#endif
pkt_dev->nflows++;
}
}
} else { /* IPV6 * */
if (pkt_dev->min_in6_daddr.s6_addr32[0] == 0 &&
pkt_dev->min_in6_daddr.s6_addr32[1] == 0 &&
pkt_dev->min_in6_daddr.s6_addr32[2] == 0 &&
pkt_dev->min_in6_daddr.s6_addr32[3] == 0) ;
else {
int i;
/* Only random destinations yet */
for (i = 0; i < 4; i++) {
pkt_dev->cur_in6_daddr.s6_addr32[i] =
(((__force __be32)random32() |
pkt_dev->min_in6_daddr.s6_addr32[i]) &
pkt_dev->max_in6_daddr.s6_addr32[i]);
}
}
}
if (pkt_dev->min_pkt_size < pkt_dev->max_pkt_size) {
__u32 t;
if (pkt_dev->flags & F_TXSIZE_RND) {
t = random32() %
(pkt_dev->max_pkt_size - pkt_dev->min_pkt_size)
+ pkt_dev->min_pkt_size;
} else {
t = pkt_dev->cur_pkt_size + 1;
if (t > pkt_dev->max_pkt_size)
t = pkt_dev->min_pkt_size;
}
pkt_dev->cur_pkt_size = t;
}
set_cur_queue_map(pkt_dev);
pkt_dev->flows[flow].count++;
}
#ifdef CONFIG_XFRM
static int pktgen_output_ipsec(struct sk_buff *skb, struct pktgen_dev *pkt_dev)
{
struct xfrm_state *x = pkt_dev->flows[pkt_dev->curfl].x;
int err = 0;
if (!x)
return 0;
/* XXX: we dont support tunnel mode for now until
* we resolve the dst issue */
if (x->props.mode != XFRM_MODE_TRANSPORT)
return 0;
spin_lock(&x->lock);
err = x->outer_mode->output(x, skb);
if (err)
goto error;
err = x->type->output(x, skb);
if (err)
goto error;
x->curlft.bytes += skb->len;
x->curlft.packets++;
error:
spin_unlock(&x->lock);
return err;
}
static void free_SAs(struct pktgen_dev *pkt_dev)
{
if (pkt_dev->cflows) {
/* let go of the SAs if we have them */
int i;
for (i = 0; i < pkt_dev->cflows; i++) {
struct xfrm_state *x = pkt_dev->flows[i].x;
if (x) {
xfrm_state_put(x);
pkt_dev->flows[i].x = NULL;
}
}
}
}
static int process_ipsec(struct pktgen_dev *pkt_dev,
struct sk_buff *skb, __be16 protocol)
{
if (pkt_dev->flags & F_IPSEC_ON) {
struct xfrm_state *x = pkt_dev->flows[pkt_dev->curfl].x;
int nhead = 0;
if (x) {
int ret;
__u8 *eth;
nhead = x->props.header_len - skb_headroom(skb);
if (nhead > 0) {
ret = pskb_expand_head(skb, nhead, 0, GFP_ATOMIC);
if (ret < 0) {
pr_err("Error expanding ipsec packet %d\n",
ret);
goto err;
}
}
/* ipsec is not expecting ll header */
skb_pull(skb, ETH_HLEN);
ret = pktgen_output_ipsec(skb, pkt_dev);
if (ret) {
pr_err("Error creating ipsec packet %d\n", ret);
goto err;
}
/* restore ll */
eth = (__u8 *) skb_push(skb, ETH_HLEN);
memcpy(eth, pkt_dev->hh, 12);
*(u16 *) ð[12] = protocol;
}
}
return 1;
err:
kfree_skb(skb);
return 0;
}
#endif
static void mpls_push(__be32 *mpls, struct pktgen_dev *pkt_dev)
{
unsigned i;
for (i = 0; i < pkt_dev->nr_labels; i++)
*mpls++ = pkt_dev->labels[i] & ~MPLS_STACK_BOTTOM;
mpls--;
*mpls |= MPLS_STACK_BOTTOM;
}
static inline __be16 build_tci(unsigned int id, unsigned int cfi,
unsigned int prio)
{
return htons(id | (cfi << 12) | (prio << 13));
}
static void pktgen_finalize_skb(struct pktgen_dev *pkt_dev, struct sk_buff *skb,
int datalen)
{
struct timeval timestamp;
struct pktgen_hdr *pgh;
pgh = (struct pktgen_hdr *)skb_put(skb, sizeof(*pgh));
datalen -= sizeof(*pgh);
if (pkt_dev->nfrags <= 0) {
memset(skb_put(skb, datalen), 0, datalen);
} else {
int frags = pkt_dev->nfrags;
int i, len;
int frag_len;
if (frags > MAX_SKB_FRAGS)
frags = MAX_SKB_FRAGS;
len = datalen - frags * PAGE_SIZE;
if (len > 0) {
memset(skb_put(skb, len), 0, len);
datalen = frags * PAGE_SIZE;
}
i = 0;
frag_len = (datalen/frags) < PAGE_SIZE ?
(datalen/frags) : PAGE_SIZE;
while (datalen > 0) {
if (unlikely(!pkt_dev->page)) {
int node = numa_node_id();
if (pkt_dev->node >= 0 && (pkt_dev->flags & F_NODE))
node = pkt_dev->node;
pkt_dev->page = alloc_pages_node(node, GFP_KERNEL | __GFP_ZERO, 0);
if (!pkt_dev->page)
break;
}
skb_shinfo(skb)->frags[i].page = pkt_dev->page;
get_page(pkt_dev->page);
skb_shinfo(skb)->frags[i].page_offset = 0;
/*last fragment, fill rest of data*/
if (i == (frags - 1))
skb_shinfo(skb)->frags[i].size =
(datalen < PAGE_SIZE ? datalen : PAGE_SIZE);
else
skb_shinfo(skb)->frags[i].size = frag_len;
datalen -= skb_shinfo(skb)->frags[i].size;
skb->len += skb_shinfo(skb)->frags[i].size;
skb->data_len += skb_shinfo(skb)->frags[i].size;
i++;
skb_shinfo(skb)->nr_frags = i;
}
}
/* Stamp the time, and sequence number,
* convert them to network byte order
*/
pgh->pgh_magic = htonl(PKTGEN_MAGIC);
pgh->seq_num = htonl(pkt_dev->seq_num);
do_gettimeofday(×tamp);
pgh->tv_sec = htonl(timestamp.tv_sec);
pgh->tv_usec = htonl(timestamp.tv_usec);
}
static struct sk_buff *fill_packet_ipv4(struct net_device *odev,
struct pktgen_dev *pkt_dev)
{
struct sk_buff *skb = NULL;
__u8 *eth;
struct udphdr *udph;
int datalen, iplen;
struct iphdr *iph;
__be16 protocol = htons(ETH_P_IP);
__be32 *mpls;
__be16 *vlan_tci = NULL; /* Encapsulates priority and VLAN ID */
__be16 *vlan_encapsulated_proto = NULL; /* packet type ID field (or len) for VLAN tag */
__be16 *svlan_tci = NULL; /* Encapsulates priority and SVLAN ID */
__be16 *svlan_encapsulated_proto = NULL; /* packet type ID field (or len) for SVLAN tag */
u16 queue_map;
if (pkt_dev->nr_labels)
protocol = htons(ETH_P_MPLS_UC);
if (pkt_dev->vlan_id != 0xffff)
protocol = htons(ETH_P_8021Q);
/* Update any of the values, used when we're incrementing various
* fields.
*/
mod_cur_headers(pkt_dev);
queue_map = pkt_dev->cur_queue_map;
datalen = (odev->hard_header_len + 16) & ~0xf;
if (pkt_dev->flags & F_NODE) {
int node;
if (pkt_dev->node >= 0)
node = pkt_dev->node;
else
node = numa_node_id();
skb = __alloc_skb(NET_SKB_PAD + pkt_dev->cur_pkt_size + 64
+ datalen + pkt_dev->pkt_overhead, GFP_NOWAIT, 0, node);
if (likely(skb)) {
skb_reserve(skb, NET_SKB_PAD);
skb->dev = odev;
}
}
else
skb = __netdev_alloc_skb(odev,
pkt_dev->cur_pkt_size + 64
+ datalen + pkt_dev->pkt_overhead, GFP_NOWAIT);
if (!skb) {
sprintf(pkt_dev->result, "No memory");
return NULL;
}
prefetchw(skb->data);
skb_reserve(skb, datalen);
/* Reserve for ethernet and IP header */
eth = (__u8 *) skb_push(skb, 14);
mpls = (__be32 *)skb_put(skb, pkt_dev->nr_labels*sizeof(__u32));
if (pkt_dev->nr_labels)
mpls_push(mpls, pkt_dev);
if (pkt_dev->vlan_id != 0xffff) {
if (pkt_dev->svlan_id != 0xffff) {
svlan_tci = (__be16 *)skb_put(skb, sizeof(__be16));
*svlan_tci = build_tci(pkt_dev->svlan_id,
pkt_dev->svlan_cfi,
pkt_dev->svlan_p);
svlan_encapsulated_proto = (__be16 *)skb_put(skb, sizeof(__be16));
*svlan_encapsulated_proto = htons(ETH_P_8021Q);
}
vlan_tci = (__be16 *)skb_put(skb, sizeof(__be16));
*vlan_tci = build_tci(pkt_dev->vlan_id,
pkt_dev->vlan_cfi,
pkt_dev->vlan_p);
vlan_encapsulated_proto = (__be16 *)skb_put(skb, sizeof(__be16));
*vlan_encapsulated_proto = htons(ETH_P_IP);
}
skb->network_header = skb->tail;
skb->transport_header = skb->network_header + sizeof(struct iphdr);
skb_put(skb, sizeof(struct iphdr) + sizeof(struct udphdr));
skb_set_queue_mapping(skb, queue_map);
skb->priority = pkt_dev->skb_priority;
iph = ip_hdr(skb);
udph = udp_hdr(skb);
memcpy(eth, pkt_dev->hh, 12);
*(__be16 *) & eth[12] = protocol;
/* Eth + IPh + UDPh + mpls */
datalen = pkt_dev->cur_pkt_size - 14 - 20 - 8 -
pkt_dev->pkt_overhead;
if (datalen < sizeof(struct pktgen_hdr))
datalen = sizeof(struct pktgen_hdr);
udph->source = htons(pkt_dev->cur_udp_src);
udph->dest = htons(pkt_dev->cur_udp_dst);
udph->len = htons(datalen + 8); /* DATA + udphdr */
udph->check = 0; /* No checksum */
iph->ihl = 5;
iph->version = 4;
iph->ttl = 32;
iph->tos = pkt_dev->tos;
iph->protocol = IPPROTO_UDP; /* UDP */
iph->saddr = pkt_dev->cur_saddr;
iph->daddr = pkt_dev->cur_daddr;
iph->id = htons(pkt_dev->ip_id);
pkt_dev->ip_id++;
iph->frag_off = 0;
iplen = 20 + 8 + datalen;
iph->tot_len = htons(iplen);
iph->check = 0;
iph->check = ip_fast_csum((void *)iph, iph->ihl);
skb->protocol = protocol;
skb->mac_header = (skb->network_header - ETH_HLEN -
pkt_dev->pkt_overhead);
skb->dev = odev;
skb->pkt_type = PACKET_HOST;
pktgen_finalize_skb(pkt_dev, skb, datalen);
#ifdef CONFIG_XFRM
if (!process_ipsec(pkt_dev, skb, protocol))
return NULL;
#endif
return skb;
}
/*
* scan_ip6, fmt_ip taken from dietlibc-0.21
* Author Felix von Leitner <felix-dietlibc@fefe.de>
*
* Slightly modified for kernel.
* Should be candidate for net/ipv4/utils.c
* --ro
*/
static unsigned int scan_ip6(const char *s, char ip[16])
{
unsigned int i;
unsigned int len = 0;
unsigned long u;
char suffix[16];
unsigned int prefixlen = 0;
unsigned int suffixlen = 0;
__be32 tmp;
char *pos;
for (i = 0; i < 16; i++)
ip[i] = 0;
for (;;) {
if (*s == ':') {
len++;
if (s[1] == ':') { /* Found "::", skip to part 2 */
s += 2;
len++;
break;
}
s++;
}
u = simple_strtoul(s, &pos, 16);
i = pos - s;
if (!i)
return 0;
if (prefixlen == 12 && s[i] == '.') {
/* the last 4 bytes may be written as IPv4 address */
tmp = in_aton(s);
memcpy((struct in_addr *)(ip + 12), &tmp, sizeof(tmp));
return i + len;
}
ip[prefixlen++] = (u >> 8);
ip[prefixlen++] = (u & 255);
s += i;
len += i;
if (prefixlen == 16)
return len;
}
/* part 2, after "::" */
for (;;) {
if (*s == ':') {
if (suffixlen == 0)
break;
s++;
len++;
} else if (suffixlen != 0)
break;
u = simple_strtol(s, &pos, 16);
i = pos - s;
if (!i) {
if (*s)
len--;
break;
}
if (suffixlen + prefixlen <= 12 && s[i] == '.') {
tmp = in_aton(s);
memcpy((struct in_addr *)(suffix + suffixlen), &tmp,
sizeof(tmp));
suffixlen += 4;
len += strlen(s);
break;
}
suffix[suffixlen++] = (u >> 8);
suffix[suffixlen++] = (u & 255);
s += i;
len += i;
if (prefixlen + suffixlen == 16)
break;
}
for (i = 0; i < suffixlen; i++)
ip[16 - suffixlen + i] = suffix[i];
return len;
}
static struct sk_buff *fill_packet_ipv6(struct net_device *odev,
struct pktgen_dev *pkt_dev)
{
struct sk_buff *skb = NULL;
__u8 *eth;
struct udphdr *udph;
int datalen;
struct ipv6hdr *iph;
__be16 protocol = htons(ETH_P_IPV6);
__be32 *mpls;
__be16 *vlan_tci = NULL; /* Encapsulates priority and VLAN ID */
__be16 *vlan_encapsulated_proto = NULL; /* packet type ID field (or len) for VLAN tag */
__be16 *svlan_tci = NULL; /* Encapsulates priority and SVLAN ID */
__be16 *svlan_encapsulated_proto = NULL; /* packet type ID field (or len) for SVLAN tag */
u16 queue_map;
if (pkt_dev->nr_labels)
protocol = htons(ETH_P_MPLS_UC);
if (pkt_dev->vlan_id != 0xffff)
protocol = htons(ETH_P_8021Q);
/* Update any of the values, used when we're incrementing various
* fields.
*/
mod_cur_headers(pkt_dev);
queue_map = pkt_dev->cur_queue_map;
skb = __netdev_alloc_skb(odev,
pkt_dev->cur_pkt_size + 64
+ 16 + pkt_dev->pkt_overhead, GFP_NOWAIT);
if (!skb) {
sprintf(pkt_dev->result, "No memory");
return NULL;
}
prefetchw(skb->data);
skb_reserve(skb, 16);
/* Reserve for ethernet and IP header */
eth = (__u8 *) skb_push(skb, 14);
mpls = (__be32 *)skb_put(skb, pkt_dev->nr_labels*sizeof(__u32));
if (pkt_dev->nr_labels)
mpls_push(mpls, pkt_dev);
if (pkt_dev->vlan_id != 0xffff) {
if (pkt_dev->svlan_id != 0xffff) {
svlan_tci = (__be16 *)skb_put(skb, sizeof(__be16));
*svlan_tci = build_tci(pkt_dev->svlan_id,
pkt_dev->svlan_cfi,
pkt_dev->svlan_p);
svlan_encapsulated_proto = (__be16 *)skb_put(skb, sizeof(__be16));
*svlan_encapsulated_proto = htons(ETH_P_8021Q);
}
vlan_tci = (__be16 *)skb_put(skb, sizeof(__be16));
*vlan_tci = build_tci(pkt_dev->vlan_id,
pkt_dev->vlan_cfi,
pkt_dev->vlan_p);
vlan_encapsulated_proto = (__be16 *)skb_put(skb, sizeof(__be16));
*vlan_encapsulated_proto = htons(ETH_P_IPV6);
}
skb->network_header = skb->tail;
skb->transport_header = skb->network_header + sizeof(struct ipv6hdr);
skb_put(skb, sizeof(struct ipv6hdr) + sizeof(struct udphdr));
skb_set_queue_mapping(skb, queue_map);
skb->priority = pkt_dev->skb_priority;
iph = ipv6_hdr(skb);
udph = udp_hdr(skb);
memcpy(eth, pkt_dev->hh, 12);
*(__be16 *) ð[12] = protocol;
/* Eth + IPh + UDPh + mpls */
datalen = pkt_dev->cur_pkt_size - 14 -
sizeof(struct ipv6hdr) - sizeof(struct udphdr) -
pkt_dev->pkt_overhead;
if (datalen < 0 || datalen < sizeof(struct pktgen_hdr)) {
datalen = sizeof(struct pktgen_hdr);
if (net_ratelimit())
pr_info("increased datalen to %d\n", datalen);
}
udph->source = htons(pkt_dev->cur_udp_src);
udph->dest = htons(pkt_dev->cur_udp_dst);
udph->len = htons(datalen + sizeof(struct udphdr));
udph->check = 0; /* No checksum */
*(__be32 *) iph = htonl(0x60000000); /* Version + flow */
if (pkt_dev->traffic_class) {
/* Version + traffic class + flow (0) */
*(__be32 *)iph |= htonl(0x60000000 | (pkt_dev->traffic_class << 20));
}
iph->hop_limit = 32;
iph->payload_len = htons(sizeof(struct udphdr) + datalen);
iph->nexthdr = IPPROTO_UDP;
ipv6_addr_copy(&iph->daddr, &pkt_dev->cur_in6_daddr);
ipv6_addr_copy(&iph->saddr, &pkt_dev->cur_in6_saddr);
skb->mac_header = (skb->network_header - ETH_HLEN -
pkt_dev->pkt_overhead);
skb->protocol = protocol;
skb->dev = odev;
skb->pkt_type = PACKET_HOST;
pktgen_finalize_skb(pkt_dev, skb, datalen);
return skb;
}
static struct sk_buff *fill_packet(struct net_device *odev,
struct pktgen_dev *pkt_dev)
{
if (pkt_dev->flags & F_IPV6)
return fill_packet_ipv6(odev, pkt_dev);
else
return fill_packet_ipv4(odev, pkt_dev);
}
static void pktgen_clear_counters(struct pktgen_dev *pkt_dev)
{
pkt_dev->seq_num = 1;
pkt_dev->idle_acc = 0;
pkt_dev->sofar = 0;
pkt_dev->tx_bytes = 0;
pkt_dev->errors = 0;
}
/* Set up structure for sending pkts, clear counters */
static void pktgen_run(struct pktgen_thread *t)
{
struct pktgen_dev *pkt_dev;
int started = 0;
func_enter();
if_lock(t);
list_for_each_entry(pkt_dev, &t->if_list, list) {
/*
* setup odev and create initial packet.
*/
pktgen_setup_inject(pkt_dev);
if (pkt_dev->odev) {
pktgen_clear_counters(pkt_dev);
pkt_dev->running = 1; /* Cranke yeself! */
pkt_dev->skb = NULL;
pkt_dev->started_at =
pkt_dev->next_tx = ktime_now();
set_pkt_overhead(pkt_dev);
strcpy(pkt_dev->result, "Starting");
started++;
} else
strcpy(pkt_dev->result, "Error starting");
}
if_unlock(t);
if (started)
t->control &= ~(T_STOP);
}
static void pktgen_stop_all_threads_ifs(void)
{
struct pktgen_thread *t;
func_enter();
mutex_lock(&pktgen_thread_lock);
list_for_each_entry(t, &pktgen_threads, th_list)
t->control |= T_STOP;
mutex_unlock(&pktgen_thread_lock);
}
static int thread_is_running(const struct pktgen_thread *t)
{
const struct pktgen_dev *pkt_dev;
list_for_each_entry(pkt_dev, &t->if_list, list)
if (pkt_dev->running)
return 1;
return 0;
}
static int pktgen_wait_thread_run(struct pktgen_thread *t)
{
if_lock(t);
while (thread_is_running(t)) {
if_unlock(t);
msleep_interruptible(100);
if (signal_pending(current))
goto signal;
if_lock(t);
}
if_unlock(t);
return 1;
signal:
return 0;
}
static int pktgen_wait_all_threads_run(void)
{
struct pktgen_thread *t;
int sig = 1;
mutex_lock(&pktgen_thread_lock);
list_for_each_entry(t, &pktgen_threads, th_list) {
sig = pktgen_wait_thread_run(t);
if (sig == 0)
break;
}
if (sig == 0)
list_for_each_entry(t, &pktgen_threads, th_list)
t->control |= (T_STOP);
mutex_unlock(&pktgen_thread_lock);
return sig;
}
static void pktgen_run_all_threads(void)
{
struct pktgen_thread *t;
func_enter();
mutex_lock(&pktgen_thread_lock);
list_for_each_entry(t, &pktgen_threads, th_list)
t->control |= (T_RUN);
mutex_unlock(&pktgen_thread_lock);
/* Propagate thread->control */
schedule_timeout_interruptible(msecs_to_jiffies(125));
pktgen_wait_all_threads_run();
}
static void pktgen_reset_all_threads(void)
{
struct pktgen_thread *t;
func_enter();
mutex_lock(&pktgen_thread_lock);
list_for_each_entry(t, &pktgen_threads, th_list)
t->control |= (T_REMDEVALL);
mutex_unlock(&pktgen_thread_lock);
/* Propagate thread->control */
schedule_timeout_interruptible(msecs_to_jiffies(125));
pktgen_wait_all_threads_run();
}
static void show_results(struct pktgen_dev *pkt_dev, int nr_frags)
{
__u64 bps, mbps, pps;
char *p = pkt_dev->result;
ktime_t elapsed = ktime_sub(pkt_dev->stopped_at,
pkt_dev->started_at);
ktime_t idle = ns_to_ktime(pkt_dev->idle_acc);
p += sprintf(p, "OK: %llu(c%llu+d%llu) usec, %llu (%dbyte,%dfrags)\n",
(unsigned long long)ktime_to_us(elapsed),
(unsigned long long)ktime_to_us(ktime_sub(elapsed, idle)),
(unsigned long long)ktime_to_us(idle),
(unsigned long long)pkt_dev->sofar,
pkt_dev->cur_pkt_size, nr_frags);
pps = div64_u64(pkt_dev->sofar * NSEC_PER_SEC,
ktime_to_ns(elapsed));
bps = pps * 8 * pkt_dev->cur_pkt_size;
mbps = bps;
do_div(mbps, 1000000);
p += sprintf(p, " %llupps %lluMb/sec (%llubps) errors: %llu",
(unsigned long long)pps,
(unsigned long long)mbps,
(unsigned long long)bps,
(unsigned long long)pkt_dev->errors);
}
/* Set stopped-at timer, remove from running list, do counters & statistics */
static int pktgen_stop_device(struct pktgen_dev *pkt_dev)
{
int nr_frags = pkt_dev->skb ? skb_shinfo(pkt_dev->skb)->nr_frags : -1;
if (!pkt_dev->running) {
pr_warning("interface: %s is already stopped\n",
pkt_dev->odevname);
return -EINVAL;
}
kfree_skb(pkt_dev->skb);
pkt_dev->skb = NULL;
pkt_dev->stopped_at = ktime_now();
pkt_dev->running = 0;
show_results(pkt_dev, nr_frags);
return 0;
}
static struct pktgen_dev *next_to_run(struct pktgen_thread *t)
{
struct pktgen_dev *pkt_dev, *best = NULL;
if_lock(t);
list_for_each_entry(pkt_dev, &t->if_list, list) {
if (!pkt_dev->running)
continue;
if (best == NULL)
best = pkt_dev;
else if (ktime_lt(pkt_dev->next_tx, best->next_tx))
best = pkt_dev;
}
if_unlock(t);
return best;
}
static void pktgen_stop(struct pktgen_thread *t)
{
struct pktgen_dev *pkt_dev;
func_enter();
if_lock(t);
list_for_each_entry(pkt_dev, &t->if_list, list) {
pktgen_stop_device(pkt_dev);
}
if_unlock(t);
}
/*
* one of our devices needs to be removed - find it
* and remove it
*/
static void pktgen_rem_one_if(struct pktgen_thread *t)
{
struct list_head *q, *n;
struct pktgen_dev *cur;
func_enter();
if_lock(t);
list_for_each_safe(q, n, &t->if_list) {
cur = list_entry(q, struct pktgen_dev, list);
if (!cur->removal_mark)
continue;
kfree_skb(cur->skb);
cur->skb = NULL;
pktgen_remove_device(t, cur);
break;
}
if_unlock(t);
}
static void pktgen_rem_all_ifs(struct pktgen_thread *t)
{
struct list_head *q, *n;
struct pktgen_dev *cur;
func_enter();
/* Remove all devices, free mem */
if_lock(t);
list_for_each_safe(q, n, &t->if_list) {
cur = list_entry(q, struct pktgen_dev, list);
kfree_skb(cur->skb);
cur->skb = NULL;
pktgen_remove_device(t, cur);
}
if_unlock(t);
}
static void pktgen_rem_thread(struct pktgen_thread *t)
{
/* Remove from the thread list */
remove_proc_entry(t->tsk->comm, pg_proc_dir);
}
static void pktgen_resched(struct pktgen_dev *pkt_dev)
{
ktime_t idle_start = ktime_now();
schedule();
pkt_dev->idle_acc += ktime_to_ns(ktime_sub(ktime_now(), idle_start));
}
static void pktgen_wait_for_skb(struct pktgen_dev *pkt_dev)
{
ktime_t idle_start = ktime_now();
while (atomic_read(&(pkt_dev->skb->users)) != 1) {
if (signal_pending(current))
break;
if (need_resched())
pktgen_resched(pkt_dev);
else
cpu_relax();
}
pkt_dev->idle_acc += ktime_to_ns(ktime_sub(ktime_now(), idle_start));
}
static void pktgen_xmit(struct pktgen_dev *pkt_dev)
{
struct net_device *odev = pkt_dev->odev;
netdev_tx_t (*xmit)(struct sk_buff *, struct net_device *)
= odev->netdev_ops->ndo_start_xmit;
struct netdev_queue *txq;
u16 queue_map;
int ret;
/* If device is offline, then don't send */
if (unlikely(!netif_running(odev) || !netif_carrier_ok(odev))) {
pktgen_stop_device(pkt_dev);
return;
}
/* This is max DELAY, this has special meaning of
* "never transmit"
*/
if (unlikely(pkt_dev->delay == ULLONG_MAX)) {
pkt_dev->next_tx = ktime_add_ns(ktime_now(), ULONG_MAX);
return;
}
/* If no skb or clone count exhausted then get new one */
if (!pkt_dev->skb || (pkt_dev->last_ok &&
++pkt_dev->clone_count >= pkt_dev->clone_skb)) {
/* build a new pkt */
kfree_skb(pkt_dev->skb);
pkt_dev->skb = fill_packet(odev, pkt_dev);
if (pkt_dev->skb == NULL) {
pr_err("ERROR: couldn't allocate skb in fill_packet\n");
schedule();
pkt_dev->clone_count--; /* back out increment, OOM */
return;
}
pkt_dev->last_pkt_size = pkt_dev->skb->len;
pkt_dev->allocated_skbs++;
pkt_dev->clone_count = 0; /* reset counter */
}
if (pkt_dev->delay && pkt_dev->last_ok)
spin(pkt_dev, pkt_dev->next_tx);
queue_map = skb_get_queue_mapping(pkt_dev->skb);
txq = netdev_get_tx_queue(odev, queue_map);
__netif_tx_lock_bh(txq);
if (unlikely(netif_tx_queue_frozen_or_stopped(txq))) {
ret = NETDEV_TX_BUSY;
pkt_dev->last_ok = 0;
goto unlock;
}
atomic_inc(&(pkt_dev->skb->users));
ret = (*xmit)(pkt_dev->skb, odev);
switch (ret) {
case NETDEV_TX_OK:
txq_trans_update(txq);
pkt_dev->last_ok = 1;
pkt_dev->sofar++;
pkt_dev->seq_num++;
pkt_dev->tx_bytes += pkt_dev->last_pkt_size;
break;
case NET_XMIT_DROP:
case NET_XMIT_CN:
case NET_XMIT_POLICED:
/* skb has been consumed */
pkt_dev->errors++;
break;
default: /* Drivers are not supposed to return other values! */
if (net_ratelimit())
pr_info("%s xmit error: %d\n", pkt_dev->odevname, ret);
pkt_dev->errors++;
/* fallthru */
case NETDEV_TX_LOCKED:
case NETDEV_TX_BUSY:
/* Retry it next time */
atomic_dec(&(pkt_dev->skb->users));
pkt_dev->last_ok = 0;
}
unlock:
__netif_tx_unlock_bh(txq);
/* If pkt_dev->count is zero, then run forever */
if ((pkt_dev->count != 0) && (pkt_dev->sofar >= pkt_dev->count)) {
pktgen_wait_for_skb(pkt_dev);
/* Done with this */
pktgen_stop_device(pkt_dev);
}
}
/*
* Main loop of the thread goes here
*/
static int pktgen_thread_worker(void *arg)
{
DEFINE_WAIT(wait);
struct pktgen_thread *t = arg;
struct pktgen_dev *pkt_dev = NULL;
int cpu = t->cpu;
BUG_ON(smp_processor_id() != cpu);
init_waitqueue_head(&t->queue);
complete(&t->start_done);
pr_debug("starting pktgen/%d: pid=%d\n", cpu, task_pid_nr(current));
set_current_state(TASK_INTERRUPTIBLE);
set_freezable();
while (!kthread_should_stop()) {
pkt_dev = next_to_run(t);
if (unlikely(!pkt_dev && t->control == 0)) {
if (pktgen_exiting)
break;
wait_event_interruptible_timeout(t->queue,
t->control != 0,
HZ/10);
try_to_freeze();
continue;
}
__set_current_state(TASK_RUNNING);
if (likely(pkt_dev)) {
pktgen_xmit(pkt_dev);
if (need_resched())
pktgen_resched(pkt_dev);
else
cpu_relax();
}
if (t->control & T_STOP) {
pktgen_stop(t);
t->control &= ~(T_STOP);
}
if (t->control & T_RUN) {
pktgen_run(t);
t->control &= ~(T_RUN);
}
if (t->control & T_REMDEVALL) {
pktgen_rem_all_ifs(t);
t->control &= ~(T_REMDEVALL);
}
if (t->control & T_REMDEV) {
pktgen_rem_one_if(t);
t->control &= ~(T_REMDEV);
}
try_to_freeze();
set_current_state(TASK_INTERRUPTIBLE);
}
pr_debug("%s stopping all device\n", t->tsk->comm);
pktgen_stop(t);
pr_debug("%s removing all device\n", t->tsk->comm);
pktgen_rem_all_ifs(t);
pr_debug("%s removing thread\n", t->tsk->comm);
pktgen_rem_thread(t);
/* Wait for kthread_stop */
while (!kthread_should_stop()) {
set_current_state(TASK_INTERRUPTIBLE);
schedule();
}
__set_current_state(TASK_RUNNING);
return 0;
}
static struct pktgen_dev *pktgen_find_dev(struct pktgen_thread *t,
const char *ifname, bool exact)
{
struct pktgen_dev *p, *pkt_dev = NULL;
size_t len = strlen(ifname);
if_lock(t);
list_for_each_entry(p, &t->if_list, list)
if (strncmp(p->odevname, ifname, len) == 0) {
if (p->odevname[len]) {
if (exact || p->odevname[len] != '@')
continue;
}
pkt_dev = p;
break;
}
if_unlock(t);
pr_debug("find_dev(%s) returning %p\n", ifname, pkt_dev);
return pkt_dev;
}
/*
* Adds a dev at front of if_list.
*/
static int add_dev_to_thread(struct pktgen_thread *t,
struct pktgen_dev *pkt_dev)
{
int rv = 0;
if_lock(t);
if (pkt_dev->pg_thread) {
pr_err("ERROR: already assigned to a thread\n");
rv = -EBUSY;
goto out;
}
list_add(&pkt_dev->list, &t->if_list);
pkt_dev->pg_thread = t;
pkt_dev->running = 0;
out:
if_unlock(t);
return rv;
}
/* Called under thread lock */
static int pktgen_add_device(struct pktgen_thread *t, const char *ifname)
{
struct pktgen_dev *pkt_dev;
int err;
int node = cpu_to_node(t->cpu);
/* We don't allow a device to be on several threads */
pkt_dev = __pktgen_NN_threads(ifname, FIND);
if (pkt_dev) {
pr_err("ERROR: interface already used\n");
return -EBUSY;
}
pkt_dev = kzalloc_node(sizeof(struct pktgen_dev), GFP_KERNEL, node);
if (!pkt_dev)
return -ENOMEM;
strcpy(pkt_dev->odevname, ifname);
pkt_dev->flows = vzalloc_node(MAX_CFLOWS * sizeof(struct flow_state),
node);
if (pkt_dev->flows == NULL) {
kfree(pkt_dev);
return -ENOMEM;
}
pkt_dev->removal_mark = 0;
pkt_dev->min_pkt_size = ETH_ZLEN;
pkt_dev->max_pkt_size = ETH_ZLEN;
pkt_dev->nfrags = 0;
pkt_dev->delay = pg_delay_d;
pkt_dev->count = pg_count_d;
pkt_dev->sofar = 0;
pkt_dev->udp_src_min = 9; /* sink port */
pkt_dev->udp_src_max = 9;
pkt_dev->udp_dst_min = 9;
pkt_dev->udp_dst_max = 9;
pkt_dev->vlan_p = 0;
pkt_dev->vlan_cfi = 0;
pkt_dev->vlan_id = 0xffff;
pkt_dev->svlan_p = 0;
pkt_dev->svlan_cfi = 0;
pkt_dev->svlan_id = 0xffff;
pkt_dev->node = -1;
err = pktgen_setup_dev(pkt_dev, ifname);
if (err)
goto out1;
if (pkt_dev->odev->priv_flags & IFF_TX_SKB_SHARING)
pkt_dev->clone_skb = pg_clone_skb_d;
pkt_dev->entry = proc_create_data(ifname, 0600, pg_proc_dir,
&pktgen_if_fops, pkt_dev);
if (!pkt_dev->entry) {
pr_err("cannot create %s/%s procfs entry\n",
PG_PROC_DIR, ifname);
err = -EINVAL;
goto out2;
}
#ifdef CONFIG_XFRM
pkt_dev->ipsmode = XFRM_MODE_TRANSPORT;
pkt_dev->ipsproto = IPPROTO_ESP;
#endif
return add_dev_to_thread(t, pkt_dev);
out2:
dev_put(pkt_dev->odev);
out1:
#ifdef CONFIG_XFRM
free_SAs(pkt_dev);
#endif
vfree(pkt_dev->flows);
kfree(pkt_dev);
return err;
}
static int __init pktgen_create_thread(int cpu)
{
struct pktgen_thread *t;
struct proc_dir_entry *pe;
struct task_struct *p;
t = kzalloc_node(sizeof(struct pktgen_thread), GFP_KERNEL,
cpu_to_node(cpu));
if (!t) {
pr_err("ERROR: out of memory, can't create new thread\n");
return -ENOMEM;
}
spin_lock_init(&t->if_lock);
t->cpu = cpu;
INIT_LIST_HEAD(&t->if_list);
list_add_tail(&t->th_list, &pktgen_threads);
init_completion(&t->start_done);
p = kthread_create_on_node(pktgen_thread_worker,
t,
cpu_to_node(cpu),
"kpktgend_%d", cpu);
if (IS_ERR(p)) {
pr_err("kernel_thread() failed for cpu %d\n", t->cpu);
list_del(&t->th_list);
kfree(t);
return PTR_ERR(p);
}
kthread_bind(p, cpu);
t->tsk = p;
pe = proc_create_data(t->tsk->comm, 0600, pg_proc_dir,
&pktgen_thread_fops, t);
if (!pe) {
pr_err("cannot create %s/%s procfs entry\n",
PG_PROC_DIR, t->tsk->comm);
kthread_stop(p);
list_del(&t->th_list);
kfree(t);
return -EINVAL;
}
wake_up_process(p);
wait_for_completion(&t->start_done);
return 0;
}
/*
* Removes a device from the thread if_list.
*/
static void _rem_dev_from_if_list(struct pktgen_thread *t,
struct pktgen_dev *pkt_dev)
{
struct list_head *q, *n;
struct pktgen_dev *p;
list_for_each_safe(q, n, &t->if_list) {
p = list_entry(q, struct pktgen_dev, list);
if (p == pkt_dev)
list_del(&p->list);
}
}
static int pktgen_remove_device(struct pktgen_thread *t,
struct pktgen_dev *pkt_dev)
{
pr_debug("remove_device pkt_dev=%p\n", pkt_dev);
if (pkt_dev->running) {
pr_warning("WARNING: trying to remove a running interface, stopping it now\n");
pktgen_stop_device(pkt_dev);
}
/* Dis-associate from the interface */
if (pkt_dev->odev) {
dev_put(pkt_dev->odev);
pkt_dev->odev = NULL;
}
/* And update the thread if_list */
_rem_dev_from_if_list(t, pkt_dev);
if (pkt_dev->entry)
remove_proc_entry(pkt_dev->entry->name, pg_proc_dir);
#ifdef CONFIG_XFRM
free_SAs(pkt_dev);
#endif
vfree(pkt_dev->flows);
if (pkt_dev->page)
put_page(pkt_dev->page);
kfree(pkt_dev);
return 0;
}
static int __init pg_init(void)
{
int cpu;
struct proc_dir_entry *pe;
int ret = 0;
pr_info("%s", version);
pg_proc_dir = proc_mkdir(PG_PROC_DIR, init_net.proc_net);
if (!pg_proc_dir)
return -ENODEV;
pe = proc_create(PGCTRL, 0600, pg_proc_dir, &pktgen_fops);
if (pe == NULL) {
pr_err("ERROR: cannot create %s procfs entry\n", PGCTRL);
ret = -EINVAL;
goto remove_dir;
}
register_netdevice_notifier(&pktgen_notifier_block);
for_each_online_cpu(cpu) {
int err;
err = pktgen_create_thread(cpu);
if (err)
pr_warning("WARNING: Cannot create thread for cpu %d (%d)\n",
cpu, err);
}
if (list_empty(&pktgen_threads)) {
pr_err("ERROR: Initialization failed for all threads\n");
ret = -ENODEV;
goto unregister;
}
return 0;
unregister:
unregister_netdevice_notifier(&pktgen_notifier_block);
remove_proc_entry(PGCTRL, pg_proc_dir);
remove_dir:
proc_net_remove(&init_net, PG_PROC_DIR);
return ret;
}
static void __exit pg_cleanup(void)
{
struct pktgen_thread *t;
struct list_head *q, *n;
LIST_HEAD(list);
/* Stop all interfaces & threads */
pktgen_exiting = true;
mutex_lock(&pktgen_thread_lock);
list_splice_init(&pktgen_threads, &list);
mutex_unlock(&pktgen_thread_lock);
list_for_each_safe(q, n, &list) {
t = list_entry(q, struct pktgen_thread, th_list);
list_del(&t->th_list);
kthread_stop(t->tsk);
kfree(t);
}
/* Un-register us from receiving netdevice events */
unregister_netdevice_notifier(&pktgen_notifier_block);
/* Clean up proc file system */
remove_proc_entry(PGCTRL, pg_proc_dir);
proc_net_remove(&init_net, PG_PROC_DIR);
}
module_init(pg_init);
module_exit(pg_cleanup);
MODULE_AUTHOR("Robert Olsson <robert.olsson@its.uu.se>");
MODULE_DESCRIPTION("Packet Generator tool");
MODULE_LICENSE("GPL");
MODULE_VERSION(VERSION);
module_param(pg_count_d, int, 0);
MODULE_PARM_DESC(pg_count_d, "Default number of packets to inject");
module_param(pg_delay_d, int, 0);
MODULE_PARM_DESC(pg_delay_d, "Default delay between packets (nanoseconds)");
module_param(pg_clone_skb_d, int, 0);
MODULE_PARM_DESC(pg_clone_skb_d, "Default number of copies of the same packet");
module_param(debug, int, 0);
MODULE_PARM_DESC(debug, "Enable debugging of pktgen module");
| gpl-2.0 |
bugralevent/linux | drivers/clk/versatile/clk-impd1.c | 1079 | 5155 | /*
* Clock driver for the ARM Integrator/IM-PD1 board
* Copyright (C) 2012-2013 Linus Walleij
*
* 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/clk-provider.h>
#include <linux/clk.h>
#include <linux/clkdev.h>
#include <linux/err.h>
#include <linux/io.h>
#include <linux/platform_data/clk-integrator.h>
#include "clk-icst.h"
#define IMPD1_OSC1 0x00
#define IMPD1_OSC2 0x04
#define IMPD1_LOCK 0x08
struct impd1_clk {
char *pclkname;
struct clk *pclk;
char *vco1name;
struct clk *vco1clk;
char *vco2name;
struct clk *vco2clk;
struct clk *mmciclk;
char *uartname;
struct clk *uartclk;
char *spiname;
struct clk *spiclk;
char *scname;
struct clk *scclk;
struct clk_lookup *clks[15];
};
/* One entry for each connected IM-PD1 LM */
static struct impd1_clk impd1_clks[4];
/*
* There are two VCO's on the IM-PD1
*/
static const struct icst_params impd1_vco1_params = {
.ref = 24000000, /* 24 MHz */
.vco_max = ICST525_VCO_MAX_3V,
.vco_min = ICST525_VCO_MIN,
.vd_min = 12,
.vd_max = 519,
.rd_min = 3,
.rd_max = 120,
.s2div = icst525_s2div,
.idx2s = icst525_idx2s,
};
static const struct clk_icst_desc impd1_icst1_desc = {
.params = &impd1_vco1_params,
.vco_offset = IMPD1_OSC1,
.lock_offset = IMPD1_LOCK,
};
static const struct icst_params impd1_vco2_params = {
.ref = 24000000, /* 24 MHz */
.vco_max = ICST525_VCO_MAX_3V,
.vco_min = ICST525_VCO_MIN,
.vd_min = 12,
.vd_max = 519,
.rd_min = 3,
.rd_max = 120,
.s2div = icst525_s2div,
.idx2s = icst525_idx2s,
};
static const struct clk_icst_desc impd1_icst2_desc = {
.params = &impd1_vco2_params,
.vco_offset = IMPD1_OSC2,
.lock_offset = IMPD1_LOCK,
};
/**
* integrator_impd1_clk_init() - set up the integrator clock tree
* @base: base address of the logic module (LM)
* @id: the ID of this LM
*/
void integrator_impd1_clk_init(void __iomem *base, unsigned int id)
{
struct impd1_clk *imc;
struct clk *clk;
struct clk *pclk;
int i;
if (id > 3) {
pr_crit("no more than 4 LMs can be attached\n");
return;
}
imc = &impd1_clks[id];
/* Register the fixed rate PCLK */
imc->pclkname = kasprintf(GFP_KERNEL, "lm%x-pclk", id);
pclk = clk_register_fixed_rate(NULL, imc->pclkname, NULL,
CLK_IS_ROOT, 0);
imc->pclk = pclk;
imc->vco1name = kasprintf(GFP_KERNEL, "lm%x-vco1", id);
clk = icst_clk_register(NULL, &impd1_icst1_desc, imc->vco1name, NULL,
base);
imc->vco1clk = clk;
imc->clks[0] = clkdev_alloc(pclk, "apb_pclk", "lm%x:01000", id);
imc->clks[1] = clkdev_alloc(clk, NULL, "lm%x:01000", id);
/* VCO2 is also called "CLK2" */
imc->vco2name = kasprintf(GFP_KERNEL, "lm%x-vco2", id);
clk = icst_clk_register(NULL, &impd1_icst2_desc, imc->vco2name, NULL,
base);
imc->vco2clk = clk;
/* MMCI uses CLK2 right off */
imc->clks[2] = clkdev_alloc(pclk, "apb_pclk", "lm%x:00700", id);
imc->clks[3] = clkdev_alloc(clk, NULL, "lm%x:00700", id);
/* UART reference clock divides CLK2 by a fixed factor 4 */
imc->uartname = kasprintf(GFP_KERNEL, "lm%x-uartclk", id);
clk = clk_register_fixed_factor(NULL, imc->uartname, imc->vco2name,
CLK_IGNORE_UNUSED, 1, 4);
imc->uartclk = clk;
imc->clks[4] = clkdev_alloc(pclk, "apb_pclk", "lm%x:00100", id);
imc->clks[5] = clkdev_alloc(clk, NULL, "lm%x:00100", id);
imc->clks[6] = clkdev_alloc(pclk, "apb_pclk", "lm%x:00200", id);
imc->clks[7] = clkdev_alloc(clk, NULL, "lm%x:00200", id);
/* SPI PL022 clock divides CLK2 by a fixed factor 64 */
imc->spiname = kasprintf(GFP_KERNEL, "lm%x-spiclk", id);
clk = clk_register_fixed_factor(NULL, imc->spiname, imc->vco2name,
CLK_IGNORE_UNUSED, 1, 64);
imc->clks[8] = clkdev_alloc(pclk, "apb_pclk", "lm%x:00300", id);
imc->clks[9] = clkdev_alloc(clk, NULL, "lm%x:00300", id);
/* The GPIO blocks and AACI have only PCLK */
imc->clks[10] = clkdev_alloc(pclk, "apb_pclk", "lm%x:00400", id);
imc->clks[11] = clkdev_alloc(pclk, "apb_pclk", "lm%x:00500", id);
imc->clks[12] = clkdev_alloc(pclk, "apb_pclk", "lm%x:00800", id);
/* Smart Card clock divides CLK2 by a fixed factor 4 */
imc->scname = kasprintf(GFP_KERNEL, "lm%x-scclk", id);
clk = clk_register_fixed_factor(NULL, imc->scname, imc->vco2name,
CLK_IGNORE_UNUSED, 1, 4);
imc->scclk = clk;
imc->clks[13] = clkdev_alloc(pclk, "apb_pclk", "lm%x:00600", id);
imc->clks[14] = clkdev_alloc(clk, NULL, "lm%x:00600", id);
for (i = 0; i < ARRAY_SIZE(imc->clks); i++)
clkdev_add(imc->clks[i]);
}
EXPORT_SYMBOL_GPL(integrator_impd1_clk_init);
void integrator_impd1_clk_exit(unsigned int id)
{
int i;
struct impd1_clk *imc;
if (id > 3)
return;
imc = &impd1_clks[id];
for (i = 0; i < ARRAY_SIZE(imc->clks); i++)
clkdev_drop(imc->clks[i]);
clk_unregister(imc->spiclk);
clk_unregister(imc->uartclk);
clk_unregister(imc->vco2clk);
clk_unregister(imc->vco1clk);
clk_unregister(imc->pclk);
kfree(imc->scname);
kfree(imc->spiname);
kfree(imc->uartname);
kfree(imc->vco2name);
kfree(imc->vco1name);
kfree(imc->pclkname);
}
EXPORT_SYMBOL_GPL(integrator_impd1_clk_exit);
| gpl-2.0 |
humberos/android_kernel_sony_msm8994 | net/netfilter/nf_conntrack_proto_generic.c | 1335 | 5826 | /* (C) 1999-2001 Paul `Rusty' Russell
* (C) 2002-2004 Netfilter Core Team <coreteam@netfilter.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/types.h>
#include <linux/jiffies.h>
#include <linux/timer.h>
#include <linux/netfilter.h>
#include <net/netfilter/nf_conntrack_l4proto.h>
static unsigned int nf_ct_generic_timeout __read_mostly = 600*HZ;
static bool nf_generic_should_process(u8 proto)
{
switch (proto) {
#ifdef CONFIG_NF_CT_PROTO_SCTP_MODULE
case IPPROTO_SCTP:
return false;
#endif
#ifdef CONFIG_NF_CT_PROTO_DCCP_MODULE
case IPPROTO_DCCP:
return false;
#endif
#ifdef CONFIG_NF_CT_PROTO_GRE_MODULE
case IPPROTO_GRE:
return false;
#endif
#ifdef CONFIG_NF_CT_PROTO_UDPLITE_MODULE
case IPPROTO_UDPLITE:
return false;
#endif
default:
return true;
}
}
static inline struct nf_generic_net *generic_pernet(struct net *net)
{
return &net->ct.nf_ct_proto.generic;
}
static bool generic_pkt_to_tuple(const struct sk_buff *skb,
unsigned int dataoff,
struct nf_conntrack_tuple *tuple)
{
tuple->src.u.all = 0;
tuple->dst.u.all = 0;
return true;
}
static bool generic_invert_tuple(struct nf_conntrack_tuple *tuple,
const struct nf_conntrack_tuple *orig)
{
tuple->src.u.all = 0;
tuple->dst.u.all = 0;
return true;
}
/* Print out the per-protocol part of the tuple. */
static int generic_print_tuple(struct seq_file *s,
const struct nf_conntrack_tuple *tuple)
{
return 0;
}
static unsigned int *generic_get_timeouts(struct net *net)
{
return &(generic_pernet(net)->timeout);
}
/* Returns verdict for packet, or -1 for invalid. */
static int generic_packet(struct nf_conn *ct,
const struct sk_buff *skb,
unsigned int dataoff,
enum ip_conntrack_info ctinfo,
u_int8_t pf,
unsigned int hooknum,
unsigned int *timeout)
{
nf_ct_refresh_acct(ct, ctinfo, skb, *timeout);
return NF_ACCEPT;
}
/* Called when a new connection for this protocol found. */
static bool generic_new(struct nf_conn *ct, const struct sk_buff *skb,
unsigned int dataoff, unsigned int *timeouts)
{
return nf_generic_should_process(nf_ct_protonum(ct));
}
#if IS_ENABLED(CONFIG_NF_CT_NETLINK_TIMEOUT)
#include <linux/netfilter/nfnetlink.h>
#include <linux/netfilter/nfnetlink_cttimeout.h>
static int generic_timeout_nlattr_to_obj(struct nlattr *tb[],
struct net *net, void *data)
{
unsigned int *timeout = data;
struct nf_generic_net *gn = generic_pernet(net);
if (tb[CTA_TIMEOUT_GENERIC_TIMEOUT])
*timeout =
ntohl(nla_get_be32(tb[CTA_TIMEOUT_GENERIC_TIMEOUT])) * HZ;
else {
/* Set default generic timeout. */
*timeout = gn->timeout;
}
return 0;
}
static int
generic_timeout_obj_to_nlattr(struct sk_buff *skb, const void *data)
{
const unsigned int *timeout = data;
if (nla_put_be32(skb, CTA_TIMEOUT_GENERIC_TIMEOUT, htonl(*timeout / HZ)))
goto nla_put_failure;
return 0;
nla_put_failure:
return -ENOSPC;
}
static const struct nla_policy
generic_timeout_nla_policy[CTA_TIMEOUT_GENERIC_MAX+1] = {
[CTA_TIMEOUT_GENERIC_TIMEOUT] = { .type = NLA_U32 },
};
#endif /* CONFIG_NF_CT_NETLINK_TIMEOUT */
#ifdef CONFIG_SYSCTL
static struct ctl_table generic_sysctl_table[] = {
{
.procname = "nf_conntrack_generic_timeout",
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{ }
};
#ifdef CONFIG_NF_CONNTRACK_PROC_COMPAT
static struct ctl_table generic_compat_sysctl_table[] = {
{
.procname = "ip_conntrack_generic_timeout",
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{ }
};
#endif /* CONFIG_NF_CONNTRACK_PROC_COMPAT */
#endif /* CONFIG_SYSCTL */
static int generic_kmemdup_sysctl_table(struct nf_proto_net *pn,
struct nf_generic_net *gn)
{
#ifdef CONFIG_SYSCTL
pn->ctl_table = kmemdup(generic_sysctl_table,
sizeof(generic_sysctl_table),
GFP_KERNEL);
if (!pn->ctl_table)
return -ENOMEM;
pn->ctl_table[0].data = &gn->timeout;
#endif
return 0;
}
static int generic_kmemdup_compat_sysctl_table(struct nf_proto_net *pn,
struct nf_generic_net *gn)
{
#ifdef CONFIG_SYSCTL
#ifdef CONFIG_NF_CONNTRACK_PROC_COMPAT
pn->ctl_compat_table = kmemdup(generic_compat_sysctl_table,
sizeof(generic_compat_sysctl_table),
GFP_KERNEL);
if (!pn->ctl_compat_table)
return -ENOMEM;
pn->ctl_compat_table[0].data = &gn->timeout;
#endif
#endif
return 0;
}
static int generic_init_net(struct net *net, u_int16_t proto)
{
int ret;
struct nf_generic_net *gn = generic_pernet(net);
struct nf_proto_net *pn = &gn->pn;
gn->timeout = nf_ct_generic_timeout;
ret = generic_kmemdup_compat_sysctl_table(pn, gn);
if (ret < 0)
return ret;
ret = generic_kmemdup_sysctl_table(pn, gn);
if (ret < 0)
nf_ct_kfree_compat_sysctl_table(pn);
return ret;
}
static struct nf_proto_net *generic_get_net_proto(struct net *net)
{
return &net->ct.nf_ct_proto.generic.pn;
}
struct nf_conntrack_l4proto nf_conntrack_l4proto_generic __read_mostly =
{
.l3proto = PF_UNSPEC,
.l4proto = 255,
.name = "unknown",
.pkt_to_tuple = generic_pkt_to_tuple,
.invert_tuple = generic_invert_tuple,
.print_tuple = generic_print_tuple,
.packet = generic_packet,
.get_timeouts = generic_get_timeouts,
.new = generic_new,
#if IS_ENABLED(CONFIG_NF_CT_NETLINK_TIMEOUT)
.ctnl_timeout = {
.nlattr_to_obj = generic_timeout_nlattr_to_obj,
.obj_to_nlattr = generic_timeout_obj_to_nlattr,
.nlattr_max = CTA_TIMEOUT_GENERIC_MAX,
.obj_size = sizeof(unsigned int),
.nla_policy = generic_timeout_nla_policy,
},
#endif /* CONFIG_NF_CT_NETLINK_TIMEOUT */
.init_net = generic_init_net,
.get_net_proto = generic_get_net_proto,
};
| gpl-2.0 |
mathkid95/linux_motorola_lollipop | arch/arm/mach-mmp/mmp2-dt.c | 2103 | 1781 | /*
* linux/arch/arm/mach-mmp/mmp2-dt.c
*
* Copyright (C) 2012 Marvell Technology Group Ltd.
* Author: Haojian Zhuang <haojian.zhuang@marvell.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* publishhed by the Free Software Foundation.
*/
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/irqdomain.h>
#include <linux/of_irq.h>
#include <linux/of_platform.h>
#include <asm/mach/arch.h>
#include <asm/mach/time.h>
#include <mach/irqs.h>
#include <mach/regs-apbc.h>
#include "common.h"
extern void __init mmp_dt_irq_init(void);
extern void __init mmp_dt_init_timer(void);
static const struct of_dev_auxdata mmp2_auxdata_lookup[] __initconst = {
OF_DEV_AUXDATA("mrvl,mmp-uart", 0xd4030000, "pxa2xx-uart.0", NULL),
OF_DEV_AUXDATA("mrvl,mmp-uart", 0xd4017000, "pxa2xx-uart.1", NULL),
OF_DEV_AUXDATA("mrvl,mmp-uart", 0xd4018000, "pxa2xx-uart.2", NULL),
OF_DEV_AUXDATA("mrvl,mmp-uart", 0xd4016000, "pxa2xx-uart.3", NULL),
OF_DEV_AUXDATA("mrvl,mmp-twsi", 0xd4011000, "pxa2xx-i2c.0", NULL),
OF_DEV_AUXDATA("mrvl,mmp-twsi", 0xd4025000, "pxa2xx-i2c.1", NULL),
OF_DEV_AUXDATA("marvell,mmp-gpio", 0xd4019000, "mmp2-gpio", NULL),
OF_DEV_AUXDATA("mrvl,mmp-rtc", 0xd4010000, "sa1100-rtc", NULL),
{}
};
static void __init mmp2_dt_init(void)
{
of_platform_populate(NULL, of_default_bus_match_table,
mmp2_auxdata_lookup, NULL);
}
static const char *mmp2_dt_board_compat[] __initdata = {
"mrvl,mmp2-brownstone",
NULL,
};
DT_MACHINE_START(MMP2_DT, "Marvell MMP2 (Device Tree Support)")
.map_io = mmp_map_io,
.init_irq = mmp_dt_irq_init,
.init_time = mmp_dt_init_timer,
.init_machine = mmp2_dt_init,
.dt_compat = mmp2_dt_board_compat,
MACHINE_END
| gpl-2.0 |
jeboo/kernel_JB_ZSLS6_i777 | net/sched/sch_sfq.c | 2359 | 17343 | /*
* net/sched/sch_sfq.c Stochastic Fairness Queueing discipline.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/jiffies.h>
#include <linux/string.h>
#include <linux/in.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/ipv6.h>
#include <linux/skbuff.h>
#include <linux/jhash.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <net/ip.h>
#include <net/netlink.h>
#include <net/pkt_sched.h>
/* Stochastic Fairness Queuing algorithm.
=======================================
Source:
Paul E. McKenney "Stochastic Fairness Queuing",
IEEE INFOCOMM'90 Proceedings, San Francisco, 1990.
Paul E. McKenney "Stochastic Fairness Queuing",
"Interworking: Research and Experience", v.2, 1991, p.113-131.
See also:
M. Shreedhar and George Varghese "Efficient Fair
Queuing using Deficit Round Robin", Proc. SIGCOMM 95.
This is not the thing that is usually called (W)FQ nowadays.
It does not use any timestamp mechanism, but instead
processes queues in round-robin order.
ADVANTAGE:
- It is very cheap. Both CPU and memory requirements are minimal.
DRAWBACKS:
- "Stochastic" -> It is not 100% fair.
When hash collisions occur, several flows are considered as one.
- "Round-robin" -> It introduces larger delays than virtual clock
based schemes, and should not be used for isolating interactive
traffic from non-interactive. It means, that this scheduler
should be used as leaf of CBQ or P3, which put interactive traffic
to higher priority band.
We still need true WFQ for top level CSZ, but using WFQ
for the best effort traffic is absolutely pointless:
SFQ is superior for this purpose.
IMPLEMENTATION:
This implementation limits maximal queue length to 128;
max mtu to 2^18-1; max 128 flows, number of hash buckets to 1024.
The only goal of this restrictions was that all data
fit into one 4K page on 32bit arches.
It is easy to increase these values, but not in flight. */
#define SFQ_DEPTH 128 /* max number of packets per flow */
#define SFQ_SLOTS 128 /* max number of flows */
#define SFQ_EMPTY_SLOT 255
#define SFQ_DEFAULT_HASH_DIVISOR 1024
/* We use 16 bits to store allot, and want to handle packets up to 64K
* Scale allot by 8 (1<<3) so that no overflow occurs.
*/
#define SFQ_ALLOT_SHIFT 3
#define SFQ_ALLOT_SIZE(X) DIV_ROUND_UP(X, 1 << SFQ_ALLOT_SHIFT)
/* This type should contain at least SFQ_DEPTH + SFQ_SLOTS values */
typedef unsigned char sfq_index;
/*
* We dont use pointers to save space.
* Small indexes [0 ... SFQ_SLOTS - 1] are 'pointers' to slots[] array
* while following values [SFQ_SLOTS ... SFQ_SLOTS + SFQ_DEPTH - 1]
* are 'pointers' to dep[] array
*/
struct sfq_head {
sfq_index next;
sfq_index prev;
};
struct sfq_slot {
struct sk_buff *skblist_next;
struct sk_buff *skblist_prev;
sfq_index qlen; /* number of skbs in skblist */
sfq_index next; /* next slot in sfq chain */
struct sfq_head dep; /* anchor in dep[] chains */
unsigned short hash; /* hash value (index in ht[]) */
short allot; /* credit for this slot */
};
struct sfq_sched_data {
/* Parameters */
int perturb_period;
unsigned int quantum; /* Allotment per round: MUST BE >= MTU */
int limit;
unsigned int divisor; /* number of slots in hash table */
/* Variables */
struct tcf_proto *filter_list;
struct timer_list perturb_timer;
u32 perturbation;
sfq_index cur_depth; /* depth of longest slot */
unsigned short scaled_quantum; /* SFQ_ALLOT_SIZE(quantum) */
struct sfq_slot *tail; /* current slot in round */
sfq_index *ht; /* Hash table (divisor slots) */
struct sfq_slot slots[SFQ_SLOTS];
struct sfq_head dep[SFQ_DEPTH]; /* Linked list of slots, indexed by depth */
};
/*
* sfq_head are either in a sfq_slot or in dep[] array
*/
static inline struct sfq_head *sfq_dep_head(struct sfq_sched_data *q, sfq_index val)
{
if (val < SFQ_SLOTS)
return &q->slots[val].dep;
return &q->dep[val - SFQ_SLOTS];
}
static unsigned int sfq_fold_hash(struct sfq_sched_data *q, u32 h, u32 h1)
{
return jhash_2words(h, h1, q->perturbation) & (q->divisor - 1);
}
static unsigned int sfq_hash(struct sfq_sched_data *q, struct sk_buff *skb)
{
u32 h, h2;
switch (skb->protocol) {
case htons(ETH_P_IP):
{
const struct iphdr *iph;
int poff;
if (!pskb_network_may_pull(skb, sizeof(*iph)))
goto err;
iph = ip_hdr(skb);
h = (__force u32)iph->daddr;
h2 = (__force u32)iph->saddr ^ iph->protocol;
if (iph->frag_off & htons(IP_MF | IP_OFFSET))
break;
poff = proto_ports_offset(iph->protocol);
if (poff >= 0 &&
pskb_network_may_pull(skb, iph->ihl * 4 + 4 + poff)) {
iph = ip_hdr(skb);
h2 ^= *(u32 *)((void *)iph + iph->ihl * 4 + poff);
}
break;
}
case htons(ETH_P_IPV6):
{
const struct ipv6hdr *iph;
int poff;
if (!pskb_network_may_pull(skb, sizeof(*iph)))
goto err;
iph = ipv6_hdr(skb);
h = (__force u32)iph->daddr.s6_addr32[3];
h2 = (__force u32)iph->saddr.s6_addr32[3] ^ iph->nexthdr;
poff = proto_ports_offset(iph->nexthdr);
if (poff >= 0 &&
pskb_network_may_pull(skb, sizeof(*iph) + 4 + poff)) {
iph = ipv6_hdr(skb);
h2 ^= *(u32 *)((void *)iph + sizeof(*iph) + poff);
}
break;
}
default:
err:
h = (unsigned long)skb_dst(skb) ^ (__force u32)skb->protocol;
h2 = (unsigned long)skb->sk;
}
return sfq_fold_hash(q, h, h2);
}
static unsigned int sfq_classify(struct sk_buff *skb, struct Qdisc *sch,
int *qerr)
{
struct sfq_sched_data *q = qdisc_priv(sch);
struct tcf_result res;
int result;
if (TC_H_MAJ(skb->priority) == sch->handle &&
TC_H_MIN(skb->priority) > 0 &&
TC_H_MIN(skb->priority) <= q->divisor)
return TC_H_MIN(skb->priority);
if (!q->filter_list)
return sfq_hash(q, skb) + 1;
*qerr = NET_XMIT_SUCCESS | __NET_XMIT_BYPASS;
result = tc_classify(skb, q->filter_list, &res);
if (result >= 0) {
#ifdef CONFIG_NET_CLS_ACT
switch (result) {
case TC_ACT_STOLEN:
case TC_ACT_QUEUED:
*qerr = NET_XMIT_SUCCESS | __NET_XMIT_STOLEN;
case TC_ACT_SHOT:
return 0;
}
#endif
if (TC_H_MIN(res.classid) <= q->divisor)
return TC_H_MIN(res.classid);
}
return 0;
}
/*
* x : slot number [0 .. SFQ_SLOTS - 1]
*/
static inline void sfq_link(struct sfq_sched_data *q, sfq_index x)
{
sfq_index p, n;
int qlen = q->slots[x].qlen;
p = qlen + SFQ_SLOTS;
n = q->dep[qlen].next;
q->slots[x].dep.next = n;
q->slots[x].dep.prev = p;
q->dep[qlen].next = x; /* sfq_dep_head(q, p)->next = x */
sfq_dep_head(q, n)->prev = x;
}
#define sfq_unlink(q, x, n, p) \
n = q->slots[x].dep.next; \
p = q->slots[x].dep.prev; \
sfq_dep_head(q, p)->next = n; \
sfq_dep_head(q, n)->prev = p
static inline void sfq_dec(struct sfq_sched_data *q, sfq_index x)
{
sfq_index p, n;
int d;
sfq_unlink(q, x, n, p);
d = q->slots[x].qlen--;
if (n == p && q->cur_depth == d)
q->cur_depth--;
sfq_link(q, x);
}
static inline void sfq_inc(struct sfq_sched_data *q, sfq_index x)
{
sfq_index p, n;
int d;
sfq_unlink(q, x, n, p);
d = ++q->slots[x].qlen;
if (q->cur_depth < d)
q->cur_depth = d;
sfq_link(q, x);
}
/* helper functions : might be changed when/if skb use a standard list_head */
/* remove one skb from tail of slot queue */
static inline struct sk_buff *slot_dequeue_tail(struct sfq_slot *slot)
{
struct sk_buff *skb = slot->skblist_prev;
slot->skblist_prev = skb->prev;
skb->prev->next = (struct sk_buff *)slot;
skb->next = skb->prev = NULL;
return skb;
}
/* remove one skb from head of slot queue */
static inline struct sk_buff *slot_dequeue_head(struct sfq_slot *slot)
{
struct sk_buff *skb = slot->skblist_next;
slot->skblist_next = skb->next;
skb->next->prev = (struct sk_buff *)slot;
skb->next = skb->prev = NULL;
return skb;
}
static inline void slot_queue_init(struct sfq_slot *slot)
{
slot->skblist_prev = slot->skblist_next = (struct sk_buff *)slot;
}
/* add skb to slot queue (tail add) */
static inline void slot_queue_add(struct sfq_slot *slot, struct sk_buff *skb)
{
skb->prev = slot->skblist_prev;
skb->next = (struct sk_buff *)slot;
slot->skblist_prev->next = skb;
slot->skblist_prev = skb;
}
#define slot_queue_walk(slot, skb) \
for (skb = slot->skblist_next; \
skb != (struct sk_buff *)slot; \
skb = skb->next)
static unsigned int sfq_drop(struct Qdisc *sch)
{
struct sfq_sched_data *q = qdisc_priv(sch);
sfq_index x, d = q->cur_depth;
struct sk_buff *skb;
unsigned int len;
struct sfq_slot *slot;
/* Queue is full! Find the longest slot and drop tail packet from it */
if (d > 1) {
x = q->dep[d].next;
slot = &q->slots[x];
drop:
skb = slot_dequeue_tail(slot);
len = qdisc_pkt_len(skb);
sfq_dec(q, x);
kfree_skb(skb);
sch->q.qlen--;
sch->qstats.drops++;
sch->qstats.backlog -= len;
return len;
}
if (d == 1) {
/* It is difficult to believe, but ALL THE SLOTS HAVE LENGTH 1. */
x = q->tail->next;
slot = &q->slots[x];
q->tail->next = slot->next;
q->ht[slot->hash] = SFQ_EMPTY_SLOT;
goto drop;
}
return 0;
}
static int
sfq_enqueue(struct sk_buff *skb, struct Qdisc *sch)
{
struct sfq_sched_data *q = qdisc_priv(sch);
unsigned int hash;
sfq_index x, qlen;
struct sfq_slot *slot;
int uninitialized_var(ret);
hash = sfq_classify(skb, sch, &ret);
if (hash == 0) {
if (ret & __NET_XMIT_BYPASS)
sch->qstats.drops++;
kfree_skb(skb);
return ret;
}
hash--;
x = q->ht[hash];
slot = &q->slots[x];
if (x == SFQ_EMPTY_SLOT) {
x = q->dep[0].next; /* get a free slot */
q->ht[hash] = x;
slot = &q->slots[x];
slot->hash = hash;
}
/* If selected queue has length q->limit, do simple tail drop,
* i.e. drop _this_ packet.
*/
if (slot->qlen >= q->limit)
return qdisc_drop(skb, sch);
sch->qstats.backlog += qdisc_pkt_len(skb);
slot_queue_add(slot, skb);
sfq_inc(q, x);
if (slot->qlen == 1) { /* The flow is new */
if (q->tail == NULL) { /* It is the first flow */
slot->next = x;
} else {
slot->next = q->tail->next;
q->tail->next = x;
}
q->tail = slot;
slot->allot = q->scaled_quantum;
}
if (++sch->q.qlen <= q->limit)
return NET_XMIT_SUCCESS;
qlen = slot->qlen;
sfq_drop(sch);
/* Return Congestion Notification only if we dropped a packet
* from this flow.
*/
if (qlen != slot->qlen)
return NET_XMIT_CN;
/* As we dropped a packet, better let upper stack know this */
qdisc_tree_decrease_qlen(sch, 1);
return NET_XMIT_SUCCESS;
}
static struct sk_buff *
sfq_dequeue(struct Qdisc *sch)
{
struct sfq_sched_data *q = qdisc_priv(sch);
struct sk_buff *skb;
sfq_index a, next_a;
struct sfq_slot *slot;
/* No active slots */
if (q->tail == NULL)
return NULL;
next_slot:
a = q->tail->next;
slot = &q->slots[a];
if (slot->allot <= 0) {
q->tail = slot;
slot->allot += q->scaled_quantum;
goto next_slot;
}
skb = slot_dequeue_head(slot);
sfq_dec(q, a);
qdisc_bstats_update(sch, skb);
sch->q.qlen--;
sch->qstats.backlog -= qdisc_pkt_len(skb);
/* Is the slot empty? */
if (slot->qlen == 0) {
q->ht[slot->hash] = SFQ_EMPTY_SLOT;
next_a = slot->next;
if (a == next_a) {
q->tail = NULL; /* no more active slots */
return skb;
}
q->tail->next = next_a;
} else {
slot->allot -= SFQ_ALLOT_SIZE(qdisc_pkt_len(skb));
}
return skb;
}
static void
sfq_reset(struct Qdisc *sch)
{
struct sk_buff *skb;
while ((skb = sfq_dequeue(sch)) != NULL)
kfree_skb(skb);
}
static void sfq_perturbation(unsigned long arg)
{
struct Qdisc *sch = (struct Qdisc *)arg;
struct sfq_sched_data *q = qdisc_priv(sch);
q->perturbation = net_random();
if (q->perturb_period)
mod_timer(&q->perturb_timer, jiffies + q->perturb_period);
}
static int sfq_change(struct Qdisc *sch, struct nlattr *opt)
{
struct sfq_sched_data *q = qdisc_priv(sch);
struct tc_sfq_qopt *ctl = nla_data(opt);
unsigned int qlen;
if (opt->nla_len < nla_attr_size(sizeof(*ctl)))
return -EINVAL;
if (ctl->divisor &&
(!is_power_of_2(ctl->divisor) || ctl->divisor > 65536))
return -EINVAL;
sch_tree_lock(sch);
q->quantum = ctl->quantum ? : psched_mtu(qdisc_dev(sch));
q->scaled_quantum = SFQ_ALLOT_SIZE(q->quantum);
q->perturb_period = ctl->perturb_period * HZ;
if (ctl->limit)
q->limit = min_t(u32, ctl->limit, SFQ_DEPTH - 1);
if (ctl->divisor)
q->divisor = ctl->divisor;
qlen = sch->q.qlen;
while (sch->q.qlen > q->limit)
sfq_drop(sch);
qdisc_tree_decrease_qlen(sch, qlen - sch->q.qlen);
del_timer(&q->perturb_timer);
if (q->perturb_period) {
mod_timer(&q->perturb_timer, jiffies + q->perturb_period);
q->perturbation = net_random();
}
sch_tree_unlock(sch);
return 0;
}
static int sfq_init(struct Qdisc *sch, struct nlattr *opt)
{
struct sfq_sched_data *q = qdisc_priv(sch);
size_t sz;
int i;
q->perturb_timer.function = sfq_perturbation;
q->perturb_timer.data = (unsigned long)sch;
init_timer_deferrable(&q->perturb_timer);
for (i = 0; i < SFQ_DEPTH; i++) {
q->dep[i].next = i + SFQ_SLOTS;
q->dep[i].prev = i + SFQ_SLOTS;
}
q->limit = SFQ_DEPTH - 1;
q->cur_depth = 0;
q->tail = NULL;
q->divisor = SFQ_DEFAULT_HASH_DIVISOR;
if (opt == NULL) {
q->quantum = psched_mtu(qdisc_dev(sch));
q->scaled_quantum = SFQ_ALLOT_SIZE(q->quantum);
q->perturb_period = 0;
q->perturbation = net_random();
} else {
int err = sfq_change(sch, opt);
if (err)
return err;
}
sz = sizeof(q->ht[0]) * q->divisor;
q->ht = kmalloc(sz, GFP_KERNEL);
if (!q->ht && sz > PAGE_SIZE)
q->ht = vmalloc(sz);
if (!q->ht)
return -ENOMEM;
for (i = 0; i < q->divisor; i++)
q->ht[i] = SFQ_EMPTY_SLOT;
for (i = 0; i < SFQ_SLOTS; i++) {
slot_queue_init(&q->slots[i]);
sfq_link(q, i);
}
if (q->limit >= 1)
sch->flags |= TCQ_F_CAN_BYPASS;
else
sch->flags &= ~TCQ_F_CAN_BYPASS;
return 0;
}
static void sfq_destroy(struct Qdisc *sch)
{
struct sfq_sched_data *q = qdisc_priv(sch);
tcf_destroy_chain(&q->filter_list);
q->perturb_period = 0;
del_timer_sync(&q->perturb_timer);
if (is_vmalloc_addr(q->ht))
vfree(q->ht);
else
kfree(q->ht);
}
static int sfq_dump(struct Qdisc *sch, struct sk_buff *skb)
{
struct sfq_sched_data *q = qdisc_priv(sch);
unsigned char *b = skb_tail_pointer(skb);
struct tc_sfq_qopt opt;
opt.quantum = q->quantum;
opt.perturb_period = q->perturb_period / HZ;
opt.limit = q->limit;
opt.divisor = q->divisor;
opt.flows = q->limit;
NLA_PUT(skb, TCA_OPTIONS, sizeof(opt), &opt);
return skb->len;
nla_put_failure:
nlmsg_trim(skb, b);
return -1;
}
static struct Qdisc *sfq_leaf(struct Qdisc *sch, unsigned long arg)
{
return NULL;
}
static unsigned long sfq_get(struct Qdisc *sch, u32 classid)
{
return 0;
}
static unsigned long sfq_bind(struct Qdisc *sch, unsigned long parent,
u32 classid)
{
/* we cannot bypass queue discipline anymore */
sch->flags &= ~TCQ_F_CAN_BYPASS;
return 0;
}
static void sfq_put(struct Qdisc *q, unsigned long cl)
{
}
static struct tcf_proto **sfq_find_tcf(struct Qdisc *sch, unsigned long cl)
{
struct sfq_sched_data *q = qdisc_priv(sch);
if (cl)
return NULL;
return &q->filter_list;
}
static int sfq_dump_class(struct Qdisc *sch, unsigned long cl,
struct sk_buff *skb, struct tcmsg *tcm)
{
tcm->tcm_handle |= TC_H_MIN(cl);
return 0;
}
static int sfq_dump_class_stats(struct Qdisc *sch, unsigned long cl,
struct gnet_dump *d)
{
struct sfq_sched_data *q = qdisc_priv(sch);
sfq_index idx = q->ht[cl - 1];
struct gnet_stats_queue qs = { 0 };
struct tc_sfq_xstats xstats = { 0 };
struct sk_buff *skb;
if (idx != SFQ_EMPTY_SLOT) {
const struct sfq_slot *slot = &q->slots[idx];
xstats.allot = slot->allot << SFQ_ALLOT_SHIFT;
qs.qlen = slot->qlen;
slot_queue_walk(slot, skb)
qs.backlog += qdisc_pkt_len(skb);
}
if (gnet_stats_copy_queue(d, &qs) < 0)
return -1;
return gnet_stats_copy_app(d, &xstats, sizeof(xstats));
}
static void sfq_walk(struct Qdisc *sch, struct qdisc_walker *arg)
{
struct sfq_sched_data *q = qdisc_priv(sch);
unsigned int i;
if (arg->stop)
return;
for (i = 0; i < q->divisor; i++) {
if (q->ht[i] == SFQ_EMPTY_SLOT ||
arg->count < arg->skip) {
arg->count++;
continue;
}
if (arg->fn(sch, i + 1, arg) < 0) {
arg->stop = 1;
break;
}
arg->count++;
}
}
static const struct Qdisc_class_ops sfq_class_ops = {
.leaf = sfq_leaf,
.get = sfq_get,
.put = sfq_put,
.tcf_chain = sfq_find_tcf,
.bind_tcf = sfq_bind,
.unbind_tcf = sfq_put,
.dump = sfq_dump_class,
.dump_stats = sfq_dump_class_stats,
.walk = sfq_walk,
};
static struct Qdisc_ops sfq_qdisc_ops __read_mostly = {
.cl_ops = &sfq_class_ops,
.id = "sfq",
.priv_size = sizeof(struct sfq_sched_data),
.enqueue = sfq_enqueue,
.dequeue = sfq_dequeue,
.peek = qdisc_peek_dequeued,
.drop = sfq_drop,
.init = sfq_init,
.reset = sfq_reset,
.destroy = sfq_destroy,
.change = NULL,
.dump = sfq_dump,
.owner = THIS_MODULE,
};
static int __init sfq_module_init(void)
{
return register_qdisc(&sfq_qdisc_ops);
}
static void __exit sfq_module_exit(void)
{
unregister_qdisc(&sfq_qdisc_ops);
}
module_init(sfq_module_init)
module_exit(sfq_module_exit)
MODULE_LICENSE("GPL");
| gpl-2.0 |
cmenard/kernel_smdk4412 | fs/btrfs/transaction.c | 2359 | 38349 | /*
* Copyright (C) 2007 Oracle. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License v2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 021110-1307, USA.
*/
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/writeback.h>
#include <linux/pagemap.h>
#include <linux/blkdev.h>
#include "ctree.h"
#include "disk-io.h"
#include "transaction.h"
#include "locking.h"
#include "tree-log.h"
#include "inode-map.h"
#define BTRFS_ROOT_TRANS_TAG 0
static noinline void put_transaction(struct btrfs_transaction *transaction)
{
WARN_ON(atomic_read(&transaction->use_count) == 0);
if (atomic_dec_and_test(&transaction->use_count)) {
BUG_ON(!list_empty(&transaction->list));
memset(transaction, 0, sizeof(*transaction));
kmem_cache_free(btrfs_transaction_cachep, transaction);
}
}
static noinline void switch_commit_root(struct btrfs_root *root)
{
free_extent_buffer(root->commit_root);
root->commit_root = btrfs_root_node(root);
}
/*
* either allocate a new transaction or hop into the existing one
*/
static noinline int join_transaction(struct btrfs_root *root, int nofail)
{
struct btrfs_transaction *cur_trans;
spin_lock(&root->fs_info->trans_lock);
if (root->fs_info->trans_no_join) {
if (!nofail) {
spin_unlock(&root->fs_info->trans_lock);
return -EBUSY;
}
}
cur_trans = root->fs_info->running_transaction;
if (cur_trans) {
atomic_inc(&cur_trans->use_count);
atomic_inc(&cur_trans->num_writers);
cur_trans->num_joined++;
spin_unlock(&root->fs_info->trans_lock);
return 0;
}
spin_unlock(&root->fs_info->trans_lock);
cur_trans = kmem_cache_alloc(btrfs_transaction_cachep, GFP_NOFS);
if (!cur_trans)
return -ENOMEM;
spin_lock(&root->fs_info->trans_lock);
if (root->fs_info->running_transaction) {
kmem_cache_free(btrfs_transaction_cachep, cur_trans);
cur_trans = root->fs_info->running_transaction;
atomic_inc(&cur_trans->use_count);
atomic_inc(&cur_trans->num_writers);
cur_trans->num_joined++;
spin_unlock(&root->fs_info->trans_lock);
return 0;
}
atomic_set(&cur_trans->num_writers, 1);
cur_trans->num_joined = 0;
init_waitqueue_head(&cur_trans->writer_wait);
init_waitqueue_head(&cur_trans->commit_wait);
cur_trans->in_commit = 0;
cur_trans->blocked = 0;
/*
* One for this trans handle, one so it will live on until we
* commit the transaction.
*/
atomic_set(&cur_trans->use_count, 2);
cur_trans->commit_done = 0;
cur_trans->start_time = get_seconds();
cur_trans->delayed_refs.root = RB_ROOT;
cur_trans->delayed_refs.num_entries = 0;
cur_trans->delayed_refs.num_heads_ready = 0;
cur_trans->delayed_refs.num_heads = 0;
cur_trans->delayed_refs.flushing = 0;
cur_trans->delayed_refs.run_delayed_start = 0;
spin_lock_init(&cur_trans->commit_lock);
spin_lock_init(&cur_trans->delayed_refs.lock);
INIT_LIST_HEAD(&cur_trans->pending_snapshots);
list_add_tail(&cur_trans->list, &root->fs_info->trans_list);
extent_io_tree_init(&cur_trans->dirty_pages,
root->fs_info->btree_inode->i_mapping);
root->fs_info->generation++;
cur_trans->transid = root->fs_info->generation;
root->fs_info->running_transaction = cur_trans;
spin_unlock(&root->fs_info->trans_lock);
return 0;
}
/*
* this does all the record keeping required to make sure that a reference
* counted root is properly recorded in a given transaction. This is required
* to make sure the old root from before we joined the transaction is deleted
* when the transaction commits
*/
static int record_root_in_trans(struct btrfs_trans_handle *trans,
struct btrfs_root *root)
{
if (root->ref_cows && root->last_trans < trans->transid) {
WARN_ON(root == root->fs_info->extent_root);
WARN_ON(root->commit_root != root->node);
/*
* see below for in_trans_setup usage rules
* we have the reloc mutex held now, so there
* is only one writer in this function
*/
root->in_trans_setup = 1;
/* make sure readers find in_trans_setup before
* they find our root->last_trans update
*/
smp_wmb();
spin_lock(&root->fs_info->fs_roots_radix_lock);
if (root->last_trans == trans->transid) {
spin_unlock(&root->fs_info->fs_roots_radix_lock);
return 0;
}
radix_tree_tag_set(&root->fs_info->fs_roots_radix,
(unsigned long)root->root_key.objectid,
BTRFS_ROOT_TRANS_TAG);
spin_unlock(&root->fs_info->fs_roots_radix_lock);
root->last_trans = trans->transid;
/* this is pretty tricky. We don't want to
* take the relocation lock in btrfs_record_root_in_trans
* unless we're really doing the first setup for this root in
* this transaction.
*
* Normally we'd use root->last_trans as a flag to decide
* if we want to take the expensive mutex.
*
* But, we have to set root->last_trans before we
* init the relocation root, otherwise, we trip over warnings
* in ctree.c. The solution used here is to flag ourselves
* with root->in_trans_setup. When this is 1, we're still
* fixing up the reloc trees and everyone must wait.
*
* When this is zero, they can trust root->last_trans and fly
* through btrfs_record_root_in_trans without having to take the
* lock. smp_wmb() makes sure that all the writes above are
* done before we pop in the zero below
*/
btrfs_init_reloc_root(trans, root);
smp_wmb();
root->in_trans_setup = 0;
}
return 0;
}
int btrfs_record_root_in_trans(struct btrfs_trans_handle *trans,
struct btrfs_root *root)
{
if (!root->ref_cows)
return 0;
/*
* see record_root_in_trans for comments about in_trans_setup usage
* and barriers
*/
smp_rmb();
if (root->last_trans == trans->transid &&
!root->in_trans_setup)
return 0;
mutex_lock(&root->fs_info->reloc_mutex);
record_root_in_trans(trans, root);
mutex_unlock(&root->fs_info->reloc_mutex);
return 0;
}
/* wait for commit against the current transaction to become unblocked
* when this is done, it is safe to start a new transaction, but the current
* transaction might not be fully on disk.
*/
static void wait_current_trans(struct btrfs_root *root)
{
struct btrfs_transaction *cur_trans;
spin_lock(&root->fs_info->trans_lock);
cur_trans = root->fs_info->running_transaction;
if (cur_trans && cur_trans->blocked) {
DEFINE_WAIT(wait);
atomic_inc(&cur_trans->use_count);
spin_unlock(&root->fs_info->trans_lock);
while (1) {
prepare_to_wait(&root->fs_info->transaction_wait, &wait,
TASK_UNINTERRUPTIBLE);
if (!cur_trans->blocked)
break;
schedule();
}
finish_wait(&root->fs_info->transaction_wait, &wait);
put_transaction(cur_trans);
} else {
spin_unlock(&root->fs_info->trans_lock);
}
}
enum btrfs_trans_type {
TRANS_START,
TRANS_JOIN,
TRANS_USERSPACE,
TRANS_JOIN_NOLOCK,
};
static int may_wait_transaction(struct btrfs_root *root, int type)
{
if (root->fs_info->log_root_recovering)
return 0;
if (type == TRANS_USERSPACE)
return 1;
if (type == TRANS_START &&
!atomic_read(&root->fs_info->open_ioctl_trans))
return 1;
return 0;
}
static struct btrfs_trans_handle *start_transaction(struct btrfs_root *root,
u64 num_items, int type)
{
struct btrfs_trans_handle *h;
struct btrfs_transaction *cur_trans;
int retries = 0;
int ret;
if (root->fs_info->fs_state & BTRFS_SUPER_FLAG_ERROR)
return ERR_PTR(-EROFS);
if (current->journal_info) {
WARN_ON(type != TRANS_JOIN && type != TRANS_JOIN_NOLOCK);
h = current->journal_info;
h->use_count++;
h->orig_rsv = h->block_rsv;
h->block_rsv = NULL;
goto got_it;
}
again:
h = kmem_cache_alloc(btrfs_trans_handle_cachep, GFP_NOFS);
if (!h)
return ERR_PTR(-ENOMEM);
if (may_wait_transaction(root, type))
wait_current_trans(root);
do {
ret = join_transaction(root, type == TRANS_JOIN_NOLOCK);
if (ret == -EBUSY)
wait_current_trans(root);
} while (ret == -EBUSY);
if (ret < 0) {
kmem_cache_free(btrfs_trans_handle_cachep, h);
return ERR_PTR(ret);
}
cur_trans = root->fs_info->running_transaction;
h->transid = cur_trans->transid;
h->transaction = cur_trans;
h->blocks_used = 0;
h->bytes_reserved = 0;
h->delayed_ref_updates = 0;
h->use_count = 1;
h->block_rsv = NULL;
h->orig_rsv = NULL;
smp_mb();
if (cur_trans->blocked && may_wait_transaction(root, type)) {
btrfs_commit_transaction(h, root);
goto again;
}
if (num_items > 0) {
ret = btrfs_trans_reserve_metadata(h, root, num_items);
if (ret == -EAGAIN && !retries) {
retries++;
btrfs_commit_transaction(h, root);
goto again;
} else if (ret == -EAGAIN) {
/*
* We have already retried and got EAGAIN, so really we
* don't have space, so set ret to -ENOSPC.
*/
ret = -ENOSPC;
}
if (ret < 0) {
btrfs_end_transaction(h, root);
return ERR_PTR(ret);
}
}
got_it:
btrfs_record_root_in_trans(h, root);
if (!current->journal_info && type != TRANS_USERSPACE)
current->journal_info = h;
return h;
}
struct btrfs_trans_handle *btrfs_start_transaction(struct btrfs_root *root,
int num_items)
{
return start_transaction(root, num_items, TRANS_START);
}
struct btrfs_trans_handle *btrfs_join_transaction(struct btrfs_root *root)
{
return start_transaction(root, 0, TRANS_JOIN);
}
struct btrfs_trans_handle *btrfs_join_transaction_nolock(struct btrfs_root *root)
{
return start_transaction(root, 0, TRANS_JOIN_NOLOCK);
}
struct btrfs_trans_handle *btrfs_start_ioctl_transaction(struct btrfs_root *root)
{
return start_transaction(root, 0, TRANS_USERSPACE);
}
/* wait for a transaction commit to be fully complete */
static noinline int wait_for_commit(struct btrfs_root *root,
struct btrfs_transaction *commit)
{
DEFINE_WAIT(wait);
while (!commit->commit_done) {
prepare_to_wait(&commit->commit_wait, &wait,
TASK_UNINTERRUPTIBLE);
if (commit->commit_done)
break;
schedule();
}
finish_wait(&commit->commit_wait, &wait);
return 0;
}
int btrfs_wait_for_commit(struct btrfs_root *root, u64 transid)
{
struct btrfs_transaction *cur_trans = NULL, *t;
int ret;
ret = 0;
if (transid) {
if (transid <= root->fs_info->last_trans_committed)
goto out;
/* find specified transaction */
spin_lock(&root->fs_info->trans_lock);
list_for_each_entry(t, &root->fs_info->trans_list, list) {
if (t->transid == transid) {
cur_trans = t;
atomic_inc(&cur_trans->use_count);
break;
}
if (t->transid > transid)
break;
}
spin_unlock(&root->fs_info->trans_lock);
ret = -EINVAL;
if (!cur_trans)
goto out; /* bad transid */
} else {
/* find newest transaction that is committing | committed */
spin_lock(&root->fs_info->trans_lock);
list_for_each_entry_reverse(t, &root->fs_info->trans_list,
list) {
if (t->in_commit) {
if (t->commit_done)
break;
cur_trans = t;
atomic_inc(&cur_trans->use_count);
break;
}
}
spin_unlock(&root->fs_info->trans_lock);
if (!cur_trans)
goto out; /* nothing committing|committed */
}
wait_for_commit(root, cur_trans);
put_transaction(cur_trans);
ret = 0;
out:
return ret;
}
void btrfs_throttle(struct btrfs_root *root)
{
if (!atomic_read(&root->fs_info->open_ioctl_trans))
wait_current_trans(root);
}
static int should_end_transaction(struct btrfs_trans_handle *trans,
struct btrfs_root *root)
{
int ret;
ret = btrfs_block_rsv_check(trans, root,
&root->fs_info->global_block_rsv, 0, 5);
return ret ? 1 : 0;
}
int btrfs_should_end_transaction(struct btrfs_trans_handle *trans,
struct btrfs_root *root)
{
struct btrfs_transaction *cur_trans = trans->transaction;
int updates;
smp_mb();
if (cur_trans->blocked || cur_trans->delayed_refs.flushing)
return 1;
updates = trans->delayed_ref_updates;
trans->delayed_ref_updates = 0;
if (updates)
btrfs_run_delayed_refs(trans, root, updates);
return should_end_transaction(trans, root);
}
static int __btrfs_end_transaction(struct btrfs_trans_handle *trans,
struct btrfs_root *root, int throttle, int lock)
{
struct btrfs_transaction *cur_trans = trans->transaction;
struct btrfs_fs_info *info = root->fs_info;
int count = 0;
if (--trans->use_count) {
trans->block_rsv = trans->orig_rsv;
return 0;
}
while (count < 4) {
unsigned long cur = trans->delayed_ref_updates;
trans->delayed_ref_updates = 0;
if (cur &&
trans->transaction->delayed_refs.num_heads_ready > 64) {
trans->delayed_ref_updates = 0;
/*
* do a full flush if the transaction is trying
* to close
*/
if (trans->transaction->delayed_refs.flushing)
cur = 0;
btrfs_run_delayed_refs(trans, root, cur);
} else {
break;
}
count++;
}
btrfs_trans_release_metadata(trans, root);
if (lock && !atomic_read(&root->fs_info->open_ioctl_trans) &&
should_end_transaction(trans, root)) {
trans->transaction->blocked = 1;
smp_wmb();
}
if (lock && cur_trans->blocked && !cur_trans->in_commit) {
if (throttle)
return btrfs_commit_transaction(trans, root);
else
wake_up_process(info->transaction_kthread);
}
WARN_ON(cur_trans != info->running_transaction);
WARN_ON(atomic_read(&cur_trans->num_writers) < 1);
atomic_dec(&cur_trans->num_writers);
smp_mb();
if (waitqueue_active(&cur_trans->writer_wait))
wake_up(&cur_trans->writer_wait);
put_transaction(cur_trans);
if (current->journal_info == trans)
current->journal_info = NULL;
memset(trans, 0, sizeof(*trans));
kmem_cache_free(btrfs_trans_handle_cachep, trans);
if (throttle)
btrfs_run_delayed_iputs(root);
return 0;
}
int btrfs_end_transaction(struct btrfs_trans_handle *trans,
struct btrfs_root *root)
{
int ret;
ret = __btrfs_end_transaction(trans, root, 0, 1);
if (ret)
return ret;
return 0;
}
int btrfs_end_transaction_throttle(struct btrfs_trans_handle *trans,
struct btrfs_root *root)
{
int ret;
ret = __btrfs_end_transaction(trans, root, 1, 1);
if (ret)
return ret;
return 0;
}
int btrfs_end_transaction_nolock(struct btrfs_trans_handle *trans,
struct btrfs_root *root)
{
int ret;
ret = __btrfs_end_transaction(trans, root, 0, 0);
if (ret)
return ret;
return 0;
}
int btrfs_end_transaction_dmeta(struct btrfs_trans_handle *trans,
struct btrfs_root *root)
{
return __btrfs_end_transaction(trans, root, 1, 1);
}
/*
* when btree blocks are allocated, they have some corresponding bits set for
* them in one of two extent_io trees. This is used to make sure all of
* those extents are sent to disk but does not wait on them
*/
int btrfs_write_marked_extents(struct btrfs_root *root,
struct extent_io_tree *dirty_pages, int mark)
{
int ret;
int err = 0;
int werr = 0;
struct page *page;
struct inode *btree_inode = root->fs_info->btree_inode;
u64 start = 0;
u64 end;
unsigned long index;
while (1) {
ret = find_first_extent_bit(dirty_pages, start, &start, &end,
mark);
if (ret)
break;
while (start <= end) {
cond_resched();
index = start >> PAGE_CACHE_SHIFT;
start = (u64)(index + 1) << PAGE_CACHE_SHIFT;
page = find_get_page(btree_inode->i_mapping, index);
if (!page)
continue;
btree_lock_page_hook(page);
if (!page->mapping) {
unlock_page(page);
page_cache_release(page);
continue;
}
if (PageWriteback(page)) {
if (PageDirty(page))
wait_on_page_writeback(page);
else {
unlock_page(page);
page_cache_release(page);
continue;
}
}
err = write_one_page(page, 0);
if (err)
werr = err;
page_cache_release(page);
}
}
if (err)
werr = err;
return werr;
}
/*
* when btree blocks are allocated, they have some corresponding bits set for
* them in one of two extent_io trees. This is used to make sure all of
* those extents are on disk for transaction or log commit. We wait
* on all the pages and clear them from the dirty pages state tree
*/
int btrfs_wait_marked_extents(struct btrfs_root *root,
struct extent_io_tree *dirty_pages, int mark)
{
int ret;
int err = 0;
int werr = 0;
struct page *page;
struct inode *btree_inode = root->fs_info->btree_inode;
u64 start = 0;
u64 end;
unsigned long index;
while (1) {
ret = find_first_extent_bit(dirty_pages, start, &start, &end,
mark);
if (ret)
break;
clear_extent_bits(dirty_pages, start, end, mark, GFP_NOFS);
while (start <= end) {
index = start >> PAGE_CACHE_SHIFT;
start = (u64)(index + 1) << PAGE_CACHE_SHIFT;
page = find_get_page(btree_inode->i_mapping, index);
if (!page)
continue;
if (PageDirty(page)) {
btree_lock_page_hook(page);
wait_on_page_writeback(page);
err = write_one_page(page, 0);
if (err)
werr = err;
}
wait_on_page_writeback(page);
page_cache_release(page);
cond_resched();
}
}
if (err)
werr = err;
return werr;
}
/*
* when btree blocks are allocated, they have some corresponding bits set for
* them in one of two extent_io trees. This is used to make sure all of
* those extents are on disk for transaction or log commit
*/
int btrfs_write_and_wait_marked_extents(struct btrfs_root *root,
struct extent_io_tree *dirty_pages, int mark)
{
int ret;
int ret2;
ret = btrfs_write_marked_extents(root, dirty_pages, mark);
ret2 = btrfs_wait_marked_extents(root, dirty_pages, mark);
return ret || ret2;
}
int btrfs_write_and_wait_transaction(struct btrfs_trans_handle *trans,
struct btrfs_root *root)
{
if (!trans || !trans->transaction) {
struct inode *btree_inode;
btree_inode = root->fs_info->btree_inode;
return filemap_write_and_wait(btree_inode->i_mapping);
}
return btrfs_write_and_wait_marked_extents(root,
&trans->transaction->dirty_pages,
EXTENT_DIRTY);
}
/*
* this is used to update the root pointer in the tree of tree roots.
*
* But, in the case of the extent allocation tree, updating the root
* pointer may allocate blocks which may change the root of the extent
* allocation tree.
*
* So, this loops and repeats and makes sure the cowonly root didn't
* change while the root pointer was being updated in the metadata.
*/
static int update_cowonly_root(struct btrfs_trans_handle *trans,
struct btrfs_root *root)
{
int ret;
u64 old_root_bytenr;
u64 old_root_used;
struct btrfs_root *tree_root = root->fs_info->tree_root;
old_root_used = btrfs_root_used(&root->root_item);
btrfs_write_dirty_block_groups(trans, root);
while (1) {
old_root_bytenr = btrfs_root_bytenr(&root->root_item);
if (old_root_bytenr == root->node->start &&
old_root_used == btrfs_root_used(&root->root_item))
break;
btrfs_set_root_node(&root->root_item, root->node);
ret = btrfs_update_root(trans, tree_root,
&root->root_key,
&root->root_item);
BUG_ON(ret);
old_root_used = btrfs_root_used(&root->root_item);
ret = btrfs_write_dirty_block_groups(trans, root);
BUG_ON(ret);
}
if (root != root->fs_info->extent_root)
switch_commit_root(root);
return 0;
}
/*
* update all the cowonly tree roots on disk
*/
static noinline int commit_cowonly_roots(struct btrfs_trans_handle *trans,
struct btrfs_root *root)
{
struct btrfs_fs_info *fs_info = root->fs_info;
struct list_head *next;
struct extent_buffer *eb;
int ret;
ret = btrfs_run_delayed_refs(trans, root, (unsigned long)-1);
BUG_ON(ret);
eb = btrfs_lock_root_node(fs_info->tree_root);
btrfs_cow_block(trans, fs_info->tree_root, eb, NULL, 0, &eb);
btrfs_tree_unlock(eb);
free_extent_buffer(eb);
ret = btrfs_run_delayed_refs(trans, root, (unsigned long)-1);
BUG_ON(ret);
while (!list_empty(&fs_info->dirty_cowonly_roots)) {
next = fs_info->dirty_cowonly_roots.next;
list_del_init(next);
root = list_entry(next, struct btrfs_root, dirty_list);
update_cowonly_root(trans, root);
}
down_write(&fs_info->extent_commit_sem);
switch_commit_root(fs_info->extent_root);
up_write(&fs_info->extent_commit_sem);
return 0;
}
/*
* dead roots are old snapshots that need to be deleted. This allocates
* a dirty root struct and adds it into the list of dead roots that need to
* be deleted
*/
int btrfs_add_dead_root(struct btrfs_root *root)
{
spin_lock(&root->fs_info->trans_lock);
list_add(&root->root_list, &root->fs_info->dead_roots);
spin_unlock(&root->fs_info->trans_lock);
return 0;
}
/*
* update all the cowonly tree roots on disk
*/
static noinline int commit_fs_roots(struct btrfs_trans_handle *trans,
struct btrfs_root *root)
{
struct btrfs_root *gang[8];
struct btrfs_fs_info *fs_info = root->fs_info;
int i;
int ret;
int err = 0;
spin_lock(&fs_info->fs_roots_radix_lock);
while (1) {
ret = radix_tree_gang_lookup_tag(&fs_info->fs_roots_radix,
(void **)gang, 0,
ARRAY_SIZE(gang),
BTRFS_ROOT_TRANS_TAG);
if (ret == 0)
break;
for (i = 0; i < ret; i++) {
root = gang[i];
radix_tree_tag_clear(&fs_info->fs_roots_radix,
(unsigned long)root->root_key.objectid,
BTRFS_ROOT_TRANS_TAG);
spin_unlock(&fs_info->fs_roots_radix_lock);
btrfs_free_log(trans, root);
btrfs_update_reloc_root(trans, root);
btrfs_orphan_commit_root(trans, root);
btrfs_save_ino_cache(root, trans);
if (root->commit_root != root->node) {
mutex_lock(&root->fs_commit_mutex);
switch_commit_root(root);
btrfs_unpin_free_ino(root);
mutex_unlock(&root->fs_commit_mutex);
btrfs_set_root_node(&root->root_item,
root->node);
}
err = btrfs_update_root(trans, fs_info->tree_root,
&root->root_key,
&root->root_item);
spin_lock(&fs_info->fs_roots_radix_lock);
if (err)
break;
}
}
spin_unlock(&fs_info->fs_roots_radix_lock);
return err;
}
/*
* defrag a given btree. If cacheonly == 1, this won't read from the disk,
* otherwise every leaf in the btree is read and defragged.
*/
int btrfs_defrag_root(struct btrfs_root *root, int cacheonly)
{
struct btrfs_fs_info *info = root->fs_info;
struct btrfs_trans_handle *trans;
int ret;
unsigned long nr;
if (xchg(&root->defrag_running, 1))
return 0;
while (1) {
trans = btrfs_start_transaction(root, 0);
if (IS_ERR(trans))
return PTR_ERR(trans);
ret = btrfs_defrag_leaves(trans, root, cacheonly);
nr = trans->blocks_used;
btrfs_end_transaction(trans, root);
btrfs_btree_balance_dirty(info->tree_root, nr);
cond_resched();
if (btrfs_fs_closing(root->fs_info) || ret != -EAGAIN)
break;
}
root->defrag_running = 0;
return ret;
}
/*
* new snapshots need to be created at a very specific time in the
* transaction commit. This does the actual creation
*/
static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans,
struct btrfs_fs_info *fs_info,
struct btrfs_pending_snapshot *pending)
{
struct btrfs_key key;
struct btrfs_root_item *new_root_item;
struct btrfs_root *tree_root = fs_info->tree_root;
struct btrfs_root *root = pending->root;
struct btrfs_root *parent_root;
struct inode *parent_inode;
struct dentry *parent;
struct dentry *dentry;
struct extent_buffer *tmp;
struct extent_buffer *old;
int ret;
u64 to_reserve = 0;
u64 index = 0;
u64 objectid;
u64 root_flags;
new_root_item = kmalloc(sizeof(*new_root_item), GFP_NOFS);
if (!new_root_item) {
pending->error = -ENOMEM;
goto fail;
}
ret = btrfs_find_free_objectid(tree_root, &objectid);
if (ret) {
pending->error = ret;
goto fail;
}
btrfs_reloc_pre_snapshot(trans, pending, &to_reserve);
btrfs_orphan_pre_snapshot(trans, pending, &to_reserve);
if (to_reserve > 0) {
ret = btrfs_block_rsv_add(trans, root, &pending->block_rsv,
to_reserve);
if (ret) {
pending->error = ret;
goto fail;
}
}
key.objectid = objectid;
key.offset = (u64)-1;
key.type = BTRFS_ROOT_ITEM_KEY;
trans->block_rsv = &pending->block_rsv;
dentry = pending->dentry;
parent = dget_parent(dentry);
parent_inode = parent->d_inode;
parent_root = BTRFS_I(parent_inode)->root;
record_root_in_trans(trans, parent_root);
/*
* insert the directory item
*/
ret = btrfs_set_inode_index(parent_inode, &index);
BUG_ON(ret);
ret = btrfs_insert_dir_item(trans, parent_root,
dentry->d_name.name, dentry->d_name.len,
parent_inode, &key,
BTRFS_FT_DIR, index);
BUG_ON(ret);
btrfs_i_size_write(parent_inode, parent_inode->i_size +
dentry->d_name.len * 2);
ret = btrfs_update_inode(trans, parent_root, parent_inode);
BUG_ON(ret);
/*
* pull in the delayed directory update
* and the delayed inode item
* otherwise we corrupt the FS during
* snapshot
*/
ret = btrfs_run_delayed_items(trans, root);
BUG_ON(ret);
record_root_in_trans(trans, root);
btrfs_set_root_last_snapshot(&root->root_item, trans->transid);
memcpy(new_root_item, &root->root_item, sizeof(*new_root_item));
btrfs_check_and_init_root_item(new_root_item);
root_flags = btrfs_root_flags(new_root_item);
if (pending->readonly)
root_flags |= BTRFS_ROOT_SUBVOL_RDONLY;
else
root_flags &= ~BTRFS_ROOT_SUBVOL_RDONLY;
btrfs_set_root_flags(new_root_item, root_flags);
old = btrfs_lock_root_node(root);
btrfs_cow_block(trans, root, old, NULL, 0, &old);
btrfs_set_lock_blocking(old);
btrfs_copy_root(trans, root, old, &tmp, objectid);
btrfs_tree_unlock(old);
free_extent_buffer(old);
btrfs_set_root_node(new_root_item, tmp);
/* record when the snapshot was created in key.offset */
key.offset = trans->transid;
ret = btrfs_insert_root(trans, tree_root, &key, new_root_item);
btrfs_tree_unlock(tmp);
free_extent_buffer(tmp);
BUG_ON(ret);
/*
* insert root back/forward references
*/
ret = btrfs_add_root_ref(trans, tree_root, objectid,
parent_root->root_key.objectid,
btrfs_ino(parent_inode), index,
dentry->d_name.name, dentry->d_name.len);
BUG_ON(ret);
dput(parent);
key.offset = (u64)-1;
pending->snap = btrfs_read_fs_root_no_name(root->fs_info, &key);
BUG_ON(IS_ERR(pending->snap));
btrfs_reloc_post_snapshot(trans, pending);
btrfs_orphan_post_snapshot(trans, pending);
fail:
kfree(new_root_item);
btrfs_block_rsv_release(root, &pending->block_rsv, (u64)-1);
return 0;
}
/*
* create all the snapshots we've scheduled for creation
*/
static noinline int create_pending_snapshots(struct btrfs_trans_handle *trans,
struct btrfs_fs_info *fs_info)
{
struct btrfs_pending_snapshot *pending;
struct list_head *head = &trans->transaction->pending_snapshots;
int ret;
list_for_each_entry(pending, head, list) {
ret = create_pending_snapshot(trans, fs_info, pending);
BUG_ON(ret);
}
return 0;
}
static void update_super_roots(struct btrfs_root *root)
{
struct btrfs_root_item *root_item;
struct btrfs_super_block *super;
super = &root->fs_info->super_copy;
root_item = &root->fs_info->chunk_root->root_item;
super->chunk_root = root_item->bytenr;
super->chunk_root_generation = root_item->generation;
super->chunk_root_level = root_item->level;
root_item = &root->fs_info->tree_root->root_item;
super->root = root_item->bytenr;
super->generation = root_item->generation;
super->root_level = root_item->level;
if (super->cache_generation != 0 || btrfs_test_opt(root, SPACE_CACHE))
super->cache_generation = root_item->generation;
}
int btrfs_transaction_in_commit(struct btrfs_fs_info *info)
{
int ret = 0;
spin_lock(&info->trans_lock);
if (info->running_transaction)
ret = info->running_transaction->in_commit;
spin_unlock(&info->trans_lock);
return ret;
}
int btrfs_transaction_blocked(struct btrfs_fs_info *info)
{
int ret = 0;
spin_lock(&info->trans_lock);
if (info->running_transaction)
ret = info->running_transaction->blocked;
spin_unlock(&info->trans_lock);
return ret;
}
/*
* wait for the current transaction commit to start and block subsequent
* transaction joins
*/
static void wait_current_trans_commit_start(struct btrfs_root *root,
struct btrfs_transaction *trans)
{
DEFINE_WAIT(wait);
if (trans->in_commit)
return;
while (1) {
prepare_to_wait(&root->fs_info->transaction_blocked_wait, &wait,
TASK_UNINTERRUPTIBLE);
if (trans->in_commit) {
finish_wait(&root->fs_info->transaction_blocked_wait,
&wait);
break;
}
schedule();
finish_wait(&root->fs_info->transaction_blocked_wait, &wait);
}
}
/*
* wait for the current transaction to start and then become unblocked.
* caller holds ref.
*/
static void wait_current_trans_commit_start_and_unblock(struct btrfs_root *root,
struct btrfs_transaction *trans)
{
DEFINE_WAIT(wait);
if (trans->commit_done || (trans->in_commit && !trans->blocked))
return;
while (1) {
prepare_to_wait(&root->fs_info->transaction_wait, &wait,
TASK_UNINTERRUPTIBLE);
if (trans->commit_done ||
(trans->in_commit && !trans->blocked)) {
finish_wait(&root->fs_info->transaction_wait,
&wait);
break;
}
schedule();
finish_wait(&root->fs_info->transaction_wait,
&wait);
}
}
/*
* commit transactions asynchronously. once btrfs_commit_transaction_async
* returns, any subsequent transaction will not be allowed to join.
*/
struct btrfs_async_commit {
struct btrfs_trans_handle *newtrans;
struct btrfs_root *root;
struct delayed_work work;
};
static void do_async_commit(struct work_struct *work)
{
struct btrfs_async_commit *ac =
container_of(work, struct btrfs_async_commit, work.work);
btrfs_commit_transaction(ac->newtrans, ac->root);
kfree(ac);
}
int btrfs_commit_transaction_async(struct btrfs_trans_handle *trans,
struct btrfs_root *root,
int wait_for_unblock)
{
struct btrfs_async_commit *ac;
struct btrfs_transaction *cur_trans;
ac = kmalloc(sizeof(*ac), GFP_NOFS);
if (!ac)
return -ENOMEM;
INIT_DELAYED_WORK(&ac->work, do_async_commit);
ac->root = root;
ac->newtrans = btrfs_join_transaction(root);
if (IS_ERR(ac->newtrans)) {
int err = PTR_ERR(ac->newtrans);
kfree(ac);
return err;
}
/* take transaction reference */
cur_trans = trans->transaction;
atomic_inc(&cur_trans->use_count);
btrfs_end_transaction(trans, root);
schedule_delayed_work(&ac->work, 0);
/* wait for transaction to start and unblock */
if (wait_for_unblock)
wait_current_trans_commit_start_and_unblock(root, cur_trans);
else
wait_current_trans_commit_start(root, cur_trans);
if (current->journal_info == trans)
current->journal_info = NULL;
put_transaction(cur_trans);
return 0;
}
/*
* btrfs_transaction state sequence:
* in_commit = 0, blocked = 0 (initial)
* in_commit = 1, blocked = 1
* blocked = 0
* commit_done = 1
*/
int btrfs_commit_transaction(struct btrfs_trans_handle *trans,
struct btrfs_root *root)
{
unsigned long joined = 0;
struct btrfs_transaction *cur_trans;
struct btrfs_transaction *prev_trans = NULL;
DEFINE_WAIT(wait);
int ret;
int should_grow = 0;
unsigned long now = get_seconds();
int flush_on_commit = btrfs_test_opt(root, FLUSHONCOMMIT);
btrfs_run_ordered_operations(root, 0);
/* make a pass through all the delayed refs we have so far
* any runnings procs may add more while we are here
*/
ret = btrfs_run_delayed_refs(trans, root, 0);
BUG_ON(ret);
btrfs_trans_release_metadata(trans, root);
cur_trans = trans->transaction;
/*
* set the flushing flag so procs in this transaction have to
* start sending their work down.
*/
cur_trans->delayed_refs.flushing = 1;
ret = btrfs_run_delayed_refs(trans, root, 0);
BUG_ON(ret);
spin_lock(&cur_trans->commit_lock);
if (cur_trans->in_commit) {
spin_unlock(&cur_trans->commit_lock);
atomic_inc(&cur_trans->use_count);
btrfs_end_transaction(trans, root);
ret = wait_for_commit(root, cur_trans);
BUG_ON(ret);
put_transaction(cur_trans);
return 0;
}
trans->transaction->in_commit = 1;
trans->transaction->blocked = 1;
spin_unlock(&cur_trans->commit_lock);
wake_up(&root->fs_info->transaction_blocked_wait);
spin_lock(&root->fs_info->trans_lock);
if (cur_trans->list.prev != &root->fs_info->trans_list) {
prev_trans = list_entry(cur_trans->list.prev,
struct btrfs_transaction, list);
if (!prev_trans->commit_done) {
atomic_inc(&prev_trans->use_count);
spin_unlock(&root->fs_info->trans_lock);
wait_for_commit(root, prev_trans);
put_transaction(prev_trans);
} else {
spin_unlock(&root->fs_info->trans_lock);
}
} else {
spin_unlock(&root->fs_info->trans_lock);
}
if (now < cur_trans->start_time || now - cur_trans->start_time < 1)
should_grow = 1;
do {
int snap_pending = 0;
joined = cur_trans->num_joined;
if (!list_empty(&trans->transaction->pending_snapshots))
snap_pending = 1;
WARN_ON(cur_trans != trans->transaction);
if (flush_on_commit || snap_pending) {
btrfs_start_delalloc_inodes(root, 1);
ret = btrfs_wait_ordered_extents(root, 0, 1);
BUG_ON(ret);
}
ret = btrfs_run_delayed_items(trans, root);
BUG_ON(ret);
/*
* rename don't use btrfs_join_transaction, so, once we
* set the transaction to blocked above, we aren't going
* to get any new ordered operations. We can safely run
* it here and no for sure that nothing new will be added
* to the list
*/
btrfs_run_ordered_operations(root, 1);
prepare_to_wait(&cur_trans->writer_wait, &wait,
TASK_UNINTERRUPTIBLE);
if (atomic_read(&cur_trans->num_writers) > 1)
schedule_timeout(MAX_SCHEDULE_TIMEOUT);
else if (should_grow)
schedule_timeout(1);
finish_wait(&cur_trans->writer_wait, &wait);
} while (atomic_read(&cur_trans->num_writers) > 1 ||
(should_grow && cur_trans->num_joined != joined));
/*
* Ok now we need to make sure to block out any other joins while we
* commit the transaction. We could have started a join before setting
* no_join so make sure to wait for num_writers to == 1 again.
*/
spin_lock(&root->fs_info->trans_lock);
root->fs_info->trans_no_join = 1;
spin_unlock(&root->fs_info->trans_lock);
wait_event(cur_trans->writer_wait,
atomic_read(&cur_trans->num_writers) == 1);
/*
* the reloc mutex makes sure that we stop
* the balancing code from coming in and moving
* extents around in the middle of the commit
*/
mutex_lock(&root->fs_info->reloc_mutex);
ret = btrfs_run_delayed_items(trans, root);
BUG_ON(ret);
ret = create_pending_snapshots(trans, root->fs_info);
BUG_ON(ret);
ret = btrfs_run_delayed_refs(trans, root, (unsigned long)-1);
BUG_ON(ret);
/*
* make sure none of the code above managed to slip in a
* delayed item
*/
btrfs_assert_delayed_root_empty(root);
WARN_ON(cur_trans != trans->transaction);
btrfs_scrub_pause(root);
/* btrfs_commit_tree_roots is responsible for getting the
* various roots consistent with each other. Every pointer
* in the tree of tree roots has to point to the most up to date
* root for every subvolume and other tree. So, we have to keep
* the tree logging code from jumping in and changing any
* of the trees.
*
* At this point in the commit, there can't be any tree-log
* writers, but a little lower down we drop the trans mutex
* and let new people in. By holding the tree_log_mutex
* from now until after the super is written, we avoid races
* with the tree-log code.
*/
mutex_lock(&root->fs_info->tree_log_mutex);
ret = commit_fs_roots(trans, root);
BUG_ON(ret);
/* commit_fs_roots gets rid of all the tree log roots, it is now
* safe to free the root of tree log roots
*/
btrfs_free_log_root_tree(trans, root->fs_info);
ret = commit_cowonly_roots(trans, root);
BUG_ON(ret);
btrfs_prepare_extent_commit(trans, root);
cur_trans = root->fs_info->running_transaction;
btrfs_set_root_node(&root->fs_info->tree_root->root_item,
root->fs_info->tree_root->node);
switch_commit_root(root->fs_info->tree_root);
btrfs_set_root_node(&root->fs_info->chunk_root->root_item,
root->fs_info->chunk_root->node);
switch_commit_root(root->fs_info->chunk_root);
update_super_roots(root);
if (!root->fs_info->log_root_recovering) {
btrfs_set_super_log_root(&root->fs_info->super_copy, 0);
btrfs_set_super_log_root_level(&root->fs_info->super_copy, 0);
}
memcpy(&root->fs_info->super_for_commit, &root->fs_info->super_copy,
sizeof(root->fs_info->super_copy));
trans->transaction->blocked = 0;
spin_lock(&root->fs_info->trans_lock);
root->fs_info->running_transaction = NULL;
root->fs_info->trans_no_join = 0;
spin_unlock(&root->fs_info->trans_lock);
mutex_unlock(&root->fs_info->reloc_mutex);
wake_up(&root->fs_info->transaction_wait);
ret = btrfs_write_and_wait_transaction(trans, root);
BUG_ON(ret);
write_ctree_super(trans, root, 0);
/*
* the super is written, we can safely allow the tree-loggers
* to go about their business
*/
mutex_unlock(&root->fs_info->tree_log_mutex);
btrfs_finish_extent_commit(trans, root);
cur_trans->commit_done = 1;
root->fs_info->last_trans_committed = cur_trans->transid;
wake_up(&cur_trans->commit_wait);
spin_lock(&root->fs_info->trans_lock);
list_del_init(&cur_trans->list);
spin_unlock(&root->fs_info->trans_lock);
put_transaction(cur_trans);
put_transaction(cur_trans);
trace_btrfs_transaction_commit(root);
btrfs_scrub_continue(root);
if (current->journal_info == trans)
current->journal_info = NULL;
kmem_cache_free(btrfs_trans_handle_cachep, trans);
if (current != root->fs_info->transaction_kthread)
btrfs_run_delayed_iputs(root);
return ret;
}
/*
* interface function to delete all the snapshots we have scheduled for deletion
*/
int btrfs_clean_old_snapshots(struct btrfs_root *root)
{
LIST_HEAD(list);
struct btrfs_fs_info *fs_info = root->fs_info;
spin_lock(&fs_info->trans_lock);
list_splice_init(&fs_info->dead_roots, &list);
spin_unlock(&fs_info->trans_lock);
while (!list_empty(&list)) {
root = list_entry(list.next, struct btrfs_root, root_list);
list_del(&root->root_list);
btrfs_kill_all_delayed_nodes(root);
if (btrfs_header_backref_rev(root->node) <
BTRFS_MIXED_BACKREF_REV)
btrfs_drop_snapshot(root, NULL, 0);
else
btrfs_drop_snapshot(root, NULL, 1);
}
return 0;
}
| gpl-2.0 |
alvinhochun/sony-nicki-ss-kernel-caf | drivers/acpi/acpica/utdebug.c | 4919 | 19337 | /******************************************************************************
*
* Module Name: utdebug - Debug print routines
*
*****************************************************************************/
/*
* Copyright (C) 2000 - 2012, 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 <linux/export.h>
#include <acpi/acpi.h>
#include "accommon.h"
#define _COMPONENT ACPI_UTILITIES
ACPI_MODULE_NAME("utdebug")
#ifdef ACPI_DEBUG_OUTPUT
static acpi_thread_id acpi_gbl_prev_thread_id;
static char *acpi_gbl_fn_entry_str = "----Entry";
static char *acpi_gbl_fn_exit_str = "----Exit-";
/* Local prototypes */
static const char *acpi_ut_trim_function_name(const char *function_name);
/*******************************************************************************
*
* FUNCTION: acpi_ut_init_stack_ptr_trace
*
* PARAMETERS: None
*
* RETURN: None
*
* DESCRIPTION: Save the current CPU stack pointer at subsystem startup
*
******************************************************************************/
void acpi_ut_init_stack_ptr_trace(void)
{
acpi_size current_sp;
acpi_gbl_entry_stack_pointer = ¤t_sp;
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_track_stack_ptr
*
* PARAMETERS: None
*
* RETURN: None
*
* DESCRIPTION: Save the current CPU stack pointer
*
******************************************************************************/
void acpi_ut_track_stack_ptr(void)
{
acpi_size current_sp;
if (¤t_sp < acpi_gbl_lowest_stack_pointer) {
acpi_gbl_lowest_stack_pointer = ¤t_sp;
}
if (acpi_gbl_nesting_level > acpi_gbl_deepest_nesting) {
acpi_gbl_deepest_nesting = acpi_gbl_nesting_level;
}
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_trim_function_name
*
* PARAMETERS: function_name - Ascii string containing a procedure name
*
* RETURN: Updated pointer to the function name
*
* DESCRIPTION: Remove the "Acpi" prefix from the function name, if present.
* This allows compiler macros such as __func__ to be used
* with no change to the debug output.
*
******************************************************************************/
static const char *acpi_ut_trim_function_name(const char *function_name)
{
/* All Function names are longer than 4 chars, check is safe */
if (*(ACPI_CAST_PTR(u32, function_name)) == ACPI_PREFIX_MIXED) {
/* This is the case where the original source has not been modified */
return (function_name + 4);
}
if (*(ACPI_CAST_PTR(u32, function_name)) == ACPI_PREFIX_LOWER) {
/* This is the case where the source has been 'linuxized' */
return (function_name + 5);
}
return (function_name);
}
/*******************************************************************************
*
* FUNCTION: acpi_debug_print
*
* PARAMETERS: requested_debug_level - Requested debug print level
* line_number - Caller's line number (for error output)
* function_name - Caller's procedure name
* module_name - Caller's module name
* component_id - Caller's component ID
* Format - Printf format field
* ... - Optional printf arguments
*
* RETURN: None
*
* DESCRIPTION: Print error message with prefix consisting of the module name,
* line number, and component ID.
*
******************************************************************************/
void ACPI_INTERNAL_VAR_XFACE
acpi_debug_print(u32 requested_debug_level,
u32 line_number,
const char *function_name,
const char *module_name,
u32 component_id, const char *format, ...)
{
acpi_thread_id thread_id;
va_list args;
/*
* Stay silent if the debug level or component ID is disabled
*/
if (!(requested_debug_level & acpi_dbg_level) ||
!(component_id & acpi_dbg_layer)) {
return;
}
/*
* Thread tracking and context switch notification
*/
thread_id = acpi_os_get_thread_id();
if (thread_id != acpi_gbl_prev_thread_id) {
if (ACPI_LV_THREADS & acpi_dbg_level) {
acpi_os_printf
("\n**** Context Switch from TID %u to TID %u ****\n\n",
(u32)acpi_gbl_prev_thread_id, (u32)thread_id);
}
acpi_gbl_prev_thread_id = thread_id;
}
/*
* Display the module name, current line number, thread ID (if requested),
* current procedure nesting level, and the current procedure name
*/
acpi_os_printf("%8s-%04ld ", module_name, line_number);
if (ACPI_LV_THREADS & acpi_dbg_level) {
acpi_os_printf("[%u] ", (u32)thread_id);
}
acpi_os_printf("[%02ld] %-22.22s: ",
acpi_gbl_nesting_level,
acpi_ut_trim_function_name(function_name));
va_start(args, format);
acpi_os_vprintf(format, args);
va_end(args);
}
ACPI_EXPORT_SYMBOL(acpi_debug_print)
/*******************************************************************************
*
* FUNCTION: acpi_debug_print_raw
*
* PARAMETERS: requested_debug_level - Requested debug print level
* line_number - Caller's line number
* function_name - Caller's procedure name
* module_name - Caller's module name
* component_id - Caller's component ID
* Format - Printf format field
* ... - Optional printf arguments
*
* RETURN: None
*
* DESCRIPTION: Print message with no headers. Has same interface as
* debug_print so that the same macros can be used.
*
******************************************************************************/
void ACPI_INTERNAL_VAR_XFACE
acpi_debug_print_raw(u32 requested_debug_level,
u32 line_number,
const char *function_name,
const char *module_name,
u32 component_id, const char *format, ...)
{
va_list args;
if (!(requested_debug_level & acpi_dbg_level) ||
!(component_id & acpi_dbg_layer)) {
return;
}
va_start(args, format);
acpi_os_vprintf(format, args);
va_end(args);
}
ACPI_EXPORT_SYMBOL(acpi_debug_print_raw)
/*******************************************************************************
*
* FUNCTION: acpi_ut_trace
*
* PARAMETERS: line_number - Caller's line number
* function_name - Caller's procedure name
* module_name - Caller's module name
* component_id - Caller's component ID
*
* RETURN: None
*
* DESCRIPTION: Function entry trace. Prints only if TRACE_FUNCTIONS bit is
* set in debug_level
*
******************************************************************************/
void
acpi_ut_trace(u32 line_number,
const char *function_name,
const char *module_name, u32 component_id)
{
acpi_gbl_nesting_level++;
acpi_ut_track_stack_ptr();
acpi_debug_print(ACPI_LV_FUNCTIONS,
line_number, function_name, module_name, component_id,
"%s\n", acpi_gbl_fn_entry_str);
}
ACPI_EXPORT_SYMBOL(acpi_ut_trace)
/*******************************************************************************
*
* FUNCTION: acpi_ut_trace_ptr
*
* PARAMETERS: line_number - Caller's line number
* function_name - Caller's procedure name
* module_name - Caller's module name
* component_id - Caller's component ID
* Pointer - Pointer to display
*
* RETURN: None
*
* DESCRIPTION: Function entry trace. Prints only if TRACE_FUNCTIONS bit is
* set in debug_level
*
******************************************************************************/
void
acpi_ut_trace_ptr(u32 line_number,
const char *function_name,
const char *module_name, u32 component_id, void *pointer)
{
acpi_gbl_nesting_level++;
acpi_ut_track_stack_ptr();
acpi_debug_print(ACPI_LV_FUNCTIONS,
line_number, function_name, module_name, component_id,
"%s %p\n", acpi_gbl_fn_entry_str, pointer);
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_trace_str
*
* PARAMETERS: line_number - Caller's line number
* function_name - Caller's procedure name
* module_name - Caller's module name
* component_id - Caller's component ID
* String - Additional string to display
*
* RETURN: None
*
* DESCRIPTION: Function entry trace. Prints only if TRACE_FUNCTIONS bit is
* set in debug_level
*
******************************************************************************/
void
acpi_ut_trace_str(u32 line_number,
const char *function_name,
const char *module_name, u32 component_id, char *string)
{
acpi_gbl_nesting_level++;
acpi_ut_track_stack_ptr();
acpi_debug_print(ACPI_LV_FUNCTIONS,
line_number, function_name, module_name, component_id,
"%s %s\n", acpi_gbl_fn_entry_str, string);
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_trace_u32
*
* PARAMETERS: line_number - Caller's line number
* function_name - Caller's procedure name
* module_name - Caller's module name
* component_id - Caller's component ID
* Integer - Integer to display
*
* RETURN: None
*
* DESCRIPTION: Function entry trace. Prints only if TRACE_FUNCTIONS bit is
* set in debug_level
*
******************************************************************************/
void
acpi_ut_trace_u32(u32 line_number,
const char *function_name,
const char *module_name, u32 component_id, u32 integer)
{
acpi_gbl_nesting_level++;
acpi_ut_track_stack_ptr();
acpi_debug_print(ACPI_LV_FUNCTIONS,
line_number, function_name, module_name, component_id,
"%s %08X\n", acpi_gbl_fn_entry_str, integer);
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_exit
*
* PARAMETERS: line_number - Caller's line number
* function_name - Caller's procedure name
* module_name - Caller's module name
* component_id - Caller's component ID
*
* RETURN: None
*
* DESCRIPTION: Function exit trace. Prints only if TRACE_FUNCTIONS bit is
* set in debug_level
*
******************************************************************************/
void
acpi_ut_exit(u32 line_number,
const char *function_name,
const char *module_name, u32 component_id)
{
acpi_debug_print(ACPI_LV_FUNCTIONS,
line_number, function_name, module_name, component_id,
"%s\n", acpi_gbl_fn_exit_str);
acpi_gbl_nesting_level--;
}
ACPI_EXPORT_SYMBOL(acpi_ut_exit)
/*******************************************************************************
*
* FUNCTION: acpi_ut_status_exit
*
* PARAMETERS: line_number - Caller's line number
* function_name - Caller's procedure name
* module_name - Caller's module name
* component_id - Caller's component ID
* Status - Exit status code
*
* RETURN: None
*
* DESCRIPTION: Function exit trace. Prints only if TRACE_FUNCTIONS bit is
* set in debug_level. Prints exit status also.
*
******************************************************************************/
void
acpi_ut_status_exit(u32 line_number,
const char *function_name,
const char *module_name,
u32 component_id, acpi_status status)
{
if (ACPI_SUCCESS(status)) {
acpi_debug_print(ACPI_LV_FUNCTIONS,
line_number, function_name, module_name,
component_id, "%s %s\n", acpi_gbl_fn_exit_str,
acpi_format_exception(status));
} else {
acpi_debug_print(ACPI_LV_FUNCTIONS,
line_number, function_name, module_name,
component_id, "%s ****Exception****: %s\n",
acpi_gbl_fn_exit_str,
acpi_format_exception(status));
}
acpi_gbl_nesting_level--;
}
ACPI_EXPORT_SYMBOL(acpi_ut_status_exit)
/*******************************************************************************
*
* FUNCTION: acpi_ut_value_exit
*
* PARAMETERS: line_number - Caller's line number
* function_name - Caller's procedure name
* module_name - Caller's module name
* component_id - Caller's component ID
* Value - Value to be printed with exit msg
*
* RETURN: None
*
* DESCRIPTION: Function exit trace. Prints only if TRACE_FUNCTIONS bit is
* set in debug_level. Prints exit value also.
*
******************************************************************************/
void
acpi_ut_value_exit(u32 line_number,
const char *function_name,
const char *module_name, u32 component_id, u64 value)
{
acpi_debug_print(ACPI_LV_FUNCTIONS,
line_number, function_name, module_name, component_id,
"%s %8.8X%8.8X\n", acpi_gbl_fn_exit_str,
ACPI_FORMAT_UINT64(value));
acpi_gbl_nesting_level--;
}
ACPI_EXPORT_SYMBOL(acpi_ut_value_exit)
/*******************************************************************************
*
* FUNCTION: acpi_ut_ptr_exit
*
* PARAMETERS: line_number - Caller's line number
* function_name - Caller's procedure name
* module_name - Caller's module name
* component_id - Caller's component ID
* Ptr - Pointer to display
*
* RETURN: None
*
* DESCRIPTION: Function exit trace. Prints only if TRACE_FUNCTIONS bit is
* set in debug_level. Prints exit value also.
*
******************************************************************************/
void
acpi_ut_ptr_exit(u32 line_number,
const char *function_name,
const char *module_name, u32 component_id, u8 *ptr)
{
acpi_debug_print(ACPI_LV_FUNCTIONS,
line_number, function_name, module_name, component_id,
"%s %p\n", acpi_gbl_fn_exit_str, ptr);
acpi_gbl_nesting_level--;
}
#endif
/*******************************************************************************
*
* FUNCTION: acpi_ut_dump_buffer
*
* PARAMETERS: Buffer - Buffer to dump
* Count - Amount to dump, in bytes
* Display - BYTE, WORD, DWORD, or QWORD display
* component_iD - Caller's component ID
*
* RETURN: None
*
* DESCRIPTION: Generic dump buffer in both hex and ascii.
*
******************************************************************************/
void acpi_ut_dump_buffer2(u8 * buffer, u32 count, u32 display)
{
u32 i = 0;
u32 j;
u32 temp32;
u8 buf_char;
if (!buffer) {
acpi_os_printf("Null Buffer Pointer in DumpBuffer!\n");
return;
}
if ((count < 4) || (count & 0x01)) {
display = DB_BYTE_DISPLAY;
}
/* Nasty little dump buffer routine! */
while (i < count) {
/* Print current offset */
acpi_os_printf("%6.4X: ", i);
/* Print 16 hex chars */
for (j = 0; j < 16;) {
if (i + j >= count) {
/* Dump fill spaces */
acpi_os_printf("%*s", ((display * 2) + 1), " ");
j += display;
continue;
}
switch (display) {
case DB_BYTE_DISPLAY:
default: /* Default is BYTE display */
acpi_os_printf("%02X ",
buffer[(acpi_size) i + j]);
break;
case DB_WORD_DISPLAY:
ACPI_MOVE_16_TO_32(&temp32,
&buffer[(acpi_size) i + j]);
acpi_os_printf("%04X ", temp32);
break;
case DB_DWORD_DISPLAY:
ACPI_MOVE_32_TO_32(&temp32,
&buffer[(acpi_size) i + j]);
acpi_os_printf("%08X ", temp32);
break;
case DB_QWORD_DISPLAY:
ACPI_MOVE_32_TO_32(&temp32,
&buffer[(acpi_size) i + j]);
acpi_os_printf("%08X", temp32);
ACPI_MOVE_32_TO_32(&temp32,
&buffer[(acpi_size) i + j +
4]);
acpi_os_printf("%08X ", temp32);
break;
}
j += display;
}
/*
* Print the ASCII equivalent characters but watch out for the bad
* unprintable ones (printable chars are 0x20 through 0x7E)
*/
acpi_os_printf(" ");
for (j = 0; j < 16; j++) {
if (i + j >= count) {
acpi_os_printf("\n");
return;
}
buf_char = buffer[(acpi_size) i + j];
if (ACPI_IS_PRINT(buf_char)) {
acpi_os_printf("%c", buf_char);
} else {
acpi_os_printf(".");
}
}
/* Done with that line. */
acpi_os_printf("\n");
i += 16;
}
return;
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_dump_buffer
*
* PARAMETERS: Buffer - Buffer to dump
* Count - Amount to dump, in bytes
* Display - BYTE, WORD, DWORD, or QWORD display
* component_iD - Caller's component ID
*
* RETURN: None
*
* DESCRIPTION: Generic dump buffer in both hex and ascii.
*
******************************************************************************/
void acpi_ut_dump_buffer(u8 * buffer, u32 count, u32 display, u32 component_id)
{
/* Only dump the buffer if tracing is enabled */
if (!((ACPI_LV_TABLES & acpi_dbg_level) &&
(component_id & acpi_dbg_layer))) {
return;
}
acpi_ut_dump_buffer2(buffer, count, display);
}
| gpl-2.0 |
lawnn/Linux_3.4.y | drivers/acpi/acpica/nsload.c | 4919 | 9106 | /******************************************************************************
*
* Module Name: nsload - namespace loading/expanding/contracting procedures
*
*****************************************************************************/
/*
* Copyright (C) 2000 - 2012, 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"
#include "acdispat.h"
#include "actables.h"
#define _COMPONENT ACPI_NAMESPACE
ACPI_MODULE_NAME("nsload")
/* Local prototypes */
#ifdef ACPI_FUTURE_IMPLEMENTATION
acpi_status acpi_ns_unload_namespace(acpi_handle handle);
static acpi_status acpi_ns_delete_subtree(acpi_handle start_handle);
#endif
#ifndef ACPI_NO_METHOD_EXECUTION
/*******************************************************************************
*
* FUNCTION: acpi_ns_load_table
*
* PARAMETERS: table_index - Index for table to be loaded
* Node - Owning NS node
*
* RETURN: Status
*
* DESCRIPTION: Load one ACPI table into the namespace
*
******************************************************************************/
acpi_status
acpi_ns_load_table(u32 table_index, struct acpi_namespace_node *node)
{
acpi_status status;
ACPI_FUNCTION_TRACE(ns_load_table);
/*
* Parse the table and load the namespace with all named
* objects found within. Control methods are NOT parsed
* at this time. In fact, the control methods cannot be
* parsed until the entire namespace is loaded, because
* if a control method makes a forward reference (call)
* to another control method, we can't continue parsing
* because we don't know how many arguments to parse next!
*/
status = acpi_ut_acquire_mutex(ACPI_MTX_NAMESPACE);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
/* If table already loaded into namespace, just return */
if (acpi_tb_is_table_loaded(table_index)) {
status = AE_ALREADY_EXISTS;
goto unlock;
}
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"**** Loading table into namespace ****\n"));
status = acpi_tb_allocate_owner_id(table_index);
if (ACPI_FAILURE(status)) {
goto unlock;
}
status = acpi_ns_parse_table(table_index, node);
if (ACPI_SUCCESS(status)) {
acpi_tb_set_table_loaded_flag(table_index, TRUE);
} else {
(void)acpi_tb_release_owner_id(table_index);
}
unlock:
(void)acpi_ut_release_mutex(ACPI_MTX_NAMESPACE);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
/*
* Now we can parse the control methods. We always parse
* them here for a sanity check, and if configured for
* just-in-time parsing, we delete the control method
* parse trees.
*/
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"**** Begin Table Method Parsing and Object Initialization\n"));
status = acpi_ds_initialize_objects(table_index, node);
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"**** Completed Table Method Parsing and Object Initialization\n"));
return_ACPI_STATUS(status);
}
#ifdef ACPI_OBSOLETE_FUNCTIONS
/*******************************************************************************
*
* FUNCTION: acpi_load_namespace
*
* PARAMETERS: None
*
* RETURN: Status
*
* DESCRIPTION: Load the name space from what ever is pointed to by DSDT.
* (DSDT points to either the BIOS or a buffer.)
*
******************************************************************************/
acpi_status acpi_ns_load_namespace(void)
{
acpi_status status;
ACPI_FUNCTION_TRACE(acpi_load_name_space);
/* There must be at least a DSDT installed */
if (acpi_gbl_DSDT == NULL) {
ACPI_ERROR((AE_INFO, "DSDT is not in memory"));
return_ACPI_STATUS(AE_NO_ACPI_TABLES);
}
/*
* Load the namespace. The DSDT is required,
* but the SSDT and PSDT tables are optional.
*/
status = acpi_ns_load_table_by_type(ACPI_TABLE_ID_DSDT);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
/* Ignore exceptions from these */
(void)acpi_ns_load_table_by_type(ACPI_TABLE_ID_SSDT);
(void)acpi_ns_load_table_by_type(ACPI_TABLE_ID_PSDT);
ACPI_DEBUG_PRINT_RAW((ACPI_DB_INIT,
"ACPI Namespace successfully loaded at root %p\n",
acpi_gbl_root_node));
return_ACPI_STATUS(status);
}
#endif
#ifdef ACPI_FUTURE_IMPLEMENTATION
/*******************************************************************************
*
* FUNCTION: acpi_ns_delete_subtree
*
* PARAMETERS: start_handle - Handle in namespace where search begins
*
* RETURNS Status
*
* DESCRIPTION: Walks the namespace starting at the given handle and deletes
* all objects, entries, and scopes in the entire subtree.
*
* Namespace/Interpreter should be locked or the subsystem should
* be in shutdown before this routine is called.
*
******************************************************************************/
static acpi_status acpi_ns_delete_subtree(acpi_handle start_handle)
{
acpi_status status;
acpi_handle child_handle;
acpi_handle parent_handle;
acpi_handle next_child_handle;
acpi_handle dummy;
u32 level;
ACPI_FUNCTION_TRACE(ns_delete_subtree);
parent_handle = start_handle;
child_handle = NULL;
level = 1;
/*
* Traverse the tree of objects until we bubble back up
* to where we started.
*/
while (level > 0) {
/* Attempt to get the next object in this scope */
status = acpi_get_next_object(ACPI_TYPE_ANY, parent_handle,
child_handle, &next_child_handle);
child_handle = next_child_handle;
/* Did we get a new object? */
if (ACPI_SUCCESS(status)) {
/* Check if this object has any children */
if (ACPI_SUCCESS
(acpi_get_next_object
(ACPI_TYPE_ANY, child_handle, NULL, &dummy))) {
/*
* There is at least one child of this object,
* visit the object
*/
level++;
parent_handle = child_handle;
child_handle = NULL;
}
} else {
/*
* No more children in this object, go back up to
* the object's parent
*/
level--;
/* Delete all children now */
acpi_ns_delete_children(child_handle);
child_handle = parent_handle;
status = acpi_get_parent(parent_handle, &parent_handle);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
}
}
/* Now delete the starting object, and we are done */
acpi_ns_remove_node(child_handle);
return_ACPI_STATUS(AE_OK);
}
/*******************************************************************************
*
* FUNCTION: acpi_ns_unload_name_space
*
* PARAMETERS: Handle - Root of namespace subtree to be deleted
*
* RETURN: Status
*
* DESCRIPTION: Shrinks the namespace, typically in response to an undocking
* event. Deletes an entire subtree starting from (and
* including) the given handle.
*
******************************************************************************/
acpi_status acpi_ns_unload_namespace(acpi_handle handle)
{
acpi_status status;
ACPI_FUNCTION_TRACE(ns_unload_name_space);
/* Parameter validation */
if (!acpi_gbl_root_node) {
return_ACPI_STATUS(AE_NO_NAMESPACE);
}
if (!handle) {
return_ACPI_STATUS(AE_BAD_PARAMETER);
}
/* This function does the real work */
status = acpi_ns_delete_subtree(handle);
return_ACPI_STATUS(status);
}
#endif
#endif
| gpl-2.0 |
eoghan2t9/android_kernel_oppo_find5 | drivers/acpi/acpica/exconvrt.c | 4919 | 17863 | /******************************************************************************
*
* Module Name: exconvrt - Object conversion routines
*
*****************************************************************************/
/*
* Copyright (C) 2000 - 2012, 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 "acinterp.h"
#include "amlcode.h"
#define _COMPONENT ACPI_EXECUTER
ACPI_MODULE_NAME("exconvrt")
/* Local prototypes */
static u32
acpi_ex_convert_to_ascii(u64 integer, u16 base, u8 *string, u8 max_length);
/*******************************************************************************
*
* FUNCTION: acpi_ex_convert_to_integer
*
* PARAMETERS: obj_desc - Object to be converted. Must be an
* Integer, Buffer, or String
* result_desc - Where the new Integer object is returned
* Flags - Used for string conversion
*
* RETURN: Status
*
* DESCRIPTION: Convert an ACPI Object to an integer.
*
******************************************************************************/
acpi_status
acpi_ex_convert_to_integer(union acpi_operand_object *obj_desc,
union acpi_operand_object **result_desc, u32 flags)
{
union acpi_operand_object *return_desc;
u8 *pointer;
u64 result;
u32 i;
u32 count;
acpi_status status;
ACPI_FUNCTION_TRACE_PTR(ex_convert_to_integer, obj_desc);
switch (obj_desc->common.type) {
case ACPI_TYPE_INTEGER:
/* No conversion necessary */
*result_desc = obj_desc;
return_ACPI_STATUS(AE_OK);
case ACPI_TYPE_BUFFER:
case ACPI_TYPE_STRING:
/* Note: Takes advantage of common buffer/string fields */
pointer = obj_desc->buffer.pointer;
count = obj_desc->buffer.length;
break;
default:
return_ACPI_STATUS(AE_TYPE);
}
/*
* Convert the buffer/string to an integer. Note that both buffers and
* strings are treated as raw data - we don't convert ascii to hex for
* strings.
*
* There are two terminating conditions for the loop:
* 1) The size of an integer has been reached, or
* 2) The end of the buffer or string has been reached
*/
result = 0;
/* String conversion is different than Buffer conversion */
switch (obj_desc->common.type) {
case ACPI_TYPE_STRING:
/*
* Convert string to an integer - for most cases, the string must be
* hexadecimal as per the ACPI specification. The only exception (as
* of ACPI 3.0) is that the to_integer() operator allows both decimal
* and hexadecimal strings (hex prefixed with "0x").
*/
status = acpi_ut_strtoul64((char *)pointer, flags, &result);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
break;
case ACPI_TYPE_BUFFER:
/* Check for zero-length buffer */
if (!count) {
return_ACPI_STATUS(AE_AML_BUFFER_LIMIT);
}
/* Transfer no more than an integer's worth of data */
if (count > acpi_gbl_integer_byte_width) {
count = acpi_gbl_integer_byte_width;
}
/*
* Convert buffer to an integer - we simply grab enough raw data
* from the buffer to fill an integer
*/
for (i = 0; i < count; i++) {
/*
* Get next byte and shift it into the Result.
* Little endian is used, meaning that the first byte of the buffer
* is the LSB of the integer
*/
result |= (((u64) pointer[i]) << (i * 8));
}
break;
default:
/* No other types can get here */
break;
}
/* Create a new integer */
return_desc = acpi_ut_create_integer_object(result);
if (!return_desc) {
return_ACPI_STATUS(AE_NO_MEMORY);
}
ACPI_DEBUG_PRINT((ACPI_DB_EXEC, "Converted value: %8.8X%8.8X\n",
ACPI_FORMAT_UINT64(result)));
/* Save the Result */
acpi_ex_truncate_for32bit_table(return_desc);
*result_desc = return_desc;
return_ACPI_STATUS(AE_OK);
}
/*******************************************************************************
*
* FUNCTION: acpi_ex_convert_to_buffer
*
* PARAMETERS: obj_desc - Object to be converted. Must be an
* Integer, Buffer, or String
* result_desc - Where the new buffer object is returned
*
* RETURN: Status
*
* DESCRIPTION: Convert an ACPI Object to a Buffer
*
******************************************************************************/
acpi_status
acpi_ex_convert_to_buffer(union acpi_operand_object *obj_desc,
union acpi_operand_object **result_desc)
{
union acpi_operand_object *return_desc;
u8 *new_buf;
ACPI_FUNCTION_TRACE_PTR(ex_convert_to_buffer, obj_desc);
switch (obj_desc->common.type) {
case ACPI_TYPE_BUFFER:
/* No conversion necessary */
*result_desc = obj_desc;
return_ACPI_STATUS(AE_OK);
case ACPI_TYPE_INTEGER:
/*
* Create a new Buffer object.
* Need enough space for one integer
*/
return_desc =
acpi_ut_create_buffer_object(acpi_gbl_integer_byte_width);
if (!return_desc) {
return_ACPI_STATUS(AE_NO_MEMORY);
}
/* Copy the integer to the buffer, LSB first */
new_buf = return_desc->buffer.pointer;
ACPI_MEMCPY(new_buf,
&obj_desc->integer.value,
acpi_gbl_integer_byte_width);
break;
case ACPI_TYPE_STRING:
/*
* Create a new Buffer object
* Size will be the string length
*
* NOTE: Add one to the string length to include the null terminator.
* The ACPI spec is unclear on this subject, but there is existing
* ASL/AML code that depends on the null being transferred to the new
* buffer.
*/
return_desc = acpi_ut_create_buffer_object((acpi_size)
obj_desc->string.
length + 1);
if (!return_desc) {
return_ACPI_STATUS(AE_NO_MEMORY);
}
/* Copy the string to the buffer */
new_buf = return_desc->buffer.pointer;
ACPI_STRNCPY((char *)new_buf, (char *)obj_desc->string.pointer,
obj_desc->string.length);
break;
default:
return_ACPI_STATUS(AE_TYPE);
}
/* Mark buffer initialized */
return_desc->common.flags |= AOPOBJ_DATA_VALID;
*result_desc = return_desc;
return_ACPI_STATUS(AE_OK);
}
/*******************************************************************************
*
* FUNCTION: acpi_ex_convert_to_ascii
*
* PARAMETERS: Integer - Value to be converted
* Base - ACPI_STRING_DECIMAL or ACPI_STRING_HEX
* String - Where the string is returned
* data_width - Size of data item to be converted, in bytes
*
* RETURN: Actual string length
*
* DESCRIPTION: Convert an ACPI Integer to a hex or decimal string
*
******************************************************************************/
static u32
acpi_ex_convert_to_ascii(u64 integer, u16 base, u8 *string, u8 data_width)
{
u64 digit;
u32 i;
u32 j;
u32 k = 0;
u32 hex_length;
u32 decimal_length;
u32 remainder;
u8 supress_zeros;
ACPI_FUNCTION_ENTRY();
switch (base) {
case 10:
/* Setup max length for the decimal number */
switch (data_width) {
case 1:
decimal_length = ACPI_MAX8_DECIMAL_DIGITS;
break;
case 4:
decimal_length = ACPI_MAX32_DECIMAL_DIGITS;
break;
case 8:
default:
decimal_length = ACPI_MAX64_DECIMAL_DIGITS;
break;
}
supress_zeros = TRUE; /* No leading zeros */
remainder = 0;
for (i = decimal_length; i > 0; i--) {
/* Divide by nth factor of 10 */
digit = integer;
for (j = 0; j < i; j++) {
(void)acpi_ut_short_divide(digit, 10, &digit,
&remainder);
}
/* Handle leading zeros */
if (remainder != 0) {
supress_zeros = FALSE;
}
if (!supress_zeros) {
string[k] = (u8) (ACPI_ASCII_ZERO + remainder);
k++;
}
}
break;
case 16:
/* hex_length: 2 ascii hex chars per data byte */
hex_length = ACPI_MUL_2(data_width);
for (i = 0, j = (hex_length - 1); i < hex_length; i++, j--) {
/* Get one hex digit, most significant digits first */
string[k] =
(u8) acpi_ut_hex_to_ascii_char(integer,
ACPI_MUL_4(j));
k++;
}
break;
default:
return (0);
}
/*
* Since leading zeros are suppressed, we must check for the case where
* the integer equals 0
*
* Finally, null terminate the string and return the length
*/
if (!k) {
string[0] = ACPI_ASCII_ZERO;
k = 1;
}
string[k] = 0;
return ((u32) k);
}
/*******************************************************************************
*
* FUNCTION: acpi_ex_convert_to_string
*
* PARAMETERS: obj_desc - Object to be converted. Must be an
* Integer, Buffer, or String
* result_desc - Where the string object is returned
* Type - String flags (base and conversion type)
*
* RETURN: Status
*
* DESCRIPTION: Convert an ACPI Object to a string
*
******************************************************************************/
acpi_status
acpi_ex_convert_to_string(union acpi_operand_object * obj_desc,
union acpi_operand_object ** result_desc, u32 type)
{
union acpi_operand_object *return_desc;
u8 *new_buf;
u32 i;
u32 string_length = 0;
u16 base = 16;
u8 separator = ',';
ACPI_FUNCTION_TRACE_PTR(ex_convert_to_string, obj_desc);
switch (obj_desc->common.type) {
case ACPI_TYPE_STRING:
/* No conversion necessary */
*result_desc = obj_desc;
return_ACPI_STATUS(AE_OK);
case ACPI_TYPE_INTEGER:
switch (type) {
case ACPI_EXPLICIT_CONVERT_DECIMAL:
/* Make room for maximum decimal number */
string_length = ACPI_MAX_DECIMAL_DIGITS;
base = 10;
break;
default:
/* Two hex string characters for each integer byte */
string_length = ACPI_MUL_2(acpi_gbl_integer_byte_width);
break;
}
/*
* Create a new String
* Need enough space for one ASCII integer (plus null terminator)
*/
return_desc =
acpi_ut_create_string_object((acpi_size) string_length);
if (!return_desc) {
return_ACPI_STATUS(AE_NO_MEMORY);
}
new_buf = return_desc->buffer.pointer;
/* Convert integer to string */
string_length =
acpi_ex_convert_to_ascii(obj_desc->integer.value, base,
new_buf,
acpi_gbl_integer_byte_width);
/* Null terminate at the correct place */
return_desc->string.length = string_length;
new_buf[string_length] = 0;
break;
case ACPI_TYPE_BUFFER:
/* Setup string length, base, and separator */
switch (type) {
case ACPI_EXPLICIT_CONVERT_DECIMAL: /* Used by to_decimal_string */
/*
* From ACPI: "If Data is a buffer, it is converted to a string of
* decimal values separated by commas."
*/
base = 10;
/*
* Calculate the final string length. Individual string values
* are variable length (include separator for each)
*/
for (i = 0; i < obj_desc->buffer.length; i++) {
if (obj_desc->buffer.pointer[i] >= 100) {
string_length += 4;
} else if (obj_desc->buffer.pointer[i] >= 10) {
string_length += 3;
} else {
string_length += 2;
}
}
break;
case ACPI_IMPLICIT_CONVERT_HEX:
/*
* From the ACPI spec:
*"The entire contents of the buffer are converted to a string of
* two-character hexadecimal numbers, each separated by a space."
*/
separator = ' ';
string_length = (obj_desc->buffer.length * 3);
break;
case ACPI_EXPLICIT_CONVERT_HEX: /* Used by to_hex_string */
/*
* From ACPI: "If Data is a buffer, it is converted to a string of
* hexadecimal values separated by commas."
*/
string_length = (obj_desc->buffer.length * 3);
break;
default:
return_ACPI_STATUS(AE_BAD_PARAMETER);
}
/*
* Create a new string object and string buffer
* (-1 because of extra separator included in string_length from above)
* Allow creation of zero-length strings from zero-length buffers.
*/
if (string_length) {
string_length--;
}
return_desc = acpi_ut_create_string_object((acpi_size)
string_length);
if (!return_desc) {
return_ACPI_STATUS(AE_NO_MEMORY);
}
new_buf = return_desc->buffer.pointer;
/*
* Convert buffer bytes to hex or decimal values
* (separated by commas or spaces)
*/
for (i = 0; i < obj_desc->buffer.length; i++) {
new_buf += acpi_ex_convert_to_ascii((u64) obj_desc->
buffer.pointer[i],
base, new_buf, 1);
*new_buf++ = separator; /* each separated by a comma or space */
}
/*
* Null terminate the string
* (overwrites final comma/space from above)
*/
if (obj_desc->buffer.length) {
new_buf--;
}
*new_buf = 0;
break;
default:
return_ACPI_STATUS(AE_TYPE);
}
*result_desc = return_desc;
return_ACPI_STATUS(AE_OK);
}
/*******************************************************************************
*
* FUNCTION: acpi_ex_convert_to_target_type
*
* PARAMETERS: destination_type - Current type of the destination
* source_desc - Source object to be converted.
* result_desc - Where the converted object is returned
* walk_state - Current method state
*
* RETURN: Status
*
* DESCRIPTION: Implements "implicit conversion" rules for storing an object.
*
******************************************************************************/
acpi_status
acpi_ex_convert_to_target_type(acpi_object_type destination_type,
union acpi_operand_object *source_desc,
union acpi_operand_object **result_desc,
struct acpi_walk_state *walk_state)
{
acpi_status status = AE_OK;
ACPI_FUNCTION_TRACE(ex_convert_to_target_type);
/* Default behavior */
*result_desc = source_desc;
/*
* If required by the target,
* perform implicit conversion on the source before we store it.
*/
switch (GET_CURRENT_ARG_TYPE(walk_state->op_info->runtime_args)) {
case ARGI_SIMPLE_TARGET:
case ARGI_FIXED_TARGET:
case ARGI_INTEGER_REF: /* Handles Increment, Decrement cases */
switch (destination_type) {
case ACPI_TYPE_LOCAL_REGION_FIELD:
/*
* Named field can always handle conversions
*/
break;
default:
/* No conversion allowed for these types */
if (destination_type != source_desc->common.type) {
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"Explicit operator, will store (%s) over existing type (%s)\n",
acpi_ut_get_object_type_name
(source_desc),
acpi_ut_get_type_name
(destination_type)));
status = AE_TYPE;
}
}
break;
case ARGI_TARGETREF:
switch (destination_type) {
case ACPI_TYPE_INTEGER:
case ACPI_TYPE_BUFFER_FIELD:
case ACPI_TYPE_LOCAL_BANK_FIELD:
case ACPI_TYPE_LOCAL_INDEX_FIELD:
/*
* These types require an Integer operand. We can convert
* a Buffer or a String to an Integer if necessary.
*/
status =
acpi_ex_convert_to_integer(source_desc, result_desc,
16);
break;
case ACPI_TYPE_STRING:
/*
* The operand must be a String. We can convert an
* Integer or Buffer if necessary
*/
status =
acpi_ex_convert_to_string(source_desc, result_desc,
ACPI_IMPLICIT_CONVERT_HEX);
break;
case ACPI_TYPE_BUFFER:
/*
* The operand must be a Buffer. We can convert an
* Integer or String if necessary
*/
status =
acpi_ex_convert_to_buffer(source_desc, result_desc);
break;
default:
ACPI_ERROR((AE_INFO,
"Bad destination type during conversion: 0x%X",
destination_type));
status = AE_AML_INTERNAL;
break;
}
break;
case ARGI_REFERENCE:
/*
* create_xxxx_field cases - we are storing the field object into the name
*/
break;
default:
ACPI_ERROR((AE_INFO,
"Unknown Target type ID 0x%X AmlOpcode 0x%X DestType %s",
GET_CURRENT_ARG_TYPE(walk_state->op_info->
runtime_args),
walk_state->opcode,
acpi_ut_get_type_name(destination_type)));
status = AE_AML_INTERNAL;
}
/*
* Source-to-Target conversion semantics:
*
* If conversion to the target type cannot be performed, then simply
* overwrite the target with the new object and type.
*/
if (status == AE_TYPE) {
status = AE_OK;
}
return_ACPI_STATUS(status);
}
| gpl-2.0 |
FrostedKernel/android_kernel_htc_msm8960 | drivers/acpi/acpica/nsnames.c | 4919 | 8030 | /*******************************************************************************
*
* Module Name: nsnames - Name manipulation and search
*
******************************************************************************/
/*
* Copyright (C) 2000 - 2012, 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 "amlcode.h"
#include "acnamesp.h"
#define _COMPONENT ACPI_NAMESPACE
ACPI_MODULE_NAME("nsnames")
/*******************************************************************************
*
* FUNCTION: acpi_ns_build_external_path
*
* PARAMETERS: Node - NS node whose pathname is needed
* Size - Size of the pathname
* *name_buffer - Where to return the pathname
*
* RETURN: Status
* Places the pathname into the name_buffer, in external format
* (name segments separated by path separators)
*
* DESCRIPTION: Generate a full pathaname
*
******************************************************************************/
acpi_status
acpi_ns_build_external_path(struct acpi_namespace_node *node,
acpi_size size, char *name_buffer)
{
acpi_size index;
struct acpi_namespace_node *parent_node;
ACPI_FUNCTION_ENTRY();
/* Special case for root */
index = size - 1;
if (index < ACPI_NAME_SIZE) {
name_buffer[0] = AML_ROOT_PREFIX;
name_buffer[1] = 0;
return (AE_OK);
}
/* Store terminator byte, then build name backwards */
parent_node = node;
name_buffer[index] = 0;
while ((index > ACPI_NAME_SIZE) && (parent_node != acpi_gbl_root_node)) {
index -= ACPI_NAME_SIZE;
/* Put the name into the buffer */
ACPI_MOVE_32_TO_32((name_buffer + index), &parent_node->name);
parent_node = parent_node->parent;
/* Prefix name with the path separator */
index--;
name_buffer[index] = ACPI_PATH_SEPARATOR;
}
/* Overwrite final separator with the root prefix character */
name_buffer[index] = AML_ROOT_PREFIX;
if (index != 0) {
ACPI_ERROR((AE_INFO,
"Could not construct external pathname; index=%u, size=%u, Path=%s",
(u32) index, (u32) size, &name_buffer[size]));
return (AE_BAD_PARAMETER);
}
return (AE_OK);
}
/*******************************************************************************
*
* FUNCTION: acpi_ns_get_external_pathname
*
* PARAMETERS: Node - Namespace node whose pathname is needed
*
* RETURN: Pointer to storage containing the fully qualified name of
* the node, In external format (name segments separated by path
* separators.)
*
* DESCRIPTION: Used for debug printing in acpi_ns_search_table().
*
******************************************************************************/
char *acpi_ns_get_external_pathname(struct acpi_namespace_node *node)
{
acpi_status status;
char *name_buffer;
acpi_size size;
ACPI_FUNCTION_TRACE_PTR(ns_get_external_pathname, node);
/* Calculate required buffer size based on depth below root */
size = acpi_ns_get_pathname_length(node);
if (!size) {
return_PTR(NULL);
}
/* Allocate a buffer to be returned to caller */
name_buffer = ACPI_ALLOCATE_ZEROED(size);
if (!name_buffer) {
ACPI_ERROR((AE_INFO, "Could not allocate %u bytes", (u32)size));
return_PTR(NULL);
}
/* Build the path in the allocated buffer */
status = acpi_ns_build_external_path(node, size, name_buffer);
if (ACPI_FAILURE(status)) {
ACPI_FREE(name_buffer);
return_PTR(NULL);
}
return_PTR(name_buffer);
}
/*******************************************************************************
*
* FUNCTION: acpi_ns_get_pathname_length
*
* PARAMETERS: Node - Namespace node
*
* RETURN: Length of path, including prefix
*
* DESCRIPTION: Get the length of the pathname string for this node
*
******************************************************************************/
acpi_size acpi_ns_get_pathname_length(struct acpi_namespace_node *node)
{
acpi_size size;
struct acpi_namespace_node *next_node;
ACPI_FUNCTION_ENTRY();
/*
* Compute length of pathname as 5 * number of name segments.
* Go back up the parent tree to the root
*/
size = 0;
next_node = node;
while (next_node && (next_node != acpi_gbl_root_node)) {
if (ACPI_GET_DESCRIPTOR_TYPE(next_node) != ACPI_DESC_TYPE_NAMED) {
ACPI_ERROR((AE_INFO,
"Invalid Namespace Node (%p) while traversing namespace",
next_node));
return 0;
}
size += ACPI_PATH_SEGMENT_LENGTH;
next_node = next_node->parent;
}
if (!size) {
size = 1; /* Root node case */
}
return (size + 1); /* +1 for null string terminator */
}
/*******************************************************************************
*
* FUNCTION: acpi_ns_handle_to_pathname
*
* PARAMETERS: target_handle - Handle of named object whose name is
* to be found
* Buffer - Where the pathname is returned
*
* RETURN: Status, Buffer is filled with pathname if status is AE_OK
*
* DESCRIPTION: Build and return a full namespace pathname
*
******************************************************************************/
acpi_status
acpi_ns_handle_to_pathname(acpi_handle target_handle,
struct acpi_buffer * buffer)
{
acpi_status status;
struct acpi_namespace_node *node;
acpi_size required_size;
ACPI_FUNCTION_TRACE_PTR(ns_handle_to_pathname, target_handle);
node = acpi_ns_validate_handle(target_handle);
if (!node) {
return_ACPI_STATUS(AE_BAD_PARAMETER);
}
/* Determine size required for the caller buffer */
required_size = acpi_ns_get_pathname_length(node);
if (!required_size) {
return_ACPI_STATUS(AE_BAD_PARAMETER);
}
/* Validate/Allocate/Clear caller buffer */
status = acpi_ut_initialize_buffer(buffer, required_size);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
/* Build the path in the caller buffer */
status =
acpi_ns_build_external_path(node, required_size, buffer->pointer);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
ACPI_DEBUG_PRINT((ACPI_DB_EXEC, "%s [%X]\n",
(char *)buffer->pointer, (u32) required_size));
return_ACPI_STATUS(AE_OK);
}
| gpl-2.0 |
SerenityS/android_kernel_pantech_ef39s_jb | net/irda/irqueue.c | 5431 | 23284 | /*********************************************************************
*
* Filename: irqueue.c
* Version: 0.3
* Description: General queue implementation
* Status: Experimental.
* Author: Dag Brattli <dagb@cs.uit.no>
* Created at: Tue Jun 9 13:29:31 1998
* Modified at: Sun Dec 12 13:48:22 1999
* Modified by: Dag Brattli <dagb@cs.uit.no>
* Modified at: Thu Jan 4 14:29:10 CET 2001
* Modified by: Marc Zyngier <mzyngier@freesurf.fr>
*
* Copyright (C) 1998-1999, Aage Kvalnes <aage@cs.uit.no>
* Copyright (C) 1998, Dag Brattli,
* All Rights Reserved.
*
* This code is taken from the Vortex Operating System written by Aage
* Kvalnes. Aage has agreed that this code can use the GPL licence,
* although he does not use that licence in his own code.
*
* This copyright does however _not_ include the ELF hash() function
* which I currently don't know which licence or copyright it
* has. Please inform me if you know.
*
* 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.
*
* Neither Dag Brattli nor University of Tromsø admit liability nor
* provide warranty for any of this software. This material is
* provided "AS-IS" and at no charge.
*
********************************************************************/
/*
* NOTE :
* There are various problems with this package :
* o the hash function for ints is pathetic (but could be changed)
* o locking is sometime suspicious (especially during enumeration)
* o most users have only a few elements (== overhead)
* o most users never use search, so don't benefit from hashing
* Problem already fixed :
* o not 64 bit compliant (most users do hashv = (int) self)
* o hashbin_remove() is broken => use hashbin_remove_this()
* I think most users would be better served by a simple linked list
* (like include/linux/list.h) with a global spinlock per list.
* Jean II
*/
/*
* Notes on the concurrent access to hashbin and other SMP issues
* -------------------------------------------------------------
* Hashbins are very often in the IrDA stack a global repository of
* information, and therefore used in a very asynchronous manner following
* various events (driver calls, timers, user calls...).
* Therefore, very often it is highly important to consider the
* management of concurrent access to the hashbin and how to guarantee the
* consistency of the operations on it.
*
* First, we need to define the objective of locking :
* 1) Protect user data (content pointed by the hashbin)
* 2) Protect hashbin structure itself (linked list in each bin)
*
* OLD LOCKING
* -----------
*
* The previous locking strategy, either HB_LOCAL or HB_GLOBAL were
* both inadequate in *both* aspect.
* o HB_GLOBAL was using a spinlock for each bin (local locking).
* o HB_LOCAL was disabling irq on *all* CPUs, so use a single
* global semaphore.
* The problems were :
* A) Global irq disabling is no longer supported by the kernel
* B) No protection for the hashbin struct global data
* o hashbin_delete()
* o hb_current
* C) No protection for user data in some cases
*
* A) HB_LOCAL use global irq disabling, so doesn't work on kernel
* 2.5.X. Even when it is supported (kernel 2.4.X and earlier), its
* performance is not satisfactory on SMP setups. Most hashbins were
* HB_LOCAL, so (A) definitely need fixing.
* B) HB_LOCAL could be modified to fix (B). However, because HB_GLOBAL
* lock only the individual bins, it will never be able to lock the
* global data, so can't do (B).
* C) Some functions return pointer to data that is still in the
* hashbin :
* o hashbin_find()
* o hashbin_get_first()
* o hashbin_get_next()
* As the data is still in the hashbin, it may be changed or free'd
* while the caller is examinimg the data. In those case, locking can't
* be done within the hashbin, but must include use of the data within
* the caller.
* The caller can easily do this with HB_LOCAL (just disable irqs).
* However, this is impossible with HB_GLOBAL because the caller has no
* way to know the proper bin, so don't know which spinlock to use.
*
* Quick summary : can no longer use HB_LOCAL, and HB_GLOBAL is
* fundamentally broken and will never work.
*
* NEW LOCKING
* -----------
*
* To fix those problems, I've introduce a few changes in the
* hashbin locking :
* 1) New HB_LOCK scheme
* 2) hashbin->hb_spinlock
* 3) New hashbin usage policy
*
* HB_LOCK :
* -------
* HB_LOCK is a locking scheme intermediate between the old HB_LOCAL
* and HB_GLOBAL. It uses a single spinlock to protect the whole content
* of the hashbin. As it is a single spinlock, it can protect the global
* data of the hashbin and not only the bins themselves.
* HB_LOCK can only protect some of the hashbin calls, so it only lock
* call that can be made 100% safe and leave other call unprotected.
* HB_LOCK in theory is slower than HB_GLOBAL, but as the hashbin
* content is always small contention is not high, so it doesn't matter
* much. HB_LOCK is probably faster than HB_LOCAL.
*
* hashbin->hb_spinlock :
* --------------------
* The spinlock that HB_LOCK uses is available for caller, so that
* the caller can protect unprotected calls (see below).
* If the caller want to do entirely its own locking (HB_NOLOCK), he
* can do so and may use safely this spinlock.
* Locking is done like this :
* spin_lock_irqsave(&hashbin->hb_spinlock, flags);
* Releasing the lock :
* spin_unlock_irqrestore(&hashbin->hb_spinlock, flags);
*
* Safe & Protected calls :
* ----------------------
* The following calls are safe or protected via HB_LOCK :
* o hashbin_new() -> safe
* o hashbin_delete()
* o hashbin_insert()
* o hashbin_remove_first()
* o hashbin_remove()
* o hashbin_remove_this()
* o HASHBIN_GET_SIZE() -> atomic
*
* The following calls only protect the hashbin itself :
* o hashbin_lock_find()
* o hashbin_find_next()
*
* Unprotected calls :
* -----------------
* The following calls need to be protected by the caller :
* o hashbin_find()
* o hashbin_get_first()
* o hashbin_get_next()
*
* Locking Policy :
* --------------
* If the hashbin is used only in a single thread of execution
* (explicitly or implicitely), you can use HB_NOLOCK
* If the calling module already provide concurrent access protection,
* you may use HB_NOLOCK.
*
* In all other cases, you need to use HB_LOCK and lock the hashbin
* every time before calling one of the unprotected calls. You also must
* use the pointer returned by the unprotected call within the locked
* region.
*
* Extra care for enumeration :
* --------------------------
* hashbin_get_first() and hashbin_get_next() use the hashbin to
* store the current position, in hb_current.
* As long as the hashbin remains locked, this is safe. If you unlock
* the hashbin, the current position may change if anybody else modify
* or enumerate the hashbin.
* Summary : do the full enumeration while locked.
*
* Alternatively, you may use hashbin_find_next(). But, this will
* be slower, is more complex to use and doesn't protect the hashbin
* content. So, care is needed here as well.
*
* Other issues :
* ------------
* I believe that we are overdoing it by using spin_lock_irqsave()
* and we should use only spin_lock_bh() or similar. But, I don't have
* the balls to try it out.
* Don't believe that because hashbin are now (somewhat) SMP safe
* that the rest of the code is. Higher layers tend to be safest,
* but LAP and LMP would need some serious dedicated love.
*
* Jean II
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <net/irda/irda.h>
#include <net/irda/irqueue.h>
/************************ QUEUE SUBROUTINES ************************/
/*
* Hashbin
*/
#define GET_HASHBIN(x) ( x & HASHBIN_MASK )
/*
* Function hash (name)
*
* This function hash the input string 'name' using the ELF hash
* function for strings.
*/
static __u32 hash( const char* name)
{
__u32 h = 0;
__u32 g;
while(*name) {
h = (h<<4) + *name++;
if ((g = (h & 0xf0000000)))
h ^=g>>24;
h &=~g;
}
return h;
}
/*
* Function enqueue_first (queue, proc)
*
* Insert item first in queue.
*
*/
static void enqueue_first(irda_queue_t **queue, irda_queue_t* element)
{
IRDA_DEBUG( 4, "%s()\n", __func__);
/*
* Check if queue is empty.
*/
if ( *queue == NULL ) {
/*
* Queue is empty. Insert one element into the queue.
*/
element->q_next = element->q_prev = *queue = element;
} else {
/*
* Queue is not empty. Insert element into front of queue.
*/
element->q_next = (*queue);
(*queue)->q_prev->q_next = element;
element->q_prev = (*queue)->q_prev;
(*queue)->q_prev = element;
(*queue) = element;
}
}
/*
* Function dequeue (queue)
*
* Remove first entry in queue
*
*/
static irda_queue_t *dequeue_first(irda_queue_t **queue)
{
irda_queue_t *ret;
IRDA_DEBUG( 4, "dequeue_first()\n");
/*
* Set return value
*/
ret = *queue;
if ( *queue == NULL ) {
/*
* Queue was empty.
*/
} else if ( (*queue)->q_next == *queue ) {
/*
* Queue only contained a single element. It will now be
* empty.
*/
*queue = NULL;
} else {
/*
* Queue contained several element. Remove the first one.
*/
(*queue)->q_prev->q_next = (*queue)->q_next;
(*queue)->q_next->q_prev = (*queue)->q_prev;
*queue = (*queue)->q_next;
}
/*
* Return the removed entry (or NULL of queue was empty).
*/
return ret;
}
/*
* Function dequeue_general (queue, element)
*
*
*/
static irda_queue_t *dequeue_general(irda_queue_t **queue, irda_queue_t* element)
{
irda_queue_t *ret;
IRDA_DEBUG( 4, "dequeue_general()\n");
/*
* Set return value
*/
ret = *queue;
if ( *queue == NULL ) {
/*
* Queue was empty.
*/
} else if ( (*queue)->q_next == *queue ) {
/*
* Queue only contained a single element. It will now be
* empty.
*/
*queue = NULL;
} else {
/*
* Remove specific element.
*/
element->q_prev->q_next = element->q_next;
element->q_next->q_prev = element->q_prev;
if ( (*queue) == element)
(*queue) = element->q_next;
}
/*
* Return the removed entry (or NULL of queue was empty).
*/
return ret;
}
/************************ HASHBIN MANAGEMENT ************************/
/*
* Function hashbin_create ( type, name )
*
* Create hashbin!
*
*/
hashbin_t *hashbin_new(int type)
{
hashbin_t* hashbin;
/*
* Allocate new hashbin
*/
hashbin = kzalloc(sizeof(*hashbin), GFP_ATOMIC);
if (!hashbin)
return NULL;
/*
* Initialize structure
*/
hashbin->hb_type = type;
hashbin->magic = HB_MAGIC;
//hashbin->hb_current = NULL;
/* Make sure all spinlock's are unlocked */
if ( hashbin->hb_type & HB_LOCK ) {
spin_lock_init(&hashbin->hb_spinlock);
}
return hashbin;
}
EXPORT_SYMBOL(hashbin_new);
/*
* Function hashbin_delete (hashbin, free_func)
*
* Destroy hashbin, the free_func can be a user supplied special routine
* for deallocating this structure if it's complex. If not the user can
* just supply kfree, which should take care of the job.
*/
#ifdef CONFIG_LOCKDEP
static int hashbin_lock_depth = 0;
#endif
int hashbin_delete( hashbin_t* hashbin, FREE_FUNC free_func)
{
irda_queue_t* queue;
unsigned long flags = 0;
int i;
IRDA_ASSERT(hashbin != NULL, return -1;);
IRDA_ASSERT(hashbin->magic == HB_MAGIC, return -1;);
/* Synchronize */
if ( hashbin->hb_type & HB_LOCK ) {
spin_lock_irqsave_nested(&hashbin->hb_spinlock, flags,
hashbin_lock_depth++);
}
/*
* Free the entries in the hashbin, TODO: use hashbin_clear when
* it has been shown to work
*/
for (i = 0; i < HASHBIN_SIZE; i ++ ) {
queue = dequeue_first((irda_queue_t**) &hashbin->hb_queue[i]);
while (queue ) {
if (free_func)
(*free_func)(queue);
queue = dequeue_first(
(irda_queue_t**) &hashbin->hb_queue[i]);
}
}
/* Cleanup local data */
hashbin->hb_current = NULL;
hashbin->magic = ~HB_MAGIC;
/* Release lock */
if ( hashbin->hb_type & HB_LOCK) {
spin_unlock_irqrestore(&hashbin->hb_spinlock, flags);
#ifdef CONFIG_LOCKDEP
hashbin_lock_depth--;
#endif
}
/*
* Free the hashbin structure
*/
kfree(hashbin);
return 0;
}
EXPORT_SYMBOL(hashbin_delete);
/********************* HASHBIN LIST OPERATIONS *********************/
/*
* Function hashbin_insert (hashbin, entry, name)
*
* Insert an entry into the hashbin
*
*/
void hashbin_insert(hashbin_t* hashbin, irda_queue_t* entry, long hashv,
const char* name)
{
unsigned long flags = 0;
int bin;
IRDA_DEBUG( 4, "%s()\n", __func__);
IRDA_ASSERT( hashbin != NULL, return;);
IRDA_ASSERT( hashbin->magic == HB_MAGIC, return;);
/*
* Locate hashbin
*/
if ( name )
hashv = hash( name );
bin = GET_HASHBIN( hashv );
/* Synchronize */
if ( hashbin->hb_type & HB_LOCK ) {
spin_lock_irqsave(&hashbin->hb_spinlock, flags);
} /* Default is no-lock */
/*
* Store name and key
*/
entry->q_hash = hashv;
if ( name )
strlcpy( entry->q_name, name, sizeof(entry->q_name));
/*
* Insert new entry first
*/
enqueue_first( (irda_queue_t**) &hashbin->hb_queue[ bin ],
entry);
hashbin->hb_size++;
/* Release lock */
if ( hashbin->hb_type & HB_LOCK ) {
spin_unlock_irqrestore(&hashbin->hb_spinlock, flags);
} /* Default is no-lock */
}
EXPORT_SYMBOL(hashbin_insert);
/*
* Function hashbin_remove_first (hashbin)
*
* Remove first entry of the hashbin
*
* Note : this function no longer use hashbin_remove(), but does things
* similar to hashbin_remove_this(), so can be considered safe.
* Jean II
*/
void *hashbin_remove_first( hashbin_t *hashbin)
{
unsigned long flags = 0;
irda_queue_t *entry = NULL;
/* Synchronize */
if ( hashbin->hb_type & HB_LOCK ) {
spin_lock_irqsave(&hashbin->hb_spinlock, flags);
} /* Default is no-lock */
entry = hashbin_get_first( hashbin);
if ( entry != NULL) {
int bin;
long hashv;
/*
* Locate hashbin
*/
hashv = entry->q_hash;
bin = GET_HASHBIN( hashv );
/*
* Dequeue the entry...
*/
dequeue_general( (irda_queue_t**) &hashbin->hb_queue[ bin ],
(irda_queue_t*) entry );
hashbin->hb_size--;
entry->q_next = NULL;
entry->q_prev = NULL;
/*
* Check if this item is the currently selected item, and in
* that case we must reset hb_current
*/
if ( entry == hashbin->hb_current)
hashbin->hb_current = NULL;
}
/* Release lock */
if ( hashbin->hb_type & HB_LOCK ) {
spin_unlock_irqrestore(&hashbin->hb_spinlock, flags);
} /* Default is no-lock */
return entry;
}
/*
* Function hashbin_remove (hashbin, hashv, name)
*
* Remove entry with the given name
*
* The use of this function is highly discouraged, because the whole
* concept behind hashbin_remove() is broken. In many cases, it's not
* possible to guarantee the unicity of the index (either hashv or name),
* leading to removing the WRONG entry.
* The only simple safe use is :
* hashbin_remove(hasbin, (int) self, NULL);
* In other case, you must think hard to guarantee unicity of the index.
* Jean II
*/
void* hashbin_remove( hashbin_t* hashbin, long hashv, const char* name)
{
int bin, found = FALSE;
unsigned long flags = 0;
irda_queue_t* entry;
IRDA_DEBUG( 4, "%s()\n", __func__);
IRDA_ASSERT( hashbin != NULL, return NULL;);
IRDA_ASSERT( hashbin->magic == HB_MAGIC, return NULL;);
/*
* Locate hashbin
*/
if ( name )
hashv = hash( name );
bin = GET_HASHBIN( hashv );
/* Synchronize */
if ( hashbin->hb_type & HB_LOCK ) {
spin_lock_irqsave(&hashbin->hb_spinlock, flags);
} /* Default is no-lock */
/*
* Search for entry
*/
entry = hashbin->hb_queue[ bin ];
if ( entry ) {
do {
/*
* Check for key
*/
if ( entry->q_hash == hashv ) {
/*
* Name compare too?
*/
if ( name ) {
if ( strcmp( entry->q_name, name) == 0)
{
found = TRUE;
break;
}
} else {
found = TRUE;
break;
}
}
entry = entry->q_next;
} while ( entry != hashbin->hb_queue[ bin ] );
}
/*
* If entry was found, dequeue it
*/
if ( found ) {
dequeue_general( (irda_queue_t**) &hashbin->hb_queue[ bin ],
(irda_queue_t*) entry );
hashbin->hb_size--;
/*
* Check if this item is the currently selected item, and in
* that case we must reset hb_current
*/
if ( entry == hashbin->hb_current)
hashbin->hb_current = NULL;
}
/* Release lock */
if ( hashbin->hb_type & HB_LOCK ) {
spin_unlock_irqrestore(&hashbin->hb_spinlock, flags);
} /* Default is no-lock */
/* Return */
if ( found )
return entry;
else
return NULL;
}
EXPORT_SYMBOL(hashbin_remove);
/*
* Function hashbin_remove_this (hashbin, entry)
*
* Remove entry with the given name
*
* In some cases, the user of hashbin can't guarantee the unicity
* of either the hashv or name.
* In those cases, using the above function is guaranteed to cause troubles,
* so we use this one instead...
* And by the way, it's also faster, because we skip the search phase ;-)
*/
void* hashbin_remove_this( hashbin_t* hashbin, irda_queue_t* entry)
{
unsigned long flags = 0;
int bin;
long hashv;
IRDA_DEBUG( 4, "%s()\n", __func__);
IRDA_ASSERT( hashbin != NULL, return NULL;);
IRDA_ASSERT( hashbin->magic == HB_MAGIC, return NULL;);
IRDA_ASSERT( entry != NULL, return NULL;);
/* Synchronize */
if ( hashbin->hb_type & HB_LOCK ) {
spin_lock_irqsave(&hashbin->hb_spinlock, flags);
} /* Default is no-lock */
/* Check if valid and not already removed... */
if((entry->q_next == NULL) || (entry->q_prev == NULL)) {
entry = NULL;
goto out;
}
/*
* Locate hashbin
*/
hashv = entry->q_hash;
bin = GET_HASHBIN( hashv );
/*
* Dequeue the entry...
*/
dequeue_general( (irda_queue_t**) &hashbin->hb_queue[ bin ],
(irda_queue_t*) entry );
hashbin->hb_size--;
entry->q_next = NULL;
entry->q_prev = NULL;
/*
* Check if this item is the currently selected item, and in
* that case we must reset hb_current
*/
if ( entry == hashbin->hb_current)
hashbin->hb_current = NULL;
out:
/* Release lock */
if ( hashbin->hb_type & HB_LOCK ) {
spin_unlock_irqrestore(&hashbin->hb_spinlock, flags);
} /* Default is no-lock */
return entry;
}
EXPORT_SYMBOL(hashbin_remove_this);
/*********************** HASHBIN ENUMERATION ***********************/
/*
* Function hashbin_common_find (hashbin, hashv, name)
*
* Find item with the given hashv or name
*
*/
void* hashbin_find( hashbin_t* hashbin, long hashv, const char* name )
{
int bin;
irda_queue_t* entry;
IRDA_DEBUG( 4, "hashbin_find()\n");
IRDA_ASSERT( hashbin != NULL, return NULL;);
IRDA_ASSERT( hashbin->magic == HB_MAGIC, return NULL;);
/*
* Locate hashbin
*/
if ( name )
hashv = hash( name );
bin = GET_HASHBIN( hashv );
/*
* Search for entry
*/
entry = hashbin->hb_queue[ bin];
if ( entry ) {
do {
/*
* Check for key
*/
if ( entry->q_hash == hashv ) {
/*
* Name compare too?
*/
if ( name ) {
if ( strcmp( entry->q_name, name ) == 0 ) {
return entry;
}
} else {
return entry;
}
}
entry = entry->q_next;
} while ( entry != hashbin->hb_queue[ bin ] );
}
return NULL;
}
EXPORT_SYMBOL(hashbin_find);
/*
* Function hashbin_lock_find (hashbin, hashv, name)
*
* Find item with the given hashv or name
*
* Same, but with spinlock protection...
* I call it safe, but it's only safe with respect to the hashbin, not its
* content. - Jean II
*/
void* hashbin_lock_find( hashbin_t* hashbin, long hashv, const char* name )
{
unsigned long flags = 0;
irda_queue_t* entry;
/* Synchronize */
spin_lock_irqsave(&hashbin->hb_spinlock, flags);
/*
* Search for entry
*/
entry = hashbin_find(hashbin, hashv, name);
/* Release lock */
spin_unlock_irqrestore(&hashbin->hb_spinlock, flags);
return entry;
}
EXPORT_SYMBOL(hashbin_lock_find);
/*
* Function hashbin_find (hashbin, hashv, name, pnext)
*
* Find an item with the given hashv or name, and its successor
*
* This function allow to do concurrent enumerations without the
* need to lock over the whole session, because the caller keep the
* context of the search. On the other hand, it might fail and return
* NULL if the entry is removed. - Jean II
*/
void* hashbin_find_next( hashbin_t* hashbin, long hashv, const char* name,
void ** pnext)
{
unsigned long flags = 0;
irda_queue_t* entry;
/* Synchronize */
spin_lock_irqsave(&hashbin->hb_spinlock, flags);
/*
* Search for current entry
* This allow to check if the current item is still in the
* hashbin or has been removed.
*/
entry = hashbin_find(hashbin, hashv, name);
/*
* Trick hashbin_get_next() to return what we want
*/
if(entry) {
hashbin->hb_current = entry;
*pnext = hashbin_get_next( hashbin );
} else
*pnext = NULL;
/* Release lock */
spin_unlock_irqrestore(&hashbin->hb_spinlock, flags);
return entry;
}
/*
* Function hashbin_get_first (hashbin)
*
* Get a pointer to first element in hashbin, this function must be
* called before any calls to hashbin_get_next()!
*
*/
irda_queue_t *hashbin_get_first( hashbin_t* hashbin)
{
irda_queue_t *entry;
int i;
IRDA_ASSERT( hashbin != NULL, return NULL;);
IRDA_ASSERT( hashbin->magic == HB_MAGIC, return NULL;);
if ( hashbin == NULL)
return NULL;
for ( i = 0; i < HASHBIN_SIZE; i ++ ) {
entry = hashbin->hb_queue[ i];
if ( entry) {
hashbin->hb_current = entry;
return entry;
}
}
/*
* Did not find any item in hashbin
*/
return NULL;
}
EXPORT_SYMBOL(hashbin_get_first);
/*
* Function hashbin_get_next (hashbin)
*
* Get next item in hashbin. A series of hashbin_get_next() calls must
* be started by a call to hashbin_get_first(). The function returns
* NULL when all items have been traversed
*
* The context of the search is stored within the hashbin, so you must
* protect yourself from concurrent enumerations. - Jean II
*/
irda_queue_t *hashbin_get_next( hashbin_t *hashbin)
{
irda_queue_t* entry;
int bin;
int i;
IRDA_ASSERT( hashbin != NULL, return NULL;);
IRDA_ASSERT( hashbin->magic == HB_MAGIC, return NULL;);
if ( hashbin->hb_current == NULL) {
IRDA_ASSERT( hashbin->hb_current != NULL, return NULL;);
return NULL;
}
entry = hashbin->hb_current->q_next;
bin = GET_HASHBIN( entry->q_hash);
/*
* Make sure that we are not back at the beginning of the queue
* again
*/
if ( entry != hashbin->hb_queue[ bin ]) {
hashbin->hb_current = entry;
return entry;
}
/*
* Check that this is not the last queue in hashbin
*/
if ( bin >= HASHBIN_SIZE)
return NULL;
/*
* Move to next queue in hashbin
*/
bin++;
for ( i = bin; i < HASHBIN_SIZE; i++ ) {
entry = hashbin->hb_queue[ i];
if ( entry) {
hashbin->hb_current = entry;
return entry;
}
}
return NULL;
}
EXPORT_SYMBOL(hashbin_get_next);
| gpl-2.0 |
revjunkie/galbi-g2 | drivers/video/asiliantfb.c | 9271 | 17013 | /*
* drivers/video/asiliantfb.c
* frame buffer driver for Asiliant 69000 chip
* Copyright (C) 2001-2003 Saito.K & Jeanne
*
* from driver/video/chipsfb.c and,
*
* drivers/video/asiliantfb.c -- frame buffer device for
* Asiliant 69030 chip (formerly Intel, formerly Chips & Technologies)
* Author: apc@agelectronics.co.uk
* Copyright (C) 2000 AG Electronics
* Note: the data sheets don't seem to be available from Asiliant.
* They are available by searching developer.intel.com, but are not otherwise
* linked to.
*
* This driver should be portable with minimal effort to the 69000 display
* chip, and to the twin-display mode of the 69030.
* Contains code from Thomas Hhenleitner <th@visuelle-maschinen.de> (thanks)
*
* Derived from the CT65550 driver chipsfb.c:
* Copyright (C) 1998 Paul Mackerras
* ...which was derived from the Powermac "chips" driver:
* Copyright (C) 1997 Fabio Riccardi.
* And from the frame buffer device for Open Firmware-initialized devices:
* Copyright (C) 1997 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/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/fb.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <asm/io.h>
/* Built in clock of the 69030 */
static const unsigned Fref = 14318180;
#define mmio_base (p->screen_base + 0x400000)
#define mm_write_ind(num, val, ap, dp) do { \
writeb((num), mmio_base + (ap)); writeb((val), mmio_base + (dp)); \
} while (0)
static void mm_write_xr(struct fb_info *p, u8 reg, u8 data)
{
mm_write_ind(reg, data, 0x7ac, 0x7ad);
}
#define write_xr(num, val) mm_write_xr(p, num, val)
static void mm_write_fr(struct fb_info *p, u8 reg, u8 data)
{
mm_write_ind(reg, data, 0x7a0, 0x7a1);
}
#define write_fr(num, val) mm_write_fr(p, num, val)
static void mm_write_cr(struct fb_info *p, u8 reg, u8 data)
{
mm_write_ind(reg, data, 0x7a8, 0x7a9);
}
#define write_cr(num, val) mm_write_cr(p, num, val)
static void mm_write_gr(struct fb_info *p, u8 reg, u8 data)
{
mm_write_ind(reg, data, 0x79c, 0x79d);
}
#define write_gr(num, val) mm_write_gr(p, num, val)
static void mm_write_sr(struct fb_info *p, u8 reg, u8 data)
{
mm_write_ind(reg, data, 0x788, 0x789);
}
#define write_sr(num, val) mm_write_sr(p, num, val)
static void mm_write_ar(struct fb_info *p, u8 reg, u8 data)
{
readb(mmio_base + 0x7b4);
mm_write_ind(reg, data, 0x780, 0x780);
}
#define write_ar(num, val) mm_write_ar(p, num, val)
static int asiliantfb_pci_init(struct pci_dev *dp, const struct pci_device_id *);
static int asiliantfb_check_var(struct fb_var_screeninfo *var,
struct fb_info *info);
static int asiliantfb_set_par(struct fb_info *info);
static int asiliantfb_setcolreg(u_int regno, u_int red, u_int green, u_int blue,
u_int transp, struct fb_info *info);
static struct fb_ops asiliantfb_ops = {
.owner = THIS_MODULE,
.fb_check_var = asiliantfb_check_var,
.fb_set_par = asiliantfb_set_par,
.fb_setcolreg = asiliantfb_setcolreg,
.fb_fillrect = cfb_fillrect,
.fb_copyarea = cfb_copyarea,
.fb_imageblit = cfb_imageblit,
};
/* Calculate the ratios for the dot clocks without using a single long long
* value */
static void asiliant_calc_dclk2(u32 *ppixclock, u8 *dclk2_m, u8 *dclk2_n, u8 *dclk2_div)
{
unsigned pixclock = *ppixclock;
unsigned Ftarget = 1000000 * (1000000 / pixclock);
unsigned n;
unsigned best_error = 0xffffffff;
unsigned best_m = 0xffffffff,
best_n = 0xffffffff;
unsigned ratio;
unsigned remainder;
unsigned char divisor = 0;
/* Calculate the frequency required. This is hard enough. */
ratio = 1000000 / pixclock;
remainder = 1000000 % pixclock;
Ftarget = 1000000 * ratio + (1000000 * remainder) / pixclock;
while (Ftarget < 100000000) {
divisor += 0x10;
Ftarget <<= 1;
}
ratio = Ftarget / Fref;
remainder = Ftarget % Fref;
/* This expresses the constraint that 150kHz <= Fref/n <= 5Mhz,
* together with 3 <= n <= 257. */
for (n = 3; n <= 257; n++) {
unsigned m = n * ratio + (n * remainder) / Fref;
/* 3 <= m <= 257 */
if (m >= 3 && m <= 257) {
unsigned new_error = Ftarget * n >= Fref * m ?
((Ftarget * n) - (Fref * m)) : ((Fref * m) - (Ftarget * n));
if (new_error < best_error) {
best_n = n;
best_m = m;
best_error = new_error;
}
}
/* But if VLD = 4, then 4m <= 1028 */
else if (m <= 1028) {
/* remember there are still only 8-bits of precision in m, so
* avoid over-optimistic error calculations */
unsigned new_error = Ftarget * n >= Fref * (m & ~3) ?
((Ftarget * n) - (Fref * (m & ~3))) : ((Fref * (m & ~3)) - (Ftarget * n));
if (new_error < best_error) {
best_n = n;
best_m = m;
best_error = new_error;
}
}
}
if (best_m > 257)
best_m >>= 2; /* divide m by 4, and leave VCO loop divide at 4 */
else
divisor |= 4; /* or set VCO loop divide to 1 */
*dclk2_m = best_m - 2;
*dclk2_n = best_n - 2;
*dclk2_div = divisor;
*ppixclock = pixclock;
return;
}
static void asiliant_set_timing(struct fb_info *p)
{
unsigned hd = p->var.xres / 8;
unsigned hs = (p->var.xres + p->var.right_margin) / 8;
unsigned he = (p->var.xres + p->var.right_margin + p->var.hsync_len) / 8;
unsigned ht = (p->var.left_margin + p->var.xres + p->var.right_margin + p->var.hsync_len) / 8;
unsigned vd = p->var.yres;
unsigned vs = p->var.yres + p->var.lower_margin;
unsigned ve = p->var.yres + p->var.lower_margin + p->var.vsync_len;
unsigned vt = p->var.upper_margin + p->var.yres + p->var.lower_margin + p->var.vsync_len;
unsigned wd = (p->var.xres_virtual * ((p->var.bits_per_pixel+7)/8)) / 8;
if ((p->var.xres == 640) && (p->var.yres == 480) && (p->var.pixclock == 39722)) {
write_fr(0x01, 0x02); /* LCD */
} else {
write_fr(0x01, 0x01); /* CRT */
}
write_cr(0x11, (ve - 1) & 0x0f);
write_cr(0x00, (ht - 5) & 0xff);
write_cr(0x01, hd - 1);
write_cr(0x02, hd);
write_cr(0x03, ((ht - 1) & 0x1f) | 0x80);
write_cr(0x04, hs);
write_cr(0x05, (((ht - 1) & 0x20) <<2) | (he & 0x1f));
write_cr(0x3c, (ht - 1) & 0xc0);
write_cr(0x06, (vt - 2) & 0xff);
write_cr(0x30, (vt - 2) >> 8);
write_cr(0x07, 0x00);
write_cr(0x08, 0x00);
write_cr(0x09, 0x00);
write_cr(0x10, (vs - 1) & 0xff);
write_cr(0x32, ((vs - 1) >> 8) & 0xf);
write_cr(0x11, ((ve - 1) & 0x0f) | 0x80);
write_cr(0x12, (vd - 1) & 0xff);
write_cr(0x31, ((vd - 1) & 0xf00) >> 8);
write_cr(0x13, wd & 0xff);
write_cr(0x41, (wd & 0xf00) >> 8);
write_cr(0x15, (vs - 1) & 0xff);
write_cr(0x33, ((vs - 1) >> 8) & 0xf);
write_cr(0x38, ((ht - 5) & 0x100) >> 8);
write_cr(0x16, (vt - 1) & 0xff);
write_cr(0x18, 0x00);
if (p->var.xres == 640) {
writeb(0xc7, mmio_base + 0x784); /* set misc output reg */
} else {
writeb(0x07, mmio_base + 0x784); /* set misc output reg */
}
}
static int asiliantfb_check_var(struct fb_var_screeninfo *var,
struct fb_info *p)
{
unsigned long Ftarget, ratio, remainder;
ratio = 1000000 / var->pixclock;
remainder = 1000000 % var->pixclock;
Ftarget = 1000000 * ratio + (1000000 * remainder) / var->pixclock;
/* First check the constraint that the maximum post-VCO divisor is 32,
* and the maximum Fvco is 220MHz */
if (Ftarget > 220000000 || Ftarget < 3125000) {
printk(KERN_ERR "asiliantfb dotclock must be between 3.125 and 220MHz\n");
return -ENXIO;
}
var->xres_virtual = var->xres;
var->yres_virtual = var->yres;
if (var->bits_per_pixel == 24) {
var->red.offset = 16;
var->green.offset = 8;
var->blue.offset = 0;
var->red.length = var->blue.length = var->green.length = 8;
} else if (var->bits_per_pixel == 16) {
switch (var->red.offset) {
case 11:
var->green.length = 6;
break;
case 10:
var->green.length = 5;
break;
default:
return -EINVAL;
}
var->green.offset = 5;
var->blue.offset = 0;
var->red.length = var->blue.length = 5;
} else if (var->bits_per_pixel == 8) {
var->red.offset = var->green.offset = var->blue.offset = 0;
var->red.length = var->green.length = var->blue.length = 8;
}
return 0;
}
static int asiliantfb_set_par(struct fb_info *p)
{
u8 dclk2_m; /* Holds m-2 value for register */
u8 dclk2_n; /* Holds n-2 value for register */
u8 dclk2_div; /* Holds divisor bitmask */
/* Set pixclock */
asiliant_calc_dclk2(&p->var.pixclock, &dclk2_m, &dclk2_n, &dclk2_div);
/* Set color depth */
if (p->var.bits_per_pixel == 24) {
write_xr(0x81, 0x16); /* 24 bit packed color mode */
write_xr(0x82, 0x00); /* Disable palettes */
write_xr(0x20, 0x20); /* 24 bit blitter mode */
} else if (p->var.bits_per_pixel == 16) {
if (p->var.red.offset == 11)
write_xr(0x81, 0x15); /* 16 bit color mode */
else
write_xr(0x81, 0x14); /* 15 bit color mode */
write_xr(0x82, 0x00); /* Disable palettes */
write_xr(0x20, 0x10); /* 16 bit blitter mode */
} else if (p->var.bits_per_pixel == 8) {
write_xr(0x0a, 0x02); /* Linear */
write_xr(0x81, 0x12); /* 8 bit color mode */
write_xr(0x82, 0x00); /* Graphics gamma enable */
write_xr(0x20, 0x00); /* 8 bit blitter mode */
}
p->fix.line_length = p->var.xres * (p->var.bits_per_pixel >> 3);
p->fix.visual = (p->var.bits_per_pixel == 8) ? FB_VISUAL_PSEUDOCOLOR : FB_VISUAL_TRUECOLOR;
write_xr(0xc4, dclk2_m);
write_xr(0xc5, dclk2_n);
write_xr(0xc7, dclk2_div);
/* Set up the CR registers */
asiliant_set_timing(p);
return 0;
}
static int asiliantfb_setcolreg(u_int regno, u_int red, u_int green, u_int blue,
u_int transp, struct fb_info *p)
{
if (regno > 255)
return 1;
red >>= 8;
green >>= 8;
blue >>= 8;
/* Set hardware palete */
writeb(regno, mmio_base + 0x790);
udelay(1);
writeb(red, mmio_base + 0x791);
writeb(green, mmio_base + 0x791);
writeb(blue, mmio_base + 0x791);
if (regno < 16) {
switch(p->var.red.offset) {
case 10: /* RGB 555 */
((u32 *)(p->pseudo_palette))[regno] =
((red & 0xf8) << 7) |
((green & 0xf8) << 2) |
((blue & 0xf8) >> 3);
break;
case 11: /* RGB 565 */
((u32 *)(p->pseudo_palette))[regno] =
((red & 0xf8) << 8) |
((green & 0xfc) << 3) |
((blue & 0xf8) >> 3);
break;
case 16: /* RGB 888 */
((u32 *)(p->pseudo_palette))[regno] =
(red << 16) |
(green << 8) |
(blue);
break;
}
}
return 0;
}
struct chips_init_reg {
unsigned char addr;
unsigned char data;
};
static struct chips_init_reg chips_init_sr[] =
{
{0x00, 0x03}, /* Reset register */
{0x01, 0x01}, /* Clocking mode */
{0x02, 0x0f}, /* Plane mask */
{0x04, 0x0e} /* Memory mode */
};
static struct chips_init_reg chips_init_gr[] =
{
{0x03, 0x00}, /* Data rotate */
{0x05, 0x00}, /* Graphics mode */
{0x06, 0x01}, /* Miscellaneous */
{0x08, 0x00} /* Bit mask */
};
static struct chips_init_reg chips_init_ar[] =
{
{0x10, 0x01}, /* Mode control */
{0x11, 0x00}, /* Overscan */
{0x12, 0x0f}, /* Memory plane enable */
{0x13, 0x00} /* Horizontal pixel panning */
};
static struct chips_init_reg chips_init_cr[] =
{
{0x0c, 0x00}, /* Start address high */
{0x0d, 0x00}, /* Start address low */
{0x40, 0x00}, /* Extended Start Address */
{0x41, 0x00}, /* Extended Start Address */
{0x14, 0x00}, /* Underline location */
{0x17, 0xe3}, /* CRT mode control */
{0x70, 0x00} /* Interlace control */
};
static struct chips_init_reg chips_init_fr[] =
{
{0x01, 0x02},
{0x03, 0x08},
{0x08, 0xcc},
{0x0a, 0x08},
{0x18, 0x00},
{0x1e, 0x80},
{0x40, 0x83},
{0x41, 0x00},
{0x48, 0x13},
{0x4d, 0x60},
{0x4e, 0x0f},
{0x0b, 0x01},
{0x21, 0x51},
{0x22, 0x1d},
{0x23, 0x5f},
{0x20, 0x4f},
{0x34, 0x00},
{0x24, 0x51},
{0x25, 0x00},
{0x27, 0x0b},
{0x26, 0x00},
{0x37, 0x80},
{0x33, 0x0b},
{0x35, 0x11},
{0x36, 0x02},
{0x31, 0xea},
{0x32, 0x0c},
{0x30, 0xdf},
{0x10, 0x0c},
{0x11, 0xe0},
{0x12, 0x50},
{0x13, 0x00},
{0x16, 0x03},
{0x17, 0xbd},
{0x1a, 0x00},
};
static struct chips_init_reg chips_init_xr[] =
{
{0xce, 0x00}, /* set default memory clock */
{0xcc, 200 }, /* MCLK ratio M */
{0xcd, 18 }, /* MCLK ratio N */
{0xce, 0x90}, /* MCLK divisor = 2 */
{0xc4, 209 },
{0xc5, 118 },
{0xc7, 32 },
{0xcf, 0x06},
{0x09, 0x01}, /* IO Control - CRT controller extensions */
{0x0a, 0x02}, /* Frame buffer mapping */
{0x0b, 0x01}, /* PCI burst write */
{0x40, 0x03}, /* Memory access control */
{0x80, 0x82}, /* Pixel pipeline configuration 0 */
{0x81, 0x12}, /* Pixel pipeline configuration 1 */
{0x82, 0x08}, /* Pixel pipeline configuration 2 */
{0xd0, 0x0f},
{0xd1, 0x01},
};
static void __devinit chips_hw_init(struct fb_info *p)
{
int i;
for (i = 0; i < ARRAY_SIZE(chips_init_xr); ++i)
write_xr(chips_init_xr[i].addr, chips_init_xr[i].data);
write_xr(0x81, 0x12);
write_xr(0x82, 0x08);
write_xr(0x20, 0x00);
for (i = 0; i < ARRAY_SIZE(chips_init_sr); ++i)
write_sr(chips_init_sr[i].addr, chips_init_sr[i].data);
for (i = 0; i < ARRAY_SIZE(chips_init_gr); ++i)
write_gr(chips_init_gr[i].addr, chips_init_gr[i].data);
for (i = 0; i < ARRAY_SIZE(chips_init_ar); ++i)
write_ar(chips_init_ar[i].addr, chips_init_ar[i].data);
/* Enable video output in attribute index register */
writeb(0x20, mmio_base + 0x780);
for (i = 0; i < ARRAY_SIZE(chips_init_cr); ++i)
write_cr(chips_init_cr[i].addr, chips_init_cr[i].data);
for (i = 0; i < ARRAY_SIZE(chips_init_fr); ++i)
write_fr(chips_init_fr[i].addr, chips_init_fr[i].data);
}
static struct fb_fix_screeninfo asiliantfb_fix __devinitdata = {
.id = "Asiliant 69000",
.type = FB_TYPE_PACKED_PIXELS,
.visual = FB_VISUAL_PSEUDOCOLOR,
.accel = FB_ACCEL_NONE,
.line_length = 640,
.smem_len = 0x200000, /* 2MB */
};
static struct fb_var_screeninfo asiliantfb_var __devinitdata = {
.xres = 640,
.yres = 480,
.xres_virtual = 640,
.yres_virtual = 480,
.bits_per_pixel = 8,
.red = { .length = 8 },
.green = { .length = 8 },
.blue = { .length = 8 },
.height = -1,
.width = -1,
.vmode = FB_VMODE_NONINTERLACED,
.pixclock = 39722,
.left_margin = 48,
.right_margin = 16,
.upper_margin = 33,
.lower_margin = 10,
.hsync_len = 96,
.vsync_len = 2,
};
static int __devinit init_asiliant(struct fb_info *p, unsigned long addr)
{
int err;
p->fix = asiliantfb_fix;
p->fix.smem_start = addr;
p->var = asiliantfb_var;
p->fbops = &asiliantfb_ops;
p->flags = FBINFO_DEFAULT;
err = fb_alloc_cmap(&p->cmap, 256, 0);
if (err) {
printk(KERN_ERR "C&T 69000 fb failed to alloc cmap memory\n");
return err;
}
err = register_framebuffer(p);
if (err < 0) {
printk(KERN_ERR "C&T 69000 framebuffer failed to register\n");
fb_dealloc_cmap(&p->cmap);
return err;
}
printk(KERN_INFO "fb%d: Asiliant 69000 frame buffer (%dK RAM detected)\n",
p->node, p->fix.smem_len / 1024);
writeb(0xff, mmio_base + 0x78c);
chips_hw_init(p);
return 0;
}
static int __devinit
asiliantfb_pci_init(struct pci_dev *dp, const struct pci_device_id *ent)
{
unsigned long addr, size;
struct fb_info *p;
int err;
if ((dp->resource[0].flags & IORESOURCE_MEM) == 0)
return -ENODEV;
addr = pci_resource_start(dp, 0);
size = pci_resource_len(dp, 0);
if (addr == 0)
return -ENODEV;
if (!request_mem_region(addr, size, "asiliantfb"))
return -EBUSY;
p = framebuffer_alloc(sizeof(u32) * 16, &dp->dev);
if (!p) {
release_mem_region(addr, size);
return -ENOMEM;
}
p->pseudo_palette = p->par;
p->par = NULL;
p->screen_base = ioremap(addr, 0x800000);
if (p->screen_base == NULL) {
release_mem_region(addr, size);
framebuffer_release(p);
return -ENOMEM;
}
pci_write_config_dword(dp, 4, 0x02800083);
writeb(3, p->screen_base + 0x400784);
err = init_asiliant(p, addr);
if (err) {
iounmap(p->screen_base);
release_mem_region(addr, size);
framebuffer_release(p);
return err;
}
pci_set_drvdata(dp, p);
return 0;
}
static void __devexit asiliantfb_remove(struct pci_dev *dp)
{
struct fb_info *p = pci_get_drvdata(dp);
unregister_framebuffer(p);
fb_dealloc_cmap(&p->cmap);
iounmap(p->screen_base);
release_mem_region(pci_resource_start(dp, 0), pci_resource_len(dp, 0));
pci_set_drvdata(dp, NULL);
framebuffer_release(p);
}
static struct pci_device_id asiliantfb_pci_tbl[] __devinitdata = {
{ PCI_VENDOR_ID_CT, PCI_DEVICE_ID_CT_69000, PCI_ANY_ID, PCI_ANY_ID },
{ 0 }
};
MODULE_DEVICE_TABLE(pci, asiliantfb_pci_tbl);
static struct pci_driver asiliantfb_driver = {
.name = "asiliantfb",
.id_table = asiliantfb_pci_tbl,
.probe = asiliantfb_pci_init,
.remove = __devexit_p(asiliantfb_remove),
};
static int __init asiliantfb_init(void)
{
if (fb_get_options("asiliantfb", NULL))
return -ENODEV;
return pci_register_driver(&asiliantfb_driver);
}
module_init(asiliantfb_init);
static void __exit asiliantfb_exit(void)
{
pci_unregister_driver(&asiliantfb_driver);
}
MODULE_LICENSE("GPL");
| gpl-2.0 |
Split-Screen/android_kernel_lge_gproj | arch/mips/pci/fixup-malta.c | 9271 | 2876 | #include <linux/init.h>
#include <linux/pci.h>
/* PCI interrupt pins */
#define PCIA 1
#define PCIB 2
#define PCIC 3
#define PCID 4
/* This table is filled in by interrogating the PIIX4 chip */
static char pci_irq[5] __initdata;
static char irq_tab[][5] __initdata = {
/* INTA INTB INTC INTD */
{0, 0, 0, 0, 0 }, /* 0: GT64120 PCI bridge */
{0, 0, 0, 0, 0 }, /* 1: Unused */
{0, 0, 0, 0, 0 }, /* 2: Unused */
{0, 0, 0, 0, 0 }, /* 3: Unused */
{0, 0, 0, 0, 0 }, /* 4: Unused */
{0, 0, 0, 0, 0 }, /* 5: Unused */
{0, 0, 0, 0, 0 }, /* 6: Unused */
{0, 0, 0, 0, 0 }, /* 7: Unused */
{0, 0, 0, 0, 0 }, /* 8: Unused */
{0, 0, 0, 0, 0 }, /* 9: Unused */
{0, 0, 0, 0, PCID }, /* 10: PIIX4 USB */
{0, PCIB, 0, 0, 0 }, /* 11: AMD 79C973 Ethernet */
{0, PCIC, 0, 0, 0 }, /* 12: Crystal 4281 Sound */
{0, 0, 0, 0, 0 }, /* 13: Unused */
{0, 0, 0, 0, 0 }, /* 14: Unused */
{0, 0, 0, 0, 0 }, /* 15: Unused */
{0, 0, 0, 0, 0 }, /* 16: Unused */
{0, 0, 0, 0, 0 }, /* 17: Bonito/SOC-it PCI Bridge*/
{0, PCIA, PCIB, PCIC, PCID }, /* 18: PCI Slot 1 */
{0, PCIB, PCIC, PCID, PCIA }, /* 19: PCI Slot 2 */
{0, PCIC, PCID, PCIA, PCIB }, /* 20: PCI Slot 3 */
{0, PCID, PCIA, PCIB, PCIC } /* 21: PCI Slot 4 */
};
int __init pcibios_map_irq(const struct pci_dev *dev, u8 slot, u8 pin)
{
int virq;
virq = irq_tab[slot][pin];
return pci_irq[virq];
}
/* Do platform specific device initialization at pci_enable_device() time */
int pcibios_plat_dev_init(struct pci_dev *dev)
{
return 0;
}
static void __init malta_piix_func0_fixup(struct pci_dev *pdev)
{
unsigned char reg_val;
static int piixirqmap[16] __initdata = { /* PIIX PIRQC[A:D] irq mappings */
0, 0, 0, 3,
4, 5, 6, 7,
0, 9, 10, 11,
12, 0, 14, 15
};
int i;
/* Interrogate PIIX4 to get PCI IRQ mapping */
for (i = 0; i <= 3; i++) {
pci_read_config_byte(pdev, 0x60+i, ®_val);
if (reg_val & 0x80)
pci_irq[PCIA+i] = 0; /* Disabled */
else
pci_irq[PCIA+i] = piixirqmap[reg_val & 15];
}
/* Done by YAMON 2.00 onwards */
if (PCI_SLOT(pdev->devfn) == 10) {
/*
* Set top of main memory accessible by ISA or DMA
* devices to 16 Mb.
*/
pci_read_config_byte(pdev, 0x69, ®_val);
pci_write_config_byte(pdev, 0x69, reg_val | 0xf0);
}
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82371AB_0,
malta_piix_func0_fixup);
static void __init malta_piix_func1_fixup(struct pci_dev *pdev)
{
unsigned char reg_val;
/* Done by YAMON 2.02 onwards */
if (PCI_SLOT(pdev->devfn) == 10) {
/*
* IDE Decode enable.
*/
pci_read_config_byte(pdev, 0x41, ®_val);
pci_write_config_byte(pdev, 0x41, reg_val|0x80);
pci_read_config_byte(pdev, 0x43, ®_val);
pci_write_config_byte(pdev, 0x43, reg_val|0x80);
}
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82371AB,
malta_piix_func1_fixup);
| gpl-2.0 |
myhro/debian-linux-kernel-gzip | drivers/staging/comedi/drivers/addi-data/hwdrv_apci3120.c | 56 | 66857 | /**
@verbatim
Copyright (C) 2004,2005 ADDI-DATA GmbH for the source code of this module.
ADDI-DATA GmbH
Dieselstrasse 3
D-77833 Ottersweier
Tel: +19(0)7223/9493-0
Fax: +49(0)7223/9493-92
http://www.addi-data.com
info@addi-data.com
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
@endverbatim
*/
/*
+-----------------------------------------------------------------------+
| (C) ADDI-DATA GmbH Dieselstrasse 3 D-77833 Ottersweier |
+-----------------------------------------------------------------------+
| Tel : +49 (0) 7223/9493-0 | email : info@addi-data.com |
| Fax : +49 (0) 7223/9493-92 | Internet : http://www.addi-data.com |
+-----------------------------------------------------------------------+
| Project : APCI-3120 | Compiler : GCC |
| Module name : hwdrv_apci3120.c| Version : 2.96 |
+-------------------------------+---------------------------------------+
| Project manager: Eric Stolz | Date : 02/12/2002 |
+-----------------------------------------------------------------------+
| Description :APCI3120 Module. Hardware abstraction Layer for APCI3120|
+-----------------------------------------------------------------------+
| UPDATE'S |
+-----------------------------------------------------------------------+
| Date | Author | Description of updates |
+----------+-----------+------------------------------------------------+
| | | |
| | | |
+----------+-----------+------------------------------------------------+
*/
#include <linux/delay.h>
/*
* ADDON RELATED ADDITIONS
*/
/* Constant */
#define APCI3120_ENABLE_TRANSFER_ADD_ON_LOW 0x00
#define APCI3120_ENABLE_TRANSFER_ADD_ON_HIGH 0x1200
#define APCI3120_A2P_FIFO_MANAGEMENT 0x04000400L
#define APCI3120_AMWEN_ENABLE 0x02
#define APCI3120_A2P_FIFO_WRITE_ENABLE 0x01
#define APCI3120_FIFO_ADVANCE_ON_BYTE_2 0x20000000L
#define APCI3120_ENABLE_WRITE_TC_INT 0x00004000L
#define APCI3120_CLEAR_WRITE_TC_INT 0x00040000L
#define APCI3120_DISABLE_AMWEN_AND_A2P_FIFO_WRITE 0x0
#define APCI3120_DISABLE_BUS_MASTER_ADD_ON 0x0
#define APCI3120_DISABLE_BUS_MASTER_PCI 0x0
/* ADD_ON ::: this needed since apci supports 16 bit interface to add on */
#define APCI3120_ADD_ON_AGCSTS_LOW 0x3C
#define APCI3120_ADD_ON_AGCSTS_HIGH (APCI3120_ADD_ON_AGCSTS_LOW + 2)
#define APCI3120_ADD_ON_MWAR_LOW 0x24
#define APCI3120_ADD_ON_MWAR_HIGH (APCI3120_ADD_ON_MWAR_LOW + 2)
#define APCI3120_ADD_ON_MWTC_LOW 0x058
#define APCI3120_ADD_ON_MWTC_HIGH (APCI3120_ADD_ON_MWTC_LOW + 2)
/* AMCC */
#define APCI3120_AMCC_OP_MCSR 0x3C
#define APCI3120_AMCC_OP_REG_INTCSR 0x38
/* for transfer count enable bit */
#define AGCSTS_TC_ENABLE 0x10000000
/* used for test on mixture of BIP/UNI ranges */
#define APCI3120_BIPOLAR_RANGES 4
#define APCI3120_ADDRESS_RANGE 16
#define APCI3120_DISABLE 0
#define APCI3120_ENABLE 1
#define APCI3120_START 1
#define APCI3120_STOP 0
#define APCI3120_EOC_MODE 1
#define APCI3120_EOS_MODE 2
#define APCI3120_DMA_MODE 3
/* DIGITAL INPUT-OUTPUT DEFINE */
#define APCI3120_DIGITAL_OUTPUT 0x0d
#define APCI3120_RD_STATUS 0x02
#define APCI3120_RD_FIFO 0x00
/* digital output insn_write ON /OFF selection */
#define APCI3120_SET4DIGITALOUTPUTON 1
#define APCI3120_SET4DIGITALOUTPUTOFF 0
/* analog output SELECT BIT */
#define APCI3120_ANALOG_OP_CHANNEL_1 0x0000
#define APCI3120_ANALOG_OP_CHANNEL_2 0x4000
#define APCI3120_ANALOG_OP_CHANNEL_3 0x8000
#define APCI3120_ANALOG_OP_CHANNEL_4 0xc000
#define APCI3120_ANALOG_OP_CHANNEL_5 0x0000
#define APCI3120_ANALOG_OP_CHANNEL_6 0x4000
#define APCI3120_ANALOG_OP_CHANNEL_7 0x8000
#define APCI3120_ANALOG_OP_CHANNEL_8 0xc000
/* Enable external trigger bit in nWrAddress */
#define APCI3120_ENABLE_EXT_TRIGGER 0x8000
/* ANALOG OUTPUT AND INPUT DEFINE */
#define APCI3120_UNIPOLAR 0x80
#define APCI3120_BIPOLAR 0x00
#define APCI3120_ANALOG_OUTPUT_1 0x08
#define APCI3120_ANALOG_OUTPUT_2 0x0a
#define APCI3120_1_GAIN 0x00
#define APCI3120_2_GAIN 0x10
#define APCI3120_5_GAIN 0x20
#define APCI3120_10_GAIN 0x30
#define APCI3120_SEQ_RAM_ADDRESS 0x06
#define APCI3120_RESET_FIFO 0x0c
#define APCI3120_TIMER_0_MODE_2 0x01
#define APCI3120_TIMER_0_MODE_4 0x2
#define APCI3120_SELECT_TIMER_0_WORD 0x00
#define APCI3120_ENABLE_TIMER0 0x1000
#define APCI3120_CLEAR_PR 0xf0ff
#define APCI3120_CLEAR_PA 0xfff0
#define APCI3120_CLEAR_PA_PR (APCI3120_CLEAR_PR & APCI3120_CLEAR_PA)
/* nWrMode_Select */
#define APCI3120_ENABLE_SCAN 0x8
#define APCI3120_DISABLE_SCAN (~APCI3120_ENABLE_SCAN)
#define APCI3120_ENABLE_EOS_INT 0x2
#define APCI3120_DISABLE_EOS_INT (~APCI3120_ENABLE_EOS_INT)
#define APCI3120_ENABLE_EOC_INT 0x1
#define APCI3120_DISABLE_EOC_INT (~APCI3120_ENABLE_EOC_INT)
#define APCI3120_DISABLE_ALL_INTERRUPT_WITHOUT_TIMER \
(APCI3120_DISABLE_EOS_INT & APCI3120_DISABLE_EOC_INT)
#define APCI3120_DISABLE_ALL_INTERRUPT \
(APCI3120_DISABLE_TIMER_INT & APCI3120_DISABLE_EOS_INT & APCI3120_DISABLE_EOC_INT)
/* status register bits */
#define APCI3120_EOC 0x8000
#define APCI3120_EOS 0x2000
/* software trigger dummy register */
#define APCI3120_START_CONVERSION 0x02
/* TIMER DEFINE */
#define APCI3120_QUARTZ_A 70
#define APCI3120_QUARTZ_B 50
#define APCI3120_TIMER 1
#define APCI3120_WATCHDOG 2
#define APCI3120_TIMER_DISABLE 0
#define APCI3120_TIMER_ENABLE 1
#define APCI3120_ENABLE_TIMER2 0x4000
#define APCI3120_DISABLE_TIMER2 (~APCI3120_ENABLE_TIMER2)
#define APCI3120_ENABLE_TIMER_INT 0x04
#define APCI3120_DISABLE_TIMER_INT (~APCI3120_ENABLE_TIMER_INT)
#define APCI3120_WRITE_MODE_SELECT 0x0e
#define APCI3120_SELECT_TIMER_0_WORD 0x00
#define APCI3120_SELECT_TIMER_1_WORD 0x01
#define APCI3120_TIMER_1_MODE_2 0x4
/* $$ BIT FOR MODE IN nCsTimerCtr1 */
#define APCI3120_TIMER_2_MODE_0 0x0
#define APCI3120_TIMER_2_MODE_2 0x10
#define APCI3120_TIMER_2_MODE_5 0x30
/* $$ BIT FOR MODE IN nCsTimerCtr0 */
#define APCI3120_SELECT_TIMER_2_LOW_WORD 0x02
#define APCI3120_SELECT_TIMER_2_HIGH_WORD 0x03
#define APCI3120_TIMER_CRT0 0x0d
#define APCI3120_TIMER_CRT1 0x0c
#define APCI3120_TIMER_VALUE 0x04
#define APCI3120_TIMER_STATUS_REGISTER 0x0d
#define APCI3120_RD_STATUS 0x02
#define APCI3120_WR_ADDRESS 0x00
#define APCI3120_ENABLE_WATCHDOG 0x20
#define APCI3120_DISABLE_WATCHDOG (~APCI3120_ENABLE_WATCHDOG)
#define APCI3120_ENABLE_TIMER_COUNTER 0x10
#define APCI3120_DISABLE_TIMER_COUNTER (~APCI3120_ENABLE_TIMER_COUNTER)
#define APCI3120_FC_TIMER 0x1000
#define APCI3120_ENABLE_TIMER0 0x1000
#define APCI3120_ENABLE_TIMER1 0x2000
#define APCI3120_ENABLE_TIMER2 0x4000
#define APCI3120_DISABLE_TIMER0 (~APCI3120_ENABLE_TIMER0)
#define APCI3120_DISABLE_TIMER1 (~APCI3120_ENABLE_TIMER1)
#define APCI3120_DISABLE_TIMER2 (~APCI3120_ENABLE_TIMER2)
#define APCI3120_TIMER2_SELECT_EOS 0xc0
#define APCI3120_COUNTER 3
#define APCI3120_DISABLE_ALL_TIMER (APCI3120_DISABLE_TIMER0 & \
APCI3120_DISABLE_TIMER1 & \
APCI3120_DISABLE_TIMER2)
#define MAX_ANALOGINPUT_CHANNELS 32
struct str_AnalogReadInformation {
/* EOC or EOS */
unsigned char b_Type;
/* Interrupt use or not */
unsigned char b_InterruptFlag;
/* Selection of the conversion time */
unsigned int ui_ConvertTiming;
/* Number of channel to read */
unsigned char b_NbrOfChannel;
/* Number of the channel to be read */
unsigned int ui_ChannelList[MAX_ANALOGINPUT_CHANNELS];
/* Gain of each channel */
unsigned int ui_RangeList[MAX_ANALOGINPUT_CHANNELS];
};
/* ANALOG INPUT RANGE */
static const struct comedi_lrange range_apci3120_ai = {
8, {
BIP_RANGE(10),
BIP_RANGE(5),
BIP_RANGE(2),
BIP_RANGE(1),
UNI_RANGE(10),
UNI_RANGE(5),
UNI_RANGE(2),
UNI_RANGE(1)
}
};
/* ANALOG OUTPUT RANGE */
static const struct comedi_lrange range_apci3120_ao = {
2, {
BIP_RANGE(10),
UNI_RANGE(10)
}
};
/* FUNCTION DEFINITIONS */
/*
+----------------------------------------------------------------------------+
| ANALOG INPUT SUBDEVICE |
+----------------------------------------------------------------------------+
*/
static int apci3120_ai_insn_config(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
const struct addi_board *this_board = comedi_board(dev);
struct addi_private *devpriv = dev->private;
unsigned int i;
if ((data[0] != APCI3120_EOC_MODE) && (data[0] != APCI3120_EOS_MODE))
return -1;
/* Check for Conversion time to be added ?? */
devpriv->ui_EocEosConversionTime = data[2];
if (data[0] == APCI3120_EOS_MODE) {
/* Test the number of the channel */
for (i = 0; i < data[3]; i++) {
if (CR_CHAN(data[4 + i]) >=
this_board->i_NbrAiChannel) {
printk("bad channel list\n");
return -2;
}
}
devpriv->b_InterruptMode = APCI3120_EOS_MODE;
if (data[1])
devpriv->b_EocEosInterrupt = APCI3120_ENABLE;
else
devpriv->b_EocEosInterrupt = APCI3120_DISABLE;
/* Copy channel list and Range List to devpriv */
devpriv->ui_AiNbrofChannels = data[3];
for (i = 0; i < devpriv->ui_AiNbrofChannels; i++)
devpriv->ui_AiChannelList[i] = data[4 + i];
} else { /* EOC */
devpriv->b_InterruptMode = APCI3120_EOC_MODE;
if (data[1])
devpriv->b_EocEosInterrupt = APCI3120_ENABLE;
else
devpriv->b_EocEosInterrupt = APCI3120_DISABLE;
}
return insn->n;
}
/*
* This function will first check channel list is ok or not and then
* initialize the sequence RAM with the polarity, Gain,Channel number.
* If the last argument of function "check"is 1 then it only checks
* the channel list is ok or not.
*/
static int apci3120_setup_chan_list(struct comedi_device *dev,
struct comedi_subdevice *s,
int n_chan,
unsigned int *chanlist,
char check)
{
struct addi_private *devpriv = dev->private;
unsigned int i; /* , differencial=0, bipolar=0; */
unsigned int gain;
unsigned short us_TmpValue;
/* correct channel and range number check itself comedi/range.c */
if (n_chan < 1) {
if (!check)
comedi_error(dev, "range/channel list is empty!");
return 0;
}
/* All is ok, so we can setup channel/range list */
if (check)
return 1;
/* Code to set the PA and PR...Here it set PA to 0.. */
devpriv->us_OutputRegister =
devpriv->us_OutputRegister & APCI3120_CLEAR_PA_PR;
devpriv->us_OutputRegister = ((n_chan - 1) & 0xf) << 8;
outw(devpriv->us_OutputRegister, dev->iobase + APCI3120_WR_ADDRESS);
for (i = 0; i < n_chan; i++) {
/* store range list to card */
us_TmpValue = CR_CHAN(chanlist[i]); /* get channel number; */
if (CR_RANGE(chanlist[i]) < APCI3120_BIPOLAR_RANGES)
us_TmpValue &= ((~APCI3120_UNIPOLAR) & 0xff); /* set bipolar */
else
us_TmpValue |= APCI3120_UNIPOLAR; /* enable unipolar...... */
gain = CR_RANGE(chanlist[i]); /* get gain number */
us_TmpValue |= ((gain & 0x03) << 4); /* <<4 for G0 and G1 bit in RAM */
us_TmpValue |= i << 8; /* To select the RAM LOCATION.... */
outw(us_TmpValue, dev->iobase + APCI3120_SEQ_RAM_ADDRESS);
printk("\n Gain = %i",
(((unsigned char)CR_RANGE(chanlist[i]) & 0x03) << 2));
printk("\n Channel = %i", CR_CHAN(chanlist[i]));
printk("\n Polarity = %i", us_TmpValue & APCI3120_UNIPOLAR);
}
return 1; /* we can serve this with scan logic */
}
/*
* Reads analog input in synchronous mode EOC and EOS is selected
* as per configured if no conversion time is set uses default
* conversion time 10 microsec.
*/
static int apci3120_ai_insn_read(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
const struct addi_board *this_board = comedi_board(dev);
struct addi_private *devpriv = dev->private;
unsigned short us_ConvertTiming, us_TmpValue, i;
unsigned char b_Tmp;
/* fix conversion time to 10 us */
if (!devpriv->ui_EocEosConversionTime) {
printk("No timer0 Value using 10 us\n");
us_ConvertTiming = 10;
} else
us_ConvertTiming = (unsigned short) (devpriv->ui_EocEosConversionTime / 1000); /* nano to useconds */
/* this_board->ai_read(dev,us_ConvertTiming,insn->n,&insn->chanspec,data,insn->unused[0]); */
/* Clear software registers */
devpriv->b_TimerSelectMode = 0;
devpriv->b_ModeSelectRegister = 0;
devpriv->us_OutputRegister = 0;
/* devpriv->b_DigitalOutputRegister=0; */
if (insn->unused[0] == 222) { /* second insn read */
for (i = 0; i < insn->n; i++)
data[i] = devpriv->ui_AiReadData[i];
} else {
devpriv->tsk_Current = current; /* Save the current process task structure */
/*
* Testing if board have the new Quartz and calculate the time value
* to set in the timer
*/
us_TmpValue =
(unsigned short) inw(devpriv->iobase + APCI3120_RD_STATUS);
/* EL250804: Testing if board APCI3120 have the new Quartz or if it is an APCI3001 */
if ((us_TmpValue & 0x00B0) == 0x00B0
|| !strcmp(this_board->pc_DriverName, "apci3001")) {
us_ConvertTiming = (us_ConvertTiming * 2) - 2;
} else {
us_ConvertTiming =
((us_ConvertTiming * 12926) / 10000) - 1;
}
us_TmpValue = (unsigned short) devpriv->b_InterruptMode;
switch (us_TmpValue) {
case APCI3120_EOC_MODE:
/*
* Testing the interrupt flag and set the EOC bit Clears the FIFO
*/
inw(devpriv->iobase + APCI3120_RESET_FIFO);
/* Initialize the sequence array */
if (!apci3120_setup_chan_list(dev, s, 1,
&insn->chanspec, 0))
return -EINVAL;
/* Initialize Timer 0 mode 4 */
devpriv->b_TimerSelectMode =
(devpriv->
b_TimerSelectMode & 0xFC) |
APCI3120_TIMER_0_MODE_4;
outb(devpriv->b_TimerSelectMode,
devpriv->iobase + APCI3120_TIMER_CRT1);
/* Reset the scan bit and Disables the EOS, DMA, EOC interrupt */
devpriv->b_ModeSelectRegister =
devpriv->
b_ModeSelectRegister & APCI3120_DISABLE_SCAN;
if (devpriv->b_EocEosInterrupt == APCI3120_ENABLE) {
/* Disables the EOS,DMA and enables the EOC interrupt */
devpriv->b_ModeSelectRegister =
(devpriv->
b_ModeSelectRegister &
APCI3120_DISABLE_EOS_INT) |
APCI3120_ENABLE_EOC_INT;
inw(devpriv->iobase);
} else {
devpriv->b_ModeSelectRegister =
devpriv->
b_ModeSelectRegister &
APCI3120_DISABLE_ALL_INTERRUPT_WITHOUT_TIMER;
}
outb(devpriv->b_ModeSelectRegister,
devpriv->iobase + APCI3120_WRITE_MODE_SELECT);
/* Sets gate 0 */
devpriv->us_OutputRegister =
(devpriv->
us_OutputRegister & APCI3120_CLEAR_PA_PR) |
APCI3120_ENABLE_TIMER0;
outw(devpriv->us_OutputRegister,
devpriv->iobase + APCI3120_WR_ADDRESS);
/* Select Timer 0 */
b_Tmp = ((devpriv->
b_DigitalOutputRegister) & 0xF0) |
APCI3120_SELECT_TIMER_0_WORD;
outb(b_Tmp, devpriv->iobase + APCI3120_TIMER_CRT0);
/* Set the conversion time */
outw(us_ConvertTiming,
devpriv->iobase + APCI3120_TIMER_VALUE);
us_TmpValue =
(unsigned short) inw(dev->iobase + APCI3120_RD_STATUS);
if (devpriv->b_EocEosInterrupt == APCI3120_DISABLE) {
do {
/* Waiting for the end of conversion */
us_TmpValue =
inw(devpriv->iobase +
APCI3120_RD_STATUS);
} while ((us_TmpValue & APCI3120_EOC) ==
APCI3120_EOC);
/* Read the result in FIFO and put it in insn data pointer */
us_TmpValue = inw(devpriv->iobase + 0);
*data = us_TmpValue;
inw(devpriv->iobase + APCI3120_RESET_FIFO);
}
break;
case APCI3120_EOS_MODE:
inw(devpriv->iobase);
/* Clears the FIFO */
inw(devpriv->iobase + APCI3120_RESET_FIFO);
/* clear PA PR and disable timer 0 */
devpriv->us_OutputRegister =
(devpriv->
us_OutputRegister & APCI3120_CLEAR_PA_PR) |
APCI3120_DISABLE_TIMER0;
outw(devpriv->us_OutputRegister,
devpriv->iobase + APCI3120_WR_ADDRESS);
if (!apci3120_setup_chan_list(dev, s,
devpriv->ui_AiNbrofChannels,
devpriv->ui_AiChannelList, 0))
return -EINVAL;
/* Initialize Timer 0 mode 2 */
devpriv->b_TimerSelectMode =
(devpriv->
b_TimerSelectMode & 0xFC) |
APCI3120_TIMER_0_MODE_2;
outb(devpriv->b_TimerSelectMode,
devpriv->iobase + APCI3120_TIMER_CRT1);
/* Select Timer 0 */
b_Tmp = ((devpriv->
b_DigitalOutputRegister) & 0xF0) |
APCI3120_SELECT_TIMER_0_WORD;
outb(b_Tmp, devpriv->iobase + APCI3120_TIMER_CRT0);
/* Set the conversion time */
outw(us_ConvertTiming,
devpriv->iobase + APCI3120_TIMER_VALUE);
/* Set the scan bit */
devpriv->b_ModeSelectRegister =
devpriv->
b_ModeSelectRegister | APCI3120_ENABLE_SCAN;
outb(devpriv->b_ModeSelectRegister,
devpriv->iobase + APCI3120_WRITE_MODE_SELECT);
/* If Interrupt function is loaded */
if (devpriv->b_EocEosInterrupt == APCI3120_ENABLE) {
/* Disables the EOC,DMA and enables the EOS interrupt */
devpriv->b_ModeSelectRegister =
(devpriv->
b_ModeSelectRegister &
APCI3120_DISABLE_EOC_INT) |
APCI3120_ENABLE_EOS_INT;
inw(devpriv->iobase);
} else
devpriv->b_ModeSelectRegister =
devpriv->
b_ModeSelectRegister &
APCI3120_DISABLE_ALL_INTERRUPT_WITHOUT_TIMER;
outb(devpriv->b_ModeSelectRegister,
devpriv->iobase + APCI3120_WRITE_MODE_SELECT);
inw(devpriv->iobase + APCI3120_RD_STATUS);
/* Sets gate 0 */
devpriv->us_OutputRegister =
devpriv->
us_OutputRegister | APCI3120_ENABLE_TIMER0;
outw(devpriv->us_OutputRegister,
devpriv->iobase + APCI3120_WR_ADDRESS);
/* Start conversion */
outw(0, devpriv->iobase + APCI3120_START_CONVERSION);
/* Waiting of end of conversion if interrupt is not installed */
if (devpriv->b_EocEosInterrupt == APCI3120_DISABLE) {
/* Waiting the end of conversion */
do {
us_TmpValue =
inw(devpriv->iobase +
APCI3120_RD_STATUS);
} while ((us_TmpValue & APCI3120_EOS) !=
APCI3120_EOS);
for (i = 0; i < devpriv->ui_AiNbrofChannels;
i++) {
/* Read the result in FIFO and write them in shared memory */
us_TmpValue = inw(devpriv->iobase);
data[i] = (unsigned int) us_TmpValue;
}
devpriv->b_InterruptMode = APCI3120_EOC_MODE; /* Restore defaults. */
}
break;
default:
printk("inputs wrong\n");
}
devpriv->ui_EocEosConversionTime = 0; /* re initializing the variable; */
}
return insn->n;
}
static int apci3120_reset(struct comedi_device *dev)
{
struct addi_private *devpriv = dev->private;
unsigned int i;
unsigned short us_TmpValue;
devpriv->ai_running = 0;
devpriv->b_EocEosInterrupt = APCI3120_DISABLE;
devpriv->b_InterruptMode = APCI3120_EOC_MODE;
devpriv->ui_EocEosConversionTime = 0; /* set eoc eos conv time to 0 */
/* variables used in timer subdevice */
devpriv->b_Timer2Mode = 0;
devpriv->b_Timer2Interrupt = 0;
devpriv->b_ExttrigEnable = 0; /* Disable ext trigger */
/* Disable all interrupts, watchdog for the anolog output */
devpriv->b_ModeSelectRegister = 0;
outb(devpriv->b_ModeSelectRegister,
dev->iobase + APCI3120_WRITE_MODE_SELECT);
/* Disables all counters, ext trigger and clears PA, PR */
devpriv->us_OutputRegister = 0;
outw(devpriv->us_OutputRegister, dev->iobase + APCI3120_WR_ADDRESS);
/*
* Code to set the all anolog o/p channel to 0v 8191 is decimal
* value for zero(0 v)volt in bipolar mode(default)
*/
outw(8191 | APCI3120_ANALOG_OP_CHANNEL_1, dev->iobase + APCI3120_ANALOG_OUTPUT_1); /* channel 1 */
outw(8191 | APCI3120_ANALOG_OP_CHANNEL_2, dev->iobase + APCI3120_ANALOG_OUTPUT_1); /* channel 2 */
outw(8191 | APCI3120_ANALOG_OP_CHANNEL_3, dev->iobase + APCI3120_ANALOG_OUTPUT_1); /* channel 3 */
outw(8191 | APCI3120_ANALOG_OP_CHANNEL_4, dev->iobase + APCI3120_ANALOG_OUTPUT_1); /* channel 4 */
outw(8191 | APCI3120_ANALOG_OP_CHANNEL_5, dev->iobase + APCI3120_ANALOG_OUTPUT_2); /* channel 5 */
outw(8191 | APCI3120_ANALOG_OP_CHANNEL_6, dev->iobase + APCI3120_ANALOG_OUTPUT_2); /* channel 6 */
outw(8191 | APCI3120_ANALOG_OP_CHANNEL_7, dev->iobase + APCI3120_ANALOG_OUTPUT_2); /* channel 7 */
outw(8191 | APCI3120_ANALOG_OP_CHANNEL_8, dev->iobase + APCI3120_ANALOG_OUTPUT_2); /* channel 8 */
/* Reset digital output to L0W */
/* ES05 outb(0x0,dev->iobase+APCI3120_DIGITAL_OUTPUT); */
udelay(10);
inw(dev->iobase + 0); /* make a dummy read */
inb(dev->iobase + APCI3120_RESET_FIFO); /* flush FIFO */
inw(dev->iobase + APCI3120_RD_STATUS); /* flush A/D status register */
/* code to reset the RAM sequence */
for (i = 0; i < 16; i++) {
us_TmpValue = i << 8; /* select the location */
outw(us_TmpValue, dev->iobase + APCI3120_SEQ_RAM_ADDRESS);
}
return 0;
}
static int apci3120_exttrig_enable(struct comedi_device *dev)
{
struct addi_private *devpriv = dev->private;
devpriv->us_OutputRegister |= APCI3120_ENABLE_EXT_TRIGGER;
outw(devpriv->us_OutputRegister, dev->iobase + APCI3120_WR_ADDRESS);
return 0;
}
static int apci3120_exttrig_disable(struct comedi_device *dev)
{
struct addi_private *devpriv = dev->private;
devpriv->us_OutputRegister &= ~APCI3120_ENABLE_EXT_TRIGGER;
outw(devpriv->us_OutputRegister, dev->iobase + APCI3120_WR_ADDRESS);
return 0;
}
static int apci3120_cancel(struct comedi_device *dev,
struct comedi_subdevice *s)
{
struct addi_private *devpriv = dev->private;
/* Disable A2P Fifo write and AMWEN signal */
outw(0, devpriv->i_IobaseAddon + 4);
/* Disable Bus Master ADD ON */
outw(APCI3120_ADD_ON_AGCSTS_LOW, devpriv->i_IobaseAddon + 0);
outw(0, devpriv->i_IobaseAddon + 2);
outw(APCI3120_ADD_ON_AGCSTS_HIGH, devpriv->i_IobaseAddon + 0);
outw(0, devpriv->i_IobaseAddon + 2);
/* Disable BUS Master PCI */
outl(0, devpriv->i_IobaseAmcc + AMCC_OP_REG_MCSR);
/* outl(inl(devpriv->i_IobaseAmcc+AMCC_OP_REG_INTCSR)&(~AINT_WRITE_COMPL),
* devpriv->i_IobaseAmcc+AMCC_OP_REG_INTCSR); stop amcc irqs */
/* outl(inl(devpriv->i_IobaseAmcc+AMCC_OP_REG_MCSR)&(~EN_A2P_TRANSFERS),
* devpriv->i_IobaseAmcc+AMCC_OP_REG_MCSR); stop DMA */
/* Disable ext trigger */
apci3120_exttrig_disable(dev);
devpriv->us_OutputRegister = 0;
/* stop counters */
outw(devpriv->
us_OutputRegister & APCI3120_DISABLE_TIMER0 &
APCI3120_DISABLE_TIMER1, dev->iobase + APCI3120_WR_ADDRESS);
outw(APCI3120_DISABLE_ALL_TIMER, dev->iobase + APCI3120_WR_ADDRESS);
/* DISABLE_ALL_INTERRUPT */
outb(APCI3120_DISABLE_ALL_INTERRUPT,
dev->iobase + APCI3120_WRITE_MODE_SELECT);
/* Flush FIFO */
inb(dev->iobase + APCI3120_RESET_FIFO);
inw(dev->iobase + APCI3120_RD_STATUS);
devpriv->ui_AiActualScan = 0;
s->async->cur_chan = 0;
devpriv->ui_DmaActualBuffer = 0;
devpriv->ai_running = 0;
devpriv->b_InterruptMode = APCI3120_EOC_MODE;
devpriv->b_EocEosInterrupt = APCI3120_DISABLE;
apci3120_reset(dev);
return 0;
}
static int apci3120_ai_cmdtest(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_cmd *cmd)
{
int err = 0;
/* Step 1 : check if triggers are trivially valid */
err |= cfc_check_trigger_src(&cmd->start_src, TRIG_NOW | TRIG_EXT);
err |= cfc_check_trigger_src(&cmd->scan_begin_src,
TRIG_TIMER | TRIG_FOLLOW);
err |= cfc_check_trigger_src(&cmd->convert_src, TRIG_TIMER);
err |= cfc_check_trigger_src(&cmd->scan_end_src, TRIG_COUNT);
err |= cfc_check_trigger_src(&cmd->stop_src, TRIG_COUNT | TRIG_NONE);
if (err)
return 1;
/* Step 2a : make sure trigger sources are unique */
err |= cfc_check_trigger_is_unique(cmd->start_src);
err |= cfc_check_trigger_is_unique(cmd->scan_begin_src);
err |= cfc_check_trigger_is_unique(cmd->stop_src);
/* Step 2b : and mutually compatible */
if (err)
return 2;
/* Step 3: check if arguments are trivially valid */
err |= cfc_check_trigger_arg_is(&cmd->start_arg, 0);
if (cmd->scan_begin_src == TRIG_TIMER) /* Test Delay timing */
err |= cfc_check_trigger_arg_min(&cmd->scan_begin_arg, 100000);
if (cmd->scan_begin_src == TRIG_TIMER) {
if (cmd->convert_arg)
err |= cfc_check_trigger_arg_min(&cmd->convert_arg,
10000);
} else {
err |= cfc_check_trigger_arg_min(&cmd->convert_arg, 10000);
}
err |= cfc_check_trigger_arg_min(&cmd->chanlist_len, 1);
err |= cfc_check_trigger_arg_is(&cmd->scan_end_arg, cmd->chanlist_len);
if (cmd->stop_src == TRIG_COUNT)
err |= cfc_check_trigger_arg_min(&cmd->stop_arg, 1);
else /* TRIG_NONE */
err |= cfc_check_trigger_arg_is(&cmd->stop_arg, 0);
if (err)
return 3;
/* step 4: fix up any arguments */
if (cmd->scan_begin_src == TRIG_TIMER &&
cmd->scan_begin_arg < cmd->convert_arg * cmd->scan_end_arg) {
cmd->scan_begin_arg = cmd->convert_arg * cmd->scan_end_arg;
err |= -EINVAL;
}
if (err)
return 4;
return 0;
}
/*
* This is used for analog input cyclic acquisition.
* Performs the command operations.
* If DMA is configured does DMA initialization otherwise does the
* acquisition with EOS interrupt.
*/
static int apci3120_cyclic_ai(int mode,
struct comedi_device *dev,
struct comedi_subdevice *s)
{
const struct addi_board *this_board = comedi_board(dev);
struct addi_private *devpriv = dev->private;
struct comedi_cmd *cmd = &s->async->cmd;
unsigned char b_Tmp;
unsigned int ui_Tmp, ui_DelayTiming = 0, ui_TimerValue1 = 0, dmalen0 =
0, dmalen1 = 0, ui_TimerValue2 =
0, ui_TimerValue0, ui_ConvertTiming;
unsigned short us_TmpValue;
/*******************/
/* Resets the FIFO */
/*******************/
inb(dev->iobase + APCI3120_RESET_FIFO);
/* BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver */
/* inw(dev->iobase+APCI3120_RD_STATUS); */
/* END JK 07.05.04: Comparison between WIN32 and Linux driver */
devpriv->ai_running = 1;
/* clear software registers */
devpriv->b_TimerSelectMode = 0;
devpriv->us_OutputRegister = 0;
devpriv->b_ModeSelectRegister = 0;
/* devpriv->b_DigitalOutputRegister=0; */
/* COMMENT JK 07.05.04: Followings calls are in i_APCI3120_StartAnalogInputAcquisition */
/****************************/
/* Clear Timer Write TC int */
/****************************/
outl(APCI3120_CLEAR_WRITE_TC_INT,
devpriv->i_IobaseAmcc + APCI3120_AMCC_OP_REG_INTCSR);
/************************************/
/* Clears the timer status register */
/************************************/
/* BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver */
/* inw(dev->iobase+APCI3120_TIMER_STATUS_REGISTER); */
/* inb(dev->iobase + APCI3120_TIMER_STATUS_REGISTER); */
/* END JK 07.05.04: Comparison between WIN32 and Linux driver */
/**************************/
/* Disables All Timer */
/* Sets PR and PA to 0 */
/**************************/
devpriv->us_OutputRegister = devpriv->us_OutputRegister &
APCI3120_DISABLE_TIMER0 &
APCI3120_DISABLE_TIMER1 & APCI3120_CLEAR_PA_PR;
outw(devpriv->us_OutputRegister, dev->iobase + APCI3120_WR_ADDRESS);
/*******************/
/* Resets the FIFO */
/*******************/
/* BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver */
inb(devpriv->iobase + APCI3120_RESET_FIFO);
/* END JK 07.05.04: Comparison between WIN32 and Linux driver */
devpriv->ui_AiActualScan = 0;
s->async->cur_chan = 0;
devpriv->ui_DmaActualBuffer = 0;
/* value for timer2 minus -2 has to be done .....dunno y?? */
ui_TimerValue2 = cmd->stop_arg - 2;
ui_ConvertTiming = cmd->convert_arg;
if (mode == 2)
ui_DelayTiming = cmd->scan_begin_arg;
/**********************************/
/* Initializes the sequence array */
/**********************************/
if (!apci3120_setup_chan_list(dev, s, devpriv->ui_AiNbrofChannels,
cmd->chanlist, 0))
return -EINVAL;
us_TmpValue = (unsigned short) inw(dev->iobase + APCI3120_RD_STATUS);
/*** EL241003 : add this section in comment because floats must not be used
if((us_TmpValue & 0x00B0)==0x00B0)
{
f_ConvertValue=(((float)ui_ConvertTiming * 0.002) - 2);
ui_TimerValue0=(unsigned int)f_ConvertValue;
if (mode==2)
{
f_DelayValue = (((float)ui_DelayTiming * 0.00002) - 2);
ui_TimerValue1 = (unsigned int) f_DelayValue;
}
}
else
{
f_ConvertValue=(((float)ui_ConvertTiming * 0.0012926) - 1);
ui_TimerValue0=(unsigned int)f_ConvertValue;
if (mode == 2)
{
f_DelayValue = (((float)ui_DelayTiming * 0.000012926) - 1);
ui_TimerValue1 = (unsigned int) f_DelayValue;
}
}
***********************************************************************************************/
/*** EL241003 Begin : add this section to replace floats calculation by integer calculations **/
/* EL250804: Testing if board APCI3120 have the new Quartz or if it is an APCI3001 */
if ((us_TmpValue & 0x00B0) == 0x00B0
|| !strcmp(this_board->pc_DriverName, "apci3001")) {
ui_TimerValue0 = ui_ConvertTiming * 2 - 2000;
ui_TimerValue0 = ui_TimerValue0 / 1000;
if (mode == 2) {
ui_DelayTiming = ui_DelayTiming / 1000;
ui_TimerValue1 = ui_DelayTiming * 2 - 200;
ui_TimerValue1 = ui_TimerValue1 / 100;
}
} else {
ui_ConvertTiming = ui_ConvertTiming / 1000;
ui_TimerValue0 = ui_ConvertTiming * 12926 - 10000;
ui_TimerValue0 = ui_TimerValue0 / 10000;
if (mode == 2) {
ui_DelayTiming = ui_DelayTiming / 1000;
ui_TimerValue1 = ui_DelayTiming * 12926 - 1;
ui_TimerValue1 = ui_TimerValue1 / 1000000;
}
}
/*** EL241003 End ******************************************************************************/
if (devpriv->b_ExttrigEnable == APCI3120_ENABLE)
apci3120_exttrig_enable(dev); /* activate EXT trigger */
switch (mode) {
case 1:
/* init timer0 in mode 2 */
devpriv->b_TimerSelectMode =
(devpriv->
b_TimerSelectMode & 0xFC) | APCI3120_TIMER_0_MODE_2;
outb(devpriv->b_TimerSelectMode,
dev->iobase + APCI3120_TIMER_CRT1);
/* Select Timer 0 */
b_Tmp = ((devpriv->
b_DigitalOutputRegister) & 0xF0) |
APCI3120_SELECT_TIMER_0_WORD;
outb(b_Tmp, dev->iobase + APCI3120_TIMER_CRT0);
/* Set the conversion time */
outw(((unsigned short) ui_TimerValue0),
dev->iobase + APCI3120_TIMER_VALUE);
break;
case 2:
/* init timer1 in mode 2 */
devpriv->b_TimerSelectMode =
(devpriv->
b_TimerSelectMode & 0xF3) | APCI3120_TIMER_1_MODE_2;
outb(devpriv->b_TimerSelectMode,
dev->iobase + APCI3120_TIMER_CRT1);
/* Select Timer 1 */
b_Tmp = ((devpriv->
b_DigitalOutputRegister) & 0xF0) |
APCI3120_SELECT_TIMER_1_WORD;
outb(b_Tmp, dev->iobase + APCI3120_TIMER_CRT0);
/* Set the conversion time */
outw(((unsigned short) ui_TimerValue1),
dev->iobase + APCI3120_TIMER_VALUE);
/* init timer0 in mode 2 */
devpriv->b_TimerSelectMode =
(devpriv->
b_TimerSelectMode & 0xFC) | APCI3120_TIMER_0_MODE_2;
outb(devpriv->b_TimerSelectMode,
dev->iobase + APCI3120_TIMER_CRT1);
/* Select Timer 0 */
b_Tmp = ((devpriv->
b_DigitalOutputRegister) & 0xF0) |
APCI3120_SELECT_TIMER_0_WORD;
outb(b_Tmp, dev->iobase + APCI3120_TIMER_CRT0);
/* Set the conversion time */
outw(((unsigned short) ui_TimerValue0),
dev->iobase + APCI3120_TIMER_VALUE);
break;
}
/* ##########common for all modes################# */
/***********************/
/* Clears the SCAN bit */
/***********************/
/* BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver */
/* devpriv->b_ModeSelectRegister=devpriv->b_ModeSelectRegister | APCI3120_DISABLE_SCAN; */
devpriv->b_ModeSelectRegister = devpriv->b_ModeSelectRegister &
APCI3120_DISABLE_SCAN;
/* END JK 07.05.04: Comparison between WIN32 and Linux driver */
outb(devpriv->b_ModeSelectRegister,
dev->iobase + APCI3120_WRITE_MODE_SELECT);
/* If DMA is disabled */
if (devpriv->us_UseDma == APCI3120_DISABLE) {
/* disable EOC and enable EOS */
devpriv->b_InterruptMode = APCI3120_EOS_MODE;
devpriv->b_EocEosInterrupt = APCI3120_ENABLE;
devpriv->b_ModeSelectRegister =
(devpriv->
b_ModeSelectRegister & APCI3120_DISABLE_EOC_INT) |
APCI3120_ENABLE_EOS_INT;
outb(devpriv->b_ModeSelectRegister,
dev->iobase + APCI3120_WRITE_MODE_SELECT);
if (cmd->stop_src == TRIG_COUNT) {
/*
* configure Timer2 For counting EOS Reset gate 2 of Timer 2 to
* disable it (Set Bit D14 to 0)
*/
devpriv->us_OutputRegister =
devpriv->
us_OutputRegister & APCI3120_DISABLE_TIMER2;
outw(devpriv->us_OutputRegister,
dev->iobase + APCI3120_WR_ADDRESS);
/* DISABLE TIMER intERRUPT */
devpriv->b_ModeSelectRegister =
devpriv->
b_ModeSelectRegister &
APCI3120_DISABLE_TIMER_INT & 0xEF;
outb(devpriv->b_ModeSelectRegister,
dev->iobase + APCI3120_WRITE_MODE_SELECT);
/* (1) Init timer 2 in mode 0 and write timer value */
devpriv->b_TimerSelectMode =
(devpriv->
b_TimerSelectMode & 0x0F) |
APCI3120_TIMER_2_MODE_0;
outb(devpriv->b_TimerSelectMode,
dev->iobase + APCI3120_TIMER_CRT1);
/* Writing LOW unsigned short */
b_Tmp = ((devpriv->
b_DigitalOutputRegister) & 0xF0) |
APCI3120_SELECT_TIMER_2_LOW_WORD;
outb(b_Tmp, dev->iobase + APCI3120_TIMER_CRT0);
outw(LOWORD(ui_TimerValue2),
dev->iobase + APCI3120_TIMER_VALUE);
/* Writing HIGH unsigned short */
b_Tmp = ((devpriv->
b_DigitalOutputRegister) & 0xF0) |
APCI3120_SELECT_TIMER_2_HIGH_WORD;
outb(b_Tmp, dev->iobase + APCI3120_TIMER_CRT0);
outw(HIWORD(ui_TimerValue2),
dev->iobase + APCI3120_TIMER_VALUE);
/* (2) Reset FC_TIMER BIT Clearing timer status register */
inb(dev->iobase + APCI3120_TIMER_STATUS_REGISTER);
/* enable timer counter and disable watch dog */
devpriv->b_ModeSelectRegister =
(devpriv->
b_ModeSelectRegister |
APCI3120_ENABLE_TIMER_COUNTER) &
APCI3120_DISABLE_WATCHDOG;
/* select EOS clock input for timer 2 */
devpriv->b_ModeSelectRegister =
devpriv->
b_ModeSelectRegister |
APCI3120_TIMER2_SELECT_EOS;
/* Enable timer2 interrupt */
devpriv->b_ModeSelectRegister =
devpriv->
b_ModeSelectRegister |
APCI3120_ENABLE_TIMER_INT;
outb(devpriv->b_ModeSelectRegister,
dev->iobase + APCI3120_WRITE_MODE_SELECT);
devpriv->b_Timer2Mode = APCI3120_COUNTER;
devpriv->b_Timer2Interrupt = APCI3120_ENABLE;
}
} else {
/* If DMA Enabled */
unsigned int scan_bytes = cmd->scan_end_arg * sizeof(short);
/* BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver */
/* inw(dev->iobase+0); reset EOC bit */
/* END JK 07.05.04: Comparison between WIN32 and Linux driver */
devpriv->b_InterruptMode = APCI3120_DMA_MODE;
/************************************/
/* Disables the EOC, EOS interrupt */
/************************************/
devpriv->b_ModeSelectRegister = devpriv->b_ModeSelectRegister &
APCI3120_DISABLE_EOC_INT & APCI3120_DISABLE_EOS_INT;
outb(devpriv->b_ModeSelectRegister,
dev->iobase + APCI3120_WRITE_MODE_SELECT);
dmalen0 = devpriv->ui_DmaBufferSize[0];
dmalen1 = devpriv->ui_DmaBufferSize[1];
if (cmd->stop_src == TRIG_COUNT) {
/*
* Must we fill full first buffer? And must we fill
* full second buffer when first is once filled?
*/
if (dmalen0 > (cmd->stop_arg * scan_bytes)) {
dmalen0 = cmd->stop_arg * scan_bytes;
} else if (dmalen1 > (cmd->stop_arg * scan_bytes -
dmalen0))
dmalen1 = cmd->stop_arg * scan_bytes -
dmalen0;
}
if (cmd->flags & TRIG_WAKE_EOS) {
/* don't we want wake up every scan? */
if (dmalen0 > scan_bytes) {
dmalen0 = scan_bytes;
if (cmd->scan_end_arg & 1)
dmalen0 += 2;
}
if (dmalen1 > scan_bytes) {
dmalen1 = scan_bytes;
if (cmd->scan_end_arg & 1)
dmalen1 -= 2;
if (dmalen1 < 4)
dmalen1 = 4;
}
} else { /* isn't output buff smaller that our DMA buff? */
if (dmalen0 > s->async->prealloc_bufsz)
dmalen0 = s->async->prealloc_bufsz;
if (dmalen1 > s->async->prealloc_bufsz)
dmalen1 = s->async->prealloc_bufsz;
}
devpriv->ui_DmaBufferUsesize[0] = dmalen0;
devpriv->ui_DmaBufferUsesize[1] = dmalen1;
/* Initialize DMA */
/*
* Set Transfer count enable bit and A2P_fifo reset bit in AGCSTS
* register 1
*/
ui_Tmp = AGCSTS_TC_ENABLE | AGCSTS_RESET_A2P_FIFO;
outl(ui_Tmp, devpriv->i_IobaseAmcc + AMCC_OP_REG_AGCSTS);
/* changed since 16 bit interface for add on */
/*********************/
/* ENABLE BUS MASTER */
/*********************/
outw(APCI3120_ADD_ON_AGCSTS_LOW, devpriv->i_IobaseAddon + 0);
outw(APCI3120_ENABLE_TRANSFER_ADD_ON_LOW,
devpriv->i_IobaseAddon + 2);
outw(APCI3120_ADD_ON_AGCSTS_HIGH, devpriv->i_IobaseAddon + 0);
outw(APCI3120_ENABLE_TRANSFER_ADD_ON_HIGH,
devpriv->i_IobaseAddon + 2);
/*
* TO VERIFIED BEGIN JK 07.05.04: Comparison between WIN32 and Linux
* driver
*/
outw(0x1000, devpriv->i_IobaseAddon + 2);
/* END JK 07.05.04: Comparison between WIN32 and Linux driver */
/* 2 No change */
/* A2P FIFO MANAGEMENT */
/* A2P fifo reset & transfer control enable */
/***********************/
/* A2P FIFO MANAGEMENT */
/***********************/
outl(APCI3120_A2P_FIFO_MANAGEMENT, devpriv->i_IobaseAmcc +
APCI3120_AMCC_OP_MCSR);
/*
* 3
* beginning address of dma buf The 32 bit address of dma buffer
* is converted into two 16 bit addresses Can done by using _attach
* and put into into an array array used may be for differnet pages
*/
/* DMA Start Address Low */
outw(APCI3120_ADD_ON_MWAR_LOW, devpriv->i_IobaseAddon + 0);
outw((devpriv->ul_DmaBufferHw[0] & 0xFFFF),
devpriv->i_IobaseAddon + 2);
/*************************/
/* DMA Start Address High */
/*************************/
outw(APCI3120_ADD_ON_MWAR_HIGH, devpriv->i_IobaseAddon + 0);
outw((devpriv->ul_DmaBufferHw[0] / 65536),
devpriv->i_IobaseAddon + 2);
/*
* 4
* amount of bytes to be transferred set transfer count used ADDON
* MWTC register commented testing
* outl(devpriv->ui_DmaBufferUsesize[0],
* devpriv->i_IobaseAddon+AMCC_OP_REG_AMWTC);
*/
/**************************/
/* Nbr of acquisition LOW */
/**************************/
outw(APCI3120_ADD_ON_MWTC_LOW, devpriv->i_IobaseAddon + 0);
outw((devpriv->ui_DmaBufferUsesize[0] & 0xFFFF),
devpriv->i_IobaseAddon + 2);
/***************************/
/* Nbr of acquisition HIGH */
/***************************/
outw(APCI3120_ADD_ON_MWTC_HIGH, devpriv->i_IobaseAddon + 0);
outw((devpriv->ui_DmaBufferUsesize[0] / 65536),
devpriv->i_IobaseAddon + 2);
/*
* 5
* To configure A2P FIFO testing outl(
* FIFO_ADVANCE_ON_BYTE_2,devpriv->i_IobaseAmcc+AMCC_OP_REG_INTCSR);
*/
/******************/
/* A2P FIFO RESET */
/******************/
/*
* TO VERIFY BEGIN JK 07.05.04: Comparison between WIN32 and Linux
* driver
*/
outl(0x04000000UL, devpriv->i_IobaseAmcc + AMCC_OP_REG_MCSR);
/* END JK 07.05.04: Comparison between WIN32 and Linux driver */
/*
* 6
* ENABLE A2P FIFO WRITE AND ENABLE AMWEN AMWEN_ENABLE |
* A2P_FIFO_WRITE_ENABLE (0x01|0x02)=0x03
*/
/* BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver */
/* outw(3,devpriv->i_IobaseAddon + 4); */
/* END JK 07.05.04: Comparison between WIN32 and Linux driver */
/*
* 7
* initialise end of dma interrupt AINT_WRITE_COMPL =
* ENABLE_WRITE_TC_INT(ADDI)
*/
/***************************************************/
/* A2P FIFO CONFIGURATE, END OF DMA intERRUPT INIT */
/***************************************************/
outl((APCI3120_FIFO_ADVANCE_ON_BYTE_2 |
APCI3120_ENABLE_WRITE_TC_INT),
devpriv->i_IobaseAmcc + AMCC_OP_REG_INTCSR);
/* BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver */
/******************************************/
/* ENABLE A2P FIFO WRITE AND ENABLE AMWEN */
/******************************************/
outw(3, devpriv->i_IobaseAddon + 4);
/* END JK 07.05.04: Comparison between WIN32 and Linux driver */
/******************/
/* A2P FIFO RESET */
/******************/
/* BEGIN JK 07.05.04: Comparison between WIN32 and Linux driver */
outl(0x04000000UL,
devpriv->i_IobaseAmcc + APCI3120_AMCC_OP_MCSR);
/* END JK 07.05.04: Comparison between WIN32 and Linux driver */
}
if (devpriv->us_UseDma == APCI3120_DISABLE &&
cmd->stop_src == TRIG_COUNT) {
/* set gate 2 to start conversion */
devpriv->us_OutputRegister =
devpriv->us_OutputRegister | APCI3120_ENABLE_TIMER2;
outw(devpriv->us_OutputRegister,
dev->iobase + APCI3120_WR_ADDRESS);
}
switch (mode) {
case 1:
/* set gate 0 to start conversion */
devpriv->us_OutputRegister =
devpriv->us_OutputRegister | APCI3120_ENABLE_TIMER0;
outw(devpriv->us_OutputRegister,
dev->iobase + APCI3120_WR_ADDRESS);
break;
case 2:
/* set gate 0 and gate 1 */
devpriv->us_OutputRegister =
devpriv->us_OutputRegister | APCI3120_ENABLE_TIMER1;
devpriv->us_OutputRegister =
devpriv->us_OutputRegister | APCI3120_ENABLE_TIMER0;
outw(devpriv->us_OutputRegister,
dev->iobase + APCI3120_WR_ADDRESS);
break;
}
return 0;
}
/*
* Does asynchronous acquisition.
* Determines the mode 1 or 2.
*/
static int apci3120_ai_cmd(struct comedi_device *dev,
struct comedi_subdevice *s)
{
struct addi_private *devpriv = dev->private;
struct comedi_cmd *cmd = &s->async->cmd;
/* loading private structure with cmd structure inputs */
devpriv->ui_AiNbrofChannels = cmd->chanlist_len;
if (cmd->start_src == TRIG_EXT)
devpriv->b_ExttrigEnable = APCI3120_ENABLE;
else
devpriv->b_ExttrigEnable = APCI3120_DISABLE;
if (cmd->scan_begin_src == TRIG_FOLLOW)
return apci3120_cyclic_ai(1, dev, s);
else /* TRIG_TIMER */
return apci3120_cyclic_ai(2, dev, s);
}
/*
* This function copies the data from DMA buffer to the Comedi buffer.
*/
static void v_APCI3120_InterruptDmaMoveBlock16bit(struct comedi_device *dev,
struct comedi_subdevice *s,
unsigned short *dma_buffer,
unsigned int num_samples)
{
struct addi_private *devpriv = dev->private;
struct comedi_cmd *cmd = &s->async->cmd;
devpriv->ui_AiActualScan +=
(s->async->cur_chan + num_samples) / cmd->scan_end_arg;
s->async->cur_chan += num_samples;
s->async->cur_chan %= cmd->scan_end_arg;
cfc_write_array_to_buffer(s, dma_buffer, num_samples * sizeof(short));
}
/*
* This is a handler for the DMA interrupt.
* This function copies the data to Comedi Buffer.
* For continuous DMA it reinitializes the DMA operation.
* For single mode DMA it stop the acquisition.
*/
static void apci3120_interrupt_dma(int irq, void *d)
{
struct comedi_device *dev = d;
struct addi_private *devpriv = dev->private;
struct comedi_subdevice *s = dev->read_subdev;
struct comedi_cmd *cmd = &s->async->cmd;
unsigned int next_dma_buf, samplesinbuf;
unsigned long low_word, high_word, var;
unsigned int ui_Tmp;
samplesinbuf =
devpriv->ui_DmaBufferUsesize[devpriv->ui_DmaActualBuffer] -
inl(devpriv->i_IobaseAmcc + AMCC_OP_REG_MWTC);
if (samplesinbuf <
devpriv->ui_DmaBufferUsesize[devpriv->ui_DmaActualBuffer]) {
comedi_error(dev, "Interrupted DMA transfer!");
}
if (samplesinbuf & 1) {
comedi_error(dev, "Odd count of bytes in DMA ring!");
apci3120_cancel(dev, s);
return;
}
samplesinbuf = samplesinbuf >> 1; /* number of received samples */
if (devpriv->b_DmaDoubleBuffer) {
/* switch DMA buffers if is used double buffering */
next_dma_buf = 1 - devpriv->ui_DmaActualBuffer;
ui_Tmp = AGCSTS_TC_ENABLE | AGCSTS_RESET_A2P_FIFO;
outl(ui_Tmp, devpriv->i_IobaseAddon + AMCC_OP_REG_AGCSTS);
/* changed since 16 bit interface for add on */
outw(APCI3120_ADD_ON_AGCSTS_LOW, devpriv->i_IobaseAddon + 0);
outw(APCI3120_ENABLE_TRANSFER_ADD_ON_LOW,
devpriv->i_IobaseAddon + 2);
outw(APCI3120_ADD_ON_AGCSTS_HIGH, devpriv->i_IobaseAddon + 0);
outw(APCI3120_ENABLE_TRANSFER_ADD_ON_HIGH, devpriv->i_IobaseAddon + 2); /* 0x1000 is out putted in windows driver */
var = devpriv->ul_DmaBufferHw[next_dma_buf];
low_word = var & 0xffff;
var = devpriv->ul_DmaBufferHw[next_dma_buf];
high_word = var / 65536;
/* DMA Start Address Low */
outw(APCI3120_ADD_ON_MWAR_LOW, devpriv->i_IobaseAddon + 0);
outw(low_word, devpriv->i_IobaseAddon + 2);
/* DMA Start Address High */
outw(APCI3120_ADD_ON_MWAR_HIGH, devpriv->i_IobaseAddon + 0);
outw(high_word, devpriv->i_IobaseAddon + 2);
var = devpriv->ui_DmaBufferUsesize[next_dma_buf];
low_word = var & 0xffff;
var = devpriv->ui_DmaBufferUsesize[next_dma_buf];
high_word = var / 65536;
/* Nbr of acquisition LOW */
outw(APCI3120_ADD_ON_MWTC_LOW, devpriv->i_IobaseAddon + 0);
outw(low_word, devpriv->i_IobaseAddon + 2);
/* Nbr of acquisition HIGH */
outw(APCI3120_ADD_ON_MWTC_HIGH, devpriv->i_IobaseAddon + 0);
outw(high_word, devpriv->i_IobaseAddon + 2);
/*
* To configure A2P FIFO
* ENABLE A2P FIFO WRITE AND ENABLE AMWEN
* AMWEN_ENABLE | A2P_FIFO_WRITE_ENABLE (0x01|0x02)=0x03
*/
outw(3, devpriv->i_IobaseAddon + 4);
/* initialise end of dma interrupt AINT_WRITE_COMPL = ENABLE_WRITE_TC_INT(ADDI) */
outl((APCI3120_FIFO_ADVANCE_ON_BYTE_2 |
APCI3120_ENABLE_WRITE_TC_INT),
devpriv->i_IobaseAmcc + AMCC_OP_REG_INTCSR);
}
if (samplesinbuf) {
v_APCI3120_InterruptDmaMoveBlock16bit(dev, s,
devpriv->ul_DmaBufferVirtual[devpriv->
ui_DmaActualBuffer], samplesinbuf);
if (!(cmd->flags & TRIG_WAKE_EOS)) {
s->async->events |= COMEDI_CB_EOS;
comedi_event(dev, s);
}
}
if (cmd->stop_src == TRIG_COUNT)
if (devpriv->ui_AiActualScan >= cmd->stop_arg) {
/* all data sampled */
apci3120_cancel(dev, s);
s->async->events |= COMEDI_CB_EOA;
comedi_event(dev, s);
return;
}
if (devpriv->b_DmaDoubleBuffer) { /* switch dma buffers */
devpriv->ui_DmaActualBuffer = 1 - devpriv->ui_DmaActualBuffer;
} else {
/*
* restart DMA if is not used double buffering
* ADDED REINITIALISE THE DMA
*/
ui_Tmp = AGCSTS_TC_ENABLE | AGCSTS_RESET_A2P_FIFO;
outl(ui_Tmp, devpriv->i_IobaseAddon + AMCC_OP_REG_AGCSTS);
/* changed since 16 bit interface for add on */
outw(APCI3120_ADD_ON_AGCSTS_LOW, devpriv->i_IobaseAddon + 0);
outw(APCI3120_ENABLE_TRANSFER_ADD_ON_LOW,
devpriv->i_IobaseAddon + 2);
outw(APCI3120_ADD_ON_AGCSTS_HIGH, devpriv->i_IobaseAddon + 0);
outw(APCI3120_ENABLE_TRANSFER_ADD_ON_HIGH, devpriv->i_IobaseAddon + 2); /* */
/*
* A2P FIFO MANAGEMENT
* A2P fifo reset & transfer control enable
*/
outl(APCI3120_A2P_FIFO_MANAGEMENT,
devpriv->i_IobaseAmcc + AMCC_OP_REG_MCSR);
var = devpriv->ul_DmaBufferHw[0];
low_word = var & 0xffff;
var = devpriv->ul_DmaBufferHw[0];
high_word = var / 65536;
outw(APCI3120_ADD_ON_MWAR_LOW, devpriv->i_IobaseAddon + 0);
outw(low_word, devpriv->i_IobaseAddon + 2);
outw(APCI3120_ADD_ON_MWAR_HIGH, devpriv->i_IobaseAddon + 0);
outw(high_word, devpriv->i_IobaseAddon + 2);
var = devpriv->ui_DmaBufferUsesize[0];
low_word = var & 0xffff; /* changed */
var = devpriv->ui_DmaBufferUsesize[0];
high_word = var / 65536;
outw(APCI3120_ADD_ON_MWTC_LOW, devpriv->i_IobaseAddon + 0);
outw(low_word, devpriv->i_IobaseAddon + 2);
outw(APCI3120_ADD_ON_MWTC_HIGH, devpriv->i_IobaseAddon + 0);
outw(high_word, devpriv->i_IobaseAddon + 2);
/*
* To configure A2P FIFO
* ENABLE A2P FIFO WRITE AND ENABLE AMWEN
* AMWEN_ENABLE | A2P_FIFO_WRITE_ENABLE (0x01|0x02)=0x03
*/
outw(3, devpriv->i_IobaseAddon + 4);
/* initialise end of dma interrupt AINT_WRITE_COMPL = ENABLE_WRITE_TC_INT(ADDI) */
outl((APCI3120_FIFO_ADVANCE_ON_BYTE_2 |
APCI3120_ENABLE_WRITE_TC_INT),
devpriv->i_IobaseAmcc + AMCC_OP_REG_INTCSR);
}
}
/*
* This function handles EOS interrupt.
* This function copies the acquired data(from FIFO) to Comedi buffer.
*/
static int apci3120_interrupt_handle_eos(struct comedi_device *dev)
{
struct addi_private *devpriv = dev->private;
struct comedi_subdevice *s = dev->read_subdev;
int n_chan, i;
int err = 1;
n_chan = devpriv->ui_AiNbrofChannels;
for (i = 0; i < n_chan; i++)
err &= comedi_buf_put(s, inw(dev->iobase + 0));
s->async->events |= COMEDI_CB_EOS;
if (err == 0)
s->async->events |= COMEDI_CB_OVERFLOW;
comedi_event(dev, s);
return 0;
}
static void apci3120_interrupt(int irq, void *d)
{
struct comedi_device *dev = d;
struct addi_private *devpriv = dev->private;
struct comedi_subdevice *s = dev->read_subdev;
unsigned short int_daq;
unsigned int int_amcc, ui_Check, i;
unsigned short us_TmpValue;
unsigned char b_DummyRead;
ui_Check = 1;
int_daq = inw(dev->iobase + APCI3120_RD_STATUS) & 0xf000; /* get IRQ reasons */
int_amcc = inl(devpriv->i_IobaseAmcc + AMCC_OP_REG_INTCSR); /* get AMCC int register */
if ((!int_daq) && (!(int_amcc & ANY_S593X_INT))) {
comedi_error(dev, "IRQ from unknown source");
return;
}
outl(int_amcc | 0x00ff0000, devpriv->i_IobaseAmcc + AMCC_OP_REG_INTCSR); /* shutdown IRQ reasons in AMCC */
int_daq = (int_daq >> 12) & 0xF;
if (devpriv->b_ExttrigEnable == APCI3120_ENABLE) {
/* Disable ext trigger */
apci3120_exttrig_disable(dev);
devpriv->b_ExttrigEnable = APCI3120_DISABLE;
}
/* clear the timer 2 interrupt */
inb(devpriv->i_IobaseAmcc + APCI3120_TIMER_STATUS_REGISTER);
if (int_amcc & MASTER_ABORT_INT)
comedi_error(dev, "AMCC IRQ - MASTER DMA ABORT!");
if (int_amcc & TARGET_ABORT_INT)
comedi_error(dev, "AMCC IRQ - TARGET DMA ABORT!");
/* Ckeck if EOC interrupt */
if (((int_daq & 0x8) == 0)
&& (devpriv->b_InterruptMode == APCI3120_EOC_MODE)) {
if (devpriv->b_EocEosInterrupt == APCI3120_ENABLE) {
/* Read the AI Value */
devpriv->ui_AiReadData[0] =
(unsigned int) inw(devpriv->iobase + 0);
devpriv->b_EocEosInterrupt = APCI3120_DISABLE;
send_sig(SIGIO, devpriv->tsk_Current, 0); /* send signal to the sample */
} else {
/* Disable EOC Interrupt */
devpriv->b_ModeSelectRegister =
devpriv->
b_ModeSelectRegister & APCI3120_DISABLE_EOC_INT;
outb(devpriv->b_ModeSelectRegister,
devpriv->iobase + APCI3120_WRITE_MODE_SELECT);
}
}
/* Check If EOS interrupt */
if ((int_daq & 0x2) && (devpriv->b_InterruptMode == APCI3120_EOS_MODE)) {
if (devpriv->b_EocEosInterrupt == APCI3120_ENABLE) { /* enable this in without DMA ??? */
if (devpriv->ai_running) {
ui_Check = 0;
apci3120_interrupt_handle_eos(dev);
devpriv->ui_AiActualScan++;
devpriv->b_ModeSelectRegister =
devpriv->
b_ModeSelectRegister |
APCI3120_ENABLE_EOS_INT;
outb(devpriv->b_ModeSelectRegister,
dev->iobase +
APCI3120_WRITE_MODE_SELECT);
} else {
ui_Check = 0;
for (i = 0; i < devpriv->ui_AiNbrofChannels;
i++) {
us_TmpValue = inw(devpriv->iobase + 0);
devpriv->ui_AiReadData[i] =
(unsigned int) us_TmpValue;
}
devpriv->b_EocEosInterrupt = APCI3120_DISABLE;
devpriv->b_InterruptMode = APCI3120_EOC_MODE;
send_sig(SIGIO, devpriv->tsk_Current, 0); /* send signal to the sample */
}
} else {
devpriv->b_ModeSelectRegister =
devpriv->
b_ModeSelectRegister & APCI3120_DISABLE_EOS_INT;
outb(devpriv->b_ModeSelectRegister,
dev->iobase + APCI3120_WRITE_MODE_SELECT);
devpriv->b_EocEosInterrupt = APCI3120_DISABLE; /* Default settings */
devpriv->b_InterruptMode = APCI3120_EOC_MODE;
}
}
/* Timer2 interrupt */
if (int_daq & 0x1) {
switch (devpriv->b_Timer2Mode) {
case APCI3120_COUNTER:
devpriv->b_ModeSelectRegister =
devpriv->
b_ModeSelectRegister & APCI3120_DISABLE_EOS_INT;
outb(devpriv->b_ModeSelectRegister,
dev->iobase + APCI3120_WRITE_MODE_SELECT);
/* stop timer 2 */
devpriv->us_OutputRegister =
devpriv->
us_OutputRegister & APCI3120_DISABLE_ALL_TIMER;
outw(devpriv->us_OutputRegister,
dev->iobase + APCI3120_WR_ADDRESS);
/* stop timer 0 and timer 1 */
apci3120_cancel(dev, s);
/* UPDATE-0.7.57->0.7.68comedi_done(dev,s); */
s->async->events |= COMEDI_CB_EOA;
comedi_event(dev, s);
break;
case APCI3120_TIMER:
/* Send a signal to from kernel to user space */
send_sig(SIGIO, devpriv->tsk_Current, 0);
break;
case APCI3120_WATCHDOG:
/* Send a signal to from kernel to user space */
send_sig(SIGIO, devpriv->tsk_Current, 0);
break;
default:
/* disable Timer Interrupt */
devpriv->b_ModeSelectRegister =
devpriv->
b_ModeSelectRegister &
APCI3120_DISABLE_TIMER_INT;
outb(devpriv->b_ModeSelectRegister,
dev->iobase + APCI3120_WRITE_MODE_SELECT);
}
b_DummyRead = inb(dev->iobase + APCI3120_TIMER_STATUS_REGISTER);
}
if ((int_daq & 0x4) && (devpriv->b_InterruptMode == APCI3120_DMA_MODE)) {
if (devpriv->ai_running) {
/****************************/
/* Clear Timer Write TC int */
/****************************/
outl(APCI3120_CLEAR_WRITE_TC_INT,
devpriv->i_IobaseAmcc +
APCI3120_AMCC_OP_REG_INTCSR);
/************************************/
/* Clears the timer status register */
/************************************/
inw(dev->iobase + APCI3120_TIMER_STATUS_REGISTER);
/* do some data transfer */
apci3120_interrupt_dma(irq, d);
} else {
/* Stops the Timer */
outw(devpriv->
us_OutputRegister & APCI3120_DISABLE_TIMER0 &
APCI3120_DISABLE_TIMER1,
dev->iobase + APCI3120_WR_ADDRESS);
}
}
return;
}
/*
* Configure Timer 2
*
* data[0] = TIMER configure as timer
* = WATCHDOG configure as watchdog
* data[1] = Timer constant
* data[2] = Timer2 interrupt (1)enable or(0) disable
*/
static int apci3120_config_insn_timer(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
const struct addi_board *this_board = comedi_board(dev);
struct addi_private *devpriv = dev->private;
unsigned int ui_Timervalue2;
unsigned short us_TmpValue;
unsigned char b_Tmp;
if (!data[1])
comedi_error(dev, "config:No timer constant !");
devpriv->b_Timer2Interrupt = (unsigned char) data[2]; /* save info whether to enable or disable interrupt */
ui_Timervalue2 = data[1] / 1000; /* convert nano seconds to u seconds */
/* this_board->timer_config(dev, ui_Timervalue2,(unsigned char)data[0]); */
us_TmpValue = (unsigned short) inw(devpriv->iobase + APCI3120_RD_STATUS);
/*
* EL250804: Testing if board APCI3120 have the new Quartz or if it
* is an APCI3001 and calculate the time value to set in the timer
*/
if ((us_TmpValue & 0x00B0) == 0x00B0
|| !strcmp(this_board->pc_DriverName, "apci3001")) {
/* Calculate the time value to set in the timer */
ui_Timervalue2 = ui_Timervalue2 / 50;
} else {
/* Calculate the time value to set in the timer */
ui_Timervalue2 = ui_Timervalue2 / 70;
}
/* Reset gate 2 of Timer 2 to disable it (Set Bit D14 to 0) */
devpriv->us_OutputRegister =
devpriv->us_OutputRegister & APCI3120_DISABLE_TIMER2;
outw(devpriv->us_OutputRegister, devpriv->iobase + APCI3120_WR_ADDRESS);
/* Disable TIMER Interrupt */
devpriv->b_ModeSelectRegister =
devpriv->
b_ModeSelectRegister & APCI3120_DISABLE_TIMER_INT & 0xEF;
/* Disable Eoc and Eos Interrupts */
devpriv->b_ModeSelectRegister =
devpriv->
b_ModeSelectRegister & APCI3120_DISABLE_EOC_INT &
APCI3120_DISABLE_EOS_INT;
outb(devpriv->b_ModeSelectRegister,
devpriv->iobase + APCI3120_WRITE_MODE_SELECT);
if (data[0] == APCI3120_TIMER) { /* initialize timer */
/* devpriv->b_ModeSelectRegister=devpriv->b_ModeSelectRegister |
* APCI3120_ENABLE_TIMER_INT; */
/* outb(devpriv->b_ModeSelectRegister,devpriv->iobase+APCI3120_WRITE_MODE_SELECT); */
/* Set the Timer 2 in mode 2(Timer) */
devpriv->b_TimerSelectMode =
(devpriv->
b_TimerSelectMode & 0x0F) | APCI3120_TIMER_2_MODE_2;
outb(devpriv->b_TimerSelectMode,
devpriv->iobase + APCI3120_TIMER_CRT1);
/*
* Configure the timer 2 for writing the LOW unsigned short of timer
* is Delay value You must make a b_tmp variable with
* DigitalOutPutRegister because at Address_1+APCI3120_TIMER_CRT0
* you can set the digital output and configure the timer 2,and if
* you don't make this, digital output are erase (Set to 0)
*/
/* Writing LOW unsigned short */
b_Tmp = ((devpriv->
b_DigitalOutputRegister) & 0xF0) |
APCI3120_SELECT_TIMER_2_LOW_WORD;
outb(b_Tmp, devpriv->iobase + APCI3120_TIMER_CRT0);
outw(LOWORD(ui_Timervalue2),
devpriv->iobase + APCI3120_TIMER_VALUE);
/* Writing HIGH unsigned short */
b_Tmp = ((devpriv->
b_DigitalOutputRegister) & 0xF0) |
APCI3120_SELECT_TIMER_2_HIGH_WORD;
outb(b_Tmp, devpriv->iobase + APCI3120_TIMER_CRT0);
outw(HIWORD(ui_Timervalue2),
devpriv->iobase + APCI3120_TIMER_VALUE);
/* timer2 in Timer mode enabled */
devpriv->b_Timer2Mode = APCI3120_TIMER;
} else { /* Initialize Watch dog */
/* Set the Timer 2 in mode 5(Watchdog) */
devpriv->b_TimerSelectMode =
(devpriv->
b_TimerSelectMode & 0x0F) | APCI3120_TIMER_2_MODE_5;
outb(devpriv->b_TimerSelectMode,
devpriv->iobase + APCI3120_TIMER_CRT1);
/*
* Configure the timer 2 for writing the LOW unsigned short of timer
* is Delay value You must make a b_tmp variable with
* DigitalOutPutRegister because at Address_1+APCI3120_TIMER_CRT0
* you can set the digital output and configure the timer 2,and if
* you don't make this, digital output are erase (Set to 0)
*/
/* Writing LOW unsigned short */
b_Tmp = ((devpriv->
b_DigitalOutputRegister) & 0xF0) |
APCI3120_SELECT_TIMER_2_LOW_WORD;
outb(b_Tmp, devpriv->iobase + APCI3120_TIMER_CRT0);
outw(LOWORD(ui_Timervalue2),
devpriv->iobase + APCI3120_TIMER_VALUE);
/* Writing HIGH unsigned short */
b_Tmp = ((devpriv->
b_DigitalOutputRegister) & 0xF0) |
APCI3120_SELECT_TIMER_2_HIGH_WORD;
outb(b_Tmp, devpriv->iobase + APCI3120_TIMER_CRT0);
outw(HIWORD(ui_Timervalue2),
devpriv->iobase + APCI3120_TIMER_VALUE);
/* watchdog enabled */
devpriv->b_Timer2Mode = APCI3120_WATCHDOG;
}
return insn->n;
}
/*
* To start and stop the timer
*
* data[0] = 1 (start)
* = 0 (stop)
* = 2 (write new value)
* data[1] = new value
*
* devpriv->b_Timer2Mode = 0 DISABLE
* = 1 Timer
* = 2 Watch dog
*/
static int apci3120_write_insn_timer(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
const struct addi_board *this_board = comedi_board(dev);
struct addi_private *devpriv = dev->private;
unsigned int ui_Timervalue2 = 0;
unsigned short us_TmpValue;
unsigned char b_Tmp;
if ((devpriv->b_Timer2Mode != APCI3120_WATCHDOG)
&& (devpriv->b_Timer2Mode != APCI3120_TIMER)) {
comedi_error(dev, "\nwrite:timer2 not configured ");
return -EINVAL;
}
if (data[0] == 2) { /* write new value */
if (devpriv->b_Timer2Mode != APCI3120_TIMER) {
comedi_error(dev,
"write :timer2 not configured in TIMER MODE");
return -EINVAL;
}
if (data[1])
ui_Timervalue2 = data[1];
else
ui_Timervalue2 = 0;
}
/* this_board->timer_write(dev,data[0],ui_Timervalue2); */
switch (data[0]) {
case APCI3120_START:
/* Reset FC_TIMER BIT */
inb(devpriv->iobase + APCI3120_TIMER_STATUS_REGISTER);
if (devpriv->b_Timer2Mode == APCI3120_TIMER) { /* start timer */
/* Enable Timer */
devpriv->b_ModeSelectRegister =
devpriv->b_ModeSelectRegister & 0x0B;
} else { /* start watch dog */
/* Enable WatchDog */
devpriv->b_ModeSelectRegister =
(devpriv->
b_ModeSelectRegister & 0x0B) |
APCI3120_ENABLE_WATCHDOG;
}
/* enable disable interrupt */
if ((devpriv->b_Timer2Interrupt) == APCI3120_ENABLE) {
devpriv->b_ModeSelectRegister =
devpriv->
b_ModeSelectRegister |
APCI3120_ENABLE_TIMER_INT;
/* save the task structure to pass info to user */
devpriv->tsk_Current = current;
} else {
devpriv->b_ModeSelectRegister =
devpriv->
b_ModeSelectRegister &
APCI3120_DISABLE_TIMER_INT;
}
outb(devpriv->b_ModeSelectRegister,
devpriv->iobase + APCI3120_WRITE_MODE_SELECT);
if (devpriv->b_Timer2Mode == APCI3120_TIMER) { /* start timer */
/* For Timer mode is Gate2 must be activated **timer started */
devpriv->us_OutputRegister =
devpriv->
us_OutputRegister | APCI3120_ENABLE_TIMER2;
outw(devpriv->us_OutputRegister,
devpriv->iobase + APCI3120_WR_ADDRESS);
}
break;
case APCI3120_STOP:
if (devpriv->b_Timer2Mode == APCI3120_TIMER) {
/* Disable timer */
devpriv->b_ModeSelectRegister =
devpriv->
b_ModeSelectRegister &
APCI3120_DISABLE_TIMER_COUNTER;
} else {
/* Disable WatchDog */
devpriv->b_ModeSelectRegister =
devpriv->
b_ModeSelectRegister &
APCI3120_DISABLE_WATCHDOG;
}
/* Disable timer interrupt */
devpriv->b_ModeSelectRegister =
devpriv->
b_ModeSelectRegister & APCI3120_DISABLE_TIMER_INT;
/* Write above states to register */
outb(devpriv->b_ModeSelectRegister,
devpriv->iobase + APCI3120_WRITE_MODE_SELECT);
/* Reset Gate 2 */
devpriv->us_OutputRegister =
devpriv->us_OutputRegister & APCI3120_DISABLE_TIMER_INT;
outw(devpriv->us_OutputRegister,
devpriv->iobase + APCI3120_WR_ADDRESS);
/* Reset FC_TIMER BIT */
inb(devpriv->iobase + APCI3120_TIMER_STATUS_REGISTER);
/* Disable timer */
/* devpriv->b_Timer2Mode=APCI3120_DISABLE; */
break;
case 2: /* write new value to Timer */
if (devpriv->b_Timer2Mode != APCI3120_TIMER) {
comedi_error(dev,
"write :timer2 not configured in TIMER MODE");
return -EINVAL;
}
/* ui_Timervalue2=data[1]; // passed as argument */
us_TmpValue =
(unsigned short) inw(devpriv->iobase + APCI3120_RD_STATUS);
/*
* EL250804: Testing if board APCI3120 have the new Quartz or if it
* is an APCI3001 and calculate the time value to set in the timer
*/
if ((us_TmpValue & 0x00B0) == 0x00B0
|| !strcmp(this_board->pc_DriverName, "apci3001")) {
/* Calculate the time value to set in the timer */
ui_Timervalue2 = ui_Timervalue2 / 50;
} else {
/* Calculate the time value to set in the timer */
ui_Timervalue2 = ui_Timervalue2 / 70;
}
/* Writing LOW unsigned short */
b_Tmp = ((devpriv->
b_DigitalOutputRegister) & 0xF0) |
APCI3120_SELECT_TIMER_2_LOW_WORD;
outb(b_Tmp, devpriv->iobase + APCI3120_TIMER_CRT0);
outw(LOWORD(ui_Timervalue2),
devpriv->iobase + APCI3120_TIMER_VALUE);
/* Writing HIGH unsigned short */
b_Tmp = ((devpriv->
b_DigitalOutputRegister) & 0xF0) |
APCI3120_SELECT_TIMER_2_HIGH_WORD;
outb(b_Tmp, devpriv->iobase + APCI3120_TIMER_CRT0);
outw(HIWORD(ui_Timervalue2),
devpriv->iobase + APCI3120_TIMER_VALUE);
break;
default:
return -EINVAL; /* Not a valid input */
}
return insn->n;
}
/*
* Read the Timer value
*
* for Timer: data[0]= Timer constant
*
* for watchdog: data[0] = 0 (still running)
* = 1 (run down)
*/
static int apci3120_read_insn_timer(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
struct addi_private *devpriv = dev->private;
unsigned char b_Tmp;
unsigned short us_TmpValue, us_TmpValue_2, us_StatusValue;
if ((devpriv->b_Timer2Mode != APCI3120_WATCHDOG)
&& (devpriv->b_Timer2Mode != APCI3120_TIMER)) {
comedi_error(dev, "\nread:timer2 not configured ");
}
/* this_board->timer_read(dev,data); */
if (devpriv->b_Timer2Mode == APCI3120_TIMER) {
/* Read the LOW unsigned short of Timer 2 register */
b_Tmp = ((devpriv->
b_DigitalOutputRegister) & 0xF0) |
APCI3120_SELECT_TIMER_2_LOW_WORD;
outb(b_Tmp, devpriv->iobase + APCI3120_TIMER_CRT0);
us_TmpValue = inw(devpriv->iobase + APCI3120_TIMER_VALUE);
/* Read the HIGH unsigned short of Timer 2 register */
b_Tmp = ((devpriv->
b_DigitalOutputRegister) & 0xF0) |
APCI3120_SELECT_TIMER_2_HIGH_WORD;
outb(b_Tmp, devpriv->iobase + APCI3120_TIMER_CRT0);
us_TmpValue_2 = inw(devpriv->iobase + APCI3120_TIMER_VALUE);
/* combining both words */
data[0] = (unsigned int) ((us_TmpValue) | ((us_TmpValue_2) << 16));
} else { /* Read watch dog status */
us_StatusValue = inw(devpriv->iobase + APCI3120_RD_STATUS);
us_StatusValue =
((us_StatusValue & APCI3120_FC_TIMER) >> 12) & 1;
if (us_StatusValue == 1) {
/* RESET FC_TIMER BIT */
inb(devpriv->iobase + APCI3120_TIMER_STATUS_REGISTER);
}
data[0] = us_StatusValue; /* when data[0] = 1 then the watch dog has rundown */
}
return insn->n;
}
static int apci3120_di_insn_bits(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
struct addi_private *devpriv = dev->private;
unsigned int val;
/* the input channels are bits 11:8 of the status reg */
val = inw(devpriv->iobase + APCI3120_RD_STATUS);
data[1] = (val >> 8) & 0xf;
return insn->n;
}
static int apci3120_do_insn_bits(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
struct addi_private *devpriv = dev->private;
if (comedi_dio_update_state(s, data)) {
/* The do channels are bits 7:4 of the do register */
devpriv->b_DigitalOutputRegister = s->state << 4;
outb(devpriv->b_DigitalOutputRegister,
devpriv->iobase + APCI3120_DIGITAL_OUTPUT);
}
data[1] = s->state;
return insn->n;
}
static int apci3120_ao_insn_write(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned int *data)
{
struct addi_private *devpriv = dev->private;
unsigned int ui_Range, ui_Channel;
unsigned short us_TmpValue;
ui_Range = CR_RANGE(insn->chanspec);
ui_Channel = CR_CHAN(insn->chanspec);
/* this_board->ao_write(dev, ui_Range, ui_Channel,data[0]); */
if (ui_Range) { /* if 1 then unipolar */
if (data[0] != 0)
data[0] =
((((ui_Channel & 0x03) << 14) & 0xC000) | (1 <<
13) | (data[0] + 8191));
else
data[0] =
((((ui_Channel & 0x03) << 14) & 0xC000) | (1 <<
13) | 8192);
} else { /* if 0 then bipolar */
data[0] =
((((ui_Channel & 0x03) << 14) & 0xC000) | (0 << 13) |
data[0]);
}
/*
* out put n values at the given channel. printk("\nwaiting for
* DA_READY BIT");
*/
do { /* Waiting of DA_READY BIT */
us_TmpValue =
((unsigned short) inw(devpriv->iobase +
APCI3120_RD_STATUS)) & 0x0001;
} while (us_TmpValue != 0x0001);
if (ui_Channel <= 3)
/*
* for channel 0-3 out at the register 1 (wrDac1-8) data[i]
* typecasted to ushort since word write is to be done
*/
outw((unsigned short) data[0],
devpriv->iobase + APCI3120_ANALOG_OUTPUT_1);
else
/*
* for channel 4-7 out at the register 2 (wrDac5-8) data[i]
* typecasted to ushort since word write is to be done
*/
outw((unsigned short) data[0],
devpriv->iobase + APCI3120_ANALOG_OUTPUT_2);
return insn->n;
}
| gpl-2.0 |
ZeroInfinityXDA/HelixKernel_Nougat | drivers/misc/qcom/qdsp6v2/audio_aac.c | 56 | 13458 | /* aac audio output device
*
* Copyright (C) 2008 Google, Inc.
* Copyright (C) 2008 HTC Corporation
* Copyright (c) 2010-2016, The Linux Foundation. All rights reserved.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/msm_audio_aac.h>
#include <linux/compat.h>
#include "audio_utils_aio.h"
#define AUDIO_AAC_DUAL_MONO_INVALID -1
#define PCM_BUFSZ_MIN_AAC ((8*1024) + sizeof(struct dec_meta_out))
static struct miscdevice audio_aac_misc;
static struct ws_mgr audio_aac_ws_mgr;
#ifdef CONFIG_DEBUG_FS
static const struct file_operations audio_aac_debug_fops = {
.read = audio_aio_debug_read,
.open = audio_aio_debug_open,
};
#endif
static long audio_ioctl_shared(struct file *file, unsigned int cmd,
void *arg)
{
struct q6audio_aio *audio = file->private_data;
int rc = 0;
switch (cmd) {
case AUDIO_START: {
struct asm_aac_cfg aac_cfg;
struct msm_audio_aac_config *aac_config;
uint32_t sbr_ps = 0x00;
pr_debug("%s: AUDIO_START session_id[%d]\n", __func__,
audio->ac->session);
if (audio->feedback == NON_TUNNEL_MODE) {
/* Configure PCM output block */
rc = q6asm_enc_cfg_blk_pcm(audio->ac, 0, 0);
if (rc < 0) {
pr_err("pcm output block config failed\n");
break;
}
}
/* turn on both sbr and ps */
rc = q6asm_enable_sbrps(audio->ac, sbr_ps);
if (rc < 0)
pr_err("sbr-ps enable failed\n");
aac_config = (struct msm_audio_aac_config *)audio->codec_cfg;
if (aac_config->sbr_ps_on_flag)
aac_cfg.aot = AAC_ENC_MODE_EAAC_P;
else if (aac_config->sbr_on_flag)
aac_cfg.aot = AAC_ENC_MODE_AAC_P;
else
aac_cfg.aot = AAC_ENC_MODE_AAC_LC;
switch (aac_config->format) {
case AUDIO_AAC_FORMAT_ADTS:
aac_cfg.format = 0x00;
break;
case AUDIO_AAC_FORMAT_LOAS:
aac_cfg.format = 0x01;
break;
case AUDIO_AAC_FORMAT_ADIF:
aac_cfg.format = 0x02;
break;
default:
case AUDIO_AAC_FORMAT_RAW:
aac_cfg.format = 0x03;
}
aac_cfg.ep_config = aac_config->ep_config;
aac_cfg.section_data_resilience =
aac_config->aac_section_data_resilience_flag;
aac_cfg.scalefactor_data_resilience =
aac_config->aac_scalefactor_data_resilience_flag;
aac_cfg.spectral_data_resilience =
aac_config->aac_spectral_data_resilience_flag;
aac_cfg.ch_cfg = audio->pcm_cfg.channel_count;
if (audio->feedback == TUNNEL_MODE) {
aac_cfg.sample_rate = aac_config->sample_rate;
aac_cfg.ch_cfg = aac_config->channel_configuration;
} else {
aac_cfg.sample_rate = audio->pcm_cfg.sample_rate;
aac_cfg.ch_cfg = audio->pcm_cfg.channel_count;
}
pr_debug("%s:format=%x aot=%d ch=%d sr=%d\n",
__func__, aac_cfg.format,
aac_cfg.aot, aac_cfg.ch_cfg,
aac_cfg.sample_rate);
/* Configure Media format block */
rc = q6asm_media_format_block_aac(audio->ac, &aac_cfg);
if (rc < 0) {
pr_err("cmd media format block failed\n");
break;
}
rc = audio_aio_enable(audio);
audio->eos_rsp = 0;
audio->eos_flag = 0;
if (!rc) {
rc = enable_volume_ramp(audio);
if (rc < 0) {
pr_err("%s: Failed to enable volume ramp\n",
__func__);
}
audio->enabled = 1;
} else {
audio->enabled = 0;
pr_err("Audio Start procedure failed rc=%d\n", rc);
break;
}
pr_info("%s: AUDIO_START sessionid[%d]enable[%d]\n", __func__,
audio->ac->session,
audio->enabled);
if (audio->stopped == 1)
audio->stopped = 0;
break;
}
case AUDIO_SET_AAC_CONFIG: {
struct msm_audio_aac_config *aac_config;
uint16_t sce_left = 1, sce_right = 2;
pr_debug("%s: AUDIO_SET_AAC_CONFIG\n", __func__);
aac_config = (struct msm_audio_aac_config *)arg;
if (aac_config == NULL) {
pr_err("%s: Invalid config pointer\n", __func__);
rc = -EINVAL;
break;
}
memcpy(audio->codec_cfg, aac_config,
sizeof(struct msm_audio_aac_config));
/* PL_PR is 0 only need to check PL_SR */
if (aac_config->dual_mono_mode >
AUDIO_AAC_DUAL_MONO_PL_SR) {
pr_err("%s:Invalid dual_mono mode =%d\n", __func__,
aac_config->dual_mono_mode);
} else {
/* convert the data from user into sce_left
* and sce_right based on the definitions
*/
pr_debug("%s: modify dual_mono mode =%d\n", __func__,
aac_config->dual_mono_mode);
switch (aac_config->dual_mono_mode) {
case AUDIO_AAC_DUAL_MONO_PL_PR:
sce_left = 1;
sce_right = 1;
break;
case AUDIO_AAC_DUAL_MONO_SL_SR:
sce_left = 2;
sce_right = 2;
break;
case AUDIO_AAC_DUAL_MONO_SL_PR:
sce_left = 2;
sce_right = 1;
break;
case AUDIO_AAC_DUAL_MONO_PL_SR:
default:
sce_left = 1;
sce_right = 2;
break;
}
rc = q6asm_cfg_dual_mono_aac(audio->ac,
sce_left, sce_right);
if (rc < 0)
pr_err("%s:asm cmd dualmono failed rc=%d\n",
__func__, rc);
}
break;
}
default:
pr_err("%s: Unknown ioctl cmd = %d", __func__, cmd);
break;
}
return rc;
}
static long audio_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct q6audio_aio *audio = file->private_data;
int rc = 0;
switch (cmd) {
case AUDIO_START: {
rc = audio_ioctl_shared(file, cmd, (void *)arg);
break;
}
case AUDIO_GET_AAC_CONFIG: {
if (copy_to_user((void *)arg, audio->codec_cfg,
sizeof(struct msm_audio_aac_config))) {
pr_err("%s: copy_to_user for AUDIO_GET_AAC_CONFIG failed\n",
__func__);
rc = -EFAULT;
break;
}
break;
}
case AUDIO_SET_AAC_CONFIG: {
struct msm_audio_aac_config aac_config;
pr_debug("%s: AUDIO_SET_AAC_CONFIG\n", __func__);
if (copy_from_user(&aac_config, (void *)arg,
sizeof(aac_config))) {
pr_err("%s: copy_from_user for AUDIO_SET_AAC_CONFIG failed\n",
__func__);
rc = -EFAULT;
break;
}
rc = audio_ioctl_shared(file, cmd, &aac_config);
if (rc)
pr_err("%s:AUDIO_SET_AAC_CONFIG failed. Rc= %d\n",
__func__, rc);
break;
}
default: {
pr_debug("%s[%pK]: Calling utils ioctl\n", __func__, audio);
rc = audio->codec_ioctl(file, cmd, arg);
if (rc)
pr_err("%s[%pK]:Failed in utils_ioctl: %d\n",
__func__, audio, rc);
}
}
return rc;
}
#ifdef CONFIG_COMPAT
struct msm_audio_aac_config32 {
s16 format;
u16 audio_object;
u16 ep_config; /* 0 ~ 3 useful only obj = ERLC */
u16 aac_section_data_resilience_flag;
u16 aac_scalefactor_data_resilience_flag;
u16 aac_spectral_data_resilience_flag;
u16 sbr_on_flag;
u16 sbr_ps_on_flag;
u16 dual_mono_mode;
u16 channel_configuration;
u16 sample_rate;
};
enum {
AUDIO_SET_AAC_CONFIG_32 = _IOW(AUDIO_IOCTL_MAGIC,
(AUDIO_MAX_COMMON_IOCTL_NUM+0), struct msm_audio_aac_config32),
AUDIO_GET_AAC_CONFIG_32 = _IOR(AUDIO_IOCTL_MAGIC,
(AUDIO_MAX_COMMON_IOCTL_NUM+1), struct msm_audio_aac_config32)
};
static long audio_compat_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
struct q6audio_aio *audio = file->private_data;
int rc = 0;
switch (cmd) {
case AUDIO_START: {
rc = audio_ioctl_shared(file, cmd, (void *)arg);
break;
}
case AUDIO_GET_AAC_CONFIG_32: {
struct msm_audio_aac_config *aac_config;
struct msm_audio_aac_config32 aac_config_32;
aac_config = (struct msm_audio_aac_config *)audio->codec_cfg;
aac_config_32.format = aac_config->format;
aac_config_32.audio_object = aac_config->audio_object;
aac_config_32.ep_config = aac_config->ep_config;
aac_config_32.aac_section_data_resilience_flag =
aac_config->aac_section_data_resilience_flag;
aac_config_32.aac_scalefactor_data_resilience_flag =
aac_config->aac_scalefactor_data_resilience_flag;
aac_config_32.aac_spectral_data_resilience_flag =
aac_config->aac_spectral_data_resilience_flag;
aac_config_32.sbr_on_flag = aac_config->sbr_on_flag;
aac_config_32.sbr_ps_on_flag = aac_config->sbr_ps_on_flag;
aac_config_32.dual_mono_mode = aac_config->dual_mono_mode;
aac_config_32.channel_configuration =
aac_config->channel_configuration;
aac_config_32.sample_rate = aac_config->sample_rate;
if (copy_to_user((void *)arg, &aac_config_32,
sizeof(aac_config_32))) {
pr_err("%s: copy_to_user for AUDIO_GET_AAC_CONFIG_32 failed\n",
__func__);
rc = -EFAULT;
break;
}
break;
}
case AUDIO_SET_AAC_CONFIG_32: {
struct msm_audio_aac_config aac_config;
struct msm_audio_aac_config32 aac_config_32;
pr_debug("%s: AUDIO_SET_AAC_CONFIG\n", __func__);
if (copy_from_user(&aac_config_32, (void *)arg,
sizeof(aac_config_32))) {
pr_err("%s: copy_from_user for AUDIO_SET_AAC_CONFIG_32 failed\n",
__func__);
rc = -EFAULT;
break;
}
aac_config.format = aac_config_32.format;
aac_config.audio_object = aac_config_32.audio_object;
aac_config.ep_config = aac_config_32.ep_config;
aac_config.aac_section_data_resilience_flag =
aac_config_32.aac_section_data_resilience_flag;
aac_config.aac_scalefactor_data_resilience_flag =
aac_config_32.aac_scalefactor_data_resilience_flag;
aac_config.aac_spectral_data_resilience_flag =
aac_config_32.aac_spectral_data_resilience_flag;
aac_config.sbr_on_flag = aac_config_32.sbr_on_flag;
aac_config.sbr_ps_on_flag = aac_config_32.sbr_ps_on_flag;
aac_config.dual_mono_mode = aac_config_32.dual_mono_mode;
aac_config.channel_configuration =
aac_config_32.channel_configuration;
aac_config.sample_rate = aac_config_32.sample_rate;
cmd = AUDIO_SET_AAC_CONFIG;
rc = audio_ioctl_shared(file, cmd, &aac_config);
if (rc)
pr_err("%s:AUDIO_SET_AAC_CONFIG failed. Rc= %d\n",
__func__, rc);
break;
}
default: {
pr_debug("%s[%pK]: Calling utils ioctl\n", __func__, audio);
rc = audio->codec_compat_ioctl(file, cmd, arg);
if (rc)
pr_err("%s[%pK]:Failed in utils_ioctl: %d\n",
__func__, audio, rc);
}
}
return rc;
}
#else
#define audio_compat_ioctl NULL
#endif
static int audio_open(struct inode *inode, struct file *file)
{
struct q6audio_aio *audio = NULL;
int rc = 0;
struct msm_audio_aac_config *aac_config = NULL;
#ifdef CONFIG_DEBUG_FS
/* 4 bytes represents decoder number, 1 byte for terminate string */
char name[sizeof "msm_aac_" + 5];
#endif
audio = kzalloc(sizeof(struct q6audio_aio), GFP_KERNEL);
if (audio == NULL) {
pr_err("Could not allocate memory for aac decode driver\n");
return -ENOMEM;
}
audio->codec_cfg = kzalloc(sizeof(struct msm_audio_aac_config),
GFP_KERNEL);
if (audio->codec_cfg == NULL) {
pr_err("%s:Could not allocate memory for aac"
"config\n", __func__);
kfree(audio);
return -ENOMEM;
}
aac_config = audio->codec_cfg;
/* Settings will be re-config at AUDIO_SET_CONFIG,
* but at least we need to have initial config
*/
audio->pcm_cfg.buffer_size = PCM_BUFSZ_MIN_AAC;
audio->miscdevice = &audio_aac_misc;
audio->wakelock_voted = false;
audio->audio_ws_mgr = &audio_aac_ws_mgr;
aac_config->dual_mono_mode = AUDIO_AAC_DUAL_MONO_INVALID;
init_waitqueue_head(&audio->event_wait);
audio->ac = q6asm_audio_client_alloc((app_cb) q6_audio_cb,
(void *)audio);
if (!audio->ac) {
pr_err("Could not allocate memory for audio client\n");
kfree(audio->codec_cfg);
kfree(audio);
return -ENOMEM;
}
rc = audio_aio_open(audio, file);
if (rc < 0) {
pr_err("%s: audio_aio_open rc=%d\n",
__func__, rc);
goto fail;
}
/* open in T/NT mode */
if ((file->f_mode & FMODE_WRITE) && (file->f_mode & FMODE_READ)) {
rc = q6asm_open_read_write(audio->ac, FORMAT_LINEAR_PCM,
FORMAT_MPEG4_AAC);
if (rc < 0) {
pr_err("NT mode Open failed rc=%d\n", rc);
rc = -ENODEV;
goto fail;
}
audio->feedback = NON_TUNNEL_MODE;
/* open AAC decoder, expected frames is always 1
audio->buf_cfg.frames_per_buf = 0x01;*/
audio->buf_cfg.meta_info_enable = 0x01;
} else if ((file->f_mode & FMODE_WRITE) &&
!(file->f_mode & FMODE_READ)) {
rc = q6asm_open_write(audio->ac, FORMAT_MPEG4_AAC);
if (rc < 0) {
pr_err("T mode Open failed rc=%d\n", rc);
rc = -ENODEV;
goto fail;
}
audio->feedback = TUNNEL_MODE;
audio->buf_cfg.meta_info_enable = 0x00;
} else {
pr_err("Not supported mode\n");
rc = -EACCES;
goto fail;
}
#ifdef CONFIG_DEBUG_FS
snprintf(name, sizeof name, "msm_aac_%04x", audio->ac->session);
audio->dentry = debugfs_create_file(name, S_IFREG | S_IRUGO,
NULL, (void *)audio,
&audio_aac_debug_fops);
if (IS_ERR(audio->dentry))
pr_debug("debugfs_create_file failed\n");
#endif
pr_info("%s:aacdec success mode[%d]session[%d]\n", __func__,
audio->feedback,
audio->ac->session);
return rc;
fail:
q6asm_audio_client_free(audio->ac);
kfree(audio->codec_cfg);
kfree(audio);
return rc;
}
static const struct file_operations audio_aac_fops = {
.owner = THIS_MODULE,
.open = audio_open,
.release = audio_aio_release,
.unlocked_ioctl = audio_ioctl,
.fsync = audio_aio_fsync,
.compat_ioctl = audio_compat_ioctl
};
static struct miscdevice audio_aac_misc = {
.minor = MISC_DYNAMIC_MINOR,
.name = "msm_aac",
.fops = &audio_aac_fops,
};
static int __init audio_aac_init(void)
{
int ret = misc_register(&audio_aac_misc);
if (ret == 0)
device_init_wakeup(audio_aac_misc.this_device, true);
audio_aac_ws_mgr.ref_cnt = 0;
mutex_init(&audio_aac_ws_mgr.ws_lock);
return ret;
}
device_initcall(audio_aac_init);
| gpl-2.0 |
v1ron/linux-mainline | drivers/md/bcache/super.c | 56 | 51119 | /*
* bcache setup/teardown code, and some metadata io - read a superblock and
* figure out what to do with it.
*
* Copyright 2010, 2011 Kent Overstreet <kent.overstreet@gmail.com>
* Copyright 2012 Google, Inc.
*/
#include "bcache.h"
#include "btree.h"
#include "debug.h"
#include "extents.h"
#include "request.h"
#include "writeback.h"
#include <linux/blkdev.h>
#include <linux/buffer_head.h>
#include <linux/debugfs.h>
#include <linux/genhd.h>
#include <linux/idr.h>
#include <linux/kthread.h>
#include <linux/module.h>
#include <linux/random.h>
#include <linux/reboot.h>
#include <linux/sysfs.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Kent Overstreet <kent.overstreet@gmail.com>");
static const char bcache_magic[] = {
0xc6, 0x85, 0x73, 0xf6, 0x4e, 0x1a, 0x45, 0xca,
0x82, 0x65, 0xf5, 0x7f, 0x48, 0xba, 0x6d, 0x81
};
static const char invalid_uuid[] = {
0xa0, 0x3e, 0xf8, 0xed, 0x3e, 0xe1, 0xb8, 0x78,
0xc8, 0x50, 0xfc, 0x5e, 0xcb, 0x16, 0xcd, 0x99
};
/* Default is -1; we skip past it for struct cached_dev's cache mode */
const char * const bch_cache_modes[] = {
"default",
"writethrough",
"writeback",
"writearound",
"none",
NULL
};
static struct kobject *bcache_kobj;
struct mutex bch_register_lock;
LIST_HEAD(bch_cache_sets);
static LIST_HEAD(uncached_devices);
static int bcache_major;
static DEFINE_IDA(bcache_minor);
static wait_queue_head_t unregister_wait;
struct workqueue_struct *bcache_wq;
#define BTREE_MAX_PAGES (256 * 1024 / PAGE_SIZE)
/* Superblock */
static const char *read_super(struct cache_sb *sb, struct block_device *bdev,
struct page **res)
{
const char *err;
struct cache_sb *s;
struct buffer_head *bh = __bread(bdev, 1, SB_SIZE);
unsigned i;
if (!bh)
return "IO error";
s = (struct cache_sb *) bh->b_data;
sb->offset = le64_to_cpu(s->offset);
sb->version = le64_to_cpu(s->version);
memcpy(sb->magic, s->magic, 16);
memcpy(sb->uuid, s->uuid, 16);
memcpy(sb->set_uuid, s->set_uuid, 16);
memcpy(sb->label, s->label, SB_LABEL_SIZE);
sb->flags = le64_to_cpu(s->flags);
sb->seq = le64_to_cpu(s->seq);
sb->last_mount = le32_to_cpu(s->last_mount);
sb->first_bucket = le16_to_cpu(s->first_bucket);
sb->keys = le16_to_cpu(s->keys);
for (i = 0; i < SB_JOURNAL_BUCKETS; i++)
sb->d[i] = le64_to_cpu(s->d[i]);
pr_debug("read sb version %llu, flags %llu, seq %llu, journal size %u",
sb->version, sb->flags, sb->seq, sb->keys);
err = "Not a bcache superblock";
if (sb->offset != SB_SECTOR)
goto err;
if (memcmp(sb->magic, bcache_magic, 16))
goto err;
err = "Too many journal buckets";
if (sb->keys > SB_JOURNAL_BUCKETS)
goto err;
err = "Bad checksum";
if (s->csum != csum_set(s))
goto err;
err = "Bad UUID";
if (bch_is_zero(sb->uuid, 16))
goto err;
sb->block_size = le16_to_cpu(s->block_size);
err = "Superblock block size smaller than device block size";
if (sb->block_size << 9 < bdev_logical_block_size(bdev))
goto err;
switch (sb->version) {
case BCACHE_SB_VERSION_BDEV:
sb->data_offset = BDEV_DATA_START_DEFAULT;
break;
case BCACHE_SB_VERSION_BDEV_WITH_OFFSET:
sb->data_offset = le64_to_cpu(s->data_offset);
err = "Bad data offset";
if (sb->data_offset < BDEV_DATA_START_DEFAULT)
goto err;
break;
case BCACHE_SB_VERSION_CDEV:
case BCACHE_SB_VERSION_CDEV_WITH_UUID:
sb->nbuckets = le64_to_cpu(s->nbuckets);
sb->block_size = le16_to_cpu(s->block_size);
sb->bucket_size = le16_to_cpu(s->bucket_size);
sb->nr_in_set = le16_to_cpu(s->nr_in_set);
sb->nr_this_dev = le16_to_cpu(s->nr_this_dev);
err = "Too many buckets";
if (sb->nbuckets > LONG_MAX)
goto err;
err = "Not enough buckets";
if (sb->nbuckets < 1 << 7)
goto err;
err = "Bad block/bucket size";
if (!is_power_of_2(sb->block_size) ||
sb->block_size > PAGE_SECTORS ||
!is_power_of_2(sb->bucket_size) ||
sb->bucket_size < PAGE_SECTORS)
goto err;
err = "Invalid superblock: device too small";
if (get_capacity(bdev->bd_disk) < sb->bucket_size * sb->nbuckets)
goto err;
err = "Bad UUID";
if (bch_is_zero(sb->set_uuid, 16))
goto err;
err = "Bad cache device number in set";
if (!sb->nr_in_set ||
sb->nr_in_set <= sb->nr_this_dev ||
sb->nr_in_set > MAX_CACHES_PER_SET)
goto err;
err = "Journal buckets not sequential";
for (i = 0; i < sb->keys; i++)
if (sb->d[i] != sb->first_bucket + i)
goto err;
err = "Too many journal buckets";
if (sb->first_bucket + sb->keys > sb->nbuckets)
goto err;
err = "Invalid superblock: first bucket comes before end of super";
if (sb->first_bucket * sb->bucket_size < 16)
goto err;
break;
default:
err = "Unsupported superblock version";
goto err;
}
sb->last_mount = get_seconds();
err = NULL;
get_page(bh->b_page);
*res = bh->b_page;
err:
put_bh(bh);
return err;
}
static void write_bdev_super_endio(struct bio *bio)
{
struct cached_dev *dc = bio->bi_private;
/* XXX: error checking */
closure_put(&dc->sb_write);
}
static void __write_super(struct cache_sb *sb, struct bio *bio)
{
struct cache_sb *out = page_address(bio->bi_io_vec[0].bv_page);
unsigned i;
bio->bi_iter.bi_sector = SB_SECTOR;
bio->bi_rw = REQ_SYNC|REQ_META;
bio->bi_iter.bi_size = SB_SIZE;
bch_bio_map(bio, NULL);
out->offset = cpu_to_le64(sb->offset);
out->version = cpu_to_le64(sb->version);
memcpy(out->uuid, sb->uuid, 16);
memcpy(out->set_uuid, sb->set_uuid, 16);
memcpy(out->label, sb->label, SB_LABEL_SIZE);
out->flags = cpu_to_le64(sb->flags);
out->seq = cpu_to_le64(sb->seq);
out->last_mount = cpu_to_le32(sb->last_mount);
out->first_bucket = cpu_to_le16(sb->first_bucket);
out->keys = cpu_to_le16(sb->keys);
for (i = 0; i < sb->keys; i++)
out->d[i] = cpu_to_le64(sb->d[i]);
out->csum = csum_set(out);
pr_debug("ver %llu, flags %llu, seq %llu",
sb->version, sb->flags, sb->seq);
submit_bio(REQ_WRITE, bio);
}
static void bch_write_bdev_super_unlock(struct closure *cl)
{
struct cached_dev *dc = container_of(cl, struct cached_dev, sb_write);
up(&dc->sb_write_mutex);
}
void bch_write_bdev_super(struct cached_dev *dc, struct closure *parent)
{
struct closure *cl = &dc->sb_write;
struct bio *bio = &dc->sb_bio;
down(&dc->sb_write_mutex);
closure_init(cl, parent);
bio_reset(bio);
bio->bi_bdev = dc->bdev;
bio->bi_end_io = write_bdev_super_endio;
bio->bi_private = dc;
closure_get(cl);
__write_super(&dc->sb, bio);
closure_return_with_destructor(cl, bch_write_bdev_super_unlock);
}
static void write_super_endio(struct bio *bio)
{
struct cache *ca = bio->bi_private;
bch_count_io_errors(ca, bio->bi_error, "writing superblock");
closure_put(&ca->set->sb_write);
}
static void bcache_write_super_unlock(struct closure *cl)
{
struct cache_set *c = container_of(cl, struct cache_set, sb_write);
up(&c->sb_write_mutex);
}
void bcache_write_super(struct cache_set *c)
{
struct closure *cl = &c->sb_write;
struct cache *ca;
unsigned i;
down(&c->sb_write_mutex);
closure_init(cl, &c->cl);
c->sb.seq++;
for_each_cache(ca, c, i) {
struct bio *bio = &ca->sb_bio;
ca->sb.version = BCACHE_SB_VERSION_CDEV_WITH_UUID;
ca->sb.seq = c->sb.seq;
ca->sb.last_mount = c->sb.last_mount;
SET_CACHE_SYNC(&ca->sb, CACHE_SYNC(&c->sb));
bio_reset(bio);
bio->bi_bdev = ca->bdev;
bio->bi_end_io = write_super_endio;
bio->bi_private = ca;
closure_get(cl);
__write_super(&ca->sb, bio);
}
closure_return_with_destructor(cl, bcache_write_super_unlock);
}
/* UUID io */
static void uuid_endio(struct bio *bio)
{
struct closure *cl = bio->bi_private;
struct cache_set *c = container_of(cl, struct cache_set, uuid_write);
cache_set_err_on(bio->bi_error, c, "accessing uuids");
bch_bbio_free(bio, c);
closure_put(cl);
}
static void uuid_io_unlock(struct closure *cl)
{
struct cache_set *c = container_of(cl, struct cache_set, uuid_write);
up(&c->uuid_write_mutex);
}
static void uuid_io(struct cache_set *c, unsigned long rw,
struct bkey *k, struct closure *parent)
{
struct closure *cl = &c->uuid_write;
struct uuid_entry *u;
unsigned i;
char buf[80];
BUG_ON(!parent);
down(&c->uuid_write_mutex);
closure_init(cl, parent);
for (i = 0; i < KEY_PTRS(k); i++) {
struct bio *bio = bch_bbio_alloc(c);
bio->bi_rw = REQ_SYNC|REQ_META|rw;
bio->bi_iter.bi_size = KEY_SIZE(k) << 9;
bio->bi_end_io = uuid_endio;
bio->bi_private = cl;
bch_bio_map(bio, c->uuids);
bch_submit_bbio(bio, c, k, i);
if (!(rw & WRITE))
break;
}
bch_extent_to_text(buf, sizeof(buf), k);
pr_debug("%s UUIDs at %s", rw & REQ_WRITE ? "wrote" : "read", buf);
for (u = c->uuids; u < c->uuids + c->nr_uuids; u++)
if (!bch_is_zero(u->uuid, 16))
pr_debug("Slot %zi: %pU: %s: 1st: %u last: %u inv: %u",
u - c->uuids, u->uuid, u->label,
u->first_reg, u->last_reg, u->invalidated);
closure_return_with_destructor(cl, uuid_io_unlock);
}
static char *uuid_read(struct cache_set *c, struct jset *j, struct closure *cl)
{
struct bkey *k = &j->uuid_bucket;
if (__bch_btree_ptr_invalid(c, k))
return "bad uuid pointer";
bkey_copy(&c->uuid_bucket, k);
uuid_io(c, READ_SYNC, k, cl);
if (j->version < BCACHE_JSET_VERSION_UUIDv1) {
struct uuid_entry_v0 *u0 = (void *) c->uuids;
struct uuid_entry *u1 = (void *) c->uuids;
int i;
closure_sync(cl);
/*
* Since the new uuid entry is bigger than the old, we have to
* convert starting at the highest memory address and work down
* in order to do it in place
*/
for (i = c->nr_uuids - 1;
i >= 0;
--i) {
memcpy(u1[i].uuid, u0[i].uuid, 16);
memcpy(u1[i].label, u0[i].label, 32);
u1[i].first_reg = u0[i].first_reg;
u1[i].last_reg = u0[i].last_reg;
u1[i].invalidated = u0[i].invalidated;
u1[i].flags = 0;
u1[i].sectors = 0;
}
}
return NULL;
}
static int __uuid_write(struct cache_set *c)
{
BKEY_PADDED(key) k;
struct closure cl;
closure_init_stack(&cl);
lockdep_assert_held(&bch_register_lock);
if (bch_bucket_alloc_set(c, RESERVE_BTREE, &k.key, 1, true))
return 1;
SET_KEY_SIZE(&k.key, c->sb.bucket_size);
uuid_io(c, REQ_WRITE, &k.key, &cl);
closure_sync(&cl);
bkey_copy(&c->uuid_bucket, &k.key);
bkey_put(c, &k.key);
return 0;
}
int bch_uuid_write(struct cache_set *c)
{
int ret = __uuid_write(c);
if (!ret)
bch_journal_meta(c, NULL);
return ret;
}
static struct uuid_entry *uuid_find(struct cache_set *c, const char *uuid)
{
struct uuid_entry *u;
for (u = c->uuids;
u < c->uuids + c->nr_uuids; u++)
if (!memcmp(u->uuid, uuid, 16))
return u;
return NULL;
}
static struct uuid_entry *uuid_find_empty(struct cache_set *c)
{
static const char zero_uuid[16] = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
return uuid_find(c, zero_uuid);
}
/*
* Bucket priorities/gens:
*
* For each bucket, we store on disk its
* 8 bit gen
* 16 bit priority
*
* See alloc.c for an explanation of the gen. The priority is used to implement
* lru (and in the future other) cache replacement policies; for most purposes
* it's just an opaque integer.
*
* The gens and the priorities don't have a whole lot to do with each other, and
* it's actually the gens that must be written out at specific times - it's no
* big deal if the priorities don't get written, if we lose them we just reuse
* buckets in suboptimal order.
*
* On disk they're stored in a packed array, and in as many buckets are required
* to fit them all. The buckets we use to store them form a list; the journal
* header points to the first bucket, the first bucket points to the second
* bucket, et cetera.
*
* This code is used by the allocation code; periodically (whenever it runs out
* of buckets to allocate from) the allocation code will invalidate some
* buckets, but it can't use those buckets until their new gens are safely on
* disk.
*/
static void prio_endio(struct bio *bio)
{
struct cache *ca = bio->bi_private;
cache_set_err_on(bio->bi_error, ca->set, "accessing priorities");
bch_bbio_free(bio, ca->set);
closure_put(&ca->prio);
}
static void prio_io(struct cache *ca, uint64_t bucket, unsigned long rw)
{
struct closure *cl = &ca->prio;
struct bio *bio = bch_bbio_alloc(ca->set);
closure_init_stack(cl);
bio->bi_iter.bi_sector = bucket * ca->sb.bucket_size;
bio->bi_bdev = ca->bdev;
bio->bi_rw = REQ_SYNC|REQ_META|rw;
bio->bi_iter.bi_size = bucket_bytes(ca);
bio->bi_end_io = prio_endio;
bio->bi_private = ca;
bch_bio_map(bio, ca->disk_buckets);
closure_bio_submit(bio, &ca->prio);
closure_sync(cl);
}
void bch_prio_write(struct cache *ca)
{
int i;
struct bucket *b;
struct closure cl;
closure_init_stack(&cl);
lockdep_assert_held(&ca->set->bucket_lock);
ca->disk_buckets->seq++;
atomic_long_add(ca->sb.bucket_size * prio_buckets(ca),
&ca->meta_sectors_written);
//pr_debug("free %zu, free_inc %zu, unused %zu", fifo_used(&ca->free),
// fifo_used(&ca->free_inc), fifo_used(&ca->unused));
for (i = prio_buckets(ca) - 1; i >= 0; --i) {
long bucket;
struct prio_set *p = ca->disk_buckets;
struct bucket_disk *d = p->data;
struct bucket_disk *end = d + prios_per_bucket(ca);
for (b = ca->buckets + i * prios_per_bucket(ca);
b < ca->buckets + ca->sb.nbuckets && d < end;
b++, d++) {
d->prio = cpu_to_le16(b->prio);
d->gen = b->gen;
}
p->next_bucket = ca->prio_buckets[i + 1];
p->magic = pset_magic(&ca->sb);
p->csum = bch_crc64(&p->magic, bucket_bytes(ca) - 8);
bucket = bch_bucket_alloc(ca, RESERVE_PRIO, true);
BUG_ON(bucket == -1);
mutex_unlock(&ca->set->bucket_lock);
prio_io(ca, bucket, REQ_WRITE);
mutex_lock(&ca->set->bucket_lock);
ca->prio_buckets[i] = bucket;
atomic_dec_bug(&ca->buckets[bucket].pin);
}
mutex_unlock(&ca->set->bucket_lock);
bch_journal_meta(ca->set, &cl);
closure_sync(&cl);
mutex_lock(&ca->set->bucket_lock);
/*
* Don't want the old priorities to get garbage collected until after we
* finish writing the new ones, and they're journalled
*/
for (i = 0; i < prio_buckets(ca); i++) {
if (ca->prio_last_buckets[i])
__bch_bucket_free(ca,
&ca->buckets[ca->prio_last_buckets[i]]);
ca->prio_last_buckets[i] = ca->prio_buckets[i];
}
}
static void prio_read(struct cache *ca, uint64_t bucket)
{
struct prio_set *p = ca->disk_buckets;
struct bucket_disk *d = p->data + prios_per_bucket(ca), *end = d;
struct bucket *b;
unsigned bucket_nr = 0;
for (b = ca->buckets;
b < ca->buckets + ca->sb.nbuckets;
b++, d++) {
if (d == end) {
ca->prio_buckets[bucket_nr] = bucket;
ca->prio_last_buckets[bucket_nr] = bucket;
bucket_nr++;
prio_io(ca, bucket, READ_SYNC);
if (p->csum != bch_crc64(&p->magic, bucket_bytes(ca) - 8))
pr_warn("bad csum reading priorities");
if (p->magic != pset_magic(&ca->sb))
pr_warn("bad magic reading priorities");
bucket = p->next_bucket;
d = p->data;
}
b->prio = le16_to_cpu(d->prio);
b->gen = b->last_gc = d->gen;
}
}
/* Bcache device */
static int open_dev(struct block_device *b, fmode_t mode)
{
struct bcache_device *d = b->bd_disk->private_data;
if (test_bit(BCACHE_DEV_CLOSING, &d->flags))
return -ENXIO;
closure_get(&d->cl);
return 0;
}
static void release_dev(struct gendisk *b, fmode_t mode)
{
struct bcache_device *d = b->private_data;
closure_put(&d->cl);
}
static int ioctl_dev(struct block_device *b, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
struct bcache_device *d = b->bd_disk->private_data;
return d->ioctl(d, mode, cmd, arg);
}
static const struct block_device_operations bcache_ops = {
.open = open_dev,
.release = release_dev,
.ioctl = ioctl_dev,
.owner = THIS_MODULE,
};
void bcache_device_stop(struct bcache_device *d)
{
if (!test_and_set_bit(BCACHE_DEV_CLOSING, &d->flags))
closure_queue(&d->cl);
}
static void bcache_device_unlink(struct bcache_device *d)
{
lockdep_assert_held(&bch_register_lock);
if (d->c && !test_and_set_bit(BCACHE_DEV_UNLINK_DONE, &d->flags)) {
unsigned i;
struct cache *ca;
sysfs_remove_link(&d->c->kobj, d->name);
sysfs_remove_link(&d->kobj, "cache");
for_each_cache(ca, d->c, i)
bd_unlink_disk_holder(ca->bdev, d->disk);
}
}
static void bcache_device_link(struct bcache_device *d, struct cache_set *c,
const char *name)
{
unsigned i;
struct cache *ca;
for_each_cache(ca, d->c, i)
bd_link_disk_holder(ca->bdev, d->disk);
snprintf(d->name, BCACHEDEVNAME_SIZE,
"%s%u", name, d->id);
WARN(sysfs_create_link(&d->kobj, &c->kobj, "cache") ||
sysfs_create_link(&c->kobj, &d->kobj, d->name),
"Couldn't create device <-> cache set symlinks");
clear_bit(BCACHE_DEV_UNLINK_DONE, &d->flags);
}
static void bcache_device_detach(struct bcache_device *d)
{
lockdep_assert_held(&bch_register_lock);
if (test_bit(BCACHE_DEV_DETACHING, &d->flags)) {
struct uuid_entry *u = d->c->uuids + d->id;
SET_UUID_FLASH_ONLY(u, 0);
memcpy(u->uuid, invalid_uuid, 16);
u->invalidated = cpu_to_le32(get_seconds());
bch_uuid_write(d->c);
}
bcache_device_unlink(d);
d->c->devices[d->id] = NULL;
closure_put(&d->c->caching);
d->c = NULL;
}
static void bcache_device_attach(struct bcache_device *d, struct cache_set *c,
unsigned id)
{
d->id = id;
d->c = c;
c->devices[id] = d;
closure_get(&c->caching);
}
static void bcache_device_free(struct bcache_device *d)
{
lockdep_assert_held(&bch_register_lock);
pr_info("%s stopped", d->disk->disk_name);
if (d->c)
bcache_device_detach(d);
if (d->disk && d->disk->flags & GENHD_FL_UP)
del_gendisk(d->disk);
if (d->disk && d->disk->queue)
blk_cleanup_queue(d->disk->queue);
if (d->disk) {
ida_simple_remove(&bcache_minor, d->disk->first_minor);
put_disk(d->disk);
}
if (d->bio_split)
bioset_free(d->bio_split);
kvfree(d->full_dirty_stripes);
kvfree(d->stripe_sectors_dirty);
closure_debug_destroy(&d->cl);
}
static int bcache_device_init(struct bcache_device *d, unsigned block_size,
sector_t sectors)
{
struct request_queue *q;
size_t n;
int minor;
if (!d->stripe_size)
d->stripe_size = 1 << 31;
d->nr_stripes = DIV_ROUND_UP_ULL(sectors, d->stripe_size);
if (!d->nr_stripes ||
d->nr_stripes > INT_MAX ||
d->nr_stripes > SIZE_MAX / sizeof(atomic_t)) {
pr_err("nr_stripes too large");
return -ENOMEM;
}
n = d->nr_stripes * sizeof(atomic_t);
d->stripe_sectors_dirty = n < PAGE_SIZE << 6
? kzalloc(n, GFP_KERNEL)
: vzalloc(n);
if (!d->stripe_sectors_dirty)
return -ENOMEM;
n = BITS_TO_LONGS(d->nr_stripes) * sizeof(unsigned long);
d->full_dirty_stripes = n < PAGE_SIZE << 6
? kzalloc(n, GFP_KERNEL)
: vzalloc(n);
if (!d->full_dirty_stripes)
return -ENOMEM;
minor = ida_simple_get(&bcache_minor, 0, MINORMASK + 1, GFP_KERNEL);
if (minor < 0)
return minor;
if (!(d->bio_split = bioset_create(4, offsetof(struct bbio, bio))) ||
!(d->disk = alloc_disk(1))) {
ida_simple_remove(&bcache_minor, minor);
return -ENOMEM;
}
set_capacity(d->disk, sectors);
snprintf(d->disk->disk_name, DISK_NAME_LEN, "bcache%i", minor);
d->disk->major = bcache_major;
d->disk->first_minor = minor;
d->disk->fops = &bcache_ops;
d->disk->private_data = d;
q = blk_alloc_queue(GFP_KERNEL);
if (!q)
return -ENOMEM;
blk_queue_make_request(q, NULL);
d->disk->queue = q;
q->queuedata = d;
q->backing_dev_info.congested_data = d;
q->limits.max_hw_sectors = UINT_MAX;
q->limits.max_sectors = UINT_MAX;
q->limits.max_segment_size = UINT_MAX;
q->limits.max_segments = BIO_MAX_PAGES;
blk_queue_max_discard_sectors(q, UINT_MAX);
q->limits.discard_granularity = 512;
q->limits.io_min = block_size;
q->limits.logical_block_size = block_size;
q->limits.physical_block_size = block_size;
set_bit(QUEUE_FLAG_NONROT, &d->disk->queue->queue_flags);
clear_bit(QUEUE_FLAG_ADD_RANDOM, &d->disk->queue->queue_flags);
set_bit(QUEUE_FLAG_DISCARD, &d->disk->queue->queue_flags);
blk_queue_flush(q, REQ_FLUSH|REQ_FUA);
return 0;
}
/* Cached device */
static void calc_cached_dev_sectors(struct cache_set *c)
{
uint64_t sectors = 0;
struct cached_dev *dc;
list_for_each_entry(dc, &c->cached_devs, list)
sectors += bdev_sectors(dc->bdev);
c->cached_dev_sectors = sectors;
}
void bch_cached_dev_run(struct cached_dev *dc)
{
struct bcache_device *d = &dc->disk;
char buf[SB_LABEL_SIZE + 1];
char *env[] = {
"DRIVER=bcache",
kasprintf(GFP_KERNEL, "CACHED_UUID=%pU", dc->sb.uuid),
NULL,
NULL,
};
memcpy(buf, dc->sb.label, SB_LABEL_SIZE);
buf[SB_LABEL_SIZE] = '\0';
env[2] = kasprintf(GFP_KERNEL, "CACHED_LABEL=%s", buf);
if (atomic_xchg(&dc->running, 1)) {
kfree(env[1]);
kfree(env[2]);
return;
}
if (!d->c &&
BDEV_STATE(&dc->sb) != BDEV_STATE_NONE) {
struct closure cl;
closure_init_stack(&cl);
SET_BDEV_STATE(&dc->sb, BDEV_STATE_STALE);
bch_write_bdev_super(dc, &cl);
closure_sync(&cl);
}
add_disk(d->disk);
bd_link_disk_holder(dc->bdev, dc->disk.disk);
/* won't show up in the uevent file, use udevadm monitor -e instead
* only class / kset properties are persistent */
kobject_uevent_env(&disk_to_dev(d->disk)->kobj, KOBJ_CHANGE, env);
kfree(env[1]);
kfree(env[2]);
if (sysfs_create_link(&d->kobj, &disk_to_dev(d->disk)->kobj, "dev") ||
sysfs_create_link(&disk_to_dev(d->disk)->kobj, &d->kobj, "bcache"))
pr_debug("error creating sysfs link");
}
static void cached_dev_detach_finish(struct work_struct *w)
{
struct cached_dev *dc = container_of(w, struct cached_dev, detach);
char buf[BDEVNAME_SIZE];
struct closure cl;
closure_init_stack(&cl);
BUG_ON(!test_bit(BCACHE_DEV_DETACHING, &dc->disk.flags));
BUG_ON(atomic_read(&dc->count));
mutex_lock(&bch_register_lock);
memset(&dc->sb.set_uuid, 0, 16);
SET_BDEV_STATE(&dc->sb, BDEV_STATE_NONE);
bch_write_bdev_super(dc, &cl);
closure_sync(&cl);
bcache_device_detach(&dc->disk);
list_move(&dc->list, &uncached_devices);
clear_bit(BCACHE_DEV_DETACHING, &dc->disk.flags);
clear_bit(BCACHE_DEV_UNLINK_DONE, &dc->disk.flags);
mutex_unlock(&bch_register_lock);
pr_info("Caching disabled for %s", bdevname(dc->bdev, buf));
/* Drop ref we took in cached_dev_detach() */
closure_put(&dc->disk.cl);
}
void bch_cached_dev_detach(struct cached_dev *dc)
{
lockdep_assert_held(&bch_register_lock);
if (test_bit(BCACHE_DEV_CLOSING, &dc->disk.flags))
return;
if (test_and_set_bit(BCACHE_DEV_DETACHING, &dc->disk.flags))
return;
/*
* Block the device from being closed and freed until we're finished
* detaching
*/
closure_get(&dc->disk.cl);
bch_writeback_queue(dc);
cached_dev_put(dc);
}
int bch_cached_dev_attach(struct cached_dev *dc, struct cache_set *c)
{
uint32_t rtime = cpu_to_le32(get_seconds());
struct uuid_entry *u;
char buf[BDEVNAME_SIZE];
bdevname(dc->bdev, buf);
if (memcmp(dc->sb.set_uuid, c->sb.set_uuid, 16))
return -ENOENT;
if (dc->disk.c) {
pr_err("Can't attach %s: already attached", buf);
return -EINVAL;
}
if (test_bit(CACHE_SET_STOPPING, &c->flags)) {
pr_err("Can't attach %s: shutting down", buf);
return -EINVAL;
}
if (dc->sb.block_size < c->sb.block_size) {
/* Will die */
pr_err("Couldn't attach %s: block size less than set's block size",
buf);
return -EINVAL;
}
u = uuid_find(c, dc->sb.uuid);
if (u &&
(BDEV_STATE(&dc->sb) == BDEV_STATE_STALE ||
BDEV_STATE(&dc->sb) == BDEV_STATE_NONE)) {
memcpy(u->uuid, invalid_uuid, 16);
u->invalidated = cpu_to_le32(get_seconds());
u = NULL;
}
if (!u) {
if (BDEV_STATE(&dc->sb) == BDEV_STATE_DIRTY) {
pr_err("Couldn't find uuid for %s in set", buf);
return -ENOENT;
}
u = uuid_find_empty(c);
if (!u) {
pr_err("Not caching %s, no room for UUID", buf);
return -EINVAL;
}
}
/* Deadlocks since we're called via sysfs...
sysfs_remove_file(&dc->kobj, &sysfs_attach);
*/
if (bch_is_zero(u->uuid, 16)) {
struct closure cl;
closure_init_stack(&cl);
memcpy(u->uuid, dc->sb.uuid, 16);
memcpy(u->label, dc->sb.label, SB_LABEL_SIZE);
u->first_reg = u->last_reg = rtime;
bch_uuid_write(c);
memcpy(dc->sb.set_uuid, c->sb.set_uuid, 16);
SET_BDEV_STATE(&dc->sb, BDEV_STATE_CLEAN);
bch_write_bdev_super(dc, &cl);
closure_sync(&cl);
} else {
u->last_reg = rtime;
bch_uuid_write(c);
}
bcache_device_attach(&dc->disk, c, u - c->uuids);
list_move(&dc->list, &c->cached_devs);
calc_cached_dev_sectors(c);
smp_wmb();
/*
* dc->c must be set before dc->count != 0 - paired with the mb in
* cached_dev_get()
*/
atomic_set(&dc->count, 1);
/* Block writeback thread, but spawn it */
down_write(&dc->writeback_lock);
if (bch_cached_dev_writeback_start(dc)) {
up_write(&dc->writeback_lock);
return -ENOMEM;
}
if (BDEV_STATE(&dc->sb) == BDEV_STATE_DIRTY) {
bch_sectors_dirty_init(dc);
atomic_set(&dc->has_dirty, 1);
atomic_inc(&dc->count);
bch_writeback_queue(dc);
}
bch_cached_dev_run(dc);
bcache_device_link(&dc->disk, c, "bdev");
/* Allow the writeback thread to proceed */
up_write(&dc->writeback_lock);
pr_info("Caching %s as %s on set %pU",
bdevname(dc->bdev, buf), dc->disk.disk->disk_name,
dc->disk.c->sb.set_uuid);
return 0;
}
void bch_cached_dev_release(struct kobject *kobj)
{
struct cached_dev *dc = container_of(kobj, struct cached_dev,
disk.kobj);
kfree(dc);
module_put(THIS_MODULE);
}
static void cached_dev_free(struct closure *cl)
{
struct cached_dev *dc = container_of(cl, struct cached_dev, disk.cl);
cancel_delayed_work_sync(&dc->writeback_rate_update);
if (!IS_ERR_OR_NULL(dc->writeback_thread))
kthread_stop(dc->writeback_thread);
mutex_lock(&bch_register_lock);
if (atomic_read(&dc->running))
bd_unlink_disk_holder(dc->bdev, dc->disk.disk);
bcache_device_free(&dc->disk);
list_del(&dc->list);
mutex_unlock(&bch_register_lock);
if (!IS_ERR_OR_NULL(dc->bdev))
blkdev_put(dc->bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
wake_up(&unregister_wait);
kobject_put(&dc->disk.kobj);
}
static void cached_dev_flush(struct closure *cl)
{
struct cached_dev *dc = container_of(cl, struct cached_dev, disk.cl);
struct bcache_device *d = &dc->disk;
mutex_lock(&bch_register_lock);
bcache_device_unlink(d);
mutex_unlock(&bch_register_lock);
bch_cache_accounting_destroy(&dc->accounting);
kobject_del(&d->kobj);
continue_at(cl, cached_dev_free, system_wq);
}
static int cached_dev_init(struct cached_dev *dc, unsigned block_size)
{
int ret;
struct io *io;
struct request_queue *q = bdev_get_queue(dc->bdev);
__module_get(THIS_MODULE);
INIT_LIST_HEAD(&dc->list);
closure_init(&dc->disk.cl, NULL);
set_closure_fn(&dc->disk.cl, cached_dev_flush, system_wq);
kobject_init(&dc->disk.kobj, &bch_cached_dev_ktype);
INIT_WORK(&dc->detach, cached_dev_detach_finish);
sema_init(&dc->sb_write_mutex, 1);
INIT_LIST_HEAD(&dc->io_lru);
spin_lock_init(&dc->io_lock);
bch_cache_accounting_init(&dc->accounting, &dc->disk.cl);
dc->sequential_cutoff = 4 << 20;
for (io = dc->io; io < dc->io + RECENT_IO; io++) {
list_add(&io->lru, &dc->io_lru);
hlist_add_head(&io->hash, dc->io_hash + RECENT_IO);
}
dc->disk.stripe_size = q->limits.io_opt >> 9;
if (dc->disk.stripe_size)
dc->partial_stripes_expensive =
q->limits.raid_partial_stripes_expensive;
ret = bcache_device_init(&dc->disk, block_size,
dc->bdev->bd_part->nr_sects - dc->sb.data_offset);
if (ret)
return ret;
set_capacity(dc->disk.disk,
dc->bdev->bd_part->nr_sects - dc->sb.data_offset);
dc->disk.disk->queue->backing_dev_info.ra_pages =
max(dc->disk.disk->queue->backing_dev_info.ra_pages,
q->backing_dev_info.ra_pages);
bch_cached_dev_request_init(dc);
bch_cached_dev_writeback_init(dc);
return 0;
}
/* Cached device - bcache superblock */
static void register_bdev(struct cache_sb *sb, struct page *sb_page,
struct block_device *bdev,
struct cached_dev *dc)
{
char name[BDEVNAME_SIZE];
const char *err = "cannot allocate memory";
struct cache_set *c;
memcpy(&dc->sb, sb, sizeof(struct cache_sb));
dc->bdev = bdev;
dc->bdev->bd_holder = dc;
bio_init(&dc->sb_bio);
dc->sb_bio.bi_max_vecs = 1;
dc->sb_bio.bi_io_vec = dc->sb_bio.bi_inline_vecs;
dc->sb_bio.bi_io_vec[0].bv_page = sb_page;
get_page(sb_page);
if (cached_dev_init(dc, sb->block_size << 9))
goto err;
err = "error creating kobject";
if (kobject_add(&dc->disk.kobj, &part_to_dev(bdev->bd_part)->kobj,
"bcache"))
goto err;
if (bch_cache_accounting_add_kobjs(&dc->accounting, &dc->disk.kobj))
goto err;
pr_info("registered backing device %s", bdevname(bdev, name));
list_add(&dc->list, &uncached_devices);
list_for_each_entry(c, &bch_cache_sets, list)
bch_cached_dev_attach(dc, c);
if (BDEV_STATE(&dc->sb) == BDEV_STATE_NONE ||
BDEV_STATE(&dc->sb) == BDEV_STATE_STALE)
bch_cached_dev_run(dc);
return;
err:
pr_notice("error opening %s: %s", bdevname(bdev, name), err);
bcache_device_stop(&dc->disk);
}
/* Flash only volumes */
void bch_flash_dev_release(struct kobject *kobj)
{
struct bcache_device *d = container_of(kobj, struct bcache_device,
kobj);
kfree(d);
}
static void flash_dev_free(struct closure *cl)
{
struct bcache_device *d = container_of(cl, struct bcache_device, cl);
mutex_lock(&bch_register_lock);
bcache_device_free(d);
mutex_unlock(&bch_register_lock);
kobject_put(&d->kobj);
}
static void flash_dev_flush(struct closure *cl)
{
struct bcache_device *d = container_of(cl, struct bcache_device, cl);
mutex_lock(&bch_register_lock);
bcache_device_unlink(d);
mutex_unlock(&bch_register_lock);
kobject_del(&d->kobj);
continue_at(cl, flash_dev_free, system_wq);
}
static int flash_dev_run(struct cache_set *c, struct uuid_entry *u)
{
struct bcache_device *d = kzalloc(sizeof(struct bcache_device),
GFP_KERNEL);
if (!d)
return -ENOMEM;
closure_init(&d->cl, NULL);
set_closure_fn(&d->cl, flash_dev_flush, system_wq);
kobject_init(&d->kobj, &bch_flash_dev_ktype);
if (bcache_device_init(d, block_bytes(c), u->sectors))
goto err;
bcache_device_attach(d, c, u - c->uuids);
bch_flash_dev_request_init(d);
add_disk(d->disk);
if (kobject_add(&d->kobj, &disk_to_dev(d->disk)->kobj, "bcache"))
goto err;
bcache_device_link(d, c, "volume");
return 0;
err:
kobject_put(&d->kobj);
return -ENOMEM;
}
static int flash_devs_run(struct cache_set *c)
{
int ret = 0;
struct uuid_entry *u;
for (u = c->uuids;
u < c->uuids + c->nr_uuids && !ret;
u++)
if (UUID_FLASH_ONLY(u))
ret = flash_dev_run(c, u);
return ret;
}
int bch_flash_dev_create(struct cache_set *c, uint64_t size)
{
struct uuid_entry *u;
if (test_bit(CACHE_SET_STOPPING, &c->flags))
return -EINTR;
if (!test_bit(CACHE_SET_RUNNING, &c->flags))
return -EPERM;
u = uuid_find_empty(c);
if (!u) {
pr_err("Can't create volume, no room for UUID");
return -EINVAL;
}
get_random_bytes(u->uuid, 16);
memset(u->label, 0, 32);
u->first_reg = u->last_reg = cpu_to_le32(get_seconds());
SET_UUID_FLASH_ONLY(u, 1);
u->sectors = size >> 9;
bch_uuid_write(c);
return flash_dev_run(c, u);
}
/* Cache set */
__printf(2, 3)
bool bch_cache_set_error(struct cache_set *c, const char *fmt, ...)
{
va_list args;
if (c->on_error != ON_ERROR_PANIC &&
test_bit(CACHE_SET_STOPPING, &c->flags))
return false;
/* XXX: we can be called from atomic context
acquire_console_sem();
*/
printk(KERN_ERR "bcache: error on %pU: ", c->sb.set_uuid);
va_start(args, fmt);
vprintk(fmt, args);
va_end(args);
printk(", disabling caching\n");
if (c->on_error == ON_ERROR_PANIC)
panic("panic forced after error\n");
bch_cache_set_unregister(c);
return true;
}
void bch_cache_set_release(struct kobject *kobj)
{
struct cache_set *c = container_of(kobj, struct cache_set, kobj);
kfree(c);
module_put(THIS_MODULE);
}
static void cache_set_free(struct closure *cl)
{
struct cache_set *c = container_of(cl, struct cache_set, cl);
struct cache *ca;
unsigned i;
if (!IS_ERR_OR_NULL(c->debug))
debugfs_remove(c->debug);
bch_open_buckets_free(c);
bch_btree_cache_free(c);
bch_journal_free(c);
for_each_cache(ca, c, i)
if (ca) {
ca->set = NULL;
c->cache[ca->sb.nr_this_dev] = NULL;
kobject_put(&ca->kobj);
}
bch_bset_sort_state_free(&c->sort);
free_pages((unsigned long) c->uuids, ilog2(bucket_pages(c)));
if (c->moving_gc_wq)
destroy_workqueue(c->moving_gc_wq);
if (c->bio_split)
bioset_free(c->bio_split);
if (c->fill_iter)
mempool_destroy(c->fill_iter);
if (c->bio_meta)
mempool_destroy(c->bio_meta);
if (c->search)
mempool_destroy(c->search);
kfree(c->devices);
mutex_lock(&bch_register_lock);
list_del(&c->list);
mutex_unlock(&bch_register_lock);
pr_info("Cache set %pU unregistered", c->sb.set_uuid);
wake_up(&unregister_wait);
closure_debug_destroy(&c->cl);
kobject_put(&c->kobj);
}
static void cache_set_flush(struct closure *cl)
{
struct cache_set *c = container_of(cl, struct cache_set, caching);
struct cache *ca;
struct btree *b;
unsigned i;
if (!c)
closure_return(cl);
bch_cache_accounting_destroy(&c->accounting);
kobject_put(&c->internal);
kobject_del(&c->kobj);
if (c->gc_thread)
kthread_stop(c->gc_thread);
if (!IS_ERR_OR_NULL(c->root))
list_add(&c->root->list, &c->btree_cache);
/* Should skip this if we're unregistering because of an error */
list_for_each_entry(b, &c->btree_cache, list) {
mutex_lock(&b->write_lock);
if (btree_node_dirty(b))
__bch_btree_node_write(b, NULL);
mutex_unlock(&b->write_lock);
}
for_each_cache(ca, c, i)
if (ca->alloc_thread)
kthread_stop(ca->alloc_thread);
if (c->journal.cur) {
cancel_delayed_work_sync(&c->journal.work);
/* flush last journal entry if needed */
c->journal.work.work.func(&c->journal.work.work);
}
closure_return(cl);
}
static void __cache_set_unregister(struct closure *cl)
{
struct cache_set *c = container_of(cl, struct cache_set, caching);
struct cached_dev *dc;
size_t i;
mutex_lock(&bch_register_lock);
for (i = 0; i < c->nr_uuids; i++)
if (c->devices[i]) {
if (!UUID_FLASH_ONLY(&c->uuids[i]) &&
test_bit(CACHE_SET_UNREGISTERING, &c->flags)) {
dc = container_of(c->devices[i],
struct cached_dev, disk);
bch_cached_dev_detach(dc);
} else {
bcache_device_stop(c->devices[i]);
}
}
mutex_unlock(&bch_register_lock);
continue_at(cl, cache_set_flush, system_wq);
}
void bch_cache_set_stop(struct cache_set *c)
{
if (!test_and_set_bit(CACHE_SET_STOPPING, &c->flags))
closure_queue(&c->caching);
}
void bch_cache_set_unregister(struct cache_set *c)
{
set_bit(CACHE_SET_UNREGISTERING, &c->flags);
bch_cache_set_stop(c);
}
#define alloc_bucket_pages(gfp, c) \
((void *) __get_free_pages(__GFP_ZERO|gfp, ilog2(bucket_pages(c))))
struct cache_set *bch_cache_set_alloc(struct cache_sb *sb)
{
int iter_size;
struct cache_set *c = kzalloc(sizeof(struct cache_set), GFP_KERNEL);
if (!c)
return NULL;
__module_get(THIS_MODULE);
closure_init(&c->cl, NULL);
set_closure_fn(&c->cl, cache_set_free, system_wq);
closure_init(&c->caching, &c->cl);
set_closure_fn(&c->caching, __cache_set_unregister, system_wq);
/* Maybe create continue_at_noreturn() and use it here? */
closure_set_stopped(&c->cl);
closure_put(&c->cl);
kobject_init(&c->kobj, &bch_cache_set_ktype);
kobject_init(&c->internal, &bch_cache_set_internal_ktype);
bch_cache_accounting_init(&c->accounting, &c->cl);
memcpy(c->sb.set_uuid, sb->set_uuid, 16);
c->sb.block_size = sb->block_size;
c->sb.bucket_size = sb->bucket_size;
c->sb.nr_in_set = sb->nr_in_set;
c->sb.last_mount = sb->last_mount;
c->bucket_bits = ilog2(sb->bucket_size);
c->block_bits = ilog2(sb->block_size);
c->nr_uuids = bucket_bytes(c) / sizeof(struct uuid_entry);
c->btree_pages = bucket_pages(c);
if (c->btree_pages > BTREE_MAX_PAGES)
c->btree_pages = max_t(int, c->btree_pages / 4,
BTREE_MAX_PAGES);
sema_init(&c->sb_write_mutex, 1);
mutex_init(&c->bucket_lock);
init_waitqueue_head(&c->btree_cache_wait);
init_waitqueue_head(&c->bucket_wait);
sema_init(&c->uuid_write_mutex, 1);
spin_lock_init(&c->btree_gc_time.lock);
spin_lock_init(&c->btree_split_time.lock);
spin_lock_init(&c->btree_read_time.lock);
bch_moving_init_cache_set(c);
INIT_LIST_HEAD(&c->list);
INIT_LIST_HEAD(&c->cached_devs);
INIT_LIST_HEAD(&c->btree_cache);
INIT_LIST_HEAD(&c->btree_cache_freeable);
INIT_LIST_HEAD(&c->btree_cache_freed);
INIT_LIST_HEAD(&c->data_buckets);
c->search = mempool_create_slab_pool(32, bch_search_cache);
if (!c->search)
goto err;
iter_size = (sb->bucket_size / sb->block_size + 1) *
sizeof(struct btree_iter_set);
if (!(c->devices = kzalloc(c->nr_uuids * sizeof(void *), GFP_KERNEL)) ||
!(c->bio_meta = mempool_create_kmalloc_pool(2,
sizeof(struct bbio) + sizeof(struct bio_vec) *
bucket_pages(c))) ||
!(c->fill_iter = mempool_create_kmalloc_pool(1, iter_size)) ||
!(c->bio_split = bioset_create(4, offsetof(struct bbio, bio))) ||
!(c->uuids = alloc_bucket_pages(GFP_KERNEL, c)) ||
!(c->moving_gc_wq = create_workqueue("bcache_gc")) ||
bch_journal_alloc(c) ||
bch_btree_cache_alloc(c) ||
bch_open_buckets_alloc(c) ||
bch_bset_sort_state_init(&c->sort, ilog2(c->btree_pages)))
goto err;
c->congested_read_threshold_us = 2000;
c->congested_write_threshold_us = 20000;
c->error_limit = 8 << IO_ERROR_SHIFT;
return c;
err:
bch_cache_set_unregister(c);
return NULL;
}
static void run_cache_set(struct cache_set *c)
{
const char *err = "cannot allocate memory";
struct cached_dev *dc, *t;
struct cache *ca;
struct closure cl;
unsigned i;
closure_init_stack(&cl);
for_each_cache(ca, c, i)
c->nbuckets += ca->sb.nbuckets;
if (CACHE_SYNC(&c->sb)) {
LIST_HEAD(journal);
struct bkey *k;
struct jset *j;
err = "cannot allocate memory for journal";
if (bch_journal_read(c, &journal))
goto err;
pr_debug("btree_journal_read() done");
err = "no journal entries found";
if (list_empty(&journal))
goto err;
j = &list_entry(journal.prev, struct journal_replay, list)->j;
err = "IO error reading priorities";
for_each_cache(ca, c, i)
prio_read(ca, j->prio_bucket[ca->sb.nr_this_dev]);
/*
* If prio_read() fails it'll call cache_set_error and we'll
* tear everything down right away, but if we perhaps checked
* sooner we could avoid journal replay.
*/
k = &j->btree_root;
err = "bad btree root";
if (__bch_btree_ptr_invalid(c, k))
goto err;
err = "error reading btree root";
c->root = bch_btree_node_get(c, NULL, k, j->btree_level, true, NULL);
if (IS_ERR_OR_NULL(c->root))
goto err;
list_del_init(&c->root->list);
rw_unlock(true, c->root);
err = uuid_read(c, j, &cl);
if (err)
goto err;
err = "error in recovery";
if (bch_btree_check(c))
goto err;
bch_journal_mark(c, &journal);
bch_initial_gc_finish(c);
pr_debug("btree_check() done");
/*
* bcache_journal_next() can't happen sooner, or
* btree_gc_finish() will give spurious errors about last_gc >
* gc_gen - this is a hack but oh well.
*/
bch_journal_next(&c->journal);
err = "error starting allocator thread";
for_each_cache(ca, c, i)
if (bch_cache_allocator_start(ca))
goto err;
/*
* First place it's safe to allocate: btree_check() and
* btree_gc_finish() have to run before we have buckets to
* allocate, and bch_bucket_alloc_set() might cause a journal
* entry to be written so bcache_journal_next() has to be called
* first.
*
* If the uuids were in the old format we have to rewrite them
* before the next journal entry is written:
*/
if (j->version < BCACHE_JSET_VERSION_UUID)
__uuid_write(c);
bch_journal_replay(c, &journal);
} else {
pr_notice("invalidating existing data");
for_each_cache(ca, c, i) {
unsigned j;
ca->sb.keys = clamp_t(int, ca->sb.nbuckets >> 7,
2, SB_JOURNAL_BUCKETS);
for (j = 0; j < ca->sb.keys; j++)
ca->sb.d[j] = ca->sb.first_bucket + j;
}
bch_initial_gc_finish(c);
err = "error starting allocator thread";
for_each_cache(ca, c, i)
if (bch_cache_allocator_start(ca))
goto err;
mutex_lock(&c->bucket_lock);
for_each_cache(ca, c, i)
bch_prio_write(ca);
mutex_unlock(&c->bucket_lock);
err = "cannot allocate new UUID bucket";
if (__uuid_write(c))
goto err;
err = "cannot allocate new btree root";
c->root = __bch_btree_node_alloc(c, NULL, 0, true, NULL);
if (IS_ERR_OR_NULL(c->root))
goto err;
mutex_lock(&c->root->write_lock);
bkey_copy_key(&c->root->key, &MAX_KEY);
bch_btree_node_write(c->root, &cl);
mutex_unlock(&c->root->write_lock);
bch_btree_set_root(c->root);
rw_unlock(true, c->root);
/*
* We don't want to write the first journal entry until
* everything is set up - fortunately journal entries won't be
* written until the SET_CACHE_SYNC() here:
*/
SET_CACHE_SYNC(&c->sb, true);
bch_journal_next(&c->journal);
bch_journal_meta(c, &cl);
}
err = "error starting gc thread";
if (bch_gc_thread_start(c))
goto err;
closure_sync(&cl);
c->sb.last_mount = get_seconds();
bcache_write_super(c);
list_for_each_entry_safe(dc, t, &uncached_devices, list)
bch_cached_dev_attach(dc, c);
flash_devs_run(c);
set_bit(CACHE_SET_RUNNING, &c->flags);
return;
err:
closure_sync(&cl);
/* XXX: test this, it's broken */
bch_cache_set_error(c, "%s", err);
}
static bool can_attach_cache(struct cache *ca, struct cache_set *c)
{
return ca->sb.block_size == c->sb.block_size &&
ca->sb.bucket_size == c->sb.bucket_size &&
ca->sb.nr_in_set == c->sb.nr_in_set;
}
static const char *register_cache_set(struct cache *ca)
{
char buf[12];
const char *err = "cannot allocate memory";
struct cache_set *c;
list_for_each_entry(c, &bch_cache_sets, list)
if (!memcmp(c->sb.set_uuid, ca->sb.set_uuid, 16)) {
if (c->cache[ca->sb.nr_this_dev])
return "duplicate cache set member";
if (!can_attach_cache(ca, c))
return "cache sb does not match set";
if (!CACHE_SYNC(&ca->sb))
SET_CACHE_SYNC(&c->sb, false);
goto found;
}
c = bch_cache_set_alloc(&ca->sb);
if (!c)
return err;
err = "error creating kobject";
if (kobject_add(&c->kobj, bcache_kobj, "%pU", c->sb.set_uuid) ||
kobject_add(&c->internal, &c->kobj, "internal"))
goto err;
if (bch_cache_accounting_add_kobjs(&c->accounting, &c->kobj))
goto err;
bch_debug_init_cache_set(c);
list_add(&c->list, &bch_cache_sets);
found:
sprintf(buf, "cache%i", ca->sb.nr_this_dev);
if (sysfs_create_link(&ca->kobj, &c->kobj, "set") ||
sysfs_create_link(&c->kobj, &ca->kobj, buf))
goto err;
if (ca->sb.seq > c->sb.seq) {
c->sb.version = ca->sb.version;
memcpy(c->sb.set_uuid, ca->sb.set_uuid, 16);
c->sb.flags = ca->sb.flags;
c->sb.seq = ca->sb.seq;
pr_debug("set version = %llu", c->sb.version);
}
kobject_get(&ca->kobj);
ca->set = c;
ca->set->cache[ca->sb.nr_this_dev] = ca;
c->cache_by_alloc[c->caches_loaded++] = ca;
if (c->caches_loaded == c->sb.nr_in_set)
run_cache_set(c);
return NULL;
err:
bch_cache_set_unregister(c);
return err;
}
/* Cache device */
void bch_cache_release(struct kobject *kobj)
{
struct cache *ca = container_of(kobj, struct cache, kobj);
unsigned i;
if (ca->set) {
BUG_ON(ca->set->cache[ca->sb.nr_this_dev] != ca);
ca->set->cache[ca->sb.nr_this_dev] = NULL;
}
free_pages((unsigned long) ca->disk_buckets, ilog2(bucket_pages(ca)));
kfree(ca->prio_buckets);
vfree(ca->buckets);
free_heap(&ca->heap);
free_fifo(&ca->free_inc);
for (i = 0; i < RESERVE_NR; i++)
free_fifo(&ca->free[i]);
if (ca->sb_bio.bi_inline_vecs[0].bv_page)
put_page(ca->sb_bio.bi_io_vec[0].bv_page);
if (!IS_ERR_OR_NULL(ca->bdev))
blkdev_put(ca->bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
kfree(ca);
module_put(THIS_MODULE);
}
static int cache_alloc(struct cache_sb *sb, struct cache *ca)
{
size_t free;
struct bucket *b;
__module_get(THIS_MODULE);
kobject_init(&ca->kobj, &bch_cache_ktype);
bio_init(&ca->journal.bio);
ca->journal.bio.bi_max_vecs = 8;
ca->journal.bio.bi_io_vec = ca->journal.bio.bi_inline_vecs;
free = roundup_pow_of_two(ca->sb.nbuckets) >> 10;
if (!init_fifo(&ca->free[RESERVE_BTREE], 8, GFP_KERNEL) ||
!init_fifo(&ca->free[RESERVE_PRIO], prio_buckets(ca), GFP_KERNEL) ||
!init_fifo(&ca->free[RESERVE_MOVINGGC], free, GFP_KERNEL) ||
!init_fifo(&ca->free[RESERVE_NONE], free, GFP_KERNEL) ||
!init_fifo(&ca->free_inc, free << 2, GFP_KERNEL) ||
!init_heap(&ca->heap, free << 3, GFP_KERNEL) ||
!(ca->buckets = vzalloc(sizeof(struct bucket) *
ca->sb.nbuckets)) ||
!(ca->prio_buckets = kzalloc(sizeof(uint64_t) * prio_buckets(ca) *
2, GFP_KERNEL)) ||
!(ca->disk_buckets = alloc_bucket_pages(GFP_KERNEL, ca)))
return -ENOMEM;
ca->prio_last_buckets = ca->prio_buckets + prio_buckets(ca);
for_each_bucket(b, ca)
atomic_set(&b->pin, 0);
return 0;
}
static int register_cache(struct cache_sb *sb, struct page *sb_page,
struct block_device *bdev, struct cache *ca)
{
char name[BDEVNAME_SIZE];
const char *err = NULL;
int ret = 0;
memcpy(&ca->sb, sb, sizeof(struct cache_sb));
ca->bdev = bdev;
ca->bdev->bd_holder = ca;
bio_init(&ca->sb_bio);
ca->sb_bio.bi_max_vecs = 1;
ca->sb_bio.bi_io_vec = ca->sb_bio.bi_inline_vecs;
ca->sb_bio.bi_io_vec[0].bv_page = sb_page;
get_page(sb_page);
if (blk_queue_discard(bdev_get_queue(ca->bdev)))
ca->discard = CACHE_DISCARD(&ca->sb);
ret = cache_alloc(sb, ca);
if (ret != 0)
goto err;
if (kobject_add(&ca->kobj, &part_to_dev(bdev->bd_part)->kobj, "bcache")) {
err = "error calling kobject_add";
ret = -ENOMEM;
goto out;
}
mutex_lock(&bch_register_lock);
err = register_cache_set(ca);
mutex_unlock(&bch_register_lock);
if (err) {
ret = -ENODEV;
goto out;
}
pr_info("registered cache device %s", bdevname(bdev, name));
out:
kobject_put(&ca->kobj);
err:
if (err)
pr_notice("error opening %s: %s", bdevname(bdev, name), err);
return ret;
}
/* Global interfaces/init */
static ssize_t register_bcache(struct kobject *, struct kobj_attribute *,
const char *, size_t);
kobj_attribute_write(register, register_bcache);
kobj_attribute_write(register_quiet, register_bcache);
static bool bch_is_open_backing(struct block_device *bdev) {
struct cache_set *c, *tc;
struct cached_dev *dc, *t;
list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
list_for_each_entry_safe(dc, t, &c->cached_devs, list)
if (dc->bdev == bdev)
return true;
list_for_each_entry_safe(dc, t, &uncached_devices, list)
if (dc->bdev == bdev)
return true;
return false;
}
static bool bch_is_open_cache(struct block_device *bdev) {
struct cache_set *c, *tc;
struct cache *ca;
unsigned i;
list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
for_each_cache(ca, c, i)
if (ca->bdev == bdev)
return true;
return false;
}
static bool bch_is_open(struct block_device *bdev) {
return bch_is_open_cache(bdev) || bch_is_open_backing(bdev);
}
static ssize_t register_bcache(struct kobject *k, struct kobj_attribute *attr,
const char *buffer, size_t size)
{
ssize_t ret = size;
const char *err = "cannot allocate memory";
char *path = NULL;
struct cache_sb *sb = NULL;
struct block_device *bdev = NULL;
struct page *sb_page = NULL;
if (!try_module_get(THIS_MODULE))
return -EBUSY;
if (!(path = kstrndup(buffer, size, GFP_KERNEL)) ||
!(sb = kmalloc(sizeof(struct cache_sb), GFP_KERNEL)))
goto err;
err = "failed to open device";
bdev = blkdev_get_by_path(strim(path),
FMODE_READ|FMODE_WRITE|FMODE_EXCL,
sb);
if (IS_ERR(bdev)) {
if (bdev == ERR_PTR(-EBUSY)) {
bdev = lookup_bdev(strim(path));
mutex_lock(&bch_register_lock);
if (!IS_ERR(bdev) && bch_is_open(bdev))
err = "device already registered";
else
err = "device busy";
mutex_unlock(&bch_register_lock);
if (attr == &ksysfs_register_quiet)
goto out;
}
goto err;
}
err = "failed to set blocksize";
if (set_blocksize(bdev, 4096))
goto err_close;
err = read_super(sb, bdev, &sb_page);
if (err)
goto err_close;
if (SB_IS_BDEV(sb)) {
struct cached_dev *dc = kzalloc(sizeof(*dc), GFP_KERNEL);
if (!dc)
goto err_close;
mutex_lock(&bch_register_lock);
register_bdev(sb, sb_page, bdev, dc);
mutex_unlock(&bch_register_lock);
} else {
struct cache *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
if (!ca)
goto err_close;
if (register_cache(sb, sb_page, bdev, ca) != 0)
goto err_close;
}
out:
if (sb_page)
put_page(sb_page);
kfree(sb);
kfree(path);
module_put(THIS_MODULE);
return ret;
err_close:
blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
err:
pr_info("error opening %s: %s", path, err);
ret = -EINVAL;
goto out;
}
static int bcache_reboot(struct notifier_block *n, unsigned long code, void *x)
{
if (code == SYS_DOWN ||
code == SYS_HALT ||
code == SYS_POWER_OFF) {
DEFINE_WAIT(wait);
unsigned long start = jiffies;
bool stopped = false;
struct cache_set *c, *tc;
struct cached_dev *dc, *tdc;
mutex_lock(&bch_register_lock);
if (list_empty(&bch_cache_sets) &&
list_empty(&uncached_devices))
goto out;
pr_info("Stopping all devices:");
list_for_each_entry_safe(c, tc, &bch_cache_sets, list)
bch_cache_set_stop(c);
list_for_each_entry_safe(dc, tdc, &uncached_devices, list)
bcache_device_stop(&dc->disk);
/* What's a condition variable? */
while (1) {
long timeout = start + 2 * HZ - jiffies;
stopped = list_empty(&bch_cache_sets) &&
list_empty(&uncached_devices);
if (timeout < 0 || stopped)
break;
prepare_to_wait(&unregister_wait, &wait,
TASK_UNINTERRUPTIBLE);
mutex_unlock(&bch_register_lock);
schedule_timeout(timeout);
mutex_lock(&bch_register_lock);
}
finish_wait(&unregister_wait, &wait);
if (stopped)
pr_info("All devices stopped");
else
pr_notice("Timeout waiting for devices to be closed");
out:
mutex_unlock(&bch_register_lock);
}
return NOTIFY_DONE;
}
static struct notifier_block reboot = {
.notifier_call = bcache_reboot,
.priority = INT_MAX, /* before any real devices */
};
static void bcache_exit(void)
{
bch_debug_exit();
bch_request_exit();
if (bcache_kobj)
kobject_put(bcache_kobj);
if (bcache_wq)
destroy_workqueue(bcache_wq);
if (bcache_major)
unregister_blkdev(bcache_major, "bcache");
unregister_reboot_notifier(&reboot);
}
static int __init bcache_init(void)
{
static const struct attribute *files[] = {
&ksysfs_register.attr,
&ksysfs_register_quiet.attr,
NULL
};
mutex_init(&bch_register_lock);
init_waitqueue_head(&unregister_wait);
register_reboot_notifier(&reboot);
closure_debug_init();
bcache_major = register_blkdev(0, "bcache");
if (bcache_major < 0) {
unregister_reboot_notifier(&reboot);
return bcache_major;
}
if (!(bcache_wq = create_workqueue("bcache")) ||
!(bcache_kobj = kobject_create_and_add("bcache", fs_kobj)) ||
sysfs_create_files(bcache_kobj, files) ||
bch_request_init() ||
bch_debug_init(bcache_kobj))
goto err;
return 0;
err:
bcache_exit();
return -ENOMEM;
}
module_exit(bcache_exit);
module_init(bcache_init);
| gpl-2.0 |
garrikus/o3_linux | drivers/char/agp/amd64-agp.c | 56 | 20654 | /*
* Copyright 2001-2003 SuSE Labs.
* Distributed under the GNU public license, v2.
*
* This is a GART driver for the AMD Opteron/Athlon64 on-CPU northbridge.
* It also includes support for the AMD 8151 AGP bridge,
* although it doesn't actually do much, as all the real
* work is done in the northbridge(s).
*/
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/agp_backend.h>
#include <linux/mmzone.h>
#include <asm/page.h> /* PAGE_SIZE */
#include <asm/e820.h>
#include <asm/amd_nb.h>
#include <asm/gart.h>
#include "agp.h"
/* NVIDIA K8 registers */
#define NVIDIA_X86_64_0_APBASE 0x10
#define NVIDIA_X86_64_1_APBASE1 0x50
#define NVIDIA_X86_64_1_APLIMIT1 0x54
#define NVIDIA_X86_64_1_APSIZE 0xa8
#define NVIDIA_X86_64_1_APBASE2 0xd8
#define NVIDIA_X86_64_1_APLIMIT2 0xdc
/* ULi K8 registers */
#define ULI_X86_64_BASE_ADDR 0x10
#define ULI_X86_64_HTT_FEA_REG 0x50
#define ULI_X86_64_ENU_SCR_REG 0x54
static struct resource *aperture_resource;
static int __initdata agp_try_unsupported = 1;
static int agp_bridges_found;
static void amd64_tlbflush(struct agp_memory *temp)
{
k8_flush_garts();
}
static int amd64_insert_memory(struct agp_memory *mem, off_t pg_start, int type)
{
int i, j, num_entries;
long long tmp;
int mask_type;
struct agp_bridge_data *bridge = mem->bridge;
u32 pte;
num_entries = agp_num_entries();
if (type != mem->type)
return -EINVAL;
mask_type = bridge->driver->agp_type_to_mask_type(bridge, type);
if (mask_type != 0)
return -EINVAL;
/* Make sure we can fit the range in the gatt table. */
/* FIXME: could wrap */
if (((unsigned long)pg_start + mem->page_count) > num_entries)
return -EINVAL;
j = pg_start;
/* gatt table should be empty. */
while (j < (pg_start + mem->page_count)) {
if (!PGE_EMPTY(agp_bridge, readl(agp_bridge->gatt_table+j)))
return -EBUSY;
j++;
}
if (!mem->is_flushed) {
global_cache_flush();
mem->is_flushed = true;
}
for (i = 0, j = pg_start; i < mem->page_count; i++, j++) {
tmp = agp_bridge->driver->mask_memory(agp_bridge,
page_to_phys(mem->pages[i]),
mask_type);
BUG_ON(tmp & 0xffffff0000000ffcULL);
pte = (tmp & 0x000000ff00000000ULL) >> 28;
pte |=(tmp & 0x00000000fffff000ULL);
pte |= GPTE_VALID | GPTE_COHERENT;
writel(pte, agp_bridge->gatt_table+j);
readl(agp_bridge->gatt_table+j); /* PCI Posting. */
}
amd64_tlbflush(mem);
return 0;
}
/*
* This hack alters the order element according
* to the size of a long. It sucks. I totally disown this, even
* though it does appear to work for the most part.
*/
static struct aper_size_info_32 amd64_aperture_sizes[7] =
{
{32, 8192, 3+(sizeof(long)/8), 0 },
{64, 16384, 4+(sizeof(long)/8), 1<<1 },
{128, 32768, 5+(sizeof(long)/8), 1<<2 },
{256, 65536, 6+(sizeof(long)/8), 1<<1 | 1<<2 },
{512, 131072, 7+(sizeof(long)/8), 1<<3 },
{1024, 262144, 8+(sizeof(long)/8), 1<<1 | 1<<3},
{2048, 524288, 9+(sizeof(long)/8), 1<<2 | 1<<3}
};
/*
* Get the current Aperture size from the x86-64.
* Note, that there may be multiple x86-64's, but we just return
* the value from the first one we find. The set_size functions
* keep the rest coherent anyway. Or at least should do.
*/
static int amd64_fetch_size(void)
{
struct pci_dev *dev;
int i;
u32 temp;
struct aper_size_info_32 *values;
dev = k8_northbridges.nb_misc[0];
if (dev==NULL)
return 0;
pci_read_config_dword(dev, AMD64_GARTAPERTURECTL, &temp);
temp = (temp & 0xe);
values = A_SIZE_32(amd64_aperture_sizes);
for (i = 0; i < agp_bridge->driver->num_aperture_sizes; i++) {
if (temp == values[i].size_value) {
agp_bridge->previous_size =
agp_bridge->current_size = (void *) (values + i);
agp_bridge->aperture_size_idx = i;
return values[i].size;
}
}
return 0;
}
/*
* In a multiprocessor x86-64 system, this function gets
* called once for each CPU.
*/
static u64 amd64_configure(struct pci_dev *hammer, u64 gatt_table)
{
u64 aperturebase;
u32 tmp;
u64 aper_base;
/* Address to map to */
pci_read_config_dword(hammer, AMD64_GARTAPERTUREBASE, &tmp);
aperturebase = tmp << 25;
aper_base = (aperturebase & PCI_BASE_ADDRESS_MEM_MASK);
enable_gart_translation(hammer, gatt_table);
return aper_base;
}
static const struct aper_size_info_32 amd_8151_sizes[7] =
{
{2048, 524288, 9, 0x00000000 }, /* 0 0 0 0 0 0 */
{1024, 262144, 8, 0x00000400 }, /* 1 0 0 0 0 0 */
{512, 131072, 7, 0x00000600 }, /* 1 1 0 0 0 0 */
{256, 65536, 6, 0x00000700 }, /* 1 1 1 0 0 0 */
{128, 32768, 5, 0x00000720 }, /* 1 1 1 1 0 0 */
{64, 16384, 4, 0x00000730 }, /* 1 1 1 1 1 0 */
{32, 8192, 3, 0x00000738 } /* 1 1 1 1 1 1 */
};
static int amd_8151_configure(void)
{
unsigned long gatt_bus = virt_to_phys(agp_bridge->gatt_table_real);
int i;
if (!k8_northbridges.gart_supported)
return 0;
/* Configure AGP regs in each x86-64 host bridge. */
for (i = 0; i < k8_northbridges.num; i++) {
agp_bridge->gart_bus_addr =
amd64_configure(k8_northbridges.nb_misc[i],
gatt_bus);
}
k8_flush_garts();
return 0;
}
static void amd64_cleanup(void)
{
u32 tmp;
int i;
if (!k8_northbridges.gart_supported)
return;
for (i = 0; i < k8_northbridges.num; i++) {
struct pci_dev *dev = k8_northbridges.nb_misc[i];
/* disable gart translation */
pci_read_config_dword(dev, AMD64_GARTAPERTURECTL, &tmp);
tmp &= ~GARTEN;
pci_write_config_dword(dev, AMD64_GARTAPERTURECTL, tmp);
}
}
static const struct agp_bridge_driver amd_8151_driver = {
.owner = THIS_MODULE,
.aperture_sizes = amd_8151_sizes,
.size_type = U32_APER_SIZE,
.num_aperture_sizes = 7,
.needs_scratch_page = true,
.configure = amd_8151_configure,
.fetch_size = amd64_fetch_size,
.cleanup = amd64_cleanup,
.tlb_flush = amd64_tlbflush,
.mask_memory = agp_generic_mask_memory,
.masks = NULL,
.agp_enable = agp_generic_enable,
.cache_flush = global_cache_flush,
.create_gatt_table = agp_generic_create_gatt_table,
.free_gatt_table = agp_generic_free_gatt_table,
.insert_memory = amd64_insert_memory,
.remove_memory = agp_generic_remove_memory,
.alloc_by_type = agp_generic_alloc_by_type,
.free_by_type = agp_generic_free_by_type,
.agp_alloc_page = agp_generic_alloc_page,
.agp_alloc_pages = agp_generic_alloc_pages,
.agp_destroy_page = agp_generic_destroy_page,
.agp_destroy_pages = agp_generic_destroy_pages,
.agp_type_to_mask_type = agp_generic_type_to_mask_type,
};
/* Some basic sanity checks for the aperture. */
static int __devinit agp_aperture_valid(u64 aper, u32 size)
{
if (!aperture_valid(aper, size, 32*1024*1024))
return 0;
/* Request the Aperture. This catches cases when someone else
already put a mapping in there - happens with some very broken BIOS
Maybe better to use pci_assign_resource/pci_enable_device instead
trusting the bridges? */
if (!aperture_resource &&
!(aperture_resource = request_mem_region(aper, size, "aperture"))) {
printk(KERN_ERR PFX "Aperture conflicts with PCI mapping.\n");
return 0;
}
return 1;
}
/*
* W*s centric BIOS sometimes only set up the aperture in the AGP
* bridge, not the northbridge. On AMD64 this is handled early
* in aperture.c, but when IOMMU is not enabled or we run
* on a 32bit kernel this needs to be redone.
* Unfortunately it is impossible to fix the aperture here because it's too late
* to allocate that much memory. But at least error out cleanly instead of
* crashing.
*/
static __devinit int fix_northbridge(struct pci_dev *nb, struct pci_dev *agp,
u16 cap)
{
u32 aper_low, aper_hi;
u64 aper, nb_aper;
int order = 0;
u32 nb_order, nb_base;
u16 apsize;
pci_read_config_dword(nb, AMD64_GARTAPERTURECTL, &nb_order);
nb_order = (nb_order >> 1) & 7;
pci_read_config_dword(nb, AMD64_GARTAPERTUREBASE, &nb_base);
nb_aper = nb_base << 25;
/* Northbridge seems to contain crap. Try the AGP bridge. */
pci_read_config_word(agp, cap+0x14, &apsize);
if (apsize == 0xffff) {
if (agp_aperture_valid(nb_aper, (32*1024*1024)<<nb_order))
return 0;
return -1;
}
apsize &= 0xfff;
/* Some BIOS use weird encodings not in the AGPv3 table. */
if (apsize & 0xff)
apsize |= 0xf00;
order = 7 - hweight16(apsize);
pci_read_config_dword(agp, 0x10, &aper_low);
pci_read_config_dword(agp, 0x14, &aper_hi);
aper = (aper_low & ~((1<<22)-1)) | ((u64)aper_hi << 32);
/*
* On some sick chips APSIZE is 0. This means it wants 4G
* so let double check that order, and lets trust the AMD NB settings
*/
if (order >=0 && aper + (32ULL<<(20 + order)) > 0x100000000ULL) {
dev_info(&agp->dev, "aperture size %u MB is not right, using settings from NB\n",
32 << order);
order = nb_order;
}
if (nb_order >= order) {
if (agp_aperture_valid(nb_aper, (32*1024*1024)<<nb_order))
return 0;
}
dev_info(&agp->dev, "aperture from AGP @ %Lx size %u MB\n",
aper, 32 << order);
if (order < 0 || !agp_aperture_valid(aper, (32*1024*1024)<<order))
return -1;
gart_set_size_and_enable(nb, order);
pci_write_config_dword(nb, AMD64_GARTAPERTUREBASE, aper >> 25);
return 0;
}
static __devinit int cache_nbs(struct pci_dev *pdev, u32 cap_ptr)
{
int i;
if (cache_k8_northbridges() < 0)
return -ENODEV;
if (!k8_northbridges.gart_supported)
return -ENODEV;
i = 0;
for (i = 0; i < k8_northbridges.num; i++) {
struct pci_dev *dev = k8_northbridges.nb_misc[i];
if (fix_northbridge(dev, pdev, cap_ptr) < 0) {
dev_err(&dev->dev, "no usable aperture found\n");
#ifdef __x86_64__
/* should port this to i386 */
dev_err(&dev->dev, "consider rebooting with iommu=memaper=2 to get a good aperture\n");
#endif
return -1;
}
}
return 0;
}
/* Handle AMD 8151 quirks */
static void __devinit amd8151_init(struct pci_dev *pdev, struct agp_bridge_data *bridge)
{
char *revstring;
switch (pdev->revision) {
case 0x01: revstring="A0"; break;
case 0x02: revstring="A1"; break;
case 0x11: revstring="B0"; break;
case 0x12: revstring="B1"; break;
case 0x13: revstring="B2"; break;
case 0x14: revstring="B3"; break;
default: revstring="??"; break;
}
dev_info(&pdev->dev, "AMD 8151 AGP Bridge rev %s\n", revstring);
/*
* Work around errata.
* Chips before B2 stepping incorrectly reporting v3.5
*/
if (pdev->revision < 0x13) {
dev_info(&pdev->dev, "correcting AGP revision (reports 3.5, is really 3.0)\n");
bridge->major_version = 3;
bridge->minor_version = 0;
}
}
static const struct aper_size_info_32 uli_sizes[7] =
{
{256, 65536, 6, 10},
{128, 32768, 5, 9},
{64, 16384, 4, 8},
{32, 8192, 3, 7},
{16, 4096, 2, 6},
{8, 2048, 1, 4},
{4, 1024, 0, 3}
};
static int __devinit uli_agp_init(struct pci_dev *pdev)
{
u32 httfea,baseaddr,enuscr;
struct pci_dev *dev1;
int i, ret;
unsigned size = amd64_fetch_size();
dev_info(&pdev->dev, "setting up ULi AGP\n");
dev1 = pci_get_slot (pdev->bus,PCI_DEVFN(0,0));
if (dev1 == NULL) {
dev_info(&pdev->dev, "can't find ULi secondary device\n");
return -ENODEV;
}
for (i = 0; i < ARRAY_SIZE(uli_sizes); i++)
if (uli_sizes[i].size == size)
break;
if (i == ARRAY_SIZE(uli_sizes)) {
dev_info(&pdev->dev, "no ULi size found for %d\n", size);
ret = -ENODEV;
goto put;
}
/* shadow x86-64 registers into ULi registers */
pci_read_config_dword (k8_northbridges.nb_misc[0], AMD64_GARTAPERTUREBASE,
&httfea);
/* if x86-64 aperture base is beyond 4G, exit here */
if ((httfea & 0x7fff) >> (32 - 25)) {
ret = -ENODEV;
goto put;
}
httfea = (httfea& 0x7fff) << 25;
pci_read_config_dword(pdev, ULI_X86_64_BASE_ADDR, &baseaddr);
baseaddr&= ~PCI_BASE_ADDRESS_MEM_MASK;
baseaddr|= httfea;
pci_write_config_dword(pdev, ULI_X86_64_BASE_ADDR, baseaddr);
enuscr= httfea+ (size * 1024 * 1024) - 1;
pci_write_config_dword(dev1, ULI_X86_64_HTT_FEA_REG, httfea);
pci_write_config_dword(dev1, ULI_X86_64_ENU_SCR_REG, enuscr);
ret = 0;
put:
pci_dev_put(dev1);
return ret;
}
static const struct aper_size_info_32 nforce3_sizes[5] =
{
{512, 131072, 7, 0x00000000 },
{256, 65536, 6, 0x00000008 },
{128, 32768, 5, 0x0000000C },
{64, 16384, 4, 0x0000000E },
{32, 8192, 3, 0x0000000F }
};
/* Handle shadow device of the Nvidia NForce3 */
/* CHECK-ME original 2.4 version set up some IORRs. Check if that is needed. */
static int nforce3_agp_init(struct pci_dev *pdev)
{
u32 tmp, apbase, apbar, aplimit;
struct pci_dev *dev1;
int i, ret;
unsigned size = amd64_fetch_size();
dev_info(&pdev->dev, "setting up Nforce3 AGP\n");
dev1 = pci_get_slot(pdev->bus, PCI_DEVFN(11, 0));
if (dev1 == NULL) {
dev_info(&pdev->dev, "can't find Nforce3 secondary device\n");
return -ENODEV;
}
for (i = 0; i < ARRAY_SIZE(nforce3_sizes); i++)
if (nforce3_sizes[i].size == size)
break;
if (i == ARRAY_SIZE(nforce3_sizes)) {
dev_info(&pdev->dev, "no NForce3 size found for %d\n", size);
ret = -ENODEV;
goto put;
}
pci_read_config_dword(dev1, NVIDIA_X86_64_1_APSIZE, &tmp);
tmp &= ~(0xf);
tmp |= nforce3_sizes[i].size_value;
pci_write_config_dword(dev1, NVIDIA_X86_64_1_APSIZE, tmp);
/* shadow x86-64 registers into NVIDIA registers */
pci_read_config_dword (k8_northbridges.nb_misc[0], AMD64_GARTAPERTUREBASE,
&apbase);
/* if x86-64 aperture base is beyond 4G, exit here */
if ( (apbase & 0x7fff) >> (32 - 25) ) {
dev_info(&pdev->dev, "aperture base > 4G\n");
ret = -ENODEV;
goto put;
}
apbase = (apbase & 0x7fff) << 25;
pci_read_config_dword(pdev, NVIDIA_X86_64_0_APBASE, &apbar);
apbar &= ~PCI_BASE_ADDRESS_MEM_MASK;
apbar |= apbase;
pci_write_config_dword(pdev, NVIDIA_X86_64_0_APBASE, apbar);
aplimit = apbase + (size * 1024 * 1024) - 1;
pci_write_config_dword(dev1, NVIDIA_X86_64_1_APBASE1, apbase);
pci_write_config_dword(dev1, NVIDIA_X86_64_1_APLIMIT1, aplimit);
pci_write_config_dword(dev1, NVIDIA_X86_64_1_APBASE2, apbase);
pci_write_config_dword(dev1, NVIDIA_X86_64_1_APLIMIT2, aplimit);
ret = 0;
put:
pci_dev_put(dev1);
return ret;
}
static int __devinit agp_amd64_probe(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct agp_bridge_data *bridge;
u8 cap_ptr;
int err;
/* The Highlander principle */
if (agp_bridges_found)
return -ENODEV;
cap_ptr = pci_find_capability(pdev, PCI_CAP_ID_AGP);
if (!cap_ptr)
return -ENODEV;
/* Could check for AGPv3 here */
bridge = agp_alloc_bridge();
if (!bridge)
return -ENOMEM;
if (pdev->vendor == PCI_VENDOR_ID_AMD &&
pdev->device == PCI_DEVICE_ID_AMD_8151_0) {
amd8151_init(pdev, bridge);
} else {
dev_info(&pdev->dev, "AGP bridge [%04x/%04x]\n",
pdev->vendor, pdev->device);
}
bridge->driver = &amd_8151_driver;
bridge->dev = pdev;
bridge->capndx = cap_ptr;
/* Fill in the mode register */
pci_read_config_dword(pdev, bridge->capndx+PCI_AGP_STATUS, &bridge->mode);
if (cache_nbs(pdev, cap_ptr) == -1) {
agp_put_bridge(bridge);
return -ENODEV;
}
if (pdev->vendor == PCI_VENDOR_ID_NVIDIA) {
int ret = nforce3_agp_init(pdev);
if (ret) {
agp_put_bridge(bridge);
return ret;
}
}
if (pdev->vendor == PCI_VENDOR_ID_AL) {
int ret = uli_agp_init(pdev);
if (ret) {
agp_put_bridge(bridge);
return ret;
}
}
pci_set_drvdata(pdev, bridge);
err = agp_add_bridge(bridge);
if (err < 0)
return err;
agp_bridges_found++;
return 0;
}
static void __devexit agp_amd64_remove(struct pci_dev *pdev)
{
struct agp_bridge_data *bridge = pci_get_drvdata(pdev);
release_mem_region(virt_to_phys(bridge->gatt_table_real),
amd64_aperture_sizes[bridge->aperture_size_idx].size);
agp_remove_bridge(bridge);
agp_put_bridge(bridge);
agp_bridges_found--;
}
#ifdef CONFIG_PM
static int agp_amd64_suspend(struct pci_dev *pdev, pm_message_t state)
{
pci_save_state(pdev);
pci_set_power_state(pdev, pci_choose_state(pdev, state));
return 0;
}
static int agp_amd64_resume(struct pci_dev *pdev)
{
pci_set_power_state(pdev, PCI_D0);
pci_restore_state(pdev);
if (pdev->vendor == PCI_VENDOR_ID_NVIDIA)
nforce3_agp_init(pdev);
return amd_8151_configure();
}
#endif /* CONFIG_PM */
static struct pci_device_id agp_amd64_pci_table[] = {
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_AMD,
.device = PCI_DEVICE_ID_AMD_8151_0,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
/* ULi M1689 */
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_AL,
.device = PCI_DEVICE_ID_AL_M1689,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
/* VIA K8T800Pro */
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_VIA,
.device = PCI_DEVICE_ID_VIA_K8T800PRO_0,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
/* VIA K8T800 */
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_VIA,
.device = PCI_DEVICE_ID_VIA_8385_0,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
/* VIA K8M800 / K8N800 */
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_VIA,
.device = PCI_DEVICE_ID_VIA_8380_0,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
/* VIA K8M890 / K8N890 */
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_VIA,
.device = PCI_DEVICE_ID_VIA_VT3336,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
/* VIA K8T890 */
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_VIA,
.device = PCI_DEVICE_ID_VIA_3238_0,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
/* VIA K8T800/K8M800/K8N800 */
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_VIA,
.device = PCI_DEVICE_ID_VIA_838X_1,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
/* NForce3 */
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_NVIDIA,
.device = PCI_DEVICE_ID_NVIDIA_NFORCE3,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_NVIDIA,
.device = PCI_DEVICE_ID_NVIDIA_NFORCE3S,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
/* SIS 755 */
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_SI,
.device = PCI_DEVICE_ID_SI_755,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
/* SIS 760 */
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_SI,
.device = PCI_DEVICE_ID_SI_760,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
/* ALI/ULI M1695 */
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_AL,
.device = 0x1695,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{ }
};
MODULE_DEVICE_TABLE(pci, agp_amd64_pci_table);
static DEFINE_PCI_DEVICE_TABLE(agp_amd64_pci_promisc_table) = {
{ PCI_DEVICE_CLASS(0, 0) },
{ }
};
static struct pci_driver agp_amd64_pci_driver = {
.name = "agpgart-amd64",
.id_table = agp_amd64_pci_table,
.probe = agp_amd64_probe,
.remove = agp_amd64_remove,
#ifdef CONFIG_PM
.suspend = agp_amd64_suspend,
.resume = agp_amd64_resume,
#endif
};
/* Not static due to IOMMU code calling it early. */
int __init agp_amd64_init(void)
{
int err = 0;
if (agp_off)
return -EINVAL;
err = pci_register_driver(&agp_amd64_pci_driver);
if (err < 0)
return err;
if (agp_bridges_found == 0) {
if (!agp_try_unsupported && !agp_try_unsupported_boot) {
printk(KERN_INFO PFX "No supported AGP bridge found.\n");
#ifdef MODULE
printk(KERN_INFO PFX "You can try agp_try_unsupported=1\n");
#else
printk(KERN_INFO PFX "You can boot with agp=try_unsupported\n");
#endif
return -ENODEV;
}
/* First check that we have at least one AMD64 NB */
if (!pci_dev_present(k8_nb_ids))
return -ENODEV;
/* Look for any AGP bridge */
agp_amd64_pci_driver.id_table = agp_amd64_pci_promisc_table;
err = driver_attach(&agp_amd64_pci_driver.driver);
if (err == 0 && agp_bridges_found == 0)
err = -ENODEV;
}
return err;
}
static int __init agp_amd64_mod_init(void)
{
#ifndef MODULE
if (gart_iommu_aperture)
return agp_bridges_found ? 0 : -ENODEV;
#endif
return agp_amd64_init();
}
static void __exit agp_amd64_cleanup(void)
{
#ifndef MODULE
if (gart_iommu_aperture)
return;
#endif
if (aperture_resource)
release_resource(aperture_resource);
pci_unregister_driver(&agp_amd64_pci_driver);
}
module_init(agp_amd64_mod_init);
module_exit(agp_amd64_cleanup);
MODULE_AUTHOR("Dave Jones <davej@redhat.com>, Andi Kleen");
module_param(agp_try_unsupported, bool, 0);
MODULE_LICENSE("GPL");
| gpl-2.0 |
zengxiange/limbo-android | jni/qemu/hw/omap2.c | 56 | 88290 | /*
* TI OMAP processors emulation.
*
* Copyright (C) 2007-2008 Nokia Corporation
* Written by Andrzej Zaborowski <andrew@openedhand.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 or
* (at your option) version 3 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, see <http://www.gnu.org/licenses/>.
*/
#include "blockdev.h"
#include "hw.h"
#include "arm-misc.h"
#include "omap.h"
#include "sysemu.h"
#include "qemu-timer.h"
#include "qemu-char.h"
#include "flash.h"
#include "soc_dma.h"
#include "sysbus.h"
#include "audio/audio.h"
/* Enhanced Audio Controller (CODEC only) */
struct omap_eac_s {
qemu_irq irq;
MemoryRegion iomem;
uint16_t sysconfig;
uint8_t config[4];
uint8_t control;
uint8_t address;
uint16_t data;
uint8_t vtol;
uint8_t vtsl;
uint16_t mixer;
uint16_t gain[4];
uint8_t att;
uint16_t max[7];
struct {
qemu_irq txdrq;
qemu_irq rxdrq;
uint32_t (*txrx)(void *opaque, uint32_t, int);
void *opaque;
#define EAC_BUF_LEN 1024
uint32_t rxbuf[EAC_BUF_LEN];
int rxoff;
int rxlen;
int rxavail;
uint32_t txbuf[EAC_BUF_LEN];
int txlen;
int txavail;
int enable;
int rate;
uint16_t config[4];
/* These need to be moved to the actual codec */
QEMUSoundCard card;
SWVoiceIn *in_voice;
SWVoiceOut *out_voice;
int hw_enable;
} codec;
struct {
uint8_t control;
uint16_t config;
} modem, bt;
};
static inline void omap_eac_interrupt_update(struct omap_eac_s *s)
{
qemu_set_irq(s->irq, (s->codec.config[1] >> 14) & 1); /* AURDI */
}
static inline void omap_eac_in_dmarequest_update(struct omap_eac_s *s)
{
qemu_set_irq(s->codec.rxdrq, (s->codec.rxavail || s->codec.rxlen) &&
((s->codec.config[1] >> 12) & 1)); /* DMAREN */
}
static inline void omap_eac_out_dmarequest_update(struct omap_eac_s *s)
{
qemu_set_irq(s->codec.txdrq, s->codec.txlen < s->codec.txavail &&
((s->codec.config[1] >> 11) & 1)); /* DMAWEN */
}
static inline void omap_eac_in_refill(struct omap_eac_s *s)
{
int left = MIN(EAC_BUF_LEN - s->codec.rxlen, s->codec.rxavail) << 2;
int start = ((s->codec.rxoff + s->codec.rxlen) & (EAC_BUF_LEN - 1)) << 2;
int leftwrap = MIN(left, (EAC_BUF_LEN << 2) - start);
int recv = 1;
uint8_t *buf = (uint8_t *) s->codec.rxbuf + start;
left -= leftwrap;
start = 0;
while (leftwrap && (recv = AUD_read(s->codec.in_voice, buf + start,
leftwrap)) > 0) { /* Be defensive */
start += recv;
leftwrap -= recv;
}
if (recv <= 0)
s->codec.rxavail = 0;
else
s->codec.rxavail -= start >> 2;
s->codec.rxlen += start >> 2;
if (recv > 0 && left > 0) {
start = 0;
while (left && (recv = AUD_read(s->codec.in_voice,
(uint8_t *) s->codec.rxbuf + start,
left)) > 0) { /* Be defensive */
start += recv;
left -= recv;
}
if (recv <= 0)
s->codec.rxavail = 0;
else
s->codec.rxavail -= start >> 2;
s->codec.rxlen += start >> 2;
}
}
static inline void omap_eac_out_empty(struct omap_eac_s *s)
{
int left = s->codec.txlen << 2;
int start = 0;
int sent = 1;
while (left && (sent = AUD_write(s->codec.out_voice,
(uint8_t *) s->codec.txbuf + start,
left)) > 0) { /* Be defensive */
start += sent;
left -= sent;
}
if (!sent) {
s->codec.txavail = 0;
omap_eac_out_dmarequest_update(s);
}
if (start)
s->codec.txlen = 0;
}
static void omap_eac_in_cb(void *opaque, int avail_b)
{
struct omap_eac_s *s = (struct omap_eac_s *) opaque;
s->codec.rxavail = avail_b >> 2;
omap_eac_in_refill(s);
/* TODO: possibly discard current buffer if overrun */
omap_eac_in_dmarequest_update(s);
}
static void omap_eac_out_cb(void *opaque, int free_b)
{
struct omap_eac_s *s = (struct omap_eac_s *) opaque;
s->codec.txavail = free_b >> 2;
if (s->codec.txlen)
omap_eac_out_empty(s);
else
omap_eac_out_dmarequest_update(s);
}
static void omap_eac_enable_update(struct omap_eac_s *s)
{
s->codec.enable = !(s->codec.config[1] & 1) && /* EACPWD */
(s->codec.config[1] & 2) && /* AUDEN */
s->codec.hw_enable;
}
static const int omap_eac_fsint[4] = {
8000,
11025,
22050,
44100,
};
static const int omap_eac_fsint2[8] = {
8000,
11025,
22050,
44100,
48000,
0, 0, 0,
};
static const int omap_eac_fsint3[16] = {
8000,
11025,
16000,
22050,
24000,
32000,
44100,
48000,
0, 0, 0, 0, 0, 0, 0, 0,
};
static void omap_eac_rate_update(struct omap_eac_s *s)
{
int fsint[3];
fsint[2] = (s->codec.config[3] >> 9) & 0xf;
fsint[1] = (s->codec.config[2] >> 0) & 0x7;
fsint[0] = (s->codec.config[0] >> 6) & 0x3;
if (fsint[2] < 0xf)
s->codec.rate = omap_eac_fsint3[fsint[2]];
else if (fsint[1] < 0x7)
s->codec.rate = omap_eac_fsint2[fsint[1]];
else
s->codec.rate = omap_eac_fsint[fsint[0]];
}
static void omap_eac_volume_update(struct omap_eac_s *s)
{
/* TODO */
}
static void omap_eac_format_update(struct omap_eac_s *s)
{
struct audsettings fmt;
/* The hardware buffers at most one sample */
if (s->codec.rxlen)
s->codec.rxlen = 1;
if (s->codec.in_voice) {
AUD_set_active_in(s->codec.in_voice, 0);
AUD_close_in(&s->codec.card, s->codec.in_voice);
s->codec.in_voice = NULL;
}
if (s->codec.out_voice) {
omap_eac_out_empty(s);
AUD_set_active_out(s->codec.out_voice, 0);
AUD_close_out(&s->codec.card, s->codec.out_voice);
s->codec.out_voice = NULL;
s->codec.txavail = 0;
}
/* Discard what couldn't be written */
s->codec.txlen = 0;
omap_eac_enable_update(s);
if (!s->codec.enable)
return;
omap_eac_rate_update(s);
fmt.endianness = ((s->codec.config[0] >> 8) & 1); /* LI_BI */
fmt.nchannels = ((s->codec.config[0] >> 10) & 1) ? 2 : 1; /* MN_ST */
fmt.freq = s->codec.rate;
/* TODO: signedness possibly depends on the CODEC hardware - or
* does I2S specify it? */
/* All register writes are 16 bits so we we store 16-bit samples
* in the buffers regardless of AGCFR[B8_16] value. */
fmt.fmt = AUD_FMT_U16;
s->codec.in_voice = AUD_open_in(&s->codec.card, s->codec.in_voice,
"eac.codec.in", s, omap_eac_in_cb, &fmt);
s->codec.out_voice = AUD_open_out(&s->codec.card, s->codec.out_voice,
"eac.codec.out", s, omap_eac_out_cb, &fmt);
omap_eac_volume_update(s);
AUD_set_active_in(s->codec.in_voice, 1);
AUD_set_active_out(s->codec.out_voice, 1);
}
static void omap_eac_reset(struct omap_eac_s *s)
{
s->sysconfig = 0;
s->config[0] = 0x0c;
s->config[1] = 0x09;
s->config[2] = 0xab;
s->config[3] = 0x03;
s->control = 0x00;
s->address = 0x00;
s->data = 0x0000;
s->vtol = 0x00;
s->vtsl = 0x00;
s->mixer = 0x0000;
s->gain[0] = 0xe7e7;
s->gain[1] = 0x6767;
s->gain[2] = 0x6767;
s->gain[3] = 0x6767;
s->att = 0xce;
s->max[0] = 0;
s->max[1] = 0;
s->max[2] = 0;
s->max[3] = 0;
s->max[4] = 0;
s->max[5] = 0;
s->max[6] = 0;
s->modem.control = 0x00;
s->modem.config = 0x0000;
s->bt.control = 0x00;
s->bt.config = 0x0000;
s->codec.config[0] = 0x0649;
s->codec.config[1] = 0x0000;
s->codec.config[2] = 0x0007;
s->codec.config[3] = 0x1ffc;
s->codec.rxoff = 0;
s->codec.rxlen = 0;
s->codec.txlen = 0;
s->codec.rxavail = 0;
s->codec.txavail = 0;
omap_eac_format_update(s);
omap_eac_interrupt_update(s);
}
static uint64_t omap_eac_read(void *opaque, target_phys_addr_t addr,
unsigned size)
{
struct omap_eac_s *s = (struct omap_eac_s *) opaque;
uint32_t ret;
if (size != 2) {
return omap_badwidth_read16(opaque, addr);
}
switch (addr) {
case 0x000: /* CPCFR1 */
return s->config[0];
case 0x004: /* CPCFR2 */
return s->config[1];
case 0x008: /* CPCFR3 */
return s->config[2];
case 0x00c: /* CPCFR4 */
return s->config[3];
case 0x010: /* CPTCTL */
return s->control | ((s->codec.rxavail + s->codec.rxlen > 0) << 7) |
((s->codec.txlen < s->codec.txavail) << 5);
case 0x014: /* CPTTADR */
return s->address;
case 0x018: /* CPTDATL */
return s->data & 0xff;
case 0x01c: /* CPTDATH */
return s->data >> 8;
case 0x020: /* CPTVSLL */
return s->vtol;
case 0x024: /* CPTVSLH */
return s->vtsl | (3 << 5); /* CRDY1 | CRDY2 */
case 0x040: /* MPCTR */
return s->modem.control;
case 0x044: /* MPMCCFR */
return s->modem.config;
case 0x060: /* BPCTR */
return s->bt.control;
case 0x064: /* BPMCCFR */
return s->bt.config;
case 0x080: /* AMSCFR */
return s->mixer;
case 0x084: /* AMVCTR */
return s->gain[0];
case 0x088: /* AM1VCTR */
return s->gain[1];
case 0x08c: /* AM2VCTR */
return s->gain[2];
case 0x090: /* AM3VCTR */
return s->gain[3];
case 0x094: /* ASTCTR */
return s->att;
case 0x098: /* APD1LCR */
return s->max[0];
case 0x09c: /* APD1RCR */
return s->max[1];
case 0x0a0: /* APD2LCR */
return s->max[2];
case 0x0a4: /* APD2RCR */
return s->max[3];
case 0x0a8: /* APD3LCR */
return s->max[4];
case 0x0ac: /* APD3RCR */
return s->max[5];
case 0x0b0: /* APD4R */
return s->max[6];
case 0x0b4: /* ADWR */
/* This should be write-only? Docs list it as read-only. */
return 0x0000;
case 0x0b8: /* ADRDR */
if (likely(s->codec.rxlen > 1)) {
ret = s->codec.rxbuf[s->codec.rxoff ++];
s->codec.rxlen --;
s->codec.rxoff &= EAC_BUF_LEN - 1;
return ret;
} else if (s->codec.rxlen) {
ret = s->codec.rxbuf[s->codec.rxoff ++];
s->codec.rxlen --;
s->codec.rxoff &= EAC_BUF_LEN - 1;
if (s->codec.rxavail)
omap_eac_in_refill(s);
omap_eac_in_dmarequest_update(s);
return ret;
}
return 0x0000;
case 0x0bc: /* AGCFR */
return s->codec.config[0];
case 0x0c0: /* AGCTR */
return s->codec.config[1] | ((s->codec.config[1] & 2) << 14);
case 0x0c4: /* AGCFR2 */
return s->codec.config[2];
case 0x0c8: /* AGCFR3 */
return s->codec.config[3];
case 0x0cc: /* MBPDMACTR */
case 0x0d0: /* MPDDMARR */
case 0x0d8: /* MPUDMARR */
case 0x0e4: /* BPDDMARR */
case 0x0ec: /* BPUDMARR */
return 0x0000;
case 0x100: /* VERSION_NUMBER */
return 0x0010;
case 0x104: /* SYSCONFIG */
return s->sysconfig;
case 0x108: /* SYSSTATUS */
return 1 | 0xe; /* RESETDONE | stuff */
}
OMAP_BAD_REG(addr);
return 0;
}
static void omap_eac_write(void *opaque, target_phys_addr_t addr,
uint64_t value, unsigned size)
{
struct omap_eac_s *s = (struct omap_eac_s *) opaque;
if (size != 2) {
return omap_badwidth_write16(opaque, addr, value);
}
switch (addr) {
case 0x098: /* APD1LCR */
case 0x09c: /* APD1RCR */
case 0x0a0: /* APD2LCR */
case 0x0a4: /* APD2RCR */
case 0x0a8: /* APD3LCR */
case 0x0ac: /* APD3RCR */
case 0x0b0: /* APD4R */
case 0x0b8: /* ADRDR */
case 0x0d0: /* MPDDMARR */
case 0x0d8: /* MPUDMARR */
case 0x0e4: /* BPDDMARR */
case 0x0ec: /* BPUDMARR */
case 0x100: /* VERSION_NUMBER */
case 0x108: /* SYSSTATUS */
OMAP_RO_REG(addr);
return;
case 0x000: /* CPCFR1 */
s->config[0] = value & 0xff;
omap_eac_format_update(s);
break;
case 0x004: /* CPCFR2 */
s->config[1] = value & 0xff;
omap_eac_format_update(s);
break;
case 0x008: /* CPCFR3 */
s->config[2] = value & 0xff;
omap_eac_format_update(s);
break;
case 0x00c: /* CPCFR4 */
s->config[3] = value & 0xff;
omap_eac_format_update(s);
break;
case 0x010: /* CPTCTL */
/* Assuming TXF and TXE bits are read-only... */
s->control = value & 0x5f;
omap_eac_interrupt_update(s);
break;
case 0x014: /* CPTTADR */
s->address = value & 0xff;
break;
case 0x018: /* CPTDATL */
s->data &= 0xff00;
s->data |= value & 0xff;
break;
case 0x01c: /* CPTDATH */
s->data &= 0x00ff;
s->data |= value << 8;
break;
case 0x020: /* CPTVSLL */
s->vtol = value & 0xf8;
break;
case 0x024: /* CPTVSLH */
s->vtsl = value & 0x9f;
break;
case 0x040: /* MPCTR */
s->modem.control = value & 0x8f;
break;
case 0x044: /* MPMCCFR */
s->modem.config = value & 0x7fff;
break;
case 0x060: /* BPCTR */
s->bt.control = value & 0x8f;
break;
case 0x064: /* BPMCCFR */
s->bt.config = value & 0x7fff;
break;
case 0x080: /* AMSCFR */
s->mixer = value & 0x0fff;
break;
case 0x084: /* AMVCTR */
s->gain[0] = value & 0xffff;
break;
case 0x088: /* AM1VCTR */
s->gain[1] = value & 0xff7f;
break;
case 0x08c: /* AM2VCTR */
s->gain[2] = value & 0xff7f;
break;
case 0x090: /* AM3VCTR */
s->gain[3] = value & 0xff7f;
break;
case 0x094: /* ASTCTR */
s->att = value & 0xff;
break;
case 0x0b4: /* ADWR */
s->codec.txbuf[s->codec.txlen ++] = value;
if (unlikely(s->codec.txlen == EAC_BUF_LEN ||
s->codec.txlen == s->codec.txavail)) {
if (s->codec.txavail)
omap_eac_out_empty(s);
/* Discard what couldn't be written */
s->codec.txlen = 0;
}
break;
case 0x0bc: /* AGCFR */
s->codec.config[0] = value & 0x07ff;
omap_eac_format_update(s);
break;
case 0x0c0: /* AGCTR */
s->codec.config[1] = value & 0x780f;
omap_eac_format_update(s);
break;
case 0x0c4: /* AGCFR2 */
s->codec.config[2] = value & 0x003f;
omap_eac_format_update(s);
break;
case 0x0c8: /* AGCFR3 */
s->codec.config[3] = value & 0xffff;
omap_eac_format_update(s);
break;
case 0x0cc: /* MBPDMACTR */
case 0x0d4: /* MPDDMAWR */
case 0x0e0: /* MPUDMAWR */
case 0x0e8: /* BPDDMAWR */
case 0x0f0: /* BPUDMAWR */
break;
case 0x104: /* SYSCONFIG */
if (value & (1 << 1)) /* SOFTRESET */
omap_eac_reset(s);
s->sysconfig = value & 0x31d;
break;
default:
OMAP_BAD_REG(addr);
return;
}
}
static const MemoryRegionOps omap_eac_ops = {
.read = omap_eac_read,
.write = omap_eac_write,
.endianness = DEVICE_NATIVE_ENDIAN,
};
static struct omap_eac_s *omap_eac_init(struct omap_target_agent_s *ta,
qemu_irq irq, qemu_irq *drq, omap_clk fclk, omap_clk iclk)
{
struct omap_eac_s *s = (struct omap_eac_s *)
g_malloc0(sizeof(struct omap_eac_s));
s->irq = irq;
s->codec.rxdrq = *drq ++;
s->codec.txdrq = *drq;
omap_eac_reset(s);
AUD_register_card("OMAP EAC", &s->codec.card);
memory_region_init_io(&s->iomem, &omap_eac_ops, s, "omap.eac",
omap_l4_region_size(ta, 0));
omap_l4_attach(ta, 0, &s->iomem);
return s;
}
/* STI/XTI (emulation interface) console - reverse engineered only */
struct omap_sti_s {
qemu_irq irq;
MemoryRegion iomem;
MemoryRegion iomem_fifo;
CharDriverState *chr;
uint32_t sysconfig;
uint32_t systest;
uint32_t irqst;
uint32_t irqen;
uint32_t clkcontrol;
uint32_t serial_config;
};
#define STI_TRACE_CONSOLE_CHANNEL 239
#define STI_TRACE_CONTROL_CHANNEL 253
static inline void omap_sti_interrupt_update(struct omap_sti_s *s)
{
qemu_set_irq(s->irq, s->irqst & s->irqen);
}
static void omap_sti_reset(struct omap_sti_s *s)
{
s->sysconfig = 0;
s->irqst = 0;
s->irqen = 0;
s->clkcontrol = 0;
s->serial_config = 0;
omap_sti_interrupt_update(s);
}
static uint64_t omap_sti_read(void *opaque, target_phys_addr_t addr,
unsigned size)
{
struct omap_sti_s *s = (struct omap_sti_s *) opaque;
if (size != 4) {
return omap_badwidth_read32(opaque, addr);
}
switch (addr) {
case 0x00: /* STI_REVISION */
return 0x10;
case 0x10: /* STI_SYSCONFIG */
return s->sysconfig;
case 0x14: /* STI_SYSSTATUS / STI_RX_STATUS / XTI_SYSSTATUS */
return 0x00;
case 0x18: /* STI_IRQSTATUS */
return s->irqst;
case 0x1c: /* STI_IRQSETEN / STI_IRQCLREN */
return s->irqen;
case 0x24: /* STI_ER / STI_DR / XTI_TRACESELECT */
case 0x28: /* STI_RX_DR / XTI_RXDATA */
/* TODO */
return 0;
case 0x2c: /* STI_CLK_CTRL / XTI_SCLKCRTL */
return s->clkcontrol;
case 0x30: /* STI_SERIAL_CFG / XTI_SCONFIG */
return s->serial_config;
}
OMAP_BAD_REG(addr);
return 0;
}
static void omap_sti_write(void *opaque, target_phys_addr_t addr,
uint64_t value, unsigned size)
{
struct omap_sti_s *s = (struct omap_sti_s *) opaque;
if (size != 4) {
return omap_badwidth_write32(opaque, addr, value);
}
switch (addr) {
case 0x00: /* STI_REVISION */
case 0x14: /* STI_SYSSTATUS / STI_RX_STATUS / XTI_SYSSTATUS */
OMAP_RO_REG(addr);
return;
case 0x10: /* STI_SYSCONFIG */
if (value & (1 << 1)) /* SOFTRESET */
omap_sti_reset(s);
s->sysconfig = value & 0xfe;
break;
case 0x18: /* STI_IRQSTATUS */
s->irqst &= ~value;
omap_sti_interrupt_update(s);
break;
case 0x1c: /* STI_IRQSETEN / STI_IRQCLREN */
s->irqen = value & 0xffff;
omap_sti_interrupt_update(s);
break;
case 0x2c: /* STI_CLK_CTRL / XTI_SCLKCRTL */
s->clkcontrol = value & 0xff;
break;
case 0x30: /* STI_SERIAL_CFG / XTI_SCONFIG */
s->serial_config = value & 0xff;
break;
case 0x24: /* STI_ER / STI_DR / XTI_TRACESELECT */
case 0x28: /* STI_RX_DR / XTI_RXDATA */
/* TODO */
return;
default:
OMAP_BAD_REG(addr);
return;
}
}
static const MemoryRegionOps omap_sti_ops = {
.read = omap_sti_read,
.write = omap_sti_write,
.endianness = DEVICE_NATIVE_ENDIAN,
};
static uint64_t omap_sti_fifo_read(void *opaque, target_phys_addr_t addr,
unsigned size)
{
OMAP_BAD_REG(addr);
return 0;
}
static void omap_sti_fifo_write(void *opaque, target_phys_addr_t addr,
uint64_t value, unsigned size)
{
struct omap_sti_s *s = (struct omap_sti_s *) opaque;
int ch = addr >> 6;
uint8_t byte = value;
if (size != 1) {
return omap_badwidth_write8(opaque, addr, size);
}
if (ch == STI_TRACE_CONTROL_CHANNEL) {
/* Flush channel <i>value</i>. */
qemu_chr_fe_write(s->chr, (const uint8_t *) "\r", 1);
} else if (ch == STI_TRACE_CONSOLE_CHANNEL || 1) {
if (value == 0xc0 || value == 0xc3) {
/* Open channel <i>ch</i>. */
} else if (value == 0x00)
qemu_chr_fe_write(s->chr, (const uint8_t *) "\n", 1);
else
qemu_chr_fe_write(s->chr, &byte, 1);
}
}
static const MemoryRegionOps omap_sti_fifo_ops = {
.read = omap_sti_fifo_read,
.write = omap_sti_fifo_write,
.endianness = DEVICE_NATIVE_ENDIAN,
};
static struct omap_sti_s *omap_sti_init(struct omap_target_agent_s *ta,
MemoryRegion *sysmem,
target_phys_addr_t channel_base, qemu_irq irq, omap_clk clk,
CharDriverState *chr)
{
struct omap_sti_s *s = (struct omap_sti_s *)
g_malloc0(sizeof(struct omap_sti_s));
s->irq = irq;
omap_sti_reset(s);
s->chr = chr ?: qemu_chr_new("null", "null", NULL);
memory_region_init_io(&s->iomem, &omap_sti_ops, s, "omap.sti",
omap_l4_region_size(ta, 0));
omap_l4_attach(ta, 0, &s->iomem);
memory_region_init_io(&s->iomem_fifo, &omap_sti_fifo_ops, s,
"omap.sti.fifo", 0x10000);
memory_region_add_subregion(sysmem, channel_base, &s->iomem_fifo);
return s;
}
/* L4 Interconnect */
#define L4TA(n) (n)
#define L4TAO(n) ((n) + 39)
static const struct omap_l4_region_s omap_l4_region[125] = {
[ 1] = { 0x40800, 0x800, 32 }, /* Initiator agent */
[ 2] = { 0x41000, 0x1000, 32 }, /* Link agent */
[ 0] = { 0x40000, 0x800, 32 }, /* Address and protection */
[ 3] = { 0x00000, 0x1000, 32 | 16 | 8 }, /* System Control and Pinout */
[ 4] = { 0x01000, 0x1000, 32 | 16 | 8 }, /* L4TAO1 */
[ 5] = { 0x04000, 0x1000, 32 | 16 }, /* 32K Timer */
[ 6] = { 0x05000, 0x1000, 32 | 16 | 8 }, /* L4TAO2 */
[ 7] = { 0x08000, 0x800, 32 }, /* PRCM Region A */
[ 8] = { 0x08800, 0x800, 32 }, /* PRCM Region B */
[ 9] = { 0x09000, 0x1000, 32 | 16 | 8 }, /* L4TAO */
[ 10] = { 0x12000, 0x1000, 32 | 16 | 8 }, /* Test (BCM) */
[ 11] = { 0x13000, 0x1000, 32 | 16 | 8 }, /* L4TA1 */
[ 12] = { 0x14000, 0x1000, 32 }, /* Test/emulation (TAP) */
[ 13] = { 0x15000, 0x1000, 32 | 16 | 8 }, /* L4TA2 */
[ 14] = { 0x18000, 0x1000, 32 | 16 | 8 }, /* GPIO1 */
[ 16] = { 0x1a000, 0x1000, 32 | 16 | 8 }, /* GPIO2 */
[ 18] = { 0x1c000, 0x1000, 32 | 16 | 8 }, /* GPIO3 */
[ 19] = { 0x1e000, 0x1000, 32 | 16 | 8 }, /* GPIO4 */
[ 15] = { 0x19000, 0x1000, 32 | 16 | 8 }, /* Quad GPIO TOP */
[ 17] = { 0x1b000, 0x1000, 32 | 16 | 8 }, /* L4TA3 */
[ 20] = { 0x20000, 0x1000, 32 | 16 | 8 }, /* WD Timer 1 (Secure) */
[ 22] = { 0x22000, 0x1000, 32 | 16 | 8 }, /* WD Timer 2 (OMAP) */
[ 21] = { 0x21000, 0x1000, 32 | 16 | 8 }, /* Dual WD timer TOP */
[ 23] = { 0x23000, 0x1000, 32 | 16 | 8 }, /* L4TA4 */
[ 24] = { 0x28000, 0x1000, 32 | 16 | 8 }, /* GP Timer 1 */
[ 25] = { 0x29000, 0x1000, 32 | 16 | 8 }, /* L4TA7 */
[ 26] = { 0x48000, 0x2000, 32 | 16 | 8 }, /* Emulation (ARM11ETB) */
[ 27] = { 0x4a000, 0x1000, 32 | 16 | 8 }, /* L4TA9 */
[ 28] = { 0x50000, 0x400, 32 | 16 | 8 }, /* Display top */
[ 29] = { 0x50400, 0x400, 32 | 16 | 8 }, /* Display control */
[ 30] = { 0x50800, 0x400, 32 | 16 | 8 }, /* Display RFBI */
[ 31] = { 0x50c00, 0x400, 32 | 16 | 8 }, /* Display encoder */
[ 32] = { 0x51000, 0x1000, 32 | 16 | 8 }, /* L4TA10 */
[ 33] = { 0x52000, 0x400, 32 | 16 | 8 }, /* Camera top */
[ 34] = { 0x52400, 0x400, 32 | 16 | 8 }, /* Camera core */
[ 35] = { 0x52800, 0x400, 32 | 16 | 8 }, /* Camera DMA */
[ 36] = { 0x52c00, 0x400, 32 | 16 | 8 }, /* Camera MMU */
[ 37] = { 0x53000, 0x1000, 32 | 16 | 8 }, /* L4TA11 */
[ 38] = { 0x56000, 0x1000, 32 | 16 | 8 }, /* sDMA */
[ 39] = { 0x57000, 0x1000, 32 | 16 | 8 }, /* L4TA12 */
[ 40] = { 0x58000, 0x1000, 32 | 16 | 8 }, /* SSI top */
[ 41] = { 0x59000, 0x1000, 32 | 16 | 8 }, /* SSI GDD */
[ 42] = { 0x5a000, 0x1000, 32 | 16 | 8 }, /* SSI Port1 */
[ 43] = { 0x5b000, 0x1000, 32 | 16 | 8 }, /* SSI Port2 */
[ 44] = { 0x5c000, 0x1000, 32 | 16 | 8 }, /* L4TA13 */
[ 45] = { 0x5e000, 0x1000, 32 | 16 | 8 }, /* USB OTG */
[ 46] = { 0x5f000, 0x1000, 32 | 16 | 8 }, /* L4TAO4 */
[ 47] = { 0x60000, 0x1000, 32 | 16 | 8 }, /* Emulation (WIN_TRACER1SDRC) */
[ 48] = { 0x61000, 0x1000, 32 | 16 | 8 }, /* L4TA14 */
[ 49] = { 0x62000, 0x1000, 32 | 16 | 8 }, /* Emulation (WIN_TRACER2GPMC) */
[ 50] = { 0x63000, 0x1000, 32 | 16 | 8 }, /* L4TA15 */
[ 51] = { 0x64000, 0x1000, 32 | 16 | 8 }, /* Emulation (WIN_TRACER3OCM) */
[ 52] = { 0x65000, 0x1000, 32 | 16 | 8 }, /* L4TA16 */
[ 53] = { 0x66000, 0x300, 32 | 16 | 8 }, /* Emulation (WIN_TRACER4L4) */
[ 54] = { 0x67000, 0x1000, 32 | 16 | 8 }, /* L4TA17 */
[ 55] = { 0x68000, 0x1000, 32 | 16 | 8 }, /* Emulation (XTI) */
[ 56] = { 0x69000, 0x1000, 32 | 16 | 8 }, /* L4TA18 */
[ 57] = { 0x6a000, 0x1000, 16 | 8 }, /* UART1 */
[ 58] = { 0x6b000, 0x1000, 32 | 16 | 8 }, /* L4TA19 */
[ 59] = { 0x6c000, 0x1000, 16 | 8 }, /* UART2 */
[ 60] = { 0x6d000, 0x1000, 32 | 16 | 8 }, /* L4TA20 */
[ 61] = { 0x6e000, 0x1000, 16 | 8 }, /* UART3 */
[ 62] = { 0x6f000, 0x1000, 32 | 16 | 8 }, /* L4TA21 */
[ 63] = { 0x70000, 0x1000, 16 }, /* I2C1 */
[ 64] = { 0x71000, 0x1000, 32 | 16 | 8 }, /* L4TAO5 */
[ 65] = { 0x72000, 0x1000, 16 }, /* I2C2 */
[ 66] = { 0x73000, 0x1000, 32 | 16 | 8 }, /* L4TAO6 */
[ 67] = { 0x74000, 0x1000, 16 }, /* McBSP1 */
[ 68] = { 0x75000, 0x1000, 32 | 16 | 8 }, /* L4TAO7 */
[ 69] = { 0x76000, 0x1000, 16 }, /* McBSP2 */
[ 70] = { 0x77000, 0x1000, 32 | 16 | 8 }, /* L4TAO8 */
[ 71] = { 0x24000, 0x1000, 32 | 16 | 8 }, /* WD Timer 3 (DSP) */
[ 72] = { 0x25000, 0x1000, 32 | 16 | 8 }, /* L4TA5 */
[ 73] = { 0x26000, 0x1000, 32 | 16 | 8 }, /* WD Timer 4 (IVA) */
[ 74] = { 0x27000, 0x1000, 32 | 16 | 8 }, /* L4TA6 */
[ 75] = { 0x2a000, 0x1000, 32 | 16 | 8 }, /* GP Timer 2 */
[ 76] = { 0x2b000, 0x1000, 32 | 16 | 8 }, /* L4TA8 */
[ 77] = { 0x78000, 0x1000, 32 | 16 | 8 }, /* GP Timer 3 */
[ 78] = { 0x79000, 0x1000, 32 | 16 | 8 }, /* L4TA22 */
[ 79] = { 0x7a000, 0x1000, 32 | 16 | 8 }, /* GP Timer 4 */
[ 80] = { 0x7b000, 0x1000, 32 | 16 | 8 }, /* L4TA23 */
[ 81] = { 0x7c000, 0x1000, 32 | 16 | 8 }, /* GP Timer 5 */
[ 82] = { 0x7d000, 0x1000, 32 | 16 | 8 }, /* L4TA24 */
[ 83] = { 0x7e000, 0x1000, 32 | 16 | 8 }, /* GP Timer 6 */
[ 84] = { 0x7f000, 0x1000, 32 | 16 | 8 }, /* L4TA25 */
[ 85] = { 0x80000, 0x1000, 32 | 16 | 8 }, /* GP Timer 7 */
[ 86] = { 0x81000, 0x1000, 32 | 16 | 8 }, /* L4TA26 */
[ 87] = { 0x82000, 0x1000, 32 | 16 | 8 }, /* GP Timer 8 */
[ 88] = { 0x83000, 0x1000, 32 | 16 | 8 }, /* L4TA27 */
[ 89] = { 0x84000, 0x1000, 32 | 16 | 8 }, /* GP Timer 9 */
[ 90] = { 0x85000, 0x1000, 32 | 16 | 8 }, /* L4TA28 */
[ 91] = { 0x86000, 0x1000, 32 | 16 | 8 }, /* GP Timer 10 */
[ 92] = { 0x87000, 0x1000, 32 | 16 | 8 }, /* L4TA29 */
[ 93] = { 0x88000, 0x1000, 32 | 16 | 8 }, /* GP Timer 11 */
[ 94] = { 0x89000, 0x1000, 32 | 16 | 8 }, /* L4TA30 */
[ 95] = { 0x8a000, 0x1000, 32 | 16 | 8 }, /* GP Timer 12 */
[ 96] = { 0x8b000, 0x1000, 32 | 16 | 8 }, /* L4TA31 */
[ 97] = { 0x90000, 0x1000, 16 }, /* EAC */
[ 98] = { 0x91000, 0x1000, 32 | 16 | 8 }, /* L4TA32 */
[ 99] = { 0x92000, 0x1000, 16 }, /* FAC */
[100] = { 0x93000, 0x1000, 32 | 16 | 8 }, /* L4TA33 */
[101] = { 0x94000, 0x1000, 32 | 16 | 8 }, /* IPC (MAILBOX) */
[102] = { 0x95000, 0x1000, 32 | 16 | 8 }, /* L4TA34 */
[103] = { 0x98000, 0x1000, 32 | 16 | 8 }, /* SPI1 */
[104] = { 0x99000, 0x1000, 32 | 16 | 8 }, /* L4TA35 */
[105] = { 0x9a000, 0x1000, 32 | 16 | 8 }, /* SPI2 */
[106] = { 0x9b000, 0x1000, 32 | 16 | 8 }, /* L4TA36 */
[107] = { 0x9c000, 0x1000, 16 | 8 }, /* MMC SDIO */
[108] = { 0x9d000, 0x1000, 32 | 16 | 8 }, /* L4TAO9 */
[109] = { 0x9e000, 0x1000, 32 | 16 | 8 }, /* MS_PRO */
[110] = { 0x9f000, 0x1000, 32 | 16 | 8 }, /* L4TAO10 */
[111] = { 0xa0000, 0x1000, 32 }, /* RNG */
[112] = { 0xa1000, 0x1000, 32 | 16 | 8 }, /* L4TAO11 */
[113] = { 0xa2000, 0x1000, 32 }, /* DES3DES */
[114] = { 0xa3000, 0x1000, 32 | 16 | 8 }, /* L4TAO12 */
[115] = { 0xa4000, 0x1000, 32 }, /* SHA1MD5 */
[116] = { 0xa5000, 0x1000, 32 | 16 | 8 }, /* L4TAO13 */
[117] = { 0xa6000, 0x1000, 32 }, /* AES */
[118] = { 0xa7000, 0x1000, 32 | 16 | 8 }, /* L4TA37 */
[119] = { 0xa8000, 0x2000, 32 }, /* PKA */
[120] = { 0xaa000, 0x1000, 32 | 16 | 8 }, /* L4TA38 */
[121] = { 0xb0000, 0x1000, 32 }, /* MG */
[122] = { 0xb1000, 0x1000, 32 | 16 | 8 },
[123] = { 0xb2000, 0x1000, 32 }, /* HDQ/1-Wire */
[124] = { 0xb3000, 0x1000, 32 | 16 | 8 }, /* L4TA39 */
};
static const struct omap_l4_agent_info_s omap_l4_agent_info[54] = {
{ 0, 0, 3, 2 }, /* L4IA initiatior agent */
{ L4TAO(1), 3, 2, 1 }, /* Control and pinout module */
{ L4TAO(2), 5, 2, 1 }, /* 32K timer */
{ L4TAO(3), 7, 3, 2 }, /* PRCM */
{ L4TA(1), 10, 2, 1 }, /* BCM */
{ L4TA(2), 12, 2, 1 }, /* Test JTAG */
{ L4TA(3), 14, 6, 3 }, /* Quad GPIO */
{ L4TA(4), 20, 4, 3 }, /* WD timer 1/2 */
{ L4TA(7), 24, 2, 1 }, /* GP timer 1 */
{ L4TA(9), 26, 2, 1 }, /* ATM11 ETB */
{ L4TA(10), 28, 5, 4 }, /* Display subsystem */
{ L4TA(11), 33, 5, 4 }, /* Camera subsystem */
{ L4TA(12), 38, 2, 1 }, /* sDMA */
{ L4TA(13), 40, 5, 4 }, /* SSI */
{ L4TAO(4), 45, 2, 1 }, /* USB */
{ L4TA(14), 47, 2, 1 }, /* Win Tracer1 */
{ L4TA(15), 49, 2, 1 }, /* Win Tracer2 */
{ L4TA(16), 51, 2, 1 }, /* Win Tracer3 */
{ L4TA(17), 53, 2, 1 }, /* Win Tracer4 */
{ L4TA(18), 55, 2, 1 }, /* XTI */
{ L4TA(19), 57, 2, 1 }, /* UART1 */
{ L4TA(20), 59, 2, 1 }, /* UART2 */
{ L4TA(21), 61, 2, 1 }, /* UART3 */
{ L4TAO(5), 63, 2, 1 }, /* I2C1 */
{ L4TAO(6), 65, 2, 1 }, /* I2C2 */
{ L4TAO(7), 67, 2, 1 }, /* McBSP1 */
{ L4TAO(8), 69, 2, 1 }, /* McBSP2 */
{ L4TA(5), 71, 2, 1 }, /* WD Timer 3 (DSP) */
{ L4TA(6), 73, 2, 1 }, /* WD Timer 4 (IVA) */
{ L4TA(8), 75, 2, 1 }, /* GP Timer 2 */
{ L4TA(22), 77, 2, 1 }, /* GP Timer 3 */
{ L4TA(23), 79, 2, 1 }, /* GP Timer 4 */
{ L4TA(24), 81, 2, 1 }, /* GP Timer 5 */
{ L4TA(25), 83, 2, 1 }, /* GP Timer 6 */
{ L4TA(26), 85, 2, 1 }, /* GP Timer 7 */
{ L4TA(27), 87, 2, 1 }, /* GP Timer 8 */
{ L4TA(28), 89, 2, 1 }, /* GP Timer 9 */
{ L4TA(29), 91, 2, 1 }, /* GP Timer 10 */
{ L4TA(30), 93, 2, 1 }, /* GP Timer 11 */
{ L4TA(31), 95, 2, 1 }, /* GP Timer 12 */
{ L4TA(32), 97, 2, 1 }, /* EAC */
{ L4TA(33), 99, 2, 1 }, /* FAC */
{ L4TA(34), 101, 2, 1 }, /* IPC */
{ L4TA(35), 103, 2, 1 }, /* SPI1 */
{ L4TA(36), 105, 2, 1 }, /* SPI2 */
{ L4TAO(9), 107, 2, 1 }, /* MMC SDIO */
{ L4TAO(10), 109, 2, 1 },
{ L4TAO(11), 111, 2, 1 }, /* RNG */
{ L4TAO(12), 113, 2, 1 }, /* DES3DES */
{ L4TAO(13), 115, 2, 1 }, /* SHA1MD5 */
{ L4TA(37), 117, 2, 1 }, /* AES */
{ L4TA(38), 119, 2, 1 }, /* PKA */
{ -1, 121, 2, 1 },
{ L4TA(39), 123, 2, 1 }, /* HDQ/1-Wire */
};
#define omap_l4ta(bus, cs) \
omap_l4ta_get(bus, omap_l4_region, omap_l4_agent_info, L4TA(cs))
#define omap_l4tao(bus, cs) \
omap_l4ta_get(bus, omap_l4_region, omap_l4_agent_info, L4TAO(cs))
/* Power, Reset, and Clock Management */
struct omap_prcm_s {
qemu_irq irq[3];
struct omap_mpu_state_s *mpu;
MemoryRegion iomem0;
MemoryRegion iomem1;
uint32_t irqst[3];
uint32_t irqen[3];
uint32_t sysconfig;
uint32_t voltctrl;
uint32_t scratch[20];
uint32_t clksrc[1];
uint32_t clkout[1];
uint32_t clkemul[1];
uint32_t clkpol[1];
uint32_t clksel[8];
uint32_t clken[12];
uint32_t clkctrl[4];
uint32_t clkidle[7];
uint32_t setuptime[2];
uint32_t wkup[3];
uint32_t wken[3];
uint32_t wkst[3];
uint32_t rst[4];
uint32_t rstctrl[1];
uint32_t power[4];
uint32_t rsttime_wkup;
uint32_t ev;
uint32_t evtime[2];
int dpll_lock, apll_lock[2];
};
static void omap_prcm_int_update(struct omap_prcm_s *s, int dom)
{
qemu_set_irq(s->irq[dom], s->irqst[dom] & s->irqen[dom]);
/* XXX or is the mask applied before PRCM_IRQSTATUS_* ? */
}
static uint64_t omap_prcm_read(void *opaque, target_phys_addr_t addr,
unsigned size)
{
struct omap_prcm_s *s = (struct omap_prcm_s *) opaque;
uint32_t ret;
if (size != 4) {
return omap_badwidth_read32(opaque, addr);
}
switch (addr) {
case 0x000: /* PRCM_REVISION */
return 0x10;
case 0x010: /* PRCM_SYSCONFIG */
return s->sysconfig;
case 0x018: /* PRCM_IRQSTATUS_MPU */
return s->irqst[0];
case 0x01c: /* PRCM_IRQENABLE_MPU */
return s->irqen[0];
case 0x050: /* PRCM_VOLTCTRL */
return s->voltctrl;
case 0x054: /* PRCM_VOLTST */
return s->voltctrl & 3;
case 0x060: /* PRCM_CLKSRC_CTRL */
return s->clksrc[0];
case 0x070: /* PRCM_CLKOUT_CTRL */
return s->clkout[0];
case 0x078: /* PRCM_CLKEMUL_CTRL */
return s->clkemul[0];
case 0x080: /* PRCM_CLKCFG_CTRL */
case 0x084: /* PRCM_CLKCFG_STATUS */
return 0;
case 0x090: /* PRCM_VOLTSETUP */
return s->setuptime[0];
case 0x094: /* PRCM_CLKSSETUP */
return s->setuptime[1];
case 0x098: /* PRCM_POLCTRL */
return s->clkpol[0];
case 0x0b0: /* GENERAL_PURPOSE1 */
case 0x0b4: /* GENERAL_PURPOSE2 */
case 0x0b8: /* GENERAL_PURPOSE3 */
case 0x0bc: /* GENERAL_PURPOSE4 */
case 0x0c0: /* GENERAL_PURPOSE5 */
case 0x0c4: /* GENERAL_PURPOSE6 */
case 0x0c8: /* GENERAL_PURPOSE7 */
case 0x0cc: /* GENERAL_PURPOSE8 */
case 0x0d0: /* GENERAL_PURPOSE9 */
case 0x0d4: /* GENERAL_PURPOSE10 */
case 0x0d8: /* GENERAL_PURPOSE11 */
case 0x0dc: /* GENERAL_PURPOSE12 */
case 0x0e0: /* GENERAL_PURPOSE13 */
case 0x0e4: /* GENERAL_PURPOSE14 */
case 0x0e8: /* GENERAL_PURPOSE15 */
case 0x0ec: /* GENERAL_PURPOSE16 */
case 0x0f0: /* GENERAL_PURPOSE17 */
case 0x0f4: /* GENERAL_PURPOSE18 */
case 0x0f8: /* GENERAL_PURPOSE19 */
case 0x0fc: /* GENERAL_PURPOSE20 */
return s->scratch[(addr - 0xb0) >> 2];
case 0x140: /* CM_CLKSEL_MPU */
return s->clksel[0];
case 0x148: /* CM_CLKSTCTRL_MPU */
return s->clkctrl[0];
case 0x158: /* RM_RSTST_MPU */
return s->rst[0];
case 0x1c8: /* PM_WKDEP_MPU */
return s->wkup[0];
case 0x1d4: /* PM_EVGENCTRL_MPU */
return s->ev;
case 0x1d8: /* PM_EVEGENONTIM_MPU */
return s->evtime[0];
case 0x1dc: /* PM_EVEGENOFFTIM_MPU */
return s->evtime[1];
case 0x1e0: /* PM_PWSTCTRL_MPU */
return s->power[0];
case 0x1e4: /* PM_PWSTST_MPU */
return 0;
case 0x200: /* CM_FCLKEN1_CORE */
return s->clken[0];
case 0x204: /* CM_FCLKEN2_CORE */
return s->clken[1];
case 0x210: /* CM_ICLKEN1_CORE */
return s->clken[2];
case 0x214: /* CM_ICLKEN2_CORE */
return s->clken[3];
case 0x21c: /* CM_ICLKEN4_CORE */
return s->clken[4];
case 0x220: /* CM_IDLEST1_CORE */
/* TODO: check the actual iclk status */
return 0x7ffffff9;
case 0x224: /* CM_IDLEST2_CORE */
/* TODO: check the actual iclk status */
return 0x00000007;
case 0x22c: /* CM_IDLEST4_CORE */
/* TODO: check the actual iclk status */
return 0x0000001f;
case 0x230: /* CM_AUTOIDLE1_CORE */
return s->clkidle[0];
case 0x234: /* CM_AUTOIDLE2_CORE */
return s->clkidle[1];
case 0x238: /* CM_AUTOIDLE3_CORE */
return s->clkidle[2];
case 0x23c: /* CM_AUTOIDLE4_CORE */
return s->clkidle[3];
case 0x240: /* CM_CLKSEL1_CORE */
return s->clksel[1];
case 0x244: /* CM_CLKSEL2_CORE */
return s->clksel[2];
case 0x248: /* CM_CLKSTCTRL_CORE */
return s->clkctrl[1];
case 0x2a0: /* PM_WKEN1_CORE */
return s->wken[0];
case 0x2a4: /* PM_WKEN2_CORE */
return s->wken[1];
case 0x2b0: /* PM_WKST1_CORE */
return s->wkst[0];
case 0x2b4: /* PM_WKST2_CORE */
return s->wkst[1];
case 0x2c8: /* PM_WKDEP_CORE */
return 0x1e;
case 0x2e0: /* PM_PWSTCTRL_CORE */
return s->power[1];
case 0x2e4: /* PM_PWSTST_CORE */
return 0x000030 | (s->power[1] & 0xfc00);
case 0x300: /* CM_FCLKEN_GFX */
return s->clken[5];
case 0x310: /* CM_ICLKEN_GFX */
return s->clken[6];
case 0x320: /* CM_IDLEST_GFX */
/* TODO: check the actual iclk status */
return 0x00000001;
case 0x340: /* CM_CLKSEL_GFX */
return s->clksel[3];
case 0x348: /* CM_CLKSTCTRL_GFX */
return s->clkctrl[2];
case 0x350: /* RM_RSTCTRL_GFX */
return s->rstctrl[0];
case 0x358: /* RM_RSTST_GFX */
return s->rst[1];
case 0x3c8: /* PM_WKDEP_GFX */
return s->wkup[1];
case 0x3e0: /* PM_PWSTCTRL_GFX */
return s->power[2];
case 0x3e4: /* PM_PWSTST_GFX */
return s->power[2] & 3;
case 0x400: /* CM_FCLKEN_WKUP */
return s->clken[7];
case 0x410: /* CM_ICLKEN_WKUP */
return s->clken[8];
case 0x420: /* CM_IDLEST_WKUP */
/* TODO: check the actual iclk status */
return 0x0000003f;
case 0x430: /* CM_AUTOIDLE_WKUP */
return s->clkidle[4];
case 0x440: /* CM_CLKSEL_WKUP */
return s->clksel[4];
case 0x450: /* RM_RSTCTRL_WKUP */
return 0;
case 0x454: /* RM_RSTTIME_WKUP */
return s->rsttime_wkup;
case 0x458: /* RM_RSTST_WKUP */
return s->rst[2];
case 0x4a0: /* PM_WKEN_WKUP */
return s->wken[2];
case 0x4b0: /* PM_WKST_WKUP */
return s->wkst[2];
case 0x500: /* CM_CLKEN_PLL */
return s->clken[9];
case 0x520: /* CM_IDLEST_CKGEN */
ret = 0x0000070 | (s->apll_lock[0] << 9) | (s->apll_lock[1] << 8);
if (!(s->clksel[6] & 3))
/* Core uses 32-kHz clock */
ret |= 3 << 0;
else if (!s->dpll_lock)
/* DPLL not locked, core uses ref_clk */
ret |= 1 << 0;
else
/* Core uses DPLL */
ret |= 2 << 0;
return ret;
case 0x530: /* CM_AUTOIDLE_PLL */
return s->clkidle[5];
case 0x540: /* CM_CLKSEL1_PLL */
return s->clksel[5];
case 0x544: /* CM_CLKSEL2_PLL */
return s->clksel[6];
case 0x800: /* CM_FCLKEN_DSP */
return s->clken[10];
case 0x810: /* CM_ICLKEN_DSP */
return s->clken[11];
case 0x820: /* CM_IDLEST_DSP */
/* TODO: check the actual iclk status */
return 0x00000103;
case 0x830: /* CM_AUTOIDLE_DSP */
return s->clkidle[6];
case 0x840: /* CM_CLKSEL_DSP */
return s->clksel[7];
case 0x848: /* CM_CLKSTCTRL_DSP */
return s->clkctrl[3];
case 0x850: /* RM_RSTCTRL_DSP */
return 0;
case 0x858: /* RM_RSTST_DSP */
return s->rst[3];
case 0x8c8: /* PM_WKDEP_DSP */
return s->wkup[2];
case 0x8e0: /* PM_PWSTCTRL_DSP */
return s->power[3];
case 0x8e4: /* PM_PWSTST_DSP */
return 0x008030 | (s->power[3] & 0x3003);
case 0x8f0: /* PRCM_IRQSTATUS_DSP */
return s->irqst[1];
case 0x8f4: /* PRCM_IRQENABLE_DSP */
return s->irqen[1];
case 0x8f8: /* PRCM_IRQSTATUS_IVA */
return s->irqst[2];
case 0x8fc: /* PRCM_IRQENABLE_IVA */
return s->irqen[2];
}
OMAP_BAD_REG(addr);
return 0;
}
static void omap_prcm_apll_update(struct omap_prcm_s *s)
{
int mode[2];
mode[0] = (s->clken[9] >> 6) & 3;
s->apll_lock[0] = (mode[0] == 3);
mode[1] = (s->clken[9] >> 2) & 3;
s->apll_lock[1] = (mode[1] == 3);
/* TODO: update clocks */
if (mode[0] == 1 || mode[0] == 2 || mode[1] == 1 || mode[1] == 2)
fprintf(stderr, "%s: bad EN_54M_PLL or bad EN_96M_PLL\n",
__FUNCTION__);
}
static void omap_prcm_dpll_update(struct omap_prcm_s *s)
{
omap_clk dpll = omap_findclk(s->mpu, "dpll");
omap_clk dpll_x2 = omap_findclk(s->mpu, "dpll");
omap_clk core = omap_findclk(s->mpu, "core_clk");
int mode = (s->clken[9] >> 0) & 3;
int mult, div;
mult = (s->clksel[5] >> 12) & 0x3ff;
div = (s->clksel[5] >> 8) & 0xf;
if (mult == 0 || mult == 1)
mode = 1; /* Bypass */
s->dpll_lock = 0;
switch (mode) {
case 0:
fprintf(stderr, "%s: bad EN_DPLL\n", __FUNCTION__);
break;
case 1: /* Low-power bypass mode (Default) */
case 2: /* Fast-relock bypass mode */
omap_clk_setrate(dpll, 1, 1);
omap_clk_setrate(dpll_x2, 1, 1);
break;
case 3: /* Lock mode */
s->dpll_lock = 1; /* After 20 FINT cycles (ref_clk / (div + 1)). */
omap_clk_setrate(dpll, div + 1, mult);
omap_clk_setrate(dpll_x2, div + 1, mult * 2);
break;
}
switch ((s->clksel[6] >> 0) & 3) {
case 0:
omap_clk_reparent(core, omap_findclk(s->mpu, "clk32-kHz"));
break;
case 1:
omap_clk_reparent(core, dpll);
break;
case 2:
/* Default */
omap_clk_reparent(core, dpll_x2);
break;
case 3:
fprintf(stderr, "%s: bad CORE_CLK_SRC\n", __FUNCTION__);
break;
}
}
static void omap_prcm_write(void *opaque, target_phys_addr_t addr,
uint64_t value, unsigned size)
{
struct omap_prcm_s *s = (struct omap_prcm_s *) opaque;
if (size != 4) {
return omap_badwidth_write32(opaque, addr, value);
}
switch (addr) {
case 0x000: /* PRCM_REVISION */
case 0x054: /* PRCM_VOLTST */
case 0x084: /* PRCM_CLKCFG_STATUS */
case 0x1e4: /* PM_PWSTST_MPU */
case 0x220: /* CM_IDLEST1_CORE */
case 0x224: /* CM_IDLEST2_CORE */
case 0x22c: /* CM_IDLEST4_CORE */
case 0x2c8: /* PM_WKDEP_CORE */
case 0x2e4: /* PM_PWSTST_CORE */
case 0x320: /* CM_IDLEST_GFX */
case 0x3e4: /* PM_PWSTST_GFX */
case 0x420: /* CM_IDLEST_WKUP */
case 0x520: /* CM_IDLEST_CKGEN */
case 0x820: /* CM_IDLEST_DSP */
case 0x8e4: /* PM_PWSTST_DSP */
OMAP_RO_REG(addr);
return;
case 0x010: /* PRCM_SYSCONFIG */
s->sysconfig = value & 1;
break;
case 0x018: /* PRCM_IRQSTATUS_MPU */
s->irqst[0] &= ~value;
omap_prcm_int_update(s, 0);
break;
case 0x01c: /* PRCM_IRQENABLE_MPU */
s->irqen[0] = value & 0x3f;
omap_prcm_int_update(s, 0);
break;
case 0x050: /* PRCM_VOLTCTRL */
s->voltctrl = value & 0xf1c3;
break;
case 0x060: /* PRCM_CLKSRC_CTRL */
s->clksrc[0] = value & 0xdb;
/* TODO update clocks */
break;
case 0x070: /* PRCM_CLKOUT_CTRL */
s->clkout[0] = value & 0xbbbb;
/* TODO update clocks */
break;
case 0x078: /* PRCM_CLKEMUL_CTRL */
s->clkemul[0] = value & 1;
/* TODO update clocks */
break;
case 0x080: /* PRCM_CLKCFG_CTRL */
break;
case 0x090: /* PRCM_VOLTSETUP */
s->setuptime[0] = value & 0xffff;
break;
case 0x094: /* PRCM_CLKSSETUP */
s->setuptime[1] = value & 0xffff;
break;
case 0x098: /* PRCM_POLCTRL */
s->clkpol[0] = value & 0x701;
break;
case 0x0b0: /* GENERAL_PURPOSE1 */
case 0x0b4: /* GENERAL_PURPOSE2 */
case 0x0b8: /* GENERAL_PURPOSE3 */
case 0x0bc: /* GENERAL_PURPOSE4 */
case 0x0c0: /* GENERAL_PURPOSE5 */
case 0x0c4: /* GENERAL_PURPOSE6 */
case 0x0c8: /* GENERAL_PURPOSE7 */
case 0x0cc: /* GENERAL_PURPOSE8 */
case 0x0d0: /* GENERAL_PURPOSE9 */
case 0x0d4: /* GENERAL_PURPOSE10 */
case 0x0d8: /* GENERAL_PURPOSE11 */
case 0x0dc: /* GENERAL_PURPOSE12 */
case 0x0e0: /* GENERAL_PURPOSE13 */
case 0x0e4: /* GENERAL_PURPOSE14 */
case 0x0e8: /* GENERAL_PURPOSE15 */
case 0x0ec: /* GENERAL_PURPOSE16 */
case 0x0f0: /* GENERAL_PURPOSE17 */
case 0x0f4: /* GENERAL_PURPOSE18 */
case 0x0f8: /* GENERAL_PURPOSE19 */
case 0x0fc: /* GENERAL_PURPOSE20 */
s->scratch[(addr - 0xb0) >> 2] = value;
break;
case 0x140: /* CM_CLKSEL_MPU */
s->clksel[0] = value & 0x1f;
/* TODO update clocks */
break;
case 0x148: /* CM_CLKSTCTRL_MPU */
s->clkctrl[0] = value & 0x1f;
break;
case 0x158: /* RM_RSTST_MPU */
s->rst[0] &= ~value;
break;
case 0x1c8: /* PM_WKDEP_MPU */
s->wkup[0] = value & 0x15;
break;
case 0x1d4: /* PM_EVGENCTRL_MPU */
s->ev = value & 0x1f;
break;
case 0x1d8: /* PM_EVEGENONTIM_MPU */
s->evtime[0] = value;
break;
case 0x1dc: /* PM_EVEGENOFFTIM_MPU */
s->evtime[1] = value;
break;
case 0x1e0: /* PM_PWSTCTRL_MPU */
s->power[0] = value & 0xc0f;
break;
case 0x200: /* CM_FCLKEN1_CORE */
s->clken[0] = value & 0xbfffffff;
/* TODO update clocks */
/* The EN_EAC bit only gets/puts func_96m_clk. */
break;
case 0x204: /* CM_FCLKEN2_CORE */
s->clken[1] = value & 0x00000007;
/* TODO update clocks */
break;
case 0x210: /* CM_ICLKEN1_CORE */
s->clken[2] = value & 0xfffffff9;
/* TODO update clocks */
/* The EN_EAC bit only gets/puts core_l4_iclk. */
break;
case 0x214: /* CM_ICLKEN2_CORE */
s->clken[3] = value & 0x00000007;
/* TODO update clocks */
break;
case 0x21c: /* CM_ICLKEN4_CORE */
s->clken[4] = value & 0x0000001f;
/* TODO update clocks */
break;
case 0x230: /* CM_AUTOIDLE1_CORE */
s->clkidle[0] = value & 0xfffffff9;
/* TODO update clocks */
break;
case 0x234: /* CM_AUTOIDLE2_CORE */
s->clkidle[1] = value & 0x00000007;
/* TODO update clocks */
break;
case 0x238: /* CM_AUTOIDLE3_CORE */
s->clkidle[2] = value & 0x00000007;
/* TODO update clocks */
break;
case 0x23c: /* CM_AUTOIDLE4_CORE */
s->clkidle[3] = value & 0x0000001f;
/* TODO update clocks */
break;
case 0x240: /* CM_CLKSEL1_CORE */
s->clksel[1] = value & 0x0fffbf7f;
/* TODO update clocks */
break;
case 0x244: /* CM_CLKSEL2_CORE */
s->clksel[2] = value & 0x00fffffc;
/* TODO update clocks */
break;
case 0x248: /* CM_CLKSTCTRL_CORE */
s->clkctrl[1] = value & 0x7;
break;
case 0x2a0: /* PM_WKEN1_CORE */
s->wken[0] = value & 0x04667ff8;
break;
case 0x2a4: /* PM_WKEN2_CORE */
s->wken[1] = value & 0x00000005;
break;
case 0x2b0: /* PM_WKST1_CORE */
s->wkst[0] &= ~value;
break;
case 0x2b4: /* PM_WKST2_CORE */
s->wkst[1] &= ~value;
break;
case 0x2e0: /* PM_PWSTCTRL_CORE */
s->power[1] = (value & 0x00fc3f) | (1 << 2);
break;
case 0x300: /* CM_FCLKEN_GFX */
s->clken[5] = value & 6;
/* TODO update clocks */
break;
case 0x310: /* CM_ICLKEN_GFX */
s->clken[6] = value & 1;
/* TODO update clocks */
break;
case 0x340: /* CM_CLKSEL_GFX */
s->clksel[3] = value & 7;
/* TODO update clocks */
break;
case 0x348: /* CM_CLKSTCTRL_GFX */
s->clkctrl[2] = value & 1;
break;
case 0x350: /* RM_RSTCTRL_GFX */
s->rstctrl[0] = value & 1;
/* TODO: reset */
break;
case 0x358: /* RM_RSTST_GFX */
s->rst[1] &= ~value;
break;
case 0x3c8: /* PM_WKDEP_GFX */
s->wkup[1] = value & 0x13;
break;
case 0x3e0: /* PM_PWSTCTRL_GFX */
s->power[2] = (value & 0x00c0f) | (3 << 2);
break;
case 0x400: /* CM_FCLKEN_WKUP */
s->clken[7] = value & 0xd;
/* TODO update clocks */
break;
case 0x410: /* CM_ICLKEN_WKUP */
s->clken[8] = value & 0x3f;
/* TODO update clocks */
break;
case 0x430: /* CM_AUTOIDLE_WKUP */
s->clkidle[4] = value & 0x0000003f;
/* TODO update clocks */
break;
case 0x440: /* CM_CLKSEL_WKUP */
s->clksel[4] = value & 3;
/* TODO update clocks */
break;
case 0x450: /* RM_RSTCTRL_WKUP */
/* TODO: reset */
if (value & 2)
qemu_system_reset_request();
break;
case 0x454: /* RM_RSTTIME_WKUP */
s->rsttime_wkup = value & 0x1fff;
break;
case 0x458: /* RM_RSTST_WKUP */
s->rst[2] &= ~value;
break;
case 0x4a0: /* PM_WKEN_WKUP */
s->wken[2] = value & 0x00000005;
break;
case 0x4b0: /* PM_WKST_WKUP */
s->wkst[2] &= ~value;
break;
case 0x500: /* CM_CLKEN_PLL */
if (value & 0xffffff30)
fprintf(stderr, "%s: write 0s in CM_CLKEN_PLL for "
"future compatibility\n", __FUNCTION__);
if ((s->clken[9] ^ value) & 0xcc) {
s->clken[9] &= ~0xcc;
s->clken[9] |= value & 0xcc;
omap_prcm_apll_update(s);
}
if ((s->clken[9] ^ value) & 3) {
s->clken[9] &= ~3;
s->clken[9] |= value & 3;
omap_prcm_dpll_update(s);
}
break;
case 0x530: /* CM_AUTOIDLE_PLL */
s->clkidle[5] = value & 0x000000cf;
/* TODO update clocks */
break;
case 0x540: /* CM_CLKSEL1_PLL */
if (value & 0xfc4000d7)
fprintf(stderr, "%s: write 0s in CM_CLKSEL1_PLL for "
"future compatibility\n", __FUNCTION__);
if ((s->clksel[5] ^ value) & 0x003fff00) {
s->clksel[5] = value & 0x03bfff28;
omap_prcm_dpll_update(s);
}
/* TODO update the other clocks */
s->clksel[5] = value & 0x03bfff28;
break;
case 0x544: /* CM_CLKSEL2_PLL */
if (value & ~3)
fprintf(stderr, "%s: write 0s in CM_CLKSEL2_PLL[31:2] for "
"future compatibility\n", __FUNCTION__);
if (s->clksel[6] != (value & 3)) {
s->clksel[6] = value & 3;
omap_prcm_dpll_update(s);
}
break;
case 0x800: /* CM_FCLKEN_DSP */
s->clken[10] = value & 0x501;
/* TODO update clocks */
break;
case 0x810: /* CM_ICLKEN_DSP */
s->clken[11] = value & 0x2;
/* TODO update clocks */
break;
case 0x830: /* CM_AUTOIDLE_DSP */
s->clkidle[6] = value & 0x2;
/* TODO update clocks */
break;
case 0x840: /* CM_CLKSEL_DSP */
s->clksel[7] = value & 0x3fff;
/* TODO update clocks */
break;
case 0x848: /* CM_CLKSTCTRL_DSP */
s->clkctrl[3] = value & 0x101;
break;
case 0x850: /* RM_RSTCTRL_DSP */
/* TODO: reset */
break;
case 0x858: /* RM_RSTST_DSP */
s->rst[3] &= ~value;
break;
case 0x8c8: /* PM_WKDEP_DSP */
s->wkup[2] = value & 0x13;
break;
case 0x8e0: /* PM_PWSTCTRL_DSP */
s->power[3] = (value & 0x03017) | (3 << 2);
break;
case 0x8f0: /* PRCM_IRQSTATUS_DSP */
s->irqst[1] &= ~value;
omap_prcm_int_update(s, 1);
break;
case 0x8f4: /* PRCM_IRQENABLE_DSP */
s->irqen[1] = value & 0x7;
omap_prcm_int_update(s, 1);
break;
case 0x8f8: /* PRCM_IRQSTATUS_IVA */
s->irqst[2] &= ~value;
omap_prcm_int_update(s, 2);
break;
case 0x8fc: /* PRCM_IRQENABLE_IVA */
s->irqen[2] = value & 0x7;
omap_prcm_int_update(s, 2);
break;
default:
OMAP_BAD_REG(addr);
return;
}
}
static const MemoryRegionOps omap_prcm_ops = {
.read = omap_prcm_read,
.write = omap_prcm_write,
.endianness = DEVICE_NATIVE_ENDIAN,
};
static void omap_prcm_reset(struct omap_prcm_s *s)
{
s->sysconfig = 0;
s->irqst[0] = 0;
s->irqst[1] = 0;
s->irqst[2] = 0;
s->irqen[0] = 0;
s->irqen[1] = 0;
s->irqen[2] = 0;
s->voltctrl = 0x1040;
s->ev = 0x14;
s->evtime[0] = 0;
s->evtime[1] = 0;
s->clkctrl[0] = 0;
s->clkctrl[1] = 0;
s->clkctrl[2] = 0;
s->clkctrl[3] = 0;
s->clken[1] = 7;
s->clken[3] = 7;
s->clken[4] = 0;
s->clken[5] = 0;
s->clken[6] = 0;
s->clken[7] = 0xc;
s->clken[8] = 0x3e;
s->clken[9] = 0x0d;
s->clken[10] = 0;
s->clken[11] = 0;
s->clkidle[0] = 0;
s->clkidle[2] = 7;
s->clkidle[3] = 0;
s->clkidle[4] = 0;
s->clkidle[5] = 0x0c;
s->clkidle[6] = 0;
s->clksel[0] = 0x01;
s->clksel[1] = 0x02100121;
s->clksel[2] = 0x00000000;
s->clksel[3] = 0x01;
s->clksel[4] = 0;
s->clksel[7] = 0x0121;
s->wkup[0] = 0x15;
s->wkup[1] = 0x13;
s->wkup[2] = 0x13;
s->wken[0] = 0x04667ff8;
s->wken[1] = 0x00000005;
s->wken[2] = 5;
s->wkst[0] = 0;
s->wkst[1] = 0;
s->wkst[2] = 0;
s->power[0] = 0x00c;
s->power[1] = 4;
s->power[2] = 0x0000c;
s->power[3] = 0x14;
s->rstctrl[0] = 1;
s->rst[3] = 1;
omap_prcm_apll_update(s);
omap_prcm_dpll_update(s);
}
static void omap_prcm_coldreset(struct omap_prcm_s *s)
{
s->setuptime[0] = 0;
s->setuptime[1] = 0;
memset(&s->scratch, 0, sizeof(s->scratch));
s->rst[0] = 0x01;
s->rst[1] = 0x00;
s->rst[2] = 0x01;
s->clken[0] = 0;
s->clken[2] = 0;
s->clkidle[1] = 0;
s->clksel[5] = 0;
s->clksel[6] = 2;
s->clksrc[0] = 0x43;
s->clkout[0] = 0x0303;
s->clkemul[0] = 0;
s->clkpol[0] = 0x100;
s->rsttime_wkup = 0x1002;
omap_prcm_reset(s);
}
static struct omap_prcm_s *omap_prcm_init(struct omap_target_agent_s *ta,
qemu_irq mpu_int, qemu_irq dsp_int, qemu_irq iva_int,
struct omap_mpu_state_s *mpu)
{
struct omap_prcm_s *s = (struct omap_prcm_s *)
g_malloc0(sizeof(struct omap_prcm_s));
s->irq[0] = mpu_int;
s->irq[1] = dsp_int;
s->irq[2] = iva_int;
s->mpu = mpu;
omap_prcm_coldreset(s);
memory_region_init_io(&s->iomem0, &omap_prcm_ops, s, "omap.pcrm0",
omap_l4_region_size(ta, 0));
memory_region_init_io(&s->iomem1, &omap_prcm_ops, s, "omap.pcrm1",
omap_l4_region_size(ta, 1));
omap_l4_attach(ta, 0, &s->iomem0);
omap_l4_attach(ta, 1, &s->iomem1);
return s;
}
/* System and Pinout control */
struct omap_sysctl_s {
struct omap_mpu_state_s *mpu;
MemoryRegion iomem;
uint32_t sysconfig;
uint32_t devconfig;
uint32_t psaconfig;
uint32_t padconf[0x45];
uint8_t obs;
uint32_t msuspendmux[5];
};
static uint32_t omap_sysctl_read8(void *opaque, target_phys_addr_t addr)
{
struct omap_sysctl_s *s = (struct omap_sysctl_s *) opaque;
int pad_offset, byte_offset;
int value;
switch (addr) {
case 0x030 ... 0x140: /* CONTROL_PADCONF - only used in the POP */
pad_offset = (addr - 0x30) >> 2;
byte_offset = (addr - 0x30) & (4 - 1);
value = s->padconf[pad_offset];
value = (value >> (byte_offset * 8)) & 0xff;
return value;
default:
break;
}
OMAP_BAD_REG(addr);
return 0;
}
static uint32_t omap_sysctl_read(void *opaque, target_phys_addr_t addr)
{
struct omap_sysctl_s *s = (struct omap_sysctl_s *) opaque;
switch (addr) {
case 0x000: /* CONTROL_REVISION */
return 0x20;
case 0x010: /* CONTROL_SYSCONFIG */
return s->sysconfig;
case 0x030 ... 0x140: /* CONTROL_PADCONF - only used in the POP */
return s->padconf[(addr - 0x30) >> 2];
case 0x270: /* CONTROL_DEBOBS */
return s->obs;
case 0x274: /* CONTROL_DEVCONF */
return s->devconfig;
case 0x28c: /* CONTROL_EMU_SUPPORT */
return 0;
case 0x290: /* CONTROL_MSUSPENDMUX_0 */
return s->msuspendmux[0];
case 0x294: /* CONTROL_MSUSPENDMUX_1 */
return s->msuspendmux[1];
case 0x298: /* CONTROL_MSUSPENDMUX_2 */
return s->msuspendmux[2];
case 0x29c: /* CONTROL_MSUSPENDMUX_3 */
return s->msuspendmux[3];
case 0x2a0: /* CONTROL_MSUSPENDMUX_4 */
return s->msuspendmux[4];
case 0x2a4: /* CONTROL_MSUSPENDMUX_5 */
return 0;
case 0x2b8: /* CONTROL_PSA_CTRL */
return s->psaconfig;
case 0x2bc: /* CONTROL_PSA_CMD */
case 0x2c0: /* CONTROL_PSA_VALUE */
return 0;
case 0x2b0: /* CONTROL_SEC_CTRL */
return 0x800000f1;
case 0x2d0: /* CONTROL_SEC_EMU */
return 0x80000015;
case 0x2d4: /* CONTROL_SEC_TAP */
return 0x8000007f;
case 0x2b4: /* CONTROL_SEC_TEST */
case 0x2f0: /* CONTROL_SEC_STATUS */
case 0x2f4: /* CONTROL_SEC_ERR_STATUS */
/* Secure mode is not present on general-pusrpose device. Outside
* secure mode these values cannot be read or written. */
return 0;
case 0x2d8: /* CONTROL_OCM_RAM_PERM */
return 0xff;
case 0x2dc: /* CONTROL_OCM_PUB_RAM_ADD */
case 0x2e0: /* CONTROL_EXT_SEC_RAM_START_ADD */
case 0x2e4: /* CONTROL_EXT_SEC_RAM_STOP_ADD */
/* No secure mode so no Extended Secure RAM present. */
return 0;
case 0x2f8: /* CONTROL_STATUS */
/* Device Type => General-purpose */
return 0x0300;
case 0x2fc: /* CONTROL_GENERAL_PURPOSE_STATUS */
case 0x300: /* CONTROL_RPUB_KEY_H_0 */
case 0x304: /* CONTROL_RPUB_KEY_H_1 */
case 0x308: /* CONTROL_RPUB_KEY_H_2 */
case 0x30c: /* CONTROL_RPUB_KEY_H_3 */
return 0xdecafbad;
case 0x310: /* CONTROL_RAND_KEY_0 */
case 0x314: /* CONTROL_RAND_KEY_1 */
case 0x318: /* CONTROL_RAND_KEY_2 */
case 0x31c: /* CONTROL_RAND_KEY_3 */
case 0x320: /* CONTROL_CUST_KEY_0 */
case 0x324: /* CONTROL_CUST_KEY_1 */
case 0x330: /* CONTROL_TEST_KEY_0 */
case 0x334: /* CONTROL_TEST_KEY_1 */
case 0x338: /* CONTROL_TEST_KEY_2 */
case 0x33c: /* CONTROL_TEST_KEY_3 */
case 0x340: /* CONTROL_TEST_KEY_4 */
case 0x344: /* CONTROL_TEST_KEY_5 */
case 0x348: /* CONTROL_TEST_KEY_6 */
case 0x34c: /* CONTROL_TEST_KEY_7 */
case 0x350: /* CONTROL_TEST_KEY_8 */
case 0x354: /* CONTROL_TEST_KEY_9 */
/* Can only be accessed in secure mode and when C_FieldAccEnable
* bit is set in CONTROL_SEC_CTRL.
* TODO: otherwise an interconnect access error is generated. */
return 0;
}
OMAP_BAD_REG(addr);
return 0;
}
static void omap_sysctl_write8(void *opaque, target_phys_addr_t addr,
uint32_t value)
{
struct omap_sysctl_s *s = (struct omap_sysctl_s *) opaque;
int pad_offset, byte_offset;
int prev_value;
switch (addr) {
case 0x030 ... 0x140: /* CONTROL_PADCONF - only used in the POP */
pad_offset = (addr - 0x30) >> 2;
byte_offset = (addr - 0x30) & (4 - 1);
prev_value = s->padconf[pad_offset];
prev_value &= ~(0xff << (byte_offset * 8));
prev_value |= ((value & 0x1f1f1f1f) << (byte_offset * 8)) & 0x1f1f1f1f;
s->padconf[pad_offset] = prev_value;
break;
default:
OMAP_BAD_REG(addr);
break;
}
}
static void omap_sysctl_write(void *opaque, target_phys_addr_t addr,
uint32_t value)
{
struct omap_sysctl_s *s = (struct omap_sysctl_s *) opaque;
switch (addr) {
case 0x000: /* CONTROL_REVISION */
case 0x2a4: /* CONTROL_MSUSPENDMUX_5 */
case 0x2c0: /* CONTROL_PSA_VALUE */
case 0x2f8: /* CONTROL_STATUS */
case 0x2fc: /* CONTROL_GENERAL_PURPOSE_STATUS */
case 0x300: /* CONTROL_RPUB_KEY_H_0 */
case 0x304: /* CONTROL_RPUB_KEY_H_1 */
case 0x308: /* CONTROL_RPUB_KEY_H_2 */
case 0x30c: /* CONTROL_RPUB_KEY_H_3 */
case 0x310: /* CONTROL_RAND_KEY_0 */
case 0x314: /* CONTROL_RAND_KEY_1 */
case 0x318: /* CONTROL_RAND_KEY_2 */
case 0x31c: /* CONTROL_RAND_KEY_3 */
case 0x320: /* CONTROL_CUST_KEY_0 */
case 0x324: /* CONTROL_CUST_KEY_1 */
case 0x330: /* CONTROL_TEST_KEY_0 */
case 0x334: /* CONTROL_TEST_KEY_1 */
case 0x338: /* CONTROL_TEST_KEY_2 */
case 0x33c: /* CONTROL_TEST_KEY_3 */
case 0x340: /* CONTROL_TEST_KEY_4 */
case 0x344: /* CONTROL_TEST_KEY_5 */
case 0x348: /* CONTROL_TEST_KEY_6 */
case 0x34c: /* CONTROL_TEST_KEY_7 */
case 0x350: /* CONTROL_TEST_KEY_8 */
case 0x354: /* CONTROL_TEST_KEY_9 */
OMAP_RO_REG(addr);
return;
case 0x010: /* CONTROL_SYSCONFIG */
s->sysconfig = value & 0x1e;
break;
case 0x030 ... 0x140: /* CONTROL_PADCONF - only used in the POP */
/* XXX: should check constant bits */
s->padconf[(addr - 0x30) >> 2] = value & 0x1f1f1f1f;
break;
case 0x270: /* CONTROL_DEBOBS */
s->obs = value & 0xff;
break;
case 0x274: /* CONTROL_DEVCONF */
s->devconfig = value & 0xffffc7ff;
break;
case 0x28c: /* CONTROL_EMU_SUPPORT */
break;
case 0x290: /* CONTROL_MSUSPENDMUX_0 */
s->msuspendmux[0] = value & 0x3fffffff;
break;
case 0x294: /* CONTROL_MSUSPENDMUX_1 */
s->msuspendmux[1] = value & 0x3fffffff;
break;
case 0x298: /* CONTROL_MSUSPENDMUX_2 */
s->msuspendmux[2] = value & 0x3fffffff;
break;
case 0x29c: /* CONTROL_MSUSPENDMUX_3 */
s->msuspendmux[3] = value & 0x3fffffff;
break;
case 0x2a0: /* CONTROL_MSUSPENDMUX_4 */
s->msuspendmux[4] = value & 0x3fffffff;
break;
case 0x2b8: /* CONTROL_PSA_CTRL */
s->psaconfig = value & 0x1c;
s->psaconfig |= (value & 0x20) ? 2 : 1;
break;
case 0x2bc: /* CONTROL_PSA_CMD */
break;
case 0x2b0: /* CONTROL_SEC_CTRL */
case 0x2b4: /* CONTROL_SEC_TEST */
case 0x2d0: /* CONTROL_SEC_EMU */
case 0x2d4: /* CONTROL_SEC_TAP */
case 0x2d8: /* CONTROL_OCM_RAM_PERM */
case 0x2dc: /* CONTROL_OCM_PUB_RAM_ADD */
case 0x2e0: /* CONTROL_EXT_SEC_RAM_START_ADD */
case 0x2e4: /* CONTROL_EXT_SEC_RAM_STOP_ADD */
case 0x2f0: /* CONTROL_SEC_STATUS */
case 0x2f4: /* CONTROL_SEC_ERR_STATUS */
break;
default:
OMAP_BAD_REG(addr);
return;
}
}
static const MemoryRegionOps omap_sysctl_ops = {
.old_mmio = {
.read = {
omap_sysctl_read8,
omap_badwidth_read32, /* TODO */
omap_sysctl_read,
},
.write = {
omap_sysctl_write8,
omap_badwidth_write32, /* TODO */
omap_sysctl_write,
},
},
.endianness = DEVICE_NATIVE_ENDIAN,
};
static void omap_sysctl_reset(struct omap_sysctl_s *s)
{
/* (power-on reset) */
s->sysconfig = 0;
s->obs = 0;
s->devconfig = 0x0c000000;
s->msuspendmux[0] = 0x00000000;
s->msuspendmux[1] = 0x00000000;
s->msuspendmux[2] = 0x00000000;
s->msuspendmux[3] = 0x00000000;
s->msuspendmux[4] = 0x00000000;
s->psaconfig = 1;
s->padconf[0x00] = 0x000f0f0f;
s->padconf[0x01] = 0x00000000;
s->padconf[0x02] = 0x00000000;
s->padconf[0x03] = 0x00000000;
s->padconf[0x04] = 0x00000000;
s->padconf[0x05] = 0x00000000;
s->padconf[0x06] = 0x00000000;
s->padconf[0x07] = 0x00000000;
s->padconf[0x08] = 0x08080800;
s->padconf[0x09] = 0x08080808;
s->padconf[0x0a] = 0x08080808;
s->padconf[0x0b] = 0x08080808;
s->padconf[0x0c] = 0x08080808;
s->padconf[0x0d] = 0x08080800;
s->padconf[0x0e] = 0x08080808;
s->padconf[0x0f] = 0x08080808;
s->padconf[0x10] = 0x18181808; /* | 0x07070700 if SBoot3 */
s->padconf[0x11] = 0x18181818; /* | 0x07070707 if SBoot3 */
s->padconf[0x12] = 0x18181818; /* | 0x07070707 if SBoot3 */
s->padconf[0x13] = 0x18181818; /* | 0x07070707 if SBoot3 */
s->padconf[0x14] = 0x18181818; /* | 0x00070707 if SBoot3 */
s->padconf[0x15] = 0x18181818;
s->padconf[0x16] = 0x18181818; /* | 0x07000000 if SBoot3 */
s->padconf[0x17] = 0x1f001f00;
s->padconf[0x18] = 0x1f1f1f1f;
s->padconf[0x19] = 0x00000000;
s->padconf[0x1a] = 0x1f180000;
s->padconf[0x1b] = 0x00001f1f;
s->padconf[0x1c] = 0x1f001f00;
s->padconf[0x1d] = 0x00000000;
s->padconf[0x1e] = 0x00000000;
s->padconf[0x1f] = 0x08000000;
s->padconf[0x20] = 0x08080808;
s->padconf[0x21] = 0x08080808;
s->padconf[0x22] = 0x0f080808;
s->padconf[0x23] = 0x0f0f0f0f;
s->padconf[0x24] = 0x000f0f0f;
s->padconf[0x25] = 0x1f1f1f0f;
s->padconf[0x26] = 0x080f0f1f;
s->padconf[0x27] = 0x070f1808;
s->padconf[0x28] = 0x0f070707;
s->padconf[0x29] = 0x000f0f1f;
s->padconf[0x2a] = 0x0f0f0f1f;
s->padconf[0x2b] = 0x08000000;
s->padconf[0x2c] = 0x0000001f;
s->padconf[0x2d] = 0x0f0f1f00;
s->padconf[0x2e] = 0x1f1f0f0f;
s->padconf[0x2f] = 0x0f1f1f1f;
s->padconf[0x30] = 0x0f0f0f0f;
s->padconf[0x31] = 0x0f1f0f1f;
s->padconf[0x32] = 0x0f0f0f0f;
s->padconf[0x33] = 0x0f1f0f1f;
s->padconf[0x34] = 0x1f1f0f0f;
s->padconf[0x35] = 0x0f0f1f1f;
s->padconf[0x36] = 0x0f0f1f0f;
s->padconf[0x37] = 0x0f0f0f0f;
s->padconf[0x38] = 0x1f18180f;
s->padconf[0x39] = 0x1f1f1f1f;
s->padconf[0x3a] = 0x00001f1f;
s->padconf[0x3b] = 0x00000000;
s->padconf[0x3c] = 0x00000000;
s->padconf[0x3d] = 0x0f0f0f0f;
s->padconf[0x3e] = 0x18000f0f;
s->padconf[0x3f] = 0x00070000;
s->padconf[0x40] = 0x00000707;
s->padconf[0x41] = 0x0f1f0700;
s->padconf[0x42] = 0x1f1f070f;
s->padconf[0x43] = 0x0008081f;
s->padconf[0x44] = 0x00000800;
}
static struct omap_sysctl_s *omap_sysctl_init(struct omap_target_agent_s *ta,
omap_clk iclk, struct omap_mpu_state_s *mpu)
{
struct omap_sysctl_s *s = (struct omap_sysctl_s *)
g_malloc0(sizeof(struct omap_sysctl_s));
s->mpu = mpu;
omap_sysctl_reset(s);
memory_region_init_io(&s->iomem, &omap_sysctl_ops, s, "omap.sysctl",
omap_l4_region_size(ta, 0));
omap_l4_attach(ta, 0, &s->iomem);
return s;
}
/* General chip reset */
static void omap2_mpu_reset(void *opaque)
{
struct omap_mpu_state_s *mpu = (struct omap_mpu_state_s *) opaque;
omap_dma_reset(mpu->dma);
omap_prcm_reset(mpu->prcm);
omap_sysctl_reset(mpu->sysc);
omap_gp_timer_reset(mpu->gptimer[0]);
omap_gp_timer_reset(mpu->gptimer[1]);
omap_gp_timer_reset(mpu->gptimer[2]);
omap_gp_timer_reset(mpu->gptimer[3]);
omap_gp_timer_reset(mpu->gptimer[4]);
omap_gp_timer_reset(mpu->gptimer[5]);
omap_gp_timer_reset(mpu->gptimer[6]);
omap_gp_timer_reset(mpu->gptimer[7]);
omap_gp_timer_reset(mpu->gptimer[8]);
omap_gp_timer_reset(mpu->gptimer[9]);
omap_gp_timer_reset(mpu->gptimer[10]);
omap_gp_timer_reset(mpu->gptimer[11]);
omap_synctimer_reset(mpu->synctimer);
omap_sdrc_reset(mpu->sdrc);
omap_gpmc_reset(mpu->gpmc);
omap_dss_reset(mpu->dss);
omap_uart_reset(mpu->uart[0]);
omap_uart_reset(mpu->uart[1]);
omap_uart_reset(mpu->uart[2]);
omap_mmc_reset(mpu->mmc);
omap_mcspi_reset(mpu->mcspi[0]);
omap_mcspi_reset(mpu->mcspi[1]);
cpu_state_reset(mpu->env);
}
static int omap2_validate_addr(struct omap_mpu_state_s *s,
target_phys_addr_t addr)
{
return 1;
}
static const struct dma_irq_map omap2_dma_irq_map[] = {
{ 0, OMAP_INT_24XX_SDMA_IRQ0 },
{ 0, OMAP_INT_24XX_SDMA_IRQ1 },
{ 0, OMAP_INT_24XX_SDMA_IRQ2 },
{ 0, OMAP_INT_24XX_SDMA_IRQ3 },
};
struct omap_mpu_state_s *omap2420_mpu_init(MemoryRegion *sysmem,
unsigned long sdram_size,
const char *core)
{
struct omap_mpu_state_s *s = (struct omap_mpu_state_s *)
g_malloc0(sizeof(struct omap_mpu_state_s));
qemu_irq *cpu_irq;
qemu_irq dma_irqs[4];
DriveInfo *dinfo;
int i;
SysBusDevice *busdev;
struct omap_target_agent_s *ta;
/* Core */
s->mpu_model = omap2420;
s->env = cpu_init(core ?: "arm1136-r2");
if (!s->env) {
fprintf(stderr, "Unable to find CPU definition\n");
exit(1);
}
s->sdram_size = sdram_size;
s->sram_size = OMAP242X_SRAM_SIZE;
s->wakeup = qemu_allocate_irqs(omap_mpu_wakeup, s, 1)[0];
/* Clocks */
omap_clk_init(s);
/* Memory-mapped stuff */
memory_region_init_ram(&s->sdram, "omap2.dram", s->sdram_size);
vmstate_register_ram_global(&s->sdram);
memory_region_add_subregion(sysmem, OMAP2_Q2_BASE, &s->sdram);
memory_region_init_ram(&s->sram, "omap2.sram", s->sram_size);
vmstate_register_ram_global(&s->sram);
memory_region_add_subregion(sysmem, OMAP2_SRAM_BASE, &s->sram);
s->l4 = omap_l4_init(sysmem, OMAP2_L4_BASE, 54);
/* Actually mapped at any 2K boundary in the ARM11 private-peripheral if */
cpu_irq = arm_pic_init_cpu(s->env);
s->ih[0] = qdev_create(NULL, "omap2-intc");
qdev_prop_set_uint8(s->ih[0], "revision", 0x21);
qdev_prop_set_ptr(s->ih[0], "fclk", omap_findclk(s, "mpu_intc_fclk"));
qdev_prop_set_ptr(s->ih[0], "iclk", omap_findclk(s, "mpu_intc_iclk"));
qdev_init_nofail(s->ih[0]);
busdev = sysbus_from_qdev(s->ih[0]);
sysbus_connect_irq(busdev, 0, cpu_irq[ARM_PIC_CPU_IRQ]);
sysbus_connect_irq(busdev, 1, cpu_irq[ARM_PIC_CPU_FIQ]);
sysbus_mmio_map(busdev, 0, 0x480fe000);
s->prcm = omap_prcm_init(omap_l4tao(s->l4, 3),
qdev_get_gpio_in(s->ih[0],
OMAP_INT_24XX_PRCM_MPU_IRQ),
NULL, NULL, s);
s->sysc = omap_sysctl_init(omap_l4tao(s->l4, 1),
omap_findclk(s, "omapctrl_iclk"), s);
for (i = 0; i < 4; i++) {
dma_irqs[i] = qdev_get_gpio_in(s->ih[omap2_dma_irq_map[i].ih],
omap2_dma_irq_map[i].intr);
}
s->dma = omap_dma4_init(0x48056000, dma_irqs, sysmem, s, 256, 32,
omap_findclk(s, "sdma_iclk"),
omap_findclk(s, "sdma_fclk"));
s->port->addr_valid = omap2_validate_addr;
/* Register SDRAM and SRAM ports for fast DMA transfers. */
soc_dma_port_add_mem(s->dma, memory_region_get_ram_ptr(&s->sdram),
OMAP2_Q2_BASE, s->sdram_size);
soc_dma_port_add_mem(s->dma, memory_region_get_ram_ptr(&s->sram),
OMAP2_SRAM_BASE, s->sram_size);
s->uart[0] = omap2_uart_init(sysmem, omap_l4ta(s->l4, 19),
qdev_get_gpio_in(s->ih[0],
OMAP_INT_24XX_UART1_IRQ),
omap_findclk(s, "uart1_fclk"),
omap_findclk(s, "uart1_iclk"),
s->drq[OMAP24XX_DMA_UART1_TX],
s->drq[OMAP24XX_DMA_UART1_RX],
"uart1",
serial_hds[0]);
s->uart[1] = omap2_uart_init(sysmem, omap_l4ta(s->l4, 20),
qdev_get_gpio_in(s->ih[0],
OMAP_INT_24XX_UART2_IRQ),
omap_findclk(s, "uart2_fclk"),
omap_findclk(s, "uart2_iclk"),
s->drq[OMAP24XX_DMA_UART2_TX],
s->drq[OMAP24XX_DMA_UART2_RX],
"uart2",
serial_hds[0] ? serial_hds[1] : NULL);
s->uart[2] = omap2_uart_init(sysmem, omap_l4ta(s->l4, 21),
qdev_get_gpio_in(s->ih[0],
OMAP_INT_24XX_UART3_IRQ),
omap_findclk(s, "uart3_fclk"),
omap_findclk(s, "uart3_iclk"),
s->drq[OMAP24XX_DMA_UART3_TX],
s->drq[OMAP24XX_DMA_UART3_RX],
"uart3",
serial_hds[0] && serial_hds[1] ? serial_hds[2] : NULL);
s->gptimer[0] = omap_gp_timer_init(omap_l4ta(s->l4, 7),
qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER1),
omap_findclk(s, "wu_gpt1_clk"),
omap_findclk(s, "wu_l4_iclk"));
s->gptimer[1] = omap_gp_timer_init(omap_l4ta(s->l4, 8),
qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER2),
omap_findclk(s, "core_gpt2_clk"),
omap_findclk(s, "core_l4_iclk"));
s->gptimer[2] = omap_gp_timer_init(omap_l4ta(s->l4, 22),
qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER3),
omap_findclk(s, "core_gpt3_clk"),
omap_findclk(s, "core_l4_iclk"));
s->gptimer[3] = omap_gp_timer_init(omap_l4ta(s->l4, 23),
qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER4),
omap_findclk(s, "core_gpt4_clk"),
omap_findclk(s, "core_l4_iclk"));
s->gptimer[4] = omap_gp_timer_init(omap_l4ta(s->l4, 24),
qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER5),
omap_findclk(s, "core_gpt5_clk"),
omap_findclk(s, "core_l4_iclk"));
s->gptimer[5] = omap_gp_timer_init(omap_l4ta(s->l4, 25),
qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER6),
omap_findclk(s, "core_gpt6_clk"),
omap_findclk(s, "core_l4_iclk"));
s->gptimer[6] = omap_gp_timer_init(omap_l4ta(s->l4, 26),
qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER7),
omap_findclk(s, "core_gpt7_clk"),
omap_findclk(s, "core_l4_iclk"));
s->gptimer[7] = omap_gp_timer_init(omap_l4ta(s->l4, 27),
qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER8),
omap_findclk(s, "core_gpt8_clk"),
omap_findclk(s, "core_l4_iclk"));
s->gptimer[8] = omap_gp_timer_init(omap_l4ta(s->l4, 28),
qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER9),
omap_findclk(s, "core_gpt9_clk"),
omap_findclk(s, "core_l4_iclk"));
s->gptimer[9] = omap_gp_timer_init(omap_l4ta(s->l4, 29),
qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER10),
omap_findclk(s, "core_gpt10_clk"),
omap_findclk(s, "core_l4_iclk"));
s->gptimer[10] = omap_gp_timer_init(omap_l4ta(s->l4, 30),
qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER11),
omap_findclk(s, "core_gpt11_clk"),
omap_findclk(s, "core_l4_iclk"));
s->gptimer[11] = omap_gp_timer_init(omap_l4ta(s->l4, 31),
qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPTIMER12),
omap_findclk(s, "core_gpt12_clk"),
omap_findclk(s, "core_l4_iclk"));
omap_tap_init(omap_l4ta(s->l4, 2), s);
s->synctimer = omap_synctimer_init(omap_l4tao(s->l4, 2), s,
omap_findclk(s, "clk32-kHz"),
omap_findclk(s, "core_l4_iclk"));
s->i2c[0] = qdev_create(NULL, "omap_i2c");
qdev_prop_set_uint8(s->i2c[0], "revision", 0x34);
qdev_prop_set_ptr(s->i2c[0], "iclk", omap_findclk(s, "i2c1.iclk"));
qdev_prop_set_ptr(s->i2c[0], "fclk", omap_findclk(s, "i2c1.fclk"));
qdev_init_nofail(s->i2c[0]);
busdev = sysbus_from_qdev(s->i2c[0]);
sysbus_connect_irq(busdev, 0,
qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_I2C1_IRQ));
sysbus_connect_irq(busdev, 1, s->drq[OMAP24XX_DMA_I2C1_TX]);
sysbus_connect_irq(busdev, 2, s->drq[OMAP24XX_DMA_I2C1_RX]);
sysbus_mmio_map(busdev, 0, omap_l4_region_base(omap_l4tao(s->l4, 5), 0));
s->i2c[1] = qdev_create(NULL, "omap_i2c");
qdev_prop_set_uint8(s->i2c[1], "revision", 0x34);
qdev_prop_set_ptr(s->i2c[1], "iclk", omap_findclk(s, "i2c2.iclk"));
qdev_prop_set_ptr(s->i2c[1], "fclk", omap_findclk(s, "i2c2.fclk"));
qdev_init_nofail(s->i2c[1]);
busdev = sysbus_from_qdev(s->i2c[1]);
sysbus_connect_irq(busdev, 0,
qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_I2C2_IRQ));
sysbus_connect_irq(busdev, 1, s->drq[OMAP24XX_DMA_I2C2_TX]);
sysbus_connect_irq(busdev, 2, s->drq[OMAP24XX_DMA_I2C2_RX]);
sysbus_mmio_map(busdev, 0, omap_l4_region_base(omap_l4tao(s->l4, 6), 0));
s->gpio = qdev_create(NULL, "omap2-gpio");
qdev_prop_set_int32(s->gpio, "mpu_model", s->mpu_model);
qdev_prop_set_ptr(s->gpio, "iclk", omap_findclk(s, "gpio_iclk"));
qdev_prop_set_ptr(s->gpio, "fclk0", omap_findclk(s, "gpio1_dbclk"));
qdev_prop_set_ptr(s->gpio, "fclk1", omap_findclk(s, "gpio2_dbclk"));
qdev_prop_set_ptr(s->gpio, "fclk2", omap_findclk(s, "gpio3_dbclk"));
qdev_prop_set_ptr(s->gpio, "fclk3", omap_findclk(s, "gpio4_dbclk"));
if (s->mpu_model == omap2430) {
qdev_prop_set_ptr(s->gpio, "fclk4", omap_findclk(s, "gpio5_dbclk"));
}
qdev_init_nofail(s->gpio);
busdev = sysbus_from_qdev(s->gpio);
sysbus_connect_irq(busdev, 0,
qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPIO_BANK1));
sysbus_connect_irq(busdev, 3,
qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPIO_BANK2));
sysbus_connect_irq(busdev, 6,
qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPIO_BANK3));
sysbus_connect_irq(busdev, 9,
qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPIO_BANK4));
if (s->mpu_model == omap2430) {
sysbus_connect_irq(busdev, 12,
qdev_get_gpio_in(s->ih[0],
OMAP_INT_243X_GPIO_BANK5));
}
ta = omap_l4ta(s->l4, 3);
sysbus_mmio_map(busdev, 0, omap_l4_region_base(ta, 1));
sysbus_mmio_map(busdev, 1, omap_l4_region_base(ta, 0));
sysbus_mmio_map(busdev, 2, omap_l4_region_base(ta, 2));
sysbus_mmio_map(busdev, 3, omap_l4_region_base(ta, 4));
sysbus_mmio_map(busdev, 4, omap_l4_region_base(ta, 5));
s->sdrc = omap_sdrc_init(sysmem, 0x68009000);
s->gpmc = omap_gpmc_init(s, 0x6800a000,
qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_GPMC_IRQ),
s->drq[OMAP24XX_DMA_GPMC]);
dinfo = drive_get(IF_SD, 0, 0);
if (!dinfo) {
fprintf(stderr, "qemu: missing SecureDigital device\n");
exit(1);
}
s->mmc = omap2_mmc_init(omap_l4tao(s->l4, 9), dinfo->bdrv,
qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_MMC_IRQ),
&s->drq[OMAP24XX_DMA_MMC1_TX],
omap_findclk(s, "mmc_fclk"), omap_findclk(s, "mmc_iclk"));
s->mcspi[0] = omap_mcspi_init(omap_l4ta(s->l4, 35), 4,
qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_MCSPI1_IRQ),
&s->drq[OMAP24XX_DMA_SPI1_TX0],
omap_findclk(s, "spi1_fclk"),
omap_findclk(s, "spi1_iclk"));
s->mcspi[1] = omap_mcspi_init(omap_l4ta(s->l4, 36), 2,
qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_MCSPI2_IRQ),
&s->drq[OMAP24XX_DMA_SPI2_TX0],
omap_findclk(s, "spi2_fclk"),
omap_findclk(s, "spi2_iclk"));
s->dss = omap_dss_init(omap_l4ta(s->l4, 10), sysmem, 0x68000800,
/* XXX wire M_IRQ_25, D_L2_IRQ_30 and I_IRQ_13 together */
qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_DSS_IRQ),
s->drq[OMAP24XX_DMA_DSS],
omap_findclk(s, "dss_clk1"), omap_findclk(s, "dss_clk2"),
omap_findclk(s, "dss_54m_clk"),
omap_findclk(s, "dss_l3_iclk"),
omap_findclk(s, "dss_l4_iclk"));
omap_sti_init(omap_l4ta(s->l4, 18), sysmem, 0x54000000,
qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_STI),
omap_findclk(s, "emul_ck"),
serial_hds[0] && serial_hds[1] && serial_hds[2] ?
serial_hds[3] : NULL);
s->eac = omap_eac_init(omap_l4ta(s->l4, 32),
qdev_get_gpio_in(s->ih[0], OMAP_INT_24XX_EAC_IRQ),
/* Ten consecutive lines */
&s->drq[OMAP24XX_DMA_EAC_AC_RD],
omap_findclk(s, "func_96m_clk"),
omap_findclk(s, "core_l4_iclk"));
/* All register mappings (includin those not currenlty implemented):
* SystemControlMod 48000000 - 48000fff
* SystemControlL4 48001000 - 48001fff
* 32kHz Timer Mod 48004000 - 48004fff
* 32kHz Timer L4 48005000 - 48005fff
* PRCM ModA 48008000 - 480087ff
* PRCM ModB 48008800 - 48008fff
* PRCM L4 48009000 - 48009fff
* TEST-BCM Mod 48012000 - 48012fff
* TEST-BCM L4 48013000 - 48013fff
* TEST-TAP Mod 48014000 - 48014fff
* TEST-TAP L4 48015000 - 48015fff
* GPIO1 Mod 48018000 - 48018fff
* GPIO Top 48019000 - 48019fff
* GPIO2 Mod 4801a000 - 4801afff
* GPIO L4 4801b000 - 4801bfff
* GPIO3 Mod 4801c000 - 4801cfff
* GPIO4 Mod 4801e000 - 4801efff
* WDTIMER1 Mod 48020000 - 48010fff
* WDTIMER Top 48021000 - 48011fff
* WDTIMER2 Mod 48022000 - 48012fff
* WDTIMER L4 48023000 - 48013fff
* WDTIMER3 Mod 48024000 - 48014fff
* WDTIMER3 L4 48025000 - 48015fff
* WDTIMER4 Mod 48026000 - 48016fff
* WDTIMER4 L4 48027000 - 48017fff
* GPTIMER1 Mod 48028000 - 48018fff
* GPTIMER1 L4 48029000 - 48019fff
* GPTIMER2 Mod 4802a000 - 4801afff
* GPTIMER2 L4 4802b000 - 4801bfff
* L4-Config AP 48040000 - 480407ff
* L4-Config IP 48040800 - 48040fff
* L4-Config LA 48041000 - 48041fff
* ARM11ETB Mod 48048000 - 48049fff
* ARM11ETB L4 4804a000 - 4804afff
* DISPLAY Top 48050000 - 480503ff
* DISPLAY DISPC 48050400 - 480507ff
* DISPLAY RFBI 48050800 - 48050bff
* DISPLAY VENC 48050c00 - 48050fff
* DISPLAY L4 48051000 - 48051fff
* CAMERA Top 48052000 - 480523ff
* CAMERA core 48052400 - 480527ff
* CAMERA DMA 48052800 - 48052bff
* CAMERA MMU 48052c00 - 48052fff
* CAMERA L4 48053000 - 48053fff
* SDMA Mod 48056000 - 48056fff
* SDMA L4 48057000 - 48057fff
* SSI Top 48058000 - 48058fff
* SSI GDD 48059000 - 48059fff
* SSI Port1 4805a000 - 4805afff
* SSI Port2 4805b000 - 4805bfff
* SSI L4 4805c000 - 4805cfff
* USB Mod 4805e000 - 480fefff
* USB L4 4805f000 - 480fffff
* WIN_TRACER1 Mod 48060000 - 48060fff
* WIN_TRACER1 L4 48061000 - 48061fff
* WIN_TRACER2 Mod 48062000 - 48062fff
* WIN_TRACER2 L4 48063000 - 48063fff
* WIN_TRACER3 Mod 48064000 - 48064fff
* WIN_TRACER3 L4 48065000 - 48065fff
* WIN_TRACER4 Top 48066000 - 480660ff
* WIN_TRACER4 ETT 48066100 - 480661ff
* WIN_TRACER4 WT 48066200 - 480662ff
* WIN_TRACER4 L4 48067000 - 48067fff
* XTI Mod 48068000 - 48068fff
* XTI L4 48069000 - 48069fff
* UART1 Mod 4806a000 - 4806afff
* UART1 L4 4806b000 - 4806bfff
* UART2 Mod 4806c000 - 4806cfff
* UART2 L4 4806d000 - 4806dfff
* UART3 Mod 4806e000 - 4806efff
* UART3 L4 4806f000 - 4806ffff
* I2C1 Mod 48070000 - 48070fff
* I2C1 L4 48071000 - 48071fff
* I2C2 Mod 48072000 - 48072fff
* I2C2 L4 48073000 - 48073fff
* McBSP1 Mod 48074000 - 48074fff
* McBSP1 L4 48075000 - 48075fff
* McBSP2 Mod 48076000 - 48076fff
* McBSP2 L4 48077000 - 48077fff
* GPTIMER3 Mod 48078000 - 48078fff
* GPTIMER3 L4 48079000 - 48079fff
* GPTIMER4 Mod 4807a000 - 4807afff
* GPTIMER4 L4 4807b000 - 4807bfff
* GPTIMER5 Mod 4807c000 - 4807cfff
* GPTIMER5 L4 4807d000 - 4807dfff
* GPTIMER6 Mod 4807e000 - 4807efff
* GPTIMER6 L4 4807f000 - 4807ffff
* GPTIMER7 Mod 48080000 - 48080fff
* GPTIMER7 L4 48081000 - 48081fff
* GPTIMER8 Mod 48082000 - 48082fff
* GPTIMER8 L4 48083000 - 48083fff
* GPTIMER9 Mod 48084000 - 48084fff
* GPTIMER9 L4 48085000 - 48085fff
* GPTIMER10 Mod 48086000 - 48086fff
* GPTIMER10 L4 48087000 - 48087fff
* GPTIMER11 Mod 48088000 - 48088fff
* GPTIMER11 L4 48089000 - 48089fff
* GPTIMER12 Mod 4808a000 - 4808afff
* GPTIMER12 L4 4808b000 - 4808bfff
* EAC Mod 48090000 - 48090fff
* EAC L4 48091000 - 48091fff
* FAC Mod 48092000 - 48092fff
* FAC L4 48093000 - 48093fff
* MAILBOX Mod 48094000 - 48094fff
* MAILBOX L4 48095000 - 48095fff
* SPI1 Mod 48098000 - 48098fff
* SPI1 L4 48099000 - 48099fff
* SPI2 Mod 4809a000 - 4809afff
* SPI2 L4 4809b000 - 4809bfff
* MMC/SDIO Mod 4809c000 - 4809cfff
* MMC/SDIO L4 4809d000 - 4809dfff
* MS_PRO Mod 4809e000 - 4809efff
* MS_PRO L4 4809f000 - 4809ffff
* RNG Mod 480a0000 - 480a0fff
* RNG L4 480a1000 - 480a1fff
* DES3DES Mod 480a2000 - 480a2fff
* DES3DES L4 480a3000 - 480a3fff
* SHA1MD5 Mod 480a4000 - 480a4fff
* SHA1MD5 L4 480a5000 - 480a5fff
* AES Mod 480a6000 - 480a6fff
* AES L4 480a7000 - 480a7fff
* PKA Mod 480a8000 - 480a9fff
* PKA L4 480aa000 - 480aafff
* MG Mod 480b0000 - 480b0fff
* MG L4 480b1000 - 480b1fff
* HDQ/1-wire Mod 480b2000 - 480b2fff
* HDQ/1-wire L4 480b3000 - 480b3fff
* MPU interrupt 480fe000 - 480fefff
* STI channel base 54000000 - 5400ffff
* IVA RAM 5c000000 - 5c01ffff
* IVA ROM 5c020000 - 5c027fff
* IMG_BUF_A 5c040000 - 5c040fff
* IMG_BUF_B 5c042000 - 5c042fff
* VLCDS 5c048000 - 5c0487ff
* IMX_COEF 5c049000 - 5c04afff
* IMX_CMD 5c051000 - 5c051fff
* VLCDQ 5c053000 - 5c0533ff
* VLCDH 5c054000 - 5c054fff
* SEQ_CMD 5c055000 - 5c055fff
* IMX_REG 5c056000 - 5c0560ff
* VLCD_REG 5c056100 - 5c0561ff
* SEQ_REG 5c056200 - 5c0562ff
* IMG_BUF_REG 5c056300 - 5c0563ff
* SEQIRQ_REG 5c056400 - 5c0564ff
* OCP_REG 5c060000 - 5c060fff
* SYSC_REG 5c070000 - 5c070fff
* MMU_REG 5d000000 - 5d000fff
* sDMA R 68000400 - 680005ff
* sDMA W 68000600 - 680007ff
* Display Control 68000800 - 680009ff
* DSP subsystem 68000a00 - 68000bff
* MPU subsystem 68000c00 - 68000dff
* IVA subsystem 68001000 - 680011ff
* USB 68001200 - 680013ff
* Camera 68001400 - 680015ff
* VLYNQ (firewall) 68001800 - 68001bff
* VLYNQ 68001e00 - 68001fff
* SSI 68002000 - 680021ff
* L4 68002400 - 680025ff
* DSP (firewall) 68002800 - 68002bff
* DSP subsystem 68002e00 - 68002fff
* IVA (firewall) 68003000 - 680033ff
* IVA 68003600 - 680037ff
* GFX 68003a00 - 68003bff
* CMDWR emulation 68003c00 - 68003dff
* SMS 68004000 - 680041ff
* OCM 68004200 - 680043ff
* GPMC 68004400 - 680045ff
* RAM (firewall) 68005000 - 680053ff
* RAM (err login) 68005400 - 680057ff
* ROM (firewall) 68005800 - 68005bff
* ROM (err login) 68005c00 - 68005fff
* GPMC (firewall) 68006000 - 680063ff
* GPMC (err login) 68006400 - 680067ff
* SMS (err login) 68006c00 - 68006fff
* SMS registers 68008000 - 68008fff
* SDRC registers 68009000 - 68009fff
* GPMC registers 6800a000 6800afff
*/
qemu_register_reset(omap2_mpu_reset, s);
return s;
}
| gpl-2.0 |
Fusion-Devices/android_kernel_motorola_msm8226 | drivers/net/wireless/mwifiex/sta_ioctl.c | 312 | 41778 | /*
* Marvell Wireless LAN device driver: functions for station ioctl
*
* Copyright (C) 2011, Marvell International Ltd.
*
* This software file (the "File") is distributed by Marvell International
* Ltd. under the terms of the GNU General Public License Version 2, June 1991
* (the "License"). You may use, redistribute and/or modify this File in
* accordance with the terms and conditions of the License, a copy of which
* is available by writing to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the
* worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE
* IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE
* ARE EXPRESSLY DISCLAIMED. The License provides additional details about
* this warranty disclaimer.
*/
#include "decl.h"
#include "ioctl.h"
#include "util.h"
#include "fw.h"
#include "main.h"
#include "wmm.h"
#include "11n.h"
#include "cfg80211.h"
/*
* Copies the multicast address list from device to driver.
*
* This function does not validate the destination memory for
* size, and the calling function must ensure enough memory is
* available.
*/
int mwifiex_copy_mcast_addr(struct mwifiex_multicast_list *mlist,
struct net_device *dev)
{
int i = 0;
struct netdev_hw_addr *ha;
netdev_for_each_mc_addr(ha, dev)
memcpy(&mlist->mac_list[i++], ha->addr, ETH_ALEN);
return i;
}
/*
* Wait queue completion handler.
*
* This function waits on a cmd wait queue. It also cancels the pending
* request after waking up, in case of errors.
*/
int mwifiex_wait_queue_complete(struct mwifiex_adapter *adapter)
{
int status;
struct cmd_ctrl_node *cmd_queued;
if (!adapter->cmd_queued)
return 0;
cmd_queued = adapter->cmd_queued;
adapter->cmd_queued = NULL;
dev_dbg(adapter->dev, "cmd pending\n");
atomic_inc(&adapter->cmd_pending);
/* Status pending, wake up main process */
queue_work(adapter->workqueue, &adapter->main_work);
/* Wait for completion */
status = wait_event_interruptible(adapter->cmd_wait_q.wait,
*(cmd_queued->condition));
if (status) {
dev_err(adapter->dev, "cmd_wait_q terminated: %d\n", status);
return status;
}
status = adapter->cmd_wait_q.status;
adapter->cmd_wait_q.status = 0;
return status;
}
/*
* This function prepares the correct firmware command and
* issues it to set the multicast list.
*
* This function can be used to enable promiscuous mode, or enable all
* multicast packets, or to enable selective multicast.
*/
int mwifiex_request_set_multicast_list(struct mwifiex_private *priv,
struct mwifiex_multicast_list *mcast_list)
{
int ret = 0;
u16 old_pkt_filter;
old_pkt_filter = priv->curr_pkt_filter;
if (mcast_list->mode == MWIFIEX_PROMISC_MODE) {
dev_dbg(priv->adapter->dev, "info: Enable Promiscuous mode\n");
priv->curr_pkt_filter |= HostCmd_ACT_MAC_PROMISCUOUS_ENABLE;
priv->curr_pkt_filter &=
~HostCmd_ACT_MAC_ALL_MULTICAST_ENABLE;
} else {
/* Multicast */
priv->curr_pkt_filter &= ~HostCmd_ACT_MAC_PROMISCUOUS_ENABLE;
if (mcast_list->mode == MWIFIEX_MULTICAST_MODE) {
dev_dbg(priv->adapter->dev,
"info: Enabling All Multicast!\n");
priv->curr_pkt_filter |=
HostCmd_ACT_MAC_ALL_MULTICAST_ENABLE;
} else {
priv->curr_pkt_filter &=
~HostCmd_ACT_MAC_ALL_MULTICAST_ENABLE;
if (mcast_list->num_multicast_addr) {
dev_dbg(priv->adapter->dev,
"info: Set multicast list=%d\n",
mcast_list->num_multicast_addr);
/* Set multicast addresses to firmware */
if (old_pkt_filter == priv->curr_pkt_filter) {
/* Send request to firmware */
ret = mwifiex_send_cmd_async(priv,
HostCmd_CMD_MAC_MULTICAST_ADR,
HostCmd_ACT_GEN_SET, 0,
mcast_list);
} else {
/* Send request to firmware */
ret = mwifiex_send_cmd_async(priv,
HostCmd_CMD_MAC_MULTICAST_ADR,
HostCmd_ACT_GEN_SET, 0,
mcast_list);
}
}
}
}
dev_dbg(priv->adapter->dev,
"info: old_pkt_filter=%#x, curr_pkt_filter=%#x\n",
old_pkt_filter, priv->curr_pkt_filter);
if (old_pkt_filter != priv->curr_pkt_filter) {
ret = mwifiex_send_cmd_async(priv, HostCmd_CMD_MAC_CONTROL,
HostCmd_ACT_GEN_SET,
0, &priv->curr_pkt_filter);
}
return ret;
}
/*
* This function fills bss descriptor structure using provided
* information.
*/
int mwifiex_fill_new_bss_desc(struct mwifiex_private *priv,
u8 *bssid, s32 rssi, u8 *ie_buf,
size_t ie_len, u16 beacon_period,
u16 cap_info_bitmap, u8 band,
struct mwifiex_bssdescriptor *bss_desc)
{
int ret;
memcpy(bss_desc->mac_address, bssid, ETH_ALEN);
bss_desc->rssi = rssi;
bss_desc->beacon_buf = ie_buf;
bss_desc->beacon_buf_size = ie_len;
bss_desc->beacon_period = beacon_period;
bss_desc->cap_info_bitmap = cap_info_bitmap;
bss_desc->bss_band = band;
if (bss_desc->cap_info_bitmap & WLAN_CAPABILITY_PRIVACY) {
dev_dbg(priv->adapter->dev, "info: InterpretIE: AP WEP enabled\n");
bss_desc->privacy = MWIFIEX_802_11_PRIV_FILTER_8021X_WEP;
} else {
bss_desc->privacy = MWIFIEX_802_11_PRIV_FILTER_ACCEPT_ALL;
}
if (bss_desc->cap_info_bitmap & WLAN_CAPABILITY_IBSS)
bss_desc->bss_mode = NL80211_IFTYPE_ADHOC;
else
bss_desc->bss_mode = NL80211_IFTYPE_STATION;
ret = mwifiex_update_bss_desc_with_ie(priv->adapter, bss_desc,
ie_buf, ie_len);
return ret;
}
/*
* In Ad-Hoc mode, the IBSS is created if not found in scan list.
* In both Ad-Hoc and infra mode, an deauthentication is performed
* first.
*/
int mwifiex_bss_start(struct mwifiex_private *priv, struct cfg80211_bss *bss,
struct cfg80211_ssid *req_ssid)
{
int ret;
struct mwifiex_adapter *adapter = priv->adapter;
struct mwifiex_bssdescriptor *bss_desc = NULL;
u8 *beacon_ie = NULL;
priv->scan_block = false;
if (bss) {
/* Allocate and fill new bss descriptor */
bss_desc = kzalloc(sizeof(struct mwifiex_bssdescriptor),
GFP_KERNEL);
if (!bss_desc) {
dev_err(priv->adapter->dev, " failed to alloc bss_desc\n");
return -ENOMEM;
}
beacon_ie = kmemdup(bss->information_elements,
bss->len_beacon_ies, GFP_KERNEL);
if (!beacon_ie) {
kfree(bss_desc);
dev_err(priv->adapter->dev, " failed to alloc beacon_ie\n");
return -ENOMEM;
}
ret = mwifiex_fill_new_bss_desc(priv, bss->bssid, bss->signal,
beacon_ie, bss->len_beacon_ies,
bss->beacon_interval,
bss->capability,
*(u8 *)bss->priv, bss_desc);
if (ret)
goto done;
}
if (priv->bss_mode == NL80211_IFTYPE_STATION) {
/* Infra mode */
ret = mwifiex_deauthenticate(priv, NULL);
if (ret)
goto done;
ret = mwifiex_check_network_compatibility(priv, bss_desc);
if (ret)
goto done;
dev_dbg(adapter->dev, "info: SSID found in scan list ... "
"associating...\n");
if (!netif_queue_stopped(priv->netdev))
mwifiex_stop_net_dev_queue(priv->netdev, adapter);
if (netif_carrier_ok(priv->netdev))
netif_carrier_off(priv->netdev);
/* Clear any past association response stored for
* application retrieval */
priv->assoc_rsp_size = 0;
ret = mwifiex_associate(priv, bss_desc);
/* If auth type is auto and association fails using open mode,
* try to connect using shared mode */
if (ret == WLAN_STATUS_NOT_SUPPORTED_AUTH_ALG &&
priv->sec_info.is_authtype_auto &&
priv->sec_info.wep_enabled) {
priv->sec_info.authentication_mode =
NL80211_AUTHTYPE_SHARED_KEY;
ret = mwifiex_associate(priv, bss_desc);
}
if (bss)
cfg80211_put_bss(bss);
} else {
/* Adhoc mode */
/* If the requested SSID matches current SSID, return */
if (bss_desc && bss_desc->ssid.ssid_len &&
(!mwifiex_ssid_cmp(&priv->curr_bss_params.bss_descriptor.
ssid, &bss_desc->ssid))) {
kfree(bss_desc);
kfree(beacon_ie);
return 0;
}
/* Exit Adhoc mode first */
dev_dbg(adapter->dev, "info: Sending Adhoc Stop\n");
ret = mwifiex_deauthenticate(priv, NULL);
if (ret)
goto done;
priv->adhoc_is_link_sensed = false;
ret = mwifiex_check_network_compatibility(priv, bss_desc);
if (!netif_queue_stopped(priv->netdev))
mwifiex_stop_net_dev_queue(priv->netdev, adapter);
if (netif_carrier_ok(priv->netdev))
netif_carrier_off(priv->netdev);
if (!ret) {
dev_dbg(adapter->dev, "info: network found in scan"
" list. Joining...\n");
ret = mwifiex_adhoc_join(priv, bss_desc);
if (bss)
cfg80211_put_bss(bss);
} else {
dev_dbg(adapter->dev, "info: Network not found in "
"the list, creating adhoc with ssid = %s\n",
req_ssid->ssid);
ret = mwifiex_adhoc_start(priv, req_ssid);
}
}
done:
kfree(bss_desc);
kfree(beacon_ie);
return ret;
}
/*
* IOCTL request handler to set host sleep configuration.
*
* This function prepares the correct firmware command and
* issues it.
*/
static int mwifiex_set_hs_params(struct mwifiex_private *priv, u16 action,
int cmd_type, struct mwifiex_ds_hs_cfg *hs_cfg)
{
struct mwifiex_adapter *adapter = priv->adapter;
int status = 0;
u32 prev_cond = 0;
if (!hs_cfg)
return -ENOMEM;
switch (action) {
case HostCmd_ACT_GEN_SET:
if (adapter->pps_uapsd_mode) {
dev_dbg(adapter->dev, "info: Host Sleep IOCTL"
" is blocked in UAPSD/PPS mode\n");
status = -1;
break;
}
if (hs_cfg->is_invoke_hostcmd) {
if (hs_cfg->conditions == HOST_SLEEP_CFG_CANCEL) {
if (!adapter->is_hs_configured)
/* Already cancelled */
break;
/* Save previous condition */
prev_cond = le32_to_cpu(adapter->hs_cfg
.conditions);
adapter->hs_cfg.conditions =
cpu_to_le32(hs_cfg->conditions);
} else if (hs_cfg->conditions) {
adapter->hs_cfg.conditions =
cpu_to_le32(hs_cfg->conditions);
adapter->hs_cfg.gpio = (u8)hs_cfg->gpio;
if (hs_cfg->gap)
adapter->hs_cfg.gap = (u8)hs_cfg->gap;
} else if (adapter->hs_cfg.conditions
== cpu_to_le32(HOST_SLEEP_CFG_CANCEL)) {
/* Return failure if no parameters for HS
enable */
status = -1;
break;
}
if (cmd_type == MWIFIEX_SYNC_CMD)
status = mwifiex_send_cmd_sync(priv,
HostCmd_CMD_802_11_HS_CFG_ENH,
HostCmd_ACT_GEN_SET, 0,
&adapter->hs_cfg);
else
status = mwifiex_send_cmd_async(priv,
HostCmd_CMD_802_11_HS_CFG_ENH,
HostCmd_ACT_GEN_SET, 0,
&adapter->hs_cfg);
if (hs_cfg->conditions == HOST_SLEEP_CFG_CANCEL)
/* Restore previous condition */
adapter->hs_cfg.conditions =
cpu_to_le32(prev_cond);
} else {
adapter->hs_cfg.conditions =
cpu_to_le32(hs_cfg->conditions);
adapter->hs_cfg.gpio = (u8)hs_cfg->gpio;
adapter->hs_cfg.gap = (u8)hs_cfg->gap;
}
break;
case HostCmd_ACT_GEN_GET:
hs_cfg->conditions = le32_to_cpu(adapter->hs_cfg.conditions);
hs_cfg->gpio = adapter->hs_cfg.gpio;
hs_cfg->gap = adapter->hs_cfg.gap;
break;
default:
status = -1;
break;
}
return status;
}
/*
* Sends IOCTL request to cancel the existing Host Sleep configuration.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int mwifiex_cancel_hs(struct mwifiex_private *priv, int cmd_type)
{
struct mwifiex_ds_hs_cfg hscfg;
hscfg.conditions = HOST_SLEEP_CFG_CANCEL;
hscfg.is_invoke_hostcmd = true;
return mwifiex_set_hs_params(priv, HostCmd_ACT_GEN_SET,
cmd_type, &hscfg);
}
EXPORT_SYMBOL_GPL(mwifiex_cancel_hs);
/*
* Sends IOCTL request to cancel the existing Host Sleep configuration.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int mwifiex_enable_hs(struct mwifiex_adapter *adapter)
{
struct mwifiex_ds_hs_cfg hscfg;
if (adapter->hs_activated) {
dev_dbg(adapter->dev, "cmd: HS Already actived\n");
return true;
}
adapter->hs_activate_wait_q_woken = false;
memset(&hscfg, 0, sizeof(struct mwifiex_ds_hs_cfg));
hscfg.is_invoke_hostcmd = true;
if (mwifiex_set_hs_params(mwifiex_get_priv(adapter,
MWIFIEX_BSS_ROLE_STA),
HostCmd_ACT_GEN_SET, MWIFIEX_SYNC_CMD,
&hscfg)) {
dev_err(adapter->dev, "IOCTL request HS enable failed\n");
return false;
}
if (wait_event_interruptible(adapter->hs_activate_wait_q,
adapter->hs_activate_wait_q_woken)) {
dev_err(adapter->dev, "hs_activate_wait_q terminated\n");
return false;
}
return true;
}
EXPORT_SYMBOL_GPL(mwifiex_enable_hs);
/*
* IOCTL request handler to get BSS information.
*
* This function collates the information from different driver structures
* to send to the user.
*/
int mwifiex_get_bss_info(struct mwifiex_private *priv,
struct mwifiex_bss_info *info)
{
struct mwifiex_adapter *adapter = priv->adapter;
struct mwifiex_bssdescriptor *bss_desc;
if (!info)
return -1;
bss_desc = &priv->curr_bss_params.bss_descriptor;
info->bss_mode = priv->bss_mode;
memcpy(&info->ssid, &bss_desc->ssid, sizeof(struct cfg80211_ssid));
memcpy(&info->bssid, &bss_desc->mac_address, ETH_ALEN);
info->bss_chan = bss_desc->channel;
info->region_code = adapter->region_code;
info->media_connected = priv->media_connected;
info->max_power_level = priv->max_tx_power_level;
info->min_power_level = priv->min_tx_power_level;
info->adhoc_state = priv->adhoc_state;
info->bcn_nf_last = priv->bcn_nf_last;
if (priv->sec_info.wep_enabled)
info->wep_status = true;
else
info->wep_status = false;
info->is_hs_configured = adapter->is_hs_configured;
info->is_deep_sleep = adapter->is_deep_sleep;
return 0;
}
/*
* The function disables auto deep sleep mode.
*/
int mwifiex_disable_auto_ds(struct mwifiex_private *priv)
{
struct mwifiex_ds_auto_ds auto_ds;
auto_ds.auto_ds = DEEP_SLEEP_OFF;
return mwifiex_send_cmd_sync(priv, HostCmd_CMD_802_11_PS_MODE_ENH,
DIS_AUTO_PS, BITMAP_AUTO_DS, &auto_ds);
}
EXPORT_SYMBOL_GPL(mwifiex_disable_auto_ds);
/*
* IOCTL request handler to set/get active channel.
*
* This function performs validity checking on channel/frequency
* compatibility and returns failure if not valid.
*/
int mwifiex_bss_set_channel(struct mwifiex_private *priv,
struct mwifiex_chan_freq_power *chan)
{
struct mwifiex_adapter *adapter = priv->adapter;
struct mwifiex_chan_freq_power *cfp = NULL;
if (!chan)
return -1;
if (!chan->channel && !chan->freq)
return -1;
if (adapter->adhoc_start_band & BAND_AN)
adapter->adhoc_start_band = BAND_G | BAND_B | BAND_GN;
else if (adapter->adhoc_start_band & BAND_A)
adapter->adhoc_start_band = BAND_G | BAND_B;
if (chan->channel) {
if (chan->channel <= MAX_CHANNEL_BAND_BG)
cfp = mwifiex_get_cfp(priv, 0, (u16) chan->channel, 0);
if (!cfp) {
cfp = mwifiex_get_cfp(priv, BAND_A,
(u16) chan->channel, 0);
if (cfp) {
if (adapter->adhoc_11n_enabled)
adapter->adhoc_start_band = BAND_A
| BAND_AN;
else
adapter->adhoc_start_band = BAND_A;
}
}
} else {
if (chan->freq <= MAX_FREQUENCY_BAND_BG)
cfp = mwifiex_get_cfp(priv, 0, 0, chan->freq);
if (!cfp) {
cfp = mwifiex_get_cfp(priv, BAND_A, 0, chan->freq);
if (cfp) {
if (adapter->adhoc_11n_enabled)
adapter->adhoc_start_band = BAND_A
| BAND_AN;
else
adapter->adhoc_start_band = BAND_A;
}
}
}
if (!cfp || !cfp->channel) {
dev_err(adapter->dev, "invalid channel/freq\n");
return -1;
}
priv->adhoc_channel = (u8) cfp->channel;
chan->channel = cfp->channel;
chan->freq = cfp->freq;
return 0;
}
/*
* IOCTL request handler to set/get Ad-Hoc channel.
*
* This function prepares the correct firmware command and
* issues it to set or get the ad-hoc channel.
*/
static int mwifiex_bss_ioctl_ibss_channel(struct mwifiex_private *priv,
u16 action, u16 *channel)
{
if (action == HostCmd_ACT_GEN_GET) {
if (!priv->media_connected) {
*channel = priv->adhoc_channel;
return 0;
}
} else {
priv->adhoc_channel = (u8) *channel;
}
return mwifiex_send_cmd_sync(priv, HostCmd_CMD_802_11_RF_CHANNEL,
action, 0, channel);
}
/*
* IOCTL request handler to change Ad-Hoc channel.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*
* The function follows the following steps to perform the change -
* - Get current IBSS information
* - Get current channel
* - If no change is required, return
* - If not connected, change channel and return
* - If connected,
* - Disconnect
* - Change channel
* - Perform specific SSID scan with same SSID
* - Start/Join the IBSS
*/
int
mwifiex_drv_change_adhoc_chan(struct mwifiex_private *priv, u16 channel)
{
int ret;
struct mwifiex_bss_info bss_info;
struct mwifiex_ssid_bssid ssid_bssid;
u16 curr_chan = 0;
struct cfg80211_bss *bss = NULL;
struct ieee80211_channel *chan;
enum ieee80211_band band;
memset(&bss_info, 0, sizeof(bss_info));
/* Get BSS information */
if (mwifiex_get_bss_info(priv, &bss_info))
return -1;
/* Get current channel */
ret = mwifiex_bss_ioctl_ibss_channel(priv, HostCmd_ACT_GEN_GET,
&curr_chan);
if (curr_chan == channel) {
ret = 0;
goto done;
}
dev_dbg(priv->adapter->dev, "cmd: updating channel from %d to %d\n",
curr_chan, channel);
if (!bss_info.media_connected) {
ret = 0;
goto done;
}
/* Do disonnect */
memset(&ssid_bssid, 0, ETH_ALEN);
ret = mwifiex_deauthenticate(priv, ssid_bssid.bssid);
ret = mwifiex_bss_ioctl_ibss_channel(priv, HostCmd_ACT_GEN_SET,
&channel);
/* Do specific SSID scanning */
if (mwifiex_request_scan(priv, &bss_info.ssid)) {
ret = -1;
goto done;
}
band = mwifiex_band_to_radio_type(priv->curr_bss_params.band);
chan = __ieee80211_get_channel(priv->wdev->wiphy,
ieee80211_channel_to_frequency(channel,
band));
/* Find the BSS we want using available scan results */
bss = cfg80211_get_bss(priv->wdev->wiphy, chan, bss_info.bssid,
bss_info.ssid.ssid, bss_info.ssid.ssid_len,
WLAN_CAPABILITY_ESS, WLAN_CAPABILITY_ESS);
if (!bss)
wiphy_warn(priv->wdev->wiphy, "assoc: bss %pM not in scan results\n",
bss_info.bssid);
ret = mwifiex_bss_start(priv, bss, &bss_info.ssid);
done:
return ret;
}
/*
* IOCTL request handler to get rate.
*
* This function prepares the correct firmware command and
* issues it to get the current rate if it is connected,
* otherwise, the function returns the lowest supported rate
* for the band.
*/
static int mwifiex_rate_ioctl_get_rate_value(struct mwifiex_private *priv,
struct mwifiex_rate_cfg *rate_cfg)
{
rate_cfg->is_rate_auto = priv->is_data_rate_auto;
return mwifiex_send_cmd_sync(priv, HostCmd_CMD_802_11_TX_RATE_QUERY,
HostCmd_ACT_GEN_GET, 0, NULL);
}
/*
* IOCTL request handler to set rate.
*
* This function prepares the correct firmware command and
* issues it to set the current rate.
*
* The function also performs validation checking on the supplied value.
*/
static int mwifiex_rate_ioctl_set_rate_value(struct mwifiex_private *priv,
struct mwifiex_rate_cfg *rate_cfg)
{
u8 rates[MWIFIEX_SUPPORTED_RATES];
u8 *rate;
int rate_index, ret;
u16 bitmap_rates[MAX_BITMAP_RATES_SIZE];
u32 i;
struct mwifiex_adapter *adapter = priv->adapter;
if (rate_cfg->is_rate_auto) {
memset(bitmap_rates, 0, sizeof(bitmap_rates));
/* Support all HR/DSSS rates */
bitmap_rates[0] = 0x000F;
/* Support all OFDM rates */
bitmap_rates[1] = 0x00FF;
/* Support all HT-MCSs rate */
for (i = 0; i < ARRAY_SIZE(priv->bitmap_rates) - 3; i++)
bitmap_rates[i + 2] = 0xFFFF;
bitmap_rates[9] = 0x3FFF;
} else {
memset(rates, 0, sizeof(rates));
mwifiex_get_active_data_rates(priv, rates);
rate = rates;
for (i = 0; (rate[i] && i < MWIFIEX_SUPPORTED_RATES); i++) {
dev_dbg(adapter->dev, "info: rate=%#x wanted=%#x\n",
rate[i], rate_cfg->rate);
if ((rate[i] & 0x7f) == (rate_cfg->rate & 0x7f))
break;
}
if ((i == MWIFIEX_SUPPORTED_RATES) || !rate[i]) {
dev_err(adapter->dev, "fixed data rate %#x is out "
"of range\n", rate_cfg->rate);
return -1;
}
memset(bitmap_rates, 0, sizeof(bitmap_rates));
rate_index = mwifiex_data_rate_to_index(rate_cfg->rate);
/* Only allow b/g rates to be set */
if (rate_index >= MWIFIEX_RATE_INDEX_HRDSSS0 &&
rate_index <= MWIFIEX_RATE_INDEX_HRDSSS3) {
bitmap_rates[0] = 1 << rate_index;
} else {
rate_index -= 1; /* There is a 0x00 in the table */
if (rate_index >= MWIFIEX_RATE_INDEX_OFDM0 &&
rate_index <= MWIFIEX_RATE_INDEX_OFDM7)
bitmap_rates[1] = 1 << (rate_index -
MWIFIEX_RATE_INDEX_OFDM0);
}
}
ret = mwifiex_send_cmd_sync(priv, HostCmd_CMD_TX_RATE_CFG,
HostCmd_ACT_GEN_SET, 0, bitmap_rates);
return ret;
}
/*
* IOCTL request handler to set/get rate.
*
* This function can be used to set/get either the rate value or the
* rate index.
*/
static int mwifiex_rate_ioctl_cfg(struct mwifiex_private *priv,
struct mwifiex_rate_cfg *rate_cfg)
{
int status;
if (!rate_cfg)
return -1;
if (rate_cfg->action == HostCmd_ACT_GEN_GET)
status = mwifiex_rate_ioctl_get_rate_value(priv, rate_cfg);
else
status = mwifiex_rate_ioctl_set_rate_value(priv, rate_cfg);
return status;
}
/*
* Sends IOCTL request to get the data rate.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int mwifiex_drv_get_data_rate(struct mwifiex_private *priv,
struct mwifiex_rate_cfg *rate)
{
int ret;
memset(rate, 0, sizeof(struct mwifiex_rate_cfg));
rate->action = HostCmd_ACT_GEN_GET;
ret = mwifiex_rate_ioctl_cfg(priv, rate);
if (!ret) {
if (rate->is_rate_auto)
rate->rate = mwifiex_index_to_data_rate(priv,
priv->tx_rate,
priv->tx_htinfo
);
else
rate->rate = priv->data_rate;
} else {
ret = -1;
}
return ret;
}
/*
* IOCTL request handler to set tx power configuration.
*
* This function prepares the correct firmware command and
* issues it.
*
* For non-auto power mode, all the following power groups are set -
* - Modulation class HR/DSSS
* - Modulation class OFDM
* - Modulation class HTBW20
* - Modulation class HTBW40
*/
int mwifiex_set_tx_power(struct mwifiex_private *priv,
struct mwifiex_power_cfg *power_cfg)
{
int ret;
struct host_cmd_ds_txpwr_cfg *txp_cfg;
struct mwifiex_types_power_group *pg_tlv;
struct mwifiex_power_group *pg;
u8 *buf;
u16 dbm = 0;
if (!power_cfg->is_power_auto) {
dbm = (u16) power_cfg->power_level;
if ((dbm < priv->min_tx_power_level) ||
(dbm > priv->max_tx_power_level)) {
dev_err(priv->adapter->dev, "txpower value %d dBm"
" is out of range (%d dBm-%d dBm)\n",
dbm, priv->min_tx_power_level,
priv->max_tx_power_level);
return -1;
}
}
buf = kzalloc(MWIFIEX_SIZE_OF_CMD_BUFFER, GFP_KERNEL);
if (!buf) {
dev_err(priv->adapter->dev, "%s: failed to alloc cmd buffer\n",
__func__);
return -ENOMEM;
}
txp_cfg = (struct host_cmd_ds_txpwr_cfg *) buf;
txp_cfg->action = cpu_to_le16(HostCmd_ACT_GEN_SET);
if (!power_cfg->is_power_auto) {
txp_cfg->mode = cpu_to_le32(1);
pg_tlv = (struct mwifiex_types_power_group *)
(buf + sizeof(struct host_cmd_ds_txpwr_cfg));
pg_tlv->type = TLV_TYPE_POWER_GROUP;
pg_tlv->length = 4 * sizeof(struct mwifiex_power_group);
pg = (struct mwifiex_power_group *)
(buf + sizeof(struct host_cmd_ds_txpwr_cfg)
+ sizeof(struct mwifiex_types_power_group));
/* Power group for modulation class HR/DSSS */
pg->first_rate_code = 0x00;
pg->last_rate_code = 0x03;
pg->modulation_class = MOD_CLASS_HR_DSSS;
pg->power_step = 0;
pg->power_min = (s8) dbm;
pg->power_max = (s8) dbm;
pg++;
/* Power group for modulation class OFDM */
pg->first_rate_code = 0x00;
pg->last_rate_code = 0x07;
pg->modulation_class = MOD_CLASS_OFDM;
pg->power_step = 0;
pg->power_min = (s8) dbm;
pg->power_max = (s8) dbm;
pg++;
/* Power group for modulation class HTBW20 */
pg->first_rate_code = 0x00;
pg->last_rate_code = 0x20;
pg->modulation_class = MOD_CLASS_HT;
pg->power_step = 0;
pg->power_min = (s8) dbm;
pg->power_max = (s8) dbm;
pg->ht_bandwidth = HT_BW_20;
pg++;
/* Power group for modulation class HTBW40 */
pg->first_rate_code = 0x00;
pg->last_rate_code = 0x20;
pg->modulation_class = MOD_CLASS_HT;
pg->power_step = 0;
pg->power_min = (s8) dbm;
pg->power_max = (s8) dbm;
pg->ht_bandwidth = HT_BW_40;
}
ret = mwifiex_send_cmd_sync(priv, HostCmd_CMD_TXPWR_CFG,
HostCmd_ACT_GEN_SET, 0, buf);
kfree(buf);
return ret;
}
/*
* IOCTL request handler to get power save mode.
*
* This function prepares the correct firmware command and
* issues it.
*/
int mwifiex_drv_set_power(struct mwifiex_private *priv, u32 *ps_mode)
{
int ret;
struct mwifiex_adapter *adapter = priv->adapter;
u16 sub_cmd;
if (*ps_mode)
adapter->ps_mode = MWIFIEX_802_11_POWER_MODE_PSP;
else
adapter->ps_mode = MWIFIEX_802_11_POWER_MODE_CAM;
sub_cmd = (*ps_mode) ? EN_AUTO_PS : DIS_AUTO_PS;
ret = mwifiex_send_cmd_sync(priv, HostCmd_CMD_802_11_PS_MODE_ENH,
sub_cmd, BITMAP_STA_PS, NULL);
if ((!ret) && (sub_cmd == DIS_AUTO_PS))
ret = mwifiex_send_cmd_async(priv,
HostCmd_CMD_802_11_PS_MODE_ENH,
GET_PS, 0, NULL);
return ret;
}
/*
* IOCTL request handler to set/reset WPA IE.
*
* The supplied WPA IE is treated as a opaque buffer. Only the first field
* is checked to determine WPA version. If buffer length is zero, the existing
* WPA IE is reset.
*/
static int mwifiex_set_wpa_ie_helper(struct mwifiex_private *priv,
u8 *ie_data_ptr, u16 ie_len)
{
if (ie_len) {
if (ie_len > sizeof(priv->wpa_ie)) {
dev_err(priv->adapter->dev,
"failed to copy WPA IE, too big\n");
return -1;
}
memcpy(priv->wpa_ie, ie_data_ptr, ie_len);
priv->wpa_ie_len = (u8) ie_len;
dev_dbg(priv->adapter->dev, "cmd: Set Wpa_ie_len=%d IE=%#x\n",
priv->wpa_ie_len, priv->wpa_ie[0]);
if (priv->wpa_ie[0] == WLAN_EID_WPA) {
priv->sec_info.wpa_enabled = true;
} else if (priv->wpa_ie[0] == WLAN_EID_RSN) {
priv->sec_info.wpa2_enabled = true;
} else {
priv->sec_info.wpa_enabled = false;
priv->sec_info.wpa2_enabled = false;
}
} else {
memset(priv->wpa_ie, 0, sizeof(priv->wpa_ie));
priv->wpa_ie_len = 0;
dev_dbg(priv->adapter->dev, "info: reset wpa_ie_len=%d IE=%#x\n",
priv->wpa_ie_len, priv->wpa_ie[0]);
priv->sec_info.wpa_enabled = false;
priv->sec_info.wpa2_enabled = false;
}
return 0;
}
/*
* IOCTL request handler to set/reset WAPI IE.
*
* The supplied WAPI IE is treated as a opaque buffer. Only the first field
* is checked to internally enable WAPI. If buffer length is zero, the existing
* WAPI IE is reset.
*/
static int mwifiex_set_wapi_ie(struct mwifiex_private *priv,
u8 *ie_data_ptr, u16 ie_len)
{
if (ie_len) {
if (ie_len > sizeof(priv->wapi_ie)) {
dev_dbg(priv->adapter->dev,
"info: failed to copy WAPI IE, too big\n");
return -1;
}
memcpy(priv->wapi_ie, ie_data_ptr, ie_len);
priv->wapi_ie_len = ie_len;
dev_dbg(priv->adapter->dev, "cmd: Set wapi_ie_len=%d IE=%#x\n",
priv->wapi_ie_len, priv->wapi_ie[0]);
if (priv->wapi_ie[0] == WLAN_EID_BSS_AC_ACCESS_DELAY)
priv->sec_info.wapi_enabled = true;
} else {
memset(priv->wapi_ie, 0, sizeof(priv->wapi_ie));
priv->wapi_ie_len = ie_len;
dev_dbg(priv->adapter->dev,
"info: Reset wapi_ie_len=%d IE=%#x\n",
priv->wapi_ie_len, priv->wapi_ie[0]);
priv->sec_info.wapi_enabled = false;
}
return 0;
}
/*
* IOCTL request handler to set WAPI key.
*
* This function prepares the correct firmware command and
* issues it.
*/
static int mwifiex_sec_ioctl_set_wapi_key(struct mwifiex_private *priv,
struct mwifiex_ds_encrypt_key *encrypt_key)
{
return mwifiex_send_cmd_sync(priv, HostCmd_CMD_802_11_KEY_MATERIAL,
HostCmd_ACT_GEN_SET, KEY_INFO_ENABLED,
encrypt_key);
}
/*
* IOCTL request handler to set WEP network key.
*
* This function prepares the correct firmware command and
* issues it, after validation checks.
*/
static int mwifiex_sec_ioctl_set_wep_key(struct mwifiex_private *priv,
struct mwifiex_ds_encrypt_key *encrypt_key)
{
int ret;
struct mwifiex_wep_key *wep_key;
int index;
if (priv->wep_key_curr_index >= NUM_WEP_KEYS)
priv->wep_key_curr_index = 0;
wep_key = &priv->wep_key[priv->wep_key_curr_index];
index = encrypt_key->key_index;
if (encrypt_key->key_disable) {
priv->sec_info.wep_enabled = 0;
} else if (!encrypt_key->key_len) {
/* Copy the required key as the current key */
wep_key = &priv->wep_key[index];
if (!wep_key->key_length) {
dev_err(priv->adapter->dev,
"key not set, so cannot enable it\n");
return -1;
}
priv->wep_key_curr_index = (u16) index;
priv->sec_info.wep_enabled = 1;
} else {
wep_key = &priv->wep_key[index];
memset(wep_key, 0, sizeof(struct mwifiex_wep_key));
/* Copy the key in the driver */
memcpy(wep_key->key_material,
encrypt_key->key_material,
encrypt_key->key_len);
wep_key->key_index = index;
wep_key->key_length = encrypt_key->key_len;
priv->sec_info.wep_enabled = 1;
}
if (wep_key->key_length) {
/* Send request to firmware */
ret = mwifiex_send_cmd_async(priv,
HostCmd_CMD_802_11_KEY_MATERIAL,
HostCmd_ACT_GEN_SET, 0, NULL);
if (ret)
return ret;
}
if (priv->sec_info.wep_enabled)
priv->curr_pkt_filter |= HostCmd_ACT_MAC_WEP_ENABLE;
else
priv->curr_pkt_filter &= ~HostCmd_ACT_MAC_WEP_ENABLE;
ret = mwifiex_send_cmd_sync(priv, HostCmd_CMD_MAC_CONTROL,
HostCmd_ACT_GEN_SET, 0,
&priv->curr_pkt_filter);
return ret;
}
/*
* IOCTL request handler to set WPA key.
*
* This function prepares the correct firmware command and
* issues it, after validation checks.
*
* Current driver only supports key length of up to 32 bytes.
*
* This function can also be used to disable a currently set key.
*/
static int mwifiex_sec_ioctl_set_wpa_key(struct mwifiex_private *priv,
struct mwifiex_ds_encrypt_key *encrypt_key)
{
int ret;
u8 remove_key = false;
struct host_cmd_ds_802_11_key_material *ibss_key;
/* Current driver only supports key length of up to 32 bytes */
if (encrypt_key->key_len > WLAN_MAX_KEY_LEN) {
dev_err(priv->adapter->dev, "key length too long\n");
return -1;
}
if (priv->bss_mode == NL80211_IFTYPE_ADHOC) {
/*
* IBSS/WPA-None uses only one key (Group) for both receiving
* and sending unicast and multicast packets.
*/
/* Send the key as PTK to firmware */
encrypt_key->key_index = MWIFIEX_KEY_INDEX_UNICAST;
ret = mwifiex_send_cmd_async(priv,
HostCmd_CMD_802_11_KEY_MATERIAL,
HostCmd_ACT_GEN_SET,
KEY_INFO_ENABLED, encrypt_key);
if (ret)
return ret;
ibss_key = &priv->aes_key;
memset(ibss_key, 0,
sizeof(struct host_cmd_ds_802_11_key_material));
/* Copy the key in the driver */
memcpy(ibss_key->key_param_set.key, encrypt_key->key_material,
encrypt_key->key_len);
memcpy(&ibss_key->key_param_set.key_len, &encrypt_key->key_len,
sizeof(ibss_key->key_param_set.key_len));
ibss_key->key_param_set.key_type_id
= cpu_to_le16(KEY_TYPE_ID_TKIP);
ibss_key->key_param_set.key_info = cpu_to_le16(KEY_ENABLED);
/* Send the key as GTK to firmware */
encrypt_key->key_index = ~MWIFIEX_KEY_INDEX_UNICAST;
}
if (!encrypt_key->key_index)
encrypt_key->key_index = MWIFIEX_KEY_INDEX_UNICAST;
if (remove_key)
ret = mwifiex_send_cmd_sync(priv,
HostCmd_CMD_802_11_KEY_MATERIAL,
HostCmd_ACT_GEN_SET,
!KEY_INFO_ENABLED, encrypt_key);
else
ret = mwifiex_send_cmd_sync(priv,
HostCmd_CMD_802_11_KEY_MATERIAL,
HostCmd_ACT_GEN_SET,
KEY_INFO_ENABLED, encrypt_key);
return ret;
}
/*
* IOCTL request handler to set/get network keys.
*
* This is a generic key handling function which supports WEP, WPA
* and WAPI.
*/
static int
mwifiex_sec_ioctl_encrypt_key(struct mwifiex_private *priv,
struct mwifiex_ds_encrypt_key *encrypt_key)
{
int status;
if (encrypt_key->is_wapi_key)
status = mwifiex_sec_ioctl_set_wapi_key(priv, encrypt_key);
else if (encrypt_key->key_len > WLAN_KEY_LEN_WEP104)
status = mwifiex_sec_ioctl_set_wpa_key(priv, encrypt_key);
else
status = mwifiex_sec_ioctl_set_wep_key(priv, encrypt_key);
return status;
}
/*
* This function returns the driver version.
*/
int
mwifiex_drv_get_driver_version(struct mwifiex_adapter *adapter, char *version,
int max_len)
{
union {
u32 l;
u8 c[4];
} ver;
char fw_ver[32];
ver.l = adapter->fw_release_number;
sprintf(fw_ver, "%u.%u.%u.p%u", ver.c[2], ver.c[1], ver.c[0], ver.c[3]);
snprintf(version, max_len, driver_version, fw_ver);
dev_dbg(adapter->dev, "info: MWIFIEX VERSION: %s\n", version);
return 0;
}
/*
* Sends IOCTL request to get signal information.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int mwifiex_get_signal_info(struct mwifiex_private *priv,
struct mwifiex_ds_get_signal *signal)
{
int status;
signal->selector = ALL_RSSI_INFO_MASK;
/* Signal info can be obtained only if connected */
if (!priv->media_connected) {
dev_dbg(priv->adapter->dev,
"info: Can not get signal in disconnected state\n");
return -1;
}
status = mwifiex_send_cmd_sync(priv, HostCmd_CMD_RSSI_INFO,
HostCmd_ACT_GEN_GET, 0, signal);
if (!status) {
if (signal->selector & BCN_RSSI_AVG_MASK)
priv->qual_level = signal->bcn_rssi_avg;
if (signal->selector & BCN_NF_AVG_MASK)
priv->qual_noise = signal->bcn_nf_avg;
}
return status;
}
/*
* Sends IOCTL request to set encoding parameters.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int mwifiex_set_encode(struct mwifiex_private *priv, const u8 *key,
int key_len, u8 key_index, int disable)
{
struct mwifiex_ds_encrypt_key encrypt_key;
memset(&encrypt_key, 0, sizeof(struct mwifiex_ds_encrypt_key));
encrypt_key.key_len = key_len;
if (!disable) {
encrypt_key.key_index = key_index;
if (key_len)
memcpy(encrypt_key.key_material, key, key_len);
} else {
encrypt_key.key_disable = true;
}
return mwifiex_sec_ioctl_encrypt_key(priv, &encrypt_key);
}
/*
* Sends IOCTL request to get extended version.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int
mwifiex_get_ver_ext(struct mwifiex_private *priv)
{
struct mwifiex_ver_ext ver_ext;
memset(&ver_ext, 0, sizeof(struct host_cmd_ds_version_ext));
if (mwifiex_send_cmd_sync(priv, HostCmd_CMD_VERSION_EXT,
HostCmd_ACT_GEN_GET, 0, &ver_ext))
return -1;
return 0;
}
/*
* Sends IOCTL request to get statistics information.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int
mwifiex_get_stats_info(struct mwifiex_private *priv,
struct mwifiex_ds_get_stats *log)
{
return mwifiex_send_cmd_sync(priv, HostCmd_CMD_802_11_GET_LOG,
HostCmd_ACT_GEN_GET, 0, log);
}
/*
* IOCTL request handler to read/write register.
*
* This function prepares the correct firmware command and
* issues it.
*
* Access to the following registers are supported -
* - MAC
* - BBP
* - RF
* - PMIC
* - CAU
*/
static int mwifiex_reg_mem_ioctl_reg_rw(struct mwifiex_private *priv,
struct mwifiex_ds_reg_rw *reg_rw,
u16 action)
{
u16 cmd_no;
switch (le32_to_cpu(reg_rw->type)) {
case MWIFIEX_REG_MAC:
cmd_no = HostCmd_CMD_MAC_REG_ACCESS;
break;
case MWIFIEX_REG_BBP:
cmd_no = HostCmd_CMD_BBP_REG_ACCESS;
break;
case MWIFIEX_REG_RF:
cmd_no = HostCmd_CMD_RF_REG_ACCESS;
break;
case MWIFIEX_REG_PMIC:
cmd_no = HostCmd_CMD_PMIC_REG_ACCESS;
break;
case MWIFIEX_REG_CAU:
cmd_no = HostCmd_CMD_CAU_REG_ACCESS;
break;
default:
return -1;
}
return mwifiex_send_cmd_sync(priv, cmd_no, action, 0, reg_rw);
}
/*
* Sends IOCTL request to write to a register.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int
mwifiex_reg_write(struct mwifiex_private *priv, u32 reg_type,
u32 reg_offset, u32 reg_value)
{
struct mwifiex_ds_reg_rw reg_rw;
reg_rw.type = cpu_to_le32(reg_type);
reg_rw.offset = cpu_to_le32(reg_offset);
reg_rw.value = cpu_to_le32(reg_value);
return mwifiex_reg_mem_ioctl_reg_rw(priv, ®_rw, HostCmd_ACT_GEN_SET);
}
/*
* Sends IOCTL request to read from a register.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int
mwifiex_reg_read(struct mwifiex_private *priv, u32 reg_type,
u32 reg_offset, u32 *value)
{
int ret;
struct mwifiex_ds_reg_rw reg_rw;
reg_rw.type = cpu_to_le32(reg_type);
reg_rw.offset = cpu_to_le32(reg_offset);
ret = mwifiex_reg_mem_ioctl_reg_rw(priv, ®_rw, HostCmd_ACT_GEN_GET);
if (ret)
goto done;
*value = le32_to_cpu(reg_rw.value);
done:
return ret;
}
/*
* Sends IOCTL request to read from EEPROM.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int
mwifiex_eeprom_read(struct mwifiex_private *priv, u16 offset, u16 bytes,
u8 *value)
{
int ret;
struct mwifiex_ds_read_eeprom rd_eeprom;
rd_eeprom.offset = cpu_to_le16((u16) offset);
rd_eeprom.byte_count = cpu_to_le16((u16) bytes);
/* Send request to firmware */
ret = mwifiex_send_cmd_sync(priv, HostCmd_CMD_802_11_EEPROM_ACCESS,
HostCmd_ACT_GEN_GET, 0, &rd_eeprom);
if (!ret)
memcpy(value, rd_eeprom.value, MAX_EEPROM_DATA);
return ret;
}
/*
* This function sets a generic IE. In addition to generic IE, it can
* also handle WPA, WPA2 and WAPI IEs.
*/
static int
mwifiex_set_gen_ie_helper(struct mwifiex_private *priv, u8 *ie_data_ptr,
u16 ie_len)
{
int ret = 0;
struct ieee_types_vendor_header *pvendor_ie;
const u8 wpa_oui[] = { 0x00, 0x50, 0xf2, 0x01 };
const u8 wps_oui[] = { 0x00, 0x50, 0xf2, 0x04 };
/* If the passed length is zero, reset the buffer */
if (!ie_len) {
priv->gen_ie_buf_len = 0;
priv->wps.session_enable = false;
return 0;
} else if (!ie_data_ptr) {
return -1;
}
pvendor_ie = (struct ieee_types_vendor_header *) ie_data_ptr;
/* Test to see if it is a WPA IE, if not, then it is a gen IE */
if (((pvendor_ie->element_id == WLAN_EID_WPA) &&
(!memcmp(pvendor_ie->oui, wpa_oui, sizeof(wpa_oui)))) ||
(pvendor_ie->element_id == WLAN_EID_RSN)) {
/* IE is a WPA/WPA2 IE so call set_wpa function */
ret = mwifiex_set_wpa_ie_helper(priv, ie_data_ptr, ie_len);
priv->wps.session_enable = false;
return ret;
} else if (pvendor_ie->element_id == WLAN_EID_BSS_AC_ACCESS_DELAY) {
/* IE is a WAPI IE so call set_wapi function */
ret = mwifiex_set_wapi_ie(priv, ie_data_ptr, ie_len);
return ret;
}
/*
* Verify that the passed length is not larger than the
* available space remaining in the buffer
*/
if (ie_len < (sizeof(priv->gen_ie_buf) - priv->gen_ie_buf_len)) {
/* Test to see if it is a WPS IE, if so, enable
* wps session flag
*/
pvendor_ie = (struct ieee_types_vendor_header *) ie_data_ptr;
if ((pvendor_ie->element_id == WLAN_EID_VENDOR_SPECIFIC) &&
(!memcmp(pvendor_ie->oui, wps_oui, sizeof(wps_oui)))) {
priv->wps.session_enable = true;
dev_dbg(priv->adapter->dev,
"info: WPS Session Enabled.\n");
}
/* Append the passed data to the end of the
genIeBuffer */
memcpy(priv->gen_ie_buf + priv->gen_ie_buf_len, ie_data_ptr,
ie_len);
/* Increment the stored buffer length by the
size passed */
priv->gen_ie_buf_len += ie_len;
} else {
/* Passed data does not fit in the remaining
buffer space */
ret = -1;
}
/* Return 0, or -1 for error case */
return ret;
}
/*
* IOCTL request handler to set/get generic IE.
*
* In addition to various generic IEs, this function can also be
* used to set the ARP filter.
*/
static int mwifiex_misc_ioctl_gen_ie(struct mwifiex_private *priv,
struct mwifiex_ds_misc_gen_ie *gen_ie,
u16 action)
{
struct mwifiex_adapter *adapter = priv->adapter;
switch (gen_ie->type) {
case MWIFIEX_IE_TYPE_GEN_IE:
if (action == HostCmd_ACT_GEN_GET) {
gen_ie->len = priv->wpa_ie_len;
memcpy(gen_ie->ie_data, priv->wpa_ie, gen_ie->len);
} else {
mwifiex_set_gen_ie_helper(priv, gen_ie->ie_data,
(u16) gen_ie->len);
}
break;
case MWIFIEX_IE_TYPE_ARP_FILTER:
memset(adapter->arp_filter, 0, sizeof(adapter->arp_filter));
if (gen_ie->len > ARP_FILTER_MAX_BUF_SIZE) {
adapter->arp_filter_size = 0;
dev_err(adapter->dev, "invalid ARP filter size\n");
return -1;
} else {
memcpy(adapter->arp_filter, gen_ie->ie_data,
gen_ie->len);
adapter->arp_filter_size = gen_ie->len;
}
break;
default:
dev_err(adapter->dev, "invalid IE type\n");
return -1;
}
return 0;
}
/*
* Sends IOCTL request to set a generic IE.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int
mwifiex_set_gen_ie(struct mwifiex_private *priv, u8 *ie, int ie_len)
{
struct mwifiex_ds_misc_gen_ie gen_ie;
if (ie_len > IEEE_MAX_IE_SIZE)
return -EFAULT;
gen_ie.type = MWIFIEX_IE_TYPE_GEN_IE;
gen_ie.len = ie_len;
memcpy(gen_ie.ie_data, ie, ie_len);
if (mwifiex_misc_ioctl_gen_ie(priv, &gen_ie, HostCmd_ACT_GEN_SET))
return -EFAULT;
return 0;
}
| gpl-2.0 |
trevd/android_kernel_samsung_santos10 | drivers/net/wireless/mwifiex/sta_ioctl.c | 312 | 41778 | /*
* Marvell Wireless LAN device driver: functions for station ioctl
*
* Copyright (C) 2011, Marvell International Ltd.
*
* This software file (the "File") is distributed by Marvell International
* Ltd. under the terms of the GNU General Public License Version 2, June 1991
* (the "License"). You may use, redistribute and/or modify this File in
* accordance with the terms and conditions of the License, a copy of which
* is available by writing to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the
* worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE
* IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE
* ARE EXPRESSLY DISCLAIMED. The License provides additional details about
* this warranty disclaimer.
*/
#include "decl.h"
#include "ioctl.h"
#include "util.h"
#include "fw.h"
#include "main.h"
#include "wmm.h"
#include "11n.h"
#include "cfg80211.h"
/*
* Copies the multicast address list from device to driver.
*
* This function does not validate the destination memory for
* size, and the calling function must ensure enough memory is
* available.
*/
int mwifiex_copy_mcast_addr(struct mwifiex_multicast_list *mlist,
struct net_device *dev)
{
int i = 0;
struct netdev_hw_addr *ha;
netdev_for_each_mc_addr(ha, dev)
memcpy(&mlist->mac_list[i++], ha->addr, ETH_ALEN);
return i;
}
/*
* Wait queue completion handler.
*
* This function waits on a cmd wait queue. It also cancels the pending
* request after waking up, in case of errors.
*/
int mwifiex_wait_queue_complete(struct mwifiex_adapter *adapter)
{
int status;
struct cmd_ctrl_node *cmd_queued;
if (!adapter->cmd_queued)
return 0;
cmd_queued = adapter->cmd_queued;
adapter->cmd_queued = NULL;
dev_dbg(adapter->dev, "cmd pending\n");
atomic_inc(&adapter->cmd_pending);
/* Status pending, wake up main process */
queue_work(adapter->workqueue, &adapter->main_work);
/* Wait for completion */
status = wait_event_interruptible(adapter->cmd_wait_q.wait,
*(cmd_queued->condition));
if (status) {
dev_err(adapter->dev, "cmd_wait_q terminated: %d\n", status);
return status;
}
status = adapter->cmd_wait_q.status;
adapter->cmd_wait_q.status = 0;
return status;
}
/*
* This function prepares the correct firmware command and
* issues it to set the multicast list.
*
* This function can be used to enable promiscuous mode, or enable all
* multicast packets, or to enable selective multicast.
*/
int mwifiex_request_set_multicast_list(struct mwifiex_private *priv,
struct mwifiex_multicast_list *mcast_list)
{
int ret = 0;
u16 old_pkt_filter;
old_pkt_filter = priv->curr_pkt_filter;
if (mcast_list->mode == MWIFIEX_PROMISC_MODE) {
dev_dbg(priv->adapter->dev, "info: Enable Promiscuous mode\n");
priv->curr_pkt_filter |= HostCmd_ACT_MAC_PROMISCUOUS_ENABLE;
priv->curr_pkt_filter &=
~HostCmd_ACT_MAC_ALL_MULTICAST_ENABLE;
} else {
/* Multicast */
priv->curr_pkt_filter &= ~HostCmd_ACT_MAC_PROMISCUOUS_ENABLE;
if (mcast_list->mode == MWIFIEX_MULTICAST_MODE) {
dev_dbg(priv->adapter->dev,
"info: Enabling All Multicast!\n");
priv->curr_pkt_filter |=
HostCmd_ACT_MAC_ALL_MULTICAST_ENABLE;
} else {
priv->curr_pkt_filter &=
~HostCmd_ACT_MAC_ALL_MULTICAST_ENABLE;
if (mcast_list->num_multicast_addr) {
dev_dbg(priv->adapter->dev,
"info: Set multicast list=%d\n",
mcast_list->num_multicast_addr);
/* Set multicast addresses to firmware */
if (old_pkt_filter == priv->curr_pkt_filter) {
/* Send request to firmware */
ret = mwifiex_send_cmd_async(priv,
HostCmd_CMD_MAC_MULTICAST_ADR,
HostCmd_ACT_GEN_SET, 0,
mcast_list);
} else {
/* Send request to firmware */
ret = mwifiex_send_cmd_async(priv,
HostCmd_CMD_MAC_MULTICAST_ADR,
HostCmd_ACT_GEN_SET, 0,
mcast_list);
}
}
}
}
dev_dbg(priv->adapter->dev,
"info: old_pkt_filter=%#x, curr_pkt_filter=%#x\n",
old_pkt_filter, priv->curr_pkt_filter);
if (old_pkt_filter != priv->curr_pkt_filter) {
ret = mwifiex_send_cmd_async(priv, HostCmd_CMD_MAC_CONTROL,
HostCmd_ACT_GEN_SET,
0, &priv->curr_pkt_filter);
}
return ret;
}
/*
* This function fills bss descriptor structure using provided
* information.
*/
int mwifiex_fill_new_bss_desc(struct mwifiex_private *priv,
u8 *bssid, s32 rssi, u8 *ie_buf,
size_t ie_len, u16 beacon_period,
u16 cap_info_bitmap, u8 band,
struct mwifiex_bssdescriptor *bss_desc)
{
int ret;
memcpy(bss_desc->mac_address, bssid, ETH_ALEN);
bss_desc->rssi = rssi;
bss_desc->beacon_buf = ie_buf;
bss_desc->beacon_buf_size = ie_len;
bss_desc->beacon_period = beacon_period;
bss_desc->cap_info_bitmap = cap_info_bitmap;
bss_desc->bss_band = band;
if (bss_desc->cap_info_bitmap & WLAN_CAPABILITY_PRIVACY) {
dev_dbg(priv->adapter->dev, "info: InterpretIE: AP WEP enabled\n");
bss_desc->privacy = MWIFIEX_802_11_PRIV_FILTER_8021X_WEP;
} else {
bss_desc->privacy = MWIFIEX_802_11_PRIV_FILTER_ACCEPT_ALL;
}
if (bss_desc->cap_info_bitmap & WLAN_CAPABILITY_IBSS)
bss_desc->bss_mode = NL80211_IFTYPE_ADHOC;
else
bss_desc->bss_mode = NL80211_IFTYPE_STATION;
ret = mwifiex_update_bss_desc_with_ie(priv->adapter, bss_desc,
ie_buf, ie_len);
return ret;
}
/*
* In Ad-Hoc mode, the IBSS is created if not found in scan list.
* In both Ad-Hoc and infra mode, an deauthentication is performed
* first.
*/
int mwifiex_bss_start(struct mwifiex_private *priv, struct cfg80211_bss *bss,
struct cfg80211_ssid *req_ssid)
{
int ret;
struct mwifiex_adapter *adapter = priv->adapter;
struct mwifiex_bssdescriptor *bss_desc = NULL;
u8 *beacon_ie = NULL;
priv->scan_block = false;
if (bss) {
/* Allocate and fill new bss descriptor */
bss_desc = kzalloc(sizeof(struct mwifiex_bssdescriptor),
GFP_KERNEL);
if (!bss_desc) {
dev_err(priv->adapter->dev, " failed to alloc bss_desc\n");
return -ENOMEM;
}
beacon_ie = kmemdup(bss->information_elements,
bss->len_beacon_ies, GFP_KERNEL);
if (!beacon_ie) {
kfree(bss_desc);
dev_err(priv->adapter->dev, " failed to alloc beacon_ie\n");
return -ENOMEM;
}
ret = mwifiex_fill_new_bss_desc(priv, bss->bssid, bss->signal,
beacon_ie, bss->len_beacon_ies,
bss->beacon_interval,
bss->capability,
*(u8 *)bss->priv, bss_desc);
if (ret)
goto done;
}
if (priv->bss_mode == NL80211_IFTYPE_STATION) {
/* Infra mode */
ret = mwifiex_deauthenticate(priv, NULL);
if (ret)
goto done;
ret = mwifiex_check_network_compatibility(priv, bss_desc);
if (ret)
goto done;
dev_dbg(adapter->dev, "info: SSID found in scan list ... "
"associating...\n");
if (!netif_queue_stopped(priv->netdev))
mwifiex_stop_net_dev_queue(priv->netdev, adapter);
if (netif_carrier_ok(priv->netdev))
netif_carrier_off(priv->netdev);
/* Clear any past association response stored for
* application retrieval */
priv->assoc_rsp_size = 0;
ret = mwifiex_associate(priv, bss_desc);
/* If auth type is auto and association fails using open mode,
* try to connect using shared mode */
if (ret == WLAN_STATUS_NOT_SUPPORTED_AUTH_ALG &&
priv->sec_info.is_authtype_auto &&
priv->sec_info.wep_enabled) {
priv->sec_info.authentication_mode =
NL80211_AUTHTYPE_SHARED_KEY;
ret = mwifiex_associate(priv, bss_desc);
}
if (bss)
cfg80211_put_bss(bss);
} else {
/* Adhoc mode */
/* If the requested SSID matches current SSID, return */
if (bss_desc && bss_desc->ssid.ssid_len &&
(!mwifiex_ssid_cmp(&priv->curr_bss_params.bss_descriptor.
ssid, &bss_desc->ssid))) {
kfree(bss_desc);
kfree(beacon_ie);
return 0;
}
/* Exit Adhoc mode first */
dev_dbg(adapter->dev, "info: Sending Adhoc Stop\n");
ret = mwifiex_deauthenticate(priv, NULL);
if (ret)
goto done;
priv->adhoc_is_link_sensed = false;
ret = mwifiex_check_network_compatibility(priv, bss_desc);
if (!netif_queue_stopped(priv->netdev))
mwifiex_stop_net_dev_queue(priv->netdev, adapter);
if (netif_carrier_ok(priv->netdev))
netif_carrier_off(priv->netdev);
if (!ret) {
dev_dbg(adapter->dev, "info: network found in scan"
" list. Joining...\n");
ret = mwifiex_adhoc_join(priv, bss_desc);
if (bss)
cfg80211_put_bss(bss);
} else {
dev_dbg(adapter->dev, "info: Network not found in "
"the list, creating adhoc with ssid = %s\n",
req_ssid->ssid);
ret = mwifiex_adhoc_start(priv, req_ssid);
}
}
done:
kfree(bss_desc);
kfree(beacon_ie);
return ret;
}
/*
* IOCTL request handler to set host sleep configuration.
*
* This function prepares the correct firmware command and
* issues it.
*/
static int mwifiex_set_hs_params(struct mwifiex_private *priv, u16 action,
int cmd_type, struct mwifiex_ds_hs_cfg *hs_cfg)
{
struct mwifiex_adapter *adapter = priv->adapter;
int status = 0;
u32 prev_cond = 0;
if (!hs_cfg)
return -ENOMEM;
switch (action) {
case HostCmd_ACT_GEN_SET:
if (adapter->pps_uapsd_mode) {
dev_dbg(adapter->dev, "info: Host Sleep IOCTL"
" is blocked in UAPSD/PPS mode\n");
status = -1;
break;
}
if (hs_cfg->is_invoke_hostcmd) {
if (hs_cfg->conditions == HOST_SLEEP_CFG_CANCEL) {
if (!adapter->is_hs_configured)
/* Already cancelled */
break;
/* Save previous condition */
prev_cond = le32_to_cpu(adapter->hs_cfg
.conditions);
adapter->hs_cfg.conditions =
cpu_to_le32(hs_cfg->conditions);
} else if (hs_cfg->conditions) {
adapter->hs_cfg.conditions =
cpu_to_le32(hs_cfg->conditions);
adapter->hs_cfg.gpio = (u8)hs_cfg->gpio;
if (hs_cfg->gap)
adapter->hs_cfg.gap = (u8)hs_cfg->gap;
} else if (adapter->hs_cfg.conditions
== cpu_to_le32(HOST_SLEEP_CFG_CANCEL)) {
/* Return failure if no parameters for HS
enable */
status = -1;
break;
}
if (cmd_type == MWIFIEX_SYNC_CMD)
status = mwifiex_send_cmd_sync(priv,
HostCmd_CMD_802_11_HS_CFG_ENH,
HostCmd_ACT_GEN_SET, 0,
&adapter->hs_cfg);
else
status = mwifiex_send_cmd_async(priv,
HostCmd_CMD_802_11_HS_CFG_ENH,
HostCmd_ACT_GEN_SET, 0,
&adapter->hs_cfg);
if (hs_cfg->conditions == HOST_SLEEP_CFG_CANCEL)
/* Restore previous condition */
adapter->hs_cfg.conditions =
cpu_to_le32(prev_cond);
} else {
adapter->hs_cfg.conditions =
cpu_to_le32(hs_cfg->conditions);
adapter->hs_cfg.gpio = (u8)hs_cfg->gpio;
adapter->hs_cfg.gap = (u8)hs_cfg->gap;
}
break;
case HostCmd_ACT_GEN_GET:
hs_cfg->conditions = le32_to_cpu(adapter->hs_cfg.conditions);
hs_cfg->gpio = adapter->hs_cfg.gpio;
hs_cfg->gap = adapter->hs_cfg.gap;
break;
default:
status = -1;
break;
}
return status;
}
/*
* Sends IOCTL request to cancel the existing Host Sleep configuration.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int mwifiex_cancel_hs(struct mwifiex_private *priv, int cmd_type)
{
struct mwifiex_ds_hs_cfg hscfg;
hscfg.conditions = HOST_SLEEP_CFG_CANCEL;
hscfg.is_invoke_hostcmd = true;
return mwifiex_set_hs_params(priv, HostCmd_ACT_GEN_SET,
cmd_type, &hscfg);
}
EXPORT_SYMBOL_GPL(mwifiex_cancel_hs);
/*
* Sends IOCTL request to cancel the existing Host Sleep configuration.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int mwifiex_enable_hs(struct mwifiex_adapter *adapter)
{
struct mwifiex_ds_hs_cfg hscfg;
if (adapter->hs_activated) {
dev_dbg(adapter->dev, "cmd: HS Already actived\n");
return true;
}
adapter->hs_activate_wait_q_woken = false;
memset(&hscfg, 0, sizeof(struct mwifiex_ds_hs_cfg));
hscfg.is_invoke_hostcmd = true;
if (mwifiex_set_hs_params(mwifiex_get_priv(adapter,
MWIFIEX_BSS_ROLE_STA),
HostCmd_ACT_GEN_SET, MWIFIEX_SYNC_CMD,
&hscfg)) {
dev_err(adapter->dev, "IOCTL request HS enable failed\n");
return false;
}
if (wait_event_interruptible(adapter->hs_activate_wait_q,
adapter->hs_activate_wait_q_woken)) {
dev_err(adapter->dev, "hs_activate_wait_q terminated\n");
return false;
}
return true;
}
EXPORT_SYMBOL_GPL(mwifiex_enable_hs);
/*
* IOCTL request handler to get BSS information.
*
* This function collates the information from different driver structures
* to send to the user.
*/
int mwifiex_get_bss_info(struct mwifiex_private *priv,
struct mwifiex_bss_info *info)
{
struct mwifiex_adapter *adapter = priv->adapter;
struct mwifiex_bssdescriptor *bss_desc;
if (!info)
return -1;
bss_desc = &priv->curr_bss_params.bss_descriptor;
info->bss_mode = priv->bss_mode;
memcpy(&info->ssid, &bss_desc->ssid, sizeof(struct cfg80211_ssid));
memcpy(&info->bssid, &bss_desc->mac_address, ETH_ALEN);
info->bss_chan = bss_desc->channel;
info->region_code = adapter->region_code;
info->media_connected = priv->media_connected;
info->max_power_level = priv->max_tx_power_level;
info->min_power_level = priv->min_tx_power_level;
info->adhoc_state = priv->adhoc_state;
info->bcn_nf_last = priv->bcn_nf_last;
if (priv->sec_info.wep_enabled)
info->wep_status = true;
else
info->wep_status = false;
info->is_hs_configured = adapter->is_hs_configured;
info->is_deep_sleep = adapter->is_deep_sleep;
return 0;
}
/*
* The function disables auto deep sleep mode.
*/
int mwifiex_disable_auto_ds(struct mwifiex_private *priv)
{
struct mwifiex_ds_auto_ds auto_ds;
auto_ds.auto_ds = DEEP_SLEEP_OFF;
return mwifiex_send_cmd_sync(priv, HostCmd_CMD_802_11_PS_MODE_ENH,
DIS_AUTO_PS, BITMAP_AUTO_DS, &auto_ds);
}
EXPORT_SYMBOL_GPL(mwifiex_disable_auto_ds);
/*
* IOCTL request handler to set/get active channel.
*
* This function performs validity checking on channel/frequency
* compatibility and returns failure if not valid.
*/
int mwifiex_bss_set_channel(struct mwifiex_private *priv,
struct mwifiex_chan_freq_power *chan)
{
struct mwifiex_adapter *adapter = priv->adapter;
struct mwifiex_chan_freq_power *cfp = NULL;
if (!chan)
return -1;
if (!chan->channel && !chan->freq)
return -1;
if (adapter->adhoc_start_band & BAND_AN)
adapter->adhoc_start_band = BAND_G | BAND_B | BAND_GN;
else if (adapter->adhoc_start_band & BAND_A)
adapter->adhoc_start_band = BAND_G | BAND_B;
if (chan->channel) {
if (chan->channel <= MAX_CHANNEL_BAND_BG)
cfp = mwifiex_get_cfp(priv, 0, (u16) chan->channel, 0);
if (!cfp) {
cfp = mwifiex_get_cfp(priv, BAND_A,
(u16) chan->channel, 0);
if (cfp) {
if (adapter->adhoc_11n_enabled)
adapter->adhoc_start_band = BAND_A
| BAND_AN;
else
adapter->adhoc_start_band = BAND_A;
}
}
} else {
if (chan->freq <= MAX_FREQUENCY_BAND_BG)
cfp = mwifiex_get_cfp(priv, 0, 0, chan->freq);
if (!cfp) {
cfp = mwifiex_get_cfp(priv, BAND_A, 0, chan->freq);
if (cfp) {
if (adapter->adhoc_11n_enabled)
adapter->adhoc_start_band = BAND_A
| BAND_AN;
else
adapter->adhoc_start_band = BAND_A;
}
}
}
if (!cfp || !cfp->channel) {
dev_err(adapter->dev, "invalid channel/freq\n");
return -1;
}
priv->adhoc_channel = (u8) cfp->channel;
chan->channel = cfp->channel;
chan->freq = cfp->freq;
return 0;
}
/*
* IOCTL request handler to set/get Ad-Hoc channel.
*
* This function prepares the correct firmware command and
* issues it to set or get the ad-hoc channel.
*/
static int mwifiex_bss_ioctl_ibss_channel(struct mwifiex_private *priv,
u16 action, u16 *channel)
{
if (action == HostCmd_ACT_GEN_GET) {
if (!priv->media_connected) {
*channel = priv->adhoc_channel;
return 0;
}
} else {
priv->adhoc_channel = (u8) *channel;
}
return mwifiex_send_cmd_sync(priv, HostCmd_CMD_802_11_RF_CHANNEL,
action, 0, channel);
}
/*
* IOCTL request handler to change Ad-Hoc channel.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*
* The function follows the following steps to perform the change -
* - Get current IBSS information
* - Get current channel
* - If no change is required, return
* - If not connected, change channel and return
* - If connected,
* - Disconnect
* - Change channel
* - Perform specific SSID scan with same SSID
* - Start/Join the IBSS
*/
int
mwifiex_drv_change_adhoc_chan(struct mwifiex_private *priv, u16 channel)
{
int ret;
struct mwifiex_bss_info bss_info;
struct mwifiex_ssid_bssid ssid_bssid;
u16 curr_chan = 0;
struct cfg80211_bss *bss = NULL;
struct ieee80211_channel *chan;
enum ieee80211_band band;
memset(&bss_info, 0, sizeof(bss_info));
/* Get BSS information */
if (mwifiex_get_bss_info(priv, &bss_info))
return -1;
/* Get current channel */
ret = mwifiex_bss_ioctl_ibss_channel(priv, HostCmd_ACT_GEN_GET,
&curr_chan);
if (curr_chan == channel) {
ret = 0;
goto done;
}
dev_dbg(priv->adapter->dev, "cmd: updating channel from %d to %d\n",
curr_chan, channel);
if (!bss_info.media_connected) {
ret = 0;
goto done;
}
/* Do disonnect */
memset(&ssid_bssid, 0, ETH_ALEN);
ret = mwifiex_deauthenticate(priv, ssid_bssid.bssid);
ret = mwifiex_bss_ioctl_ibss_channel(priv, HostCmd_ACT_GEN_SET,
&channel);
/* Do specific SSID scanning */
if (mwifiex_request_scan(priv, &bss_info.ssid)) {
ret = -1;
goto done;
}
band = mwifiex_band_to_radio_type(priv->curr_bss_params.band);
chan = __ieee80211_get_channel(priv->wdev->wiphy,
ieee80211_channel_to_frequency(channel,
band));
/* Find the BSS we want using available scan results */
bss = cfg80211_get_bss(priv->wdev->wiphy, chan, bss_info.bssid,
bss_info.ssid.ssid, bss_info.ssid.ssid_len,
WLAN_CAPABILITY_ESS, WLAN_CAPABILITY_ESS);
if (!bss)
wiphy_warn(priv->wdev->wiphy, "assoc: bss %pM not in scan results\n",
bss_info.bssid);
ret = mwifiex_bss_start(priv, bss, &bss_info.ssid);
done:
return ret;
}
/*
* IOCTL request handler to get rate.
*
* This function prepares the correct firmware command and
* issues it to get the current rate if it is connected,
* otherwise, the function returns the lowest supported rate
* for the band.
*/
static int mwifiex_rate_ioctl_get_rate_value(struct mwifiex_private *priv,
struct mwifiex_rate_cfg *rate_cfg)
{
rate_cfg->is_rate_auto = priv->is_data_rate_auto;
return mwifiex_send_cmd_sync(priv, HostCmd_CMD_802_11_TX_RATE_QUERY,
HostCmd_ACT_GEN_GET, 0, NULL);
}
/*
* IOCTL request handler to set rate.
*
* This function prepares the correct firmware command and
* issues it to set the current rate.
*
* The function also performs validation checking on the supplied value.
*/
static int mwifiex_rate_ioctl_set_rate_value(struct mwifiex_private *priv,
struct mwifiex_rate_cfg *rate_cfg)
{
u8 rates[MWIFIEX_SUPPORTED_RATES];
u8 *rate;
int rate_index, ret;
u16 bitmap_rates[MAX_BITMAP_RATES_SIZE];
u32 i;
struct mwifiex_adapter *adapter = priv->adapter;
if (rate_cfg->is_rate_auto) {
memset(bitmap_rates, 0, sizeof(bitmap_rates));
/* Support all HR/DSSS rates */
bitmap_rates[0] = 0x000F;
/* Support all OFDM rates */
bitmap_rates[1] = 0x00FF;
/* Support all HT-MCSs rate */
for (i = 0; i < ARRAY_SIZE(priv->bitmap_rates) - 3; i++)
bitmap_rates[i + 2] = 0xFFFF;
bitmap_rates[9] = 0x3FFF;
} else {
memset(rates, 0, sizeof(rates));
mwifiex_get_active_data_rates(priv, rates);
rate = rates;
for (i = 0; (rate[i] && i < MWIFIEX_SUPPORTED_RATES); i++) {
dev_dbg(adapter->dev, "info: rate=%#x wanted=%#x\n",
rate[i], rate_cfg->rate);
if ((rate[i] & 0x7f) == (rate_cfg->rate & 0x7f))
break;
}
if ((i == MWIFIEX_SUPPORTED_RATES) || !rate[i]) {
dev_err(adapter->dev, "fixed data rate %#x is out "
"of range\n", rate_cfg->rate);
return -1;
}
memset(bitmap_rates, 0, sizeof(bitmap_rates));
rate_index = mwifiex_data_rate_to_index(rate_cfg->rate);
/* Only allow b/g rates to be set */
if (rate_index >= MWIFIEX_RATE_INDEX_HRDSSS0 &&
rate_index <= MWIFIEX_RATE_INDEX_HRDSSS3) {
bitmap_rates[0] = 1 << rate_index;
} else {
rate_index -= 1; /* There is a 0x00 in the table */
if (rate_index >= MWIFIEX_RATE_INDEX_OFDM0 &&
rate_index <= MWIFIEX_RATE_INDEX_OFDM7)
bitmap_rates[1] = 1 << (rate_index -
MWIFIEX_RATE_INDEX_OFDM0);
}
}
ret = mwifiex_send_cmd_sync(priv, HostCmd_CMD_TX_RATE_CFG,
HostCmd_ACT_GEN_SET, 0, bitmap_rates);
return ret;
}
/*
* IOCTL request handler to set/get rate.
*
* This function can be used to set/get either the rate value or the
* rate index.
*/
static int mwifiex_rate_ioctl_cfg(struct mwifiex_private *priv,
struct mwifiex_rate_cfg *rate_cfg)
{
int status;
if (!rate_cfg)
return -1;
if (rate_cfg->action == HostCmd_ACT_GEN_GET)
status = mwifiex_rate_ioctl_get_rate_value(priv, rate_cfg);
else
status = mwifiex_rate_ioctl_set_rate_value(priv, rate_cfg);
return status;
}
/*
* Sends IOCTL request to get the data rate.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int mwifiex_drv_get_data_rate(struct mwifiex_private *priv,
struct mwifiex_rate_cfg *rate)
{
int ret;
memset(rate, 0, sizeof(struct mwifiex_rate_cfg));
rate->action = HostCmd_ACT_GEN_GET;
ret = mwifiex_rate_ioctl_cfg(priv, rate);
if (!ret) {
if (rate->is_rate_auto)
rate->rate = mwifiex_index_to_data_rate(priv,
priv->tx_rate,
priv->tx_htinfo
);
else
rate->rate = priv->data_rate;
} else {
ret = -1;
}
return ret;
}
/*
* IOCTL request handler to set tx power configuration.
*
* This function prepares the correct firmware command and
* issues it.
*
* For non-auto power mode, all the following power groups are set -
* - Modulation class HR/DSSS
* - Modulation class OFDM
* - Modulation class HTBW20
* - Modulation class HTBW40
*/
int mwifiex_set_tx_power(struct mwifiex_private *priv,
struct mwifiex_power_cfg *power_cfg)
{
int ret;
struct host_cmd_ds_txpwr_cfg *txp_cfg;
struct mwifiex_types_power_group *pg_tlv;
struct mwifiex_power_group *pg;
u8 *buf;
u16 dbm = 0;
if (!power_cfg->is_power_auto) {
dbm = (u16) power_cfg->power_level;
if ((dbm < priv->min_tx_power_level) ||
(dbm > priv->max_tx_power_level)) {
dev_err(priv->adapter->dev, "txpower value %d dBm"
" is out of range (%d dBm-%d dBm)\n",
dbm, priv->min_tx_power_level,
priv->max_tx_power_level);
return -1;
}
}
buf = kzalloc(MWIFIEX_SIZE_OF_CMD_BUFFER, GFP_KERNEL);
if (!buf) {
dev_err(priv->adapter->dev, "%s: failed to alloc cmd buffer\n",
__func__);
return -ENOMEM;
}
txp_cfg = (struct host_cmd_ds_txpwr_cfg *) buf;
txp_cfg->action = cpu_to_le16(HostCmd_ACT_GEN_SET);
if (!power_cfg->is_power_auto) {
txp_cfg->mode = cpu_to_le32(1);
pg_tlv = (struct mwifiex_types_power_group *)
(buf + sizeof(struct host_cmd_ds_txpwr_cfg));
pg_tlv->type = TLV_TYPE_POWER_GROUP;
pg_tlv->length = 4 * sizeof(struct mwifiex_power_group);
pg = (struct mwifiex_power_group *)
(buf + sizeof(struct host_cmd_ds_txpwr_cfg)
+ sizeof(struct mwifiex_types_power_group));
/* Power group for modulation class HR/DSSS */
pg->first_rate_code = 0x00;
pg->last_rate_code = 0x03;
pg->modulation_class = MOD_CLASS_HR_DSSS;
pg->power_step = 0;
pg->power_min = (s8) dbm;
pg->power_max = (s8) dbm;
pg++;
/* Power group for modulation class OFDM */
pg->first_rate_code = 0x00;
pg->last_rate_code = 0x07;
pg->modulation_class = MOD_CLASS_OFDM;
pg->power_step = 0;
pg->power_min = (s8) dbm;
pg->power_max = (s8) dbm;
pg++;
/* Power group for modulation class HTBW20 */
pg->first_rate_code = 0x00;
pg->last_rate_code = 0x20;
pg->modulation_class = MOD_CLASS_HT;
pg->power_step = 0;
pg->power_min = (s8) dbm;
pg->power_max = (s8) dbm;
pg->ht_bandwidth = HT_BW_20;
pg++;
/* Power group for modulation class HTBW40 */
pg->first_rate_code = 0x00;
pg->last_rate_code = 0x20;
pg->modulation_class = MOD_CLASS_HT;
pg->power_step = 0;
pg->power_min = (s8) dbm;
pg->power_max = (s8) dbm;
pg->ht_bandwidth = HT_BW_40;
}
ret = mwifiex_send_cmd_sync(priv, HostCmd_CMD_TXPWR_CFG,
HostCmd_ACT_GEN_SET, 0, buf);
kfree(buf);
return ret;
}
/*
* IOCTL request handler to get power save mode.
*
* This function prepares the correct firmware command and
* issues it.
*/
int mwifiex_drv_set_power(struct mwifiex_private *priv, u32 *ps_mode)
{
int ret;
struct mwifiex_adapter *adapter = priv->adapter;
u16 sub_cmd;
if (*ps_mode)
adapter->ps_mode = MWIFIEX_802_11_POWER_MODE_PSP;
else
adapter->ps_mode = MWIFIEX_802_11_POWER_MODE_CAM;
sub_cmd = (*ps_mode) ? EN_AUTO_PS : DIS_AUTO_PS;
ret = mwifiex_send_cmd_sync(priv, HostCmd_CMD_802_11_PS_MODE_ENH,
sub_cmd, BITMAP_STA_PS, NULL);
if ((!ret) && (sub_cmd == DIS_AUTO_PS))
ret = mwifiex_send_cmd_async(priv,
HostCmd_CMD_802_11_PS_MODE_ENH,
GET_PS, 0, NULL);
return ret;
}
/*
* IOCTL request handler to set/reset WPA IE.
*
* The supplied WPA IE is treated as a opaque buffer. Only the first field
* is checked to determine WPA version. If buffer length is zero, the existing
* WPA IE is reset.
*/
static int mwifiex_set_wpa_ie_helper(struct mwifiex_private *priv,
u8 *ie_data_ptr, u16 ie_len)
{
if (ie_len) {
if (ie_len > sizeof(priv->wpa_ie)) {
dev_err(priv->adapter->dev,
"failed to copy WPA IE, too big\n");
return -1;
}
memcpy(priv->wpa_ie, ie_data_ptr, ie_len);
priv->wpa_ie_len = (u8) ie_len;
dev_dbg(priv->adapter->dev, "cmd: Set Wpa_ie_len=%d IE=%#x\n",
priv->wpa_ie_len, priv->wpa_ie[0]);
if (priv->wpa_ie[0] == WLAN_EID_WPA) {
priv->sec_info.wpa_enabled = true;
} else if (priv->wpa_ie[0] == WLAN_EID_RSN) {
priv->sec_info.wpa2_enabled = true;
} else {
priv->sec_info.wpa_enabled = false;
priv->sec_info.wpa2_enabled = false;
}
} else {
memset(priv->wpa_ie, 0, sizeof(priv->wpa_ie));
priv->wpa_ie_len = 0;
dev_dbg(priv->adapter->dev, "info: reset wpa_ie_len=%d IE=%#x\n",
priv->wpa_ie_len, priv->wpa_ie[0]);
priv->sec_info.wpa_enabled = false;
priv->sec_info.wpa2_enabled = false;
}
return 0;
}
/*
* IOCTL request handler to set/reset WAPI IE.
*
* The supplied WAPI IE is treated as a opaque buffer. Only the first field
* is checked to internally enable WAPI. If buffer length is zero, the existing
* WAPI IE is reset.
*/
static int mwifiex_set_wapi_ie(struct mwifiex_private *priv,
u8 *ie_data_ptr, u16 ie_len)
{
if (ie_len) {
if (ie_len > sizeof(priv->wapi_ie)) {
dev_dbg(priv->adapter->dev,
"info: failed to copy WAPI IE, too big\n");
return -1;
}
memcpy(priv->wapi_ie, ie_data_ptr, ie_len);
priv->wapi_ie_len = ie_len;
dev_dbg(priv->adapter->dev, "cmd: Set wapi_ie_len=%d IE=%#x\n",
priv->wapi_ie_len, priv->wapi_ie[0]);
if (priv->wapi_ie[0] == WLAN_EID_BSS_AC_ACCESS_DELAY)
priv->sec_info.wapi_enabled = true;
} else {
memset(priv->wapi_ie, 0, sizeof(priv->wapi_ie));
priv->wapi_ie_len = ie_len;
dev_dbg(priv->adapter->dev,
"info: Reset wapi_ie_len=%d IE=%#x\n",
priv->wapi_ie_len, priv->wapi_ie[0]);
priv->sec_info.wapi_enabled = false;
}
return 0;
}
/*
* IOCTL request handler to set WAPI key.
*
* This function prepares the correct firmware command and
* issues it.
*/
static int mwifiex_sec_ioctl_set_wapi_key(struct mwifiex_private *priv,
struct mwifiex_ds_encrypt_key *encrypt_key)
{
return mwifiex_send_cmd_sync(priv, HostCmd_CMD_802_11_KEY_MATERIAL,
HostCmd_ACT_GEN_SET, KEY_INFO_ENABLED,
encrypt_key);
}
/*
* IOCTL request handler to set WEP network key.
*
* This function prepares the correct firmware command and
* issues it, after validation checks.
*/
static int mwifiex_sec_ioctl_set_wep_key(struct mwifiex_private *priv,
struct mwifiex_ds_encrypt_key *encrypt_key)
{
int ret;
struct mwifiex_wep_key *wep_key;
int index;
if (priv->wep_key_curr_index >= NUM_WEP_KEYS)
priv->wep_key_curr_index = 0;
wep_key = &priv->wep_key[priv->wep_key_curr_index];
index = encrypt_key->key_index;
if (encrypt_key->key_disable) {
priv->sec_info.wep_enabled = 0;
} else if (!encrypt_key->key_len) {
/* Copy the required key as the current key */
wep_key = &priv->wep_key[index];
if (!wep_key->key_length) {
dev_err(priv->adapter->dev,
"key not set, so cannot enable it\n");
return -1;
}
priv->wep_key_curr_index = (u16) index;
priv->sec_info.wep_enabled = 1;
} else {
wep_key = &priv->wep_key[index];
memset(wep_key, 0, sizeof(struct mwifiex_wep_key));
/* Copy the key in the driver */
memcpy(wep_key->key_material,
encrypt_key->key_material,
encrypt_key->key_len);
wep_key->key_index = index;
wep_key->key_length = encrypt_key->key_len;
priv->sec_info.wep_enabled = 1;
}
if (wep_key->key_length) {
/* Send request to firmware */
ret = mwifiex_send_cmd_async(priv,
HostCmd_CMD_802_11_KEY_MATERIAL,
HostCmd_ACT_GEN_SET, 0, NULL);
if (ret)
return ret;
}
if (priv->sec_info.wep_enabled)
priv->curr_pkt_filter |= HostCmd_ACT_MAC_WEP_ENABLE;
else
priv->curr_pkt_filter &= ~HostCmd_ACT_MAC_WEP_ENABLE;
ret = mwifiex_send_cmd_sync(priv, HostCmd_CMD_MAC_CONTROL,
HostCmd_ACT_GEN_SET, 0,
&priv->curr_pkt_filter);
return ret;
}
/*
* IOCTL request handler to set WPA key.
*
* This function prepares the correct firmware command and
* issues it, after validation checks.
*
* Current driver only supports key length of up to 32 bytes.
*
* This function can also be used to disable a currently set key.
*/
static int mwifiex_sec_ioctl_set_wpa_key(struct mwifiex_private *priv,
struct mwifiex_ds_encrypt_key *encrypt_key)
{
int ret;
u8 remove_key = false;
struct host_cmd_ds_802_11_key_material *ibss_key;
/* Current driver only supports key length of up to 32 bytes */
if (encrypt_key->key_len > WLAN_MAX_KEY_LEN) {
dev_err(priv->adapter->dev, "key length too long\n");
return -1;
}
if (priv->bss_mode == NL80211_IFTYPE_ADHOC) {
/*
* IBSS/WPA-None uses only one key (Group) for both receiving
* and sending unicast and multicast packets.
*/
/* Send the key as PTK to firmware */
encrypt_key->key_index = MWIFIEX_KEY_INDEX_UNICAST;
ret = mwifiex_send_cmd_async(priv,
HostCmd_CMD_802_11_KEY_MATERIAL,
HostCmd_ACT_GEN_SET,
KEY_INFO_ENABLED, encrypt_key);
if (ret)
return ret;
ibss_key = &priv->aes_key;
memset(ibss_key, 0,
sizeof(struct host_cmd_ds_802_11_key_material));
/* Copy the key in the driver */
memcpy(ibss_key->key_param_set.key, encrypt_key->key_material,
encrypt_key->key_len);
memcpy(&ibss_key->key_param_set.key_len, &encrypt_key->key_len,
sizeof(ibss_key->key_param_set.key_len));
ibss_key->key_param_set.key_type_id
= cpu_to_le16(KEY_TYPE_ID_TKIP);
ibss_key->key_param_set.key_info = cpu_to_le16(KEY_ENABLED);
/* Send the key as GTK to firmware */
encrypt_key->key_index = ~MWIFIEX_KEY_INDEX_UNICAST;
}
if (!encrypt_key->key_index)
encrypt_key->key_index = MWIFIEX_KEY_INDEX_UNICAST;
if (remove_key)
ret = mwifiex_send_cmd_sync(priv,
HostCmd_CMD_802_11_KEY_MATERIAL,
HostCmd_ACT_GEN_SET,
!KEY_INFO_ENABLED, encrypt_key);
else
ret = mwifiex_send_cmd_sync(priv,
HostCmd_CMD_802_11_KEY_MATERIAL,
HostCmd_ACT_GEN_SET,
KEY_INFO_ENABLED, encrypt_key);
return ret;
}
/*
* IOCTL request handler to set/get network keys.
*
* This is a generic key handling function which supports WEP, WPA
* and WAPI.
*/
static int
mwifiex_sec_ioctl_encrypt_key(struct mwifiex_private *priv,
struct mwifiex_ds_encrypt_key *encrypt_key)
{
int status;
if (encrypt_key->is_wapi_key)
status = mwifiex_sec_ioctl_set_wapi_key(priv, encrypt_key);
else if (encrypt_key->key_len > WLAN_KEY_LEN_WEP104)
status = mwifiex_sec_ioctl_set_wpa_key(priv, encrypt_key);
else
status = mwifiex_sec_ioctl_set_wep_key(priv, encrypt_key);
return status;
}
/*
* This function returns the driver version.
*/
int
mwifiex_drv_get_driver_version(struct mwifiex_adapter *adapter, char *version,
int max_len)
{
union {
u32 l;
u8 c[4];
} ver;
char fw_ver[32];
ver.l = adapter->fw_release_number;
sprintf(fw_ver, "%u.%u.%u.p%u", ver.c[2], ver.c[1], ver.c[0], ver.c[3]);
snprintf(version, max_len, driver_version, fw_ver);
dev_dbg(adapter->dev, "info: MWIFIEX VERSION: %s\n", version);
return 0;
}
/*
* Sends IOCTL request to get signal information.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int mwifiex_get_signal_info(struct mwifiex_private *priv,
struct mwifiex_ds_get_signal *signal)
{
int status;
signal->selector = ALL_RSSI_INFO_MASK;
/* Signal info can be obtained only if connected */
if (!priv->media_connected) {
dev_dbg(priv->adapter->dev,
"info: Can not get signal in disconnected state\n");
return -1;
}
status = mwifiex_send_cmd_sync(priv, HostCmd_CMD_RSSI_INFO,
HostCmd_ACT_GEN_GET, 0, signal);
if (!status) {
if (signal->selector & BCN_RSSI_AVG_MASK)
priv->qual_level = signal->bcn_rssi_avg;
if (signal->selector & BCN_NF_AVG_MASK)
priv->qual_noise = signal->bcn_nf_avg;
}
return status;
}
/*
* Sends IOCTL request to set encoding parameters.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int mwifiex_set_encode(struct mwifiex_private *priv, const u8 *key,
int key_len, u8 key_index, int disable)
{
struct mwifiex_ds_encrypt_key encrypt_key;
memset(&encrypt_key, 0, sizeof(struct mwifiex_ds_encrypt_key));
encrypt_key.key_len = key_len;
if (!disable) {
encrypt_key.key_index = key_index;
if (key_len)
memcpy(encrypt_key.key_material, key, key_len);
} else {
encrypt_key.key_disable = true;
}
return mwifiex_sec_ioctl_encrypt_key(priv, &encrypt_key);
}
/*
* Sends IOCTL request to get extended version.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int
mwifiex_get_ver_ext(struct mwifiex_private *priv)
{
struct mwifiex_ver_ext ver_ext;
memset(&ver_ext, 0, sizeof(struct host_cmd_ds_version_ext));
if (mwifiex_send_cmd_sync(priv, HostCmd_CMD_VERSION_EXT,
HostCmd_ACT_GEN_GET, 0, &ver_ext))
return -1;
return 0;
}
/*
* Sends IOCTL request to get statistics information.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int
mwifiex_get_stats_info(struct mwifiex_private *priv,
struct mwifiex_ds_get_stats *log)
{
return mwifiex_send_cmd_sync(priv, HostCmd_CMD_802_11_GET_LOG,
HostCmd_ACT_GEN_GET, 0, log);
}
/*
* IOCTL request handler to read/write register.
*
* This function prepares the correct firmware command and
* issues it.
*
* Access to the following registers are supported -
* - MAC
* - BBP
* - RF
* - PMIC
* - CAU
*/
static int mwifiex_reg_mem_ioctl_reg_rw(struct mwifiex_private *priv,
struct mwifiex_ds_reg_rw *reg_rw,
u16 action)
{
u16 cmd_no;
switch (le32_to_cpu(reg_rw->type)) {
case MWIFIEX_REG_MAC:
cmd_no = HostCmd_CMD_MAC_REG_ACCESS;
break;
case MWIFIEX_REG_BBP:
cmd_no = HostCmd_CMD_BBP_REG_ACCESS;
break;
case MWIFIEX_REG_RF:
cmd_no = HostCmd_CMD_RF_REG_ACCESS;
break;
case MWIFIEX_REG_PMIC:
cmd_no = HostCmd_CMD_PMIC_REG_ACCESS;
break;
case MWIFIEX_REG_CAU:
cmd_no = HostCmd_CMD_CAU_REG_ACCESS;
break;
default:
return -1;
}
return mwifiex_send_cmd_sync(priv, cmd_no, action, 0, reg_rw);
}
/*
* Sends IOCTL request to write to a register.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int
mwifiex_reg_write(struct mwifiex_private *priv, u32 reg_type,
u32 reg_offset, u32 reg_value)
{
struct mwifiex_ds_reg_rw reg_rw;
reg_rw.type = cpu_to_le32(reg_type);
reg_rw.offset = cpu_to_le32(reg_offset);
reg_rw.value = cpu_to_le32(reg_value);
return mwifiex_reg_mem_ioctl_reg_rw(priv, ®_rw, HostCmd_ACT_GEN_SET);
}
/*
* Sends IOCTL request to read from a register.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int
mwifiex_reg_read(struct mwifiex_private *priv, u32 reg_type,
u32 reg_offset, u32 *value)
{
int ret;
struct mwifiex_ds_reg_rw reg_rw;
reg_rw.type = cpu_to_le32(reg_type);
reg_rw.offset = cpu_to_le32(reg_offset);
ret = mwifiex_reg_mem_ioctl_reg_rw(priv, ®_rw, HostCmd_ACT_GEN_GET);
if (ret)
goto done;
*value = le32_to_cpu(reg_rw.value);
done:
return ret;
}
/*
* Sends IOCTL request to read from EEPROM.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int
mwifiex_eeprom_read(struct mwifiex_private *priv, u16 offset, u16 bytes,
u8 *value)
{
int ret;
struct mwifiex_ds_read_eeprom rd_eeprom;
rd_eeprom.offset = cpu_to_le16((u16) offset);
rd_eeprom.byte_count = cpu_to_le16((u16) bytes);
/* Send request to firmware */
ret = mwifiex_send_cmd_sync(priv, HostCmd_CMD_802_11_EEPROM_ACCESS,
HostCmd_ACT_GEN_GET, 0, &rd_eeprom);
if (!ret)
memcpy(value, rd_eeprom.value, MAX_EEPROM_DATA);
return ret;
}
/*
* This function sets a generic IE. In addition to generic IE, it can
* also handle WPA, WPA2 and WAPI IEs.
*/
static int
mwifiex_set_gen_ie_helper(struct mwifiex_private *priv, u8 *ie_data_ptr,
u16 ie_len)
{
int ret = 0;
struct ieee_types_vendor_header *pvendor_ie;
const u8 wpa_oui[] = { 0x00, 0x50, 0xf2, 0x01 };
const u8 wps_oui[] = { 0x00, 0x50, 0xf2, 0x04 };
/* If the passed length is zero, reset the buffer */
if (!ie_len) {
priv->gen_ie_buf_len = 0;
priv->wps.session_enable = false;
return 0;
} else if (!ie_data_ptr) {
return -1;
}
pvendor_ie = (struct ieee_types_vendor_header *) ie_data_ptr;
/* Test to see if it is a WPA IE, if not, then it is a gen IE */
if (((pvendor_ie->element_id == WLAN_EID_WPA) &&
(!memcmp(pvendor_ie->oui, wpa_oui, sizeof(wpa_oui)))) ||
(pvendor_ie->element_id == WLAN_EID_RSN)) {
/* IE is a WPA/WPA2 IE so call set_wpa function */
ret = mwifiex_set_wpa_ie_helper(priv, ie_data_ptr, ie_len);
priv->wps.session_enable = false;
return ret;
} else if (pvendor_ie->element_id == WLAN_EID_BSS_AC_ACCESS_DELAY) {
/* IE is a WAPI IE so call set_wapi function */
ret = mwifiex_set_wapi_ie(priv, ie_data_ptr, ie_len);
return ret;
}
/*
* Verify that the passed length is not larger than the
* available space remaining in the buffer
*/
if (ie_len < (sizeof(priv->gen_ie_buf) - priv->gen_ie_buf_len)) {
/* Test to see if it is a WPS IE, if so, enable
* wps session flag
*/
pvendor_ie = (struct ieee_types_vendor_header *) ie_data_ptr;
if ((pvendor_ie->element_id == WLAN_EID_VENDOR_SPECIFIC) &&
(!memcmp(pvendor_ie->oui, wps_oui, sizeof(wps_oui)))) {
priv->wps.session_enable = true;
dev_dbg(priv->adapter->dev,
"info: WPS Session Enabled.\n");
}
/* Append the passed data to the end of the
genIeBuffer */
memcpy(priv->gen_ie_buf + priv->gen_ie_buf_len, ie_data_ptr,
ie_len);
/* Increment the stored buffer length by the
size passed */
priv->gen_ie_buf_len += ie_len;
} else {
/* Passed data does not fit in the remaining
buffer space */
ret = -1;
}
/* Return 0, or -1 for error case */
return ret;
}
/*
* IOCTL request handler to set/get generic IE.
*
* In addition to various generic IEs, this function can also be
* used to set the ARP filter.
*/
static int mwifiex_misc_ioctl_gen_ie(struct mwifiex_private *priv,
struct mwifiex_ds_misc_gen_ie *gen_ie,
u16 action)
{
struct mwifiex_adapter *adapter = priv->adapter;
switch (gen_ie->type) {
case MWIFIEX_IE_TYPE_GEN_IE:
if (action == HostCmd_ACT_GEN_GET) {
gen_ie->len = priv->wpa_ie_len;
memcpy(gen_ie->ie_data, priv->wpa_ie, gen_ie->len);
} else {
mwifiex_set_gen_ie_helper(priv, gen_ie->ie_data,
(u16) gen_ie->len);
}
break;
case MWIFIEX_IE_TYPE_ARP_FILTER:
memset(adapter->arp_filter, 0, sizeof(adapter->arp_filter));
if (gen_ie->len > ARP_FILTER_MAX_BUF_SIZE) {
adapter->arp_filter_size = 0;
dev_err(adapter->dev, "invalid ARP filter size\n");
return -1;
} else {
memcpy(adapter->arp_filter, gen_ie->ie_data,
gen_ie->len);
adapter->arp_filter_size = gen_ie->len;
}
break;
default:
dev_err(adapter->dev, "invalid IE type\n");
return -1;
}
return 0;
}
/*
* Sends IOCTL request to set a generic IE.
*
* This function allocates the IOCTL request buffer, fills it
* with requisite parameters and calls the IOCTL handler.
*/
int
mwifiex_set_gen_ie(struct mwifiex_private *priv, u8 *ie, int ie_len)
{
struct mwifiex_ds_misc_gen_ie gen_ie;
if (ie_len > IEEE_MAX_IE_SIZE)
return -EFAULT;
gen_ie.type = MWIFIEX_IE_TYPE_GEN_IE;
gen_ie.len = ie_len;
memcpy(gen_ie.ie_data, ie, ie_len);
if (mwifiex_misc_ioctl_gen_ie(priv, &gen_ie, HostCmd_ACT_GEN_SET))
return -EFAULT;
return 0;
}
| gpl-2.0 |
gsstudios/android_kernel_samsung_smdk4412 | drivers/mfd/max8698.c | 568 | 4100 | /*
* max8698.c - mfd core driver for the Maxim 8698
*
* Copyright (C) 2009-2010 Samsung Electronics
* Kyungmin Park <kyungmin.park@samsung.com>
* Marek Szyprowski <m.szyprowski@samsung.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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
*
* 2010.10.26
* Modified by Taekki Kim <taekki.kim@samsung.com>
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/i2c.h>
#include <linux/mutex.h>
#include <linux/mfd/core.h>
#include <linux/mfd/max8698.h>
#include <linux/mfd/max8698-private.h>
static struct mfd_cell max8698_devs[] = {
{
.name = "max8698-pmic",
}
};
static int max8698_i2c_device_read(struct max8698_dev *max8698, u8 reg, u8 *dest)
{
struct i2c_client *client = max8698->i2c_client;
int ret;
mutex_lock(&max8698->iolock);
ret = i2c_smbus_read_byte_data(client, reg);
mutex_unlock(&max8698->iolock);
if (ret < 0)
return ret;
ret &= 0xff;
*dest = ret;
return 0;
}
static int max8698_i2c_device_write(struct max8698_dev *max8698, u8 reg, u8 value)
{
struct i2c_client *client = max8698->i2c_client;
int ret;
mutex_lock(&max8698->iolock);
ret = i2c_smbus_write_byte_data(client, reg, value);
mutex_unlock(&max8698->iolock);
return ret;
}
static int max8698_i2c_device_update(struct max8698_dev *max8698, u8 reg,
u8 val, u8 mask)
{
struct i2c_client *client = max8698->i2c_client;
int ret;
mutex_lock(&max8698->iolock);
ret = i2c_smbus_read_byte_data(client, reg);
if (ret >= 0) {
u8 old_val = ret & 0xff;
u8 new_val = (val & mask) | (old_val & (~mask));
ret = i2c_smbus_write_byte_data(client, reg, new_val);
if (ret >= 0)
ret = 0;
}
mutex_unlock(&max8698->iolock);
return ret;
}
static int max8698_i2c_probe(struct i2c_client *i2c,
const struct i2c_device_id *id)
{
struct max8698_dev *max8698;
int ret = 0;
max8698 = kzalloc(sizeof(struct max8698_dev), GFP_KERNEL);
if (max8698 == NULL)
return -ENOMEM;
i2c_set_clientdata(i2c, max8698);
max8698->dev = &i2c->dev;
max8698->i2c_client = i2c;
max8698->dev_read = max8698_i2c_device_read;
max8698->dev_write = max8698_i2c_device_write;
max8698->dev_update = max8698_i2c_device_update;
mutex_init(&max8698->iolock);
ret = mfd_add_devices(max8698->dev, -1,
max8698_devs, ARRAY_SIZE(max8698_devs),
NULL, 0);
if (ret < 0)
goto err;
return ret;
err:
mfd_remove_devices(max8698->dev);
kfree(max8698);
return ret;
}
static int max8698_i2c_remove(struct i2c_client *i2c)
{
struct max8698_dev *max8698 = i2c_get_clientdata(i2c);
mfd_remove_devices(max8698->dev);
kfree(max8698);
return 0;
}
static const struct i2c_device_id max8698_i2c_id[] = {
{ "max8698", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, max8698_i2c_id);
static struct i2c_driver max8698_i2c_driver = {
.driver = {
.name = "max8698",
.owner = THIS_MODULE,
},
.probe = max8698_i2c_probe,
.remove = max8698_i2c_remove,
.id_table = max8698_i2c_id,
};
static int __init max8698_i2c_init(void)
{
return i2c_add_driver(&max8698_i2c_driver);
}
/* init early so consumer devices can complete system boot */
subsys_initcall(max8698_i2c_init);
static void __exit max8698_i2c_exit(void)
{
i2c_del_driver(&max8698_i2c_driver);
}
module_exit(max8698_i2c_exit);
MODULE_DESCRIPTION("MAXIM 8698 multi-function core driver");
MODULE_AUTHOR("Kyungmin Park <kyungmin.park@samsung.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
emuikernel/Coolpad5860E-kernel | arch/arm/plat-s3c24xx/common-smdk.c | 824 | 4472 | /* linux/arch/arm/plat-s3c24xx/common-smdk.c
*
* Copyright (c) 2006 Simtec Electronics
* Ben Dooks <ben@simtec.co.uk>
*
* Common code for SMDK2410 and SMDK2440 boards
*
* http://www.fluff.org/ben/smdk2440/
*
* 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/types.h>
#include <linux/interrupt.h>
#include <linux/list.h>
#include <linux/timer.h>
#include <linux/init.h>
#include <linux/gpio.h>
#include <linux/sysdev.h>
#include <linux/platform_device.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/nand_ecc.h>
#include <linux/mtd/partitions.h>
#include <linux/io.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <asm/mach-types.h>
#include <mach/hardware.h>
#include <asm/irq.h>
#include <mach/regs-gpio.h>
#include <mach/leds-gpio.h>
#include <plat/nand.h>
#include <plat/common-smdk.h>
#include <plat/gpio-cfg.h>
#include <plat/devs.h>
#include <plat/pm.h>
/* LED devices */
static struct s3c24xx_led_platdata smdk_pdata_led4 = {
.gpio = S3C2410_GPF(4),
.flags = S3C24XX_LEDF_ACTLOW | S3C24XX_LEDF_TRISTATE,
.name = "led4",
.def_trigger = "timer",
};
static struct s3c24xx_led_platdata smdk_pdata_led5 = {
.gpio = S3C2410_GPF(5),
.flags = S3C24XX_LEDF_ACTLOW | S3C24XX_LEDF_TRISTATE,
.name = "led5",
.def_trigger = "nand-disk",
};
static struct s3c24xx_led_platdata smdk_pdata_led6 = {
.gpio = S3C2410_GPF(6),
.flags = S3C24XX_LEDF_ACTLOW | S3C24XX_LEDF_TRISTATE,
.name = "led6",
};
static struct s3c24xx_led_platdata smdk_pdata_led7 = {
.gpio = S3C2410_GPF(7),
.flags = S3C24XX_LEDF_ACTLOW | S3C24XX_LEDF_TRISTATE,
.name = "led7",
};
static struct platform_device smdk_led4 = {
.name = "s3c24xx_led",
.id = 0,
.dev = {
.platform_data = &smdk_pdata_led4,
},
};
static struct platform_device smdk_led5 = {
.name = "s3c24xx_led",
.id = 1,
.dev = {
.platform_data = &smdk_pdata_led5,
},
};
static struct platform_device smdk_led6 = {
.name = "s3c24xx_led",
.id = 2,
.dev = {
.platform_data = &smdk_pdata_led6,
},
};
static struct platform_device smdk_led7 = {
.name = "s3c24xx_led",
.id = 3,
.dev = {
.platform_data = &smdk_pdata_led7,
},
};
/* NAND parititon from 2.4.18-swl5 */
static struct mtd_partition smdk_default_nand_part[] = {
[0] = {
.name = "Boot Agent",
.size = SZ_16K,
.offset = 0,
},
[1] = {
.name = "S3C2410 flash partition 1",
.offset = 0,
.size = SZ_2M,
},
[2] = {
.name = "S3C2410 flash partition 2",
.offset = SZ_4M,
.size = SZ_4M,
},
[3] = {
.name = "S3C2410 flash partition 3",
.offset = SZ_8M,
.size = SZ_2M,
},
[4] = {
.name = "S3C2410 flash partition 4",
.offset = SZ_1M * 10,
.size = SZ_4M,
},
[5] = {
.name = "S3C2410 flash partition 5",
.offset = SZ_1M * 14,
.size = SZ_1M * 10,
},
[6] = {
.name = "S3C2410 flash partition 6",
.offset = SZ_1M * 24,
.size = SZ_1M * 24,
},
[7] = {
.name = "S3C2410 flash partition 7",
.offset = SZ_1M * 48,
.size = SZ_16M,
}
};
static struct s3c2410_nand_set smdk_nand_sets[] = {
[0] = {
.name = "NAND",
.nr_chips = 1,
.nr_partitions = ARRAY_SIZE(smdk_default_nand_part),
.partitions = smdk_default_nand_part,
},
};
/* choose a set of timings which should suit most 512Mbit
* chips and beyond.
*/
static struct s3c2410_platform_nand smdk_nand_info = {
.tacls = 20,
.twrph0 = 60,
.twrph1 = 20,
.nr_sets = ARRAY_SIZE(smdk_nand_sets),
.sets = smdk_nand_sets,
};
/* devices we initialise */
static struct platform_device __initdata *smdk_devs[] = {
&s3c_device_nand,
&smdk_led4,
&smdk_led5,
&smdk_led6,
&smdk_led7,
};
void __init smdk_machine_init(void)
{
/* Configure the LEDs (even if we have no LED support)*/
s3c_gpio_cfgpin(S3C2410_GPF(4), S3C2410_GPIO_OUTPUT);
s3c_gpio_cfgpin(S3C2410_GPF(5), S3C2410_GPIO_OUTPUT);
s3c_gpio_cfgpin(S3C2410_GPF(6), S3C2410_GPIO_OUTPUT);
s3c_gpio_cfgpin(S3C2410_GPF(7), S3C2410_GPIO_OUTPUT);
s3c2410_gpio_setpin(S3C2410_GPF(4), 1);
s3c2410_gpio_setpin(S3C2410_GPF(5), 1);
s3c2410_gpio_setpin(S3C2410_GPF(6), 1);
s3c2410_gpio_setpin(S3C2410_GPF(7), 1);
if (machine_is_smdk2443())
smdk_nand_info.twrph0 = 50;
s3c_nand_set_platdata(&smdk_nand_info);
platform_add_devices(smdk_devs, ARRAY_SIZE(smdk_devs));
s3c_pm_init();
}
| gpl-2.0 |
Jeongdeokho/Dai5y | kernel/trace/trace_selftest.c | 1848 | 20791 | /* Include in trace.c */
#include <linux/stringify.h>
#include <linux/kthread.h>
#include <linux/delay.h>
#include <linux/slab.h>
static inline int trace_valid_entry(struct trace_entry *entry)
{
switch (entry->type) {
case TRACE_FN:
case TRACE_CTX:
case TRACE_WAKE:
case TRACE_STACK:
case TRACE_PRINT:
case TRACE_BRANCH:
case TRACE_GRAPH_ENT:
case TRACE_GRAPH_RET:
return 1;
}
return 0;
}
static int trace_test_buffer_cpu(struct trace_array *tr, int cpu)
{
struct ring_buffer_event *event;
struct trace_entry *entry;
unsigned int loops = 0;
while ((event = ring_buffer_consume(tr->buffer, cpu, NULL, NULL))) {
entry = ring_buffer_event_data(event);
/*
* The ring buffer is a size of trace_buf_size, if
* we loop more than the size, there's something wrong
* with the ring buffer.
*/
if (loops++ > trace_buf_size) {
printk(KERN_CONT ".. bad ring buffer ");
goto failed;
}
if (!trace_valid_entry(entry)) {
printk(KERN_CONT ".. invalid entry %d ",
entry->type);
goto failed;
}
}
return 0;
failed:
/* disable tracing */
tracing_disabled = 1;
printk(KERN_CONT ".. corrupted trace buffer .. ");
return -1;
}
/*
* Test the trace buffer to see if all the elements
* are still sane.
*/
static int trace_test_buffer(struct trace_array *tr, unsigned long *count)
{
unsigned long flags, cnt = 0;
int cpu, ret = 0;
/* Don't allow flipping of max traces now */
local_irq_save(flags);
arch_spin_lock(&ftrace_max_lock);
cnt = ring_buffer_entries(tr->buffer);
/*
* The trace_test_buffer_cpu runs a while loop to consume all data.
* If the calling tracer is broken, and is constantly filling
* the buffer, this will run forever, and hard lock the box.
* We disable the ring buffer while we do this test to prevent
* a hard lock up.
*/
tracing_off();
for_each_possible_cpu(cpu) {
ret = trace_test_buffer_cpu(tr, cpu);
if (ret)
break;
}
tracing_on();
arch_spin_unlock(&ftrace_max_lock);
local_irq_restore(flags);
if (count)
*count = cnt;
return ret;
}
static inline void warn_failed_init_tracer(struct tracer *trace, int init_ret)
{
printk(KERN_WARNING "Failed to init %s tracer, init returned %d\n",
trace->name, init_ret);
}
#ifdef CONFIG_FUNCTION_TRACER
#ifdef CONFIG_DYNAMIC_FTRACE
static int trace_selftest_test_probe1_cnt;
static void trace_selftest_test_probe1_func(unsigned long ip,
unsigned long pip)
{
trace_selftest_test_probe1_cnt++;
}
static int trace_selftest_test_probe2_cnt;
static void trace_selftest_test_probe2_func(unsigned long ip,
unsigned long pip)
{
trace_selftest_test_probe2_cnt++;
}
static int trace_selftest_test_probe3_cnt;
static void trace_selftest_test_probe3_func(unsigned long ip,
unsigned long pip)
{
trace_selftest_test_probe3_cnt++;
}
static int trace_selftest_test_global_cnt;
static void trace_selftest_test_global_func(unsigned long ip,
unsigned long pip)
{
trace_selftest_test_global_cnt++;
}
static int trace_selftest_test_dyn_cnt;
static void trace_selftest_test_dyn_func(unsigned long ip,
unsigned long pip)
{
trace_selftest_test_dyn_cnt++;
}
static struct ftrace_ops test_probe1 = {
.func = trace_selftest_test_probe1_func,
};
static struct ftrace_ops test_probe2 = {
.func = trace_selftest_test_probe2_func,
};
static struct ftrace_ops test_probe3 = {
.func = trace_selftest_test_probe3_func,
};
static struct ftrace_ops test_global = {
.func = trace_selftest_test_global_func,
.flags = FTRACE_OPS_FL_GLOBAL,
};
static void print_counts(void)
{
printk("(%d %d %d %d %d) ",
trace_selftest_test_probe1_cnt,
trace_selftest_test_probe2_cnt,
trace_selftest_test_probe3_cnt,
trace_selftest_test_global_cnt,
trace_selftest_test_dyn_cnt);
}
static void reset_counts(void)
{
trace_selftest_test_probe1_cnt = 0;
trace_selftest_test_probe2_cnt = 0;
trace_selftest_test_probe3_cnt = 0;
trace_selftest_test_global_cnt = 0;
trace_selftest_test_dyn_cnt = 0;
}
static int trace_selftest_ops(int cnt)
{
int save_ftrace_enabled = ftrace_enabled;
struct ftrace_ops *dyn_ops;
char *func1_name;
char *func2_name;
int len1;
int len2;
int ret = -1;
printk(KERN_CONT "PASSED\n");
pr_info("Testing dynamic ftrace ops #%d: ", cnt);
ftrace_enabled = 1;
reset_counts();
/* Handle PPC64 '.' name */
func1_name = "*" __stringify(DYN_FTRACE_TEST_NAME);
func2_name = "*" __stringify(DYN_FTRACE_TEST_NAME2);
len1 = strlen(func1_name);
len2 = strlen(func2_name);
/*
* Probe 1 will trace function 1.
* Probe 2 will trace function 2.
* Probe 3 will trace functions 1 and 2.
*/
ftrace_set_filter(&test_probe1, func1_name, len1, 1);
ftrace_set_filter(&test_probe2, func2_name, len2, 1);
ftrace_set_filter(&test_probe3, func1_name, len1, 1);
ftrace_set_filter(&test_probe3, func2_name, len2, 0);
register_ftrace_function(&test_probe1);
register_ftrace_function(&test_probe2);
register_ftrace_function(&test_probe3);
register_ftrace_function(&test_global);
DYN_FTRACE_TEST_NAME();
print_counts();
if (trace_selftest_test_probe1_cnt != 1)
goto out;
if (trace_selftest_test_probe2_cnt != 0)
goto out;
if (trace_selftest_test_probe3_cnt != 1)
goto out;
if (trace_selftest_test_global_cnt == 0)
goto out;
DYN_FTRACE_TEST_NAME2();
print_counts();
if (trace_selftest_test_probe1_cnt != 1)
goto out;
if (trace_selftest_test_probe2_cnt != 1)
goto out;
if (trace_selftest_test_probe3_cnt != 2)
goto out;
/* Add a dynamic probe */
dyn_ops = kzalloc(sizeof(*dyn_ops), GFP_KERNEL);
if (!dyn_ops) {
printk("MEMORY ERROR ");
goto out;
}
dyn_ops->func = trace_selftest_test_dyn_func;
register_ftrace_function(dyn_ops);
trace_selftest_test_global_cnt = 0;
DYN_FTRACE_TEST_NAME();
print_counts();
if (trace_selftest_test_probe1_cnt != 2)
goto out_free;
if (trace_selftest_test_probe2_cnt != 1)
goto out_free;
if (trace_selftest_test_probe3_cnt != 3)
goto out_free;
if (trace_selftest_test_global_cnt == 0)
goto out;
if (trace_selftest_test_dyn_cnt == 0)
goto out_free;
DYN_FTRACE_TEST_NAME2();
print_counts();
if (trace_selftest_test_probe1_cnt != 2)
goto out_free;
if (trace_selftest_test_probe2_cnt != 2)
goto out_free;
if (trace_selftest_test_probe3_cnt != 4)
goto out_free;
ret = 0;
out_free:
unregister_ftrace_function(dyn_ops);
kfree(dyn_ops);
out:
/* Purposely unregister in the same order */
unregister_ftrace_function(&test_probe1);
unregister_ftrace_function(&test_probe2);
unregister_ftrace_function(&test_probe3);
unregister_ftrace_function(&test_global);
/* Make sure everything is off */
reset_counts();
DYN_FTRACE_TEST_NAME();
DYN_FTRACE_TEST_NAME();
if (trace_selftest_test_probe1_cnt ||
trace_selftest_test_probe2_cnt ||
trace_selftest_test_probe3_cnt ||
trace_selftest_test_global_cnt ||
trace_selftest_test_dyn_cnt)
ret = -1;
ftrace_enabled = save_ftrace_enabled;
return ret;
}
/* Test dynamic code modification and ftrace filters */
int trace_selftest_startup_dynamic_tracing(struct tracer *trace,
struct trace_array *tr,
int (*func)(void))
{
int save_ftrace_enabled = ftrace_enabled;
int save_tracer_enabled = tracer_enabled;
unsigned long count;
char *func_name;
int ret;
/* The ftrace test PASSED */
printk(KERN_CONT "PASSED\n");
pr_info("Testing dynamic ftrace: ");
/* enable tracing, and record the filter function */
ftrace_enabled = 1;
tracer_enabled = 1;
/* passed in by parameter to fool gcc from optimizing */
func();
/*
* Some archs *cough*PowerPC*cough* add characters to the
* start of the function names. We simply put a '*' to
* accommodate them.
*/
func_name = "*" __stringify(DYN_FTRACE_TEST_NAME);
/* filter only on our function */
ftrace_set_global_filter(func_name, strlen(func_name), 1);
/* enable tracing */
ret = tracer_init(trace, tr);
if (ret) {
warn_failed_init_tracer(trace, ret);
goto out;
}
/* Sleep for a 1/10 of a second */
msleep(100);
/* we should have nothing in the buffer */
ret = trace_test_buffer(tr, &count);
if (ret)
goto out;
if (count) {
ret = -1;
printk(KERN_CONT ".. filter did not filter .. ");
goto out;
}
/* call our function again */
func();
/* sleep again */
msleep(100);
/* stop the tracing. */
tracing_stop();
ftrace_enabled = 0;
/* check the trace buffer */
ret = trace_test_buffer(tr, &count);
tracing_start();
/* we should only have one item */
if (!ret && count != 1) {
trace->reset(tr);
printk(KERN_CONT ".. filter failed count=%ld ..", count);
ret = -1;
goto out;
}
/* Test the ops with global tracing running */
ret = trace_selftest_ops(1);
trace->reset(tr);
out:
ftrace_enabled = save_ftrace_enabled;
tracer_enabled = save_tracer_enabled;
/* Enable tracing on all functions again */
ftrace_set_global_filter(NULL, 0, 1);
/* Test the ops with global tracing off */
if (!ret)
ret = trace_selftest_ops(2);
return ret;
}
#else
# define trace_selftest_startup_dynamic_tracing(trace, tr, func) ({ 0; })
#endif /* CONFIG_DYNAMIC_FTRACE */
/*
* Simple verification test of ftrace function tracer.
* Enable ftrace, sleep 1/10 second, and then read the trace
* buffer to see if all is in order.
*/
int
trace_selftest_startup_function(struct tracer *trace, struct trace_array *tr)
{
int save_ftrace_enabled = ftrace_enabled;
int save_tracer_enabled = tracer_enabled;
unsigned long count;
int ret;
/* make sure msleep has been recorded */
msleep(1);
/* start the tracing */
ftrace_enabled = 1;
tracer_enabled = 1;
ret = tracer_init(trace, tr);
if (ret) {
warn_failed_init_tracer(trace, ret);
goto out;
}
/* Sleep for a 1/10 of a second */
msleep(100);
/* stop the tracing. */
tracing_stop();
ftrace_enabled = 0;
/* check the trace buffer */
ret = trace_test_buffer(tr, &count);
trace->reset(tr);
tracing_start();
if (!ret && !count) {
printk(KERN_CONT ".. no entries found ..");
ret = -1;
goto out;
}
ret = trace_selftest_startup_dynamic_tracing(trace, tr,
DYN_FTRACE_TEST_NAME);
out:
ftrace_enabled = save_ftrace_enabled;
tracer_enabled = save_tracer_enabled;
/* kill ftrace totally if we failed */
if (ret)
ftrace_kill();
return ret;
}
#endif /* CONFIG_FUNCTION_TRACER */
#ifdef CONFIG_FUNCTION_GRAPH_TRACER
/* Maximum number of functions to trace before diagnosing a hang */
#define GRAPH_MAX_FUNC_TEST 100000000
static unsigned int graph_hang_thresh;
/* Wrap the real function entry probe to avoid possible hanging */
static int trace_graph_entry_watchdog(struct ftrace_graph_ent *trace)
{
/* This is harmlessly racy, we want to approximately detect a hang */
if (unlikely(++graph_hang_thresh > GRAPH_MAX_FUNC_TEST)) {
ftrace_graph_stop();
printk(KERN_WARNING "BUG: Function graph tracer hang!\n");
if (ftrace_dump_on_oops) {
ftrace_dump(DUMP_ALL);
/* ftrace_dump() disables tracing */
tracing_on();
}
return 0;
}
return trace_graph_entry(trace);
}
/*
* Pretty much the same than for the function tracer from which the selftest
* has been borrowed.
*/
int
trace_selftest_startup_function_graph(struct tracer *trace,
struct trace_array *tr)
{
int ret;
unsigned long count;
/*
* Simulate the init() callback but we attach a watchdog callback
* to detect and recover from possible hangs
*/
tracing_reset_online_cpus(tr);
set_graph_array(tr);
ret = register_ftrace_graph(&trace_graph_return,
&trace_graph_entry_watchdog);
if (ret) {
warn_failed_init_tracer(trace, ret);
goto out;
}
tracing_start_cmdline_record();
/* Sleep for a 1/10 of a second */
msleep(100);
/* Have we just recovered from a hang? */
if (graph_hang_thresh > GRAPH_MAX_FUNC_TEST) {
tracing_selftest_disabled = true;
ret = -1;
goto out;
}
tracing_stop();
/* check the trace buffer */
ret = trace_test_buffer(tr, &count);
trace->reset(tr);
tracing_start();
if (!ret && !count) {
printk(KERN_CONT ".. no entries found ..");
ret = -1;
goto out;
}
/* Don't test dynamic tracing, the function tracer already did */
out:
/* Stop it if we failed */
if (ret)
ftrace_graph_stop();
return ret;
}
#endif /* CONFIG_FUNCTION_GRAPH_TRACER */
#ifdef CONFIG_IRQSOFF_TRACER
int
trace_selftest_startup_irqsoff(struct tracer *trace, struct trace_array *tr)
{
unsigned long save_max = tracing_max_latency;
unsigned long count;
int ret;
/* start the tracing */
ret = tracer_init(trace, tr);
if (ret) {
warn_failed_init_tracer(trace, ret);
return ret;
}
/* reset the max latency */
tracing_max_latency = 0;
/* disable interrupts for a bit */
local_irq_disable();
udelay(100);
local_irq_enable();
/*
* Stop the tracer to avoid a warning subsequent
* to buffer flipping failure because tracing_stop()
* disables the tr and max buffers, making flipping impossible
* in case of parallels max irqs off latencies.
*/
trace->stop(tr);
/* stop the tracing. */
tracing_stop();
/* check both trace buffers */
ret = trace_test_buffer(tr, NULL);
if (!ret)
ret = trace_test_buffer(&max_tr, &count);
trace->reset(tr);
tracing_start();
if (!ret && !count) {
printk(KERN_CONT ".. no entries found ..");
ret = -1;
}
tracing_max_latency = save_max;
return ret;
}
#endif /* CONFIG_IRQSOFF_TRACER */
#ifdef CONFIG_PREEMPT_TRACER
int
trace_selftest_startup_preemptoff(struct tracer *trace, struct trace_array *tr)
{
unsigned long save_max = tracing_max_latency;
unsigned long count;
int ret;
/*
* Now that the big kernel lock is no longer preemptable,
* and this is called with the BKL held, it will always
* fail. If preemption is already disabled, simply
* pass the test. When the BKL is removed, or becomes
* preemptible again, we will once again test this,
* so keep it in.
*/
if (preempt_count()) {
printk(KERN_CONT "can not test ... force ");
return 0;
}
/* start the tracing */
ret = tracer_init(trace, tr);
if (ret) {
warn_failed_init_tracer(trace, ret);
return ret;
}
/* reset the max latency */
tracing_max_latency = 0;
/* disable preemption for a bit */
preempt_disable();
udelay(100);
preempt_enable();
/*
* Stop the tracer to avoid a warning subsequent
* to buffer flipping failure because tracing_stop()
* disables the tr and max buffers, making flipping impossible
* in case of parallels max preempt off latencies.
*/
trace->stop(tr);
/* stop the tracing. */
tracing_stop();
/* check both trace buffers */
ret = trace_test_buffer(tr, NULL);
if (!ret)
ret = trace_test_buffer(&max_tr, &count);
trace->reset(tr);
tracing_start();
if (!ret && !count) {
printk(KERN_CONT ".. no entries found ..");
ret = -1;
}
tracing_max_latency = save_max;
return ret;
}
#endif /* CONFIG_PREEMPT_TRACER */
#if defined(CONFIG_IRQSOFF_TRACER) && defined(CONFIG_PREEMPT_TRACER)
int
trace_selftest_startup_preemptirqsoff(struct tracer *trace, struct trace_array *tr)
{
unsigned long save_max = tracing_max_latency;
unsigned long count;
int ret;
/*
* Now that the big kernel lock is no longer preemptable,
* and this is called with the BKL held, it will always
* fail. If preemption is already disabled, simply
* pass the test. When the BKL is removed, or becomes
* preemptible again, we will once again test this,
* so keep it in.
*/
if (preempt_count()) {
printk(KERN_CONT "can not test ... force ");
return 0;
}
/* start the tracing */
ret = tracer_init(trace, tr);
if (ret) {
warn_failed_init_tracer(trace, ret);
goto out_no_start;
}
/* reset the max latency */
tracing_max_latency = 0;
/* disable preemption and interrupts for a bit */
preempt_disable();
local_irq_disable();
udelay(100);
preempt_enable();
/* reverse the order of preempt vs irqs */
local_irq_enable();
/*
* Stop the tracer to avoid a warning subsequent
* to buffer flipping failure because tracing_stop()
* disables the tr and max buffers, making flipping impossible
* in case of parallels max irqs/preempt off latencies.
*/
trace->stop(tr);
/* stop the tracing. */
tracing_stop();
/* check both trace buffers */
ret = trace_test_buffer(tr, NULL);
if (ret)
goto out;
ret = trace_test_buffer(&max_tr, &count);
if (ret)
goto out;
if (!ret && !count) {
printk(KERN_CONT ".. no entries found ..");
ret = -1;
goto out;
}
/* do the test by disabling interrupts first this time */
tracing_max_latency = 0;
tracing_start();
trace->start(tr);
preempt_disable();
local_irq_disable();
udelay(100);
preempt_enable();
/* reverse the order of preempt vs irqs */
local_irq_enable();
trace->stop(tr);
/* stop the tracing. */
tracing_stop();
/* check both trace buffers */
ret = trace_test_buffer(tr, NULL);
if (ret)
goto out;
ret = trace_test_buffer(&max_tr, &count);
if (!ret && !count) {
printk(KERN_CONT ".. no entries found ..");
ret = -1;
goto out;
}
out:
tracing_start();
out_no_start:
trace->reset(tr);
tracing_max_latency = save_max;
return ret;
}
#endif /* CONFIG_IRQSOFF_TRACER && CONFIG_PREEMPT_TRACER */
#ifdef CONFIG_NOP_TRACER
int
trace_selftest_startup_nop(struct tracer *trace, struct trace_array *tr)
{
/* What could possibly go wrong? */
return 0;
}
#endif
#ifdef CONFIG_SCHED_TRACER
static int trace_wakeup_test_thread(void *data)
{
/* Make this a RT thread, doesn't need to be too high */
static const struct sched_param param = { .sched_priority = 5 };
struct completion *x = data;
sched_setscheduler(current, SCHED_FIFO, ¶m);
/* Make it know we have a new prio */
complete(x);
/* now go to sleep and let the test wake us up */
set_current_state(TASK_INTERRUPTIBLE);
schedule();
/* we are awake, now wait to disappear */
while (!kthread_should_stop()) {
/*
* This is an RT task, do short sleeps to let
* others run.
*/
msleep(100);
}
return 0;
}
int
trace_selftest_startup_wakeup(struct tracer *trace, struct trace_array *tr)
{
unsigned long save_max = tracing_max_latency;
struct task_struct *p;
struct completion isrt;
unsigned long count;
int ret;
init_completion(&isrt);
/* create a high prio thread */
p = kthread_run(trace_wakeup_test_thread, &isrt, "ftrace-test");
if (IS_ERR(p)) {
printk(KERN_CONT "Failed to create ftrace wakeup test thread ");
return -1;
}
/* make sure the thread is running at an RT prio */
wait_for_completion(&isrt);
/* start the tracing */
ret = tracer_init(trace, tr);
if (ret) {
warn_failed_init_tracer(trace, ret);
return ret;
}
/* reset the max latency */
tracing_max_latency = 0;
/* sleep to let the RT thread sleep too */
msleep(100);
/*
* Yes this is slightly racy. It is possible that for some
* strange reason that the RT thread we created, did not
* call schedule for 100ms after doing the completion,
* and we do a wakeup on a task that already is awake.
* But that is extremely unlikely, and the worst thing that
* happens in such a case, is that we disable tracing.
* Honestly, if this race does happen something is horrible
* wrong with the system.
*/
wake_up_process(p);
/* give a little time to let the thread wake up */
msleep(100);
/* stop the tracing. */
tracing_stop();
/* check both trace buffers */
ret = trace_test_buffer(tr, NULL);
if (!ret)
ret = trace_test_buffer(&max_tr, &count);
trace->reset(tr);
tracing_start();
tracing_max_latency = save_max;
/* kill the thread */
kthread_stop(p);
if (!ret && !count) {
printk(KERN_CONT ".. no entries found ..");
ret = -1;
}
return ret;
}
#endif /* CONFIG_SCHED_TRACER */
#ifdef CONFIG_CONTEXT_SWITCH_TRACER
int
trace_selftest_startup_sched_switch(struct tracer *trace, struct trace_array *tr)
{
unsigned long count;
int ret;
/* start the tracing */
ret = tracer_init(trace, tr);
if (ret) {
warn_failed_init_tracer(trace, ret);
return ret;
}
/* Sleep for a 1/10 of a second */
msleep(100);
/* stop the tracing. */
tracing_stop();
/* check the trace buffer */
ret = trace_test_buffer(tr, &count);
trace->reset(tr);
tracing_start();
if (!ret && !count) {
printk(KERN_CONT ".. no entries found ..");
ret = -1;
}
return ret;
}
#endif /* CONFIG_CONTEXT_SWITCH_TRACER */
#ifdef CONFIG_BRANCH_TRACER
int
trace_selftest_startup_branch(struct tracer *trace, struct trace_array *tr)
{
unsigned long count;
int ret;
/* start the tracing */
ret = tracer_init(trace, tr);
if (ret) {
warn_failed_init_tracer(trace, ret);
return ret;
}
/* Sleep for a 1/10 of a second */
msleep(100);
/* stop the tracing. */
tracing_stop();
/* check the trace buffer */
ret = trace_test_buffer(tr, &count);
trace->reset(tr);
tracing_start();
if (!ret && !count) {
printk(KERN_CONT ".. no entries found ..");
ret = -1;
}
return ret;
}
#endif /* CONFIG_BRANCH_TRACER */
| gpl-2.0 |
OctaviaBlake/kernel-msm | arch/arm/mach-omap2/clkt2xxx_apll.c | 2360 | 3200 | /*
* OMAP2xxx APLL clock control functions
*
* Copyright (C) 2005-2008 Texas Instruments, Inc.
* Copyright (C) 2004-2010 Nokia Corporation
*
* Contacts:
* Richard Woodruff <r-woodruff2@ti.com>
* Paul Walmsley
*
* Based on earlier work by Tuukka Tikkanen, Tony Lindgren,
* Gordon McNutt and RidgeRun, 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.
*/
#undef DEBUG
#include <linux/kernel.h>
#include <linux/clk.h>
#include <linux/io.h>
#include "clock.h"
#include "clock2xxx.h"
#include "cm2xxx.h"
#include "cm-regbits-24xx.h"
/* CM_CLKEN_PLL.EN_{54,96}M_PLL options (24XX) */
#define EN_APLL_STOPPED 0
#define EN_APLL_LOCKED 3
/* CM_CLKSEL1_PLL.APLLS_CLKIN options (24XX) */
#define APLLS_CLKIN_19_2MHZ 0
#define APLLS_CLKIN_13MHZ 2
#define APLLS_CLKIN_12MHZ 3
/* Private functions */
/**
* omap2xxx_clk_apll_locked - is the APLL locked?
* @hw: struct clk_hw * of the APLL to check
*
* If the APLL IP block referred to by @hw indicates that it's locked,
* return true; otherwise, return false.
*/
static bool omap2xxx_clk_apll_locked(struct clk_hw *hw)
{
struct clk_hw_omap *clk = to_clk_hw_omap(hw);
u32 r, apll_mask;
apll_mask = EN_APLL_LOCKED << clk->enable_bit;
r = omap2_cm_read_mod_reg(PLL_MOD, CM_CLKEN);
return ((r & apll_mask) == apll_mask) ? true : false;
}
int omap2_clk_apll96_enable(struct clk_hw *hw)
{
return omap2xxx_cm_apll96_enable();
}
int omap2_clk_apll54_enable(struct clk_hw *hw)
{
return omap2xxx_cm_apll54_enable();
}
static void _apll96_allow_idle(struct clk_hw_omap *clk)
{
omap2xxx_cm_set_apll96_auto_low_power_stop();
}
static void _apll96_deny_idle(struct clk_hw_omap *clk)
{
omap2xxx_cm_set_apll96_disable_autoidle();
}
static void _apll54_allow_idle(struct clk_hw_omap *clk)
{
omap2xxx_cm_set_apll54_auto_low_power_stop();
}
static void _apll54_deny_idle(struct clk_hw_omap *clk)
{
omap2xxx_cm_set_apll54_disable_autoidle();
}
void omap2_clk_apll96_disable(struct clk_hw *hw)
{
omap2xxx_cm_apll96_disable();
}
void omap2_clk_apll54_disable(struct clk_hw *hw)
{
omap2xxx_cm_apll54_disable();
}
unsigned long omap2_clk_apll54_recalc(struct clk_hw *hw,
unsigned long parent_rate)
{
return (omap2xxx_clk_apll_locked(hw)) ? 54000000 : 0;
}
unsigned long omap2_clk_apll96_recalc(struct clk_hw *hw,
unsigned long parent_rate)
{
return (omap2xxx_clk_apll_locked(hw)) ? 96000000 : 0;
}
/* Public data */
const struct clk_hw_omap_ops clkhwops_apll54 = {
.allow_idle = _apll54_allow_idle,
.deny_idle = _apll54_deny_idle,
};
const struct clk_hw_omap_ops clkhwops_apll96 = {
.allow_idle = _apll96_allow_idle,
.deny_idle = _apll96_deny_idle,
};
/* Public functions */
u32 omap2xxx_get_apll_clkin(void)
{
u32 aplls, srate = 0;
aplls = omap2_cm_read_mod_reg(PLL_MOD, CM_CLKSEL1);
aplls &= OMAP24XX_APLLS_CLKIN_MASK;
aplls >>= OMAP24XX_APLLS_CLKIN_SHIFT;
if (aplls == APLLS_CLKIN_19_2MHZ)
srate = 19200000;
else if (aplls == APLLS_CLKIN_13MHZ)
srate = 13000000;
else if (aplls == APLLS_CLKIN_12MHZ)
srate = 12000000;
return srate;
}
| gpl-2.0 |
delanoister-Andro-ID/GT-I9300-ICS-3.0.y | security/keys/keyring.c | 2360 | 30879 | /* Keyring handling
*
* Copyright (C) 2004-2005, 2008 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/security.h>
#include <linux/seq_file.h>
#include <linux/err.h>
#include <keys/keyring-type.h>
#include <linux/uaccess.h>
#include "internal.h"
#define rcu_dereference_locked_keyring(keyring) \
(rcu_dereference_protected( \
(keyring)->payload.subscriptions, \
rwsem_is_locked((struct rw_semaphore *)&(keyring)->sem)))
#define KEY_LINK_FIXQUOTA 1UL
/*
* When plumbing the depths of the key tree, this sets a hard limit
* set on how deep we're willing to go.
*/
#define KEYRING_SEARCH_MAX_DEPTH 6
/*
* We keep all named keyrings in a hash to speed looking them up.
*/
#define KEYRING_NAME_HASH_SIZE (1 << 5)
static struct list_head keyring_name_hash[KEYRING_NAME_HASH_SIZE];
static DEFINE_RWLOCK(keyring_name_lock);
static inline unsigned keyring_hash(const char *desc)
{
unsigned bucket = 0;
for (; *desc; desc++)
bucket += (unsigned char)*desc;
return bucket & (KEYRING_NAME_HASH_SIZE - 1);
}
/*
* The keyring key type definition. Keyrings are simply keys of this type and
* can be treated as ordinary keys in addition to having their own special
* operations.
*/
static int keyring_instantiate(struct key *keyring,
const void *data, size_t datalen);
static int keyring_match(const struct key *keyring, const void *criterion);
static void keyring_revoke(struct key *keyring);
static void keyring_destroy(struct key *keyring);
static void keyring_describe(const struct key *keyring, struct seq_file *m);
static long keyring_read(const struct key *keyring,
char __user *buffer, size_t buflen);
struct key_type key_type_keyring = {
.name = "keyring",
.def_datalen = sizeof(struct keyring_list),
.instantiate = keyring_instantiate,
.match = keyring_match,
.revoke = keyring_revoke,
.destroy = keyring_destroy,
.describe = keyring_describe,
.read = keyring_read,
};
EXPORT_SYMBOL(key_type_keyring);
/*
* Semaphore to serialise link/link calls to prevent two link calls in parallel
* introducing a cycle.
*/
static DECLARE_RWSEM(keyring_serialise_link_sem);
/*
* Publish the name of a keyring so that it can be found by name (if it has
* one).
*/
static void keyring_publish_name(struct key *keyring)
{
int bucket;
if (keyring->description) {
bucket = keyring_hash(keyring->description);
write_lock(&keyring_name_lock);
if (!keyring_name_hash[bucket].next)
INIT_LIST_HEAD(&keyring_name_hash[bucket]);
list_add_tail(&keyring->type_data.link,
&keyring_name_hash[bucket]);
write_unlock(&keyring_name_lock);
}
}
/*
* Initialise a keyring.
*
* Returns 0 on success, -EINVAL if given any data.
*/
static int keyring_instantiate(struct key *keyring,
const void *data, size_t datalen)
{
int ret;
ret = -EINVAL;
if (datalen == 0) {
/* make the keyring available by name if it has one */
keyring_publish_name(keyring);
ret = 0;
}
return ret;
}
/*
* Match keyrings on their name
*/
static int keyring_match(const struct key *keyring, const void *description)
{
return keyring->description &&
strcmp(keyring->description, description) == 0;
}
/*
* Clean up a keyring when it is destroyed. Unpublish its name if it had one
* and dispose of its data.
*/
static void keyring_destroy(struct key *keyring)
{
struct keyring_list *klist;
int loop;
if (keyring->description) {
write_lock(&keyring_name_lock);
if (keyring->type_data.link.next != NULL &&
!list_empty(&keyring->type_data.link))
list_del(&keyring->type_data.link);
write_unlock(&keyring_name_lock);
}
klist = rcu_dereference_check(keyring->payload.subscriptions,
rcu_read_lock_held() ||
atomic_read(&keyring->usage) == 0);
if (klist) {
for (loop = klist->nkeys - 1; loop >= 0; loop--)
key_put(klist->keys[loop]);
kfree(klist);
}
}
/*
* Describe a keyring for /proc.
*/
static void keyring_describe(const struct key *keyring, struct seq_file *m)
{
struct keyring_list *klist;
if (keyring->description)
seq_puts(m, keyring->description);
else
seq_puts(m, "[anon]");
if (key_is_instantiated(keyring)) {
rcu_read_lock();
klist = rcu_dereference(keyring->payload.subscriptions);
if (klist)
seq_printf(m, ": %u/%u", klist->nkeys, klist->maxkeys);
else
seq_puts(m, ": empty");
rcu_read_unlock();
}
}
/*
* Read a list of key IDs from the keyring's contents in binary form
*
* The keyring's semaphore is read-locked by the caller.
*/
static long keyring_read(const struct key *keyring,
char __user *buffer, size_t buflen)
{
struct keyring_list *klist;
struct key *key;
size_t qty, tmp;
int loop, ret;
ret = 0;
klist = rcu_dereference_locked_keyring(keyring);
if (klist) {
/* calculate how much data we could return */
qty = klist->nkeys * sizeof(key_serial_t);
if (buffer && buflen > 0) {
if (buflen > qty)
buflen = qty;
/* copy the IDs of the subscribed keys into the
* buffer */
ret = -EFAULT;
for (loop = 0; loop < klist->nkeys; loop++) {
key = klist->keys[loop];
tmp = sizeof(key_serial_t);
if (tmp > buflen)
tmp = buflen;
if (copy_to_user(buffer,
&key->serial,
tmp) != 0)
goto error;
buflen -= tmp;
if (buflen == 0)
break;
buffer += tmp;
}
}
ret = qty;
}
error:
return ret;
}
/*
* Allocate a keyring and link into the destination keyring.
*/
struct key *keyring_alloc(const char *description, uid_t uid, gid_t gid,
const struct cred *cred, unsigned long flags,
struct key *dest)
{
struct key *keyring;
int ret;
keyring = key_alloc(&key_type_keyring, description,
uid, gid, cred,
(KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_ALL,
flags);
if (!IS_ERR(keyring)) {
ret = key_instantiate_and_link(keyring, NULL, 0, dest, NULL);
if (ret < 0) {
key_put(keyring);
keyring = ERR_PTR(ret);
}
}
return keyring;
}
/**
* keyring_search_aux - Search a keyring tree for a key matching some criteria
* @keyring_ref: A pointer to the keyring with possession indicator.
* @cred: The credentials to use for permissions checks.
* @type: The type of key to search for.
* @description: Parameter for @match.
* @match: Function to rule on whether or not a key is the one required.
* @no_state_check: Don't check if a matching key is bad
*
* Search the supplied keyring tree for a key that matches the criteria given.
* The root keyring and any linked keyrings must grant Search permission to the
* caller to be searchable and keys can only be found if they too grant Search
* to the caller. The possession flag on the root keyring pointer controls use
* of the possessor bits in permissions checking of the entire tree. In
* addition, the LSM gets to forbid keyring searches and key matches.
*
* The search is performed as a breadth-then-depth search up to the prescribed
* limit (KEYRING_SEARCH_MAX_DEPTH).
*
* Keys are matched to the type provided and are then filtered by the match
* function, which is given the description to use in any way it sees fit. The
* match function may use any attributes of a key that it wishes to to
* determine the match. Normally the match function from the key type would be
* used.
*
* RCU is used to prevent the keyring key lists from disappearing without the
* need to take lots of locks.
*
* Returns a pointer to the found key and increments the key usage count if
* successful; -EAGAIN if no matching keys were found, or if expired or revoked
* keys were found; -ENOKEY if only negative keys were found; -ENOTDIR if the
* specified keyring wasn't a keyring.
*
* In the case of a successful return, the possession attribute from
* @keyring_ref is propagated to the returned key reference.
*/
key_ref_t keyring_search_aux(key_ref_t keyring_ref,
const struct cred *cred,
struct key_type *type,
const void *description,
key_match_func_t match,
bool no_state_check)
{
struct {
struct keyring_list *keylist;
int kix;
} stack[KEYRING_SEARCH_MAX_DEPTH];
struct keyring_list *keylist;
struct timespec now;
unsigned long possessed, kflags;
struct key *keyring, *key;
key_ref_t key_ref;
long err;
int sp, kix;
keyring = key_ref_to_ptr(keyring_ref);
possessed = is_key_possessed(keyring_ref);
key_check(keyring);
/* top keyring must have search permission to begin the search */
err = key_task_permission(keyring_ref, cred, KEY_SEARCH);
if (err < 0) {
key_ref = ERR_PTR(err);
goto error;
}
key_ref = ERR_PTR(-ENOTDIR);
if (keyring->type != &key_type_keyring)
goto error;
rcu_read_lock();
now = current_kernel_time();
err = -EAGAIN;
sp = 0;
/* firstly we should check to see if this top-level keyring is what we
* are looking for */
key_ref = ERR_PTR(-EAGAIN);
kflags = keyring->flags;
if (keyring->type == type && match(keyring, description)) {
key = keyring;
if (no_state_check)
goto found;
/* check it isn't negative and hasn't expired or been
* revoked */
if (kflags & (1 << KEY_FLAG_REVOKED))
goto error_2;
if (key->expiry && now.tv_sec >= key->expiry)
goto error_2;
key_ref = ERR_PTR(key->type_data.reject_error);
if (kflags & (1 << KEY_FLAG_NEGATIVE))
goto error_2;
goto found;
}
/* otherwise, the top keyring must not be revoked, expired, or
* negatively instantiated if we are to search it */
key_ref = ERR_PTR(-EAGAIN);
if (kflags & ((1 << KEY_FLAG_REVOKED) | (1 << KEY_FLAG_NEGATIVE)) ||
(keyring->expiry && now.tv_sec >= keyring->expiry))
goto error_2;
/* start processing a new keyring */
descend:
if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
goto not_this_keyring;
keylist = rcu_dereference(keyring->payload.subscriptions);
if (!keylist)
goto not_this_keyring;
/* iterate through the keys in this keyring first */
for (kix = 0; kix < keylist->nkeys; kix++) {
key = keylist->keys[kix];
kflags = key->flags;
/* ignore keys not of this type */
if (key->type != type)
continue;
/* skip revoked keys and expired keys */
if (!no_state_check) {
if (kflags & (1 << KEY_FLAG_REVOKED))
continue;
if (key->expiry && now.tv_sec >= key->expiry)
continue;
}
/* keys that don't match */
if (!match(key, description))
continue;
/* key must have search permissions */
if (key_task_permission(make_key_ref(key, possessed),
cred, KEY_SEARCH) < 0)
continue;
if (no_state_check)
goto found;
/* we set a different error code if we pass a negative key */
if (kflags & (1 << KEY_FLAG_NEGATIVE)) {
err = key->type_data.reject_error;
continue;
}
goto found;
}
/* search through the keyrings nested in this one */
kix = 0;
ascend:
for (; kix < keylist->nkeys; kix++) {
key = keylist->keys[kix];
if (key->type != &key_type_keyring)
continue;
/* recursively search nested keyrings
* - only search keyrings for which we have search permission
*/
if (sp >= KEYRING_SEARCH_MAX_DEPTH)
continue;
if (key_task_permission(make_key_ref(key, possessed),
cred, KEY_SEARCH) < 0)
continue;
/* stack the current position */
stack[sp].keylist = keylist;
stack[sp].kix = kix;
sp++;
/* begin again with the new keyring */
keyring = key;
goto descend;
}
/* the keyring we're looking at was disqualified or didn't contain a
* matching key */
not_this_keyring:
if (sp > 0) {
/* resume the processing of a keyring higher up in the tree */
sp--;
keylist = stack[sp].keylist;
kix = stack[sp].kix + 1;
goto ascend;
}
key_ref = ERR_PTR(err);
goto error_2;
/* we found a viable match */
found:
atomic_inc(&key->usage);
key_check(key);
key_ref = make_key_ref(key, possessed);
error_2:
rcu_read_unlock();
error:
return key_ref;
}
/**
* keyring_search - Search the supplied keyring tree for a matching key
* @keyring: The root of the keyring tree to be searched.
* @type: The type of keyring we want to find.
* @description: The name of the keyring we want to find.
*
* As keyring_search_aux() above, but using the current task's credentials and
* type's default matching function.
*/
key_ref_t keyring_search(key_ref_t keyring,
struct key_type *type,
const char *description)
{
if (!type->match)
return ERR_PTR(-ENOKEY);
return keyring_search_aux(keyring, current->cred,
type, description, type->match, false);
}
EXPORT_SYMBOL(keyring_search);
/*
* Search the given keyring only (no recursion).
*
* The caller must guarantee that the keyring is a keyring and that the
* permission is granted to search the keyring as no check is made here.
*
* RCU is used to make it unnecessary to lock the keyring key list here.
*
* Returns a pointer to the found key with usage count incremented if
* successful and returns -ENOKEY if not found. Revoked keys and keys not
* providing the requested permission are skipped over.
*
* If successful, the possession indicator is propagated from the keyring ref
* to the returned key reference.
*/
key_ref_t __keyring_search_one(key_ref_t keyring_ref,
const struct key_type *ktype,
const char *description,
key_perm_t perm)
{
struct keyring_list *klist;
unsigned long possessed;
struct key *keyring, *key;
int loop;
keyring = key_ref_to_ptr(keyring_ref);
possessed = is_key_possessed(keyring_ref);
rcu_read_lock();
klist = rcu_dereference(keyring->payload.subscriptions);
if (klist) {
for (loop = 0; loop < klist->nkeys; loop++) {
key = klist->keys[loop];
if (key->type == ktype &&
(!key->type->match ||
key->type->match(key, description)) &&
key_permission(make_key_ref(key, possessed),
perm) == 0 &&
!test_bit(KEY_FLAG_REVOKED, &key->flags)
)
goto found;
}
}
rcu_read_unlock();
return ERR_PTR(-ENOKEY);
found:
atomic_inc(&key->usage);
rcu_read_unlock();
return make_key_ref(key, possessed);
}
/*
* Find a keyring with the specified name.
*
* All named keyrings in the current user namespace are searched, provided they
* grant Search permission directly to the caller (unless this check is
* skipped). Keyrings whose usage points have reached zero or who have been
* revoked are skipped.
*
* Returns a pointer to the keyring with the keyring's refcount having being
* incremented on success. -ENOKEY is returned if a key could not be found.
*/
struct key *find_keyring_by_name(const char *name, bool skip_perm_check)
{
struct key *keyring;
int bucket;
if (!name)
return ERR_PTR(-EINVAL);
bucket = keyring_hash(name);
read_lock(&keyring_name_lock);
if (keyring_name_hash[bucket].next) {
/* search this hash bucket for a keyring with a matching name
* that's readable and that hasn't been revoked */
list_for_each_entry(keyring,
&keyring_name_hash[bucket],
type_data.link
) {
if (keyring->user->user_ns != current_user_ns())
continue;
if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
continue;
if (strcmp(keyring->description, name) != 0)
continue;
if (!skip_perm_check &&
key_permission(make_key_ref(keyring, 0),
KEY_SEARCH) < 0)
continue;
/* we've got a match but we might end up racing with
* key_cleanup() if the keyring is currently 'dead'
* (ie. it has a zero usage count) */
if (!atomic_inc_not_zero(&keyring->usage))
continue;
goto out;
}
}
keyring = ERR_PTR(-ENOKEY);
out:
read_unlock(&keyring_name_lock);
return keyring;
}
/*
* See if a cycle will will be created by inserting acyclic tree B in acyclic
* tree A at the topmost level (ie: as a direct child of A).
*
* Since we are adding B to A at the top level, checking for cycles should just
* be a matter of seeing if node A is somewhere in tree B.
*/
static int keyring_detect_cycle(struct key *A, struct key *B)
{
struct {
struct keyring_list *keylist;
int kix;
} stack[KEYRING_SEARCH_MAX_DEPTH];
struct keyring_list *keylist;
struct key *subtree, *key;
int sp, kix, ret;
rcu_read_lock();
ret = -EDEADLK;
if (A == B)
goto cycle_detected;
subtree = B;
sp = 0;
/* start processing a new keyring */
descend:
if (test_bit(KEY_FLAG_REVOKED, &subtree->flags))
goto not_this_keyring;
keylist = rcu_dereference(subtree->payload.subscriptions);
if (!keylist)
goto not_this_keyring;
kix = 0;
ascend:
/* iterate through the remaining keys in this keyring */
for (; kix < keylist->nkeys; kix++) {
key = keylist->keys[kix];
if (key == A)
goto cycle_detected;
/* recursively check nested keyrings */
if (key->type == &key_type_keyring) {
if (sp >= KEYRING_SEARCH_MAX_DEPTH)
goto too_deep;
/* stack the current position */
stack[sp].keylist = keylist;
stack[sp].kix = kix;
sp++;
/* begin again with the new keyring */
subtree = key;
goto descend;
}
}
/* the keyring we're looking at was disqualified or didn't contain a
* matching key */
not_this_keyring:
if (sp > 0) {
/* resume the checking of a keyring higher up in the tree */
sp--;
keylist = stack[sp].keylist;
kix = stack[sp].kix + 1;
goto ascend;
}
ret = 0; /* no cycles detected */
error:
rcu_read_unlock();
return ret;
too_deep:
ret = -ELOOP;
goto error;
cycle_detected:
ret = -EDEADLK;
goto error;
}
/*
* Dispose of a keyring list after the RCU grace period, freeing the unlinked
* key
*/
static void keyring_unlink_rcu_disposal(struct rcu_head *rcu)
{
struct keyring_list *klist =
container_of(rcu, struct keyring_list, rcu);
if (klist->delkey != USHRT_MAX)
key_put(klist->keys[klist->delkey]);
kfree(klist);
}
/*
* Preallocate memory so that a key can be linked into to a keyring.
*/
int __key_link_begin(struct key *keyring, const struct key_type *type,
const char *description, unsigned long *_prealloc)
__acquires(&keyring->sem)
{
struct keyring_list *klist, *nklist;
unsigned long prealloc;
unsigned max;
size_t size;
int loop, ret;
kenter("%d,%s,%s,", key_serial(keyring), type->name, description);
if (keyring->type != &key_type_keyring)
return -ENOTDIR;
down_write(&keyring->sem);
ret = -EKEYREVOKED;
if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
goto error_krsem;
/* serialise link/link calls to prevent parallel calls causing a cycle
* when linking two keyring in opposite orders */
if (type == &key_type_keyring)
down_write(&keyring_serialise_link_sem);
klist = rcu_dereference_locked_keyring(keyring);
/* see if there's a matching key we can displace */
if (klist && klist->nkeys > 0) {
for (loop = klist->nkeys - 1; loop >= 0; loop--) {
if (klist->keys[loop]->type == type &&
strcmp(klist->keys[loop]->description,
description) == 0
) {
/* found a match - we'll replace this one with
* the new key */
size = sizeof(struct key *) * klist->maxkeys;
size += sizeof(*klist);
BUG_ON(size > PAGE_SIZE);
ret = -ENOMEM;
nklist = kmemdup(klist, size, GFP_KERNEL);
if (!nklist)
goto error_sem;
/* note replacement slot */
klist->delkey = nklist->delkey = loop;
prealloc = (unsigned long)nklist;
goto done;
}
}
}
/* check that we aren't going to overrun the user's quota */
ret = key_payload_reserve(keyring,
keyring->datalen + KEYQUOTA_LINK_BYTES);
if (ret < 0)
goto error_sem;
if (klist && klist->nkeys < klist->maxkeys) {
/* there's sufficient slack space to append directly */
nklist = NULL;
prealloc = KEY_LINK_FIXQUOTA;
} else {
/* grow the key list */
max = 4;
if (klist)
max += klist->maxkeys;
ret = -ENFILE;
if (max > USHRT_MAX - 1)
goto error_quota;
size = sizeof(*klist) + sizeof(struct key *) * max;
if (size > PAGE_SIZE)
goto error_quota;
ret = -ENOMEM;
nklist = kmalloc(size, GFP_KERNEL);
if (!nklist)
goto error_quota;
nklist->maxkeys = max;
if (klist) {
memcpy(nklist->keys, klist->keys,
sizeof(struct key *) * klist->nkeys);
nklist->delkey = klist->nkeys;
nklist->nkeys = klist->nkeys + 1;
klist->delkey = USHRT_MAX;
} else {
nklist->nkeys = 1;
nklist->delkey = 0;
}
/* add the key into the new space */
nklist->keys[nklist->delkey] = NULL;
}
prealloc = (unsigned long)nklist | KEY_LINK_FIXQUOTA;
done:
*_prealloc = prealloc;
kleave(" = 0");
return 0;
error_quota:
/* undo the quota changes */
key_payload_reserve(keyring,
keyring->datalen - KEYQUOTA_LINK_BYTES);
error_sem:
if (type == &key_type_keyring)
up_write(&keyring_serialise_link_sem);
error_krsem:
up_write(&keyring->sem);
kleave(" = %d", ret);
return ret;
}
/*
* Check already instantiated keys aren't going to be a problem.
*
* The caller must have called __key_link_begin(). Don't need to call this for
* keys that were created since __key_link_begin() was called.
*/
int __key_link_check_live_key(struct key *keyring, struct key *key)
{
if (key->type == &key_type_keyring)
/* check that we aren't going to create a cycle by linking one
* keyring to another */
return keyring_detect_cycle(keyring, key);
return 0;
}
/*
* Link a key into to a keyring.
*
* Must be called with __key_link_begin() having being called. Discards any
* already extant link to matching key if there is one, so that each keyring
* holds at most one link to any given key of a particular type+description
* combination.
*/
void __key_link(struct key *keyring, struct key *key,
unsigned long *_prealloc)
{
struct keyring_list *klist, *nklist;
nklist = (struct keyring_list *)(*_prealloc & ~KEY_LINK_FIXQUOTA);
*_prealloc = 0;
kenter("%d,%d,%p", keyring->serial, key->serial, nklist);
klist = rcu_dereference_protected(keyring->payload.subscriptions,
rwsem_is_locked(&keyring->sem));
atomic_inc(&key->usage);
/* there's a matching key we can displace or an empty slot in a newly
* allocated list we can fill */
if (nklist) {
kdebug("replace %hu/%hu/%hu",
nklist->delkey, nklist->nkeys, nklist->maxkeys);
nklist->keys[nklist->delkey] = key;
rcu_assign_pointer(keyring->payload.subscriptions, nklist);
/* dispose of the old keyring list and, if there was one, the
* displaced key */
if (klist) {
kdebug("dispose %hu/%hu/%hu",
klist->delkey, klist->nkeys, klist->maxkeys);
call_rcu(&klist->rcu, keyring_unlink_rcu_disposal);
}
} else {
/* there's sufficient slack space to append directly */
klist->keys[klist->nkeys] = key;
smp_wmb();
klist->nkeys++;
}
}
/*
* Finish linking a key into to a keyring.
*
* Must be called with __key_link_begin() having being called.
*/
void __key_link_end(struct key *keyring, struct key_type *type,
unsigned long prealloc)
__releases(&keyring->sem)
{
BUG_ON(type == NULL);
BUG_ON(type->name == NULL);
kenter("%d,%s,%lx", keyring->serial, type->name, prealloc);
if (type == &key_type_keyring)
up_write(&keyring_serialise_link_sem);
if (prealloc) {
if (prealloc & KEY_LINK_FIXQUOTA)
key_payload_reserve(keyring,
keyring->datalen -
KEYQUOTA_LINK_BYTES);
kfree((struct keyring_list *)(prealloc & ~KEY_LINK_FIXQUOTA));
}
up_write(&keyring->sem);
}
/**
* key_link - Link a key to a keyring
* @keyring: The keyring to make the link in.
* @key: The key to link to.
*
* Make a link in a keyring to a key, such that the keyring holds a reference
* on that key and the key can potentially be found by searching that keyring.
*
* This function will write-lock the keyring's semaphore and will consume some
* of the user's key data quota to hold the link.
*
* Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring,
* -EKEYREVOKED if the keyring has been revoked, -ENFILE if the keyring is
* full, -EDQUOT if there is insufficient key data quota remaining to add
* another link or -ENOMEM if there's insufficient memory.
*
* It is assumed that the caller has checked that it is permitted for a link to
* be made (the keyring should have Write permission and the key Link
* permission).
*/
int key_link(struct key *keyring, struct key *key)
{
unsigned long prealloc;
int ret;
key_check(keyring);
key_check(key);
ret = __key_link_begin(keyring, key->type, key->description, &prealloc);
if (ret == 0) {
ret = __key_link_check_live_key(keyring, key);
if (ret == 0)
__key_link(keyring, key, &prealloc);
__key_link_end(keyring, key->type, prealloc);
}
return ret;
}
EXPORT_SYMBOL(key_link);
/**
* key_unlink - Unlink the first link to a key from a keyring.
* @keyring: The keyring to remove the link from.
* @key: The key the link is to.
*
* Remove a link from a keyring to a key.
*
* This function will write-lock the keyring's semaphore.
*
* Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring, -ENOENT if
* the key isn't linked to by the keyring or -ENOMEM if there's insufficient
* memory.
*
* It is assumed that the caller has checked that it is permitted for a link to
* be removed (the keyring should have Write permission; no permissions are
* required on the key).
*/
int key_unlink(struct key *keyring, struct key *key)
{
struct keyring_list *klist, *nklist;
int loop, ret;
key_check(keyring);
key_check(key);
ret = -ENOTDIR;
if (keyring->type != &key_type_keyring)
goto error;
down_write(&keyring->sem);
klist = rcu_dereference_locked_keyring(keyring);
if (klist) {
/* search the keyring for the key */
for (loop = 0; loop < klist->nkeys; loop++)
if (klist->keys[loop] == key)
goto key_is_present;
}
up_write(&keyring->sem);
ret = -ENOENT;
goto error;
key_is_present:
/* we need to copy the key list for RCU purposes */
nklist = kmalloc(sizeof(*klist) +
sizeof(struct key *) * klist->maxkeys,
GFP_KERNEL);
if (!nklist)
goto nomem;
nklist->maxkeys = klist->maxkeys;
nklist->nkeys = klist->nkeys - 1;
if (loop > 0)
memcpy(&nklist->keys[0],
&klist->keys[0],
loop * sizeof(struct key *));
if (loop < nklist->nkeys)
memcpy(&nklist->keys[loop],
&klist->keys[loop + 1],
(nklist->nkeys - loop) * sizeof(struct key *));
/* adjust the user's quota */
key_payload_reserve(keyring,
keyring->datalen - KEYQUOTA_LINK_BYTES);
rcu_assign_pointer(keyring->payload.subscriptions, nklist);
up_write(&keyring->sem);
/* schedule for later cleanup */
klist->delkey = loop;
call_rcu(&klist->rcu, keyring_unlink_rcu_disposal);
ret = 0;
error:
return ret;
nomem:
ret = -ENOMEM;
up_write(&keyring->sem);
goto error;
}
EXPORT_SYMBOL(key_unlink);
/*
* Dispose of a keyring list after the RCU grace period, releasing the keys it
* links to.
*/
static void keyring_clear_rcu_disposal(struct rcu_head *rcu)
{
struct keyring_list *klist;
int loop;
klist = container_of(rcu, struct keyring_list, rcu);
for (loop = klist->nkeys - 1; loop >= 0; loop--)
key_put(klist->keys[loop]);
kfree(klist);
}
/**
* keyring_clear - Clear a keyring
* @keyring: The keyring to clear.
*
* Clear the contents of the specified keyring.
*
* Returns 0 if successful or -ENOTDIR if the keyring isn't a keyring.
*/
int keyring_clear(struct key *keyring)
{
struct keyring_list *klist;
int ret;
ret = -ENOTDIR;
if (keyring->type == &key_type_keyring) {
/* detach the pointer block with the locks held */
down_write(&keyring->sem);
klist = rcu_dereference_locked_keyring(keyring);
if (klist) {
/* adjust the quota */
key_payload_reserve(keyring,
sizeof(struct keyring_list));
rcu_assign_pointer(keyring->payload.subscriptions,
NULL);
}
up_write(&keyring->sem);
/* free the keys after the locks have been dropped */
if (klist)
call_rcu(&klist->rcu, keyring_clear_rcu_disposal);
ret = 0;
}
return ret;
}
EXPORT_SYMBOL(keyring_clear);
/*
* Dispose of the links from a revoked keyring.
*
* This is called with the key sem write-locked.
*/
static void keyring_revoke(struct key *keyring)
{
struct keyring_list *klist;
klist = rcu_dereference_locked_keyring(keyring);
/* adjust the quota */
key_payload_reserve(keyring, 0);
if (klist) {
rcu_assign_pointer(keyring->payload.subscriptions, NULL);
call_rcu(&klist->rcu, keyring_clear_rcu_disposal);
}
}
/*
* Determine whether a key is dead.
*/
static bool key_is_dead(struct key *key, time_t limit)
{
return test_bit(KEY_FLAG_DEAD, &key->flags) ||
(key->expiry > 0 && key->expiry <= limit);
}
/*
* Collect garbage from the contents of a keyring, replacing the old list with
* a new one with the pointers all shuffled down.
*
* Dead keys are classed as oned that are flagged as being dead or are revoked,
* expired or negative keys that were revoked or expired before the specified
* limit.
*/
void keyring_gc(struct key *keyring, time_t limit)
{
struct keyring_list *klist, *new;
struct key *key;
int loop, keep, max;
kenter("{%x,%s}", key_serial(keyring), keyring->description);
down_write(&keyring->sem);
klist = rcu_dereference_locked_keyring(keyring);
if (!klist)
goto no_klist;
/* work out how many subscriptions we're keeping */
keep = 0;
for (loop = klist->nkeys - 1; loop >= 0; loop--)
if (!key_is_dead(klist->keys[loop], limit))
keep++;
if (keep == klist->nkeys)
goto just_return;
/* allocate a new keyring payload */
max = roundup(keep, 4);
new = kmalloc(sizeof(struct keyring_list) + max * sizeof(struct key *),
GFP_KERNEL);
if (!new)
goto nomem;
new->maxkeys = max;
new->nkeys = 0;
new->delkey = 0;
/* install the live keys
* - must take care as expired keys may be updated back to life
*/
keep = 0;
for (loop = klist->nkeys - 1; loop >= 0; loop--) {
key = klist->keys[loop];
if (!key_is_dead(key, limit)) {
if (keep >= max)
goto discard_new;
new->keys[keep++] = key_get(key);
}
}
new->nkeys = keep;
/* adjust the quota */
key_payload_reserve(keyring,
sizeof(struct keyring_list) +
KEYQUOTA_LINK_BYTES * keep);
if (keep == 0) {
rcu_assign_pointer(keyring->payload.subscriptions, NULL);
kfree(new);
} else {
rcu_assign_pointer(keyring->payload.subscriptions, new);
}
up_write(&keyring->sem);
call_rcu(&klist->rcu, keyring_clear_rcu_disposal);
kleave(" [yes]");
return;
discard_new:
new->nkeys = keep;
keyring_clear_rcu_disposal(&new->rcu);
up_write(&keyring->sem);
kleave(" [discard]");
return;
just_return:
up_write(&keyring->sem);
kleave(" [no dead]");
return;
no_klist:
up_write(&keyring->sem);
kleave(" [no_klist]");
return;
nomem:
up_write(&keyring->sem);
kleave(" [oom]");
}
| gpl-2.0 |
Project-Elite/elite_kernel_jf_tw | net/ipv4/proc.c | 2872 | 18039 | /*
* INET An implementation of the TCP/IP protocol suite for the LINUX
* operating system. INET is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* This file implements the various access functions for the
* PROC file system. It is mainly used for debugging and
* statistics.
*
* Authors: Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
* Gerald J. Heim, <heim@peanuts.informatik.uni-tuebingen.de>
* Fred Baumgarten, <dc6iq@insu1.etec.uni-karlsruhe.de>
* Erik Schoenfelder, <schoenfr@ibr.cs.tu-bs.de>
*
* Fixes:
* Alan Cox : UDP sockets show the rxqueue/txqueue
* using hint flag for the netinfo.
* Pauline Middelink : identd support
* Alan Cox : Make /proc safer.
* Erik Schoenfelder : /proc/net/snmp
* Alan Cox : Handle dead sockets properly.
* Gerhard Koerting : Show both timers
* Alan Cox : Allow inode to be NULL (kernel socket)
* Andi Kleen : Add support for open_requests and
* split functions for more readibility.
* Andi Kleen : Add support for /proc/net/netstat
* Arnaldo C. Melo : Convert to seq_file
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/types.h>
#include <net/net_namespace.h>
#include <net/icmp.h>
#include <net/protocol.h>
#include <net/tcp.h>
#include <net/udp.h>
#include <net/udplite.h>
#include <linux/bottom_half.h>
#include <linux/inetdevice.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/export.h>
#include <net/sock.h>
#include <net/raw.h>
/*
* Report socket allocation statistics [mea@utu.fi]
*/
static int sockstat_seq_show(struct seq_file *seq, void *v)
{
struct net *net = seq->private;
int orphans, sockets;
local_bh_disable();
orphans = percpu_counter_sum_positive(&tcp_orphan_count);
sockets = proto_sockets_allocated_sum_positive(&tcp_prot);
local_bh_enable();
socket_seq_show(seq);
seq_printf(seq, "TCP: inuse %d orphan %d tw %d alloc %d mem %ld\n",
sock_prot_inuse_get(net, &tcp_prot), orphans,
tcp_death_row.tw_count, sockets,
proto_memory_allocated(&tcp_prot));
seq_printf(seq, "UDP: inuse %d mem %ld\n",
sock_prot_inuse_get(net, &udp_prot),
proto_memory_allocated(&udp_prot));
seq_printf(seq, "UDPLITE: inuse %d\n",
sock_prot_inuse_get(net, &udplite_prot));
seq_printf(seq, "RAW: inuse %d\n",
sock_prot_inuse_get(net, &raw_prot));
seq_printf(seq, "FRAG: inuse %d memory %d\n",
ip_frag_nqueues(net), ip_frag_mem(net));
return 0;
}
static int sockstat_seq_open(struct inode *inode, struct file *file)
{
return single_open_net(inode, file, sockstat_seq_show);
}
static const struct file_operations sockstat_seq_fops = {
.owner = THIS_MODULE,
.open = sockstat_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release_net,
};
/* snmp items */
static const struct snmp_mib snmp4_ipstats_list[] = {
SNMP_MIB_ITEM("InReceives", IPSTATS_MIB_INPKTS),
SNMP_MIB_ITEM("InHdrErrors", IPSTATS_MIB_INHDRERRORS),
SNMP_MIB_ITEM("InAddrErrors", IPSTATS_MIB_INADDRERRORS),
SNMP_MIB_ITEM("ForwDatagrams", IPSTATS_MIB_OUTFORWDATAGRAMS),
SNMP_MIB_ITEM("InUnknownProtos", IPSTATS_MIB_INUNKNOWNPROTOS),
SNMP_MIB_ITEM("InDiscards", IPSTATS_MIB_INDISCARDS),
SNMP_MIB_ITEM("InDelivers", IPSTATS_MIB_INDELIVERS),
SNMP_MIB_ITEM("OutRequests", IPSTATS_MIB_OUTPKTS),
SNMP_MIB_ITEM("OutDiscards", IPSTATS_MIB_OUTDISCARDS),
SNMP_MIB_ITEM("OutNoRoutes", IPSTATS_MIB_OUTNOROUTES),
SNMP_MIB_ITEM("ReasmTimeout", IPSTATS_MIB_REASMTIMEOUT),
SNMP_MIB_ITEM("ReasmReqds", IPSTATS_MIB_REASMREQDS),
SNMP_MIB_ITEM("ReasmOKs", IPSTATS_MIB_REASMOKS),
SNMP_MIB_ITEM("ReasmFails", IPSTATS_MIB_REASMFAILS),
SNMP_MIB_ITEM("FragOKs", IPSTATS_MIB_FRAGOKS),
SNMP_MIB_ITEM("FragFails", IPSTATS_MIB_FRAGFAILS),
SNMP_MIB_ITEM("FragCreates", IPSTATS_MIB_FRAGCREATES),
SNMP_MIB_SENTINEL
};
/* Following RFC4293 items are displayed in /proc/net/netstat */
static const struct snmp_mib snmp4_ipextstats_list[] = {
SNMP_MIB_ITEM("InNoRoutes", IPSTATS_MIB_INNOROUTES),
SNMP_MIB_ITEM("InTruncatedPkts", IPSTATS_MIB_INTRUNCATEDPKTS),
SNMP_MIB_ITEM("InMcastPkts", IPSTATS_MIB_INMCASTPKTS),
SNMP_MIB_ITEM("OutMcastPkts", IPSTATS_MIB_OUTMCASTPKTS),
SNMP_MIB_ITEM("InBcastPkts", IPSTATS_MIB_INBCASTPKTS),
SNMP_MIB_ITEM("OutBcastPkts", IPSTATS_MIB_OUTBCASTPKTS),
SNMP_MIB_ITEM("InOctets", IPSTATS_MIB_INOCTETS),
SNMP_MIB_ITEM("OutOctets", IPSTATS_MIB_OUTOCTETS),
SNMP_MIB_ITEM("InMcastOctets", IPSTATS_MIB_INMCASTOCTETS),
SNMP_MIB_ITEM("OutMcastOctets", IPSTATS_MIB_OUTMCASTOCTETS),
SNMP_MIB_ITEM("InBcastOctets", IPSTATS_MIB_INBCASTOCTETS),
SNMP_MIB_ITEM("OutBcastOctets", IPSTATS_MIB_OUTBCASTOCTETS),
SNMP_MIB_SENTINEL
};
static const struct {
const char *name;
int index;
} icmpmibmap[] = {
{ "DestUnreachs", ICMP_DEST_UNREACH },
{ "TimeExcds", ICMP_TIME_EXCEEDED },
{ "ParmProbs", ICMP_PARAMETERPROB },
{ "SrcQuenchs", ICMP_SOURCE_QUENCH },
{ "Redirects", ICMP_REDIRECT },
{ "Echos", ICMP_ECHO },
{ "EchoReps", ICMP_ECHOREPLY },
{ "Timestamps", ICMP_TIMESTAMP },
{ "TimestampReps", ICMP_TIMESTAMPREPLY },
{ "AddrMasks", ICMP_ADDRESS },
{ "AddrMaskReps", ICMP_ADDRESSREPLY },
{ NULL, 0 }
};
static const struct snmp_mib snmp4_tcp_list[] = {
SNMP_MIB_ITEM("RtoAlgorithm", TCP_MIB_RTOALGORITHM),
SNMP_MIB_ITEM("RtoMin", TCP_MIB_RTOMIN),
SNMP_MIB_ITEM("RtoMax", TCP_MIB_RTOMAX),
SNMP_MIB_ITEM("MaxConn", TCP_MIB_MAXCONN),
SNMP_MIB_ITEM("ActiveOpens", TCP_MIB_ACTIVEOPENS),
SNMP_MIB_ITEM("PassiveOpens", TCP_MIB_PASSIVEOPENS),
SNMP_MIB_ITEM("AttemptFails", TCP_MIB_ATTEMPTFAILS),
SNMP_MIB_ITEM("EstabResets", TCP_MIB_ESTABRESETS),
SNMP_MIB_ITEM("CurrEstab", TCP_MIB_CURRESTAB),
SNMP_MIB_ITEM("InSegs", TCP_MIB_INSEGS),
SNMP_MIB_ITEM("OutSegs", TCP_MIB_OUTSEGS),
SNMP_MIB_ITEM("RetransSegs", TCP_MIB_RETRANSSEGS),
SNMP_MIB_ITEM("InErrs", TCP_MIB_INERRS),
SNMP_MIB_ITEM("OutRsts", TCP_MIB_OUTRSTS),
SNMP_MIB_SENTINEL
};
static const struct snmp_mib snmp4_udp_list[] = {
SNMP_MIB_ITEM("InDatagrams", UDP_MIB_INDATAGRAMS),
SNMP_MIB_ITEM("NoPorts", UDP_MIB_NOPORTS),
SNMP_MIB_ITEM("InErrors", UDP_MIB_INERRORS),
SNMP_MIB_ITEM("OutDatagrams", UDP_MIB_OUTDATAGRAMS),
SNMP_MIB_ITEM("RcvbufErrors", UDP_MIB_RCVBUFERRORS),
SNMP_MIB_ITEM("SndbufErrors", UDP_MIB_SNDBUFERRORS),
SNMP_MIB_SENTINEL
};
static const struct snmp_mib snmp4_net_list[] = {
SNMP_MIB_ITEM("SyncookiesSent", LINUX_MIB_SYNCOOKIESSENT),
SNMP_MIB_ITEM("SyncookiesRecv", LINUX_MIB_SYNCOOKIESRECV),
SNMP_MIB_ITEM("SyncookiesFailed", LINUX_MIB_SYNCOOKIESFAILED),
SNMP_MIB_ITEM("EmbryonicRsts", LINUX_MIB_EMBRYONICRSTS),
SNMP_MIB_ITEM("PruneCalled", LINUX_MIB_PRUNECALLED),
SNMP_MIB_ITEM("RcvPruned", LINUX_MIB_RCVPRUNED),
SNMP_MIB_ITEM("OfoPruned", LINUX_MIB_OFOPRUNED),
SNMP_MIB_ITEM("OutOfWindowIcmps", LINUX_MIB_OUTOFWINDOWICMPS),
SNMP_MIB_ITEM("LockDroppedIcmps", LINUX_MIB_LOCKDROPPEDICMPS),
SNMP_MIB_ITEM("ArpFilter", LINUX_MIB_ARPFILTER),
SNMP_MIB_ITEM("TW", LINUX_MIB_TIMEWAITED),
SNMP_MIB_ITEM("TWRecycled", LINUX_MIB_TIMEWAITRECYCLED),
SNMP_MIB_ITEM("TWKilled", LINUX_MIB_TIMEWAITKILLED),
SNMP_MIB_ITEM("PAWSPassive", LINUX_MIB_PAWSPASSIVEREJECTED),
SNMP_MIB_ITEM("PAWSActive", LINUX_MIB_PAWSACTIVEREJECTED),
SNMP_MIB_ITEM("PAWSEstab", LINUX_MIB_PAWSESTABREJECTED),
SNMP_MIB_ITEM("DelayedACKs", LINUX_MIB_DELAYEDACKS),
SNMP_MIB_ITEM("DelayedACKLocked", LINUX_MIB_DELAYEDACKLOCKED),
SNMP_MIB_ITEM("DelayedACKLost", LINUX_MIB_DELAYEDACKLOST),
SNMP_MIB_ITEM("ListenOverflows", LINUX_MIB_LISTENOVERFLOWS),
SNMP_MIB_ITEM("ListenDrops", LINUX_MIB_LISTENDROPS),
SNMP_MIB_ITEM("TCPPrequeued", LINUX_MIB_TCPPREQUEUED),
SNMP_MIB_ITEM("TCPDirectCopyFromBacklog", LINUX_MIB_TCPDIRECTCOPYFROMBACKLOG),
SNMP_MIB_ITEM("TCPDirectCopyFromPrequeue", LINUX_MIB_TCPDIRECTCOPYFROMPREQUEUE),
SNMP_MIB_ITEM("TCPPrequeueDropped", LINUX_MIB_TCPPREQUEUEDROPPED),
SNMP_MIB_ITEM("TCPHPHits", LINUX_MIB_TCPHPHITS),
SNMP_MIB_ITEM("TCPHPHitsToUser", LINUX_MIB_TCPHPHITSTOUSER),
SNMP_MIB_ITEM("TCPPureAcks", LINUX_MIB_TCPPUREACKS),
SNMP_MIB_ITEM("TCPHPAcks", LINUX_MIB_TCPHPACKS),
SNMP_MIB_ITEM("TCPRenoRecovery", LINUX_MIB_TCPRENORECOVERY),
SNMP_MIB_ITEM("TCPSackRecovery", LINUX_MIB_TCPSACKRECOVERY),
SNMP_MIB_ITEM("TCPSACKReneging", LINUX_MIB_TCPSACKRENEGING),
SNMP_MIB_ITEM("TCPFACKReorder", LINUX_MIB_TCPFACKREORDER),
SNMP_MIB_ITEM("TCPSACKReorder", LINUX_MIB_TCPSACKREORDER),
SNMP_MIB_ITEM("TCPRenoReorder", LINUX_MIB_TCPRENOREORDER),
SNMP_MIB_ITEM("TCPTSReorder", LINUX_MIB_TCPTSREORDER),
SNMP_MIB_ITEM("TCPFullUndo", LINUX_MIB_TCPFULLUNDO),
SNMP_MIB_ITEM("TCPPartialUndo", LINUX_MIB_TCPPARTIALUNDO),
SNMP_MIB_ITEM("TCPDSACKUndo", LINUX_MIB_TCPDSACKUNDO),
SNMP_MIB_ITEM("TCPLossUndo", LINUX_MIB_TCPLOSSUNDO),
SNMP_MIB_ITEM("TCPLostRetransmit", LINUX_MIB_TCPLOSTRETRANSMIT),
SNMP_MIB_ITEM("TCPRenoFailures", LINUX_MIB_TCPRENOFAILURES),
SNMP_MIB_ITEM("TCPSackFailures", LINUX_MIB_TCPSACKFAILURES),
SNMP_MIB_ITEM("TCPLossFailures", LINUX_MIB_TCPLOSSFAILURES),
SNMP_MIB_ITEM("TCPFastRetrans", LINUX_MIB_TCPFASTRETRANS),
SNMP_MIB_ITEM("TCPForwardRetrans", LINUX_MIB_TCPFORWARDRETRANS),
SNMP_MIB_ITEM("TCPSlowStartRetrans", LINUX_MIB_TCPSLOWSTARTRETRANS),
SNMP_MIB_ITEM("TCPTimeouts", LINUX_MIB_TCPTIMEOUTS),
SNMP_MIB_ITEM("TCPRenoRecoveryFail", LINUX_MIB_TCPRENORECOVERYFAIL),
SNMP_MIB_ITEM("TCPSackRecoveryFail", LINUX_MIB_TCPSACKRECOVERYFAIL),
SNMP_MIB_ITEM("TCPSchedulerFailed", LINUX_MIB_TCPSCHEDULERFAILED),
SNMP_MIB_ITEM("TCPRcvCollapsed", LINUX_MIB_TCPRCVCOLLAPSED),
SNMP_MIB_ITEM("TCPDSACKOldSent", LINUX_MIB_TCPDSACKOLDSENT),
SNMP_MIB_ITEM("TCPDSACKOfoSent", LINUX_MIB_TCPDSACKOFOSENT),
SNMP_MIB_ITEM("TCPDSACKRecv", LINUX_MIB_TCPDSACKRECV),
SNMP_MIB_ITEM("TCPDSACKOfoRecv", LINUX_MIB_TCPDSACKOFORECV),
SNMP_MIB_ITEM("TCPAbortOnSyn", LINUX_MIB_TCPABORTONSYN),
SNMP_MIB_ITEM("TCPAbortOnData", LINUX_MIB_TCPABORTONDATA),
SNMP_MIB_ITEM("TCPAbortOnClose", LINUX_MIB_TCPABORTONCLOSE),
SNMP_MIB_ITEM("TCPAbortOnMemory", LINUX_MIB_TCPABORTONMEMORY),
SNMP_MIB_ITEM("TCPAbortOnTimeout", LINUX_MIB_TCPABORTONTIMEOUT),
SNMP_MIB_ITEM("TCPAbortOnLinger", LINUX_MIB_TCPABORTONLINGER),
SNMP_MIB_ITEM("TCPAbortFailed", LINUX_MIB_TCPABORTFAILED),
SNMP_MIB_ITEM("TCPMemoryPressures", LINUX_MIB_TCPMEMORYPRESSURES),
SNMP_MIB_ITEM("TCPSACKDiscard", LINUX_MIB_TCPSACKDISCARD),
SNMP_MIB_ITEM("TCPDSACKIgnoredOld", LINUX_MIB_TCPDSACKIGNOREDOLD),
SNMP_MIB_ITEM("TCPDSACKIgnoredNoUndo", LINUX_MIB_TCPDSACKIGNOREDNOUNDO),
SNMP_MIB_ITEM("TCPSpuriousRTOs", LINUX_MIB_TCPSPURIOUSRTOS),
SNMP_MIB_ITEM("TCPMD5NotFound", LINUX_MIB_TCPMD5NOTFOUND),
SNMP_MIB_ITEM("TCPMD5Unexpected", LINUX_MIB_TCPMD5UNEXPECTED),
SNMP_MIB_ITEM("TCPSackShifted", LINUX_MIB_SACKSHIFTED),
SNMP_MIB_ITEM("TCPSackMerged", LINUX_MIB_SACKMERGED),
SNMP_MIB_ITEM("TCPSackShiftFallback", LINUX_MIB_SACKSHIFTFALLBACK),
SNMP_MIB_ITEM("TCPBacklogDrop", LINUX_MIB_TCPBACKLOGDROP),
SNMP_MIB_ITEM("TCPMinTTLDrop", LINUX_MIB_TCPMINTTLDROP),
SNMP_MIB_ITEM("TCPDeferAcceptDrop", LINUX_MIB_TCPDEFERACCEPTDROP),
SNMP_MIB_ITEM("IPReversePathFilter", LINUX_MIB_IPRPFILTER),
SNMP_MIB_ITEM("TCPTimeWaitOverflow", LINUX_MIB_TCPTIMEWAITOVERFLOW),
SNMP_MIB_ITEM("TCPReqQFullDoCookies", LINUX_MIB_TCPREQQFULLDOCOOKIES),
SNMP_MIB_ITEM("TCPReqQFullDrop", LINUX_MIB_TCPREQQFULLDROP),
SNMP_MIB_ITEM("TCPRetransFail", LINUX_MIB_TCPRETRANSFAIL),
SNMP_MIB_ITEM("TCPRcvCoalesce", LINUX_MIB_TCPRCVCOALESCE),
SNMP_MIB_SENTINEL
};
static void icmpmsg_put_line(struct seq_file *seq, unsigned long *vals,
unsigned short *type, int count)
{
int j;
if (count) {
seq_printf(seq, "\nIcmpMsg:");
for (j = 0; j < count; ++j)
seq_printf(seq, " %sType%u",
type[j] & 0x100 ? "Out" : "In",
type[j] & 0xff);
seq_printf(seq, "\nIcmpMsg:");
for (j = 0; j < count; ++j)
seq_printf(seq, " %lu", vals[j]);
}
}
static void icmpmsg_put(struct seq_file *seq)
{
#define PERLINE 16
int i, count;
unsigned short type[PERLINE];
unsigned long vals[PERLINE], val;
struct net *net = seq->private;
count = 0;
for (i = 0; i < ICMPMSG_MIB_MAX; i++) {
val = atomic_long_read(&net->mib.icmpmsg_statistics->mibs[i]);
if (val) {
type[count] = i;
vals[count++] = val;
}
if (count == PERLINE) {
icmpmsg_put_line(seq, vals, type, count);
count = 0;
}
}
icmpmsg_put_line(seq, vals, type, count);
#undef PERLINE
}
static void icmp_put(struct seq_file *seq)
{
int i;
struct net *net = seq->private;
atomic_long_t *ptr = net->mib.icmpmsg_statistics->mibs;
seq_puts(seq, "\nIcmp: InMsgs InErrors");
for (i=0; icmpmibmap[i].name != NULL; i++)
seq_printf(seq, " In%s", icmpmibmap[i].name);
seq_printf(seq, " OutMsgs OutErrors");
for (i=0; icmpmibmap[i].name != NULL; i++)
seq_printf(seq, " Out%s", icmpmibmap[i].name);
seq_printf(seq, "\nIcmp: %lu %lu",
snmp_fold_field((void __percpu **) net->mib.icmp_statistics, ICMP_MIB_INMSGS),
snmp_fold_field((void __percpu **) net->mib.icmp_statistics, ICMP_MIB_INERRORS));
for (i=0; icmpmibmap[i].name != NULL; i++)
seq_printf(seq, " %lu",
atomic_long_read(ptr + icmpmibmap[i].index));
seq_printf(seq, " %lu %lu",
snmp_fold_field((void __percpu **) net->mib.icmp_statistics, ICMP_MIB_OUTMSGS),
snmp_fold_field((void __percpu **) net->mib.icmp_statistics, ICMP_MIB_OUTERRORS));
for (i=0; icmpmibmap[i].name != NULL; i++)
seq_printf(seq, " %lu",
atomic_long_read(ptr + (icmpmibmap[i].index | 0x100)));
}
/*
* Called from the PROCfs module. This outputs /proc/net/snmp.
*/
static int snmp_seq_show(struct seq_file *seq, void *v)
{
int i;
struct net *net = seq->private;
seq_puts(seq, "Ip: Forwarding DefaultTTL");
for (i = 0; snmp4_ipstats_list[i].name != NULL; i++)
seq_printf(seq, " %s", snmp4_ipstats_list[i].name);
seq_printf(seq, "\nIp: %d %d",
IPV4_DEVCONF_ALL(net, FORWARDING) ? 1 : 2,
sysctl_ip_default_ttl);
BUILD_BUG_ON(offsetof(struct ipstats_mib, mibs) != 0);
for (i = 0; snmp4_ipstats_list[i].name != NULL; i++)
seq_printf(seq, " %llu",
snmp_fold_field64((void __percpu **)net->mib.ip_statistics,
snmp4_ipstats_list[i].entry,
offsetof(struct ipstats_mib, syncp)));
icmp_put(seq); /* RFC 2011 compatibility */
icmpmsg_put(seq);
seq_puts(seq, "\nTcp:");
for (i = 0; snmp4_tcp_list[i].name != NULL; i++)
seq_printf(seq, " %s", snmp4_tcp_list[i].name);
seq_puts(seq, "\nTcp:");
for (i = 0; snmp4_tcp_list[i].name != NULL; i++) {
/* MaxConn field is signed, RFC 2012 */
if (snmp4_tcp_list[i].entry == TCP_MIB_MAXCONN)
seq_printf(seq, " %ld",
snmp_fold_field((void __percpu **)net->mib.tcp_statistics,
snmp4_tcp_list[i].entry));
else
seq_printf(seq, " %lu",
snmp_fold_field((void __percpu **)net->mib.tcp_statistics,
snmp4_tcp_list[i].entry));
}
seq_puts(seq, "\nUdp:");
for (i = 0; snmp4_udp_list[i].name != NULL; i++)
seq_printf(seq, " %s", snmp4_udp_list[i].name);
seq_puts(seq, "\nUdp:");
for (i = 0; snmp4_udp_list[i].name != NULL; i++)
seq_printf(seq, " %lu",
snmp_fold_field((void __percpu **)net->mib.udp_statistics,
snmp4_udp_list[i].entry));
/* the UDP and UDP-Lite MIBs are the same */
seq_puts(seq, "\nUdpLite:");
for (i = 0; snmp4_udp_list[i].name != NULL; i++)
seq_printf(seq, " %s", snmp4_udp_list[i].name);
seq_puts(seq, "\nUdpLite:");
for (i = 0; snmp4_udp_list[i].name != NULL; i++)
seq_printf(seq, " %lu",
snmp_fold_field((void __percpu **)net->mib.udplite_statistics,
snmp4_udp_list[i].entry));
seq_putc(seq, '\n');
return 0;
}
static int snmp_seq_open(struct inode *inode, struct file *file)
{
return single_open_net(inode, file, snmp_seq_show);
}
static const struct file_operations snmp_seq_fops = {
.owner = THIS_MODULE,
.open = snmp_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release_net,
};
/*
* Output /proc/net/netstat
*/
static int netstat_seq_show(struct seq_file *seq, void *v)
{
int i;
struct net *net = seq->private;
seq_puts(seq, "TcpExt:");
for (i = 0; snmp4_net_list[i].name != NULL; i++)
seq_printf(seq, " %s", snmp4_net_list[i].name);
seq_puts(seq, "\nTcpExt:");
for (i = 0; snmp4_net_list[i].name != NULL; i++)
seq_printf(seq, " %lu",
snmp_fold_field((void __percpu **)net->mib.net_statistics,
snmp4_net_list[i].entry));
seq_puts(seq, "\nIpExt:");
for (i = 0; snmp4_ipextstats_list[i].name != NULL; i++)
seq_printf(seq, " %s", snmp4_ipextstats_list[i].name);
seq_puts(seq, "\nIpExt:");
for (i = 0; snmp4_ipextstats_list[i].name != NULL; i++)
seq_printf(seq, " %llu",
snmp_fold_field64((void __percpu **)net->mib.ip_statistics,
snmp4_ipextstats_list[i].entry,
offsetof(struct ipstats_mib, syncp)));
seq_putc(seq, '\n');
return 0;
}
static int netstat_seq_open(struct inode *inode, struct file *file)
{
return single_open_net(inode, file, netstat_seq_show);
}
static const struct file_operations netstat_seq_fops = {
.owner = THIS_MODULE,
.open = netstat_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release_net,
};
static __net_init int ip_proc_init_net(struct net *net)
{
if (!proc_net_fops_create(net, "sockstat", S_IRUGO, &sockstat_seq_fops))
goto out_sockstat;
if (!proc_net_fops_create(net, "netstat", S_IRUGO, &netstat_seq_fops))
goto out_netstat;
if (!proc_net_fops_create(net, "snmp", S_IRUGO, &snmp_seq_fops))
goto out_snmp;
return 0;
out_snmp:
proc_net_remove(net, "netstat");
out_netstat:
proc_net_remove(net, "sockstat");
out_sockstat:
return -ENOMEM;
}
static __net_exit void ip_proc_exit_net(struct net *net)
{
proc_net_remove(net, "snmp");
proc_net_remove(net, "netstat");
proc_net_remove(net, "sockstat");
}
static __net_initdata struct pernet_operations ip_proc_ops = {
.init = ip_proc_init_net,
.exit = ip_proc_exit_net,
};
int __init ip_misc_proc_init(void)
{
return register_pernet_subsys(&ip_proc_ops);
}
| gpl-2.0 |
spica234/LiteGX | drivers/input/misc/bfin_rotary.c | 3640 | 6458 | /*
* Rotary counter driver for Analog Devices Blackfin Processors
*
* Copyright 2008-2009 Analog Devices Inc.
* Licensed under the GPL-2 or later.
*/
#include <linux/module.h>
#include <linux/version.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/pm.h>
#include <linux/platform_device.h>
#include <linux/input.h>
#include <linux/slab.h>
#include <asm/portmux.h>
#include <asm/bfin_rotary.h>
static const u16 per_cnt[] = {
P_CNT_CUD,
P_CNT_CDG,
P_CNT_CZM,
0
};
struct bfin_rot {
struct input_dev *input;
int irq;
unsigned int up_key;
unsigned int down_key;
unsigned int button_key;
unsigned int rel_code;
unsigned short cnt_config;
unsigned short cnt_imask;
unsigned short cnt_debounce;
};
static void report_key_event(struct input_dev *input, int keycode)
{
/* simulate a press-n-release */
input_report_key(input, keycode, 1);
input_sync(input);
input_report_key(input, keycode, 0);
input_sync(input);
}
static void report_rotary_event(struct bfin_rot *rotary, int delta)
{
struct input_dev *input = rotary->input;
if (rotary->up_key) {
report_key_event(input,
delta > 0 ? rotary->up_key : rotary->down_key);
} else {
input_report_rel(input, rotary->rel_code, delta);
input_sync(input);
}
}
static irqreturn_t bfin_rotary_isr(int irq, void *dev_id)
{
struct platform_device *pdev = dev_id;
struct bfin_rot *rotary = platform_get_drvdata(pdev);
int delta;
switch (bfin_read_CNT_STATUS()) {
case ICII:
break;
case UCII:
case DCII:
delta = bfin_read_CNT_COUNTER();
if (delta)
report_rotary_event(rotary, delta);
break;
case CZMII:
report_key_event(rotary->input, rotary->button_key);
break;
default:
break;
}
bfin_write_CNT_COMMAND(W1LCNT_ZERO); /* Clear COUNTER */
bfin_write_CNT_STATUS(-1); /* Clear STATUS */
return IRQ_HANDLED;
}
static int __devinit bfin_rotary_probe(struct platform_device *pdev)
{
struct bfin_rotary_platform_data *pdata = pdev->dev.platform_data;
struct bfin_rot *rotary;
struct input_dev *input;
int error;
/* Basic validation */
if ((pdata->rotary_up_key && !pdata->rotary_down_key) ||
(!pdata->rotary_up_key && pdata->rotary_down_key)) {
return -EINVAL;
}
error = peripheral_request_list(per_cnt, dev_name(&pdev->dev));
if (error) {
dev_err(&pdev->dev, "requesting peripherals failed\n");
return error;
}
rotary = kzalloc(sizeof(struct bfin_rot), GFP_KERNEL);
input = input_allocate_device();
if (!rotary || !input) {
error = -ENOMEM;
goto out1;
}
rotary->input = input;
rotary->up_key = pdata->rotary_up_key;
rotary->down_key = pdata->rotary_down_key;
rotary->button_key = pdata->rotary_button_key;
rotary->rel_code = pdata->rotary_rel_code;
error = rotary->irq = platform_get_irq(pdev, 0);
if (error < 0)
goto out1;
input->name = pdev->name;
input->phys = "bfin-rotary/input0";
input->dev.parent = &pdev->dev;
input_set_drvdata(input, rotary);
input->id.bustype = BUS_HOST;
input->id.vendor = 0x0001;
input->id.product = 0x0001;
input->id.version = 0x0100;
if (rotary->up_key) {
__set_bit(EV_KEY, input->evbit);
__set_bit(rotary->up_key, input->keybit);
__set_bit(rotary->down_key, input->keybit);
} else {
__set_bit(EV_REL, input->evbit);
__set_bit(rotary->rel_code, input->relbit);
}
if (rotary->button_key) {
__set_bit(EV_KEY, input->evbit);
__set_bit(rotary->button_key, input->keybit);
}
error = request_irq(rotary->irq, bfin_rotary_isr,
0, dev_name(&pdev->dev), pdev);
if (error) {
dev_err(&pdev->dev,
"unable to claim irq %d; error %d\n",
rotary->irq, error);
goto out1;
}
error = input_register_device(input);
if (error) {
dev_err(&pdev->dev,
"unable to register input device (%d)\n", error);
goto out2;
}
if (pdata->rotary_button_key)
bfin_write_CNT_IMASK(CZMIE);
if (pdata->mode & ROT_DEBE)
bfin_write_CNT_DEBOUNCE(pdata->debounce & DPRESCALE);
if (pdata->mode)
bfin_write_CNT_CONFIG(bfin_read_CNT_CONFIG() |
(pdata->mode & ~CNTE));
bfin_write_CNT_IMASK(bfin_read_CNT_IMASK() | UCIE | DCIE);
bfin_write_CNT_CONFIG(bfin_read_CNT_CONFIG() | CNTE);
platform_set_drvdata(pdev, rotary);
device_init_wakeup(&pdev->dev, 1);
return 0;
out2:
free_irq(rotary->irq, pdev);
out1:
input_free_device(input);
kfree(rotary);
peripheral_free_list(per_cnt);
return error;
}
static int __devexit bfin_rotary_remove(struct platform_device *pdev)
{
struct bfin_rot *rotary = platform_get_drvdata(pdev);
bfin_write_CNT_CONFIG(0);
bfin_write_CNT_IMASK(0);
free_irq(rotary->irq, pdev);
input_unregister_device(rotary->input);
peripheral_free_list(per_cnt);
kfree(rotary);
platform_set_drvdata(pdev, NULL);
return 0;
}
#ifdef CONFIG_PM
static int bfin_rotary_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct bfin_rot *rotary = platform_get_drvdata(pdev);
rotary->cnt_config = bfin_read_CNT_CONFIG();
rotary->cnt_imask = bfin_read_CNT_IMASK();
rotary->cnt_debounce = bfin_read_CNT_DEBOUNCE();
if (device_may_wakeup(&pdev->dev))
enable_irq_wake(rotary->irq);
return 0;
}
static int bfin_rotary_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct bfin_rot *rotary = platform_get_drvdata(pdev);
bfin_write_CNT_DEBOUNCE(rotary->cnt_debounce);
bfin_write_CNT_IMASK(rotary->cnt_imask);
bfin_write_CNT_CONFIG(rotary->cnt_config & ~CNTE);
if (device_may_wakeup(&pdev->dev))
disable_irq_wake(rotary->irq);
if (rotary->cnt_config & CNTE)
bfin_write_CNT_CONFIG(rotary->cnt_config);
return 0;
}
static const struct dev_pm_ops bfin_rotary_pm_ops = {
.suspend = bfin_rotary_suspend,
.resume = bfin_rotary_resume,
};
#endif
static struct platform_driver bfin_rotary_device_driver = {
.probe = bfin_rotary_probe,
.remove = __devexit_p(bfin_rotary_remove),
.driver = {
.name = "bfin-rotary",
.owner = THIS_MODULE,
#ifdef CONFIG_PM
.pm = &bfin_rotary_pm_ops,
#endif
},
};
static int __init bfin_rotary_init(void)
{
return platform_driver_register(&bfin_rotary_device_driver);
}
module_init(bfin_rotary_init);
static void __exit bfin_rotary_exit(void)
{
platform_driver_unregister(&bfin_rotary_device_driver);
}
module_exit(bfin_rotary_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Michael Hennerich <hennerich@blackfin.uclinux.org>");
MODULE_DESCRIPTION("Rotary Counter driver for Blackfin Processors");
MODULE_ALIAS("platform:bfin-rotary");
| gpl-2.0 |
fergy/iphone_kernel | arch/hexagon/kernel/irq_cpu.c | 4664 | 2817 | /*
* First-level interrupt controller model for Hexagon.
*
* Copyright (c) 2010-2011, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include <linux/interrupt.h>
#include <asm/irq.h>
#include <asm/hexagon_vm.h>
static void mask_irq(struct irq_data *data)
{
__vmintop_locdis((long) data->irq);
}
static void mask_irq_num(unsigned int irq)
{
__vmintop_locdis((long) irq);
}
static void unmask_irq(struct irq_data *data)
{
__vmintop_locen((long) data->irq);
}
/* This is actually all we need for handle_fasteoi_irq */
static void eoi_irq(struct irq_data *data)
{
__vmintop_globen((long) data->irq);
}
/* Power mamangement wake call. We don't need this, however,
* if this is absent, then an -ENXIO error is returned to the
* msm_serial driver, and it fails to correctly initialize.
* This is a bug in the msm_serial driver, but, for now, we
* work around it here, by providing this bogus handler.
* XXX FIXME!!! remove this when msm_serial is fixed.
*/
static int set_wake(struct irq_data *data, unsigned int on)
{
return 0;
}
static struct irq_chip hexagon_irq_chip = {
.name = "HEXAGON",
.irq_mask = mask_irq,
.irq_unmask = unmask_irq,
.irq_set_wake = set_wake,
.irq_eoi = eoi_irq
};
/**
* The hexagon core comes with a first-level interrupt controller
* with 32 total possible interrupts. When the core is embedded
* into different systems/platforms, it is typically wrapped by
* macro cells that provide one or more second-level interrupt
* controllers that are cascaded into one or more of the first-level
* interrupts handled here. The precise wiring of these other
* irqs varies from platform to platform, and are set up & configured
* in the platform-specific files.
*
* The first-level interrupt controller is wrapped by the VM, which
* virtualizes the interrupt controller for us. It provides a very
* simple, fast & efficient API, and so the fasteoi handler is
* appropriate for this case.
*/
void __init init_IRQ(void)
{
int irq;
for (irq = 0; irq < HEXAGON_CPUINTS; irq++) {
mask_irq_num(irq);
irq_set_chip_and_handler(irq, &hexagon_irq_chip,
handle_fasteoi_irq);
}
}
| gpl-2.0 |
friedrich420/HTC-ONE-M7-AEL-Kernel-5.0.2 | kernel/irq/generic-chip.c | 7480 | 9379 | /*
* Library implementing the most common irq chip callback functions
*
* Copyright (C) 2011, Thomas Gleixner
*/
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/slab.h>
#include <linux/export.h>
#include <linux/interrupt.h>
#include <linux/kernel_stat.h>
#include <linux/syscore_ops.h>
#include "internals.h"
static LIST_HEAD(gc_list);
static DEFINE_RAW_SPINLOCK(gc_lock);
static inline struct irq_chip_regs *cur_regs(struct irq_data *d)
{
return &container_of(d->chip, struct irq_chip_type, chip)->regs;
}
/**
* irq_gc_noop - NOOP function
* @d: irq_data
*/
void irq_gc_noop(struct irq_data *d)
{
}
/**
* irq_gc_mask_disable_reg - Mask chip via disable register
* @d: irq_data
*
* Chip has separate enable/disable registers instead of a single mask
* register.
*/
void irq_gc_mask_disable_reg(struct irq_data *d)
{
struct irq_chip_generic *gc = irq_data_get_irq_chip_data(d);
u32 mask = 1 << (d->irq - gc->irq_base);
irq_gc_lock(gc);
irq_reg_writel(mask, gc->reg_base + cur_regs(d)->disable);
gc->mask_cache &= ~mask;
irq_gc_unlock(gc);
}
/**
* irq_gc_mask_set_mask_bit - Mask chip via setting bit in mask register
* @d: irq_data
*
* Chip has a single mask register. Values of this register are cached
* and protected by gc->lock
*/
void irq_gc_mask_set_bit(struct irq_data *d)
{
struct irq_chip_generic *gc = irq_data_get_irq_chip_data(d);
u32 mask = 1 << (d->irq - gc->irq_base);
irq_gc_lock(gc);
gc->mask_cache |= mask;
irq_reg_writel(gc->mask_cache, gc->reg_base + cur_regs(d)->mask);
irq_gc_unlock(gc);
}
/**
* irq_gc_mask_set_mask_bit - Mask chip via clearing bit in mask register
* @d: irq_data
*
* Chip has a single mask register. Values of this register are cached
* and protected by gc->lock
*/
void irq_gc_mask_clr_bit(struct irq_data *d)
{
struct irq_chip_generic *gc = irq_data_get_irq_chip_data(d);
u32 mask = 1 << (d->irq - gc->irq_base);
irq_gc_lock(gc);
gc->mask_cache &= ~mask;
irq_reg_writel(gc->mask_cache, gc->reg_base + cur_regs(d)->mask);
irq_gc_unlock(gc);
}
/**
* irq_gc_unmask_enable_reg - Unmask chip via enable register
* @d: irq_data
*
* Chip has separate enable/disable registers instead of a single mask
* register.
*/
void irq_gc_unmask_enable_reg(struct irq_data *d)
{
struct irq_chip_generic *gc = irq_data_get_irq_chip_data(d);
u32 mask = 1 << (d->irq - gc->irq_base);
irq_gc_lock(gc);
irq_reg_writel(mask, gc->reg_base + cur_regs(d)->enable);
gc->mask_cache |= mask;
irq_gc_unlock(gc);
}
/**
* irq_gc_ack_set_bit - Ack pending interrupt via setting bit
* @d: irq_data
*/
void irq_gc_ack_set_bit(struct irq_data *d)
{
struct irq_chip_generic *gc = irq_data_get_irq_chip_data(d);
u32 mask = 1 << (d->irq - gc->irq_base);
irq_gc_lock(gc);
irq_reg_writel(mask, gc->reg_base + cur_regs(d)->ack);
irq_gc_unlock(gc);
}
/**
* irq_gc_ack_clr_bit - Ack pending interrupt via clearing bit
* @d: irq_data
*/
void irq_gc_ack_clr_bit(struct irq_data *d)
{
struct irq_chip_generic *gc = irq_data_get_irq_chip_data(d);
u32 mask = ~(1 << (d->irq - gc->irq_base));
irq_gc_lock(gc);
irq_reg_writel(mask, gc->reg_base + cur_regs(d)->ack);
irq_gc_unlock(gc);
}
/**
* irq_gc_mask_disable_reg_and_ack- Mask and ack pending interrupt
* @d: irq_data
*/
void irq_gc_mask_disable_reg_and_ack(struct irq_data *d)
{
struct irq_chip_generic *gc = irq_data_get_irq_chip_data(d);
u32 mask = 1 << (d->irq - gc->irq_base);
irq_gc_lock(gc);
irq_reg_writel(mask, gc->reg_base + cur_regs(d)->mask);
irq_reg_writel(mask, gc->reg_base + cur_regs(d)->ack);
irq_gc_unlock(gc);
}
/**
* irq_gc_eoi - EOI interrupt
* @d: irq_data
*/
void irq_gc_eoi(struct irq_data *d)
{
struct irq_chip_generic *gc = irq_data_get_irq_chip_data(d);
u32 mask = 1 << (d->irq - gc->irq_base);
irq_gc_lock(gc);
irq_reg_writel(mask, gc->reg_base + cur_regs(d)->eoi);
irq_gc_unlock(gc);
}
/**
* irq_gc_set_wake - Set/clr wake bit for an interrupt
* @d: irq_data
*
* For chips where the wake from suspend functionality is not
* configured in a separate register and the wakeup active state is
* just stored in a bitmask.
*/
int irq_gc_set_wake(struct irq_data *d, unsigned int on)
{
struct irq_chip_generic *gc = irq_data_get_irq_chip_data(d);
u32 mask = 1 << (d->irq - gc->irq_base);
if (!(mask & gc->wake_enabled))
return -EINVAL;
irq_gc_lock(gc);
if (on)
gc->wake_active |= mask;
else
gc->wake_active &= ~mask;
irq_gc_unlock(gc);
return 0;
}
/**
* irq_alloc_generic_chip - Allocate a generic chip and initialize it
* @name: Name of the irq chip
* @num_ct: Number of irq_chip_type instances associated with this
* @irq_base: Interrupt base nr for this chip
* @reg_base: Register base address (virtual)
* @handler: Default flow handler associated with this chip
*
* Returns an initialized irq_chip_generic structure. The chip defaults
* to the primary (index 0) irq_chip_type and @handler
*/
struct irq_chip_generic *
irq_alloc_generic_chip(const char *name, int num_ct, unsigned int irq_base,
void __iomem *reg_base, irq_flow_handler_t handler)
{
struct irq_chip_generic *gc;
unsigned long sz = sizeof(*gc) + num_ct * sizeof(struct irq_chip_type);
gc = kzalloc(sz, GFP_KERNEL);
if (gc) {
raw_spin_lock_init(&gc->lock);
gc->num_ct = num_ct;
gc->irq_base = irq_base;
gc->reg_base = reg_base;
gc->chip_types->chip.name = name;
gc->chip_types->handler = handler;
}
return gc;
}
EXPORT_SYMBOL_GPL(irq_alloc_generic_chip);
/*
* Separate lockdep class for interrupt chip which can nest irq_desc
* lock.
*/
static struct lock_class_key irq_nested_lock_class;
/**
* irq_setup_generic_chip - Setup a range of interrupts with a generic chip
* @gc: Generic irq chip holding all data
* @msk: Bitmask holding the irqs to initialize relative to gc->irq_base
* @flags: Flags for initialization
* @clr: IRQ_* bits to clear
* @set: IRQ_* bits to set
*
* Set up max. 32 interrupts starting from gc->irq_base. Note, this
* initializes all interrupts to the primary irq_chip_type and its
* associated handler.
*/
void irq_setup_generic_chip(struct irq_chip_generic *gc, u32 msk,
enum irq_gc_flags flags, unsigned int clr,
unsigned int set)
{
struct irq_chip_type *ct = gc->chip_types;
unsigned int i;
raw_spin_lock(&gc_lock);
list_add_tail(&gc->list, &gc_list);
raw_spin_unlock(&gc_lock);
/* Init mask cache ? */
if (flags & IRQ_GC_INIT_MASK_CACHE)
gc->mask_cache = irq_reg_readl(gc->reg_base + ct->regs.mask);
for (i = gc->irq_base; msk; msk >>= 1, i++) {
if (!(msk & 0x01))
continue;
if (flags & IRQ_GC_INIT_NESTED_LOCK)
irq_set_lockdep_class(i, &irq_nested_lock_class);
irq_set_chip_and_handler(i, &ct->chip, ct->handler);
irq_set_chip_data(i, gc);
irq_modify_status(i, clr, set);
}
gc->irq_cnt = i - gc->irq_base;
}
EXPORT_SYMBOL_GPL(irq_setup_generic_chip);
/**
* irq_setup_alt_chip - Switch to alternative chip
* @d: irq_data for this interrupt
* @type Flow type to be initialized
*
* Only to be called from chip->irq_set_type() callbacks.
*/
int irq_setup_alt_chip(struct irq_data *d, unsigned int type)
{
struct irq_chip_generic *gc = irq_data_get_irq_chip_data(d);
struct irq_chip_type *ct = gc->chip_types;
unsigned int i;
for (i = 0; i < gc->num_ct; i++, ct++) {
if (ct->type & type) {
d->chip = &ct->chip;
irq_data_to_desc(d)->handle_irq = ct->handler;
return 0;
}
}
return -EINVAL;
}
EXPORT_SYMBOL_GPL(irq_setup_alt_chip);
/**
* irq_remove_generic_chip - Remove a chip
* @gc: Generic irq chip holding all data
* @msk: Bitmask holding the irqs to initialize relative to gc->irq_base
* @clr: IRQ_* bits to clear
* @set: IRQ_* bits to set
*
* Remove up to 32 interrupts starting from gc->irq_base.
*/
void irq_remove_generic_chip(struct irq_chip_generic *gc, u32 msk,
unsigned int clr, unsigned int set)
{
unsigned int i = gc->irq_base;
raw_spin_lock(&gc_lock);
list_del(&gc->list);
raw_spin_unlock(&gc_lock);
for (; msk; msk >>= 1, i++) {
if (!(msk & 0x01))
continue;
/* Remove handler first. That will mask the irq line */
irq_set_handler(i, NULL);
irq_set_chip(i, &no_irq_chip);
irq_set_chip_data(i, NULL);
irq_modify_status(i, clr, set);
}
}
EXPORT_SYMBOL_GPL(irq_remove_generic_chip);
#ifdef CONFIG_PM
static int irq_gc_suspend(void)
{
struct irq_chip_generic *gc;
list_for_each_entry(gc, &gc_list, list) {
struct irq_chip_type *ct = gc->chip_types;
if (ct->chip.irq_suspend)
ct->chip.irq_suspend(irq_get_irq_data(gc->irq_base));
}
return 0;
}
static void irq_gc_resume(void)
{
struct irq_chip_generic *gc;
list_for_each_entry(gc, &gc_list, list) {
struct irq_chip_type *ct = gc->chip_types;
if (ct->chip.irq_resume)
ct->chip.irq_resume(irq_get_irq_data(gc->irq_base));
}
}
#else
#define irq_gc_suspend NULL
#define irq_gc_resume NULL
#endif
static void irq_gc_shutdown(void)
{
struct irq_chip_generic *gc;
list_for_each_entry(gc, &gc_list, list) {
struct irq_chip_type *ct = gc->chip_types;
if (ct->chip.irq_pm_shutdown)
ct->chip.irq_pm_shutdown(irq_get_irq_data(gc->irq_base));
}
}
static struct syscore_ops irq_gc_syscore_ops = {
.suspend = irq_gc_suspend,
.resume = irq_gc_resume,
.shutdown = irq_gc_shutdown,
};
static int __init irq_gc_init_ops(void)
{
register_syscore_ops(&irq_gc_syscore_ops);
return 0;
}
device_initcall(irq_gc_init_ops);
| gpl-2.0 |
12thmantec/linux-3.5 | arch/arm/mach-omap2/clock3517.c | 7992 | 4288 | /*
* OMAP3517/3505-specific clock framework functions
*
* Copyright (C) 2010 Texas Instruments, Inc.
* Copyright (C) 2011 Nokia Corporation
*
* Ranjith Lohithakshan
* Paul Walmsley
*
* Parts of this code are based on code written by
* Richard Woodruff, Tony Lindgren, Tuukka Tikkanen, Karthik Dasu,
* Russell King
*
* 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.
*/
#undef DEBUG
#include <linux/kernel.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <plat/clock.h>
#include "clock.h"
#include "clock3517.h"
#include "cm2xxx_3xxx.h"
#include "cm-regbits-34xx.h"
/*
* In AM35xx IPSS, the {ICK,FCK} enable bits for modules are exported
* in the same register at a bit offset of 0x8. The EN_ACK for ICK is
* at an offset of 4 from ICK enable bit.
*/
#define AM35XX_IPSS_ICK_MASK 0xF
#define AM35XX_IPSS_ICK_EN_ACK_OFFSET 0x4
#define AM35XX_IPSS_ICK_FCK_OFFSET 0x8
#define AM35XX_IPSS_CLK_IDLEST_VAL 0
/**
* am35xx_clk_find_idlest - return clock ACK info for AM35XX IPSS
* @clk: struct clk * being enabled
* @idlest_reg: void __iomem ** to store CM_IDLEST reg address into
* @idlest_bit: pointer to a u8 to store the CM_IDLEST bit shift into
* @idlest_val: pointer to a u8 to store the CM_IDLEST indicator
*
* The interface clocks on AM35xx IPSS reflects the clock idle status
* in the enable register itsel at a bit offset of 4 from the enable
* bit. A value of 1 indicates that clock is enabled.
*/
static void am35xx_clk_find_idlest(struct clk *clk,
void __iomem **idlest_reg,
u8 *idlest_bit,
u8 *idlest_val)
{
*idlest_reg = (__force void __iomem *)(clk->enable_reg);
*idlest_bit = clk->enable_bit + AM35XX_IPSS_ICK_EN_ACK_OFFSET;
*idlest_val = AM35XX_IPSS_CLK_IDLEST_VAL;
}
/**
* am35xx_clk_find_companion - find companion clock to @clk
* @clk: struct clk * to find the companion clock of
* @other_reg: void __iomem ** to return the companion clock CM_*CLKEN va in
* @other_bit: u8 ** to return the companion clock bit shift in
*
* Some clocks don't have companion clocks. For example, modules with
* only an interface clock (such as HECC) don't have a companion
* clock. Right now, this code relies on the hardware exporting a bit
* in the correct companion register that indicates that the
* nonexistent 'companion clock' is active. Future patches will
* associate this type of code with per-module data structures to
* avoid this issue, and remove the casts. No return value.
*/
static void am35xx_clk_find_companion(struct clk *clk, void __iomem **other_reg,
u8 *other_bit)
{
*other_reg = (__force void __iomem *)(clk->enable_reg);
if (clk->enable_bit & AM35XX_IPSS_ICK_MASK)
*other_bit = clk->enable_bit + AM35XX_IPSS_ICK_FCK_OFFSET;
else
*other_bit = clk->enable_bit - AM35XX_IPSS_ICK_FCK_OFFSET;
}
const struct clkops clkops_am35xx_ipss_module_wait = {
.enable = omap2_dflt_clk_enable,
.disable = omap2_dflt_clk_disable,
.find_idlest = am35xx_clk_find_idlest,
.find_companion = am35xx_clk_find_companion,
};
/**
* am35xx_clk_ipss_find_idlest - return CM_IDLEST info for IPSS
* @clk: struct clk * being enabled
* @idlest_reg: void __iomem ** to store CM_IDLEST reg address into
* @idlest_bit: pointer to a u8 to store the CM_IDLEST bit shift into
* @idlest_val: pointer to a u8 to store the CM_IDLEST indicator
*
* The IPSS target CM_IDLEST bit is at a different shift from the
* CM_{I,F}CLKEN bit. Pass back the correct info via @idlest_reg
* and @idlest_bit. No return value.
*/
static void am35xx_clk_ipss_find_idlest(struct clk *clk,
void __iomem **idlest_reg,
u8 *idlest_bit,
u8 *idlest_val)
{
u32 r;
r = (((__force u32)clk->enable_reg & ~0xf0) | 0x20);
*idlest_reg = (__force void __iomem *)r;
*idlest_bit = AM35XX_ST_IPSS_SHIFT;
*idlest_val = OMAP34XX_CM_IDLEST_VAL;
}
const struct clkops clkops_am35xx_ipss_wait = {
.enable = omap2_dflt_clk_enable,
.disable = omap2_dflt_clk_disable,
.find_idlest = am35xx_clk_ipss_find_idlest,
.find_companion = omap2_clk_dflt_find_companion,
.allow_idle = omap2_clkt_iclk_allow_idle,
.deny_idle = omap2_clkt_iclk_deny_idle,
};
| gpl-2.0 |
pazos/linux-2.6.35.3-kobo | arch/x86/math-emu/load_store.c | 13880 | 8712 | /*---------------------------------------------------------------------------+
| load_store.c |
| |
| This file contains most of the code to interpret the FPU instructions |
| which load and store from user memory. |
| |
| Copyright (C) 1992,1993,1994,1997 |
| W. Metzenthen, 22 Parker St, Ormond, Vic 3163, |
| Australia. E-mail billm@suburbia.net |
| |
| |
+---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------+
| Note: |
| The file contains code which accesses user memory. |
| Emulator static data may change when user memory is accessed, due to |
| other processes using the emulator while swapping is in progress. |
+---------------------------------------------------------------------------*/
#include <asm/uaccess.h>
#include "fpu_system.h"
#include "exception.h"
#include "fpu_emu.h"
#include "status_w.h"
#include "control_w.h"
#define _NONE_ 0 /* st0_ptr etc not needed */
#define _REG0_ 1 /* Will be storing st(0) */
#define _PUSH_ 3 /* Need to check for space to push onto stack */
#define _null_ 4 /* Function illegal or not implemented */
#define pop_0() { FPU_settag0(TAG_Empty); top++; }
static u_char const type_table[32] = {
_PUSH_, _PUSH_, _PUSH_, _PUSH_,
_null_, _null_, _null_, _null_,
_REG0_, _REG0_, _REG0_, _REG0_,
_REG0_, _REG0_, _REG0_, _REG0_,
_NONE_, _null_, _NONE_, _PUSH_,
_NONE_, _PUSH_, _null_, _PUSH_,
_NONE_, _null_, _NONE_, _REG0_,
_NONE_, _REG0_, _NONE_, _REG0_
};
u_char const data_sizes_16[32] = {
4, 4, 8, 2, 0, 0, 0, 0,
4, 4, 8, 2, 4, 4, 8, 2,
14, 0, 94, 10, 2, 10, 0, 8,
14, 0, 94, 10, 2, 10, 2, 8
};
static u_char const data_sizes_32[32] = {
4, 4, 8, 2, 0, 0, 0, 0,
4, 4, 8, 2, 4, 4, 8, 2,
28, 0, 108, 10, 2, 10, 0, 8,
28, 0, 108, 10, 2, 10, 2, 8
};
int FPU_load_store(u_char type, fpu_addr_modes addr_modes,
void __user * data_address)
{
FPU_REG loaded_data;
FPU_REG *st0_ptr;
u_char st0_tag = TAG_Empty; /* This is just to stop a gcc warning. */
u_char loaded_tag;
st0_ptr = NULL; /* Initialized just to stop compiler warnings. */
if (addr_modes.default_mode & PROTECTED) {
if (addr_modes.default_mode == SEG32) {
if (access_limit < data_sizes_32[type])
math_abort(FPU_info, SIGSEGV);
} else if (addr_modes.default_mode == PM16) {
if (access_limit < data_sizes_16[type])
math_abort(FPU_info, SIGSEGV);
}
#ifdef PARANOID
else
EXCEPTION(EX_INTERNAL | 0x140);
#endif /* PARANOID */
}
switch (type_table[type]) {
case _NONE_:
break;
case _REG0_:
st0_ptr = &st(0); /* Some of these instructions pop after
storing */
st0_tag = FPU_gettag0();
break;
case _PUSH_:
{
if (FPU_gettagi(-1) != TAG_Empty) {
FPU_stack_overflow();
return 0;
}
top--;
st0_ptr = &st(0);
}
break;
case _null_:
FPU_illegal();
return 0;
#ifdef PARANOID
default:
EXCEPTION(EX_INTERNAL | 0x141);
return 0;
#endif /* PARANOID */
}
switch (type) {
case 000: /* fld m32real */
clear_C1();
loaded_tag =
FPU_load_single((float __user *)data_address, &loaded_data);
if ((loaded_tag == TAG_Special)
&& isNaN(&loaded_data)
&& (real_1op_NaN(&loaded_data) < 0)) {
top++;
break;
}
FPU_copy_to_reg0(&loaded_data, loaded_tag);
break;
case 001: /* fild m32int */
clear_C1();
loaded_tag =
FPU_load_int32((long __user *)data_address, &loaded_data);
FPU_copy_to_reg0(&loaded_data, loaded_tag);
break;
case 002: /* fld m64real */
clear_C1();
loaded_tag =
FPU_load_double((double __user *)data_address,
&loaded_data);
if ((loaded_tag == TAG_Special)
&& isNaN(&loaded_data)
&& (real_1op_NaN(&loaded_data) < 0)) {
top++;
break;
}
FPU_copy_to_reg0(&loaded_data, loaded_tag);
break;
case 003: /* fild m16int */
clear_C1();
loaded_tag =
FPU_load_int16((short __user *)data_address, &loaded_data);
FPU_copy_to_reg0(&loaded_data, loaded_tag);
break;
case 010: /* fst m32real */
clear_C1();
FPU_store_single(st0_ptr, st0_tag,
(float __user *)data_address);
break;
case 011: /* fist m32int */
clear_C1();
FPU_store_int32(st0_ptr, st0_tag, (long __user *)data_address);
break;
case 012: /* fst m64real */
clear_C1();
FPU_store_double(st0_ptr, st0_tag,
(double __user *)data_address);
break;
case 013: /* fist m16int */
clear_C1();
FPU_store_int16(st0_ptr, st0_tag, (short __user *)data_address);
break;
case 014: /* fstp m32real */
clear_C1();
if (FPU_store_single
(st0_ptr, st0_tag, (float __user *)data_address))
pop_0(); /* pop only if the number was actually stored
(see the 80486 manual p16-28) */
break;
case 015: /* fistp m32int */
clear_C1();
if (FPU_store_int32
(st0_ptr, st0_tag, (long __user *)data_address))
pop_0(); /* pop only if the number was actually stored
(see the 80486 manual p16-28) */
break;
case 016: /* fstp m64real */
clear_C1();
if (FPU_store_double
(st0_ptr, st0_tag, (double __user *)data_address))
pop_0(); /* pop only if the number was actually stored
(see the 80486 manual p16-28) */
break;
case 017: /* fistp m16int */
clear_C1();
if (FPU_store_int16
(st0_ptr, st0_tag, (short __user *)data_address))
pop_0(); /* pop only if the number was actually stored
(see the 80486 manual p16-28) */
break;
case 020: /* fldenv m14/28byte */
fldenv(addr_modes, (u_char __user *) data_address);
/* Ensure that the values just loaded are not changed by
fix-up operations. */
return 1;
case 022: /* frstor m94/108byte */
frstor(addr_modes, (u_char __user *) data_address);
/* Ensure that the values just loaded are not changed by
fix-up operations. */
return 1;
case 023: /* fbld m80dec */
clear_C1();
loaded_tag = FPU_load_bcd((u_char __user *) data_address);
FPU_settag0(loaded_tag);
break;
case 024: /* fldcw */
RE_ENTRANT_CHECK_OFF;
FPU_access_ok(VERIFY_READ, data_address, 2);
FPU_get_user(control_word,
(unsigned short __user *)data_address);
RE_ENTRANT_CHECK_ON;
if (partial_status & ~control_word & CW_Exceptions)
partial_status |= (SW_Summary | SW_Backward);
else
partial_status &= ~(SW_Summary | SW_Backward);
#ifdef PECULIAR_486
control_word |= 0x40; /* An 80486 appears to always set this bit */
#endif /* PECULIAR_486 */
return 1;
case 025: /* fld m80real */
clear_C1();
loaded_tag =
FPU_load_extended((long double __user *)data_address, 0);
FPU_settag0(loaded_tag);
break;
case 027: /* fild m64int */
clear_C1();
loaded_tag = FPU_load_int64((long long __user *)data_address);
if (loaded_tag == TAG_Error)
return 0;
FPU_settag0(loaded_tag);
break;
case 030: /* fstenv m14/28byte */
fstenv(addr_modes, (u_char __user *) data_address);
return 1;
case 032: /* fsave */
fsave(addr_modes, (u_char __user *) data_address);
return 1;
case 033: /* fbstp m80dec */
clear_C1();
if (FPU_store_bcd
(st0_ptr, st0_tag, (u_char __user *) data_address))
pop_0(); /* pop only if the number was actually stored
(see the 80486 manual p16-28) */
break;
case 034: /* fstcw m16int */
RE_ENTRANT_CHECK_OFF;
FPU_access_ok(VERIFY_WRITE, data_address, 2);
FPU_put_user(control_word,
(unsigned short __user *)data_address);
RE_ENTRANT_CHECK_ON;
return 1;
case 035: /* fstp m80real */
clear_C1();
if (FPU_store_extended
(st0_ptr, st0_tag, (long double __user *)data_address))
pop_0(); /* pop only if the number was actually stored
(see the 80486 manual p16-28) */
break;
case 036: /* fstsw m2byte */
RE_ENTRANT_CHECK_OFF;
FPU_access_ok(VERIFY_WRITE, data_address, 2);
FPU_put_user(status_word(),
(unsigned short __user *)data_address);
RE_ENTRANT_CHECK_ON;
return 1;
case 037: /* fistp m64int */
clear_C1();
if (FPU_store_int64
(st0_ptr, st0_tag, (long long __user *)data_address))
pop_0(); /* pop only if the number was actually stored
(see the 80486 manual p16-28) */
break;
}
return 0;
}
| gpl-2.0 |
dhkim1027/iamroot-linux-arm10c | arch/ia64/sn/kernel/sn2/timer_interrupt.c | 14136 | 2033 | /*
*
*
* Copyright (c) 2005, 2006 Silicon Graphics, Inc. All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, USA.
*
* For further information regarding this notice, see:
*
* http://oss.sgi.com/projects/GenInfo/NoticeExplan
*/
#include <linux/interrupt.h>
#include <asm/sn/pda.h>
#include <asm/sn/leds.h>
extern void sn_lb_int_war_check(void);
extern irqreturn_t timer_interrupt(int irq, void *dev_id, struct pt_regs *regs);
#define SN_LB_INT_WAR_INTERVAL 100
void sn_timer_interrupt(int irq, void *dev_id)
{
/* LED blinking */
if (!pda->hb_count--) {
pda->hb_count = HZ / 2;
set_led_bits(pda->hb_state ^=
LED_CPU_HEARTBEAT, LED_CPU_HEARTBEAT);
}
if (is_shub1()) {
if (enable_shub_wars_1_1()) {
/* Bugfix code for SHUB 1.1 */
if (pda->pio_shub_war_cam_addr)
*pda->pio_shub_war_cam_addr = 0x8000000000000010UL;
}
if (pda->sn_lb_int_war_ticks == 0)
sn_lb_int_war_check();
pda->sn_lb_int_war_ticks++;
if (pda->sn_lb_int_war_ticks >= SN_LB_INT_WAR_INTERVAL)
pda->sn_lb_int_war_ticks = 0;
}
}
| gpl-2.0 |
matteocrippa/dsl-n55u-bender | release/src-rt/linux/linux-2.6/net/irda/irnet/irnet_ppp.c | 57 | 32379 | /*
* IrNET protocol module : Synchronous PPP over an IrDA socket.
*
* Jean II - HPL `00 - <jt@hpl.hp.com>
*
* This file implement the PPP interface and /dev/irnet character device.
* The PPP interface hook to the ppp_generic module, handle all our
* relationship to the PPP code in the kernel (and by extension to pppd),
* and exchange PPP frames with this module (send/receive).
* The /dev/irnet device is used primarily for 2 functions :
* 1) as a stub for pppd (the ppp daemon), so that we can appropriately
* generate PPP sessions (we pretend we are a tty).
* 2) as a control channel (write commands, read events)
*/
#include "irnet_ppp.h" /* Private header */
/* Please put other headers in irnet.h - Thanks */
/* Generic PPP callbacks (to call us) */
static struct ppp_channel_ops irnet_ppp_ops = {
.start_xmit = ppp_irnet_send,
.ioctl = ppp_irnet_ioctl
};
/************************* CONTROL CHANNEL *************************/
/*
* When a pppd instance is not active on /dev/irnet, it acts as a control
* channel.
* Writing allow to set up the IrDA destination of the IrNET channel,
* and any application may be read events happening in IrNET...
*/
/*------------------------------------------------------------------*/
/*
* Write is used to send a command to configure a IrNET channel
* before it is open by pppd. The syntax is : "command argument"
* Currently there is only two defined commands :
* o name : set the requested IrDA nickname of the IrNET peer.
* o addr : set the requested IrDA address of the IrNET peer.
* Note : the code is crude, but effective...
*/
static inline ssize_t
irnet_ctrl_write(irnet_socket * ap,
const char __user *buf,
size_t count)
{
char command[IRNET_MAX_COMMAND];
char * start; /* Current command being processed */
char * next; /* Next command to process */
int length; /* Length of current command */
DENTER(CTRL_TRACE, "(ap=0x%p, count=%Zd)\n", ap, count);
/* Check for overflow... */
DABORT(count >= IRNET_MAX_COMMAND, -ENOMEM,
CTRL_ERROR, "Too much data !!!\n");
/* Get the data in the driver */
if(copy_from_user(command, buf, count))
{
DERROR(CTRL_ERROR, "Invalid user space pointer.\n");
return -EFAULT;
}
/* Safe terminate the string */
command[count] = '\0';
DEBUG(CTRL_INFO, "Command line received is ``%s'' (%Zd).\n",
command, count);
/* Check every commands in the command line */
next = command;
while(next != NULL)
{
/* Look at the next command */
start = next;
/* Scrap whitespaces before the command */
while(isspace(*start))
start++;
/* ',' is our command separator */
next = strchr(start, ',');
if(next)
{
*next = '\0'; /* Terminate command */
length = next - start; /* Length */
next++; /* Skip the '\0' */
}
else
length = strlen(start);
DEBUG(CTRL_INFO, "Found command ``%s'' (%d).\n", start, length);
/* Check if we recognised one of the known command
* We can't use "switch" with strings, so hack with "continue" */
/* First command : name -> Requested IrDA nickname */
if(!strncmp(start, "name", 4))
{
/* Copy the name only if is included and not "any" */
if((length > 5) && (strcmp(start + 5, "any")))
{
/* Strip out trailing whitespaces */
while(isspace(start[length - 1]))
length--;
/* Copy the name for later reuse */
memcpy(ap->rname, start + 5, length - 5);
ap->rname[length - 5] = '\0';
}
else
ap->rname[0] = '\0';
DEBUG(CTRL_INFO, "Got rname = ``%s''\n", ap->rname);
/* Restart the loop */
continue;
}
/* Second command : addr, daddr -> Requested IrDA destination address
* Also process : saddr -> Requested IrDA source address */
if((!strncmp(start, "addr", 4)) ||
(!strncmp(start, "daddr", 5)) ||
(!strncmp(start, "saddr", 5)))
{
__u32 addr = DEV_ADDR_ANY;
/* Copy the address only if is included and not "any" */
if((length > 5) && (strcmp(start + 5, "any")))
{
char * begp = start + 5;
char * endp;
/* Scrap whitespaces before the command */
while(isspace(*begp))
begp++;
/* Convert argument to a number (last arg is the base) */
addr = simple_strtoul(begp, &endp, 16);
/* Has it worked ? (endp should be start + length) */
DABORT(endp <= (start + 5), -EINVAL,
CTRL_ERROR, "Invalid address.\n");
}
/* Which type of address ? */
if(start[0] == 's')
{
/* Save it */
ap->rsaddr = addr;
DEBUG(CTRL_INFO, "Got rsaddr = %08x\n", ap->rsaddr);
}
else
{
/* Save it */
ap->rdaddr = addr;
DEBUG(CTRL_INFO, "Got rdaddr = %08x\n", ap->rdaddr);
}
/* Restart the loop */
continue;
}
/* Other possible command : connect N (number of retries) */
/* No command matched -> Failed... */
DABORT(1, -EINVAL, CTRL_ERROR, "Not a recognised IrNET command.\n");
}
/* Success : we have parsed all commands successfully */
return(count);
}
#ifdef INITIAL_DISCOVERY
/*------------------------------------------------------------------*/
/*
* Function irnet_get_discovery_log (self)
*
* Query the content on the discovery log if not done
*
* This function query the current content of the discovery log
* at the startup of the event channel and save it in the internal struct.
*/
static void
irnet_get_discovery_log(irnet_socket * ap)
{
__u16 mask = irlmp_service_to_hint(S_LAN);
/* Ask IrLMP for the current discovery log */
ap->discoveries = irlmp_get_discoveries(&ap->disco_number, mask,
DISCOVERY_DEFAULT_SLOTS);
/* Check if the we got some results */
if(ap->discoveries == NULL)
ap->disco_number = -1;
DEBUG(CTRL_INFO, "Got the log (0x%p), size is %d\n",
ap->discoveries, ap->disco_number);
}
/*------------------------------------------------------------------*/
/*
* Function irnet_read_discovery_log (self, event)
*
* Read the content on the discovery log
*
* This function dump the current content of the discovery log
* at the startup of the event channel.
* Return 1 if wrote an event on the control channel...
*
* State of the ap->disco_XXX variables :
* Socket creation : discoveries = NULL ; disco_index = 0 ; disco_number = 0
* While reading : discoveries = ptr ; disco_index = X ; disco_number = Y
* After reading : discoveries = NULL ; disco_index = Y ; disco_number = -1
*/
static inline int
irnet_read_discovery_log(irnet_socket * ap,
char * event)
{
int done_event = 0;
DENTER(CTRL_TRACE, "(ap=0x%p, event=0x%p)\n",
ap, event);
/* Test if we have some work to do or we have already finished */
if(ap->disco_number == -1)
{
DEBUG(CTRL_INFO, "Already done\n");
return 0;
}
/* Test if it's the first time and therefore we need to get the log */
if(ap->discoveries == NULL)
irnet_get_discovery_log(ap);
/* Check if we have more item to dump */
if(ap->disco_index < ap->disco_number)
{
/* Write an event */
sprintf(event, "Found %08x (%s) behind %08x {hints %02X-%02X}\n",
ap->discoveries[ap->disco_index].daddr,
ap->discoveries[ap->disco_index].info,
ap->discoveries[ap->disco_index].saddr,
ap->discoveries[ap->disco_index].hints[0],
ap->discoveries[ap->disco_index].hints[1]);
DEBUG(CTRL_INFO, "Writing discovery %d : %s\n",
ap->disco_index, ap->discoveries[ap->disco_index].info);
/* We have an event */
done_event = 1;
/* Next discovery */
ap->disco_index++;
}
/* Check if we have done the last item */
if(ap->disco_index >= ap->disco_number)
{
/* No more items : remove the log and signal termination */
DEBUG(CTRL_INFO, "Cleaning up log (0x%p)\n",
ap->discoveries);
if(ap->discoveries != NULL)
{
/* Cleanup our copy of the discovery log */
kfree(ap->discoveries);
ap->discoveries = NULL;
}
ap->disco_number = -1;
}
return done_event;
}
#endif /* INITIAL_DISCOVERY */
/*------------------------------------------------------------------*/
/*
* Read is used to get IrNET events
*/
static inline ssize_t
irnet_ctrl_read(irnet_socket * ap,
struct file * file,
char __user * buf,
size_t count)
{
DECLARE_WAITQUEUE(wait, current);
char event[64]; /* Max event is 61 char */
ssize_t ret = 0;
DENTER(CTRL_TRACE, "(ap=0x%p, count=%Zd)\n", ap, count);
/* Check if we can write an event out in one go */
DABORT(count < sizeof(event), -EOVERFLOW, CTRL_ERROR, "Buffer to small.\n");
#ifdef INITIAL_DISCOVERY
/* Check if we have read the log */
if(irnet_read_discovery_log(ap, event))
{
/* We have an event !!! Copy it to the user */
if(copy_to_user(buf, event, strlen(event)))
{
DERROR(CTRL_ERROR, "Invalid user space pointer.\n");
return -EFAULT;
}
DEXIT(CTRL_TRACE, "\n");
return(strlen(event));
}
#endif /* INITIAL_DISCOVERY */
/* Put ourselves on the wait queue to be woken up */
add_wait_queue(&irnet_events.rwait, &wait);
current->state = TASK_INTERRUPTIBLE;
for(;;)
{
/* If there is unread events */
ret = 0;
if(ap->event_index != irnet_events.index)
break;
ret = -EAGAIN;
if(file->f_flags & O_NONBLOCK)
break;
ret = -ERESTARTSYS;
if(signal_pending(current))
break;
/* Yield and wait to be woken up */
schedule();
}
current->state = TASK_RUNNING;
remove_wait_queue(&irnet_events.rwait, &wait);
/* Did we got it ? */
if(ret != 0)
{
/* No, return the error code */
DEXIT(CTRL_TRACE, " - ret %Zd\n", ret);
return ret;
}
/* Which event is it ? */
switch(irnet_events.log[ap->event_index].event)
{
case IRNET_DISCOVER:
sprintf(event, "Discovered %08x (%s) behind %08x {hints %02X-%02X}\n",
irnet_events.log[ap->event_index].daddr,
irnet_events.log[ap->event_index].name,
irnet_events.log[ap->event_index].saddr,
irnet_events.log[ap->event_index].hints.byte[0],
irnet_events.log[ap->event_index].hints.byte[1]);
break;
case IRNET_EXPIRE:
sprintf(event, "Expired %08x (%s) behind %08x {hints %02X-%02X}\n",
irnet_events.log[ap->event_index].daddr,
irnet_events.log[ap->event_index].name,
irnet_events.log[ap->event_index].saddr,
irnet_events.log[ap->event_index].hints.byte[0],
irnet_events.log[ap->event_index].hints.byte[1]);
break;
case IRNET_CONNECT_TO:
sprintf(event, "Connected to %08x (%s) on ppp%d\n",
irnet_events.log[ap->event_index].daddr,
irnet_events.log[ap->event_index].name,
irnet_events.log[ap->event_index].unit);
break;
case IRNET_CONNECT_FROM:
sprintf(event, "Connection from %08x (%s) on ppp%d\n",
irnet_events.log[ap->event_index].daddr,
irnet_events.log[ap->event_index].name,
irnet_events.log[ap->event_index].unit);
break;
case IRNET_REQUEST_FROM:
sprintf(event, "Request from %08x (%s) behind %08x\n",
irnet_events.log[ap->event_index].daddr,
irnet_events.log[ap->event_index].name,
irnet_events.log[ap->event_index].saddr);
break;
case IRNET_NOANSWER_FROM:
sprintf(event, "No-answer from %08x (%s) on ppp%d\n",
irnet_events.log[ap->event_index].daddr,
irnet_events.log[ap->event_index].name,
irnet_events.log[ap->event_index].unit);
break;
case IRNET_BLOCKED_LINK:
sprintf(event, "Blocked link with %08x (%s) on ppp%d\n",
irnet_events.log[ap->event_index].daddr,
irnet_events.log[ap->event_index].name,
irnet_events.log[ap->event_index].unit);
break;
case IRNET_DISCONNECT_FROM:
sprintf(event, "Disconnection from %08x (%s) on ppp%d\n",
irnet_events.log[ap->event_index].daddr,
irnet_events.log[ap->event_index].name,
irnet_events.log[ap->event_index].unit);
break;
case IRNET_DISCONNECT_TO:
sprintf(event, "Disconnected to %08x (%s)\n",
irnet_events.log[ap->event_index].daddr,
irnet_events.log[ap->event_index].name);
break;
default:
sprintf(event, "Bug\n");
}
/* Increment our event index */
ap->event_index = (ap->event_index + 1) % IRNET_MAX_EVENTS;
DEBUG(CTRL_INFO, "Event is :%s", event);
/* Copy it to the user */
if(copy_to_user(buf, event, strlen(event)))
{
DERROR(CTRL_ERROR, "Invalid user space pointer.\n");
return -EFAULT;
}
DEXIT(CTRL_TRACE, "\n");
return(strlen(event));
}
/*------------------------------------------------------------------*/
/*
* Poll : called when someone do a select on /dev/irnet.
* Just check if there are new events...
*/
static inline unsigned int
irnet_ctrl_poll(irnet_socket * ap,
struct file * file,
poll_table * wait)
{
unsigned int mask;
DENTER(CTRL_TRACE, "(ap=0x%p)\n", ap);
poll_wait(file, &irnet_events.rwait, wait);
mask = POLLOUT | POLLWRNORM;
/* If there is unread events */
if(ap->event_index != irnet_events.index)
mask |= POLLIN | POLLRDNORM;
#ifdef INITIAL_DISCOVERY
if(ap->disco_number != -1)
{
/* Test if it's the first time and therefore we need to get the log */
if(ap->discoveries == NULL)
irnet_get_discovery_log(ap);
/* Recheck */
if(ap->disco_number != -1)
mask |= POLLIN | POLLRDNORM;
}
#endif /* INITIAL_DISCOVERY */
DEXIT(CTRL_TRACE, " - mask=0x%X\n", mask);
return mask;
}
/*********************** FILESYSTEM CALLBACKS ***********************/
/*
* Implement the usual open, read, write functions that will be called
* by the file system when some action is performed on /dev/irnet.
* Most of those actions will in fact be performed by "pppd" or
* the control channel, we just act as a redirector...
*/
/*------------------------------------------------------------------*/
/*
* Open : when somebody open /dev/irnet
* We basically create a new instance of irnet and initialise it.
*/
static int
dev_irnet_open(struct inode * inode,
struct file * file)
{
struct irnet_socket * ap;
int err;
DENTER(FS_TRACE, "(file=0x%p)\n", file);
#ifdef SECURE_DEVIRNET
/* This could (should?) be enforced by the permissions on /dev/irnet. */
if(!capable(CAP_NET_ADMIN))
return -EPERM;
#endif /* SECURE_DEVIRNET */
/* Allocate a private structure for this IrNET instance */
ap = kzalloc(sizeof(*ap), GFP_KERNEL);
DABORT(ap == NULL, -ENOMEM, FS_ERROR, "Can't allocate struct irnet...\n");
/* initialize the irnet structure */
ap->file = file;
/* PPP channel setup */
ap->ppp_open = 0;
ap->chan.private = ap;
ap->chan.ops = &irnet_ppp_ops;
ap->chan.mtu = (2048 - TTP_MAX_HEADER - 2 - PPP_HDRLEN);
ap->chan.hdrlen = 2 + TTP_MAX_HEADER; /* for A/C + Max IrDA hdr */
/* PPP parameters */
ap->mru = (2048 - TTP_MAX_HEADER - 2 - PPP_HDRLEN);
ap->xaccm[0] = ~0U;
ap->xaccm[3] = 0x60000000U;
ap->raccm = ~0U;
/* Setup the IrDA part... */
err = irda_irnet_create(ap);
if(err)
{
DERROR(FS_ERROR, "Can't setup IrDA link...\n");
kfree(ap);
return err;
}
/* For the control channel */
ap->event_index = irnet_events.index; /* Cancel all past events */
/* Put our stuff where we will be able to find it later */
file->private_data = ap;
DEXIT(FS_TRACE, " - ap=0x%p\n", ap);
return 0;
}
/*------------------------------------------------------------------*/
/*
* Close : when somebody close /dev/irnet
* Destroy the instance of /dev/irnet
*/
static int
dev_irnet_close(struct inode * inode,
struct file * file)
{
irnet_socket * ap = (struct irnet_socket *) file->private_data;
DENTER(FS_TRACE, "(file=0x%p, ap=0x%p)\n",
file, ap);
DABORT(ap == NULL, 0, FS_ERROR, "ap is NULL !!!\n");
/* Detach ourselves */
file->private_data = NULL;
/* Close IrDA stuff */
irda_irnet_destroy(ap);
/* Disconnect from the generic PPP layer if not already done */
if(ap->ppp_open)
{
DERROR(FS_ERROR, "Channel still registered - deregistering !\n");
ap->ppp_open = 0;
ppp_unregister_channel(&ap->chan);
}
kfree(ap);
DEXIT(FS_TRACE, "\n");
return 0;
}
/*------------------------------------------------------------------*/
/*
* Write does nothing.
* (we receive packet from ppp_generic through ppp_irnet_send())
*/
static ssize_t
dev_irnet_write(struct file * file,
const char __user *buf,
size_t count,
loff_t * ppos)
{
irnet_socket * ap = (struct irnet_socket *) file->private_data;
DPASS(FS_TRACE, "(file=0x%p, ap=0x%p, count=%Zd)\n",
file, ap, count);
DABORT(ap == NULL, -ENXIO, FS_ERROR, "ap is NULL !!!\n");
/* If we are connected to ppp_generic, let it handle the job */
if(ap->ppp_open)
return -EAGAIN;
else
return irnet_ctrl_write(ap, buf, count);
}
/*------------------------------------------------------------------*/
/*
* Read doesn't do much either.
* (pppd poll us, but ultimately reads through /dev/ppp)
*/
static ssize_t
dev_irnet_read(struct file * file,
char __user * buf,
size_t count,
loff_t * ppos)
{
irnet_socket * ap = (struct irnet_socket *) file->private_data;
DPASS(FS_TRACE, "(file=0x%p, ap=0x%p, count=%Zd)\n",
file, ap, count);
DABORT(ap == NULL, -ENXIO, FS_ERROR, "ap is NULL !!!\n");
/* If we are connected to ppp_generic, let it handle the job */
if(ap->ppp_open)
return -EAGAIN;
else
return irnet_ctrl_read(ap, file, buf, count);
}
/*------------------------------------------------------------------*/
/*
* Poll : called when someone do a select on /dev/irnet
*/
static unsigned int
dev_irnet_poll(struct file * file,
poll_table * wait)
{
irnet_socket * ap = (struct irnet_socket *) file->private_data;
unsigned int mask;
DENTER(FS_TRACE, "(file=0x%p, ap=0x%p)\n",
file, ap);
mask = POLLOUT | POLLWRNORM;
DABORT(ap == NULL, mask, FS_ERROR, "ap is NULL !!!\n");
/* If we are connected to ppp_generic, let it handle the job */
if(!ap->ppp_open)
mask |= irnet_ctrl_poll(ap, file, wait);
DEXIT(FS_TRACE, " - mask=0x%X\n", mask);
return(mask);
}
/*------------------------------------------------------------------*/
/*
* IOCtl : Called when someone does some ioctls on /dev/irnet
* This is the way pppd configure us and control us while the PPP
* instance is active.
*/
static int
dev_irnet_ioctl(struct inode * inode,
struct file * file,
unsigned int cmd,
unsigned long arg)
{
irnet_socket * ap = (struct irnet_socket *) file->private_data;
int err;
int val;
void __user *argp = (void __user *)arg;
DENTER(FS_TRACE, "(file=0x%p, ap=0x%p, cmd=0x%X)\n",
file, ap, cmd);
/* Basic checks... */
DASSERT(ap != NULL, -ENXIO, PPP_ERROR, "ap is NULL...\n");
#ifdef SECURE_DEVIRNET
if(!capable(CAP_NET_ADMIN))
return -EPERM;
#endif /* SECURE_DEVIRNET */
err = -EFAULT;
switch(cmd)
{
/* Set discipline (should be N_SYNC_PPP or N_TTY) */
case TIOCSETD:
if(get_user(val, (int __user *)argp))
break;
if((val == N_SYNC_PPP) || (val == N_PPP))
{
DEBUG(FS_INFO, "Entering PPP discipline.\n");
/* PPP channel setup (ap->chan in configued in dev_irnet_open())*/
err = ppp_register_channel(&ap->chan);
if(err == 0)
{
/* Our ppp side is active */
ap->ppp_open = 1;
DEBUG(FS_INFO, "Trying to establish a connection.\n");
/* Setup the IrDA link now - may fail... */
irda_irnet_connect(ap);
}
else
DERROR(FS_ERROR, "Can't setup PPP channel...\n");
}
else
{
/* In theory, should be N_TTY */
DEBUG(FS_INFO, "Exiting PPP discipline.\n");
/* Disconnect from the generic PPP layer */
if(ap->ppp_open)
{
ap->ppp_open = 0;
ppp_unregister_channel(&ap->chan);
}
else
DERROR(FS_ERROR, "Channel not registered !\n");
err = 0;
}
break;
/* Query PPP channel and unit number */
case PPPIOCGCHAN:
if(!ap->ppp_open)
break;
if(put_user(ppp_channel_index(&ap->chan), (int __user *)argp))
break;
DEBUG(FS_INFO, "Query channel.\n");
err = 0;
break;
case PPPIOCGUNIT:
if(!ap->ppp_open)
break;
if(put_user(ppp_unit_number(&ap->chan), (int __user *)argp))
break;
DEBUG(FS_INFO, "Query unit number.\n");
err = 0;
break;
/* All these ioctls can be passed both directly and from ppp_generic,
* so we just deal with them in one place...
*/
case PPPIOCGFLAGS:
case PPPIOCSFLAGS:
case PPPIOCGASYNCMAP:
case PPPIOCSASYNCMAP:
case PPPIOCGRASYNCMAP:
case PPPIOCSRASYNCMAP:
case PPPIOCGXASYNCMAP:
case PPPIOCSXASYNCMAP:
case PPPIOCGMRU:
case PPPIOCSMRU:
DEBUG(FS_INFO, "Standard PPP ioctl.\n");
if(!capable(CAP_NET_ADMIN))
err = -EPERM;
else
err = ppp_irnet_ioctl(&ap->chan, cmd, arg);
break;
/* TTY IOCTLs : Pretend that we are a tty, to keep pppd happy */
/* Get termios */
case TCGETS:
DEBUG(FS_INFO, "Get termios.\n");
if(kernel_termios_to_user_termios((struct termios __user *)argp, &ap->termios))
break;
err = 0;
break;
/* Set termios */
case TCSETSF:
DEBUG(FS_INFO, "Set termios.\n");
if(user_termios_to_kernel_termios(&ap->termios, (struct termios __user *)argp))
break;
err = 0;
break;
/* Set DTR/RTS */
case TIOCMBIS:
case TIOCMBIC:
/* Set exclusive/non-exclusive mode */
case TIOCEXCL:
case TIOCNXCL:
DEBUG(FS_INFO, "TTY compatibility.\n");
err = 0;
break;
case TCGETA:
DEBUG(FS_INFO, "TCGETA\n");
break;
case TCFLSH:
DEBUG(FS_INFO, "TCFLSH\n");
/* Note : this will flush buffers in PPP, so it *must* be done
* We should also worry that we don't accept junk here and that
* we get rid of our own buffers */
#ifdef FLUSH_TO_PPP
ppp_output_wakeup(&ap->chan);
#endif /* FLUSH_TO_PPP */
err = 0;
break;
case FIONREAD:
DEBUG(FS_INFO, "FIONREAD\n");
val = 0;
if(put_user(val, (int __user *)argp))
break;
err = 0;
break;
default:
DERROR(FS_ERROR, "Unsupported ioctl (0x%X)\n", cmd);
err = -ENOIOCTLCMD;
}
DEXIT(FS_TRACE, " - err = 0x%X\n", err);
return err;
}
/************************** PPP CALLBACKS **************************/
/*
* This are the functions that the generic PPP driver in the kernel
* will call to communicate to us.
*/
/*------------------------------------------------------------------*/
/*
* Prepare the ppp frame for transmission over the IrDA socket.
* We make sure that the header space is enough, and we change ppp header
* according to flags passed by pppd.
* This is not a callback, but just a helper function used in ppp_irnet_send()
*/
static inline struct sk_buff *
irnet_prepare_skb(irnet_socket * ap,
struct sk_buff * skb)
{
unsigned char * data;
int proto; /* PPP protocol */
int islcp; /* Protocol == LCP */
int needaddr; /* Need PPP address */
DENTER(PPP_TRACE, "(ap=0x%p, skb=0x%p)\n",
ap, skb);
/* Extract PPP protocol from the frame */
data = skb->data;
proto = (data[0] << 8) + data[1];
/* LCP packets with codes between 1 (configure-request)
* and 7 (code-reject) must be sent as though no options
* have been negotiated. */
islcp = (proto == PPP_LCP) && (1 <= data[2]) && (data[2] <= 7);
/* compress protocol field if option enabled */
if((data[0] == 0) && (ap->flags & SC_COMP_PROT) && (!islcp))
skb_pull(skb,1);
/* Check if we need address/control fields */
needaddr = 2*((ap->flags & SC_COMP_AC) == 0 || islcp);
/* Is the skb headroom large enough to contain all IrDA-headers? */
if((skb_headroom(skb) < (ap->max_header_size + needaddr)) ||
(skb_shared(skb)))
{
struct sk_buff * new_skb;
DEBUG(PPP_INFO, "Reallocating skb\n");
/* Create a new skb */
new_skb = skb_realloc_headroom(skb, ap->max_header_size + needaddr);
/* We have to free the original skb anyway */
dev_kfree_skb(skb);
/* Did the realloc succeed ? */
DABORT(new_skb == NULL, NULL, PPP_ERROR, "Could not realloc skb\n");
/* Use the new skb instead */
skb = new_skb;
}
/* prepend address/control fields if necessary */
if(needaddr)
{
skb_push(skb, 2);
skb->data[0] = PPP_ALLSTATIONS;
skb->data[1] = PPP_UI;
}
DEXIT(PPP_TRACE, "\n");
return skb;
}
/*------------------------------------------------------------------*/
/*
* Send a packet to the peer over the IrTTP connection.
* Returns 1 iff the packet was accepted.
* Returns 0 iff packet was not consumed.
* If the packet was not accepted, we will call ppp_output_wakeup
* at some later time to reactivate flow control in ppp_generic.
*/
static int
ppp_irnet_send(struct ppp_channel * chan,
struct sk_buff * skb)
{
irnet_socket * self = (struct irnet_socket *) chan->private;
int ret;
DENTER(PPP_TRACE, "(channel=0x%p, ap/self=0x%p)\n",
chan, self);
/* Check if things are somewhat valid... */
DASSERT(self != NULL, 0, PPP_ERROR, "Self is NULL !!!\n");
/* Check if we are connected */
if(!(test_bit(0, &self->ttp_open)))
{
#ifdef CONNECT_IN_SEND
/* Let's try to connect one more time... */
/* Note : we won't be connected after this call, but we should be
* ready for next packet... */
/* If we are already connecting, this will fail */
irda_irnet_connect(self);
#endif /* CONNECT_IN_SEND */
DEBUG(PPP_INFO, "IrTTP not ready ! (%ld-%ld)\n",
self->ttp_open, self->ttp_connect);
/* Note : we can either drop the packet or block the packet.
*
* Blocking the packet allow us a better connection time,
* because by calling ppp_output_wakeup() we can have
* ppp_generic resending the LCP request immediately to us,
* rather than waiting for one of pppd periodic transmission of
* LCP request.
*
* On the other hand, if we block all packet, all those periodic
* transmissions of pppd accumulate in ppp_generic, creating a
* backlog of LCP request. When we eventually connect later on,
* we have to transmit all this backlog before we can connect
* proper (if we don't timeout before).
*
* The current strategy is as follow :
* While we are attempting to connect, we block packets to get
* a better connection time.
* If we fail to connect, we drain the queue and start dropping packets
*/
#ifdef BLOCK_WHEN_CONNECT
/* If we are attempting to connect */
if(test_bit(0, &self->ttp_connect))
{
/* Blocking packet, ppp_generic will retry later */
return 0;
}
#endif /* BLOCK_WHEN_CONNECT */
/* Dropping packet, pppd will retry later */
dev_kfree_skb(skb);
return 1;
}
/* Check if the queue can accept any packet, otherwise block */
if(self->tx_flow != FLOW_START)
DRETURN(0, PPP_INFO, "IrTTP queue full (%d skbs)...\n",
skb_queue_len(&self->tsap->tx_queue));
/* Prepare ppp frame for transmission */
skb = irnet_prepare_skb(self, skb);
DABORT(skb == NULL, 1, PPP_ERROR, "Prepare skb for Tx failed.\n");
/* Send the packet to IrTTP */
ret = irttp_data_request(self->tsap, skb);
if(ret < 0)
{
/*
* > IrTTPs tx queue is full, so we just have to
* > drop the frame! You might think that we should
* > just return -1 and don't deallocate the frame,
* > but that is dangerous since it's possible that
* > we have replaced the original skb with a new
* > one with larger headroom, and that would really
* > confuse do_dev_queue_xmit() in dev.c! I have
* > tried :-) DB
* Correction : we verify the flow control above (self->tx_flow),
* so we come here only if IrTTP doesn't like the packet (empty,
* too large, IrTTP not connected). In those rare cases, it's ok
* to drop it, we don't want to see it here again...
* Jean II
*/
DERROR(PPP_ERROR, "IrTTP doesn't like this packet !!! (0x%X)\n", ret);
/* irttp_data_request already free the packet */
}
DEXIT(PPP_TRACE, "\n");
return 1; /* Packet has been consumed */
}
/*------------------------------------------------------------------*/
/*
* Take care of the ioctls that ppp_generic doesn't want to deal with...
* Note : we are also called from dev_irnet_ioctl().
*/
static int
ppp_irnet_ioctl(struct ppp_channel * chan,
unsigned int cmd,
unsigned long arg)
{
irnet_socket * ap = (struct irnet_socket *) chan->private;
int err;
int val;
u32 accm[8];
void __user *argp = (void __user *)arg;
DENTER(PPP_TRACE, "(channel=0x%p, ap=0x%p, cmd=0x%X)\n",
chan, ap, cmd);
/* Basic checks... */
DASSERT(ap != NULL, -ENXIO, PPP_ERROR, "ap is NULL...\n");
err = -EFAULT;
switch(cmd)
{
/* PPP flags */
case PPPIOCGFLAGS:
val = ap->flags | ap->rbits;
if(put_user(val, (int __user *) argp))
break;
err = 0;
break;
case PPPIOCSFLAGS:
if(get_user(val, (int __user *) argp))
break;
ap->flags = val & ~SC_RCV_BITS;
ap->rbits = val & SC_RCV_BITS;
err = 0;
break;
/* Async map stuff - all dummy to please pppd */
case PPPIOCGASYNCMAP:
if(put_user(ap->xaccm[0], (u32 __user *) argp))
break;
err = 0;
break;
case PPPIOCSASYNCMAP:
if(get_user(ap->xaccm[0], (u32 __user *) argp))
break;
err = 0;
break;
case PPPIOCGRASYNCMAP:
if(put_user(ap->raccm, (u32 __user *) argp))
break;
err = 0;
break;
case PPPIOCSRASYNCMAP:
if(get_user(ap->raccm, (u32 __user *) argp))
break;
err = 0;
break;
case PPPIOCGXASYNCMAP:
if(copy_to_user(argp, ap->xaccm, sizeof(ap->xaccm)))
break;
err = 0;
break;
case PPPIOCSXASYNCMAP:
if(copy_from_user(accm, argp, sizeof(accm)))
break;
accm[2] &= ~0x40000000U; /* can't escape 0x5e */
accm[3] |= 0x60000000U; /* must escape 0x7d, 0x7e */
memcpy(ap->xaccm, accm, sizeof(ap->xaccm));
err = 0;
break;
/* Max PPP frame size */
case PPPIOCGMRU:
if(put_user(ap->mru, (int __user *) argp))
break;
err = 0;
break;
case PPPIOCSMRU:
if(get_user(val, (int __user *) argp))
break;
if(val < PPP_MRU)
val = PPP_MRU;
ap->mru = val;
err = 0;
break;
default:
DEBUG(PPP_INFO, "Unsupported ioctl (0x%X)\n", cmd);
err = -ENOIOCTLCMD;
}
DEXIT(PPP_TRACE, " - err = 0x%X\n", err);
return err;
}
/************************** INITIALISATION **************************/
/*
* Module initialisation and all that jazz...
*/
/*------------------------------------------------------------------*/
/*
* Hook our device callbacks in the filesystem, to connect our code
* to /dev/irnet
*/
static inline int __init
ppp_irnet_init(void)
{
int err = 0;
DENTER(MODULE_TRACE, "()\n");
/* Allocate ourselves as a minor in the misc range */
err = misc_register(&irnet_misc_device);
DEXIT(MODULE_TRACE, "\n");
return err;
}
/*------------------------------------------------------------------*/
/*
* Cleanup at exit...
*/
static inline void __exit
ppp_irnet_cleanup(void)
{
DENTER(MODULE_TRACE, "()\n");
/* De-allocate /dev/irnet minor in misc range */
misc_deregister(&irnet_misc_device);
DEXIT(MODULE_TRACE, "\n");
}
/*------------------------------------------------------------------*/
/*
* Module main entry point
*/
static int __init
irnet_init(void)
{
int err;
/* Initialise both parts... */
err = irda_irnet_init();
if(!err)
err = ppp_irnet_init();
return err;
}
/*------------------------------------------------------------------*/
/*
* Module exit
*/
static void __exit
irnet_cleanup(void)
{
irda_irnet_cleanup();
ppp_irnet_cleanup();
}
/*------------------------------------------------------------------*/
/*
* Module magic
*/
module_init(irnet_init);
module_exit(irnet_cleanup);
MODULE_AUTHOR("Jean Tourrilhes <jt@hpl.hp.com>");
MODULE_DESCRIPTION("IrNET : Synchronous PPP over IrDA");
MODULE_LICENSE("GPL");
MODULE_ALIAS_CHARDEV(10, 187);
| gpl-2.0 |
ensonic/systemd | src/libsystemd/sd-bus/test-bus-signature.c | 57 | 7538 | /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
/***
This file is part of systemd.
Copyright 2013 Lennart Poettering
systemd 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.
systemd 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 systemd; If not, see <http://www.gnu.org/licenses/>.
***/
#include "log.h"
#include "bus-signature.h"
#include "bus-internal.h"
int main(int argc, char *argv[]) {
char prefix[256];
int r;
assert_se(signature_is_single("y", false));
assert_se(signature_is_single("u", false));
assert_se(signature_is_single("v", false));
assert_se(signature_is_single("as", false));
assert_se(signature_is_single("(ss)", false));
assert_se(signature_is_single("()", false));
assert_se(signature_is_single("(()()()()())", false));
assert_se(signature_is_single("(((())))", false));
assert_se(signature_is_single("((((s))))", false));
assert_se(signature_is_single("{ss}", true));
assert_se(signature_is_single("a{ss}", false));
assert_se(!signature_is_single("uu", false));
assert_se(!signature_is_single("", false));
assert_se(!signature_is_single("(", false));
assert_se(!signature_is_single(")", false));
assert_se(!signature_is_single("())", false));
assert_se(!signature_is_single("((())", false));
assert_se(!signature_is_single("{)", false));
assert_se(!signature_is_single("{}", true));
assert_se(!signature_is_single("{sss}", true));
assert_se(!signature_is_single("{s}", true));
assert_se(!signature_is_single("{ss}", false));
assert_se(!signature_is_single("{ass}", true));
assert_se(!signature_is_single("a}", true));
assert_se(signature_is_pair("yy"));
assert_se(signature_is_pair("ss"));
assert_se(signature_is_pair("sas"));
assert_se(signature_is_pair("sv"));
assert_se(signature_is_pair("sa(vs)"));
assert_se(!signature_is_pair(""));
assert_se(!signature_is_pair("va"));
assert_se(!signature_is_pair("sss"));
assert_se(!signature_is_pair("{s}ss"));
assert_se(signature_is_valid("ssa{ss}sssub", true));
assert_se(signature_is_valid("ssa{ss}sssub", false));
assert_se(signature_is_valid("{ss}", true));
assert_se(!signature_is_valid("{ss}", false));
assert_se(signature_is_valid("", true));
assert_se(signature_is_valid("", false));
assert_se(signature_is_valid("sssusa(uuubbba(uu)uuuu)a{u(uuuvas)}", false));
assert_se(!signature_is_valid("a", false));
assert_se(signature_is_valid("as", false));
assert_se(signature_is_valid("aas", false));
assert_se(signature_is_valid("aaas", false));
assert_se(signature_is_valid("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaad", false));
assert_se(signature_is_valid("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaas", false));
assert_se(!signature_is_valid("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaau", false));
assert_se(signature_is_valid("(((((((((((((((((((((((((((((((())))))))))))))))))))))))))))))))", false));
assert_se(!signature_is_valid("((((((((((((((((((((((((((((((((()))))))))))))))))))))))))))))))))", false));
assert_se(namespace_complex_pattern("", ""));
assert_se(namespace_complex_pattern("foobar", "foobar"));
assert_se(namespace_complex_pattern("foobar.waldo", "foobar.waldo"));
assert_se(namespace_complex_pattern("foobar.", "foobar.waldo"));
assert_se(namespace_complex_pattern("foobar.waldo", "foobar."));
assert_se(!namespace_complex_pattern("foobar.waldo", "foobar"));
assert_se(!namespace_complex_pattern("foobar", "foobar.waldo"));
assert_se(!namespace_complex_pattern("", "foo"));
assert_se(!namespace_complex_pattern("foo", ""));
assert_se(!namespace_complex_pattern("foo.", ""));
assert_se(path_complex_pattern("", ""));
assert_se(!path_complex_pattern("", "/"));
assert_se(!path_complex_pattern("/", ""));
assert_se(path_complex_pattern("/", "/"));
assert_se(path_complex_pattern("/foobar/", "/"));
assert_se(!path_complex_pattern("/foobar/", "/foobar"));
assert_se(path_complex_pattern("/foobar", "/foobar"));
assert_se(!path_complex_pattern("/foobar", "/foobar/"));
assert_se(!path_complex_pattern("/foobar", "/foobar/waldo"));
assert_se(path_complex_pattern("/foobar/", "/foobar/waldo"));
assert_se(path_complex_pattern("/foobar/waldo", "/foobar/"));
assert_se(path_simple_pattern("/foo/", "/foo/bar/waldo"));
assert_se(namespace_simple_pattern("", ""));
assert_se(namespace_simple_pattern("", ".foobar"));
assert_se(namespace_simple_pattern("foobar", "foobar"));
assert_se(namespace_simple_pattern("foobar.waldo", "foobar.waldo"));
assert_se(namespace_simple_pattern("foobar", "foobar.waldo"));
assert_se(!namespace_simple_pattern("foobar.waldo", "foobar"));
assert_se(!namespace_simple_pattern("", "foo"));
assert_se(!namespace_simple_pattern("foo", ""));
assert_se(namespace_simple_pattern("foo.", "foo.bar.waldo"));
assert_se(streq(object_path_startswith("/foo/bar", "/foo"), "bar"));
assert_se(streq(object_path_startswith("/foo", "/foo"), ""));
assert_se(streq(object_path_startswith("/foo", "/"), "foo"));
assert_se(streq(object_path_startswith("/", "/"), ""));
assert_se(!object_path_startswith("/foo", "/bar"));
assert_se(!object_path_startswith("/", "/bar"));
assert_se(!object_path_startswith("/foo", ""));
assert_se(object_path_is_valid("/foo/bar"));
assert_se(object_path_is_valid("/foo"));
assert_se(object_path_is_valid("/"));
assert_se(object_path_is_valid("/foo5"));
assert_se(object_path_is_valid("/foo_5"));
assert_se(!object_path_is_valid(""));
assert_se(!object_path_is_valid("/foo/"));
assert_se(!object_path_is_valid("//"));
assert_se(!object_path_is_valid("//foo"));
assert_se(!object_path_is_valid("/foo//bar"));
assert_se(!object_path_is_valid("/foo/aaaäöä"));
OBJECT_PATH_FOREACH_PREFIX(prefix, "/") {
log_info("<%s>", prefix);
assert_not_reached("???");
}
r = 0;
OBJECT_PATH_FOREACH_PREFIX(prefix, "/xxx") {
log_info("<%s>", prefix);
assert_se(streq(prefix, "/"));
assert_se(r == 0);
r++;
}
assert_se(r == 1);
r = 0;
OBJECT_PATH_FOREACH_PREFIX(prefix, "/xxx/yyy/zzz") {
log_info("<%s>", prefix);
assert_se(r != 0 || streq(prefix, "/xxx/yyy"));
assert_se(r != 1 || streq(prefix, "/xxx"));
assert_se(r != 2 || streq(prefix, "/"));
r++;
}
assert_se(r == 3);
return 0;
}
| gpl-2.0 |
matianfu/kunlun-u-boot | board/esteem192e/flash.c | 57 | 28286 | /*
* (C) Copyright 2000
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* 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 <common.h>
#include <mpc8xx.h>
flash_info_t flash_info[CFG_MAX_FLASH_BANKS]; /* info for FLASH chips */
#ifdef CONFIG_FLASH_16BIT
#define FLASH_WORD_SIZE unsigned short
#define FLASH_ID_MASK 0xFFFF
#else
#define FLASH_WORD_SIZE unsigned long
#define FLASH_ID_MASK 0xFFFFFFFF
#endif
/*-----------------------------------------------------------------------
* Functions
*/
ulong flash_get_size (volatile FLASH_WORD_SIZE *addr, flash_info_t *info);
#ifndef CONFIG_FLASH_16BIT
static int write_word (flash_info_t *info, ulong dest, ulong data);
#else
static int write_short (flash_info_t *info, ulong dest, ushort data);
#endif
/*int flash_write (uchar *, ulong, ulong); */
/*flash_info_t *addr2info (ulong); */
static void flash_get_offsets (ulong base, flash_info_t *info);
/*-----------------------------------------------------------------------
*/
unsigned long flash_init (void)
{
volatile immap_t *immap = (immap_t *)CFG_IMMR;
volatile memctl8xx_t *memctl = &immap->im_memctl;
unsigned long size_b0, size_b1;
int i;
/* Init: no FLASHes known */
for (i=0; i<CFG_MAX_FLASH_BANKS; ++i) {
flash_info[i].flash_id = FLASH_UNKNOWN;
}
/* Static FLASH Bank configuration here - FIXME XXX */
size_b0 = flash_get_size((volatile FLASH_WORD_SIZE *)FLASH_BASE0_PRELIM,
&flash_info[0]);
if (flash_info[0].flash_id == FLASH_UNKNOWN) {
printf ("## Unknown FLASH on Bank 0 - Size = 0x%08lx = %ld MB\n",
size_b0, size_b0<<20);
}
size_b1 = flash_get_size((volatile FLASH_WORD_SIZE *)FLASH_BASE1_PRELIM,
&flash_info[1]);
if (size_b1 > size_b0) {
printf ("## ERROR: "
"Bank 1 (0x%08lx = %ld MB) > Bank 0 (0x%08lx = %ld MB)\n",
size_b1, size_b1<<20,
size_b0, size_b0<<20
);
flash_info[0].flash_id = FLASH_UNKNOWN;
flash_info[1].flash_id = FLASH_UNKNOWN;
flash_info[0].sector_count = -1;
flash_info[1].sector_count = -1;
flash_info[0].size = 0;
flash_info[1].size = 0;
return (0);
}
/* Remap FLASH according to real size */
memctl->memc_or0 = CFG_OR_TIMING_FLASH | (-size_b0 & 0xFFFF8000);
memctl->memc_br0 = CFG_FLASH_BASE | 0x00000801; /* (CFG_FLASH_BASE & BR_BA_MSK) | BR_MS_GPCM | BR_V;*/
/* Re-do sizing to get full correct info */
size_b0 = flash_get_size((volatile FLASH_WORD_SIZE *)CFG_FLASH_BASE,
&flash_info[0]);
flash_get_offsets (CFG_FLASH_BASE, &flash_info[0]);
#if CFG_MONITOR_BASE >= CFG_FLASH_BASE
/* monitor protection ON by default */
(void)flash_protect(FLAG_PROTECT_SET,
CFG_MONITOR_BASE,
CFG_MONITOR_BASE+monitor_flash_len-1,
&flash_info[0]);
#endif
if (size_b1) {
memctl->memc_or1 = CFG_OR_TIMING_FLASH | (-size_b1 & 0xFFFF8000);
memctl->memc_br1 = (CFG_FLASH_BASE | 0x00000801) + (size_b0 & BR_BA_MSK);
/*((CFG_FLASH_BASE + size_b0) & BR_BA_MSK) |
BR_MS_GPCM | BR_V;*/
/* Re-do sizing to get full correct info */
size_b1 = flash_get_size((volatile FLASH_WORD_SIZE *)(CFG_FLASH_BASE + size_b0),
&flash_info[1]);
flash_get_offsets (CFG_FLASH_BASE + size_b0, &flash_info[1]);
#if CFG_MONITOR_BASE >= CFG_FLASH_BASE
/* monitor protection ON by default */
(void)flash_protect(FLAG_PROTECT_SET,
CFG_MONITOR_BASE,
CFG_MONITOR_BASE+monitor_flash_len-1,
&flash_info[1]);
#endif
} else {
memctl->memc_br1 = 0; /* invalidate bank */
flash_info[1].flash_id = FLASH_UNKNOWN;
flash_info[1].sector_count = -1;
}
flash_info[0].size = size_b0;
flash_info[1].size = size_b1;
return (size_b0 + size_b1);
}
/*-----------------------------------------------------------------------
*/
static void flash_get_offsets (ulong base, flash_info_t *info)
{
int i;
/* set up sector start adress table */
if (info->flash_id & FLASH_BTYPE) {
if ((info->flash_id & FLASH_VENDMASK) == FLASH_MAN_INTEL) {
#ifndef CONFIG_FLASH_16BIT
/* set sector offsets for bottom boot block type */
info->start[0] = base + 0x00000000;
info->start[1] = base + 0x00004000;
info->start[2] = base + 0x00008000;
info->start[3] = base + 0x0000C000;
info->start[4] = base + 0x00010000;
info->start[5] = base + 0x00014000;
info->start[6] = base + 0x00018000;
info->start[7] = base + 0x0001C000;
for (i = 8; i < info->sector_count; i++) {
info->start[i] = base + (i * 0x00020000) - 0x000E0000;
}
}
else {
/* set sector offsets for bottom boot block type */
info->start[0] = base + 0x00000000;
info->start[1] = base + 0x00008000;
info->start[2] = base + 0x0000C000;
info->start[3] = base + 0x00010000;
for (i = 4; i < info->sector_count; i++) {
info->start[i] = base + (i * 0x00020000) - 0x00060000;
}
}
#else
/* set sector offsets for bottom boot block type */
info->start[0] = base + 0x00000000;
info->start[1] = base + 0x00002000;
info->start[2] = base + 0x00004000;
info->start[3] = base + 0x00006000;
info->start[4] = base + 0x00008000;
info->start[5] = base + 0x0000A000;
info->start[6] = base + 0x0000C000;
info->start[7] = base + 0x0000E000;
for (i = 8; i < info->sector_count; i++) {
info->start[i] = base + (i * 0x00010000) - 0x00070000;
}
}
else {
/* set sector offsets for bottom boot block type */
info->start[0] = base + 0x00000000;
info->start[1] = base + 0x00004000;
info->start[2] = base + 0x00006000;
info->start[3] = base + 0x00008000;
for (i = 4; i < info->sector_count; i++) {
info->start[i] = base + (i * 0x00010000) - 0x00030000;
}
}
#endif
} else {
/* set sector offsets for top boot block type */
i = info->sector_count - 1;
if ((info->flash_id & FLASH_VENDMASK) == FLASH_MAN_INTEL) {
#ifndef CONFIG_FLASH_16BIT
info->start[i--] = base + info->size - 0x00004000;
info->start[i--] = base + info->size - 0x00008000;
info->start[i--] = base + info->size - 0x0000C000;
info->start[i--] = base + info->size - 0x00010000;
info->start[i--] = base + info->size - 0x00014000;
info->start[i--] = base + info->size - 0x00018000;
info->start[i--] = base + info->size - 0x0001C000;
for (; i >= 0; i--) {
info->start[i] = base + i * 0x00020000;
}
} else {
info->start[i--] = base + info->size - 0x00008000;
info->start[i--] = base + info->size - 0x0000C000;
info->start[i--] = base + info->size - 0x00010000;
for (; i >= 0; i--) {
info->start[i] = base + i * 0x00020000;
}
}
#else
info->start[i--] = base + info->size - 0x00002000;
info->start[i--] = base + info->size - 0x00004000;
info->start[i--] = base + info->size - 0x00006000;
info->start[i--] = base + info->size - 0x00008000;
info->start[i--] = base + info->size - 0x0000A000;
info->start[i--] = base + info->size - 0x0000C000;
info->start[i--] = base + info->size - 0x0000E000;
for (; i >= 0; i--) {
info->start[i] = base + i * 0x00010000;
}
} else {
info->start[i--] = base + info->size - 0x00004000;
info->start[i--] = base + info->size - 0x00006000;
info->start[i--] = base + info->size - 0x00008000;
for (; i >= 0; i--) {
info->start[i] = base + i * 0x00010000;
}
}
#endif
}
}
/*-----------------------------------------------------------------------
*/
void flash_print_info (flash_info_t *info)
{
int i;
uchar *boottype;
uchar botboot[]=", bottom boot sect)\n";
uchar topboot[]=", top boot sector)\n";
if (info->flash_id == FLASH_UNKNOWN) {
printf ("missing or unknown FLASH type\n");
return;
}
switch (info->flash_id & FLASH_VENDMASK) {
case FLASH_MAN_AMD: printf ("AMD "); break;
case FLASH_MAN_FUJ: printf ("FUJITSU "); break;
case FLASH_MAN_SST: printf ("SST "); break;
case FLASH_MAN_STM: printf ("STM "); break;
case FLASH_MAN_INTEL: printf ("INTEL "); break;
default: printf ("Unknown Vendor "); break;
}
if (info->flash_id & 0x0001 ) {
boottype = botboot;
} else {
boottype = topboot;
}
switch (info->flash_id & FLASH_TYPEMASK) {
case FLASH_AM400B: printf ("AM29LV400B (4 Mbit%s",boottype);
break;
case FLASH_AM400T: printf ("AM29LV400T (4 Mbit%s",boottype);
break;
case FLASH_AM800B: printf ("AM29LV800B (8 Mbit%s",boottype);
break;
case FLASH_AM800T: printf ("AM29LV800T (8 Mbit%s",boottype);
break;
case FLASH_AM160B: printf ("AM29LV160B (16 Mbit%s",boottype);
break;
case FLASH_AM160T: printf ("AM29LV160T (16 Mbit%s",boottype);
break;
case FLASH_AM320B: printf ("AM29LV320B (32 Mbit%s",boottype);
break;
case FLASH_AM320T: printf ("AM29LV320T (32 Mbit%s",boottype);
break;
case FLASH_INTEL800B: printf ("INTEL28F800B (8 Mbit%s",boottype);
break;
case FLASH_INTEL800T: printf ("INTEL28F800T (8 Mbit%s",boottype);
break;
case FLASH_INTEL160B: printf ("INTEL28F160B (16 Mbit%s",boottype);
break;
case FLASH_INTEL160T: printf ("INTEL28F160T (16 Mbit%s",boottype);
break;
case FLASH_INTEL320B: printf ("INTEL28F320B (32 Mbit%s",boottype);
break;
case FLASH_INTEL320T: printf ("INTEL28F320T (32 Mbit%s",boottype);
break;
#if 0 /* enable when devices are available */
case FLASH_INTEL640B: printf ("INTEL28F640B (64 Mbit%s",boottype);
break;
case FLASH_INTEL640T: printf ("INTEL28F640T (64 Mbit%s",boottype);
break;
#endif
default: printf ("Unknown Chip Type\n");
break;
}
printf (" Size: %ld MB in %d Sectors\n",
info->size >> 20, info->sector_count);
printf (" Sector Start Addresses:");
for (i=0; i<info->sector_count; ++i) {
if ((i % 5) == 0)
printf ("\n ");
printf (" %08lX%s",
info->start[i],
info->protect[i] ? " (RO)" : " "
);
}
printf ("\n");
return;
}
/*-----------------------------------------------------------------------
*/
/*-----------------------------------------------------------------------
*/
/*
* The following code cannot be run from FLASH!
*/
ulong flash_get_size (volatile FLASH_WORD_SIZE *addr, flash_info_t *info)
{
short i;
ulong base = (ulong)addr;
FLASH_WORD_SIZE value;
/* Write auto select command: read Manufacturer ID */
#ifndef CONFIG_FLASH_16BIT
/*
* Note: if it is an AMD flash and the word at addr[0000]
* is 0x00890089 this routine will think it is an Intel
* flash device and may(most likely) cause trouble.
*/
addr[0x0000] = 0x00900090;
if(addr[0x0000] != 0x00890089){
addr[0x0555] = 0x00AA00AA;
addr[0x02AA] = 0x00550055;
addr[0x0555] = 0x00900090;
#else
/*
* Note: if it is an AMD flash and the word at addr[0000]
* is 0x0089 this routine will think it is an Intel
* flash device and may(most likely) cause trouble.
*/
addr[0x0000] = 0x0090;
if(addr[0x0000] != 0x0089){
addr[0x0555] = 0x00AA;
addr[0x02AA] = 0x0055;
addr[0x0555] = 0x0090;
#endif
}
value = addr[0];
switch (value) {
case (AMD_MANUFACT & FLASH_ID_MASK):
info->flash_id = FLASH_MAN_AMD;
break;
case (FUJ_MANUFACT & FLASH_ID_MASK):
info->flash_id = FLASH_MAN_FUJ;
break;
case (STM_MANUFACT & FLASH_ID_MASK):
info->flash_id = FLASH_MAN_STM;
break;
case (SST_MANUFACT & FLASH_ID_MASK):
info->flash_id = FLASH_MAN_SST;
break;
case (INTEL_MANUFACT & FLASH_ID_MASK):
info->flash_id = FLASH_MAN_INTEL;
break;
default:
info->flash_id = FLASH_UNKNOWN;
info->sector_count = 0;
info->size = 0;
return (0); /* no or unknown flash */
}
value = addr[1]; /* device ID */
switch (value) {
case (AMD_ID_LV400T & FLASH_ID_MASK):
info->flash_id += FLASH_AM400T;
info->sector_count = 11;
info->size = 0x00100000;
break; /* => 1 MB */
case (AMD_ID_LV400B & FLASH_ID_MASK):
info->flash_id += FLASH_AM400B;
info->sector_count = 11;
info->size = 0x00100000;
break; /* => 1 MB */
case (AMD_ID_LV800T & FLASH_ID_MASK):
info->flash_id += FLASH_AM800T;
info->sector_count = 19;
info->size = 0x00200000;
break; /* => 2 MB */
case (AMD_ID_LV800B & FLASH_ID_MASK):
info->flash_id += FLASH_AM800B;
info->sector_count = 19;
info->size = 0x00200000;
break; /* => 2 MB */
case (AMD_ID_LV160T & FLASH_ID_MASK):
info->flash_id += FLASH_AM160T;
info->sector_count = 35;
info->size = 0x00400000;
break; /* => 4 MB */
case (AMD_ID_LV160B & FLASH_ID_MASK):
info->flash_id += FLASH_AM160B;
info->sector_count = 35;
info->size = 0x00400000;
break; /* => 4 MB */
#if 0 /* enable when device IDs are available */
case (AMD_ID_LV320T & FLASH_ID_MASK):
info->flash_id += FLASH_AM320T;
info->sector_count = 67;
info->size = 0x00800000;
break; /* => 8 MB */
case (AMD_ID_LV320B & FLASH_ID_MASK):
info->flash_id += FLASH_AM320B;
info->sector_count = 67;
info->size = 0x00800000;
break; /* => 8 MB */
#endif
case (INTEL_ID_28F800B3T & FLASH_ID_MASK):
info->flash_id += FLASH_INTEL800T;
info->sector_count = 23;
info->size = 0x00200000;
break; /* => 2 MB */
case (INTEL_ID_28F800B3B & FLASH_ID_MASK):
info->flash_id += FLASH_INTEL800B;
info->sector_count = 23;
info->size = 0x00200000;
break; /* => 2 MB */
case (INTEL_ID_28F160B3T & FLASH_ID_MASK):
info->flash_id += FLASH_INTEL160T;
info->sector_count = 39;
info->size = 0x00400000;
break; /* => 4 MB */
case (INTEL_ID_28F160B3B & FLASH_ID_MASK):
info->flash_id += FLASH_INTEL160B;
info->sector_count = 39;
info->size = 0x00400000;
break; /* => 4 MB */
case (INTEL_ID_28F320B3T & FLASH_ID_MASK):
info->flash_id += FLASH_INTEL320T;
info->sector_count = 71;
info->size = 0x00800000;
break; /* => 8 MB */
case (INTEL_ID_28F320B3B & FLASH_ID_MASK):
info->flash_id += FLASH_AM320B;
info->sector_count = 71;
info->size = 0x00800000;
break; /* => 8 MB */
#if 0 /* enable when devices are available */
case (INTEL_ID_28F320B3T & FLASH_ID_MASK):
info->flash_id += FLASH_INTEL320T;
info->sector_count = 135;
info->size = 0x01000000;
break; /* => 16 MB */
case (INTEL_ID_28F320B3B & FLASH_ID_MASK):
info->flash_id += FLASH_AM320B;
info->sector_count = 135;
info->size = 0x01000000;
break; /* => 16 MB */
#endif
default:
info->flash_id = FLASH_UNKNOWN;
return (0); /* => no or unknown flash */
}
/* set up sector start adress table */
if (info->flash_id & FLASH_BTYPE) {
if ((info->flash_id & FLASH_VENDMASK) == FLASH_MAN_INTEL) {
#ifndef CONFIG_FLASH_16BIT
/* set sector offsets for bottom boot block type */
info->start[0] = base + 0x00000000;
info->start[1] = base + 0x00004000;
info->start[2] = base + 0x00008000;
info->start[3] = base + 0x0000C000;
info->start[4] = base + 0x00010000;
info->start[5] = base + 0x00014000;
info->start[6] = base + 0x00018000;
info->start[7] = base + 0x0001C000;
for (i = 8; i < info->sector_count; i++) {
info->start[i] = base + (i * 0x00020000) - 0x000E0000;
}
}
else {
/* set sector offsets for bottom boot block type */
info->start[0] = base + 0x00000000;
info->start[1] = base + 0x00008000;
info->start[2] = base + 0x0000C000;
info->start[3] = base + 0x00010000;
for (i = 4; i < info->sector_count; i++) {
info->start[i] = base + (i * 0x00020000) - 0x00060000;
}
}
#else
/* set sector offsets for bottom boot block type */
info->start[0] = base + 0x00000000;
info->start[1] = base + 0x00002000;
info->start[2] = base + 0x00004000;
info->start[3] = base + 0x00006000;
info->start[4] = base + 0x00008000;
info->start[5] = base + 0x0000A000;
info->start[6] = base + 0x0000C000;
info->start[7] = base + 0x0000E000;
for (i = 8; i < info->sector_count; i++) {
info->start[i] = base + (i * 0x00010000) - 0x00070000;
}
}
else {
/* set sector offsets for bottom boot block type */
info->start[0] = base + 0x00000000;
info->start[1] = base + 0x00004000;
info->start[2] = base + 0x00006000;
info->start[3] = base + 0x00008000;
for (i = 4; i < info->sector_count; i++) {
info->start[i] = base + (i * 0x00010000) - 0x00030000;
}
}
#endif
} else {
/* set sector offsets for top boot block type */
i = info->sector_count - 1;
if ((info->flash_id & FLASH_VENDMASK) == FLASH_MAN_INTEL) {
#ifndef CONFIG_FLASH_16BIT
info->start[i--] = base + info->size - 0x00004000;
info->start[i--] = base + info->size - 0x00008000;
info->start[i--] = base + info->size - 0x0000C000;
info->start[i--] = base + info->size - 0x00010000;
info->start[i--] = base + info->size - 0x00014000;
info->start[i--] = base + info->size - 0x00018000;
info->start[i--] = base + info->size - 0x0001C000;
for (; i >= 0; i--) {
info->start[i] = base + i * 0x00020000;
}
} else {
info->start[i--] = base + info->size - 0x00008000;
info->start[i--] = base + info->size - 0x0000C000;
info->start[i--] = base + info->size - 0x00010000;
for (; i >= 0; i--) {
info->start[i] = base + i * 0x00020000;
}
}
#else
info->start[i--] = base + info->size - 0x00002000;
info->start[i--] = base + info->size - 0x00004000;
info->start[i--] = base + info->size - 0x00006000;
info->start[i--] = base + info->size - 0x00008000;
info->start[i--] = base + info->size - 0x0000A000;
info->start[i--] = base + info->size - 0x0000C000;
info->start[i--] = base + info->size - 0x0000E000;
for (; i >= 0; i--) {
info->start[i] = base + i * 0x00010000;
}
} else {
info->start[i--] = base + info->size - 0x00004000;
info->start[i--] = base + info->size - 0x00006000;
info->start[i--] = base + info->size - 0x00008000;
for (; i >= 0; i--) {
info->start[i] = base + i * 0x00010000;
}
}
#endif
}
/* check for protected sectors */
for (i = 0; i < info->sector_count; i++) {
/* read sector protection at sector address, (A7 .. A0) = 0x02 */
/* D0 = 1 if protected */
addr = (volatile FLASH_WORD_SIZE *)(info->start[i]);
info->protect[i] = addr[2] & 1;
}
/*
* Prevent writes to uninitialized FLASH.
*/
if (info->flash_id != FLASH_UNKNOWN) {
addr = (volatile FLASH_WORD_SIZE *)info->start[0];
if( (info->flash_id & 0xFF00) == FLASH_MAN_INTEL){
*addr = (0x00F000F0 & FLASH_ID_MASK); /* reset bank */
} else {
*addr = (0x00FF00FF & FLASH_ID_MASK); /* reset bank */
}
}
return (info->size);
}
/*-----------------------------------------------------------------------
*/
int flash_erase (flash_info_t *info, int s_first, int s_last)
{
volatile FLASH_WORD_SIZE *addr=(volatile FLASH_WORD_SIZE*)(info->start[0]);
int flag, prot, sect, l_sect, barf;
ulong start, now, last;
int rcode = 0;
if ((s_first < 0) || (s_first > s_last)) {
if (info->flash_id == FLASH_UNKNOWN) {
printf ("- missing\n");
} else {
printf ("- no sectors to erase\n");
}
return 1;
}
if ((info->flash_id == FLASH_UNKNOWN) ||
((info->flash_id > FLASH_AMD_COMP) &&
( (info->flash_id & FLASH_VENDMASK) != FLASH_MAN_INTEL ) ) ){
printf ("Can't erase unknown flash type - aborted\n");
return 1;
}
prot = 0;
for (sect=s_first; sect<=s_last; ++sect) {
if (info->protect[sect]) {
prot++;
}
}
if (prot) {
printf ("- Warning: %d protected sectors will not be erased!\n",
prot);
} else {
printf ("\n");
}
l_sect = -1;
/* Disable interrupts which might cause a timeout here */
flag = disable_interrupts();
if(info->flash_id < FLASH_AMD_COMP) {
#ifndef CONFIG_FLASH_16BIT
addr[0x0555] = 0x00AA00AA;
addr[0x02AA] = 0x00550055;
addr[0x0555] = 0x00800080;
addr[0x0555] = 0x00AA00AA;
addr[0x02AA] = 0x00550055;
#else
addr[0x0555] = 0x00AA;
addr[0x02AA] = 0x0055;
addr[0x0555] = 0x0080;
addr[0x0555] = 0x00AA;
addr[0x02AA] = 0x0055;
#endif
/* Start erase on unprotected sectors */
for (sect = s_first; sect<=s_last; sect++) {
if (info->protect[sect] == 0) { /* not protected */
addr = (volatile FLASH_WORD_SIZE *)(info->start[sect]);
addr[0] = (0x00300030 & FLASH_ID_MASK);
l_sect = sect;
}
}
/* re-enable interrupts if necessary */
if (flag)
enable_interrupts();
/* wait at least 80us - let's wait 1 ms */
udelay (1000);
/*
* We wait for the last triggered sector
*/
if (l_sect < 0)
goto DONE;
start = get_timer (0);
last = start;
addr = (volatile FLASH_WORD_SIZE*)(info->start[l_sect]);
while ((addr[0] & (0x00800080&FLASH_ID_MASK)) !=
(0x00800080&FLASH_ID_MASK) )
{
if ((now = get_timer(start)) > CFG_FLASH_ERASE_TOUT) {
printf ("Timeout\n");
return 1;
}
/* show that we're waiting */
if ((now - last) > 1000) { /* every second */
serial_putc ('.');
last = now;
}
}
DONE:
/* reset to read mode */
addr = (volatile FLASH_WORD_SIZE *)info->start[0];
addr[0] = (0x00F000F0 & FLASH_ID_MASK); /* reset bank */
} else {
for (sect = s_first; sect<=s_last; sect++) {
if (info->protect[sect] == 0) { /* not protected */
barf = 0;
#ifndef CONFIG_FLASH_16BIT
addr = (vu_long*)(info->start[sect]);
addr[0] = 0x00200020;
addr[0] = 0x00D000D0;
while(!(addr[0] & 0x00800080)); /* wait for error or finish */
if( addr[0] & 0x003A003A) { /* check for error */
barf = addr[0] & 0x003A0000;
if( barf ) {
barf >>=16;
} else {
barf = addr[0] & 0x0000003A;
}
}
#else
addr = (vu_short*)(info->start[sect]);
addr[0] = 0x0020;
addr[0] = 0x00D0;
while(!(addr[0] & 0x0080)); /* wait for error or finish */
if( addr[0] & 0x003A) /* check for error */
barf = addr[0] & 0x003A;
#endif
if(barf) {
printf("\nFlash error in sector at %lx\n",(unsigned long)addr);
if(barf & 0x0002) printf("Block locked, not erased.\n");
if((barf & 0x0030) == 0x0030)
printf("Command Sequence error.\n");
if((barf & 0x0030) == 0x0020)
printf("Block Erase error.\n");
if(barf & 0x0008) printf("Vpp Low error.\n");
rcode = 1;
} else printf(".");
l_sect = sect;
}
addr = (volatile FLASH_WORD_SIZE *)info->start[0];
addr[0] = (0x00FF00FF & FLASH_ID_MASK); /* reset bank */
}
}
printf (" done\n");
return rcode;
}
/*-----------------------------------------------------------------------
*/
/*-----------------------------------------------------------------------
* Copy memory to flash, returns:
* 0 - OK
* 1 - write timeout
* 2 - Flash not erased
*/
int write_buff (flash_info_t *info, uchar *src, ulong addr, ulong cnt)
{
#ifndef CONFIG_FLASH_16BIT
ulong cp, wp, data;
int l;
#else
ulong cp, wp;
ushort data;
#endif
int i, rc;
#ifndef CONFIG_FLASH_16BIT
wp = (addr & ~3); /* get lower word aligned address */
/*
* handle unaligned start bytes
*/
if ((l = addr - wp) != 0) {
data = 0;
for (i=0, cp=wp; i<l; ++i, ++cp) {
data = (data << 8) | (*(uchar *)cp);
}
for (; i<4 && cnt>0; ++i) {
data = (data << 8) | *src++;
--cnt;
++cp;
}
for (; cnt==0 && i<4; ++i, ++cp) {
data = (data << 8) | (*(uchar *)cp);
}
if ((rc = write_word(info, wp, data)) != 0) {
return (rc);
}
wp += 4;
}
/*
* handle word aligned part
*/
while (cnt >= 4) {
data = 0;
for (i=0; i<4; ++i) {
data = (data << 8) | *src++;
}
if ((rc = write_word(info, wp, data)) != 0) {
return (rc);
}
wp += 4;
cnt -= 4;
}
if (cnt == 0) {
return (0);
}
/*
* handle unaligned tail bytes
*/
data = 0;
for (i=0, cp=wp; i<4 && cnt>0; ++i, ++cp) {
data = (data << 8) | *src++;
--cnt;
}
for (; i<4; ++i, ++cp) {
data = (data << 8) | (*(uchar *)cp);
}
return (write_word(info, wp, data));
#else
wp = (addr & ~1); /* get lower word aligned address */
/*
* handle unaligned start byte
*/
if (addr - wp) {
data = 0;
data = (data << 8) | *src++;
--cnt;
if ((rc = write_short(info, wp, data)) != 0) {
return (rc);
}
wp += 2;
}
/*
* handle word aligned part
*/
/* l = 0; used for debuging */
while (cnt >= 2) {
data = 0;
for (i=0; i<2; ++i) {
data = (data << 8) | *src++;
}
/* if(!l){
printf("%x",data);
l = 1;
} used for debuging */
if ((rc = write_short(info, wp, data)) != 0) {
return (rc);
}
wp += 2;
cnt -= 2;
}
if (cnt == 0) {
return (0);
}
/*
* handle unaligned tail bytes
*/
data = 0;
for (i=0, cp=wp; i<2 && cnt>0; ++i, ++cp) {
data = (data << 8) | *src++;
--cnt;
}
for (; i<2; ++i, ++cp) {
data = (data << 8) | (*(uchar *)cp);
}
return (write_short(info, wp, data));
#endif
}
/*-----------------------------------------------------------------------
* Write a word to Flash, returns:
* 0 - OK
* 1 - write timeout
* 2 - Flash not erased
*/
#ifndef CONFIG_FLASH_16BIT
static int write_word (flash_info_t *info, ulong dest, ulong data)
{
vu_long *addr = (vu_long*)(info->start[0]);
ulong start,barf;
int flag;
/* Check if Flash is (sufficiently) erased */
if ((*((vu_long *)dest) & data) != data) {
return (2);
}
/* Disable interrupts which might cause a timeout here */
flag = disable_interrupts();
if(info->flash_id > FLASH_AMD_COMP) {
/* AMD stuff */
addr[0x0555] = 0x00AA00AA;
addr[0x02AA] = 0x00550055;
addr[0x0555] = 0x00A000A0;
} else {
/* intel stuff */
*addr = 0x00400040;
}
*((vu_long *)dest) = data;
/* re-enable interrupts if necessary */
if (flag)
enable_interrupts();
/* data polling for D7 */
start = get_timer (0);
if(info->flash_id > FLASH_AMD_COMP) {
while ((*((vu_long *)dest) & 0x00800080) != (data & 0x00800080)) {
if (get_timer(start) > CFG_FLASH_WRITE_TOUT) {
return (1);
}
}
} else {
while(!(addr[0] & 0x00800080)){ /* wait for error or finish */
if (get_timer(start) > CFG_FLASH_WRITE_TOUT) {
return (1);
}
if( addr[0] & 0x003A003A) { /* check for error */
barf = addr[0] & 0x003A0000;
if( barf ) {
barf >>=16;
} else {
barf = addr[0] & 0x0000003A;
}
printf("\nFlash write error at address %lx\n",(unsigned long)dest);
if(barf & 0x0002) printf("Block locked, not erased.\n");
if(barf & 0x0010) printf("Programming error.\n");
if(barf & 0x0008) printf("Vpp Low error.\n");
return(2);
}
}
return (0);
}
#else
static int write_short (flash_info_t *info, ulong dest, ushort data)
{
vu_short *addr = (vu_short*)(info->start[0]);
ulong start,barf;
int flag;
/* Check if Flash is (sufficiently) erased */
if ((*((vu_short *)dest) & data) != data) {
return (2);
}
/* Disable interrupts which might cause a timeout here */
flag = disable_interrupts();
if(info->flash_id < FLASH_AMD_COMP) {
/* AMD stuff */
addr[0x0555] = 0x00AA;
addr[0x02AA] = 0x0055;
addr[0x0555] = 0x00A0;
} else {
/* intel stuff */
*addr = 0x00D0;
*addr = 0x0040;
}
*((vu_short *)dest) = data;
/* re-enable interrupts if necessary */
if (flag)
enable_interrupts();
/* data polling for D7 */
start = get_timer (0);
if(info->flash_id < FLASH_AMD_COMP) {
/* AMD stuff */
while ((*((vu_short *)dest) & 0x0080) != (data & 0x0080)) {
if (get_timer(start) > CFG_FLASH_WRITE_TOUT) {
return (1);
}
}
} else {
/* intel stuff */
while(!(addr[0] & 0x0080)){ /* wait for error or finish */
if (get_timer(start) > CFG_FLASH_WRITE_TOUT) return (1);
}
if( addr[0] & 0x003A) { /* check for error */
barf = addr[0] & 0x003A;
printf("\nFlash write error at address %lx\n",(unsigned long)dest);
if(barf & 0x0002) printf("Block locked, not erased.\n");
if(barf & 0x0010) printf("Programming error.\n");
if(barf & 0x0008) printf("Vpp Low error.\n");
return(2);
}
*addr = 0x00B0;
*addr = 0x0070;
while(!(addr[0] & 0x0080)){ /* wait for error or finish */
if (get_timer(start) > CFG_FLASH_WRITE_TOUT) return (1);
}
*addr = 0x00FF;
}
return (0);
}
#endif
/*-----------------------------------------------------------------------
*/
| gpl-2.0 |
Zex/linux | drivers/virtio/virtio_ring.c | 57 | 33350 | /* Virtio ring implementation.
*
* Copyright 2007 Rusty Russell IBM Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/virtio.h>
#include <linux/virtio_ring.h>
#include <linux/virtio_config.h>
#include <linux/device.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/hrtimer.h>
#include <linux/kmemleak.h>
#include <linux/dma-mapping.h>
#include <xen/xen.h>
#ifdef DEBUG
/* For development, we want to crash whenever the ring is screwed. */
#define BAD_RING(_vq, fmt, args...) \
do { \
dev_err(&(_vq)->vq.vdev->dev, \
"%s:"fmt, (_vq)->vq.name, ##args); \
BUG(); \
} while (0)
/* Caller is supposed to guarantee no reentry. */
#define START_USE(_vq) \
do { \
if ((_vq)->in_use) \
panic("%s:in_use = %i\n", \
(_vq)->vq.name, (_vq)->in_use); \
(_vq)->in_use = __LINE__; \
} while (0)
#define END_USE(_vq) \
do { BUG_ON(!(_vq)->in_use); (_vq)->in_use = 0; } while(0)
#else
#define BAD_RING(_vq, fmt, args...) \
do { \
dev_err(&_vq->vq.vdev->dev, \
"%s:"fmt, (_vq)->vq.name, ##args); \
(_vq)->broken = true; \
} while (0)
#define START_USE(vq)
#define END_USE(vq)
#endif
struct vring_desc_state {
void *data; /* Data for callback. */
struct vring_desc *indir_desc; /* Indirect descriptor, if any. */
};
struct vring_virtqueue {
struct virtqueue vq;
/* Actual memory layout for this queue */
struct vring vring;
/* Can we use weak barriers? */
bool weak_barriers;
/* Other side has made a mess, don't try any more. */
bool broken;
/* Host supports indirect buffers */
bool indirect;
/* Host publishes avail event idx */
bool event;
/* Head of free buffer list. */
unsigned int free_head;
/* Number we've added since last sync. */
unsigned int num_added;
/* Last used index we've seen. */
u16 last_used_idx;
/* Last written value to avail->flags */
u16 avail_flags_shadow;
/* Last written value to avail->idx in guest byte order */
u16 avail_idx_shadow;
/* How to notify other side. FIXME: commonalize hcalls! */
bool (*notify)(struct virtqueue *vq);
/* DMA, allocation, and size information */
bool we_own_ring;
size_t queue_size_in_bytes;
dma_addr_t queue_dma_addr;
#ifdef DEBUG
/* They're supposed to lock for us. */
unsigned int in_use;
/* Figure out if their kicks are too delayed. */
bool last_add_time_valid;
ktime_t last_add_time;
#endif
/* Per-descriptor state. */
struct vring_desc_state desc_state[];
};
#define to_vvq(_vq) container_of(_vq, struct vring_virtqueue, vq)
/*
* The interaction between virtio and a possible IOMMU is a mess.
*
* On most systems with virtio, physical addresses match bus addresses,
* and it doesn't particularly matter whether we use the DMA API.
*
* On some systems, including Xen and any system with a physical device
* that speaks virtio behind a physical IOMMU, we must use the DMA API
* for virtio DMA to work at all.
*
* On other systems, including SPARC and PPC64, virtio-pci devices are
* enumerated as though they are behind an IOMMU, but the virtio host
* ignores the IOMMU, so we must either pretend that the IOMMU isn't
* there or somehow map everything as the identity.
*
* For the time being, we preserve historic behavior and bypass the DMA
* API.
*/
static bool vring_use_dma_api(struct virtio_device *vdev)
{
/*
* In theory, it's possible to have a buggy QEMU-supposed
* emulated Q35 IOMMU and Xen enabled at the same time. On
* such a configuration, virtio has never worked and will
* not work without an even larger kludge. Instead, enable
* the DMA API if we're a Xen guest, which at least allows
* all of the sensible Xen configurations to work correctly.
*/
if (xen_domain())
return true;
return false;
}
/*
* The DMA ops on various arches are rather gnarly right now, and
* making all of the arch DMA ops work on the vring device itself
* is a mess. For now, we use the parent device for DMA ops.
*/
struct device *vring_dma_dev(const struct vring_virtqueue *vq)
{
return vq->vq.vdev->dev.parent;
}
/* Map one sg entry. */
static dma_addr_t vring_map_one_sg(const struct vring_virtqueue *vq,
struct scatterlist *sg,
enum dma_data_direction direction)
{
if (!vring_use_dma_api(vq->vq.vdev))
return (dma_addr_t)sg_phys(sg);
/*
* We can't use dma_map_sg, because we don't use scatterlists in
* the way it expects (we don't guarantee that the scatterlist
* will exist for the lifetime of the mapping).
*/
return dma_map_page(vring_dma_dev(vq),
sg_page(sg), sg->offset, sg->length,
direction);
}
static dma_addr_t vring_map_single(const struct vring_virtqueue *vq,
void *cpu_addr, size_t size,
enum dma_data_direction direction)
{
if (!vring_use_dma_api(vq->vq.vdev))
return (dma_addr_t)virt_to_phys(cpu_addr);
return dma_map_single(vring_dma_dev(vq),
cpu_addr, size, direction);
}
static void vring_unmap_one(const struct vring_virtqueue *vq,
struct vring_desc *desc)
{
u16 flags;
if (!vring_use_dma_api(vq->vq.vdev))
return;
flags = virtio16_to_cpu(vq->vq.vdev, desc->flags);
if (flags & VRING_DESC_F_INDIRECT) {
dma_unmap_single(vring_dma_dev(vq),
virtio64_to_cpu(vq->vq.vdev, desc->addr),
virtio32_to_cpu(vq->vq.vdev, desc->len),
(flags & VRING_DESC_F_WRITE) ?
DMA_FROM_DEVICE : DMA_TO_DEVICE);
} else {
dma_unmap_page(vring_dma_dev(vq),
virtio64_to_cpu(vq->vq.vdev, desc->addr),
virtio32_to_cpu(vq->vq.vdev, desc->len),
(flags & VRING_DESC_F_WRITE) ?
DMA_FROM_DEVICE : DMA_TO_DEVICE);
}
}
static int vring_mapping_error(const struct vring_virtqueue *vq,
dma_addr_t addr)
{
if (!vring_use_dma_api(vq->vq.vdev))
return 0;
return dma_mapping_error(vring_dma_dev(vq), addr);
}
static struct vring_desc *alloc_indirect(struct virtqueue *_vq,
unsigned int total_sg, gfp_t gfp)
{
struct vring_desc *desc;
unsigned int i;
/*
* We require lowmem mappings for the descriptors because
* otherwise virt_to_phys will give us bogus addresses in the
* virtqueue.
*/
gfp &= ~__GFP_HIGHMEM;
desc = kmalloc(total_sg * sizeof(struct vring_desc), gfp);
if (!desc)
return NULL;
for (i = 0; i < total_sg; i++)
desc[i].next = cpu_to_virtio16(_vq->vdev, i + 1);
return desc;
}
static inline int virtqueue_add(struct virtqueue *_vq,
struct scatterlist *sgs[],
unsigned int total_sg,
unsigned int out_sgs,
unsigned int in_sgs,
void *data,
gfp_t gfp)
{
struct vring_virtqueue *vq = to_vvq(_vq);
struct scatterlist *sg;
struct vring_desc *desc;
unsigned int i, n, avail, descs_used, uninitialized_var(prev), err_idx;
int head;
bool indirect;
START_USE(vq);
BUG_ON(data == NULL);
if (unlikely(vq->broken)) {
END_USE(vq);
return -EIO;
}
#ifdef DEBUG
{
ktime_t now = ktime_get();
/* No kick or get, with .1 second between? Warn. */
if (vq->last_add_time_valid)
WARN_ON(ktime_to_ms(ktime_sub(now, vq->last_add_time))
> 100);
vq->last_add_time = now;
vq->last_add_time_valid = true;
}
#endif
BUG_ON(total_sg > vq->vring.num);
BUG_ON(total_sg == 0);
head = vq->free_head;
/* If the host supports indirect descriptor tables, and we have multiple
* buffers, then go indirect. FIXME: tune this threshold */
if (vq->indirect && total_sg > 1 && vq->vq.num_free)
desc = alloc_indirect(_vq, total_sg, gfp);
else
desc = NULL;
if (desc) {
/* Use a single buffer which doesn't continue */
indirect = true;
/* Set up rest to use this indirect table. */
i = 0;
descs_used = 1;
} else {
indirect = false;
desc = vq->vring.desc;
i = head;
descs_used = total_sg;
}
if (vq->vq.num_free < descs_used) {
pr_debug("Can't add buf len %i - avail = %i\n",
descs_used, vq->vq.num_free);
/* FIXME: for historical reasons, we force a notify here if
* there are outgoing parts to the buffer. Presumably the
* host should service the ring ASAP. */
if (out_sgs)
vq->notify(&vq->vq);
END_USE(vq);
return -ENOSPC;
}
for (n = 0; n < out_sgs; n++) {
for (sg = sgs[n]; sg; sg = sg_next(sg)) {
dma_addr_t addr = vring_map_one_sg(vq, sg, DMA_TO_DEVICE);
if (vring_mapping_error(vq, addr))
goto unmap_release;
desc[i].flags = cpu_to_virtio16(_vq->vdev, VRING_DESC_F_NEXT);
desc[i].addr = cpu_to_virtio64(_vq->vdev, addr);
desc[i].len = cpu_to_virtio32(_vq->vdev, sg->length);
prev = i;
i = virtio16_to_cpu(_vq->vdev, desc[i].next);
}
}
for (; n < (out_sgs + in_sgs); n++) {
for (sg = sgs[n]; sg; sg = sg_next(sg)) {
dma_addr_t addr = vring_map_one_sg(vq, sg, DMA_FROM_DEVICE);
if (vring_mapping_error(vq, addr))
goto unmap_release;
desc[i].flags = cpu_to_virtio16(_vq->vdev, VRING_DESC_F_NEXT | VRING_DESC_F_WRITE);
desc[i].addr = cpu_to_virtio64(_vq->vdev, addr);
desc[i].len = cpu_to_virtio32(_vq->vdev, sg->length);
prev = i;
i = virtio16_to_cpu(_vq->vdev, desc[i].next);
}
}
/* Last one doesn't continue. */
desc[prev].flags &= cpu_to_virtio16(_vq->vdev, ~VRING_DESC_F_NEXT);
if (indirect) {
/* Now that the indirect table is filled in, map it. */
dma_addr_t addr = vring_map_single(
vq, desc, total_sg * sizeof(struct vring_desc),
DMA_TO_DEVICE);
if (vring_mapping_error(vq, addr))
goto unmap_release;
vq->vring.desc[head].flags = cpu_to_virtio16(_vq->vdev, VRING_DESC_F_INDIRECT);
vq->vring.desc[head].addr = cpu_to_virtio64(_vq->vdev, addr);
vq->vring.desc[head].len = cpu_to_virtio32(_vq->vdev, total_sg * sizeof(struct vring_desc));
}
/* We're using some buffers from the free list. */
vq->vq.num_free -= descs_used;
/* Update free pointer */
if (indirect)
vq->free_head = virtio16_to_cpu(_vq->vdev, vq->vring.desc[head].next);
else
vq->free_head = i;
/* Store token and indirect buffer state. */
vq->desc_state[head].data = data;
if (indirect)
vq->desc_state[head].indir_desc = desc;
/* Put entry in available array (but don't update avail->idx until they
* do sync). */
avail = vq->avail_idx_shadow & (vq->vring.num - 1);
vq->vring.avail->ring[avail] = cpu_to_virtio16(_vq->vdev, head);
/* Descriptors and available array need to be set before we expose the
* new available array entries. */
virtio_wmb(vq->weak_barriers);
vq->avail_idx_shadow++;
vq->vring.avail->idx = cpu_to_virtio16(_vq->vdev, vq->avail_idx_shadow);
vq->num_added++;
pr_debug("Added buffer head %i to %p\n", head, vq);
END_USE(vq);
/* This is very unlikely, but theoretically possible. Kick
* just in case. */
if (unlikely(vq->num_added == (1 << 16) - 1))
virtqueue_kick(_vq);
return 0;
unmap_release:
err_idx = i;
i = head;
for (n = 0; n < total_sg; n++) {
if (i == err_idx)
break;
vring_unmap_one(vq, &desc[i]);
i = vq->vring.desc[i].next;
}
vq->vq.num_free += total_sg;
if (indirect)
kfree(desc);
return -EIO;
}
/**
* virtqueue_add_sgs - expose buffers to other end
* @vq: the struct virtqueue we're talking about.
* @sgs: array of terminated scatterlists.
* @out_num: the number of scatterlists readable by other side
* @in_num: the number of scatterlists which are writable (after readable ones)
* @data: the token identifying the buffer.
* @gfp: how to do memory allocations (if necessary).
*
* Caller must ensure we don't call this with other virtqueue operations
* at the same time (except where noted).
*
* Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
*/
int virtqueue_add_sgs(struct virtqueue *_vq,
struct scatterlist *sgs[],
unsigned int out_sgs,
unsigned int in_sgs,
void *data,
gfp_t gfp)
{
unsigned int i, total_sg = 0;
/* Count them first. */
for (i = 0; i < out_sgs + in_sgs; i++) {
struct scatterlist *sg;
for (sg = sgs[i]; sg; sg = sg_next(sg))
total_sg++;
}
return virtqueue_add(_vq, sgs, total_sg, out_sgs, in_sgs, data, gfp);
}
EXPORT_SYMBOL_GPL(virtqueue_add_sgs);
/**
* virtqueue_add_outbuf - expose output buffers to other end
* @vq: the struct virtqueue we're talking about.
* @sg: scatterlist (must be well-formed and terminated!)
* @num: the number of entries in @sg readable by other side
* @data: the token identifying the buffer.
* @gfp: how to do memory allocations (if necessary).
*
* Caller must ensure we don't call this with other virtqueue operations
* at the same time (except where noted).
*
* Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
*/
int virtqueue_add_outbuf(struct virtqueue *vq,
struct scatterlist *sg, unsigned int num,
void *data,
gfp_t gfp)
{
return virtqueue_add(vq, &sg, num, 1, 0, data, gfp);
}
EXPORT_SYMBOL_GPL(virtqueue_add_outbuf);
/**
* virtqueue_add_inbuf - expose input buffers to other end
* @vq: the struct virtqueue we're talking about.
* @sg: scatterlist (must be well-formed and terminated!)
* @num: the number of entries in @sg writable by other side
* @data: the token identifying the buffer.
* @gfp: how to do memory allocations (if necessary).
*
* Caller must ensure we don't call this with other virtqueue operations
* at the same time (except where noted).
*
* Returns zero or a negative error (ie. ENOSPC, ENOMEM, EIO).
*/
int virtqueue_add_inbuf(struct virtqueue *vq,
struct scatterlist *sg, unsigned int num,
void *data,
gfp_t gfp)
{
return virtqueue_add(vq, &sg, num, 0, 1, data, gfp);
}
EXPORT_SYMBOL_GPL(virtqueue_add_inbuf);
/**
* virtqueue_kick_prepare - first half of split virtqueue_kick call.
* @vq: the struct virtqueue
*
* Instead of virtqueue_kick(), you can do:
* if (virtqueue_kick_prepare(vq))
* virtqueue_notify(vq);
*
* This is sometimes useful because the virtqueue_kick_prepare() needs
* to be serialized, but the actual virtqueue_notify() call does not.
*/
bool virtqueue_kick_prepare(struct virtqueue *_vq)
{
struct vring_virtqueue *vq = to_vvq(_vq);
u16 new, old;
bool needs_kick;
START_USE(vq);
/* We need to expose available array entries before checking avail
* event. */
virtio_mb(vq->weak_barriers);
old = vq->avail_idx_shadow - vq->num_added;
new = vq->avail_idx_shadow;
vq->num_added = 0;
#ifdef DEBUG
if (vq->last_add_time_valid) {
WARN_ON(ktime_to_ms(ktime_sub(ktime_get(),
vq->last_add_time)) > 100);
}
vq->last_add_time_valid = false;
#endif
if (vq->event) {
needs_kick = vring_need_event(virtio16_to_cpu(_vq->vdev, vring_avail_event(&vq->vring)),
new, old);
} else {
needs_kick = !(vq->vring.used->flags & cpu_to_virtio16(_vq->vdev, VRING_USED_F_NO_NOTIFY));
}
END_USE(vq);
return needs_kick;
}
EXPORT_SYMBOL_GPL(virtqueue_kick_prepare);
/**
* virtqueue_notify - second half of split virtqueue_kick call.
* @vq: the struct virtqueue
*
* This does not need to be serialized.
*
* Returns false if host notify failed or queue is broken, otherwise true.
*/
bool virtqueue_notify(struct virtqueue *_vq)
{
struct vring_virtqueue *vq = to_vvq(_vq);
if (unlikely(vq->broken))
return false;
/* Prod other side to tell it about changes. */
if (!vq->notify(_vq)) {
vq->broken = true;
return false;
}
return true;
}
EXPORT_SYMBOL_GPL(virtqueue_notify);
/**
* virtqueue_kick - update after add_buf
* @vq: the struct virtqueue
*
* After one or more virtqueue_add_* calls, invoke this to kick
* the other side.
*
* Caller must ensure we don't call this with other virtqueue
* operations at the same time (except where noted).
*
* Returns false if kick failed, otherwise true.
*/
bool virtqueue_kick(struct virtqueue *vq)
{
if (virtqueue_kick_prepare(vq))
return virtqueue_notify(vq);
return true;
}
EXPORT_SYMBOL_GPL(virtqueue_kick);
static void detach_buf(struct vring_virtqueue *vq, unsigned int head)
{
unsigned int i, j;
u16 nextflag = cpu_to_virtio16(vq->vq.vdev, VRING_DESC_F_NEXT);
/* Clear data ptr. */
vq->desc_state[head].data = NULL;
/* Put back on free list: unmap first-level descriptors and find end */
i = head;
while (vq->vring.desc[i].flags & nextflag) {
vring_unmap_one(vq, &vq->vring.desc[i]);
i = virtio16_to_cpu(vq->vq.vdev, vq->vring.desc[i].next);
vq->vq.num_free++;
}
vring_unmap_one(vq, &vq->vring.desc[i]);
vq->vring.desc[i].next = cpu_to_virtio16(vq->vq.vdev, vq->free_head);
vq->free_head = head;
/* Plus final descriptor */
vq->vq.num_free++;
/* Free the indirect table, if any, now that it's unmapped. */
if (vq->desc_state[head].indir_desc) {
struct vring_desc *indir_desc = vq->desc_state[head].indir_desc;
u32 len = virtio32_to_cpu(vq->vq.vdev, vq->vring.desc[head].len);
BUG_ON(!(vq->vring.desc[head].flags &
cpu_to_virtio16(vq->vq.vdev, VRING_DESC_F_INDIRECT)));
BUG_ON(len == 0 || len % sizeof(struct vring_desc));
for (j = 0; j < len / sizeof(struct vring_desc); j++)
vring_unmap_one(vq, &indir_desc[j]);
kfree(vq->desc_state[head].indir_desc);
vq->desc_state[head].indir_desc = NULL;
}
}
static inline bool more_used(const struct vring_virtqueue *vq)
{
return vq->last_used_idx != virtio16_to_cpu(vq->vq.vdev, vq->vring.used->idx);
}
/**
* virtqueue_get_buf - get the next used buffer
* @vq: the struct virtqueue we're talking about.
* @len: the length written into the buffer
*
* If the driver wrote data into the buffer, @len will be set to the
* amount written. This means you don't need to clear the buffer
* beforehand to ensure there's no data leakage in the case of short
* writes.
*
* Caller must ensure we don't call this with other virtqueue
* operations at the same time (except where noted).
*
* Returns NULL if there are no used buffers, or the "data" token
* handed to virtqueue_add_*().
*/
void *virtqueue_get_buf(struct virtqueue *_vq, unsigned int *len)
{
struct vring_virtqueue *vq = to_vvq(_vq);
void *ret;
unsigned int i;
u16 last_used;
START_USE(vq);
if (unlikely(vq->broken)) {
END_USE(vq);
return NULL;
}
if (!more_used(vq)) {
pr_debug("No more buffers in queue\n");
END_USE(vq);
return NULL;
}
/* Only get used array entries after they have been exposed by host. */
virtio_rmb(vq->weak_barriers);
last_used = (vq->last_used_idx & (vq->vring.num - 1));
i = virtio32_to_cpu(_vq->vdev, vq->vring.used->ring[last_used].id);
*len = virtio32_to_cpu(_vq->vdev, vq->vring.used->ring[last_used].len);
if (unlikely(i >= vq->vring.num)) {
BAD_RING(vq, "id %u out of range\n", i);
return NULL;
}
if (unlikely(!vq->desc_state[i].data)) {
BAD_RING(vq, "id %u is not a head!\n", i);
return NULL;
}
/* detach_buf clears data, so grab it now. */
ret = vq->desc_state[i].data;
detach_buf(vq, i);
vq->last_used_idx++;
/* If we expect an interrupt for the next entry, tell host
* by writing event index and flush out the write before
* the read in the next get_buf call. */
if (!(vq->avail_flags_shadow & VRING_AVAIL_F_NO_INTERRUPT))
virtio_store_mb(vq->weak_barriers,
&vring_used_event(&vq->vring),
cpu_to_virtio16(_vq->vdev, vq->last_used_idx));
#ifdef DEBUG
vq->last_add_time_valid = false;
#endif
END_USE(vq);
return ret;
}
EXPORT_SYMBOL_GPL(virtqueue_get_buf);
/**
* virtqueue_disable_cb - disable callbacks
* @vq: the struct virtqueue we're talking about.
*
* Note that this is not necessarily synchronous, hence unreliable and only
* useful as an optimization.
*
* Unlike other operations, this need not be serialized.
*/
void virtqueue_disable_cb(struct virtqueue *_vq)
{
struct vring_virtqueue *vq = to_vvq(_vq);
if (!(vq->avail_flags_shadow & VRING_AVAIL_F_NO_INTERRUPT)) {
vq->avail_flags_shadow |= VRING_AVAIL_F_NO_INTERRUPT;
vq->vring.avail->flags = cpu_to_virtio16(_vq->vdev, vq->avail_flags_shadow);
}
}
EXPORT_SYMBOL_GPL(virtqueue_disable_cb);
/**
* virtqueue_enable_cb_prepare - restart callbacks after disable_cb
* @vq: the struct virtqueue we're talking about.
*
* This re-enables callbacks; it returns current queue state
* in an opaque unsigned value. This value should be later tested by
* virtqueue_poll, to detect a possible race between the driver checking for
* more work, and enabling callbacks.
*
* Caller must ensure we don't call this with other virtqueue
* operations at the same time (except where noted).
*/
unsigned virtqueue_enable_cb_prepare(struct virtqueue *_vq)
{
struct vring_virtqueue *vq = to_vvq(_vq);
u16 last_used_idx;
START_USE(vq);
/* We optimistically turn back on interrupts, then check if there was
* more to do. */
/* Depending on the VIRTIO_RING_F_EVENT_IDX feature, we need to
* either clear the flags bit or point the event index at the next
* entry. Always do both to keep code simple. */
if (vq->avail_flags_shadow & VRING_AVAIL_F_NO_INTERRUPT) {
vq->avail_flags_shadow &= ~VRING_AVAIL_F_NO_INTERRUPT;
vq->vring.avail->flags = cpu_to_virtio16(_vq->vdev, vq->avail_flags_shadow);
}
vring_used_event(&vq->vring) = cpu_to_virtio16(_vq->vdev, last_used_idx = vq->last_used_idx);
END_USE(vq);
return last_used_idx;
}
EXPORT_SYMBOL_GPL(virtqueue_enable_cb_prepare);
/**
* virtqueue_poll - query pending used buffers
* @vq: the struct virtqueue we're talking about.
* @last_used_idx: virtqueue state (from call to virtqueue_enable_cb_prepare).
*
* Returns "true" if there are pending used buffers in the queue.
*
* This does not need to be serialized.
*/
bool virtqueue_poll(struct virtqueue *_vq, unsigned last_used_idx)
{
struct vring_virtqueue *vq = to_vvq(_vq);
virtio_mb(vq->weak_barriers);
return (u16)last_used_idx != virtio16_to_cpu(_vq->vdev, vq->vring.used->idx);
}
EXPORT_SYMBOL_GPL(virtqueue_poll);
/**
* virtqueue_enable_cb - restart callbacks after disable_cb.
* @vq: the struct virtqueue we're talking about.
*
* This re-enables callbacks; it returns "false" if there are pending
* buffers in the queue, to detect a possible race between the driver
* checking for more work, and enabling callbacks.
*
* Caller must ensure we don't call this with other virtqueue
* operations at the same time (except where noted).
*/
bool virtqueue_enable_cb(struct virtqueue *_vq)
{
unsigned last_used_idx = virtqueue_enable_cb_prepare(_vq);
return !virtqueue_poll(_vq, last_used_idx);
}
EXPORT_SYMBOL_GPL(virtqueue_enable_cb);
/**
* virtqueue_enable_cb_delayed - restart callbacks after disable_cb.
* @vq: the struct virtqueue we're talking about.
*
* This re-enables callbacks but hints to the other side to delay
* interrupts until most of the available buffers have been processed;
* it returns "false" if there are many pending buffers in the queue,
* to detect a possible race between the driver checking for more work,
* and enabling callbacks.
*
* Caller must ensure we don't call this with other virtqueue
* operations at the same time (except where noted).
*/
bool virtqueue_enable_cb_delayed(struct virtqueue *_vq)
{
struct vring_virtqueue *vq = to_vvq(_vq);
u16 bufs;
START_USE(vq);
/* We optimistically turn back on interrupts, then check if there was
* more to do. */
/* Depending on the VIRTIO_RING_F_USED_EVENT_IDX feature, we need to
* either clear the flags bit or point the event index at the next
* entry. Always do both to keep code simple. */
if (vq->avail_flags_shadow & VRING_AVAIL_F_NO_INTERRUPT) {
vq->avail_flags_shadow &= ~VRING_AVAIL_F_NO_INTERRUPT;
vq->vring.avail->flags = cpu_to_virtio16(_vq->vdev, vq->avail_flags_shadow);
}
/* TODO: tune this threshold */
bufs = (u16)(vq->avail_idx_shadow - vq->last_used_idx) * 3 / 4;
virtio_store_mb(vq->weak_barriers,
&vring_used_event(&vq->vring),
cpu_to_virtio16(_vq->vdev, vq->last_used_idx + bufs));
if (unlikely((u16)(virtio16_to_cpu(_vq->vdev, vq->vring.used->idx) - vq->last_used_idx) > bufs)) {
END_USE(vq);
return false;
}
END_USE(vq);
return true;
}
EXPORT_SYMBOL_GPL(virtqueue_enable_cb_delayed);
/**
* virtqueue_detach_unused_buf - detach first unused buffer
* @vq: the struct virtqueue we're talking about.
*
* Returns NULL or the "data" token handed to virtqueue_add_*().
* This is not valid on an active queue; it is useful only for device
* shutdown.
*/
void *virtqueue_detach_unused_buf(struct virtqueue *_vq)
{
struct vring_virtqueue *vq = to_vvq(_vq);
unsigned int i;
void *buf;
START_USE(vq);
for (i = 0; i < vq->vring.num; i++) {
if (!vq->desc_state[i].data)
continue;
/* detach_buf clears data, so grab it now. */
buf = vq->desc_state[i].data;
detach_buf(vq, i);
vq->avail_idx_shadow--;
vq->vring.avail->idx = cpu_to_virtio16(_vq->vdev, vq->avail_idx_shadow);
END_USE(vq);
return buf;
}
/* That should have freed everything. */
BUG_ON(vq->vq.num_free != vq->vring.num);
END_USE(vq);
return NULL;
}
EXPORT_SYMBOL_GPL(virtqueue_detach_unused_buf);
irqreturn_t vring_interrupt(int irq, void *_vq)
{
struct vring_virtqueue *vq = to_vvq(_vq);
if (!more_used(vq)) {
pr_debug("virtqueue interrupt with no work for %p\n", vq);
return IRQ_NONE;
}
if (unlikely(vq->broken))
return IRQ_HANDLED;
pr_debug("virtqueue callback for %p (%p)\n", vq, vq->vq.callback);
if (vq->vq.callback)
vq->vq.callback(&vq->vq);
return IRQ_HANDLED;
}
EXPORT_SYMBOL_GPL(vring_interrupt);
struct virtqueue *__vring_new_virtqueue(unsigned int index,
struct vring vring,
struct virtio_device *vdev,
bool weak_barriers,
bool (*notify)(struct virtqueue *),
void (*callback)(struct virtqueue *),
const char *name)
{
unsigned int i;
struct vring_virtqueue *vq;
vq = kmalloc(sizeof(*vq) + vring.num * sizeof(struct vring_desc_state),
GFP_KERNEL);
if (!vq)
return NULL;
vq->vring = vring;
vq->vq.callback = callback;
vq->vq.vdev = vdev;
vq->vq.name = name;
vq->vq.num_free = vring.num;
vq->vq.index = index;
vq->we_own_ring = false;
vq->queue_dma_addr = 0;
vq->queue_size_in_bytes = 0;
vq->notify = notify;
vq->weak_barriers = weak_barriers;
vq->broken = false;
vq->last_used_idx = 0;
vq->avail_flags_shadow = 0;
vq->avail_idx_shadow = 0;
vq->num_added = 0;
list_add_tail(&vq->vq.list, &vdev->vqs);
#ifdef DEBUG
vq->in_use = false;
vq->last_add_time_valid = false;
#endif
vq->indirect = virtio_has_feature(vdev, VIRTIO_RING_F_INDIRECT_DESC);
vq->event = virtio_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX);
/* No callback? Tell other side not to bother us. */
if (!callback) {
vq->avail_flags_shadow |= VRING_AVAIL_F_NO_INTERRUPT;
vq->vring.avail->flags = cpu_to_virtio16(vdev, vq->avail_flags_shadow);
}
/* Put everything in free lists. */
vq->free_head = 0;
for (i = 0; i < vring.num-1; i++)
vq->vring.desc[i].next = cpu_to_virtio16(vdev, i + 1);
memset(vq->desc_state, 0, vring.num * sizeof(struct vring_desc_state));
return &vq->vq;
}
EXPORT_SYMBOL_GPL(__vring_new_virtqueue);
static void *vring_alloc_queue(struct virtio_device *vdev, size_t size,
dma_addr_t *dma_handle, gfp_t flag)
{
if (vring_use_dma_api(vdev)) {
return dma_alloc_coherent(vdev->dev.parent, size,
dma_handle, flag);
} else {
void *queue = alloc_pages_exact(PAGE_ALIGN(size), flag);
if (queue) {
phys_addr_t phys_addr = virt_to_phys(queue);
*dma_handle = (dma_addr_t)phys_addr;
/*
* Sanity check: make sure we dind't truncate
* the address. The only arches I can find that
* have 64-bit phys_addr_t but 32-bit dma_addr_t
* are certain non-highmem MIPS and x86
* configurations, but these configurations
* should never allocate physical pages above 32
* bits, so this is fine. Just in case, throw a
* warning and abort if we end up with an
* unrepresentable address.
*/
if (WARN_ON_ONCE(*dma_handle != phys_addr)) {
free_pages_exact(queue, PAGE_ALIGN(size));
return NULL;
}
}
return queue;
}
}
static void vring_free_queue(struct virtio_device *vdev, size_t size,
void *queue, dma_addr_t dma_handle)
{
if (vring_use_dma_api(vdev)) {
dma_free_coherent(vdev->dev.parent, size, queue, dma_handle);
} else {
free_pages_exact(queue, PAGE_ALIGN(size));
}
}
struct virtqueue *vring_create_virtqueue(
unsigned int index,
unsigned int num,
unsigned int vring_align,
struct virtio_device *vdev,
bool weak_barriers,
bool may_reduce_num,
bool (*notify)(struct virtqueue *),
void (*callback)(struct virtqueue *),
const char *name)
{
struct virtqueue *vq;
void *queue = NULL;
dma_addr_t dma_addr;
size_t queue_size_in_bytes;
struct vring vring;
/* We assume num is a power of 2. */
if (num & (num - 1)) {
dev_warn(&vdev->dev, "Bad virtqueue length %u\n", num);
return NULL;
}
/* TODO: allocate each queue chunk individually */
for (; num && vring_size(num, vring_align) > PAGE_SIZE; num /= 2) {
queue = vring_alloc_queue(vdev, vring_size(num, vring_align),
&dma_addr,
GFP_KERNEL|__GFP_NOWARN|__GFP_ZERO);
if (queue)
break;
}
if (!num)
return NULL;
if (!queue) {
/* Try to get a single page. You are my only hope! */
queue = vring_alloc_queue(vdev, vring_size(num, vring_align),
&dma_addr, GFP_KERNEL|__GFP_ZERO);
}
if (!queue)
return NULL;
queue_size_in_bytes = vring_size(num, vring_align);
vring_init(&vring, num, queue, vring_align);
vq = __vring_new_virtqueue(index, vring, vdev, weak_barriers,
notify, callback, name);
if (!vq) {
vring_free_queue(vdev, queue_size_in_bytes, queue,
dma_addr);
return NULL;
}
to_vvq(vq)->queue_dma_addr = dma_addr;
to_vvq(vq)->queue_size_in_bytes = queue_size_in_bytes;
to_vvq(vq)->we_own_ring = true;
return vq;
}
EXPORT_SYMBOL_GPL(vring_create_virtqueue);
struct virtqueue *vring_new_virtqueue(unsigned int index,
unsigned int num,
unsigned int vring_align,
struct virtio_device *vdev,
bool weak_barriers,
void *pages,
bool (*notify)(struct virtqueue *vq),
void (*callback)(struct virtqueue *vq),
const char *name)
{
struct vring vring;
vring_init(&vring, num, pages, vring_align);
return __vring_new_virtqueue(index, vring, vdev, weak_barriers,
notify, callback, name);
}
EXPORT_SYMBOL_GPL(vring_new_virtqueue);
void vring_del_virtqueue(struct virtqueue *_vq)
{
struct vring_virtqueue *vq = to_vvq(_vq);
if (vq->we_own_ring) {
vring_free_queue(vq->vq.vdev, vq->queue_size_in_bytes,
vq->vring.desc, vq->queue_dma_addr);
}
list_del(&_vq->list);
kfree(vq);
}
EXPORT_SYMBOL_GPL(vring_del_virtqueue);
/* Manipulates transport-specific feature bits. */
void vring_transport_features(struct virtio_device *vdev)
{
unsigned int i;
for (i = VIRTIO_TRANSPORT_F_START; i < VIRTIO_TRANSPORT_F_END; i++) {
switch (i) {
case VIRTIO_RING_F_INDIRECT_DESC:
break;
case VIRTIO_RING_F_EVENT_IDX:
break;
case VIRTIO_F_VERSION_1:
break;
default:
/* We don't understand this bit. */
__virtio_clear_bit(vdev, i);
}
}
}
EXPORT_SYMBOL_GPL(vring_transport_features);
/**
* virtqueue_get_vring_size - return the size of the virtqueue's vring
* @vq: the struct virtqueue containing the vring of interest.
*
* Returns the size of the vring. This is mainly used for boasting to
* userspace. Unlike other operations, this need not be serialized.
*/
unsigned int virtqueue_get_vring_size(struct virtqueue *_vq)
{
struct vring_virtqueue *vq = to_vvq(_vq);
return vq->vring.num;
}
EXPORT_SYMBOL_GPL(virtqueue_get_vring_size);
bool virtqueue_is_broken(struct virtqueue *_vq)
{
struct vring_virtqueue *vq = to_vvq(_vq);
return vq->broken;
}
EXPORT_SYMBOL_GPL(virtqueue_is_broken);
/*
* This should prevent the device from being used, allowing drivers to
* recover. You may need to grab appropriate locks to flush.
*/
void virtio_break_device(struct virtio_device *dev)
{
struct virtqueue *_vq;
list_for_each_entry(_vq, &dev->vqs, list) {
struct vring_virtqueue *vq = to_vvq(_vq);
vq->broken = true;
}
}
EXPORT_SYMBOL_GPL(virtio_break_device);
dma_addr_t virtqueue_get_desc_addr(struct virtqueue *_vq)
{
struct vring_virtqueue *vq = to_vvq(_vq);
BUG_ON(!vq->we_own_ring);
return vq->queue_dma_addr;
}
EXPORT_SYMBOL_GPL(virtqueue_get_desc_addr);
dma_addr_t virtqueue_get_avail_addr(struct virtqueue *_vq)
{
struct vring_virtqueue *vq = to_vvq(_vq);
BUG_ON(!vq->we_own_ring);
return vq->queue_dma_addr +
((char *)vq->vring.avail - (char *)vq->vring.desc);
}
EXPORT_SYMBOL_GPL(virtqueue_get_avail_addr);
dma_addr_t virtqueue_get_used_addr(struct virtqueue *_vq)
{
struct vring_virtqueue *vq = to_vvq(_vq);
BUG_ON(!vq->we_own_ring);
return vq->queue_dma_addr +
((char *)vq->vring.used - (char *)vq->vring.desc);
}
EXPORT_SYMBOL_GPL(virtqueue_get_used_addr);
const struct vring *virtqueue_get_vring(struct virtqueue *vq)
{
return &to_vvq(vq)->vring;
}
EXPORT_SYMBOL_GPL(virtqueue_get_vring);
MODULE_LICENSE("GPL");
| gpl-2.0 |
HomuHomu/Kernel-SM-G935D-MM | drivers/net/ethernet/marvell/sky2.c | 313 | 139759 | /*
* New driver for Marvell Yukon 2 chipset.
* Based on earlier sk98lin, and skge driver.
*
* This driver intentionally does not support all the features
* of the original driver such as link fail-over and link management because
* those should be done at higher levels.
*
* Copyright (C) 2005 Stephen Hemminger <shemminger@osdl.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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/crc32.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/netdevice.h>
#include <linux/dma-mapping.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/pci.h>
#include <linux/interrupt.h>
#include <linux/ip.h>
#include <linux/slab.h>
#include <net/ip.h>
#include <linux/tcp.h>
#include <linux/in.h>
#include <linux/delay.h>
#include <linux/workqueue.h>
#include <linux/if_vlan.h>
#include <linux/prefetch.h>
#include <linux/debugfs.h>
#include <linux/mii.h>
#include <linux/of_device.h>
#include <linux/of_net.h>
#include <asm/irq.h>
#include "sky2.h"
#define DRV_NAME "sky2"
#define DRV_VERSION "1.30"
/*
* The Yukon II chipset takes 64 bit command blocks (called list elements)
* that are organized into three (receive, transmit, status) different rings
* similar to Tigon3.
*/
#define RX_LE_SIZE 1024
#define RX_LE_BYTES (RX_LE_SIZE*sizeof(struct sky2_rx_le))
#define RX_MAX_PENDING (RX_LE_SIZE/6 - 2)
#define RX_DEF_PENDING RX_MAX_PENDING
/* This is the worst case number of transmit list elements for a single skb:
VLAN:GSO + CKSUM + Data + skb_frags * DMA */
#define MAX_SKB_TX_LE (2 + (sizeof(dma_addr_t)/sizeof(u32))*(MAX_SKB_FRAGS+1))
#define TX_MIN_PENDING (MAX_SKB_TX_LE+1)
#define TX_MAX_PENDING 1024
#define TX_DEF_PENDING 63
#define TX_WATCHDOG (5 * HZ)
#define NAPI_WEIGHT 64
#define PHY_RETRIES 1000
#define SKY2_EEPROM_MAGIC 0x9955aabb
#define RING_NEXT(x, s) (((x)+1) & ((s)-1))
static const u32 default_msg =
NETIF_MSG_DRV | NETIF_MSG_PROBE | NETIF_MSG_LINK
| NETIF_MSG_TIMER | NETIF_MSG_TX_ERR | NETIF_MSG_RX_ERR
| NETIF_MSG_IFUP | NETIF_MSG_IFDOWN;
static int debug = -1; /* defaults above */
module_param(debug, int, 0);
MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all)");
static int copybreak __read_mostly = 128;
module_param(copybreak, int, 0);
MODULE_PARM_DESC(copybreak, "Receive copy threshold");
static int disable_msi = 0;
module_param(disable_msi, int, 0);
MODULE_PARM_DESC(disable_msi, "Disable Message Signaled Interrupt (MSI)");
static int legacy_pme = 0;
module_param(legacy_pme, int, 0);
MODULE_PARM_DESC(legacy_pme, "Legacy power management");
static const struct pci_device_id sky2_id_table[] = {
{ PCI_DEVICE(PCI_VENDOR_ID_SYSKONNECT, 0x9000) }, /* SK-9Sxx */
{ PCI_DEVICE(PCI_VENDOR_ID_SYSKONNECT, 0x9E00) }, /* SK-9Exx */
{ PCI_DEVICE(PCI_VENDOR_ID_SYSKONNECT, 0x9E01) }, /* SK-9E21M */
{ PCI_DEVICE(PCI_VENDOR_ID_DLINK, 0x4b00) }, /* DGE-560T */
{ PCI_DEVICE(PCI_VENDOR_ID_DLINK, 0x4001) }, /* DGE-550SX */
{ PCI_DEVICE(PCI_VENDOR_ID_DLINK, 0x4B02) }, /* DGE-560SX */
{ PCI_DEVICE(PCI_VENDOR_ID_DLINK, 0x4B03) }, /* DGE-550T */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4340) }, /* 88E8021 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4341) }, /* 88E8022 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4342) }, /* 88E8061 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4343) }, /* 88E8062 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4344) }, /* 88E8021 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4345) }, /* 88E8022 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4346) }, /* 88E8061 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4347) }, /* 88E8062 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4350) }, /* 88E8035 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4351) }, /* 88E8036 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4352) }, /* 88E8038 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4353) }, /* 88E8039 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4354) }, /* 88E8040 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4355) }, /* 88E8040T */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4356) }, /* 88EC033 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4357) }, /* 88E8042 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x435A) }, /* 88E8048 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4360) }, /* 88E8052 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4361) }, /* 88E8050 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4362) }, /* 88E8053 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4363) }, /* 88E8055 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4364) }, /* 88E8056 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4365) }, /* 88E8070 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4366) }, /* 88EC036 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4367) }, /* 88EC032 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4368) }, /* 88EC034 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4369) }, /* 88EC042 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x436A) }, /* 88E8058 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x436B) }, /* 88E8071 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x436C) }, /* 88E8072 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x436D) }, /* 88E8055 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4370) }, /* 88E8075 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4380) }, /* 88E8057 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4381) }, /* 88E8059 */
{ PCI_DEVICE(PCI_VENDOR_ID_MARVELL, 0x4382) }, /* 88E8079 */
{ 0 }
};
MODULE_DEVICE_TABLE(pci, sky2_id_table);
/* Avoid conditionals by using array */
static const unsigned txqaddr[] = { Q_XA1, Q_XA2 };
static const unsigned rxqaddr[] = { Q_R1, Q_R2 };
static const u32 portirq_msk[] = { Y2_IS_PORT_1, Y2_IS_PORT_2 };
static void sky2_set_multicast(struct net_device *dev);
static irqreturn_t sky2_intr(int irq, void *dev_id);
/* Access to PHY via serial interconnect */
static int gm_phy_write(struct sky2_hw *hw, unsigned port, u16 reg, u16 val)
{
int i;
gma_write16(hw, port, GM_SMI_DATA, val);
gma_write16(hw, port, GM_SMI_CTRL,
GM_SMI_CT_PHY_AD(PHY_ADDR_MARV) | GM_SMI_CT_REG_AD(reg));
for (i = 0; i < PHY_RETRIES; i++) {
u16 ctrl = gma_read16(hw, port, GM_SMI_CTRL);
if (ctrl == 0xffff)
goto io_error;
if (!(ctrl & GM_SMI_CT_BUSY))
return 0;
udelay(10);
}
dev_warn(&hw->pdev->dev, "%s: phy write timeout\n", hw->dev[port]->name);
return -ETIMEDOUT;
io_error:
dev_err(&hw->pdev->dev, "%s: phy I/O error\n", hw->dev[port]->name);
return -EIO;
}
static int __gm_phy_read(struct sky2_hw *hw, unsigned port, u16 reg, u16 *val)
{
int i;
gma_write16(hw, port, GM_SMI_CTRL, GM_SMI_CT_PHY_AD(PHY_ADDR_MARV)
| GM_SMI_CT_REG_AD(reg) | GM_SMI_CT_OP_RD);
for (i = 0; i < PHY_RETRIES; i++) {
u16 ctrl = gma_read16(hw, port, GM_SMI_CTRL);
if (ctrl == 0xffff)
goto io_error;
if (ctrl & GM_SMI_CT_RD_VAL) {
*val = gma_read16(hw, port, GM_SMI_DATA);
return 0;
}
udelay(10);
}
dev_warn(&hw->pdev->dev, "%s: phy read timeout\n", hw->dev[port]->name);
return -ETIMEDOUT;
io_error:
dev_err(&hw->pdev->dev, "%s: phy I/O error\n", hw->dev[port]->name);
return -EIO;
}
static inline u16 gm_phy_read(struct sky2_hw *hw, unsigned port, u16 reg)
{
u16 v;
__gm_phy_read(hw, port, reg, &v);
return v;
}
static void sky2_power_on(struct sky2_hw *hw)
{
/* switch power to VCC (WA for VAUX problem) */
sky2_write8(hw, B0_POWER_CTRL,
PC_VAUX_ENA | PC_VCC_ENA | PC_VAUX_OFF | PC_VCC_ON);
/* disable Core Clock Division, */
sky2_write32(hw, B2_Y2_CLK_CTRL, Y2_CLK_DIV_DIS);
if (hw->chip_id == CHIP_ID_YUKON_XL && hw->chip_rev > CHIP_REV_YU_XL_A1)
/* enable bits are inverted */
sky2_write8(hw, B2_Y2_CLK_GATE,
Y2_PCI_CLK_LNK1_DIS | Y2_COR_CLK_LNK1_DIS |
Y2_CLK_GAT_LNK1_DIS | Y2_PCI_CLK_LNK2_DIS |
Y2_COR_CLK_LNK2_DIS | Y2_CLK_GAT_LNK2_DIS);
else
sky2_write8(hw, B2_Y2_CLK_GATE, 0);
if (hw->flags & SKY2_HW_ADV_POWER_CTL) {
u32 reg;
sky2_pci_write32(hw, PCI_DEV_REG3, 0);
reg = sky2_pci_read32(hw, PCI_DEV_REG4);
/* set all bits to 0 except bits 15..12 and 8 */
reg &= P_ASPM_CONTROL_MSK;
sky2_pci_write32(hw, PCI_DEV_REG4, reg);
reg = sky2_pci_read32(hw, PCI_DEV_REG5);
/* set all bits to 0 except bits 28 & 27 */
reg &= P_CTL_TIM_VMAIN_AV_MSK;
sky2_pci_write32(hw, PCI_DEV_REG5, reg);
sky2_pci_write32(hw, PCI_CFG_REG_1, 0);
sky2_write16(hw, B0_CTST, Y2_HW_WOL_ON);
/* Enable workaround for dev 4.107 on Yukon-Ultra & Extreme */
reg = sky2_read32(hw, B2_GP_IO);
reg |= GLB_GPIO_STAT_RACE_DIS;
sky2_write32(hw, B2_GP_IO, reg);
sky2_read32(hw, B2_GP_IO);
}
/* Turn on "driver loaded" LED */
sky2_write16(hw, B0_CTST, Y2_LED_STAT_ON);
}
static void sky2_power_aux(struct sky2_hw *hw)
{
if (hw->chip_id == CHIP_ID_YUKON_XL && hw->chip_rev > CHIP_REV_YU_XL_A1)
sky2_write8(hw, B2_Y2_CLK_GATE, 0);
else
/* enable bits are inverted */
sky2_write8(hw, B2_Y2_CLK_GATE,
Y2_PCI_CLK_LNK1_DIS | Y2_COR_CLK_LNK1_DIS |
Y2_CLK_GAT_LNK1_DIS | Y2_PCI_CLK_LNK2_DIS |
Y2_COR_CLK_LNK2_DIS | Y2_CLK_GAT_LNK2_DIS);
/* switch power to VAUX if supported and PME from D3cold */
if ( (sky2_read32(hw, B0_CTST) & Y2_VAUX_AVAIL) &&
pci_pme_capable(hw->pdev, PCI_D3cold))
sky2_write8(hw, B0_POWER_CTRL,
(PC_VAUX_ENA | PC_VCC_ENA |
PC_VAUX_ON | PC_VCC_OFF));
/* turn off "driver loaded LED" */
sky2_write16(hw, B0_CTST, Y2_LED_STAT_OFF);
}
static void sky2_gmac_reset(struct sky2_hw *hw, unsigned port)
{
u16 reg;
/* disable all GMAC IRQ's */
sky2_write8(hw, SK_REG(port, GMAC_IRQ_MSK), 0);
gma_write16(hw, port, GM_MC_ADDR_H1, 0); /* clear MC hash */
gma_write16(hw, port, GM_MC_ADDR_H2, 0);
gma_write16(hw, port, GM_MC_ADDR_H3, 0);
gma_write16(hw, port, GM_MC_ADDR_H4, 0);
reg = gma_read16(hw, port, GM_RX_CTRL);
reg |= GM_RXCR_UCF_ENA | GM_RXCR_MCF_ENA;
gma_write16(hw, port, GM_RX_CTRL, reg);
}
/* flow control to advertise bits */
static const u16 copper_fc_adv[] = {
[FC_NONE] = 0,
[FC_TX] = PHY_M_AN_ASP,
[FC_RX] = PHY_M_AN_PC,
[FC_BOTH] = PHY_M_AN_PC | PHY_M_AN_ASP,
};
/* flow control to advertise bits when using 1000BaseX */
static const u16 fiber_fc_adv[] = {
[FC_NONE] = PHY_M_P_NO_PAUSE_X,
[FC_TX] = PHY_M_P_ASYM_MD_X,
[FC_RX] = PHY_M_P_SYM_MD_X,
[FC_BOTH] = PHY_M_P_BOTH_MD_X,
};
/* flow control to GMA disable bits */
static const u16 gm_fc_disable[] = {
[FC_NONE] = GM_GPCR_FC_RX_DIS | GM_GPCR_FC_TX_DIS,
[FC_TX] = GM_GPCR_FC_RX_DIS,
[FC_RX] = GM_GPCR_FC_TX_DIS,
[FC_BOTH] = 0,
};
static void sky2_phy_init(struct sky2_hw *hw, unsigned port)
{
struct sky2_port *sky2 = netdev_priv(hw->dev[port]);
u16 ctrl, ct1000, adv, pg, ledctrl, ledover, reg;
if ( (sky2->flags & SKY2_FLAG_AUTO_SPEED) &&
!(hw->flags & SKY2_HW_NEWER_PHY)) {
u16 ectrl = gm_phy_read(hw, port, PHY_MARV_EXT_CTRL);
ectrl &= ~(PHY_M_EC_M_DSC_MSK | PHY_M_EC_S_DSC_MSK |
PHY_M_EC_MAC_S_MSK);
ectrl |= PHY_M_EC_MAC_S(MAC_TX_CLK_25_MHZ);
/* on PHY 88E1040 Rev.D0 (and newer) downshift control changed */
if (hw->chip_id == CHIP_ID_YUKON_EC)
/* set downshift counter to 3x and enable downshift */
ectrl |= PHY_M_EC_DSC_2(2) | PHY_M_EC_DOWN_S_ENA;
else
/* set master & slave downshift counter to 1x */
ectrl |= PHY_M_EC_M_DSC(0) | PHY_M_EC_S_DSC(1);
gm_phy_write(hw, port, PHY_MARV_EXT_CTRL, ectrl);
}
ctrl = gm_phy_read(hw, port, PHY_MARV_PHY_CTRL);
if (sky2_is_copper(hw)) {
if (!(hw->flags & SKY2_HW_GIGABIT)) {
/* enable automatic crossover */
ctrl |= PHY_M_PC_MDI_XMODE(PHY_M_PC_ENA_AUTO) >> 1;
if (hw->chip_id == CHIP_ID_YUKON_FE_P &&
hw->chip_rev == CHIP_REV_YU_FE2_A0) {
u16 spec;
/* Enable Class A driver for FE+ A0 */
spec = gm_phy_read(hw, port, PHY_MARV_FE_SPEC_2);
spec |= PHY_M_FESC_SEL_CL_A;
gm_phy_write(hw, port, PHY_MARV_FE_SPEC_2, spec);
}
} else {
/* disable energy detect */
ctrl &= ~PHY_M_PC_EN_DET_MSK;
/* enable automatic crossover */
ctrl |= PHY_M_PC_MDI_XMODE(PHY_M_PC_ENA_AUTO);
/* downshift on PHY 88E1112 and 88E1149 is changed */
if ( (sky2->flags & SKY2_FLAG_AUTO_SPEED) &&
(hw->flags & SKY2_HW_NEWER_PHY)) {
/* set downshift counter to 3x and enable downshift */
ctrl &= ~PHY_M_PC_DSC_MSK;
ctrl |= PHY_M_PC_DSC(2) | PHY_M_PC_DOWN_S_ENA;
}
}
} else {
/* workaround for deviation #4.88 (CRC errors) */
/* disable Automatic Crossover */
ctrl &= ~PHY_M_PC_MDIX_MSK;
}
gm_phy_write(hw, port, PHY_MARV_PHY_CTRL, ctrl);
/* special setup for PHY 88E1112 Fiber */
if (hw->chip_id == CHIP_ID_YUKON_XL && (hw->flags & SKY2_HW_FIBRE_PHY)) {
pg = gm_phy_read(hw, port, PHY_MARV_EXT_ADR);
/* Fiber: select 1000BASE-X only mode MAC Specific Ctrl Reg. */
gm_phy_write(hw, port, PHY_MARV_EXT_ADR, 2);
ctrl = gm_phy_read(hw, port, PHY_MARV_PHY_CTRL);
ctrl &= ~PHY_M_MAC_MD_MSK;
ctrl |= PHY_M_MAC_MODE_SEL(PHY_M_MAC_MD_1000BX);
gm_phy_write(hw, port, PHY_MARV_PHY_CTRL, ctrl);
if (hw->pmd_type == 'P') {
/* select page 1 to access Fiber registers */
gm_phy_write(hw, port, PHY_MARV_EXT_ADR, 1);
/* for SFP-module set SIGDET polarity to low */
ctrl = gm_phy_read(hw, port, PHY_MARV_PHY_CTRL);
ctrl |= PHY_M_FIB_SIGD_POL;
gm_phy_write(hw, port, PHY_MARV_PHY_CTRL, ctrl);
}
gm_phy_write(hw, port, PHY_MARV_EXT_ADR, pg);
}
ctrl = PHY_CT_RESET;
ct1000 = 0;
adv = PHY_AN_CSMA;
reg = 0;
if (sky2->flags & SKY2_FLAG_AUTO_SPEED) {
if (sky2_is_copper(hw)) {
if (sky2->advertising & ADVERTISED_1000baseT_Full)
ct1000 |= PHY_M_1000C_AFD;
if (sky2->advertising & ADVERTISED_1000baseT_Half)
ct1000 |= PHY_M_1000C_AHD;
if (sky2->advertising & ADVERTISED_100baseT_Full)
adv |= PHY_M_AN_100_FD;
if (sky2->advertising & ADVERTISED_100baseT_Half)
adv |= PHY_M_AN_100_HD;
if (sky2->advertising & ADVERTISED_10baseT_Full)
adv |= PHY_M_AN_10_FD;
if (sky2->advertising & ADVERTISED_10baseT_Half)
adv |= PHY_M_AN_10_HD;
} else { /* special defines for FIBER (88E1040S only) */
if (sky2->advertising & ADVERTISED_1000baseT_Full)
adv |= PHY_M_AN_1000X_AFD;
if (sky2->advertising & ADVERTISED_1000baseT_Half)
adv |= PHY_M_AN_1000X_AHD;
}
/* Restart Auto-negotiation */
ctrl |= PHY_CT_ANE | PHY_CT_RE_CFG;
} else {
/* forced speed/duplex settings */
ct1000 = PHY_M_1000C_MSE;
/* Disable auto update for duplex flow control and duplex */
reg |= GM_GPCR_AU_DUP_DIS | GM_GPCR_AU_SPD_DIS;
switch (sky2->speed) {
case SPEED_1000:
ctrl |= PHY_CT_SP1000;
reg |= GM_GPCR_SPEED_1000;
break;
case SPEED_100:
ctrl |= PHY_CT_SP100;
reg |= GM_GPCR_SPEED_100;
break;
}
if (sky2->duplex == DUPLEX_FULL) {
reg |= GM_GPCR_DUP_FULL;
ctrl |= PHY_CT_DUP_MD;
} else if (sky2->speed < SPEED_1000)
sky2->flow_mode = FC_NONE;
}
if (sky2->flags & SKY2_FLAG_AUTO_PAUSE) {
if (sky2_is_copper(hw))
adv |= copper_fc_adv[sky2->flow_mode];
else
adv |= fiber_fc_adv[sky2->flow_mode];
} else {
reg |= GM_GPCR_AU_FCT_DIS;
reg |= gm_fc_disable[sky2->flow_mode];
/* Forward pause packets to GMAC? */
if (sky2->flow_mode & FC_RX)
sky2_write8(hw, SK_REG(port, GMAC_CTRL), GMC_PAUSE_ON);
else
sky2_write8(hw, SK_REG(port, GMAC_CTRL), GMC_PAUSE_OFF);
}
gma_write16(hw, port, GM_GP_CTRL, reg);
if (hw->flags & SKY2_HW_GIGABIT)
gm_phy_write(hw, port, PHY_MARV_1000T_CTRL, ct1000);
gm_phy_write(hw, port, PHY_MARV_AUNE_ADV, adv);
gm_phy_write(hw, port, PHY_MARV_CTRL, ctrl);
/* Setup Phy LED's */
ledctrl = PHY_M_LED_PULS_DUR(PULS_170MS);
ledover = 0;
switch (hw->chip_id) {
case CHIP_ID_YUKON_FE:
/* on 88E3082 these bits are at 11..9 (shifted left) */
ledctrl |= PHY_M_LED_BLINK_RT(BLINK_84MS) << 1;
ctrl = gm_phy_read(hw, port, PHY_MARV_FE_LED_PAR);
/* delete ACT LED control bits */
ctrl &= ~PHY_M_FELP_LED1_MSK;
/* change ACT LED control to blink mode */
ctrl |= PHY_M_FELP_LED1_CTRL(LED_PAR_CTRL_ACT_BL);
gm_phy_write(hw, port, PHY_MARV_FE_LED_PAR, ctrl);
break;
case CHIP_ID_YUKON_FE_P:
/* Enable Link Partner Next Page */
ctrl = gm_phy_read(hw, port, PHY_MARV_PHY_CTRL);
ctrl |= PHY_M_PC_ENA_LIP_NP;
/* disable Energy Detect and enable scrambler */
ctrl &= ~(PHY_M_PC_ENA_ENE_DT | PHY_M_PC_DIS_SCRAMB);
gm_phy_write(hw, port, PHY_MARV_PHY_CTRL, ctrl);
/* set LED2 -> ACT, LED1 -> LINK, LED0 -> SPEED */
ctrl = PHY_M_FELP_LED2_CTRL(LED_PAR_CTRL_ACT_BL) |
PHY_M_FELP_LED1_CTRL(LED_PAR_CTRL_LINK) |
PHY_M_FELP_LED0_CTRL(LED_PAR_CTRL_SPEED);
gm_phy_write(hw, port, PHY_MARV_FE_LED_PAR, ctrl);
break;
case CHIP_ID_YUKON_XL:
pg = gm_phy_read(hw, port, PHY_MARV_EXT_ADR);
/* select page 3 to access LED control register */
gm_phy_write(hw, port, PHY_MARV_EXT_ADR, 3);
/* set LED Function Control register */
gm_phy_write(hw, port, PHY_MARV_PHY_CTRL,
(PHY_M_LEDC_LOS_CTRL(1) | /* LINK/ACT */
PHY_M_LEDC_INIT_CTRL(7) | /* 10 Mbps */
PHY_M_LEDC_STA1_CTRL(7) | /* 100 Mbps */
PHY_M_LEDC_STA0_CTRL(7))); /* 1000 Mbps */
/* set Polarity Control register */
gm_phy_write(hw, port, PHY_MARV_PHY_STAT,
(PHY_M_POLC_LS1_P_MIX(4) |
PHY_M_POLC_IS0_P_MIX(4) |
PHY_M_POLC_LOS_CTRL(2) |
PHY_M_POLC_INIT_CTRL(2) |
PHY_M_POLC_STA1_CTRL(2) |
PHY_M_POLC_STA0_CTRL(2)));
/* restore page register */
gm_phy_write(hw, port, PHY_MARV_EXT_ADR, pg);
break;
case CHIP_ID_YUKON_EC_U:
case CHIP_ID_YUKON_EX:
case CHIP_ID_YUKON_SUPR:
pg = gm_phy_read(hw, port, PHY_MARV_EXT_ADR);
/* select page 3 to access LED control register */
gm_phy_write(hw, port, PHY_MARV_EXT_ADR, 3);
/* set LED Function Control register */
gm_phy_write(hw, port, PHY_MARV_PHY_CTRL,
(PHY_M_LEDC_LOS_CTRL(1) | /* LINK/ACT */
PHY_M_LEDC_INIT_CTRL(8) | /* 10 Mbps */
PHY_M_LEDC_STA1_CTRL(7) | /* 100 Mbps */
PHY_M_LEDC_STA0_CTRL(7)));/* 1000 Mbps */
/* set Blink Rate in LED Timer Control Register */
gm_phy_write(hw, port, PHY_MARV_INT_MASK,
ledctrl | PHY_M_LED_BLINK_RT(BLINK_84MS));
/* restore page register */
gm_phy_write(hw, port, PHY_MARV_EXT_ADR, pg);
break;
default:
/* set Tx LED (LED_TX) to blink mode on Rx OR Tx activity */
ledctrl |= PHY_M_LED_BLINK_RT(BLINK_84MS) | PHY_M_LEDC_TX_CTRL;
/* turn off the Rx LED (LED_RX) */
ledover |= PHY_M_LED_MO_RX(MO_LED_OFF);
}
if (hw->chip_id == CHIP_ID_YUKON_EC_U || hw->chip_id == CHIP_ID_YUKON_UL_2) {
/* apply fixes in PHY AFE */
gm_phy_write(hw, port, PHY_MARV_EXT_ADR, 255);
/* increase differential signal amplitude in 10BASE-T */
gm_phy_write(hw, port, 0x18, 0xaa99);
gm_phy_write(hw, port, 0x17, 0x2011);
if (hw->chip_id == CHIP_ID_YUKON_EC_U) {
/* fix for IEEE A/B Symmetry failure in 1000BASE-T */
gm_phy_write(hw, port, 0x18, 0xa204);
gm_phy_write(hw, port, 0x17, 0x2002);
}
/* set page register to 0 */
gm_phy_write(hw, port, PHY_MARV_EXT_ADR, 0);
} else if (hw->chip_id == CHIP_ID_YUKON_FE_P &&
hw->chip_rev == CHIP_REV_YU_FE2_A0) {
/* apply workaround for integrated resistors calibration */
gm_phy_write(hw, port, PHY_MARV_PAGE_ADDR, 17);
gm_phy_write(hw, port, PHY_MARV_PAGE_DATA, 0x3f60);
} else if (hw->chip_id == CHIP_ID_YUKON_OPT && hw->chip_rev == 0) {
/* apply fixes in PHY AFE */
gm_phy_write(hw, port, PHY_MARV_EXT_ADR, 0x00ff);
/* apply RDAC termination workaround */
gm_phy_write(hw, port, 24, 0x2800);
gm_phy_write(hw, port, 23, 0x2001);
/* set page register back to 0 */
gm_phy_write(hw, port, PHY_MARV_EXT_ADR, 0);
} else if (hw->chip_id != CHIP_ID_YUKON_EX &&
hw->chip_id < CHIP_ID_YUKON_SUPR) {
/* no effect on Yukon-XL */
gm_phy_write(hw, port, PHY_MARV_LED_CTRL, ledctrl);
if (!(sky2->flags & SKY2_FLAG_AUTO_SPEED) ||
sky2->speed == SPEED_100) {
/* turn on 100 Mbps LED (LED_LINK100) */
ledover |= PHY_M_LED_MO_100(MO_LED_ON);
}
if (ledover)
gm_phy_write(hw, port, PHY_MARV_LED_OVER, ledover);
} else if (hw->chip_id == CHIP_ID_YUKON_PRM &&
(sky2_read8(hw, B2_MAC_CFG) & 0xf) == 0x7) {
int i;
/* This a phy register setup workaround copied from vendor driver. */
static const struct {
u16 reg, val;
} eee_afe[] = {
{ 0x156, 0x58ce },
{ 0x153, 0x99eb },
{ 0x141, 0x8064 },
/* { 0x155, 0x130b },*/
{ 0x000, 0x0000 },
{ 0x151, 0x8433 },
{ 0x14b, 0x8c44 },
{ 0x14c, 0x0f90 },
{ 0x14f, 0x39aa },
/* { 0x154, 0x2f39 },*/
{ 0x14d, 0xba33 },
{ 0x144, 0x0048 },
{ 0x152, 0x2010 },
/* { 0x158, 0x1223 },*/
{ 0x140, 0x4444 },
{ 0x154, 0x2f3b },
{ 0x158, 0xb203 },
{ 0x157, 0x2029 },
};
/* Start Workaround for OptimaEEE Rev.Z0 */
gm_phy_write(hw, port, PHY_MARV_EXT_ADR, 0x00fb);
gm_phy_write(hw, port, 1, 0x4099);
gm_phy_write(hw, port, 3, 0x1120);
gm_phy_write(hw, port, 11, 0x113c);
gm_phy_write(hw, port, 14, 0x8100);
gm_phy_write(hw, port, 15, 0x112a);
gm_phy_write(hw, port, 17, 0x1008);
gm_phy_write(hw, port, PHY_MARV_EXT_ADR, 0x00fc);
gm_phy_write(hw, port, 1, 0x20b0);
gm_phy_write(hw, port, PHY_MARV_EXT_ADR, 0x00ff);
for (i = 0; i < ARRAY_SIZE(eee_afe); i++) {
/* apply AFE settings */
gm_phy_write(hw, port, 17, eee_afe[i].val);
gm_phy_write(hw, port, 16, eee_afe[i].reg | 1u<<13);
}
/* End Workaround for OptimaEEE */
gm_phy_write(hw, port, PHY_MARV_EXT_ADR, 0);
/* Enable 10Base-Te (EEE) */
if (hw->chip_id >= CHIP_ID_YUKON_PRM) {
reg = gm_phy_read(hw, port, PHY_MARV_EXT_CTRL);
gm_phy_write(hw, port, PHY_MARV_EXT_CTRL,
reg | PHY_M_10B_TE_ENABLE);
}
}
/* Enable phy interrupt on auto-negotiation complete (or link up) */
if (sky2->flags & SKY2_FLAG_AUTO_SPEED)
gm_phy_write(hw, port, PHY_MARV_INT_MASK, PHY_M_IS_AN_COMPL);
else
gm_phy_write(hw, port, PHY_MARV_INT_MASK, PHY_M_DEF_MSK);
}
static const u32 phy_power[] = { PCI_Y2_PHY1_POWD, PCI_Y2_PHY2_POWD };
static const u32 coma_mode[] = { PCI_Y2_PHY1_COMA, PCI_Y2_PHY2_COMA };
static void sky2_phy_power_up(struct sky2_hw *hw, unsigned port)
{
u32 reg1;
sky2_write8(hw, B2_TST_CTRL1, TST_CFG_WRITE_ON);
reg1 = sky2_pci_read32(hw, PCI_DEV_REG1);
reg1 &= ~phy_power[port];
if (hw->chip_id == CHIP_ID_YUKON_XL && hw->chip_rev > CHIP_REV_YU_XL_A1)
reg1 |= coma_mode[port];
sky2_pci_write32(hw, PCI_DEV_REG1, reg1);
sky2_write8(hw, B2_TST_CTRL1, TST_CFG_WRITE_OFF);
sky2_pci_read32(hw, PCI_DEV_REG1);
if (hw->chip_id == CHIP_ID_YUKON_FE)
gm_phy_write(hw, port, PHY_MARV_CTRL, PHY_CT_ANE);
else if (hw->flags & SKY2_HW_ADV_POWER_CTL)
sky2_write8(hw, SK_REG(port, GPHY_CTRL), GPC_RST_CLR);
}
static void sky2_phy_power_down(struct sky2_hw *hw, unsigned port)
{
u32 reg1;
u16 ctrl;
/* release GPHY Control reset */
sky2_write8(hw, SK_REG(port, GPHY_CTRL), GPC_RST_CLR);
/* release GMAC reset */
sky2_write8(hw, SK_REG(port, GMAC_CTRL), GMC_RST_CLR);
if (hw->flags & SKY2_HW_NEWER_PHY) {
/* select page 2 to access MAC control register */
gm_phy_write(hw, port, PHY_MARV_EXT_ADR, 2);
ctrl = gm_phy_read(hw, port, PHY_MARV_PHY_CTRL);
/* allow GMII Power Down */
ctrl &= ~PHY_M_MAC_GMIF_PUP;
gm_phy_write(hw, port, PHY_MARV_PHY_CTRL, ctrl);
/* set page register back to 0 */
gm_phy_write(hw, port, PHY_MARV_EXT_ADR, 0);
}
/* setup General Purpose Control Register */
gma_write16(hw, port, GM_GP_CTRL,
GM_GPCR_FL_PASS | GM_GPCR_SPEED_100 |
GM_GPCR_AU_DUP_DIS | GM_GPCR_AU_FCT_DIS |
GM_GPCR_AU_SPD_DIS);
if (hw->chip_id != CHIP_ID_YUKON_EC) {
if (hw->chip_id == CHIP_ID_YUKON_EC_U) {
/* select page 2 to access MAC control register */
gm_phy_write(hw, port, PHY_MARV_EXT_ADR, 2);
ctrl = gm_phy_read(hw, port, PHY_MARV_PHY_CTRL);
/* enable Power Down */
ctrl |= PHY_M_PC_POW_D_ENA;
gm_phy_write(hw, port, PHY_MARV_PHY_CTRL, ctrl);
/* set page register back to 0 */
gm_phy_write(hw, port, PHY_MARV_EXT_ADR, 0);
}
/* set IEEE compatible Power Down Mode (dev. #4.99) */
gm_phy_write(hw, port, PHY_MARV_CTRL, PHY_CT_PDOWN);
}
sky2_write8(hw, B2_TST_CTRL1, TST_CFG_WRITE_ON);
reg1 = sky2_pci_read32(hw, PCI_DEV_REG1);
reg1 |= phy_power[port]; /* set PHY to PowerDown/COMA Mode */
sky2_pci_write32(hw, PCI_DEV_REG1, reg1);
sky2_write8(hw, B2_TST_CTRL1, TST_CFG_WRITE_OFF);
}
/* configure IPG according to used link speed */
static void sky2_set_ipg(struct sky2_port *sky2)
{
u16 reg;
reg = gma_read16(sky2->hw, sky2->port, GM_SERIAL_MODE);
reg &= ~GM_SMOD_IPG_MSK;
if (sky2->speed > SPEED_100)
reg |= IPG_DATA_VAL(IPG_DATA_DEF_1000);
else
reg |= IPG_DATA_VAL(IPG_DATA_DEF_10_100);
gma_write16(sky2->hw, sky2->port, GM_SERIAL_MODE, reg);
}
/* Enable Rx/Tx */
static void sky2_enable_rx_tx(struct sky2_port *sky2)
{
struct sky2_hw *hw = sky2->hw;
unsigned port = sky2->port;
u16 reg;
reg = gma_read16(hw, port, GM_GP_CTRL);
reg |= GM_GPCR_RX_ENA | GM_GPCR_TX_ENA;
gma_write16(hw, port, GM_GP_CTRL, reg);
}
/* Force a renegotiation */
static void sky2_phy_reinit(struct sky2_port *sky2)
{
spin_lock_bh(&sky2->phy_lock);
sky2_phy_init(sky2->hw, sky2->port);
sky2_enable_rx_tx(sky2);
spin_unlock_bh(&sky2->phy_lock);
}
/* Put device in state to listen for Wake On Lan */
static void sky2_wol_init(struct sky2_port *sky2)
{
struct sky2_hw *hw = sky2->hw;
unsigned port = sky2->port;
enum flow_control save_mode;
u16 ctrl;
/* Bring hardware out of reset */
sky2_write16(hw, B0_CTST, CS_RST_CLR);
sky2_write16(hw, SK_REG(port, GMAC_LINK_CTRL), GMLC_RST_CLR);
sky2_write8(hw, SK_REG(port, GPHY_CTRL), GPC_RST_CLR);
sky2_write8(hw, SK_REG(port, GMAC_CTRL), GMC_RST_CLR);
/* Force to 10/100
* sky2_reset will re-enable on resume
*/
save_mode = sky2->flow_mode;
ctrl = sky2->advertising;
sky2->advertising &= ~(ADVERTISED_1000baseT_Half|ADVERTISED_1000baseT_Full);
sky2->flow_mode = FC_NONE;
spin_lock_bh(&sky2->phy_lock);
sky2_phy_power_up(hw, port);
sky2_phy_init(hw, port);
spin_unlock_bh(&sky2->phy_lock);
sky2->flow_mode = save_mode;
sky2->advertising = ctrl;
/* Set GMAC to no flow control and auto update for speed/duplex */
gma_write16(hw, port, GM_GP_CTRL,
GM_GPCR_FC_TX_DIS|GM_GPCR_TX_ENA|GM_GPCR_RX_ENA|
GM_GPCR_DUP_FULL|GM_GPCR_FC_RX_DIS|GM_GPCR_AU_FCT_DIS);
/* Set WOL address */
memcpy_toio(hw->regs + WOL_REGS(port, WOL_MAC_ADDR),
sky2->netdev->dev_addr, ETH_ALEN);
/* Turn on appropriate WOL control bits */
sky2_write16(hw, WOL_REGS(port, WOL_CTRL_STAT), WOL_CTL_CLEAR_RESULT);
ctrl = 0;
if (sky2->wol & WAKE_PHY)
ctrl |= WOL_CTL_ENA_PME_ON_LINK_CHG|WOL_CTL_ENA_LINK_CHG_UNIT;
else
ctrl |= WOL_CTL_DIS_PME_ON_LINK_CHG|WOL_CTL_DIS_LINK_CHG_UNIT;
if (sky2->wol & WAKE_MAGIC)
ctrl |= WOL_CTL_ENA_PME_ON_MAGIC_PKT|WOL_CTL_ENA_MAGIC_PKT_UNIT;
else
ctrl |= WOL_CTL_DIS_PME_ON_MAGIC_PKT|WOL_CTL_DIS_MAGIC_PKT_UNIT;
ctrl |= WOL_CTL_DIS_PME_ON_PATTERN|WOL_CTL_DIS_PATTERN_UNIT;
sky2_write16(hw, WOL_REGS(port, WOL_CTRL_STAT), ctrl);
/* Disable PiG firmware */
sky2_write16(hw, B0_CTST, Y2_HW_WOL_OFF);
/* Needed by some broken BIOSes, use PCI rather than PCI-e for WOL */
if (legacy_pme) {
u32 reg1 = sky2_pci_read32(hw, PCI_DEV_REG1);
reg1 |= PCI_Y2_PME_LEGACY;
sky2_pci_write32(hw, PCI_DEV_REG1, reg1);
}
/* block receiver */
sky2_write8(hw, SK_REG(port, RX_GMF_CTRL_T), GMF_RST_SET);
sky2_read32(hw, B0_CTST);
}
static void sky2_set_tx_stfwd(struct sky2_hw *hw, unsigned port)
{
struct net_device *dev = hw->dev[port];
if ( (hw->chip_id == CHIP_ID_YUKON_EX &&
hw->chip_rev != CHIP_REV_YU_EX_A0) ||
hw->chip_id >= CHIP_ID_YUKON_FE_P) {
/* Yukon-Extreme B0 and further Extreme devices */
sky2_write32(hw, SK_REG(port, TX_GMF_CTRL_T), TX_STFW_ENA);
} else if (dev->mtu > ETH_DATA_LEN) {
/* set Tx GMAC FIFO Almost Empty Threshold */
sky2_write32(hw, SK_REG(port, TX_GMF_AE_THR),
(ECU_JUMBO_WM << 16) | ECU_AE_THR);
sky2_write32(hw, SK_REG(port, TX_GMF_CTRL_T), TX_STFW_DIS);
} else
sky2_write32(hw, SK_REG(port, TX_GMF_CTRL_T), TX_STFW_ENA);
}
static void sky2_mac_init(struct sky2_hw *hw, unsigned port)
{
struct sky2_port *sky2 = netdev_priv(hw->dev[port]);
u16 reg;
u32 rx_reg;
int i;
const u8 *addr = hw->dev[port]->dev_addr;
sky2_write8(hw, SK_REG(port, GPHY_CTRL), GPC_RST_SET);
sky2_write8(hw, SK_REG(port, GPHY_CTRL), GPC_RST_CLR);
sky2_write8(hw, SK_REG(port, GMAC_CTRL), GMC_RST_CLR);
if (hw->chip_id == CHIP_ID_YUKON_XL &&
hw->chip_rev == CHIP_REV_YU_XL_A0 &&
port == 1) {
/* WA DEV_472 -- looks like crossed wires on port 2 */
/* clear GMAC 1 Control reset */
sky2_write8(hw, SK_REG(0, GMAC_CTRL), GMC_RST_CLR);
do {
sky2_write8(hw, SK_REG(1, GMAC_CTRL), GMC_RST_SET);
sky2_write8(hw, SK_REG(1, GMAC_CTRL), GMC_RST_CLR);
} while (gm_phy_read(hw, 1, PHY_MARV_ID0) != PHY_MARV_ID0_VAL ||
gm_phy_read(hw, 1, PHY_MARV_ID1) != PHY_MARV_ID1_Y2 ||
gm_phy_read(hw, 1, PHY_MARV_INT_MASK) != 0);
}
sky2_read16(hw, SK_REG(port, GMAC_IRQ_SRC));
/* Enable Transmit FIFO Underrun */
sky2_write8(hw, SK_REG(port, GMAC_IRQ_MSK), GMAC_DEF_MSK);
spin_lock_bh(&sky2->phy_lock);
sky2_phy_power_up(hw, port);
sky2_phy_init(hw, port);
spin_unlock_bh(&sky2->phy_lock);
/* MIB clear */
reg = gma_read16(hw, port, GM_PHY_ADDR);
gma_write16(hw, port, GM_PHY_ADDR, reg | GM_PAR_MIB_CLR);
for (i = GM_MIB_CNT_BASE; i <= GM_MIB_CNT_END; i += 4)
gma_read16(hw, port, i);
gma_write16(hw, port, GM_PHY_ADDR, reg);
/* transmit control */
gma_write16(hw, port, GM_TX_CTRL, TX_COL_THR(TX_COL_DEF));
/* receive control reg: unicast + multicast + no FCS */
gma_write16(hw, port, GM_RX_CTRL,
GM_RXCR_UCF_ENA | GM_RXCR_CRC_DIS | GM_RXCR_MCF_ENA);
/* transmit flow control */
gma_write16(hw, port, GM_TX_FLOW_CTRL, 0xffff);
/* transmit parameter */
gma_write16(hw, port, GM_TX_PARAM,
TX_JAM_LEN_VAL(TX_JAM_LEN_DEF) |
TX_JAM_IPG_VAL(TX_JAM_IPG_DEF) |
TX_IPG_JAM_DATA(TX_IPG_JAM_DEF) |
TX_BACK_OFF_LIM(TX_BOF_LIM_DEF));
/* serial mode register */
reg = DATA_BLIND_VAL(DATA_BLIND_DEF) |
GM_SMOD_VLAN_ENA | IPG_DATA_VAL(IPG_DATA_DEF_1000);
if (hw->dev[port]->mtu > ETH_DATA_LEN)
reg |= GM_SMOD_JUMBO_ENA;
if (hw->chip_id == CHIP_ID_YUKON_EC_U &&
hw->chip_rev == CHIP_REV_YU_EC_U_B1)
reg |= GM_NEW_FLOW_CTRL;
gma_write16(hw, port, GM_SERIAL_MODE, reg);
/* virtual address for data */
gma_set_addr(hw, port, GM_SRC_ADDR_2L, addr);
/* physical address: used for pause frames */
gma_set_addr(hw, port, GM_SRC_ADDR_1L, addr);
/* ignore counter overflows */
gma_write16(hw, port, GM_TX_IRQ_MSK, 0);
gma_write16(hw, port, GM_RX_IRQ_MSK, 0);
gma_write16(hw, port, GM_TR_IRQ_MSK, 0);
/* Configure Rx MAC FIFO */
sky2_write8(hw, SK_REG(port, RX_GMF_CTRL_T), GMF_RST_CLR);
rx_reg = GMF_OPER_ON | GMF_RX_F_FL_ON;
if (hw->chip_id == CHIP_ID_YUKON_EX ||
hw->chip_id == CHIP_ID_YUKON_FE_P)
rx_reg |= GMF_RX_OVER_ON;
sky2_write32(hw, SK_REG(port, RX_GMF_CTRL_T), rx_reg);
if (hw->chip_id == CHIP_ID_YUKON_XL) {
/* Hardware errata - clear flush mask */
sky2_write16(hw, SK_REG(port, RX_GMF_FL_MSK), 0);
} else {
/* Flush Rx MAC FIFO on any flow control or error */
sky2_write16(hw, SK_REG(port, RX_GMF_FL_MSK), GMR_FS_ANY_ERR);
}
/* Set threshold to 0xa (64 bytes) + 1 to workaround pause bug */
reg = RX_GMF_FL_THR_DEF + 1;
/* Another magic mystery workaround from sk98lin */
if (hw->chip_id == CHIP_ID_YUKON_FE_P &&
hw->chip_rev == CHIP_REV_YU_FE2_A0)
reg = 0x178;
sky2_write16(hw, SK_REG(port, RX_GMF_FL_THR), reg);
/* Configure Tx MAC FIFO */
sky2_write8(hw, SK_REG(port, TX_GMF_CTRL_T), GMF_RST_CLR);
sky2_write16(hw, SK_REG(port, TX_GMF_CTRL_T), GMF_OPER_ON);
/* On chips without ram buffer, pause is controlled by MAC level */
if (!(hw->flags & SKY2_HW_RAM_BUFFER)) {
/* Pause threshold is scaled by 8 in bytes */
if (hw->chip_id == CHIP_ID_YUKON_FE_P &&
hw->chip_rev == CHIP_REV_YU_FE2_A0)
reg = 1568 / 8;
else
reg = 1024 / 8;
sky2_write16(hw, SK_REG(port, RX_GMF_UP_THR), reg);
sky2_write16(hw, SK_REG(port, RX_GMF_LP_THR), 768 / 8);
sky2_set_tx_stfwd(hw, port);
}
if (hw->chip_id == CHIP_ID_YUKON_FE_P &&
hw->chip_rev == CHIP_REV_YU_FE2_A0) {
/* disable dynamic watermark */
reg = sky2_read16(hw, SK_REG(port, TX_GMF_EA));
reg &= ~TX_DYN_WM_ENA;
sky2_write16(hw, SK_REG(port, TX_GMF_EA), reg);
}
}
/* Assign Ram Buffer allocation to queue */
static void sky2_ramset(struct sky2_hw *hw, u16 q, u32 start, u32 space)
{
u32 end;
/* convert from K bytes to qwords used for hw register */
start *= 1024/8;
space *= 1024/8;
end = start + space - 1;
sky2_write8(hw, RB_ADDR(q, RB_CTRL), RB_RST_CLR);
sky2_write32(hw, RB_ADDR(q, RB_START), start);
sky2_write32(hw, RB_ADDR(q, RB_END), end);
sky2_write32(hw, RB_ADDR(q, RB_WP), start);
sky2_write32(hw, RB_ADDR(q, RB_RP), start);
if (q == Q_R1 || q == Q_R2) {
u32 tp = space - space/4;
/* On receive queue's set the thresholds
* give receiver priority when > 3/4 full
* send pause when down to 2K
*/
sky2_write32(hw, RB_ADDR(q, RB_RX_UTHP), tp);
sky2_write32(hw, RB_ADDR(q, RB_RX_LTHP), space/2);
tp = space - 8192/8;
sky2_write32(hw, RB_ADDR(q, RB_RX_UTPP), tp);
sky2_write32(hw, RB_ADDR(q, RB_RX_LTPP), space/4);
} else {
/* Enable store & forward on Tx queue's because
* Tx FIFO is only 1K on Yukon
*/
sky2_write8(hw, RB_ADDR(q, RB_CTRL), RB_ENA_STFWD);
}
sky2_write8(hw, RB_ADDR(q, RB_CTRL), RB_ENA_OP_MD);
sky2_read8(hw, RB_ADDR(q, RB_CTRL));
}
/* Setup Bus Memory Interface */
static void sky2_qset(struct sky2_hw *hw, u16 q)
{
sky2_write32(hw, Q_ADDR(q, Q_CSR), BMU_CLR_RESET);
sky2_write32(hw, Q_ADDR(q, Q_CSR), BMU_OPER_INIT);
sky2_write32(hw, Q_ADDR(q, Q_CSR), BMU_FIFO_OP_ON);
sky2_write32(hw, Q_ADDR(q, Q_WM), BMU_WM_DEFAULT);
}
/* Setup prefetch unit registers. This is the interface between
* hardware and driver list elements
*/
static void sky2_prefetch_init(struct sky2_hw *hw, u32 qaddr,
dma_addr_t addr, u32 last)
{
sky2_write32(hw, Y2_QADDR(qaddr, PREF_UNIT_CTRL), PREF_UNIT_RST_SET);
sky2_write32(hw, Y2_QADDR(qaddr, PREF_UNIT_CTRL), PREF_UNIT_RST_CLR);
sky2_write32(hw, Y2_QADDR(qaddr, PREF_UNIT_ADDR_HI), upper_32_bits(addr));
sky2_write32(hw, Y2_QADDR(qaddr, PREF_UNIT_ADDR_LO), lower_32_bits(addr));
sky2_write16(hw, Y2_QADDR(qaddr, PREF_UNIT_LAST_IDX), last);
sky2_write32(hw, Y2_QADDR(qaddr, PREF_UNIT_CTRL), PREF_UNIT_OP_ON);
sky2_read32(hw, Y2_QADDR(qaddr, PREF_UNIT_CTRL));
}
static inline struct sky2_tx_le *get_tx_le(struct sky2_port *sky2, u16 *slot)
{
struct sky2_tx_le *le = sky2->tx_le + *slot;
*slot = RING_NEXT(*slot, sky2->tx_ring_size);
le->ctrl = 0;
return le;
}
static void tx_init(struct sky2_port *sky2)
{
struct sky2_tx_le *le;
sky2->tx_prod = sky2->tx_cons = 0;
sky2->tx_tcpsum = 0;
sky2->tx_last_mss = 0;
netdev_reset_queue(sky2->netdev);
le = get_tx_le(sky2, &sky2->tx_prod);
le->addr = 0;
le->opcode = OP_ADDR64 | HW_OWNER;
sky2->tx_last_upper = 0;
}
/* Update chip's next pointer */
static inline void sky2_put_idx(struct sky2_hw *hw, unsigned q, u16 idx)
{
/* Make sure write' to descriptors are complete before we tell hardware */
wmb();
sky2_write16(hw, Y2_QADDR(q, PREF_UNIT_PUT_IDX), idx);
/* Synchronize I/O on since next processor may write to tail */
mmiowb();
}
static inline struct sky2_rx_le *sky2_next_rx(struct sky2_port *sky2)
{
struct sky2_rx_le *le = sky2->rx_le + sky2->rx_put;
sky2->rx_put = RING_NEXT(sky2->rx_put, RX_LE_SIZE);
le->ctrl = 0;
return le;
}
static unsigned sky2_get_rx_threshold(struct sky2_port *sky2)
{
unsigned size;
/* Space needed for frame data + headers rounded up */
size = roundup(sky2->netdev->mtu + ETH_HLEN + VLAN_HLEN, 8);
/* Stopping point for hardware truncation */
return (size - 8) / sizeof(u32);
}
static unsigned sky2_get_rx_data_size(struct sky2_port *sky2)
{
struct rx_ring_info *re;
unsigned size;
/* Space needed for frame data + headers rounded up */
size = roundup(sky2->netdev->mtu + ETH_HLEN + VLAN_HLEN, 8);
sky2->rx_nfrags = size >> PAGE_SHIFT;
BUG_ON(sky2->rx_nfrags > ARRAY_SIZE(re->frag_addr));
/* Compute residue after pages */
size -= sky2->rx_nfrags << PAGE_SHIFT;
/* Optimize to handle small packets and headers */
if (size < copybreak)
size = copybreak;
if (size < ETH_HLEN)
size = ETH_HLEN;
return size;
}
/* Build description to hardware for one receive segment */
static void sky2_rx_add(struct sky2_port *sky2, u8 op,
dma_addr_t map, unsigned len)
{
struct sky2_rx_le *le;
if (sizeof(dma_addr_t) > sizeof(u32)) {
le = sky2_next_rx(sky2);
le->addr = cpu_to_le32(upper_32_bits(map));
le->opcode = OP_ADDR64 | HW_OWNER;
}
le = sky2_next_rx(sky2);
le->addr = cpu_to_le32(lower_32_bits(map));
le->length = cpu_to_le16(len);
le->opcode = op | HW_OWNER;
}
/* Build description to hardware for one possibly fragmented skb */
static void sky2_rx_submit(struct sky2_port *sky2,
const struct rx_ring_info *re)
{
int i;
sky2_rx_add(sky2, OP_PACKET, re->data_addr, sky2->rx_data_size);
for (i = 0; i < skb_shinfo(re->skb)->nr_frags; i++)
sky2_rx_add(sky2, OP_BUFFER, re->frag_addr[i], PAGE_SIZE);
}
static int sky2_rx_map_skb(struct pci_dev *pdev, struct rx_ring_info *re,
unsigned size)
{
struct sk_buff *skb = re->skb;
int i;
re->data_addr = pci_map_single(pdev, skb->data, size, PCI_DMA_FROMDEVICE);
if (pci_dma_mapping_error(pdev, re->data_addr))
goto mapping_error;
dma_unmap_len_set(re, data_size, size);
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
re->frag_addr[i] = skb_frag_dma_map(&pdev->dev, frag, 0,
skb_frag_size(frag),
DMA_FROM_DEVICE);
if (dma_mapping_error(&pdev->dev, re->frag_addr[i]))
goto map_page_error;
}
return 0;
map_page_error:
while (--i >= 0) {
pci_unmap_page(pdev, re->frag_addr[i],
skb_frag_size(&skb_shinfo(skb)->frags[i]),
PCI_DMA_FROMDEVICE);
}
pci_unmap_single(pdev, re->data_addr, dma_unmap_len(re, data_size),
PCI_DMA_FROMDEVICE);
mapping_error:
if (net_ratelimit())
dev_warn(&pdev->dev, "%s: rx mapping error\n",
skb->dev->name);
return -EIO;
}
static void sky2_rx_unmap_skb(struct pci_dev *pdev, struct rx_ring_info *re)
{
struct sk_buff *skb = re->skb;
int i;
pci_unmap_single(pdev, re->data_addr, dma_unmap_len(re, data_size),
PCI_DMA_FROMDEVICE);
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
pci_unmap_page(pdev, re->frag_addr[i],
skb_frag_size(&skb_shinfo(skb)->frags[i]),
PCI_DMA_FROMDEVICE);
}
/* Tell chip where to start receive checksum.
* Actually has two checksums, but set both same to avoid possible byte
* order problems.
*/
static void rx_set_checksum(struct sky2_port *sky2)
{
struct sky2_rx_le *le = sky2_next_rx(sky2);
le->addr = cpu_to_le32((ETH_HLEN << 16) | ETH_HLEN);
le->ctrl = 0;
le->opcode = OP_TCPSTART | HW_OWNER;
sky2_write32(sky2->hw,
Q_ADDR(rxqaddr[sky2->port], Q_CSR),
(sky2->netdev->features & NETIF_F_RXCSUM)
? BMU_ENA_RX_CHKSUM : BMU_DIS_RX_CHKSUM);
}
/*
* Fixed initial key as seed to RSS.
*/
static const uint32_t rss_init_key[10] = {
0x7c3351da, 0x51c5cf4e, 0x44adbdd1, 0xe8d38d18, 0x48897c43,
0xb1d60e7e, 0x6a3dd760, 0x01a2e453, 0x16f46f13, 0x1a0e7b30
};
/* Enable/disable receive hash calculation (RSS) */
static void rx_set_rss(struct net_device *dev, netdev_features_t features)
{
struct sky2_port *sky2 = netdev_priv(dev);
struct sky2_hw *hw = sky2->hw;
int i, nkeys = 4;
/* Supports IPv6 and other modes */
if (hw->flags & SKY2_HW_NEW_LE) {
nkeys = 10;
sky2_write32(hw, SK_REG(sky2->port, RSS_CFG), HASH_ALL);
}
/* Program RSS initial values */
if (features & NETIF_F_RXHASH) {
for (i = 0; i < nkeys; i++)
sky2_write32(hw, SK_REG(sky2->port, RSS_KEY + i * 4),
rss_init_key[i]);
/* Need to turn on (undocumented) flag to make hashing work */
sky2_write32(hw, SK_REG(sky2->port, RX_GMF_CTRL_T),
RX_STFW_ENA);
sky2_write32(hw, Q_ADDR(rxqaddr[sky2->port], Q_CSR),
BMU_ENA_RX_RSS_HASH);
} else
sky2_write32(hw, Q_ADDR(rxqaddr[sky2->port], Q_CSR),
BMU_DIS_RX_RSS_HASH);
}
/*
* The RX Stop command will not work for Yukon-2 if the BMU does not
* reach the end of packet and since we can't make sure that we have
* incoming data, we must reset the BMU while it is not doing a DMA
* transfer. Since it is possible that the RX path is still active,
* the RX RAM buffer will be stopped first, so any possible incoming
* data will not trigger a DMA. After the RAM buffer is stopped, the
* BMU is polled until any DMA in progress is ended and only then it
* will be reset.
*/
static void sky2_rx_stop(struct sky2_port *sky2)
{
struct sky2_hw *hw = sky2->hw;
unsigned rxq = rxqaddr[sky2->port];
int i;
/* disable the RAM Buffer receive queue */
sky2_write8(hw, RB_ADDR(rxq, RB_CTRL), RB_DIS_OP_MD);
for (i = 0; i < 0xffff; i++)
if (sky2_read8(hw, RB_ADDR(rxq, Q_RSL))
== sky2_read8(hw, RB_ADDR(rxq, Q_RL)))
goto stopped;
netdev_warn(sky2->netdev, "receiver stop failed\n");
stopped:
sky2_write32(hw, Q_ADDR(rxq, Q_CSR), BMU_RST_SET | BMU_FIFO_RST);
/* reset the Rx prefetch unit */
sky2_write32(hw, Y2_QADDR(rxq, PREF_UNIT_CTRL), PREF_UNIT_RST_SET);
mmiowb();
}
/* Clean out receive buffer area, assumes receiver hardware stopped */
static void sky2_rx_clean(struct sky2_port *sky2)
{
unsigned i;
memset(sky2->rx_le, 0, RX_LE_BYTES);
for (i = 0; i < sky2->rx_pending; i++) {
struct rx_ring_info *re = sky2->rx_ring + i;
if (re->skb) {
sky2_rx_unmap_skb(sky2->hw->pdev, re);
kfree_skb(re->skb);
re->skb = NULL;
}
}
}
/* Basic MII support */
static int sky2_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
struct mii_ioctl_data *data = if_mii(ifr);
struct sky2_port *sky2 = netdev_priv(dev);
struct sky2_hw *hw = sky2->hw;
int err = -EOPNOTSUPP;
if (!netif_running(dev))
return -ENODEV; /* Phy still in reset */
switch (cmd) {
case SIOCGMIIPHY:
data->phy_id = PHY_ADDR_MARV;
/* fallthru */
case SIOCGMIIREG: {
u16 val = 0;
spin_lock_bh(&sky2->phy_lock);
err = __gm_phy_read(hw, sky2->port, data->reg_num & 0x1f, &val);
spin_unlock_bh(&sky2->phy_lock);
data->val_out = val;
break;
}
case SIOCSMIIREG:
spin_lock_bh(&sky2->phy_lock);
err = gm_phy_write(hw, sky2->port, data->reg_num & 0x1f,
data->val_in);
spin_unlock_bh(&sky2->phy_lock);
break;
}
return err;
}
#define SKY2_VLAN_OFFLOADS (NETIF_F_IP_CSUM | NETIF_F_SG | NETIF_F_TSO)
static void sky2_vlan_mode(struct net_device *dev, netdev_features_t features)
{
struct sky2_port *sky2 = netdev_priv(dev);
struct sky2_hw *hw = sky2->hw;
u16 port = sky2->port;
if (features & NETIF_F_HW_VLAN_CTAG_RX)
sky2_write32(hw, SK_REG(port, RX_GMF_CTRL_T),
RX_VLAN_STRIP_ON);
else
sky2_write32(hw, SK_REG(port, RX_GMF_CTRL_T),
RX_VLAN_STRIP_OFF);
if (features & NETIF_F_HW_VLAN_CTAG_TX) {
sky2_write32(hw, SK_REG(port, TX_GMF_CTRL_T),
TX_VLAN_TAG_ON);
dev->vlan_features |= SKY2_VLAN_OFFLOADS;
} else {
sky2_write32(hw, SK_REG(port, TX_GMF_CTRL_T),
TX_VLAN_TAG_OFF);
/* Can't do transmit offload of vlan without hw vlan */
dev->vlan_features &= ~SKY2_VLAN_OFFLOADS;
}
}
/* Amount of required worst case padding in rx buffer */
static inline unsigned sky2_rx_pad(const struct sky2_hw *hw)
{
return (hw->flags & SKY2_HW_RAM_BUFFER) ? 8 : 2;
}
/*
* Allocate an skb for receiving. If the MTU is large enough
* make the skb non-linear with a fragment list of pages.
*/
static struct sk_buff *sky2_rx_alloc(struct sky2_port *sky2, gfp_t gfp)
{
struct sk_buff *skb;
int i;
skb = __netdev_alloc_skb(sky2->netdev,
sky2->rx_data_size + sky2_rx_pad(sky2->hw),
gfp);
if (!skb)
goto nomem;
if (sky2->hw->flags & SKY2_HW_RAM_BUFFER) {
unsigned char *start;
/*
* Workaround for a bug in FIFO that cause hang
* if the FIFO if the receive buffer is not 64 byte aligned.
* The buffer returned from netdev_alloc_skb is
* aligned except if slab debugging is enabled.
*/
start = PTR_ALIGN(skb->data, 8);
skb_reserve(skb, start - skb->data);
} else
skb_reserve(skb, NET_IP_ALIGN);
for (i = 0; i < sky2->rx_nfrags; i++) {
struct page *page = alloc_page(gfp);
if (!page)
goto free_partial;
skb_fill_page_desc(skb, i, page, 0, PAGE_SIZE);
}
return skb;
free_partial:
kfree_skb(skb);
nomem:
return NULL;
}
static inline void sky2_rx_update(struct sky2_port *sky2, unsigned rxq)
{
sky2_put_idx(sky2->hw, rxq, sky2->rx_put);
}
static int sky2_alloc_rx_skbs(struct sky2_port *sky2)
{
struct sky2_hw *hw = sky2->hw;
unsigned i;
sky2->rx_data_size = sky2_get_rx_data_size(sky2);
/* Fill Rx ring */
for (i = 0; i < sky2->rx_pending; i++) {
struct rx_ring_info *re = sky2->rx_ring + i;
re->skb = sky2_rx_alloc(sky2, GFP_KERNEL);
if (!re->skb)
return -ENOMEM;
if (sky2_rx_map_skb(hw->pdev, re, sky2->rx_data_size)) {
dev_kfree_skb(re->skb);
re->skb = NULL;
return -ENOMEM;
}
}
return 0;
}
/*
* Setup receiver buffer pool.
* Normal case this ends up creating one list element for skb
* in the receive ring. Worst case if using large MTU and each
* allocation falls on a different 64 bit region, that results
* in 6 list elements per ring entry.
* One element is used for checksum enable/disable, and one
* extra to avoid wrap.
*/
static void sky2_rx_start(struct sky2_port *sky2)
{
struct sky2_hw *hw = sky2->hw;
struct rx_ring_info *re;
unsigned rxq = rxqaddr[sky2->port];
unsigned i, thresh;
sky2->rx_put = sky2->rx_next = 0;
sky2_qset(hw, rxq);
/* On PCI express lowering the watermark gives better performance */
if (pci_is_pcie(hw->pdev))
sky2_write32(hw, Q_ADDR(rxq, Q_WM), BMU_WM_PEX);
/* These chips have no ram buffer?
* MAC Rx RAM Read is controlled by hardware */
if (hw->chip_id == CHIP_ID_YUKON_EC_U &&
hw->chip_rev > CHIP_REV_YU_EC_U_A0)
sky2_write32(hw, Q_ADDR(rxq, Q_TEST), F_M_RX_RAM_DIS);
sky2_prefetch_init(hw, rxq, sky2->rx_le_map, RX_LE_SIZE - 1);
if (!(hw->flags & SKY2_HW_NEW_LE))
rx_set_checksum(sky2);
if (!(hw->flags & SKY2_HW_RSS_BROKEN))
rx_set_rss(sky2->netdev, sky2->netdev->features);
/* submit Rx ring */
for (i = 0; i < sky2->rx_pending; i++) {
re = sky2->rx_ring + i;
sky2_rx_submit(sky2, re);
}
/*
* The receiver hangs if it receives frames larger than the
* packet buffer. As a workaround, truncate oversize frames, but
* the register is limited to 9 bits, so if you do frames > 2052
* you better get the MTU right!
*/
thresh = sky2_get_rx_threshold(sky2);
if (thresh > 0x1ff)
sky2_write32(hw, SK_REG(sky2->port, RX_GMF_CTRL_T), RX_TRUNC_OFF);
else {
sky2_write16(hw, SK_REG(sky2->port, RX_GMF_TR_THR), thresh);
sky2_write32(hw, SK_REG(sky2->port, RX_GMF_CTRL_T), RX_TRUNC_ON);
}
/* Tell chip about available buffers */
sky2_rx_update(sky2, rxq);
if (hw->chip_id == CHIP_ID_YUKON_EX ||
hw->chip_id == CHIP_ID_YUKON_SUPR) {
/*
* Disable flushing of non ASF packets;
* must be done after initializing the BMUs;
* drivers without ASF support should do this too, otherwise
* it may happen that they cannot run on ASF devices;
* remember that the MAC FIFO isn't reset during initialization.
*/
sky2_write32(hw, SK_REG(sky2->port, RX_GMF_CTRL_T), RX_MACSEC_FLUSH_OFF);
}
if (hw->chip_id >= CHIP_ID_YUKON_SUPR) {
/* Enable RX Home Address & Routing Header checksum fix */
sky2_write16(hw, SK_REG(sky2->port, RX_GMF_FL_CTRL),
RX_IPV6_SA_MOB_ENA | RX_IPV6_DA_MOB_ENA);
/* Enable TX Home Address & Routing Header checksum fix */
sky2_write32(hw, Q_ADDR(txqaddr[sky2->port], Q_TEST),
TBMU_TEST_HOME_ADD_FIX_EN | TBMU_TEST_ROUTING_ADD_FIX_EN);
}
}
static int sky2_alloc_buffers(struct sky2_port *sky2)
{
struct sky2_hw *hw = sky2->hw;
/* must be power of 2 */
sky2->tx_le = pci_alloc_consistent(hw->pdev,
sky2->tx_ring_size *
sizeof(struct sky2_tx_le),
&sky2->tx_le_map);
if (!sky2->tx_le)
goto nomem;
sky2->tx_ring = kcalloc(sky2->tx_ring_size, sizeof(struct tx_ring_info),
GFP_KERNEL);
if (!sky2->tx_ring)
goto nomem;
sky2->rx_le = pci_zalloc_consistent(hw->pdev, RX_LE_BYTES,
&sky2->rx_le_map);
if (!sky2->rx_le)
goto nomem;
sky2->rx_ring = kcalloc(sky2->rx_pending, sizeof(struct rx_ring_info),
GFP_KERNEL);
if (!sky2->rx_ring)
goto nomem;
return sky2_alloc_rx_skbs(sky2);
nomem:
return -ENOMEM;
}
static void sky2_free_buffers(struct sky2_port *sky2)
{
struct sky2_hw *hw = sky2->hw;
sky2_rx_clean(sky2);
if (sky2->rx_le) {
pci_free_consistent(hw->pdev, RX_LE_BYTES,
sky2->rx_le, sky2->rx_le_map);
sky2->rx_le = NULL;
}
if (sky2->tx_le) {
pci_free_consistent(hw->pdev,
sky2->tx_ring_size * sizeof(struct sky2_tx_le),
sky2->tx_le, sky2->tx_le_map);
sky2->tx_le = NULL;
}
kfree(sky2->tx_ring);
kfree(sky2->rx_ring);
sky2->tx_ring = NULL;
sky2->rx_ring = NULL;
}
static void sky2_hw_up(struct sky2_port *sky2)
{
struct sky2_hw *hw = sky2->hw;
unsigned port = sky2->port;
u32 ramsize;
int cap;
struct net_device *otherdev = hw->dev[sky2->port^1];
tx_init(sky2);
/*
* On dual port PCI-X card, there is an problem where status
* can be received out of order due to split transactions
*/
if (otherdev && netif_running(otherdev) &&
(cap = pci_find_capability(hw->pdev, PCI_CAP_ID_PCIX))) {
u16 cmd;
cmd = sky2_pci_read16(hw, cap + PCI_X_CMD);
cmd &= ~PCI_X_CMD_MAX_SPLIT;
sky2_pci_write16(hw, cap + PCI_X_CMD, cmd);
}
sky2_mac_init(hw, port);
/* Register is number of 4K blocks on internal RAM buffer. */
ramsize = sky2_read8(hw, B2_E_0) * 4;
if (ramsize > 0) {
u32 rxspace;
netdev_dbg(sky2->netdev, "ram buffer %dK\n", ramsize);
if (ramsize < 16)
rxspace = ramsize / 2;
else
rxspace = 8 + (2*(ramsize - 16))/3;
sky2_ramset(hw, rxqaddr[port], 0, rxspace);
sky2_ramset(hw, txqaddr[port], rxspace, ramsize - rxspace);
/* Make sure SyncQ is disabled */
sky2_write8(hw, RB_ADDR(port == 0 ? Q_XS1 : Q_XS2, RB_CTRL),
RB_RST_SET);
}
sky2_qset(hw, txqaddr[port]);
/* This is copied from sk98lin 10.0.5.3; no one tells me about erratta's */
if (hw->chip_id == CHIP_ID_YUKON_EX && hw->chip_rev == CHIP_REV_YU_EX_B0)
sky2_write32(hw, Q_ADDR(txqaddr[port], Q_TEST), F_TX_CHK_AUTO_OFF);
/* Set almost empty threshold */
if (hw->chip_id == CHIP_ID_YUKON_EC_U &&
hw->chip_rev == CHIP_REV_YU_EC_U_A0)
sky2_write16(hw, Q_ADDR(txqaddr[port], Q_AL), ECU_TXFF_LEV);
sky2_prefetch_init(hw, txqaddr[port], sky2->tx_le_map,
sky2->tx_ring_size - 1);
sky2_vlan_mode(sky2->netdev, sky2->netdev->features);
netdev_update_features(sky2->netdev);
sky2_rx_start(sky2);
}
/* Setup device IRQ and enable napi to process */
static int sky2_setup_irq(struct sky2_hw *hw, const char *name)
{
struct pci_dev *pdev = hw->pdev;
int err;
err = request_irq(pdev->irq, sky2_intr,
(hw->flags & SKY2_HW_USE_MSI) ? 0 : IRQF_SHARED,
name, hw);
if (err)
dev_err(&pdev->dev, "cannot assign irq %d\n", pdev->irq);
else {
hw->flags |= SKY2_HW_IRQ_SETUP;
napi_enable(&hw->napi);
sky2_write32(hw, B0_IMSK, Y2_IS_BASE);
sky2_read32(hw, B0_IMSK);
}
return err;
}
/* Bring up network interface. */
static int sky2_open(struct net_device *dev)
{
struct sky2_port *sky2 = netdev_priv(dev);
struct sky2_hw *hw = sky2->hw;
unsigned port = sky2->port;
u32 imask;
int err;
netif_carrier_off(dev);
err = sky2_alloc_buffers(sky2);
if (err)
goto err_out;
/* With single port, IRQ is setup when device is brought up */
if (hw->ports == 1 && (err = sky2_setup_irq(hw, dev->name)))
goto err_out;
sky2_hw_up(sky2);
/* Enable interrupts from phy/mac for port */
imask = sky2_read32(hw, B0_IMSK);
if (hw->chip_id == CHIP_ID_YUKON_OPT ||
hw->chip_id == CHIP_ID_YUKON_PRM ||
hw->chip_id == CHIP_ID_YUKON_OP_2)
imask |= Y2_IS_PHY_QLNK; /* enable PHY Quick Link */
imask |= portirq_msk[port];
sky2_write32(hw, B0_IMSK, imask);
sky2_read32(hw, B0_IMSK);
netif_info(sky2, ifup, dev, "enabling interface\n");
return 0;
err_out:
sky2_free_buffers(sky2);
return err;
}
/* Modular subtraction in ring */
static inline int tx_inuse(const struct sky2_port *sky2)
{
return (sky2->tx_prod - sky2->tx_cons) & (sky2->tx_ring_size - 1);
}
/* Number of list elements available for next tx */
static inline int tx_avail(const struct sky2_port *sky2)
{
return sky2->tx_pending - tx_inuse(sky2);
}
/* Estimate of number of transmit list elements required */
static unsigned tx_le_req(const struct sk_buff *skb)
{
unsigned count;
count = (skb_shinfo(skb)->nr_frags + 1)
* (sizeof(dma_addr_t) / sizeof(u32));
if (skb_is_gso(skb))
++count;
else if (sizeof(dma_addr_t) == sizeof(u32))
++count; /* possible vlan */
if (skb->ip_summed == CHECKSUM_PARTIAL)
++count;
return count;
}
static void sky2_tx_unmap(struct pci_dev *pdev, struct tx_ring_info *re)
{
if (re->flags & TX_MAP_SINGLE)
pci_unmap_single(pdev, dma_unmap_addr(re, mapaddr),
dma_unmap_len(re, maplen),
PCI_DMA_TODEVICE);
else if (re->flags & TX_MAP_PAGE)
pci_unmap_page(pdev, dma_unmap_addr(re, mapaddr),
dma_unmap_len(re, maplen),
PCI_DMA_TODEVICE);
re->flags = 0;
}
/*
* Put one packet in ring for transmit.
* A single packet can generate multiple list elements, and
* the number of ring elements will probably be less than the number
* of list elements used.
*/
static netdev_tx_t sky2_xmit_frame(struct sk_buff *skb,
struct net_device *dev)
{
struct sky2_port *sky2 = netdev_priv(dev);
struct sky2_hw *hw = sky2->hw;
struct sky2_tx_le *le = NULL;
struct tx_ring_info *re;
unsigned i, len;
dma_addr_t mapping;
u32 upper;
u16 slot;
u16 mss;
u8 ctrl;
if (unlikely(tx_avail(sky2) < tx_le_req(skb)))
return NETDEV_TX_BUSY;
len = skb_headlen(skb);
mapping = pci_map_single(hw->pdev, skb->data, len, PCI_DMA_TODEVICE);
if (pci_dma_mapping_error(hw->pdev, mapping))
goto mapping_error;
slot = sky2->tx_prod;
netif_printk(sky2, tx_queued, KERN_DEBUG, dev,
"tx queued, slot %u, len %d\n", slot, skb->len);
/* Send high bits if needed */
upper = upper_32_bits(mapping);
if (upper != sky2->tx_last_upper) {
le = get_tx_le(sky2, &slot);
le->addr = cpu_to_le32(upper);
sky2->tx_last_upper = upper;
le->opcode = OP_ADDR64 | HW_OWNER;
}
/* Check for TCP Segmentation Offload */
mss = skb_shinfo(skb)->gso_size;
if (mss != 0) {
if (!(hw->flags & SKY2_HW_NEW_LE))
mss += ETH_HLEN + ip_hdrlen(skb) + tcp_hdrlen(skb);
if (mss != sky2->tx_last_mss) {
le = get_tx_le(sky2, &slot);
le->addr = cpu_to_le32(mss);
if (hw->flags & SKY2_HW_NEW_LE)
le->opcode = OP_MSS | HW_OWNER;
else
le->opcode = OP_LRGLEN | HW_OWNER;
sky2->tx_last_mss = mss;
}
}
ctrl = 0;
/* Add VLAN tag, can piggyback on LRGLEN or ADDR64 */
if (vlan_tx_tag_present(skb)) {
if (!le) {
le = get_tx_le(sky2, &slot);
le->addr = 0;
le->opcode = OP_VLAN|HW_OWNER;
} else
le->opcode |= OP_VLAN;
le->length = cpu_to_be16(vlan_tx_tag_get(skb));
ctrl |= INS_VLAN;
}
/* Handle TCP checksum offload */
if (skb->ip_summed == CHECKSUM_PARTIAL) {
/* On Yukon EX (some versions) encoding change. */
if (hw->flags & SKY2_HW_AUTO_TX_SUM)
ctrl |= CALSUM; /* auto checksum */
else {
const unsigned offset = skb_transport_offset(skb);
u32 tcpsum;
tcpsum = offset << 16; /* sum start */
tcpsum |= offset + skb->csum_offset; /* sum write */
ctrl |= CALSUM | WR_SUM | INIT_SUM | LOCK_SUM;
if (ip_hdr(skb)->protocol == IPPROTO_UDP)
ctrl |= UDPTCP;
if (tcpsum != sky2->tx_tcpsum) {
sky2->tx_tcpsum = tcpsum;
le = get_tx_le(sky2, &slot);
le->addr = cpu_to_le32(tcpsum);
le->length = 0; /* initial checksum value */
le->ctrl = 1; /* one packet */
le->opcode = OP_TCPLISW | HW_OWNER;
}
}
}
re = sky2->tx_ring + slot;
re->flags = TX_MAP_SINGLE;
dma_unmap_addr_set(re, mapaddr, mapping);
dma_unmap_len_set(re, maplen, len);
le = get_tx_le(sky2, &slot);
le->addr = cpu_to_le32(lower_32_bits(mapping));
le->length = cpu_to_le16(len);
le->ctrl = ctrl;
le->opcode = mss ? (OP_LARGESEND | HW_OWNER) : (OP_PACKET | HW_OWNER);
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
mapping = skb_frag_dma_map(&hw->pdev->dev, frag, 0,
skb_frag_size(frag), DMA_TO_DEVICE);
if (dma_mapping_error(&hw->pdev->dev, mapping))
goto mapping_unwind;
upper = upper_32_bits(mapping);
if (upper != sky2->tx_last_upper) {
le = get_tx_le(sky2, &slot);
le->addr = cpu_to_le32(upper);
sky2->tx_last_upper = upper;
le->opcode = OP_ADDR64 | HW_OWNER;
}
re = sky2->tx_ring + slot;
re->flags = TX_MAP_PAGE;
dma_unmap_addr_set(re, mapaddr, mapping);
dma_unmap_len_set(re, maplen, skb_frag_size(frag));
le = get_tx_le(sky2, &slot);
le->addr = cpu_to_le32(lower_32_bits(mapping));
le->length = cpu_to_le16(skb_frag_size(frag));
le->ctrl = ctrl;
le->opcode = OP_BUFFER | HW_OWNER;
}
re->skb = skb;
le->ctrl |= EOP;
sky2->tx_prod = slot;
if (tx_avail(sky2) <= MAX_SKB_TX_LE)
netif_stop_queue(dev);
netdev_sent_queue(dev, skb->len);
sky2_put_idx(hw, txqaddr[sky2->port], sky2->tx_prod);
return NETDEV_TX_OK;
mapping_unwind:
for (i = sky2->tx_prod; i != slot; i = RING_NEXT(i, sky2->tx_ring_size)) {
re = sky2->tx_ring + i;
sky2_tx_unmap(hw->pdev, re);
}
mapping_error:
if (net_ratelimit())
dev_warn(&hw->pdev->dev, "%s: tx mapping error\n", dev->name);
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
/*
* Free ring elements from starting at tx_cons until "done"
*
* NB:
* 1. The hardware will tell us about partial completion of multi-part
* buffers so make sure not to free skb to early.
* 2. This may run in parallel start_xmit because the it only
* looks at the tail of the queue of FIFO (tx_cons), not
* the head (tx_prod)
*/
static void sky2_tx_complete(struct sky2_port *sky2, u16 done)
{
struct net_device *dev = sky2->netdev;
u16 idx;
unsigned int bytes_compl = 0, pkts_compl = 0;
BUG_ON(done >= sky2->tx_ring_size);
for (idx = sky2->tx_cons; idx != done;
idx = RING_NEXT(idx, sky2->tx_ring_size)) {
struct tx_ring_info *re = sky2->tx_ring + idx;
struct sk_buff *skb = re->skb;
sky2_tx_unmap(sky2->hw->pdev, re);
if (skb) {
netif_printk(sky2, tx_done, KERN_DEBUG, dev,
"tx done %u\n", idx);
pkts_compl++;
bytes_compl += skb->len;
re->skb = NULL;
dev_kfree_skb_any(skb);
sky2->tx_next = RING_NEXT(idx, sky2->tx_ring_size);
}
}
sky2->tx_cons = idx;
smp_mb();
netdev_completed_queue(dev, pkts_compl, bytes_compl);
u64_stats_update_begin(&sky2->tx_stats.syncp);
sky2->tx_stats.packets += pkts_compl;
sky2->tx_stats.bytes += bytes_compl;
u64_stats_update_end(&sky2->tx_stats.syncp);
}
static void sky2_tx_reset(struct sky2_hw *hw, unsigned port)
{
/* Disable Force Sync bit and Enable Alloc bit */
sky2_write8(hw, SK_REG(port, TXA_CTRL),
TXA_DIS_FSYNC | TXA_DIS_ALLOC | TXA_STOP_RC);
/* Stop Interval Timer and Limit Counter of Tx Arbiter */
sky2_write32(hw, SK_REG(port, TXA_ITI_INI), 0L);
sky2_write32(hw, SK_REG(port, TXA_LIM_INI), 0L);
/* Reset the PCI FIFO of the async Tx queue */
sky2_write32(hw, Q_ADDR(txqaddr[port], Q_CSR),
BMU_RST_SET | BMU_FIFO_RST);
/* Reset the Tx prefetch units */
sky2_write32(hw, Y2_QADDR(txqaddr[port], PREF_UNIT_CTRL),
PREF_UNIT_RST_SET);
sky2_write32(hw, RB_ADDR(txqaddr[port], RB_CTRL), RB_RST_SET);
sky2_write8(hw, SK_REG(port, TX_GMF_CTRL_T), GMF_RST_SET);
sky2_read32(hw, B0_CTST);
}
static void sky2_hw_down(struct sky2_port *sky2)
{
struct sky2_hw *hw = sky2->hw;
unsigned port = sky2->port;
u16 ctrl;
/* Force flow control off */
sky2_write8(hw, SK_REG(port, GMAC_CTRL), GMC_PAUSE_OFF);
/* Stop transmitter */
sky2_write32(hw, Q_ADDR(txqaddr[port], Q_CSR), BMU_STOP);
sky2_read32(hw, Q_ADDR(txqaddr[port], Q_CSR));
sky2_write32(hw, RB_ADDR(txqaddr[port], RB_CTRL),
RB_RST_SET | RB_DIS_OP_MD);
ctrl = gma_read16(hw, port, GM_GP_CTRL);
ctrl &= ~(GM_GPCR_TX_ENA | GM_GPCR_RX_ENA);
gma_write16(hw, port, GM_GP_CTRL, ctrl);
sky2_write8(hw, SK_REG(port, GPHY_CTRL), GPC_RST_SET);
/* Workaround shared GMAC reset */
if (!(hw->chip_id == CHIP_ID_YUKON_XL && hw->chip_rev == 0 &&
port == 0 && hw->dev[1] && netif_running(hw->dev[1])))
sky2_write8(hw, SK_REG(port, GMAC_CTRL), GMC_RST_SET);
sky2_write8(hw, SK_REG(port, RX_GMF_CTRL_T), GMF_RST_SET);
/* Force any delayed status interrupt and NAPI */
sky2_write32(hw, STAT_LEV_TIMER_CNT, 0);
sky2_write32(hw, STAT_TX_TIMER_CNT, 0);
sky2_write32(hw, STAT_ISR_TIMER_CNT, 0);
sky2_read8(hw, STAT_ISR_TIMER_CTRL);
sky2_rx_stop(sky2);
spin_lock_bh(&sky2->phy_lock);
sky2_phy_power_down(hw, port);
spin_unlock_bh(&sky2->phy_lock);
sky2_tx_reset(hw, port);
/* Free any pending frames stuck in HW queue */
sky2_tx_complete(sky2, sky2->tx_prod);
}
/* Network shutdown */
static int sky2_close(struct net_device *dev)
{
struct sky2_port *sky2 = netdev_priv(dev);
struct sky2_hw *hw = sky2->hw;
/* Never really got started! */
if (!sky2->tx_le)
return 0;
netif_info(sky2, ifdown, dev, "disabling interface\n");
if (hw->ports == 1) {
sky2_write32(hw, B0_IMSK, 0);
sky2_read32(hw, B0_IMSK);
napi_disable(&hw->napi);
free_irq(hw->pdev->irq, hw);
hw->flags &= ~SKY2_HW_IRQ_SETUP;
} else {
u32 imask;
/* Disable port IRQ */
imask = sky2_read32(hw, B0_IMSK);
imask &= ~portirq_msk[sky2->port];
sky2_write32(hw, B0_IMSK, imask);
sky2_read32(hw, B0_IMSK);
synchronize_irq(hw->pdev->irq);
napi_synchronize(&hw->napi);
}
sky2_hw_down(sky2);
sky2_free_buffers(sky2);
return 0;
}
static u16 sky2_phy_speed(const struct sky2_hw *hw, u16 aux)
{
if (hw->flags & SKY2_HW_FIBRE_PHY)
return SPEED_1000;
if (!(hw->flags & SKY2_HW_GIGABIT)) {
if (aux & PHY_M_PS_SPEED_100)
return SPEED_100;
else
return SPEED_10;
}
switch (aux & PHY_M_PS_SPEED_MSK) {
case PHY_M_PS_SPEED_1000:
return SPEED_1000;
case PHY_M_PS_SPEED_100:
return SPEED_100;
default:
return SPEED_10;
}
}
static void sky2_link_up(struct sky2_port *sky2)
{
struct sky2_hw *hw = sky2->hw;
unsigned port = sky2->port;
static const char *fc_name[] = {
[FC_NONE] = "none",
[FC_TX] = "tx",
[FC_RX] = "rx",
[FC_BOTH] = "both",
};
sky2_set_ipg(sky2);
sky2_enable_rx_tx(sky2);
gm_phy_write(hw, port, PHY_MARV_INT_MASK, PHY_M_DEF_MSK);
netif_carrier_on(sky2->netdev);
mod_timer(&hw->watchdog_timer, jiffies + 1);
/* Turn on link LED */
sky2_write8(hw, SK_REG(port, LNK_LED_REG),
LINKLED_ON | LINKLED_BLINK_OFF | LINKLED_LINKSYNC_OFF);
netif_info(sky2, link, sky2->netdev,
"Link is up at %d Mbps, %s duplex, flow control %s\n",
sky2->speed,
sky2->duplex == DUPLEX_FULL ? "full" : "half",
fc_name[sky2->flow_status]);
}
static void sky2_link_down(struct sky2_port *sky2)
{
struct sky2_hw *hw = sky2->hw;
unsigned port = sky2->port;
u16 reg;
gm_phy_write(hw, port, PHY_MARV_INT_MASK, 0);
reg = gma_read16(hw, port, GM_GP_CTRL);
reg &= ~(GM_GPCR_RX_ENA | GM_GPCR_TX_ENA);
gma_write16(hw, port, GM_GP_CTRL, reg);
netif_carrier_off(sky2->netdev);
/* Turn off link LED */
sky2_write8(hw, SK_REG(port, LNK_LED_REG), LINKLED_OFF);
netif_info(sky2, link, sky2->netdev, "Link is down\n");
sky2_phy_init(hw, port);
}
static enum flow_control sky2_flow(int rx, int tx)
{
if (rx)
return tx ? FC_BOTH : FC_RX;
else
return tx ? FC_TX : FC_NONE;
}
static int sky2_autoneg_done(struct sky2_port *sky2, u16 aux)
{
struct sky2_hw *hw = sky2->hw;
unsigned port = sky2->port;
u16 advert, lpa;
advert = gm_phy_read(hw, port, PHY_MARV_AUNE_ADV);
lpa = gm_phy_read(hw, port, PHY_MARV_AUNE_LP);
if (lpa & PHY_M_AN_RF) {
netdev_err(sky2->netdev, "remote fault\n");
return -1;
}
if (!(aux & PHY_M_PS_SPDUP_RES)) {
netdev_err(sky2->netdev, "speed/duplex mismatch\n");
return -1;
}
sky2->speed = sky2_phy_speed(hw, aux);
sky2->duplex = (aux & PHY_M_PS_FULL_DUP) ? DUPLEX_FULL : DUPLEX_HALF;
/* Since the pause result bits seem to in different positions on
* different chips. look at registers.
*/
if (hw->flags & SKY2_HW_FIBRE_PHY) {
/* Shift for bits in fiber PHY */
advert &= ~(ADVERTISE_PAUSE_CAP|ADVERTISE_PAUSE_ASYM);
lpa &= ~(LPA_PAUSE_CAP|LPA_PAUSE_ASYM);
if (advert & ADVERTISE_1000XPAUSE)
advert |= ADVERTISE_PAUSE_CAP;
if (advert & ADVERTISE_1000XPSE_ASYM)
advert |= ADVERTISE_PAUSE_ASYM;
if (lpa & LPA_1000XPAUSE)
lpa |= LPA_PAUSE_CAP;
if (lpa & LPA_1000XPAUSE_ASYM)
lpa |= LPA_PAUSE_ASYM;
}
sky2->flow_status = FC_NONE;
if (advert & ADVERTISE_PAUSE_CAP) {
if (lpa & LPA_PAUSE_CAP)
sky2->flow_status = FC_BOTH;
else if (advert & ADVERTISE_PAUSE_ASYM)
sky2->flow_status = FC_RX;
} else if (advert & ADVERTISE_PAUSE_ASYM) {
if ((lpa & LPA_PAUSE_CAP) && (lpa & LPA_PAUSE_ASYM))
sky2->flow_status = FC_TX;
}
if (sky2->duplex == DUPLEX_HALF && sky2->speed < SPEED_1000 &&
!(hw->chip_id == CHIP_ID_YUKON_EC_U || hw->chip_id == CHIP_ID_YUKON_EX))
sky2->flow_status = FC_NONE;
if (sky2->flow_status & FC_TX)
sky2_write8(hw, SK_REG(port, GMAC_CTRL), GMC_PAUSE_ON);
else
sky2_write8(hw, SK_REG(port, GMAC_CTRL), GMC_PAUSE_OFF);
return 0;
}
/* Interrupt from PHY */
static void sky2_phy_intr(struct sky2_hw *hw, unsigned port)
{
struct net_device *dev = hw->dev[port];
struct sky2_port *sky2 = netdev_priv(dev);
u16 istatus, phystat;
if (!netif_running(dev))
return;
spin_lock(&sky2->phy_lock);
istatus = gm_phy_read(hw, port, PHY_MARV_INT_STAT);
phystat = gm_phy_read(hw, port, PHY_MARV_PHY_STAT);
netif_info(sky2, intr, sky2->netdev, "phy interrupt status 0x%x 0x%x\n",
istatus, phystat);
if (istatus & PHY_M_IS_AN_COMPL) {
if (sky2_autoneg_done(sky2, phystat) == 0 &&
!netif_carrier_ok(dev))
sky2_link_up(sky2);
goto out;
}
if (istatus & PHY_M_IS_LSP_CHANGE)
sky2->speed = sky2_phy_speed(hw, phystat);
if (istatus & PHY_M_IS_DUP_CHANGE)
sky2->duplex =
(phystat & PHY_M_PS_FULL_DUP) ? DUPLEX_FULL : DUPLEX_HALF;
if (istatus & PHY_M_IS_LST_CHANGE) {
if (phystat & PHY_M_PS_LINK_UP)
sky2_link_up(sky2);
else
sky2_link_down(sky2);
}
out:
spin_unlock(&sky2->phy_lock);
}
/* Special quick link interrupt (Yukon-2 Optima only) */
static void sky2_qlink_intr(struct sky2_hw *hw)
{
struct sky2_port *sky2 = netdev_priv(hw->dev[0]);
u32 imask;
u16 phy;
/* disable irq */
imask = sky2_read32(hw, B0_IMSK);
imask &= ~Y2_IS_PHY_QLNK;
sky2_write32(hw, B0_IMSK, imask);
/* reset PHY Link Detect */
phy = sky2_pci_read16(hw, PSM_CONFIG_REG4);
sky2_write8(hw, B2_TST_CTRL1, TST_CFG_WRITE_ON);
sky2_pci_write16(hw, PSM_CONFIG_REG4, phy | 1);
sky2_write8(hw, B2_TST_CTRL1, TST_CFG_WRITE_OFF);
sky2_link_up(sky2);
}
/* Transmit timeout is only called if we are running, carrier is up
* and tx queue is full (stopped).
*/
static void sky2_tx_timeout(struct net_device *dev)
{
struct sky2_port *sky2 = netdev_priv(dev);
struct sky2_hw *hw = sky2->hw;
netif_err(sky2, timer, dev, "tx timeout\n");
netdev_printk(KERN_DEBUG, dev, "transmit ring %u .. %u report=%u done=%u\n",
sky2->tx_cons, sky2->tx_prod,
sky2_read16(hw, sky2->port == 0 ? STAT_TXA1_RIDX : STAT_TXA2_RIDX),
sky2_read16(hw, Q_ADDR(txqaddr[sky2->port], Q_DONE)));
/* can't restart safely under softirq */
schedule_work(&hw->restart_work);
}
static int sky2_change_mtu(struct net_device *dev, int new_mtu)
{
struct sky2_port *sky2 = netdev_priv(dev);
struct sky2_hw *hw = sky2->hw;
unsigned port = sky2->port;
int err;
u16 ctl, mode;
u32 imask;
/* MTU size outside the spec */
if (new_mtu < ETH_ZLEN || new_mtu > ETH_JUMBO_MTU)
return -EINVAL;
/* MTU > 1500 on yukon FE and FE+ not allowed */
if (new_mtu > ETH_DATA_LEN &&
(hw->chip_id == CHIP_ID_YUKON_FE ||
hw->chip_id == CHIP_ID_YUKON_FE_P))
return -EINVAL;
if (!netif_running(dev)) {
dev->mtu = new_mtu;
netdev_update_features(dev);
return 0;
}
imask = sky2_read32(hw, B0_IMSK);
sky2_write32(hw, B0_IMSK, 0);
dev->trans_start = jiffies; /* prevent tx timeout */
napi_disable(&hw->napi);
netif_tx_disable(dev);
synchronize_irq(hw->pdev->irq);
if (!(hw->flags & SKY2_HW_RAM_BUFFER))
sky2_set_tx_stfwd(hw, port);
ctl = gma_read16(hw, port, GM_GP_CTRL);
gma_write16(hw, port, GM_GP_CTRL, ctl & ~GM_GPCR_RX_ENA);
sky2_rx_stop(sky2);
sky2_rx_clean(sky2);
dev->mtu = new_mtu;
netdev_update_features(dev);
mode = DATA_BLIND_VAL(DATA_BLIND_DEF) | GM_SMOD_VLAN_ENA;
if (sky2->speed > SPEED_100)
mode |= IPG_DATA_VAL(IPG_DATA_DEF_1000);
else
mode |= IPG_DATA_VAL(IPG_DATA_DEF_10_100);
if (dev->mtu > ETH_DATA_LEN)
mode |= GM_SMOD_JUMBO_ENA;
gma_write16(hw, port, GM_SERIAL_MODE, mode);
sky2_write8(hw, RB_ADDR(rxqaddr[port], RB_CTRL), RB_ENA_OP_MD);
err = sky2_alloc_rx_skbs(sky2);
if (!err)
sky2_rx_start(sky2);
else
sky2_rx_clean(sky2);
sky2_write32(hw, B0_IMSK, imask);
sky2_read32(hw, B0_Y2_SP_LISR);
napi_enable(&hw->napi);
if (err)
dev_close(dev);
else {
gma_write16(hw, port, GM_GP_CTRL, ctl);
netif_wake_queue(dev);
}
return err;
}
static inline bool needs_copy(const struct rx_ring_info *re,
unsigned length)
{
#ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
/* Some architectures need the IP header to be aligned */
if (!IS_ALIGNED(re->data_addr + ETH_HLEN, sizeof(u32)))
return true;
#endif
return length < copybreak;
}
/* For small just reuse existing skb for next receive */
static struct sk_buff *receive_copy(struct sky2_port *sky2,
const struct rx_ring_info *re,
unsigned length)
{
struct sk_buff *skb;
skb = netdev_alloc_skb_ip_align(sky2->netdev, length);
if (likely(skb)) {
pci_dma_sync_single_for_cpu(sky2->hw->pdev, re->data_addr,
length, PCI_DMA_FROMDEVICE);
skb_copy_from_linear_data(re->skb, skb->data, length);
skb->ip_summed = re->skb->ip_summed;
skb->csum = re->skb->csum;
skb_copy_hash(skb, re->skb);
skb->vlan_proto = re->skb->vlan_proto;
skb->vlan_tci = re->skb->vlan_tci;
pci_dma_sync_single_for_device(sky2->hw->pdev, re->data_addr,
length, PCI_DMA_FROMDEVICE);
re->skb->vlan_proto = 0;
re->skb->vlan_tci = 0;
skb_clear_hash(re->skb);
re->skb->ip_summed = CHECKSUM_NONE;
skb_put(skb, length);
}
return skb;
}
/* Adjust length of skb with fragments to match received data */
static void skb_put_frags(struct sk_buff *skb, unsigned int hdr_space,
unsigned int length)
{
int i, num_frags;
unsigned int size;
/* put header into skb */
size = min(length, hdr_space);
skb->tail += size;
skb->len += size;
length -= size;
num_frags = skb_shinfo(skb)->nr_frags;
for (i = 0; i < num_frags; i++) {
skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
if (length == 0) {
/* don't need this page */
__skb_frag_unref(frag);
--skb_shinfo(skb)->nr_frags;
} else {
size = min(length, (unsigned) PAGE_SIZE);
skb_frag_size_set(frag, size);
skb->data_len += size;
skb->truesize += PAGE_SIZE;
skb->len += size;
length -= size;
}
}
}
/* Normal packet - take skb from ring element and put in a new one */
static struct sk_buff *receive_new(struct sky2_port *sky2,
struct rx_ring_info *re,
unsigned int length)
{
struct sk_buff *skb;
struct rx_ring_info nre;
unsigned hdr_space = sky2->rx_data_size;
nre.skb = sky2_rx_alloc(sky2, GFP_ATOMIC);
if (unlikely(!nre.skb))
goto nobuf;
if (sky2_rx_map_skb(sky2->hw->pdev, &nre, hdr_space))
goto nomap;
skb = re->skb;
sky2_rx_unmap_skb(sky2->hw->pdev, re);
prefetch(skb->data);
*re = nre;
if (skb_shinfo(skb)->nr_frags)
skb_put_frags(skb, hdr_space, length);
else
skb_put(skb, length);
return skb;
nomap:
dev_kfree_skb(nre.skb);
nobuf:
return NULL;
}
/*
* Receive one packet.
* For larger packets, get new buffer.
*/
static struct sk_buff *sky2_receive(struct net_device *dev,
u16 length, u32 status)
{
struct sky2_port *sky2 = netdev_priv(dev);
struct rx_ring_info *re = sky2->rx_ring + sky2->rx_next;
struct sk_buff *skb = NULL;
u16 count = (status & GMR_FS_LEN) >> 16;
netif_printk(sky2, rx_status, KERN_DEBUG, dev,
"rx slot %u status 0x%x len %d\n",
sky2->rx_next, status, length);
sky2->rx_next = (sky2->rx_next + 1) % sky2->rx_pending;
prefetch(sky2->rx_ring + sky2->rx_next);
if (vlan_tx_tag_present(re->skb))
count -= VLAN_HLEN; /* Account for vlan tag */
/* This chip has hardware problems that generates bogus status.
* So do only marginal checking and expect higher level protocols
* to handle crap frames.
*/
if (sky2->hw->chip_id == CHIP_ID_YUKON_FE_P &&
sky2->hw->chip_rev == CHIP_REV_YU_FE2_A0 &&
length != count)
goto okay;
if (status & GMR_FS_ANY_ERR)
goto error;
if (!(status & GMR_FS_RX_OK))
goto resubmit;
/* if length reported by DMA does not match PHY, packet was truncated */
if (length != count)
goto error;
okay:
if (needs_copy(re, length))
skb = receive_copy(sky2, re, length);
else
skb = receive_new(sky2, re, length);
dev->stats.rx_dropped += (skb == NULL);
resubmit:
sky2_rx_submit(sky2, re);
return skb;
error:
++dev->stats.rx_errors;
if (net_ratelimit())
netif_info(sky2, rx_err, dev,
"rx error, status 0x%x length %d\n", status, length);
goto resubmit;
}
/* Transmit complete */
static inline void sky2_tx_done(struct net_device *dev, u16 last)
{
struct sky2_port *sky2 = netdev_priv(dev);
if (netif_running(dev)) {
sky2_tx_complete(sky2, last);
/* Wake unless it's detached, and called e.g. from sky2_close() */
if (tx_avail(sky2) > MAX_SKB_TX_LE + 4)
netif_wake_queue(dev);
}
}
static inline void sky2_skb_rx(const struct sky2_port *sky2,
struct sk_buff *skb)
{
if (skb->ip_summed == CHECKSUM_NONE)
netif_receive_skb(skb);
else
napi_gro_receive(&sky2->hw->napi, skb);
}
static inline void sky2_rx_done(struct sky2_hw *hw, unsigned port,
unsigned packets, unsigned bytes)
{
struct net_device *dev = hw->dev[port];
struct sky2_port *sky2 = netdev_priv(dev);
if (packets == 0)
return;
u64_stats_update_begin(&sky2->rx_stats.syncp);
sky2->rx_stats.packets += packets;
sky2->rx_stats.bytes += bytes;
u64_stats_update_end(&sky2->rx_stats.syncp);
dev->last_rx = jiffies;
sky2_rx_update(netdev_priv(dev), rxqaddr[port]);
}
static void sky2_rx_checksum(struct sky2_port *sky2, u32 status)
{
/* If this happens then driver assuming wrong format for chip type */
BUG_ON(sky2->hw->flags & SKY2_HW_NEW_LE);
/* Both checksum counters are programmed to start at
* the same offset, so unless there is a problem they
* should match. This failure is an early indication that
* hardware receive checksumming won't work.
*/
if (likely((u16)(status >> 16) == (u16)status)) {
struct sk_buff *skb = sky2->rx_ring[sky2->rx_next].skb;
skb->ip_summed = CHECKSUM_COMPLETE;
skb->csum = le16_to_cpu(status);
} else {
dev_notice(&sky2->hw->pdev->dev,
"%s: receive checksum problem (status = %#x)\n",
sky2->netdev->name, status);
/* Disable checksum offload
* It will be reenabled on next ndo_set_features, but if it's
* really broken, will get disabled again
*/
sky2->netdev->features &= ~NETIF_F_RXCSUM;
sky2_write32(sky2->hw, Q_ADDR(rxqaddr[sky2->port], Q_CSR),
BMU_DIS_RX_CHKSUM);
}
}
static void sky2_rx_tag(struct sky2_port *sky2, u16 length)
{
struct sk_buff *skb;
skb = sky2->rx_ring[sky2->rx_next].skb;
__vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), be16_to_cpu(length));
}
static void sky2_rx_hash(struct sky2_port *sky2, u32 status)
{
struct sk_buff *skb;
skb = sky2->rx_ring[sky2->rx_next].skb;
skb_set_hash(skb, le32_to_cpu(status), PKT_HASH_TYPE_L3);
}
/* Process status response ring */
static int sky2_status_intr(struct sky2_hw *hw, int to_do, u16 idx)
{
int work_done = 0;
unsigned int total_bytes[2] = { 0 };
unsigned int total_packets[2] = { 0 };
if (to_do <= 0)
return work_done;
rmb();
do {
struct sky2_port *sky2;
struct sky2_status_le *le = hw->st_le + hw->st_idx;
unsigned port;
struct net_device *dev;
struct sk_buff *skb;
u32 status;
u16 length;
u8 opcode = le->opcode;
if (!(opcode & HW_OWNER))
break;
hw->st_idx = RING_NEXT(hw->st_idx, hw->st_size);
port = le->css & CSS_LINK_BIT;
dev = hw->dev[port];
sky2 = netdev_priv(dev);
length = le16_to_cpu(le->length);
status = le32_to_cpu(le->status);
le->opcode = 0;
switch (opcode & ~HW_OWNER) {
case OP_RXSTAT:
total_packets[port]++;
total_bytes[port] += length;
skb = sky2_receive(dev, length, status);
if (!skb)
break;
/* This chip reports checksum status differently */
if (hw->flags & SKY2_HW_NEW_LE) {
if ((dev->features & NETIF_F_RXCSUM) &&
(le->css & (CSS_ISIPV4 | CSS_ISIPV6)) &&
(le->css & CSS_TCPUDPCSOK))
skb->ip_summed = CHECKSUM_UNNECESSARY;
else
skb->ip_summed = CHECKSUM_NONE;
}
skb->protocol = eth_type_trans(skb, dev);
sky2_skb_rx(sky2, skb);
/* Stop after net poll weight */
if (++work_done >= to_do)
goto exit_loop;
break;
case OP_RXVLAN:
sky2_rx_tag(sky2, length);
break;
case OP_RXCHKSVLAN:
sky2_rx_tag(sky2, length);
/* fall through */
case OP_RXCHKS:
if (likely(dev->features & NETIF_F_RXCSUM))
sky2_rx_checksum(sky2, status);
break;
case OP_RSS_HASH:
sky2_rx_hash(sky2, status);
break;
case OP_TXINDEXLE:
/* TX index reports status for both ports */
sky2_tx_done(hw->dev[0], status & 0xfff);
if (hw->dev[1])
sky2_tx_done(hw->dev[1],
((status >> 24) & 0xff)
| (u16)(length & 0xf) << 8);
break;
default:
if (net_ratelimit())
pr_warn("unknown status opcode 0x%x\n", opcode);
}
} while (hw->st_idx != idx);
/* Fully processed status ring so clear irq */
sky2_write32(hw, STAT_CTRL, SC_STAT_CLR_IRQ);
exit_loop:
sky2_rx_done(hw, 0, total_packets[0], total_bytes[0]);
sky2_rx_done(hw, 1, total_packets[1], total_bytes[1]);
return work_done;
}
static void sky2_hw_error(struct sky2_hw *hw, unsigned port, u32 status)
{
struct net_device *dev = hw->dev[port];
if (net_ratelimit())
netdev_info(dev, "hw error interrupt status 0x%x\n", status);
if (status & Y2_IS_PAR_RD1) {
if (net_ratelimit())
netdev_err(dev, "ram data read parity error\n");
/* Clear IRQ */
sky2_write16(hw, RAM_BUFFER(port, B3_RI_CTRL), RI_CLR_RD_PERR);
}
if (status & Y2_IS_PAR_WR1) {
if (net_ratelimit())
netdev_err(dev, "ram data write parity error\n");
sky2_write16(hw, RAM_BUFFER(port, B3_RI_CTRL), RI_CLR_WR_PERR);
}
if (status & Y2_IS_PAR_MAC1) {
if (net_ratelimit())
netdev_err(dev, "MAC parity error\n");
sky2_write8(hw, SK_REG(port, TX_GMF_CTRL_T), GMF_CLI_TX_PE);
}
if (status & Y2_IS_PAR_RX1) {
if (net_ratelimit())
netdev_err(dev, "RX parity error\n");
sky2_write32(hw, Q_ADDR(rxqaddr[port], Q_CSR), BMU_CLR_IRQ_PAR);
}
if (status & Y2_IS_TCP_TXA1) {
if (net_ratelimit())
netdev_err(dev, "TCP segmentation error\n");
sky2_write32(hw, Q_ADDR(txqaddr[port], Q_CSR), BMU_CLR_IRQ_TCP);
}
}
static void sky2_hw_intr(struct sky2_hw *hw)
{
struct pci_dev *pdev = hw->pdev;
u32 status = sky2_read32(hw, B0_HWE_ISRC);
u32 hwmsk = sky2_read32(hw, B0_HWE_IMSK);
status &= hwmsk;
if (status & Y2_IS_TIST_OV)
sky2_write8(hw, GMAC_TI_ST_CTRL, GMT_ST_CLR_IRQ);
if (status & (Y2_IS_MST_ERR | Y2_IS_IRQ_STAT)) {
u16 pci_err;
sky2_write8(hw, B2_TST_CTRL1, TST_CFG_WRITE_ON);
pci_err = sky2_pci_read16(hw, PCI_STATUS);
if (net_ratelimit())
dev_err(&pdev->dev, "PCI hardware error (0x%x)\n",
pci_err);
sky2_pci_write16(hw, PCI_STATUS,
pci_err | PCI_STATUS_ERROR_BITS);
sky2_write8(hw, B2_TST_CTRL1, TST_CFG_WRITE_OFF);
}
if (status & Y2_IS_PCI_EXP) {
/* PCI-Express uncorrectable Error occurred */
u32 err;
sky2_write8(hw, B2_TST_CTRL1, TST_CFG_WRITE_ON);
err = sky2_read32(hw, Y2_CFG_AER + PCI_ERR_UNCOR_STATUS);
sky2_write32(hw, Y2_CFG_AER + PCI_ERR_UNCOR_STATUS,
0xfffffffful);
if (net_ratelimit())
dev_err(&pdev->dev, "PCI Express error (0x%x)\n", err);
sky2_read32(hw, Y2_CFG_AER + PCI_ERR_UNCOR_STATUS);
sky2_write8(hw, B2_TST_CTRL1, TST_CFG_WRITE_OFF);
}
if (status & Y2_HWE_L1_MASK)
sky2_hw_error(hw, 0, status);
status >>= 8;
if (status & Y2_HWE_L1_MASK)
sky2_hw_error(hw, 1, status);
}
static void sky2_mac_intr(struct sky2_hw *hw, unsigned port)
{
struct net_device *dev = hw->dev[port];
struct sky2_port *sky2 = netdev_priv(dev);
u8 status = sky2_read8(hw, SK_REG(port, GMAC_IRQ_SRC));
netif_info(sky2, intr, dev, "mac interrupt status 0x%x\n", status);
if (status & GM_IS_RX_CO_OV)
gma_read16(hw, port, GM_RX_IRQ_SRC);
if (status & GM_IS_TX_CO_OV)
gma_read16(hw, port, GM_TX_IRQ_SRC);
if (status & GM_IS_RX_FF_OR) {
++dev->stats.rx_fifo_errors;
sky2_write8(hw, SK_REG(port, RX_GMF_CTRL_T), GMF_CLI_RX_FO);
}
if (status & GM_IS_TX_FF_UR) {
++dev->stats.tx_fifo_errors;
sky2_write8(hw, SK_REG(port, TX_GMF_CTRL_T), GMF_CLI_TX_FU);
}
}
/* This should never happen it is a bug. */
static void sky2_le_error(struct sky2_hw *hw, unsigned port, u16 q)
{
struct net_device *dev = hw->dev[port];
u16 idx = sky2_read16(hw, Y2_QADDR(q, PREF_UNIT_GET_IDX));
dev_err(&hw->pdev->dev, "%s: descriptor error q=%#x get=%u put=%u\n",
dev->name, (unsigned) q, (unsigned) idx,
(unsigned) sky2_read16(hw, Y2_QADDR(q, PREF_UNIT_PUT_IDX)));
sky2_write32(hw, Q_ADDR(q, Q_CSR), BMU_CLR_IRQ_CHK);
}
static int sky2_rx_hung(struct net_device *dev)
{
struct sky2_port *sky2 = netdev_priv(dev);
struct sky2_hw *hw = sky2->hw;
unsigned port = sky2->port;
unsigned rxq = rxqaddr[port];
u32 mac_rp = sky2_read32(hw, SK_REG(port, RX_GMF_RP));
u8 mac_lev = sky2_read8(hw, SK_REG(port, RX_GMF_RLEV));
u8 fifo_rp = sky2_read8(hw, Q_ADDR(rxq, Q_RP));
u8 fifo_lev = sky2_read8(hw, Q_ADDR(rxq, Q_RL));
/* If idle and MAC or PCI is stuck */
if (sky2->check.last == dev->last_rx &&
((mac_rp == sky2->check.mac_rp &&
mac_lev != 0 && mac_lev >= sky2->check.mac_lev) ||
/* Check if the PCI RX hang */
(fifo_rp == sky2->check.fifo_rp &&
fifo_lev != 0 && fifo_lev >= sky2->check.fifo_lev))) {
netdev_printk(KERN_DEBUG, dev,
"hung mac %d:%d fifo %d (%d:%d)\n",
mac_lev, mac_rp, fifo_lev,
fifo_rp, sky2_read8(hw, Q_ADDR(rxq, Q_WP)));
return 1;
} else {
sky2->check.last = dev->last_rx;
sky2->check.mac_rp = mac_rp;
sky2->check.mac_lev = mac_lev;
sky2->check.fifo_rp = fifo_rp;
sky2->check.fifo_lev = fifo_lev;
return 0;
}
}
static void sky2_watchdog(unsigned long arg)
{
struct sky2_hw *hw = (struct sky2_hw *) arg;
/* Check for lost IRQ once a second */
if (sky2_read32(hw, B0_ISRC)) {
napi_schedule(&hw->napi);
} else {
int i, active = 0;
for (i = 0; i < hw->ports; i++) {
struct net_device *dev = hw->dev[i];
if (!netif_running(dev))
continue;
++active;
/* For chips with Rx FIFO, check if stuck */
if ((hw->flags & SKY2_HW_RAM_BUFFER) &&
sky2_rx_hung(dev)) {
netdev_info(dev, "receiver hang detected\n");
schedule_work(&hw->restart_work);
return;
}
}
if (active == 0)
return;
}
mod_timer(&hw->watchdog_timer, round_jiffies(jiffies + HZ));
}
/* Hardware/software error handling */
static void sky2_err_intr(struct sky2_hw *hw, u32 status)
{
if (net_ratelimit())
dev_warn(&hw->pdev->dev, "error interrupt status=%#x\n", status);
if (status & Y2_IS_HW_ERR)
sky2_hw_intr(hw);
if (status & Y2_IS_IRQ_MAC1)
sky2_mac_intr(hw, 0);
if (status & Y2_IS_IRQ_MAC2)
sky2_mac_intr(hw, 1);
if (status & Y2_IS_CHK_RX1)
sky2_le_error(hw, 0, Q_R1);
if (status & Y2_IS_CHK_RX2)
sky2_le_error(hw, 1, Q_R2);
if (status & Y2_IS_CHK_TXA1)
sky2_le_error(hw, 0, Q_XA1);
if (status & Y2_IS_CHK_TXA2)
sky2_le_error(hw, 1, Q_XA2);
}
static int sky2_poll(struct napi_struct *napi, int work_limit)
{
struct sky2_hw *hw = container_of(napi, struct sky2_hw, napi);
u32 status = sky2_read32(hw, B0_Y2_SP_EISR);
int work_done = 0;
u16 idx;
if (unlikely(status & Y2_IS_ERROR))
sky2_err_intr(hw, status);
if (status & Y2_IS_IRQ_PHY1)
sky2_phy_intr(hw, 0);
if (status & Y2_IS_IRQ_PHY2)
sky2_phy_intr(hw, 1);
if (status & Y2_IS_PHY_QLNK)
sky2_qlink_intr(hw);
while ((idx = sky2_read16(hw, STAT_PUT_IDX)) != hw->st_idx) {
work_done += sky2_status_intr(hw, work_limit - work_done, idx);
if (work_done >= work_limit)
goto done;
}
napi_complete(napi);
sky2_read32(hw, B0_Y2_SP_LISR);
done:
return work_done;
}
static irqreturn_t sky2_intr(int irq, void *dev_id)
{
struct sky2_hw *hw = dev_id;
u32 status;
/* Reading this mask interrupts as side effect */
status = sky2_read32(hw, B0_Y2_SP_ISRC2);
if (status == 0 || status == ~0) {
sky2_write32(hw, B0_Y2_SP_ICR, 2);
return IRQ_NONE;
}
prefetch(&hw->st_le[hw->st_idx]);
napi_schedule(&hw->napi);
return IRQ_HANDLED;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void sky2_netpoll(struct net_device *dev)
{
struct sky2_port *sky2 = netdev_priv(dev);
napi_schedule(&sky2->hw->napi);
}
#endif
/* Chip internal frequency for clock calculations */
static u32 sky2_mhz(const struct sky2_hw *hw)
{
switch (hw->chip_id) {
case CHIP_ID_YUKON_EC:
case CHIP_ID_YUKON_EC_U:
case CHIP_ID_YUKON_EX:
case CHIP_ID_YUKON_SUPR:
case CHIP_ID_YUKON_UL_2:
case CHIP_ID_YUKON_OPT:
case CHIP_ID_YUKON_PRM:
case CHIP_ID_YUKON_OP_2:
return 125;
case CHIP_ID_YUKON_FE:
return 100;
case CHIP_ID_YUKON_FE_P:
return 50;
case CHIP_ID_YUKON_XL:
return 156;
default:
BUG();
}
}
static inline u32 sky2_us2clk(const struct sky2_hw *hw, u32 us)
{
return sky2_mhz(hw) * us;
}
static inline u32 sky2_clk2us(const struct sky2_hw *hw, u32 clk)
{
return clk / sky2_mhz(hw);
}
static int sky2_init(struct sky2_hw *hw)
{
u8 t8;
/* Enable all clocks and check for bad PCI access */
sky2_pci_write32(hw, PCI_DEV_REG3, 0);
sky2_write8(hw, B0_CTST, CS_RST_CLR);
hw->chip_id = sky2_read8(hw, B2_CHIP_ID);
hw->chip_rev = (sky2_read8(hw, B2_MAC_CFG) & CFG_CHIP_R_MSK) >> 4;
switch (hw->chip_id) {
case CHIP_ID_YUKON_XL:
hw->flags = SKY2_HW_GIGABIT | SKY2_HW_NEWER_PHY;
if (hw->chip_rev < CHIP_REV_YU_XL_A2)
hw->flags |= SKY2_HW_RSS_BROKEN;
break;
case CHIP_ID_YUKON_EC_U:
hw->flags = SKY2_HW_GIGABIT
| SKY2_HW_NEWER_PHY
| SKY2_HW_ADV_POWER_CTL;
break;
case CHIP_ID_YUKON_EX:
hw->flags = SKY2_HW_GIGABIT
| SKY2_HW_NEWER_PHY
| SKY2_HW_NEW_LE
| SKY2_HW_ADV_POWER_CTL
| SKY2_HW_RSS_CHKSUM;
/* New transmit checksum */
if (hw->chip_rev != CHIP_REV_YU_EX_B0)
hw->flags |= SKY2_HW_AUTO_TX_SUM;
break;
case CHIP_ID_YUKON_EC:
/* This rev is really old, and requires untested workarounds */
if (hw->chip_rev == CHIP_REV_YU_EC_A1) {
dev_err(&hw->pdev->dev, "unsupported revision Yukon-EC rev A1\n");
return -EOPNOTSUPP;
}
hw->flags = SKY2_HW_GIGABIT | SKY2_HW_RSS_BROKEN;
break;
case CHIP_ID_YUKON_FE:
hw->flags = SKY2_HW_RSS_BROKEN;
break;
case CHIP_ID_YUKON_FE_P:
hw->flags = SKY2_HW_NEWER_PHY
| SKY2_HW_NEW_LE
| SKY2_HW_AUTO_TX_SUM
| SKY2_HW_ADV_POWER_CTL;
/* The workaround for status conflicts VLAN tag detection. */
if (hw->chip_rev == CHIP_REV_YU_FE2_A0)
hw->flags |= SKY2_HW_VLAN_BROKEN | SKY2_HW_RSS_CHKSUM;
break;
case CHIP_ID_YUKON_SUPR:
hw->flags = SKY2_HW_GIGABIT
| SKY2_HW_NEWER_PHY
| SKY2_HW_NEW_LE
| SKY2_HW_AUTO_TX_SUM
| SKY2_HW_ADV_POWER_CTL;
if (hw->chip_rev == CHIP_REV_YU_SU_A0)
hw->flags |= SKY2_HW_RSS_CHKSUM;
break;
case CHIP_ID_YUKON_UL_2:
hw->flags = SKY2_HW_GIGABIT
| SKY2_HW_ADV_POWER_CTL;
break;
case CHIP_ID_YUKON_OPT:
case CHIP_ID_YUKON_PRM:
case CHIP_ID_YUKON_OP_2:
hw->flags = SKY2_HW_GIGABIT
| SKY2_HW_NEW_LE
| SKY2_HW_ADV_POWER_CTL;
break;
default:
dev_err(&hw->pdev->dev, "unsupported chip type 0x%x\n",
hw->chip_id);
return -EOPNOTSUPP;
}
hw->pmd_type = sky2_read8(hw, B2_PMD_TYP);
if (hw->pmd_type == 'L' || hw->pmd_type == 'S' || hw->pmd_type == 'P')
hw->flags |= SKY2_HW_FIBRE_PHY;
hw->ports = 1;
t8 = sky2_read8(hw, B2_Y2_HW_RES);
if ((t8 & CFG_DUAL_MAC_MSK) == CFG_DUAL_MAC_MSK) {
if (!(sky2_read8(hw, B2_Y2_CLK_GATE) & Y2_STATUS_LNK2_INAC))
++hw->ports;
}
if (sky2_read8(hw, B2_E_0))
hw->flags |= SKY2_HW_RAM_BUFFER;
return 0;
}
static void sky2_reset(struct sky2_hw *hw)
{
struct pci_dev *pdev = hw->pdev;
u16 status;
int i;
u32 hwe_mask = Y2_HWE_ALL_MASK;
/* disable ASF */
if (hw->chip_id == CHIP_ID_YUKON_EX
|| hw->chip_id == CHIP_ID_YUKON_SUPR) {
sky2_write32(hw, CPU_WDOG, 0);
status = sky2_read16(hw, HCU_CCSR);
status &= ~(HCU_CCSR_AHB_RST | HCU_CCSR_CPU_RST_MODE |
HCU_CCSR_UC_STATE_MSK);
/*
* CPU clock divider shouldn't be used because
* - ASF firmware may malfunction
* - Yukon-Supreme: Parallel FLASH doesn't support divided clocks
*/
status &= ~HCU_CCSR_CPU_CLK_DIVIDE_MSK;
sky2_write16(hw, HCU_CCSR, status);
sky2_write32(hw, CPU_WDOG, 0);
} else
sky2_write8(hw, B28_Y2_ASF_STAT_CMD, Y2_ASF_RESET);
sky2_write16(hw, B0_CTST, Y2_ASF_DISABLE);
/* do a SW reset */
sky2_write8(hw, B0_CTST, CS_RST_SET);
sky2_write8(hw, B0_CTST, CS_RST_CLR);
/* allow writes to PCI config */
sky2_write8(hw, B2_TST_CTRL1, TST_CFG_WRITE_ON);
/* clear PCI errors, if any */
status = sky2_pci_read16(hw, PCI_STATUS);
status |= PCI_STATUS_ERROR_BITS;
sky2_pci_write16(hw, PCI_STATUS, status);
sky2_write8(hw, B0_CTST, CS_MRST_CLR);
if (pci_is_pcie(pdev)) {
sky2_write32(hw, Y2_CFG_AER + PCI_ERR_UNCOR_STATUS,
0xfffffffful);
/* If error bit is stuck on ignore it */
if (sky2_read32(hw, B0_HWE_ISRC) & Y2_IS_PCI_EXP)
dev_info(&pdev->dev, "ignoring stuck error report bit\n");
else
hwe_mask |= Y2_IS_PCI_EXP;
}
sky2_power_on(hw);
sky2_write8(hw, B2_TST_CTRL1, TST_CFG_WRITE_OFF);
for (i = 0; i < hw->ports; i++) {
sky2_write8(hw, SK_REG(i, GMAC_LINK_CTRL), GMLC_RST_SET);
sky2_write8(hw, SK_REG(i, GMAC_LINK_CTRL), GMLC_RST_CLR);
if (hw->chip_id == CHIP_ID_YUKON_EX ||
hw->chip_id == CHIP_ID_YUKON_SUPR)
sky2_write16(hw, SK_REG(i, GMAC_CTRL),
GMC_BYP_MACSECRX_ON | GMC_BYP_MACSECTX_ON
| GMC_BYP_RETR_ON);
}
if (hw->chip_id == CHIP_ID_YUKON_SUPR && hw->chip_rev > CHIP_REV_YU_SU_B0) {
/* enable MACSec clock gating */
sky2_pci_write32(hw, PCI_DEV_REG3, P_CLK_MACSEC_DIS);
}
if (hw->chip_id == CHIP_ID_YUKON_OPT ||
hw->chip_id == CHIP_ID_YUKON_PRM ||
hw->chip_id == CHIP_ID_YUKON_OP_2) {
u16 reg;
if (hw->chip_id == CHIP_ID_YUKON_OPT && hw->chip_rev == 0) {
/* disable PCI-E PHY power down (set PHY reg 0x80, bit 7 */
sky2_write32(hw, Y2_PEX_PHY_DATA, (0x80UL << 16) | (1 << 7));
/* set PHY Link Detect Timer to 1.1 second (11x 100ms) */
reg = 10;
/* re-enable PEX PM in PEX PHY debug reg. 8 (clear bit 12) */
sky2_write32(hw, Y2_PEX_PHY_DATA, PEX_DB_ACCESS | (0x08UL << 16));
} else {
/* set PHY Link Detect Timer to 0.4 second (4x 100ms) */
reg = 3;
}
reg <<= PSM_CONFIG_REG4_TIMER_PHY_LINK_DETECT_BASE;
reg |= PSM_CONFIG_REG4_RST_PHY_LINK_DETECT;
/* reset PHY Link Detect */
sky2_write8(hw, B2_TST_CTRL1, TST_CFG_WRITE_ON);
sky2_pci_write16(hw, PSM_CONFIG_REG4, reg);
/* check if PSMv2 was running before */
reg = sky2_pci_read16(hw, PSM_CONFIG_REG3);
if (reg & PCI_EXP_LNKCTL_ASPMC)
/* restore the PCIe Link Control register */
sky2_pci_write16(hw, pdev->pcie_cap + PCI_EXP_LNKCTL,
reg);
if (hw->chip_id == CHIP_ID_YUKON_PRM &&
hw->chip_rev == CHIP_REV_YU_PRM_A0) {
/* change PHY Interrupt polarity to low active */
reg = sky2_read16(hw, GPHY_CTRL);
sky2_write16(hw, GPHY_CTRL, reg | GPC_INTPOL);
/* adapt HW for low active PHY Interrupt */
reg = sky2_read16(hw, Y2_CFG_SPC + PCI_LDO_CTRL);
sky2_write16(hw, Y2_CFG_SPC + PCI_LDO_CTRL, reg | PHY_M_UNDOC1);
}
sky2_write8(hw, B2_TST_CTRL1, TST_CFG_WRITE_OFF);
/* re-enable PEX PM in PEX PHY debug reg. 8 (clear bit 12) */
sky2_write32(hw, Y2_PEX_PHY_DATA, PEX_DB_ACCESS | (0x08UL << 16));
}
/* Clear I2C IRQ noise */
sky2_write32(hw, B2_I2C_IRQ, 1);
/* turn off hardware timer (unused) */
sky2_write8(hw, B2_TI_CTRL, TIM_STOP);
sky2_write8(hw, B2_TI_CTRL, TIM_CLR_IRQ);
/* Turn off descriptor polling */
sky2_write32(hw, B28_DPT_CTRL, DPT_STOP);
/* Turn off receive timestamp */
sky2_write8(hw, GMAC_TI_ST_CTRL, GMT_ST_STOP);
sky2_write8(hw, GMAC_TI_ST_CTRL, GMT_ST_CLR_IRQ);
/* enable the Tx Arbiters */
for (i = 0; i < hw->ports; i++)
sky2_write8(hw, SK_REG(i, TXA_CTRL), TXA_ENA_ARB);
/* Initialize ram interface */
for (i = 0; i < hw->ports; i++) {
sky2_write8(hw, RAM_BUFFER(i, B3_RI_CTRL), RI_RST_CLR);
sky2_write8(hw, RAM_BUFFER(i, B3_RI_WTO_R1), SK_RI_TO_53);
sky2_write8(hw, RAM_BUFFER(i, B3_RI_WTO_XA1), SK_RI_TO_53);
sky2_write8(hw, RAM_BUFFER(i, B3_RI_WTO_XS1), SK_RI_TO_53);
sky2_write8(hw, RAM_BUFFER(i, B3_RI_RTO_R1), SK_RI_TO_53);
sky2_write8(hw, RAM_BUFFER(i, B3_RI_RTO_XA1), SK_RI_TO_53);
sky2_write8(hw, RAM_BUFFER(i, B3_RI_RTO_XS1), SK_RI_TO_53);
sky2_write8(hw, RAM_BUFFER(i, B3_RI_WTO_R2), SK_RI_TO_53);
sky2_write8(hw, RAM_BUFFER(i, B3_RI_WTO_XA2), SK_RI_TO_53);
sky2_write8(hw, RAM_BUFFER(i, B3_RI_WTO_XS2), SK_RI_TO_53);
sky2_write8(hw, RAM_BUFFER(i, B3_RI_RTO_R2), SK_RI_TO_53);
sky2_write8(hw, RAM_BUFFER(i, B3_RI_RTO_XA2), SK_RI_TO_53);
sky2_write8(hw, RAM_BUFFER(i, B3_RI_RTO_XS2), SK_RI_TO_53);
}
sky2_write32(hw, B0_HWE_IMSK, hwe_mask);
for (i = 0; i < hw->ports; i++)
sky2_gmac_reset(hw, i);
memset(hw->st_le, 0, hw->st_size * sizeof(struct sky2_status_le));
hw->st_idx = 0;
sky2_write32(hw, STAT_CTRL, SC_STAT_RST_SET);
sky2_write32(hw, STAT_CTRL, SC_STAT_RST_CLR);
sky2_write32(hw, STAT_LIST_ADDR_LO, hw->st_dma);
sky2_write32(hw, STAT_LIST_ADDR_HI, (u64) hw->st_dma >> 32);
/* Set the list last index */
sky2_write16(hw, STAT_LAST_IDX, hw->st_size - 1);
sky2_write16(hw, STAT_TX_IDX_TH, 10);
sky2_write8(hw, STAT_FIFO_WM, 16);
/* set Status-FIFO ISR watermark */
if (hw->chip_id == CHIP_ID_YUKON_XL && hw->chip_rev == 0)
sky2_write8(hw, STAT_FIFO_ISR_WM, 4);
else
sky2_write8(hw, STAT_FIFO_ISR_WM, 16);
sky2_write32(hw, STAT_TX_TIMER_INI, sky2_us2clk(hw, 1000));
sky2_write32(hw, STAT_ISR_TIMER_INI, sky2_us2clk(hw, 20));
sky2_write32(hw, STAT_LEV_TIMER_INI, sky2_us2clk(hw, 100));
/* enable status unit */
sky2_write32(hw, STAT_CTRL, SC_STAT_OP_ON);
sky2_write8(hw, STAT_TX_TIMER_CTRL, TIM_START);
sky2_write8(hw, STAT_LEV_TIMER_CTRL, TIM_START);
sky2_write8(hw, STAT_ISR_TIMER_CTRL, TIM_START);
}
/* Take device down (offline).
* Equivalent to doing dev_stop() but this does not
* inform upper layers of the transition.
*/
static void sky2_detach(struct net_device *dev)
{
if (netif_running(dev)) {
netif_tx_lock(dev);
netif_device_detach(dev); /* stop txq */
netif_tx_unlock(dev);
sky2_close(dev);
}
}
/* Bring device back after doing sky2_detach */
static int sky2_reattach(struct net_device *dev)
{
int err = 0;
if (netif_running(dev)) {
err = sky2_open(dev);
if (err) {
netdev_info(dev, "could not restart %d\n", err);
dev_close(dev);
} else {
netif_device_attach(dev);
sky2_set_multicast(dev);
}
}
return err;
}
static void sky2_all_down(struct sky2_hw *hw)
{
int i;
if (hw->flags & SKY2_HW_IRQ_SETUP) {
sky2_read32(hw, B0_IMSK);
sky2_write32(hw, B0_IMSK, 0);
synchronize_irq(hw->pdev->irq);
napi_disable(&hw->napi);
}
for (i = 0; i < hw->ports; i++) {
struct net_device *dev = hw->dev[i];
struct sky2_port *sky2 = netdev_priv(dev);
if (!netif_running(dev))
continue;
netif_carrier_off(dev);
netif_tx_disable(dev);
sky2_hw_down(sky2);
}
}
static void sky2_all_up(struct sky2_hw *hw)
{
u32 imask = Y2_IS_BASE;
int i;
for (i = 0; i < hw->ports; i++) {
struct net_device *dev = hw->dev[i];
struct sky2_port *sky2 = netdev_priv(dev);
if (!netif_running(dev))
continue;
sky2_hw_up(sky2);
sky2_set_multicast(dev);
imask |= portirq_msk[i];
netif_wake_queue(dev);
}
if (hw->flags & SKY2_HW_IRQ_SETUP) {
sky2_write32(hw, B0_IMSK, imask);
sky2_read32(hw, B0_IMSK);
sky2_read32(hw, B0_Y2_SP_LISR);
napi_enable(&hw->napi);
}
}
static void sky2_restart(struct work_struct *work)
{
struct sky2_hw *hw = container_of(work, struct sky2_hw, restart_work);
rtnl_lock();
sky2_all_down(hw);
sky2_reset(hw);
sky2_all_up(hw);
rtnl_unlock();
}
static inline u8 sky2_wol_supported(const struct sky2_hw *hw)
{
return sky2_is_copper(hw) ? (WAKE_PHY | WAKE_MAGIC) : 0;
}
static void sky2_get_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
const struct sky2_port *sky2 = netdev_priv(dev);
wol->supported = sky2_wol_supported(sky2->hw);
wol->wolopts = sky2->wol;
}
static int sky2_set_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
struct sky2_port *sky2 = netdev_priv(dev);
struct sky2_hw *hw = sky2->hw;
bool enable_wakeup = false;
int i;
if ((wol->wolopts & ~sky2_wol_supported(sky2->hw)) ||
!device_can_wakeup(&hw->pdev->dev))
return -EOPNOTSUPP;
sky2->wol = wol->wolopts;
for (i = 0; i < hw->ports; i++) {
struct net_device *dev = hw->dev[i];
struct sky2_port *sky2 = netdev_priv(dev);
if (sky2->wol)
enable_wakeup = true;
}
device_set_wakeup_enable(&hw->pdev->dev, enable_wakeup);
return 0;
}
static u32 sky2_supported_modes(const struct sky2_hw *hw)
{
if (sky2_is_copper(hw)) {
u32 modes = SUPPORTED_10baseT_Half
| SUPPORTED_10baseT_Full
| SUPPORTED_100baseT_Half
| SUPPORTED_100baseT_Full;
if (hw->flags & SKY2_HW_GIGABIT)
modes |= SUPPORTED_1000baseT_Half
| SUPPORTED_1000baseT_Full;
return modes;
} else
return SUPPORTED_1000baseT_Half
| SUPPORTED_1000baseT_Full;
}
static int sky2_get_settings(struct net_device *dev, struct ethtool_cmd *ecmd)
{
struct sky2_port *sky2 = netdev_priv(dev);
struct sky2_hw *hw = sky2->hw;
ecmd->transceiver = XCVR_INTERNAL;
ecmd->supported = sky2_supported_modes(hw);
ecmd->phy_address = PHY_ADDR_MARV;
if (sky2_is_copper(hw)) {
ecmd->port = PORT_TP;
ethtool_cmd_speed_set(ecmd, sky2->speed);
ecmd->supported |= SUPPORTED_Autoneg | SUPPORTED_TP;
} else {
ethtool_cmd_speed_set(ecmd, SPEED_1000);
ecmd->port = PORT_FIBRE;
ecmd->supported |= SUPPORTED_Autoneg | SUPPORTED_FIBRE;
}
ecmd->advertising = sky2->advertising;
ecmd->autoneg = (sky2->flags & SKY2_FLAG_AUTO_SPEED)
? AUTONEG_ENABLE : AUTONEG_DISABLE;
ecmd->duplex = sky2->duplex;
return 0;
}
static int sky2_set_settings(struct net_device *dev, struct ethtool_cmd *ecmd)
{
struct sky2_port *sky2 = netdev_priv(dev);
const struct sky2_hw *hw = sky2->hw;
u32 supported = sky2_supported_modes(hw);
if (ecmd->autoneg == AUTONEG_ENABLE) {
if (ecmd->advertising & ~supported)
return -EINVAL;
if (sky2_is_copper(hw))
sky2->advertising = ecmd->advertising |
ADVERTISED_TP |
ADVERTISED_Autoneg;
else
sky2->advertising = ecmd->advertising |
ADVERTISED_FIBRE |
ADVERTISED_Autoneg;
sky2->flags |= SKY2_FLAG_AUTO_SPEED;
sky2->duplex = -1;
sky2->speed = -1;
} else {
u32 setting;
u32 speed = ethtool_cmd_speed(ecmd);
switch (speed) {
case SPEED_1000:
if (ecmd->duplex == DUPLEX_FULL)
setting = SUPPORTED_1000baseT_Full;
else if (ecmd->duplex == DUPLEX_HALF)
setting = SUPPORTED_1000baseT_Half;
else
return -EINVAL;
break;
case SPEED_100:
if (ecmd->duplex == DUPLEX_FULL)
setting = SUPPORTED_100baseT_Full;
else if (ecmd->duplex == DUPLEX_HALF)
setting = SUPPORTED_100baseT_Half;
else
return -EINVAL;
break;
case SPEED_10:
if (ecmd->duplex == DUPLEX_FULL)
setting = SUPPORTED_10baseT_Full;
else if (ecmd->duplex == DUPLEX_HALF)
setting = SUPPORTED_10baseT_Half;
else
return -EINVAL;
break;
default:
return -EINVAL;
}
if ((setting & supported) == 0)
return -EINVAL;
sky2->speed = speed;
sky2->duplex = ecmd->duplex;
sky2->flags &= ~SKY2_FLAG_AUTO_SPEED;
}
if (netif_running(dev)) {
sky2_phy_reinit(sky2);
sky2_set_multicast(dev);
}
return 0;
}
static void sky2_get_drvinfo(struct net_device *dev,
struct ethtool_drvinfo *info)
{
struct sky2_port *sky2 = netdev_priv(dev);
strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
strlcpy(info->version, DRV_VERSION, sizeof(info->version));
strlcpy(info->bus_info, pci_name(sky2->hw->pdev),
sizeof(info->bus_info));
}
static const struct sky2_stat {
char name[ETH_GSTRING_LEN];
u16 offset;
} sky2_stats[] = {
{ "tx_bytes", GM_TXO_OK_HI },
{ "rx_bytes", GM_RXO_OK_HI },
{ "tx_broadcast", GM_TXF_BC_OK },
{ "rx_broadcast", GM_RXF_BC_OK },
{ "tx_multicast", GM_TXF_MC_OK },
{ "rx_multicast", GM_RXF_MC_OK },
{ "tx_unicast", GM_TXF_UC_OK },
{ "rx_unicast", GM_RXF_UC_OK },
{ "tx_mac_pause", GM_TXF_MPAUSE },
{ "rx_mac_pause", GM_RXF_MPAUSE },
{ "collisions", GM_TXF_COL },
{ "late_collision",GM_TXF_LAT_COL },
{ "aborted", GM_TXF_ABO_COL },
{ "single_collisions", GM_TXF_SNG_COL },
{ "multi_collisions", GM_TXF_MUL_COL },
{ "rx_short", GM_RXF_SHT },
{ "rx_runt", GM_RXE_FRAG },
{ "rx_64_byte_packets", GM_RXF_64B },
{ "rx_65_to_127_byte_packets", GM_RXF_127B },
{ "rx_128_to_255_byte_packets", GM_RXF_255B },
{ "rx_256_to_511_byte_packets", GM_RXF_511B },
{ "rx_512_to_1023_byte_packets", GM_RXF_1023B },
{ "rx_1024_to_1518_byte_packets", GM_RXF_1518B },
{ "rx_1518_to_max_byte_packets", GM_RXF_MAX_SZ },
{ "rx_too_long", GM_RXF_LNG_ERR },
{ "rx_fifo_overflow", GM_RXE_FIFO_OV },
{ "rx_jabber", GM_RXF_JAB_PKT },
{ "rx_fcs_error", GM_RXF_FCS_ERR },
{ "tx_64_byte_packets", GM_TXF_64B },
{ "tx_65_to_127_byte_packets", GM_TXF_127B },
{ "tx_128_to_255_byte_packets", GM_TXF_255B },
{ "tx_256_to_511_byte_packets", GM_TXF_511B },
{ "tx_512_to_1023_byte_packets", GM_TXF_1023B },
{ "tx_1024_to_1518_byte_packets", GM_TXF_1518B },
{ "tx_1519_to_max_byte_packets", GM_TXF_MAX_SZ },
{ "tx_fifo_underrun", GM_TXE_FIFO_UR },
};
static u32 sky2_get_msglevel(struct net_device *netdev)
{
struct sky2_port *sky2 = netdev_priv(netdev);
return sky2->msg_enable;
}
static int sky2_nway_reset(struct net_device *dev)
{
struct sky2_port *sky2 = netdev_priv(dev);
if (!netif_running(dev) || !(sky2->flags & SKY2_FLAG_AUTO_SPEED))
return -EINVAL;
sky2_phy_reinit(sky2);
sky2_set_multicast(dev);
return 0;
}
static void sky2_phy_stats(struct sky2_port *sky2, u64 * data, unsigned count)
{
struct sky2_hw *hw = sky2->hw;
unsigned port = sky2->port;
int i;
data[0] = get_stats64(hw, port, GM_TXO_OK_LO);
data[1] = get_stats64(hw, port, GM_RXO_OK_LO);
for (i = 2; i < count; i++)
data[i] = get_stats32(hw, port, sky2_stats[i].offset);
}
static void sky2_set_msglevel(struct net_device *netdev, u32 value)
{
struct sky2_port *sky2 = netdev_priv(netdev);
sky2->msg_enable = value;
}
static int sky2_get_sset_count(struct net_device *dev, int sset)
{
switch (sset) {
case ETH_SS_STATS:
return ARRAY_SIZE(sky2_stats);
default:
return -EOPNOTSUPP;
}
}
static void sky2_get_ethtool_stats(struct net_device *dev,
struct ethtool_stats *stats, u64 * data)
{
struct sky2_port *sky2 = netdev_priv(dev);
sky2_phy_stats(sky2, data, ARRAY_SIZE(sky2_stats));
}
static void sky2_get_strings(struct net_device *dev, u32 stringset, u8 * data)
{
int i;
switch (stringset) {
case ETH_SS_STATS:
for (i = 0; i < ARRAY_SIZE(sky2_stats); i++)
memcpy(data + i * ETH_GSTRING_LEN,
sky2_stats[i].name, ETH_GSTRING_LEN);
break;
}
}
static int sky2_set_mac_address(struct net_device *dev, void *p)
{
struct sky2_port *sky2 = netdev_priv(dev);
struct sky2_hw *hw = sky2->hw;
unsigned port = sky2->port;
const struct sockaddr *addr = p;
if (!is_valid_ether_addr(addr->sa_data))
return -EADDRNOTAVAIL;
memcpy(dev->dev_addr, addr->sa_data, ETH_ALEN);
memcpy_toio(hw->regs + B2_MAC_1 + port * 8,
dev->dev_addr, ETH_ALEN);
memcpy_toio(hw->regs + B2_MAC_2 + port * 8,
dev->dev_addr, ETH_ALEN);
/* virtual address for data */
gma_set_addr(hw, port, GM_SRC_ADDR_2L, dev->dev_addr);
/* physical address: used for pause frames */
gma_set_addr(hw, port, GM_SRC_ADDR_1L, dev->dev_addr);
return 0;
}
static inline void sky2_add_filter(u8 filter[8], const u8 *addr)
{
u32 bit;
bit = ether_crc(ETH_ALEN, addr) & 63;
filter[bit >> 3] |= 1 << (bit & 7);
}
static void sky2_set_multicast(struct net_device *dev)
{
struct sky2_port *sky2 = netdev_priv(dev);
struct sky2_hw *hw = sky2->hw;
unsigned port = sky2->port;
struct netdev_hw_addr *ha;
u16 reg;
u8 filter[8];
int rx_pause;
static const u8 pause_mc_addr[ETH_ALEN] = { 0x1, 0x80, 0xc2, 0x0, 0x0, 0x1 };
rx_pause = (sky2->flow_status == FC_RX || sky2->flow_status == FC_BOTH);
memset(filter, 0, sizeof(filter));
reg = gma_read16(hw, port, GM_RX_CTRL);
reg |= GM_RXCR_UCF_ENA;
if (dev->flags & IFF_PROMISC) /* promiscuous */
reg &= ~(GM_RXCR_UCF_ENA | GM_RXCR_MCF_ENA);
else if (dev->flags & IFF_ALLMULTI)
memset(filter, 0xff, sizeof(filter));
else if (netdev_mc_empty(dev) && !rx_pause)
reg &= ~GM_RXCR_MCF_ENA;
else {
reg |= GM_RXCR_MCF_ENA;
if (rx_pause)
sky2_add_filter(filter, pause_mc_addr);
netdev_for_each_mc_addr(ha, dev)
sky2_add_filter(filter, ha->addr);
}
gma_write16(hw, port, GM_MC_ADDR_H1,
(u16) filter[0] | ((u16) filter[1] << 8));
gma_write16(hw, port, GM_MC_ADDR_H2,
(u16) filter[2] | ((u16) filter[3] << 8));
gma_write16(hw, port, GM_MC_ADDR_H3,
(u16) filter[4] | ((u16) filter[5] << 8));
gma_write16(hw, port, GM_MC_ADDR_H4,
(u16) filter[6] | ((u16) filter[7] << 8));
gma_write16(hw, port, GM_RX_CTRL, reg);
}
static struct rtnl_link_stats64 *sky2_get_stats(struct net_device *dev,
struct rtnl_link_stats64 *stats)
{
struct sky2_port *sky2 = netdev_priv(dev);
struct sky2_hw *hw = sky2->hw;
unsigned port = sky2->port;
unsigned int start;
u64 _bytes, _packets;
do {
start = u64_stats_fetch_begin_irq(&sky2->rx_stats.syncp);
_bytes = sky2->rx_stats.bytes;
_packets = sky2->rx_stats.packets;
} while (u64_stats_fetch_retry_irq(&sky2->rx_stats.syncp, start));
stats->rx_packets = _packets;
stats->rx_bytes = _bytes;
do {
start = u64_stats_fetch_begin_irq(&sky2->tx_stats.syncp);
_bytes = sky2->tx_stats.bytes;
_packets = sky2->tx_stats.packets;
} while (u64_stats_fetch_retry_irq(&sky2->tx_stats.syncp, start));
stats->tx_packets = _packets;
stats->tx_bytes = _bytes;
stats->multicast = get_stats32(hw, port, GM_RXF_MC_OK)
+ get_stats32(hw, port, GM_RXF_BC_OK);
stats->collisions = get_stats32(hw, port, GM_TXF_COL);
stats->rx_length_errors = get_stats32(hw, port, GM_RXF_LNG_ERR);
stats->rx_crc_errors = get_stats32(hw, port, GM_RXF_FCS_ERR);
stats->rx_frame_errors = get_stats32(hw, port, GM_RXF_SHT)
+ get_stats32(hw, port, GM_RXE_FRAG);
stats->rx_over_errors = get_stats32(hw, port, GM_RXE_FIFO_OV);
stats->rx_dropped = dev->stats.rx_dropped;
stats->rx_fifo_errors = dev->stats.rx_fifo_errors;
stats->tx_fifo_errors = dev->stats.tx_fifo_errors;
return stats;
}
/* Can have one global because blinking is controlled by
* ethtool and that is always under RTNL mutex
*/
static void sky2_led(struct sky2_port *sky2, enum led_mode mode)
{
struct sky2_hw *hw = sky2->hw;
unsigned port = sky2->port;
spin_lock_bh(&sky2->phy_lock);
if (hw->chip_id == CHIP_ID_YUKON_EC_U ||
hw->chip_id == CHIP_ID_YUKON_EX ||
hw->chip_id == CHIP_ID_YUKON_SUPR) {
u16 pg;
pg = gm_phy_read(hw, port, PHY_MARV_EXT_ADR);
gm_phy_write(hw, port, PHY_MARV_EXT_ADR, 3);
switch (mode) {
case MO_LED_OFF:
gm_phy_write(hw, port, PHY_MARV_PHY_CTRL,
PHY_M_LEDC_LOS_CTRL(8) |
PHY_M_LEDC_INIT_CTRL(8) |
PHY_M_LEDC_STA1_CTRL(8) |
PHY_M_LEDC_STA0_CTRL(8));
break;
case MO_LED_ON:
gm_phy_write(hw, port, PHY_MARV_PHY_CTRL,
PHY_M_LEDC_LOS_CTRL(9) |
PHY_M_LEDC_INIT_CTRL(9) |
PHY_M_LEDC_STA1_CTRL(9) |
PHY_M_LEDC_STA0_CTRL(9));
break;
case MO_LED_BLINK:
gm_phy_write(hw, port, PHY_MARV_PHY_CTRL,
PHY_M_LEDC_LOS_CTRL(0xa) |
PHY_M_LEDC_INIT_CTRL(0xa) |
PHY_M_LEDC_STA1_CTRL(0xa) |
PHY_M_LEDC_STA0_CTRL(0xa));
break;
case MO_LED_NORM:
gm_phy_write(hw, port, PHY_MARV_PHY_CTRL,
PHY_M_LEDC_LOS_CTRL(1) |
PHY_M_LEDC_INIT_CTRL(8) |
PHY_M_LEDC_STA1_CTRL(7) |
PHY_M_LEDC_STA0_CTRL(7));
}
gm_phy_write(hw, port, PHY_MARV_EXT_ADR, pg);
} else
gm_phy_write(hw, port, PHY_MARV_LED_OVER,
PHY_M_LED_MO_DUP(mode) |
PHY_M_LED_MO_10(mode) |
PHY_M_LED_MO_100(mode) |
PHY_M_LED_MO_1000(mode) |
PHY_M_LED_MO_RX(mode) |
PHY_M_LED_MO_TX(mode));
spin_unlock_bh(&sky2->phy_lock);
}
/* blink LED's for finding board */
static int sky2_set_phys_id(struct net_device *dev,
enum ethtool_phys_id_state state)
{
struct sky2_port *sky2 = netdev_priv(dev);
switch (state) {
case ETHTOOL_ID_ACTIVE:
return 1; /* cycle on/off once per second */
case ETHTOOL_ID_INACTIVE:
sky2_led(sky2, MO_LED_NORM);
break;
case ETHTOOL_ID_ON:
sky2_led(sky2, MO_LED_ON);
break;
case ETHTOOL_ID_OFF:
sky2_led(sky2, MO_LED_OFF);
break;
}
return 0;
}
static void sky2_get_pauseparam(struct net_device *dev,
struct ethtool_pauseparam *ecmd)
{
struct sky2_port *sky2 = netdev_priv(dev);
switch (sky2->flow_mode) {
case FC_NONE:
ecmd->tx_pause = ecmd->rx_pause = 0;
break;
case FC_TX:
ecmd->tx_pause = 1, ecmd->rx_pause = 0;
break;
case FC_RX:
ecmd->tx_pause = 0, ecmd->rx_pause = 1;
break;
case FC_BOTH:
ecmd->tx_pause = ecmd->rx_pause = 1;
}
ecmd->autoneg = (sky2->flags & SKY2_FLAG_AUTO_PAUSE)
? AUTONEG_ENABLE : AUTONEG_DISABLE;
}
static int sky2_set_pauseparam(struct net_device *dev,
struct ethtool_pauseparam *ecmd)
{
struct sky2_port *sky2 = netdev_priv(dev);
if (ecmd->autoneg == AUTONEG_ENABLE)
sky2->flags |= SKY2_FLAG_AUTO_PAUSE;
else
sky2->flags &= ~SKY2_FLAG_AUTO_PAUSE;
sky2->flow_mode = sky2_flow(ecmd->rx_pause, ecmd->tx_pause);
if (netif_running(dev))
sky2_phy_reinit(sky2);
return 0;
}
static int sky2_get_coalesce(struct net_device *dev,
struct ethtool_coalesce *ecmd)
{
struct sky2_port *sky2 = netdev_priv(dev);
struct sky2_hw *hw = sky2->hw;
if (sky2_read8(hw, STAT_TX_TIMER_CTRL) == TIM_STOP)
ecmd->tx_coalesce_usecs = 0;
else {
u32 clks = sky2_read32(hw, STAT_TX_TIMER_INI);
ecmd->tx_coalesce_usecs = sky2_clk2us(hw, clks);
}
ecmd->tx_max_coalesced_frames = sky2_read16(hw, STAT_TX_IDX_TH);
if (sky2_read8(hw, STAT_LEV_TIMER_CTRL) == TIM_STOP)
ecmd->rx_coalesce_usecs = 0;
else {
u32 clks = sky2_read32(hw, STAT_LEV_TIMER_INI);
ecmd->rx_coalesce_usecs = sky2_clk2us(hw, clks);
}
ecmd->rx_max_coalesced_frames = sky2_read8(hw, STAT_FIFO_WM);
if (sky2_read8(hw, STAT_ISR_TIMER_CTRL) == TIM_STOP)
ecmd->rx_coalesce_usecs_irq = 0;
else {
u32 clks = sky2_read32(hw, STAT_ISR_TIMER_INI);
ecmd->rx_coalesce_usecs_irq = sky2_clk2us(hw, clks);
}
ecmd->rx_max_coalesced_frames_irq = sky2_read8(hw, STAT_FIFO_ISR_WM);
return 0;
}
/* Note: this affect both ports */
static int sky2_set_coalesce(struct net_device *dev,
struct ethtool_coalesce *ecmd)
{
struct sky2_port *sky2 = netdev_priv(dev);
struct sky2_hw *hw = sky2->hw;
const u32 tmax = sky2_clk2us(hw, 0x0ffffff);
if (ecmd->tx_coalesce_usecs > tmax ||
ecmd->rx_coalesce_usecs > tmax ||
ecmd->rx_coalesce_usecs_irq > tmax)
return -EINVAL;
if (ecmd->tx_max_coalesced_frames >= sky2->tx_ring_size-1)
return -EINVAL;
if (ecmd->rx_max_coalesced_frames > RX_MAX_PENDING)
return -EINVAL;
if (ecmd->rx_max_coalesced_frames_irq > RX_MAX_PENDING)
return -EINVAL;
if (ecmd->tx_coalesce_usecs == 0)
sky2_write8(hw, STAT_TX_TIMER_CTRL, TIM_STOP);
else {
sky2_write32(hw, STAT_TX_TIMER_INI,
sky2_us2clk(hw, ecmd->tx_coalesce_usecs));
sky2_write8(hw, STAT_TX_TIMER_CTRL, TIM_START);
}
sky2_write16(hw, STAT_TX_IDX_TH, ecmd->tx_max_coalesced_frames);
if (ecmd->rx_coalesce_usecs == 0)
sky2_write8(hw, STAT_LEV_TIMER_CTRL, TIM_STOP);
else {
sky2_write32(hw, STAT_LEV_TIMER_INI,
sky2_us2clk(hw, ecmd->rx_coalesce_usecs));
sky2_write8(hw, STAT_LEV_TIMER_CTRL, TIM_START);
}
sky2_write8(hw, STAT_FIFO_WM, ecmd->rx_max_coalesced_frames);
if (ecmd->rx_coalesce_usecs_irq == 0)
sky2_write8(hw, STAT_ISR_TIMER_CTRL, TIM_STOP);
else {
sky2_write32(hw, STAT_ISR_TIMER_INI,
sky2_us2clk(hw, ecmd->rx_coalesce_usecs_irq));
sky2_write8(hw, STAT_ISR_TIMER_CTRL, TIM_START);
}
sky2_write8(hw, STAT_FIFO_ISR_WM, ecmd->rx_max_coalesced_frames_irq);
return 0;
}
/*
* Hardware is limited to min of 128 and max of 2048 for ring size
* and rounded up to next power of two
* to avoid division in modulus calclation
*/
static unsigned long roundup_ring_size(unsigned long pending)
{
return max(128ul, roundup_pow_of_two(pending+1));
}
static void sky2_get_ringparam(struct net_device *dev,
struct ethtool_ringparam *ering)
{
struct sky2_port *sky2 = netdev_priv(dev);
ering->rx_max_pending = RX_MAX_PENDING;
ering->tx_max_pending = TX_MAX_PENDING;
ering->rx_pending = sky2->rx_pending;
ering->tx_pending = sky2->tx_pending;
}
static int sky2_set_ringparam(struct net_device *dev,
struct ethtool_ringparam *ering)
{
struct sky2_port *sky2 = netdev_priv(dev);
if (ering->rx_pending > RX_MAX_PENDING ||
ering->rx_pending < 8 ||
ering->tx_pending < TX_MIN_PENDING ||
ering->tx_pending > TX_MAX_PENDING)
return -EINVAL;
sky2_detach(dev);
sky2->rx_pending = ering->rx_pending;
sky2->tx_pending = ering->tx_pending;
sky2->tx_ring_size = roundup_ring_size(sky2->tx_pending);
return sky2_reattach(dev);
}
static int sky2_get_regs_len(struct net_device *dev)
{
return 0x4000;
}
static int sky2_reg_access_ok(struct sky2_hw *hw, unsigned int b)
{
/* This complicated switch statement is to make sure and
* only access regions that are unreserved.
* Some blocks are only valid on dual port cards.
*/
switch (b) {
/* second port */
case 5: /* Tx Arbiter 2 */
case 9: /* RX2 */
case 14 ... 15: /* TX2 */
case 17: case 19: /* Ram Buffer 2 */
case 22 ... 23: /* Tx Ram Buffer 2 */
case 25: /* Rx MAC Fifo 1 */
case 27: /* Tx MAC Fifo 2 */
case 31: /* GPHY 2 */
case 40 ... 47: /* Pattern Ram 2 */
case 52: case 54: /* TCP Segmentation 2 */
case 112 ... 116: /* GMAC 2 */
return hw->ports > 1;
case 0: /* Control */
case 2: /* Mac address */
case 4: /* Tx Arbiter 1 */
case 7: /* PCI express reg */
case 8: /* RX1 */
case 12 ... 13: /* TX1 */
case 16: case 18:/* Rx Ram Buffer 1 */
case 20 ... 21: /* Tx Ram Buffer 1 */
case 24: /* Rx MAC Fifo 1 */
case 26: /* Tx MAC Fifo 1 */
case 28 ... 29: /* Descriptor and status unit */
case 30: /* GPHY 1*/
case 32 ... 39: /* Pattern Ram 1 */
case 48: case 50: /* TCP Segmentation 1 */
case 56 ... 60: /* PCI space */
case 80 ... 84: /* GMAC 1 */
return 1;
default:
return 0;
}
}
/*
* Returns copy of control register region
* Note: ethtool_get_regs always provides full size (16k) buffer
*/
static void sky2_get_regs(struct net_device *dev, struct ethtool_regs *regs,
void *p)
{
const struct sky2_port *sky2 = netdev_priv(dev);
const void __iomem *io = sky2->hw->regs;
unsigned int b;
regs->version = 1;
for (b = 0; b < 128; b++) {
/* skip poisonous diagnostic ram region in block 3 */
if (b == 3)
memcpy_fromio(p + 0x10, io + 0x10, 128 - 0x10);
else if (sky2_reg_access_ok(sky2->hw, b))
memcpy_fromio(p, io, 128);
else
memset(p, 0, 128);
p += 128;
io += 128;
}
}
static int sky2_get_eeprom_len(struct net_device *dev)
{
struct sky2_port *sky2 = netdev_priv(dev);
struct sky2_hw *hw = sky2->hw;
u16 reg2;
reg2 = sky2_pci_read16(hw, PCI_DEV_REG2);
return 1 << ( ((reg2 & PCI_VPD_ROM_SZ) >> 14) + 8);
}
static int sky2_vpd_wait(const struct sky2_hw *hw, int cap, u16 busy)
{
unsigned long start = jiffies;
while ( (sky2_pci_read16(hw, cap + PCI_VPD_ADDR) & PCI_VPD_ADDR_F) == busy) {
/* Can take up to 10.6 ms for write */
if (time_after(jiffies, start + HZ/4)) {
dev_err(&hw->pdev->dev, "VPD cycle timed out\n");
return -ETIMEDOUT;
}
mdelay(1);
}
return 0;
}
static int sky2_vpd_read(struct sky2_hw *hw, int cap, void *data,
u16 offset, size_t length)
{
int rc = 0;
while (length > 0) {
u32 val;
sky2_pci_write16(hw, cap + PCI_VPD_ADDR, offset);
rc = sky2_vpd_wait(hw, cap, 0);
if (rc)
break;
val = sky2_pci_read32(hw, cap + PCI_VPD_DATA);
memcpy(data, &val, min(sizeof(val), length));
offset += sizeof(u32);
data += sizeof(u32);
length -= sizeof(u32);
}
return rc;
}
static int sky2_vpd_write(struct sky2_hw *hw, int cap, const void *data,
u16 offset, unsigned int length)
{
unsigned int i;
int rc = 0;
for (i = 0; i < length; i += sizeof(u32)) {
u32 val = *(u32 *)(data + i);
sky2_pci_write32(hw, cap + PCI_VPD_DATA, val);
sky2_pci_write32(hw, cap + PCI_VPD_ADDR, offset | PCI_VPD_ADDR_F);
rc = sky2_vpd_wait(hw, cap, PCI_VPD_ADDR_F);
if (rc)
break;
}
return rc;
}
static int sky2_get_eeprom(struct net_device *dev, struct ethtool_eeprom *eeprom,
u8 *data)
{
struct sky2_port *sky2 = netdev_priv(dev);
int cap = pci_find_capability(sky2->hw->pdev, PCI_CAP_ID_VPD);
if (!cap)
return -EINVAL;
eeprom->magic = SKY2_EEPROM_MAGIC;
return sky2_vpd_read(sky2->hw, cap, data, eeprom->offset, eeprom->len);
}
static int sky2_set_eeprom(struct net_device *dev, struct ethtool_eeprom *eeprom,
u8 *data)
{
struct sky2_port *sky2 = netdev_priv(dev);
int cap = pci_find_capability(sky2->hw->pdev, PCI_CAP_ID_VPD);
if (!cap)
return -EINVAL;
if (eeprom->magic != SKY2_EEPROM_MAGIC)
return -EINVAL;
/* Partial writes not supported */
if ((eeprom->offset & 3) || (eeprom->len & 3))
return -EINVAL;
return sky2_vpd_write(sky2->hw, cap, data, eeprom->offset, eeprom->len);
}
static netdev_features_t sky2_fix_features(struct net_device *dev,
netdev_features_t features)
{
const struct sky2_port *sky2 = netdev_priv(dev);
const struct sky2_hw *hw = sky2->hw;
/* In order to do Jumbo packets on these chips, need to turn off the
* transmit store/forward. Therefore checksum offload won't work.
*/
if (dev->mtu > ETH_DATA_LEN && hw->chip_id == CHIP_ID_YUKON_EC_U) {
netdev_info(dev, "checksum offload not possible with jumbo frames\n");
features &= ~(NETIF_F_TSO|NETIF_F_SG|NETIF_F_ALL_CSUM);
}
/* Some hardware requires receive checksum for RSS to work. */
if ( (features & NETIF_F_RXHASH) &&
!(features & NETIF_F_RXCSUM) &&
(sky2->hw->flags & SKY2_HW_RSS_CHKSUM)) {
netdev_info(dev, "receive hashing forces receive checksum\n");
features |= NETIF_F_RXCSUM;
}
return features;
}
static int sky2_set_features(struct net_device *dev, netdev_features_t features)
{
struct sky2_port *sky2 = netdev_priv(dev);
netdev_features_t changed = dev->features ^ features;
if ((changed & NETIF_F_RXCSUM) &&
!(sky2->hw->flags & SKY2_HW_NEW_LE)) {
sky2_write32(sky2->hw,
Q_ADDR(rxqaddr[sky2->port], Q_CSR),
(features & NETIF_F_RXCSUM)
? BMU_ENA_RX_CHKSUM : BMU_DIS_RX_CHKSUM);
}
if (changed & NETIF_F_RXHASH)
rx_set_rss(dev, features);
if (changed & (NETIF_F_HW_VLAN_CTAG_TX|NETIF_F_HW_VLAN_CTAG_RX))
sky2_vlan_mode(dev, features);
return 0;
}
static const struct ethtool_ops sky2_ethtool_ops = {
.get_settings = sky2_get_settings,
.set_settings = sky2_set_settings,
.get_drvinfo = sky2_get_drvinfo,
.get_wol = sky2_get_wol,
.set_wol = sky2_set_wol,
.get_msglevel = sky2_get_msglevel,
.set_msglevel = sky2_set_msglevel,
.nway_reset = sky2_nway_reset,
.get_regs_len = sky2_get_regs_len,
.get_regs = sky2_get_regs,
.get_link = ethtool_op_get_link,
.get_eeprom_len = sky2_get_eeprom_len,
.get_eeprom = sky2_get_eeprom,
.set_eeprom = sky2_set_eeprom,
.get_strings = sky2_get_strings,
.get_coalesce = sky2_get_coalesce,
.set_coalesce = sky2_set_coalesce,
.get_ringparam = sky2_get_ringparam,
.set_ringparam = sky2_set_ringparam,
.get_pauseparam = sky2_get_pauseparam,
.set_pauseparam = sky2_set_pauseparam,
.set_phys_id = sky2_set_phys_id,
.get_sset_count = sky2_get_sset_count,
.get_ethtool_stats = sky2_get_ethtool_stats,
};
#ifdef CONFIG_SKY2_DEBUG
static struct dentry *sky2_debug;
/*
* Read and parse the first part of Vital Product Data
*/
#define VPD_SIZE 128
#define VPD_MAGIC 0x82
static const struct vpd_tag {
char tag[2];
char *label;
} vpd_tags[] = {
{ "PN", "Part Number" },
{ "EC", "Engineering Level" },
{ "MN", "Manufacturer" },
{ "SN", "Serial Number" },
{ "YA", "Asset Tag" },
{ "VL", "First Error Log Message" },
{ "VF", "Second Error Log Message" },
{ "VB", "Boot Agent ROM Configuration" },
{ "VE", "EFI UNDI Configuration" },
};
static void sky2_show_vpd(struct seq_file *seq, struct sky2_hw *hw)
{
size_t vpd_size;
loff_t offs;
u8 len;
unsigned char *buf;
u16 reg2;
reg2 = sky2_pci_read16(hw, PCI_DEV_REG2);
vpd_size = 1 << ( ((reg2 & PCI_VPD_ROM_SZ) >> 14) + 8);
seq_printf(seq, "%s Product Data\n", pci_name(hw->pdev));
buf = kmalloc(vpd_size, GFP_KERNEL);
if (!buf) {
seq_puts(seq, "no memory!\n");
return;
}
if (pci_read_vpd(hw->pdev, 0, vpd_size, buf) < 0) {
seq_puts(seq, "VPD read failed\n");
goto out;
}
if (buf[0] != VPD_MAGIC) {
seq_printf(seq, "VPD tag mismatch: %#x\n", buf[0]);
goto out;
}
len = buf[1];
if (len == 0 || len > vpd_size - 4) {
seq_printf(seq, "Invalid id length: %d\n", len);
goto out;
}
seq_printf(seq, "%.*s\n", len, buf + 3);
offs = len + 3;
while (offs < vpd_size - 4) {
int i;
if (!memcmp("RW", buf + offs, 2)) /* end marker */
break;
len = buf[offs + 2];
if (offs + len + 3 >= vpd_size)
break;
for (i = 0; i < ARRAY_SIZE(vpd_tags); i++) {
if (!memcmp(vpd_tags[i].tag, buf + offs, 2)) {
seq_printf(seq, " %s: %.*s\n",
vpd_tags[i].label, len, buf + offs + 3);
break;
}
}
offs += len + 3;
}
out:
kfree(buf);
}
static int sky2_debug_show(struct seq_file *seq, void *v)
{
struct net_device *dev = seq->private;
const struct sky2_port *sky2 = netdev_priv(dev);
struct sky2_hw *hw = sky2->hw;
unsigned port = sky2->port;
unsigned idx, last;
int sop;
sky2_show_vpd(seq, hw);
seq_printf(seq, "\nIRQ src=%x mask=%x control=%x\n",
sky2_read32(hw, B0_ISRC),
sky2_read32(hw, B0_IMSK),
sky2_read32(hw, B0_Y2_SP_ICR));
if (!netif_running(dev)) {
seq_printf(seq, "network not running\n");
return 0;
}
napi_disable(&hw->napi);
last = sky2_read16(hw, STAT_PUT_IDX);
seq_printf(seq, "Status ring %u\n", hw->st_size);
if (hw->st_idx == last)
seq_puts(seq, "Status ring (empty)\n");
else {
seq_puts(seq, "Status ring\n");
for (idx = hw->st_idx; idx != last && idx < hw->st_size;
idx = RING_NEXT(idx, hw->st_size)) {
const struct sky2_status_le *le = hw->st_le + idx;
seq_printf(seq, "[%d] %#x %d %#x\n",
idx, le->opcode, le->length, le->status);
}
seq_puts(seq, "\n");
}
seq_printf(seq, "Tx ring pending=%u...%u report=%d done=%d\n",
sky2->tx_cons, sky2->tx_prod,
sky2_read16(hw, port == 0 ? STAT_TXA1_RIDX : STAT_TXA2_RIDX),
sky2_read16(hw, Q_ADDR(txqaddr[port], Q_DONE)));
/* Dump contents of tx ring */
sop = 1;
for (idx = sky2->tx_next; idx != sky2->tx_prod && idx < sky2->tx_ring_size;
idx = RING_NEXT(idx, sky2->tx_ring_size)) {
const struct sky2_tx_le *le = sky2->tx_le + idx;
u32 a = le32_to_cpu(le->addr);
if (sop)
seq_printf(seq, "%u:", idx);
sop = 0;
switch (le->opcode & ~HW_OWNER) {
case OP_ADDR64:
seq_printf(seq, " %#x:", a);
break;
case OP_LRGLEN:
seq_printf(seq, " mtu=%d", a);
break;
case OP_VLAN:
seq_printf(seq, " vlan=%d", be16_to_cpu(le->length));
break;
case OP_TCPLISW:
seq_printf(seq, " csum=%#x", a);
break;
case OP_LARGESEND:
seq_printf(seq, " tso=%#x(%d)", a, le16_to_cpu(le->length));
break;
case OP_PACKET:
seq_printf(seq, " %#x(%d)", a, le16_to_cpu(le->length));
break;
case OP_BUFFER:
seq_printf(seq, " frag=%#x(%d)", a, le16_to_cpu(le->length));
break;
default:
seq_printf(seq, " op=%#x,%#x(%d)", le->opcode,
a, le16_to_cpu(le->length));
}
if (le->ctrl & EOP) {
seq_putc(seq, '\n');
sop = 1;
}
}
seq_printf(seq, "\nRx ring hw get=%d put=%d last=%d\n",
sky2_read16(hw, Y2_QADDR(rxqaddr[port], PREF_UNIT_GET_IDX)),
sky2_read16(hw, Y2_QADDR(rxqaddr[port], PREF_UNIT_PUT_IDX)),
sky2_read16(hw, Y2_QADDR(rxqaddr[port], PREF_UNIT_LAST_IDX)));
sky2_read32(hw, B0_Y2_SP_LISR);
napi_enable(&hw->napi);
return 0;
}
static int sky2_debug_open(struct inode *inode, struct file *file)
{
return single_open(file, sky2_debug_show, inode->i_private);
}
static const struct file_operations sky2_debug_fops = {
.owner = THIS_MODULE,
.open = sky2_debug_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
/*
* Use network device events to create/remove/rename
* debugfs file entries
*/
static int sky2_device_event(struct notifier_block *unused,
unsigned long event, void *ptr)
{
struct net_device *dev = netdev_notifier_info_to_dev(ptr);
struct sky2_port *sky2 = netdev_priv(dev);
if (dev->netdev_ops->ndo_open != sky2_open || !sky2_debug)
return NOTIFY_DONE;
switch (event) {
case NETDEV_CHANGENAME:
if (sky2->debugfs) {
sky2->debugfs = debugfs_rename(sky2_debug, sky2->debugfs,
sky2_debug, dev->name);
}
break;
case NETDEV_GOING_DOWN:
if (sky2->debugfs) {
netdev_printk(KERN_DEBUG, dev, "remove debugfs\n");
debugfs_remove(sky2->debugfs);
sky2->debugfs = NULL;
}
break;
case NETDEV_UP:
sky2->debugfs = debugfs_create_file(dev->name, S_IRUGO,
sky2_debug, dev,
&sky2_debug_fops);
if (IS_ERR(sky2->debugfs))
sky2->debugfs = NULL;
}
return NOTIFY_DONE;
}
static struct notifier_block sky2_notifier = {
.notifier_call = sky2_device_event,
};
static __init void sky2_debug_init(void)
{
struct dentry *ent;
ent = debugfs_create_dir("sky2", NULL);
if (!ent || IS_ERR(ent))
return;
sky2_debug = ent;
register_netdevice_notifier(&sky2_notifier);
}
static __exit void sky2_debug_cleanup(void)
{
if (sky2_debug) {
unregister_netdevice_notifier(&sky2_notifier);
debugfs_remove(sky2_debug);
sky2_debug = NULL;
}
}
#else
#define sky2_debug_init()
#define sky2_debug_cleanup()
#endif
/* Two copies of network device operations to handle special case of
not allowing netpoll on second port */
static const struct net_device_ops sky2_netdev_ops[2] = {
{
.ndo_open = sky2_open,
.ndo_stop = sky2_close,
.ndo_start_xmit = sky2_xmit_frame,
.ndo_do_ioctl = sky2_ioctl,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = sky2_set_mac_address,
.ndo_set_rx_mode = sky2_set_multicast,
.ndo_change_mtu = sky2_change_mtu,
.ndo_fix_features = sky2_fix_features,
.ndo_set_features = sky2_set_features,
.ndo_tx_timeout = sky2_tx_timeout,
.ndo_get_stats64 = sky2_get_stats,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = sky2_netpoll,
#endif
},
{
.ndo_open = sky2_open,
.ndo_stop = sky2_close,
.ndo_start_xmit = sky2_xmit_frame,
.ndo_do_ioctl = sky2_ioctl,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = sky2_set_mac_address,
.ndo_set_rx_mode = sky2_set_multicast,
.ndo_change_mtu = sky2_change_mtu,
.ndo_fix_features = sky2_fix_features,
.ndo_set_features = sky2_set_features,
.ndo_tx_timeout = sky2_tx_timeout,
.ndo_get_stats64 = sky2_get_stats,
},
};
/* Initialize network device */
static struct net_device *sky2_init_netdev(struct sky2_hw *hw, unsigned port,
int highmem, int wol)
{
struct sky2_port *sky2;
struct net_device *dev = alloc_etherdev(sizeof(*sky2));
const void *iap;
if (!dev)
return NULL;
SET_NETDEV_DEV(dev, &hw->pdev->dev);
dev->irq = hw->pdev->irq;
dev->ethtool_ops = &sky2_ethtool_ops;
dev->watchdog_timeo = TX_WATCHDOG;
dev->netdev_ops = &sky2_netdev_ops[port];
sky2 = netdev_priv(dev);
sky2->netdev = dev;
sky2->hw = hw;
sky2->msg_enable = netif_msg_init(debug, default_msg);
u64_stats_init(&sky2->tx_stats.syncp);
u64_stats_init(&sky2->rx_stats.syncp);
/* Auto speed and flow control */
sky2->flags = SKY2_FLAG_AUTO_SPEED | SKY2_FLAG_AUTO_PAUSE;
if (hw->chip_id != CHIP_ID_YUKON_XL)
dev->hw_features |= NETIF_F_RXCSUM;
sky2->flow_mode = FC_BOTH;
sky2->duplex = -1;
sky2->speed = -1;
sky2->advertising = sky2_supported_modes(hw);
sky2->wol = wol;
spin_lock_init(&sky2->phy_lock);
sky2->tx_pending = TX_DEF_PENDING;
sky2->tx_ring_size = roundup_ring_size(TX_DEF_PENDING);
sky2->rx_pending = RX_DEF_PENDING;
hw->dev[port] = dev;
sky2->port = port;
dev->hw_features |= NETIF_F_IP_CSUM | NETIF_F_SG | NETIF_F_TSO;
if (highmem)
dev->features |= NETIF_F_HIGHDMA;
/* Enable receive hashing unless hardware is known broken */
if (!(hw->flags & SKY2_HW_RSS_BROKEN))
dev->hw_features |= NETIF_F_RXHASH;
if (!(hw->flags & SKY2_HW_VLAN_BROKEN)) {
dev->hw_features |= NETIF_F_HW_VLAN_CTAG_TX |
NETIF_F_HW_VLAN_CTAG_RX;
dev->vlan_features |= SKY2_VLAN_OFFLOADS;
}
dev->features |= dev->hw_features;
/* try to get mac address in the following order:
* 1) from device tree data
* 2) from internal registers set by bootloader
*/
iap = of_get_mac_address(hw->pdev->dev.of_node);
if (iap)
memcpy(dev->dev_addr, iap, ETH_ALEN);
else
memcpy_fromio(dev->dev_addr, hw->regs + B2_MAC_1 + port * 8,
ETH_ALEN);
return dev;
}
static void sky2_show_addr(struct net_device *dev)
{
const struct sky2_port *sky2 = netdev_priv(dev);
netif_info(sky2, probe, dev, "addr %pM\n", dev->dev_addr);
}
/* Handle software interrupt used during MSI test */
static irqreturn_t sky2_test_intr(int irq, void *dev_id)
{
struct sky2_hw *hw = dev_id;
u32 status = sky2_read32(hw, B0_Y2_SP_ISRC2);
if (status == 0)
return IRQ_NONE;
if (status & Y2_IS_IRQ_SW) {
hw->flags |= SKY2_HW_USE_MSI;
wake_up(&hw->msi_wait);
sky2_write8(hw, B0_CTST, CS_CL_SW_IRQ);
}
sky2_write32(hw, B0_Y2_SP_ICR, 2);
return IRQ_HANDLED;
}
/* Test interrupt path by forcing a a software IRQ */
static int sky2_test_msi(struct sky2_hw *hw)
{
struct pci_dev *pdev = hw->pdev;
int err;
init_waitqueue_head(&hw->msi_wait);
err = request_irq(pdev->irq, sky2_test_intr, 0, DRV_NAME, hw);
if (err) {
dev_err(&pdev->dev, "cannot assign irq %d\n", pdev->irq);
return err;
}
sky2_write32(hw, B0_IMSK, Y2_IS_IRQ_SW);
sky2_write8(hw, B0_CTST, CS_ST_SW_IRQ);
sky2_read8(hw, B0_CTST);
wait_event_timeout(hw->msi_wait, (hw->flags & SKY2_HW_USE_MSI), HZ/10);
if (!(hw->flags & SKY2_HW_USE_MSI)) {
/* MSI test failed, go back to INTx mode */
dev_info(&pdev->dev, "No interrupt generated using MSI, "
"switching to INTx mode.\n");
err = -EOPNOTSUPP;
sky2_write8(hw, B0_CTST, CS_CL_SW_IRQ);
}
sky2_write32(hw, B0_IMSK, 0);
sky2_read32(hw, B0_IMSK);
free_irq(pdev->irq, hw);
return err;
}
/* This driver supports yukon2 chipset only */
static const char *sky2_name(u8 chipid, char *buf, int sz)
{
const char *name[] = {
"XL", /* 0xb3 */
"EC Ultra", /* 0xb4 */
"Extreme", /* 0xb5 */
"EC", /* 0xb6 */
"FE", /* 0xb7 */
"FE+", /* 0xb8 */
"Supreme", /* 0xb9 */
"UL 2", /* 0xba */
"Unknown", /* 0xbb */
"Optima", /* 0xbc */
"OptimaEEE", /* 0xbd */
"Optima 2", /* 0xbe */
};
if (chipid >= CHIP_ID_YUKON_XL && chipid <= CHIP_ID_YUKON_OP_2)
strncpy(buf, name[chipid - CHIP_ID_YUKON_XL], sz);
else
snprintf(buf, sz, "(chip %#x)", chipid);
return buf;
}
static int sky2_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
{
struct net_device *dev, *dev1;
struct sky2_hw *hw;
int err, using_dac = 0, wol_default;
u32 reg;
char buf1[16];
err = pci_enable_device(pdev);
if (err) {
dev_err(&pdev->dev, "cannot enable PCI device\n");
goto err_out;
}
/* Get configuration information
* Note: only regular PCI config access once to test for HW issues
* other PCI access through shared memory for speed and to
* avoid MMCONFIG problems.
*/
err = pci_read_config_dword(pdev, PCI_DEV_REG2, ®);
if (err) {
dev_err(&pdev->dev, "PCI read config failed\n");
goto err_out_disable;
}
if (~reg == 0) {
dev_err(&pdev->dev, "PCI configuration read error\n");
err = -EIO;
goto err_out_disable;
}
err = pci_request_regions(pdev, DRV_NAME);
if (err) {
dev_err(&pdev->dev, "cannot obtain PCI resources\n");
goto err_out_disable;
}
pci_set_master(pdev);
if (sizeof(dma_addr_t) > sizeof(u32) &&
!(err = pci_set_dma_mask(pdev, DMA_BIT_MASK(64)))) {
using_dac = 1;
err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64));
if (err < 0) {
dev_err(&pdev->dev, "unable to obtain 64 bit DMA "
"for consistent allocations\n");
goto err_out_free_regions;
}
} else {
err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (err) {
dev_err(&pdev->dev, "no usable DMA configuration\n");
goto err_out_free_regions;
}
}
#ifdef __BIG_ENDIAN
/* The sk98lin vendor driver uses hardware byte swapping but
* this driver uses software swapping.
*/
reg &= ~PCI_REV_DESC;
err = pci_write_config_dword(pdev, PCI_DEV_REG2, reg);
if (err) {
dev_err(&pdev->dev, "PCI write config failed\n");
goto err_out_free_regions;
}
#endif
wol_default = device_may_wakeup(&pdev->dev) ? WAKE_MAGIC : 0;
err = -ENOMEM;
hw = kzalloc(sizeof(*hw) + strlen(DRV_NAME "@pci:")
+ strlen(pci_name(pdev)) + 1, GFP_KERNEL);
if (!hw)
goto err_out_free_regions;
hw->pdev = pdev;
sprintf(hw->irq_name, DRV_NAME "@pci:%s", pci_name(pdev));
hw->regs = ioremap_nocache(pci_resource_start(pdev, 0), 0x4000);
if (!hw->regs) {
dev_err(&pdev->dev, "cannot map device registers\n");
goto err_out_free_hw;
}
err = sky2_init(hw);
if (err)
goto err_out_iounmap;
/* ring for status responses */
hw->st_size = hw->ports * roundup_pow_of_two(3*RX_MAX_PENDING + TX_MAX_PENDING);
hw->st_le = pci_alloc_consistent(pdev, hw->st_size * sizeof(struct sky2_status_le),
&hw->st_dma);
if (!hw->st_le) {
err = -ENOMEM;
goto err_out_reset;
}
dev_info(&pdev->dev, "Yukon-2 %s chip revision %d\n",
sky2_name(hw->chip_id, buf1, sizeof(buf1)), hw->chip_rev);
sky2_reset(hw);
dev = sky2_init_netdev(hw, 0, using_dac, wol_default);
if (!dev) {
err = -ENOMEM;
goto err_out_free_pci;
}
if (!disable_msi && pci_enable_msi(pdev) == 0) {
err = sky2_test_msi(hw);
if (err) {
pci_disable_msi(pdev);
if (err != -EOPNOTSUPP)
goto err_out_free_netdev;
}
}
netif_napi_add(dev, &hw->napi, sky2_poll, NAPI_WEIGHT);
err = register_netdev(dev);
if (err) {
dev_err(&pdev->dev, "cannot register net device\n");
goto err_out_free_netdev;
}
netif_carrier_off(dev);
sky2_show_addr(dev);
if (hw->ports > 1) {
dev1 = sky2_init_netdev(hw, 1, using_dac, wol_default);
if (!dev1) {
err = -ENOMEM;
goto err_out_unregister;
}
err = register_netdev(dev1);
if (err) {
dev_err(&pdev->dev, "cannot register second net device\n");
goto err_out_free_dev1;
}
err = sky2_setup_irq(hw, hw->irq_name);
if (err)
goto err_out_unregister_dev1;
sky2_show_addr(dev1);
}
setup_timer(&hw->watchdog_timer, sky2_watchdog, (unsigned long) hw);
INIT_WORK(&hw->restart_work, sky2_restart);
pci_set_drvdata(pdev, hw);
pdev->d3_delay = 150;
return 0;
err_out_unregister_dev1:
unregister_netdev(dev1);
err_out_free_dev1:
free_netdev(dev1);
err_out_unregister:
unregister_netdev(dev);
err_out_free_netdev:
if (hw->flags & SKY2_HW_USE_MSI)
pci_disable_msi(pdev);
free_netdev(dev);
err_out_free_pci:
pci_free_consistent(pdev, hw->st_size * sizeof(struct sky2_status_le),
hw->st_le, hw->st_dma);
err_out_reset:
sky2_write8(hw, B0_CTST, CS_RST_SET);
err_out_iounmap:
iounmap(hw->regs);
err_out_free_hw:
kfree(hw);
err_out_free_regions:
pci_release_regions(pdev);
err_out_disable:
pci_disable_device(pdev);
err_out:
return err;
}
static void sky2_remove(struct pci_dev *pdev)
{
struct sky2_hw *hw = pci_get_drvdata(pdev);
int i;
if (!hw)
return;
del_timer_sync(&hw->watchdog_timer);
cancel_work_sync(&hw->restart_work);
for (i = hw->ports-1; i >= 0; --i)
unregister_netdev(hw->dev[i]);
sky2_write32(hw, B0_IMSK, 0);
sky2_read32(hw, B0_IMSK);
sky2_power_aux(hw);
sky2_write8(hw, B0_CTST, CS_RST_SET);
sky2_read8(hw, B0_CTST);
if (hw->ports > 1) {
napi_disable(&hw->napi);
free_irq(pdev->irq, hw);
}
if (hw->flags & SKY2_HW_USE_MSI)
pci_disable_msi(pdev);
pci_free_consistent(pdev, hw->st_size * sizeof(struct sky2_status_le),
hw->st_le, hw->st_dma);
pci_release_regions(pdev);
pci_disable_device(pdev);
for (i = hw->ports-1; i >= 0; --i)
free_netdev(hw->dev[i]);
iounmap(hw->regs);
kfree(hw);
}
static int sky2_suspend(struct device *dev)
{
struct pci_dev *pdev = to_pci_dev(dev);
struct sky2_hw *hw = pci_get_drvdata(pdev);
int i;
if (!hw)
return 0;
del_timer_sync(&hw->watchdog_timer);
cancel_work_sync(&hw->restart_work);
rtnl_lock();
sky2_all_down(hw);
for (i = 0; i < hw->ports; i++) {
struct net_device *dev = hw->dev[i];
struct sky2_port *sky2 = netdev_priv(dev);
if (sky2->wol)
sky2_wol_init(sky2);
}
sky2_power_aux(hw);
rtnl_unlock();
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int sky2_resume(struct device *dev)
{
struct pci_dev *pdev = to_pci_dev(dev);
struct sky2_hw *hw = pci_get_drvdata(pdev);
int err;
if (!hw)
return 0;
/* Re-enable all clocks */
err = pci_write_config_dword(pdev, PCI_DEV_REG3, 0);
if (err) {
dev_err(&pdev->dev, "PCI write config failed\n");
goto out;
}
rtnl_lock();
sky2_reset(hw);
sky2_all_up(hw);
rtnl_unlock();
return 0;
out:
dev_err(&pdev->dev, "resume failed (%d)\n", err);
pci_disable_device(pdev);
return err;
}
static SIMPLE_DEV_PM_OPS(sky2_pm_ops, sky2_suspend, sky2_resume);
#define SKY2_PM_OPS (&sky2_pm_ops)
#else
#define SKY2_PM_OPS NULL
#endif
static void sky2_shutdown(struct pci_dev *pdev)
{
sky2_suspend(&pdev->dev);
pci_wake_from_d3(pdev, device_may_wakeup(&pdev->dev));
pci_set_power_state(pdev, PCI_D3hot);
}
static struct pci_driver sky2_driver = {
.name = DRV_NAME,
.id_table = sky2_id_table,
.probe = sky2_probe,
.remove = sky2_remove,
.shutdown = sky2_shutdown,
.driver.pm = SKY2_PM_OPS,
};
static int __init sky2_init_module(void)
{
pr_info("driver version " DRV_VERSION "\n");
sky2_debug_init();
return pci_register_driver(&sky2_driver);
}
static void __exit sky2_cleanup_module(void)
{
pci_unregister_driver(&sky2_driver);
sky2_debug_cleanup();
}
module_init(sky2_init_module);
module_exit(sky2_cleanup_module);
MODULE_DESCRIPTION("Marvell Yukon 2 Gigabit Ethernet driver");
MODULE_AUTHOR("Stephen Hemminger <shemminger@linux-foundation.org>");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
| gpl-2.0 |
loxK/kernel-hero | arch/x86/kernel/cpu/mtrr/centaur.c | 313 | 5432 | #include <linux/init.h>
#include <linux/mm.h>
#include <asm/mtrr.h>
#include <asm/msr.h>
#include "mtrr.h"
static struct {
unsigned long high;
unsigned long low;
} centaur_mcr[8];
static u8 centaur_mcr_reserved;
static u8 centaur_mcr_type; /* 0 for winchip, 1 for winchip2 */
/*
* Report boot time MCR setups
*/
static int
centaur_get_free_region(unsigned long base, unsigned long size, int replace_reg)
/* [SUMMARY] Get a free MTRR.
<base> The starting (base) address of the region.
<size> The size (in bytes) of the region.
[RETURNS] The index of the region on success, else -1 on error.
*/
{
int i, max;
mtrr_type ltype;
unsigned long lbase, lsize;
max = num_var_ranges;
if (replace_reg >= 0 && replace_reg < max)
return replace_reg;
for (i = 0; i < max; ++i) {
if (centaur_mcr_reserved & (1 << i))
continue;
mtrr_if->get(i, &lbase, &lsize, <ype);
if (lsize == 0)
return i;
}
return -ENOSPC;
}
void
mtrr_centaur_report_mcr(int mcr, u32 lo, u32 hi)
{
centaur_mcr[mcr].low = lo;
centaur_mcr[mcr].high = hi;
}
static void
centaur_get_mcr(unsigned int reg, unsigned long *base,
unsigned long *size, mtrr_type * type)
{
*base = centaur_mcr[reg].high >> PAGE_SHIFT;
*size = -(centaur_mcr[reg].low & 0xfffff000) >> PAGE_SHIFT;
*type = MTRR_TYPE_WRCOMB; /* If it is there, it is write-combining */
if (centaur_mcr_type == 1 && ((centaur_mcr[reg].low & 31) & 2))
*type = MTRR_TYPE_UNCACHABLE;
if (centaur_mcr_type == 1 && (centaur_mcr[reg].low & 31) == 25)
*type = MTRR_TYPE_WRBACK;
if (centaur_mcr_type == 0 && (centaur_mcr[reg].low & 31) == 31)
*type = MTRR_TYPE_WRBACK;
}
static void centaur_set_mcr(unsigned int reg, unsigned long base,
unsigned long size, mtrr_type type)
{
unsigned long low, high;
if (size == 0) {
/* Disable */
high = low = 0;
} else {
high = base << PAGE_SHIFT;
if (centaur_mcr_type == 0)
low = -size << PAGE_SHIFT | 0x1f; /* only support write-combining... */
else {
if (type == MTRR_TYPE_UNCACHABLE)
low = -size << PAGE_SHIFT | 0x02; /* NC */
else
low = -size << PAGE_SHIFT | 0x09; /* WWO,WC */
}
}
centaur_mcr[reg].high = high;
centaur_mcr[reg].low = low;
wrmsr(MSR_IDT_MCR0 + reg, low, high);
}
#if 0
/*
* Initialise the later (saner) Winchip MCR variant. In this version
* the BIOS can pass us the registers it has used (but not their values)
* and the control register is read/write
*/
static void __init
centaur_mcr1_init(void)
{
unsigned i;
u32 lo, hi;
/* Unfortunately, MCR's are read-only, so there is no way to
* find out what the bios might have done.
*/
rdmsr(MSR_IDT_MCR_CTRL, lo, hi);
if (((lo >> 17) & 7) == 1) { /* Type 1 Winchip2 MCR */
lo &= ~0x1C0; /* clear key */
lo |= 0x040; /* set key to 1 */
wrmsr(MSR_IDT_MCR_CTRL, lo, hi); /* unlock MCR */
}
centaur_mcr_type = 1;
/*
* Clear any unconfigured MCR's.
*/
for (i = 0; i < 8; ++i) {
if (centaur_mcr[i].high == 0 && centaur_mcr[i].low == 0) {
if (!(lo & (1 << (9 + i))))
wrmsr(MSR_IDT_MCR0 + i, 0, 0);
else
/*
* If the BIOS set up an MCR we cannot see it
* but we don't wish to obliterate it
*/
centaur_mcr_reserved |= (1 << i);
}
}
/*
* Throw the main write-combining switch...
* However if OOSTORE is enabled then people have already done far
* cleverer things and we should behave.
*/
lo |= 15; /* Write combine enables */
wrmsr(MSR_IDT_MCR_CTRL, lo, hi);
}
/*
* Initialise the original winchip with read only MCR registers
* no used bitmask for the BIOS to pass on and write only control
*/
static void __init
centaur_mcr0_init(void)
{
unsigned i;
/* Unfortunately, MCR's are read-only, so there is no way to
* find out what the bios might have done.
*/
/* Clear any unconfigured MCR's.
* This way we are sure that the centaur_mcr array contains the actual
* values. The disadvantage is that any BIOS tweaks are thus undone.
*
*/
for (i = 0; i < 8; ++i) {
if (centaur_mcr[i].high == 0 && centaur_mcr[i].low == 0)
wrmsr(MSR_IDT_MCR0 + i, 0, 0);
}
wrmsr(MSR_IDT_MCR_CTRL, 0x01F0001F, 0); /* Write only */
}
/*
* Initialise Winchip series MCR registers
*/
static void __init
centaur_mcr_init(void)
{
struct set_mtrr_context ctxt;
set_mtrr_prepare_save(&ctxt);
set_mtrr_cache_disable(&ctxt);
if (boot_cpu_data.x86_model == 4)
centaur_mcr0_init();
else if (boot_cpu_data.x86_model == 8 || boot_cpu_data.x86_model == 9)
centaur_mcr1_init();
set_mtrr_done(&ctxt);
}
#endif
static int centaur_validate_add_page(unsigned long base,
unsigned long size, unsigned int type)
{
/*
* FIXME: Winchip2 supports uncached
*/
if (type != MTRR_TYPE_WRCOMB &&
(centaur_mcr_type == 0 || type != MTRR_TYPE_UNCACHABLE)) {
printk(KERN_WARNING
"mtrr: only write-combining%s supported\n",
centaur_mcr_type ? " and uncacheable are"
: " is");
return -EINVAL;
}
return 0;
}
static struct mtrr_ops centaur_mtrr_ops = {
.vendor = X86_VENDOR_CENTAUR,
// .init = centaur_mcr_init,
.set = centaur_set_mcr,
.get = centaur_get_mcr,
.get_free_region = centaur_get_free_region,
.validate_add_page = centaur_validate_add_page,
.have_wrcomb = positive_have_wrcomb,
};
int __init centaur_init_mtrr(void)
{
set_mtrr_ops(¢aur_mtrr_ops);
return 0;
}
//arch_initcall(centaur_init_mtrr);
| gpl-2.0 |
gpandcb/pkernel | net/ipv4/tcp_cong.c | 313 | 11129 | /*
* Pluggable TCP congestion control support and newReno
* congestion control.
* Based on ideas from I/O scheduler support and Web100.
*
* Copyright (C) 2005 Stephen Hemminger <shemminger@osdl.org>
*/
#define pr_fmt(fmt) "TCP: " fmt
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/types.h>
#include <linux/list.h>
#include <linux/gfp.h>
#include <linux/jhash.h>
#include <net/tcp.h>
static DEFINE_SPINLOCK(tcp_cong_list_lock);
static LIST_HEAD(tcp_cong_list);
/* Simple linear search, don't expect many entries! */
static struct tcp_congestion_ops *tcp_ca_find(const char *name)
{
struct tcp_congestion_ops *e;
list_for_each_entry_rcu(e, &tcp_cong_list, list) {
if (strcmp(e->name, name) == 0)
return e;
}
return NULL;
}
/* Must be called with rcu lock held */
static const struct tcp_congestion_ops *__tcp_ca_find_autoload(const char *name)
{
const struct tcp_congestion_ops *ca = tcp_ca_find(name);
#ifdef CONFIG_MODULES
if (!ca && capable(CAP_NET_ADMIN)) {
rcu_read_unlock();
request_module("tcp_%s", name);
rcu_read_lock();
ca = tcp_ca_find(name);
}
#endif
return ca;
}
/* Simple linear search, not much in here. */
struct tcp_congestion_ops *tcp_ca_find_key(u32 key)
{
struct tcp_congestion_ops *e;
list_for_each_entry_rcu(e, &tcp_cong_list, list) {
if (e->key == key)
return e;
}
return NULL;
}
/*
* Attach new congestion control algorithm to the list
* of available options.
*/
int tcp_register_congestion_control(struct tcp_congestion_ops *ca)
{
int ret = 0;
/* all algorithms must implement ssthresh and cong_avoid ops */
if (!ca->ssthresh || !ca->cong_avoid) {
pr_err("%s does not implement required ops\n", ca->name);
return -EINVAL;
}
ca->key = jhash(ca->name, sizeof(ca->name), strlen(ca->name));
spin_lock(&tcp_cong_list_lock);
if (ca->key == TCP_CA_UNSPEC || tcp_ca_find_key(ca->key)) {
pr_notice("%s already registered or non-unique key\n",
ca->name);
ret = -EEXIST;
} else {
list_add_tail_rcu(&ca->list, &tcp_cong_list);
pr_debug("%s registered\n", ca->name);
}
spin_unlock(&tcp_cong_list_lock);
return ret;
}
EXPORT_SYMBOL_GPL(tcp_register_congestion_control);
/*
* Remove congestion control algorithm, called from
* the module's remove function. Module ref counts are used
* to ensure that this can't be done till all sockets using
* that method are closed.
*/
void tcp_unregister_congestion_control(struct tcp_congestion_ops *ca)
{
spin_lock(&tcp_cong_list_lock);
list_del_rcu(&ca->list);
spin_unlock(&tcp_cong_list_lock);
/* Wait for outstanding readers to complete before the
* module gets removed entirely.
*
* A try_module_get() should fail by now as our module is
* in "going" state since no refs are held anymore and
* module_exit() handler being called.
*/
synchronize_rcu();
}
EXPORT_SYMBOL_GPL(tcp_unregister_congestion_control);
u32 tcp_ca_get_key_by_name(const char *name, bool *ecn_ca)
{
const struct tcp_congestion_ops *ca;
u32 key = TCP_CA_UNSPEC;
might_sleep();
rcu_read_lock();
ca = __tcp_ca_find_autoload(name);
if (ca) {
key = ca->key;
*ecn_ca = ca->flags & TCP_CONG_NEEDS_ECN;
}
rcu_read_unlock();
return key;
}
EXPORT_SYMBOL_GPL(tcp_ca_get_key_by_name);
char *tcp_ca_get_name_by_key(u32 key, char *buffer)
{
const struct tcp_congestion_ops *ca;
char *ret = NULL;
rcu_read_lock();
ca = tcp_ca_find_key(key);
if (ca)
ret = strncpy(buffer, ca->name,
TCP_CA_NAME_MAX);
rcu_read_unlock();
return ret;
}
EXPORT_SYMBOL_GPL(tcp_ca_get_name_by_key);
/* Assign choice of congestion control. */
void tcp_assign_congestion_control(struct sock *sk)
{
struct inet_connection_sock *icsk = inet_csk(sk);
struct tcp_congestion_ops *ca;
rcu_read_lock();
list_for_each_entry_rcu(ca, &tcp_cong_list, list) {
if (likely(try_module_get(ca->owner))) {
icsk->icsk_ca_ops = ca;
goto out;
}
/* Fallback to next available. The last really
* guaranteed fallback is Reno from this list.
*/
}
out:
rcu_read_unlock();
/* Clear out private data before diag gets it and
* the ca has not been initialized.
*/
if (ca->get_info)
memset(icsk->icsk_ca_priv, 0, sizeof(icsk->icsk_ca_priv));
if (ca->flags & TCP_CONG_NEEDS_ECN)
INET_ECN_xmit(sk);
else
INET_ECN_dontxmit(sk);
}
void tcp_init_congestion_control(struct sock *sk)
{
const struct inet_connection_sock *icsk = inet_csk(sk);
if (icsk->icsk_ca_ops->init)
icsk->icsk_ca_ops->init(sk);
if (tcp_ca_needs_ecn(sk))
INET_ECN_xmit(sk);
else
INET_ECN_dontxmit(sk);
}
static void tcp_reinit_congestion_control(struct sock *sk,
const struct tcp_congestion_ops *ca)
{
struct inet_connection_sock *icsk = inet_csk(sk);
tcp_cleanup_congestion_control(sk);
icsk->icsk_ca_ops = ca;
icsk->icsk_ca_setsockopt = 1;
if (sk->sk_state != TCP_CLOSE)
tcp_init_congestion_control(sk);
}
/* Manage refcounts on socket close. */
void tcp_cleanup_congestion_control(struct sock *sk)
{
struct inet_connection_sock *icsk = inet_csk(sk);
if (icsk->icsk_ca_ops->release)
icsk->icsk_ca_ops->release(sk);
module_put(icsk->icsk_ca_ops->owner);
}
/* Used by sysctl to change default congestion control */
int tcp_set_default_congestion_control(const char *name)
{
struct tcp_congestion_ops *ca;
int ret = -ENOENT;
spin_lock(&tcp_cong_list_lock);
ca = tcp_ca_find(name);
#ifdef CONFIG_MODULES
if (!ca && capable(CAP_NET_ADMIN)) {
spin_unlock(&tcp_cong_list_lock);
request_module("tcp_%s", name);
spin_lock(&tcp_cong_list_lock);
ca = tcp_ca_find(name);
}
#endif
if (ca) {
ca->flags |= TCP_CONG_NON_RESTRICTED; /* default is always allowed */
list_move(&ca->list, &tcp_cong_list);
ret = 0;
}
spin_unlock(&tcp_cong_list_lock);
return ret;
}
/* Set default value from kernel configuration at bootup */
static int __init tcp_congestion_default(void)
{
return tcp_set_default_congestion_control(CONFIG_DEFAULT_TCP_CONG);
}
late_initcall(tcp_congestion_default);
/* Build string with list of available congestion control values */
void tcp_get_available_congestion_control(char *buf, size_t maxlen)
{
struct tcp_congestion_ops *ca;
size_t offs = 0;
rcu_read_lock();
list_for_each_entry_rcu(ca, &tcp_cong_list, list) {
offs += snprintf(buf + offs, maxlen - offs,
"%s%s",
offs == 0 ? "" : " ", ca->name);
}
rcu_read_unlock();
}
/* Get current default congestion control */
void tcp_get_default_congestion_control(char *name)
{
struct tcp_congestion_ops *ca;
/* We will always have reno... */
BUG_ON(list_empty(&tcp_cong_list));
rcu_read_lock();
ca = list_entry(tcp_cong_list.next, struct tcp_congestion_ops, list);
strncpy(name, ca->name, TCP_CA_NAME_MAX);
rcu_read_unlock();
}
/* Built list of non-restricted congestion control values */
void tcp_get_allowed_congestion_control(char *buf, size_t maxlen)
{
struct tcp_congestion_ops *ca;
size_t offs = 0;
*buf = '\0';
rcu_read_lock();
list_for_each_entry_rcu(ca, &tcp_cong_list, list) {
if (!(ca->flags & TCP_CONG_NON_RESTRICTED))
continue;
offs += snprintf(buf + offs, maxlen - offs,
"%s%s",
offs == 0 ? "" : " ", ca->name);
}
rcu_read_unlock();
}
/* Change list of non-restricted congestion control */
int tcp_set_allowed_congestion_control(char *val)
{
struct tcp_congestion_ops *ca;
char *saved_clone, *clone, *name;
int ret = 0;
saved_clone = clone = kstrdup(val, GFP_USER);
if (!clone)
return -ENOMEM;
spin_lock(&tcp_cong_list_lock);
/* pass 1 check for bad entries */
while ((name = strsep(&clone, " ")) && *name) {
ca = tcp_ca_find(name);
if (!ca) {
ret = -ENOENT;
goto out;
}
}
/* pass 2 clear old values */
list_for_each_entry_rcu(ca, &tcp_cong_list, list)
ca->flags &= ~TCP_CONG_NON_RESTRICTED;
/* pass 3 mark as allowed */
while ((name = strsep(&val, " ")) && *name) {
ca = tcp_ca_find(name);
WARN_ON(!ca);
if (ca)
ca->flags |= TCP_CONG_NON_RESTRICTED;
}
out:
spin_unlock(&tcp_cong_list_lock);
kfree(saved_clone);
return ret;
}
/* Change congestion control for socket */
int tcp_set_congestion_control(struct sock *sk, const char *name)
{
struct inet_connection_sock *icsk = inet_csk(sk);
const struct tcp_congestion_ops *ca;
int err = 0;
if (icsk->icsk_ca_dst_locked)
return -EPERM;
rcu_read_lock();
ca = __tcp_ca_find_autoload(name);
/* No change asking for existing value */
if (ca == icsk->icsk_ca_ops) {
icsk->icsk_ca_setsockopt = 1;
goto out;
}
if (!ca)
err = -ENOENT;
else if (!((ca->flags & TCP_CONG_NON_RESTRICTED) ||
ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)))
err = -EPERM;
else if (!try_module_get(ca->owner))
err = -EBUSY;
else
tcp_reinit_congestion_control(sk, ca);
out:
rcu_read_unlock();
return err;
}
/* Slow start is used when congestion window is no greater than the slow start
* threshold. We base on RFC2581 and also handle stretch ACKs properly.
* We do not implement RFC3465 Appropriate Byte Counting (ABC) per se but
* something better;) a packet is only considered (s)acked in its entirety to
* defend the ACK attacks described in the RFC. Slow start processes a stretch
* ACK of degree N as if N acks of degree 1 are received back to back except
* ABC caps N to 2. Slow start exits when cwnd grows over ssthresh and
* returns the leftover acks to adjust cwnd in congestion avoidance mode.
*/
u32 tcp_slow_start(struct tcp_sock *tp, u32 acked)
{
u32 cwnd = min(tp->snd_cwnd + acked, tp->snd_ssthresh);
acked -= cwnd - tp->snd_cwnd;
tp->snd_cwnd = min(cwnd, tp->snd_cwnd_clamp);
return acked;
}
EXPORT_SYMBOL_GPL(tcp_slow_start);
/* In theory this is tp->snd_cwnd += 1 / tp->snd_cwnd (or alternative w),
* for every packet that was ACKed.
*/
void tcp_cong_avoid_ai(struct tcp_sock *tp, u32 w, u32 acked)
{
/* If credits accumulated at a higher w, apply them gently now. */
if (tp->snd_cwnd_cnt >= w) {
tp->snd_cwnd_cnt = 0;
tp->snd_cwnd++;
}
tp->snd_cwnd_cnt += acked;
if (tp->snd_cwnd_cnt >= w) {
u32 delta = tp->snd_cwnd_cnt / w;
tp->snd_cwnd_cnt -= delta * w;
tp->snd_cwnd += delta;
}
tp->snd_cwnd = min(tp->snd_cwnd, tp->snd_cwnd_clamp);
}
EXPORT_SYMBOL_GPL(tcp_cong_avoid_ai);
/*
* TCP Reno congestion control
* This is special case used for fallback as well.
*/
/* This is Jacobson's slow start and congestion avoidance.
* SIGCOMM '88, p. 328.
*/
void tcp_reno_cong_avoid(struct sock *sk, u32 ack, u32 acked)
{
struct tcp_sock *tp = tcp_sk(sk);
if (!tcp_is_cwnd_limited(sk))
return;
/* In "safe" area, increase. */
if (tcp_in_slow_start(tp)) {
acked = tcp_slow_start(tp, acked);
if (!acked)
return;
}
/* In dangerous area, increase slowly. */
tcp_cong_avoid_ai(tp, tp->snd_cwnd, acked);
}
EXPORT_SYMBOL_GPL(tcp_reno_cong_avoid);
/* Slow start threshold is half the congestion window (min 2) */
u32 tcp_reno_ssthresh(struct sock *sk)
{
const struct tcp_sock *tp = tcp_sk(sk);
return max(tp->snd_cwnd >> 1U, 2U);
}
EXPORT_SYMBOL_GPL(tcp_reno_ssthresh);
struct tcp_congestion_ops tcp_reno = {
.flags = TCP_CONG_NON_RESTRICTED,
.name = "reno",
.owner = THIS_MODULE,
.ssthresh = tcp_reno_ssthresh,
.cong_avoid = tcp_reno_cong_avoid,
};
| gpl-2.0 |
yslzsl/linux | drivers/media/pci/cx23885/cimax2.c | 1593 | 13091 | /*
* cimax2.c
*
* CIMax2(R) SP2 driver in conjunction with NetUp Dual DVB-S2 CI card
*
* Copyright (C) 2009 NetUP Inc.
* Copyright (C) 2009 Igor M. Liplianin <liplianin@netup.ru>
* Copyright (C) 2009 Abylay Ospan <aospan@netup.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.
*/
#include "cx23885.h"
#include "cimax2.h"
#include "dvb_ca_en50221.h"
/* Max transfer size done by I2C transfer functions */
#define MAX_XFER_SIZE 64
/**** Bit definitions for MC417_RWD and MC417_OEN registers ***
bits 31-16
+-----------+
| Reserved |
+-----------+
bit 15 bit 14 bit 13 bit 12 bit 11 bit 10 bit 9 bit 8
+-------+-------+-------+-------+-------+-------+-------+-------+
| WR# | RD# | | ACK# | ADHI | ADLO | CS1# | CS0# |
+-------+-------+-------+-------+-------+-------+-------+-------+
bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0
+-------+-------+-------+-------+-------+-------+-------+-------+
| DATA7| DATA6| DATA5| DATA4| DATA3| DATA2| DATA1| DATA0|
+-------+-------+-------+-------+-------+-------+-------+-------+
***/
/* MC417 */
#define NETUP_DATA 0x000000ff
#define NETUP_WR 0x00008000
#define NETUP_RD 0x00004000
#define NETUP_ACK 0x00001000
#define NETUP_ADHI 0x00000800
#define NETUP_ADLO 0x00000400
#define NETUP_CS1 0x00000200
#define NETUP_CS0 0x00000100
#define NETUP_EN_ALL 0x00001000
#define NETUP_CTRL_OFF (NETUP_CS1 | NETUP_CS0 | NETUP_WR | NETUP_RD)
#define NETUP_CI_CTL 0x04
#define NETUP_CI_RD 1
#define NETUP_IRQ_DETAM 0x1
#define NETUP_IRQ_IRQAM 0x4
static unsigned int ci_dbg;
module_param(ci_dbg, int, 0644);
MODULE_PARM_DESC(ci_dbg, "Enable CI debugging");
static unsigned int ci_irq_enable;
module_param(ci_irq_enable, int, 0644);
MODULE_PARM_DESC(ci_irq_enable, "Enable IRQ from CAM");
#define ci_dbg_print(args...) \
do { \
if (ci_dbg) \
printk(KERN_DEBUG args); \
} while (0)
#define ci_irq_flags() (ci_irq_enable ? NETUP_IRQ_IRQAM : 0)
/* stores all private variables for communication with CI */
struct netup_ci_state {
struct dvb_ca_en50221 ca;
struct mutex ca_mutex;
struct i2c_adapter *i2c_adap;
u8 ci_i2c_addr;
int status;
struct work_struct work;
void *priv;
u8 current_irq_mode;
int current_ci_flag;
unsigned long next_status_checked_time;
};
static int netup_read_i2c(struct i2c_adapter *i2c_adap, u8 addr, u8 reg,
u8 *buf, int len)
{
int ret;
struct i2c_msg msg[] = {
{
.addr = addr,
.flags = 0,
.buf = ®,
.len = 1
}, {
.addr = addr,
.flags = I2C_M_RD,
.buf = buf,
.len = len
}
};
ret = i2c_transfer(i2c_adap, msg, 2);
if (ret != 2) {
ci_dbg_print("%s: i2c read error, Reg = 0x%02x, Status = %d\n",
__func__, reg, ret);
return -1;
}
ci_dbg_print("%s: i2c read Addr=0x%04x, Reg = 0x%02x, data = %02x\n",
__func__, addr, reg, buf[0]);
return 0;
}
static int netup_write_i2c(struct i2c_adapter *i2c_adap, u8 addr, u8 reg,
u8 *buf, int len)
{
int ret;
u8 buffer[MAX_XFER_SIZE];
struct i2c_msg msg = {
.addr = addr,
.flags = 0,
.buf = &buffer[0],
.len = len + 1
};
if (1 + len > sizeof(buffer)) {
printk(KERN_WARNING
"%s: i2c wr reg=%04x: len=%d is too big!\n",
KBUILD_MODNAME, reg, len);
return -EINVAL;
}
buffer[0] = reg;
memcpy(&buffer[1], buf, len);
ret = i2c_transfer(i2c_adap, &msg, 1);
if (ret != 1) {
ci_dbg_print("%s: i2c write error, Reg=[0x%02x], Status=%d\n",
__func__, reg, ret);
return -1;
}
return 0;
}
static int netup_ci_get_mem(struct cx23885_dev *dev)
{
int mem;
unsigned long timeout = jiffies + msecs_to_jiffies(1);
for (;;) {
mem = cx_read(MC417_RWD);
if ((mem & NETUP_ACK) == 0)
break;
if (time_after(jiffies, timeout))
break;
udelay(1);
}
cx_set(MC417_RWD, NETUP_CTRL_OFF);
return mem & 0xff;
}
static int netup_ci_op_cam(struct dvb_ca_en50221 *en50221, int slot,
u8 flag, u8 read, int addr, u8 data)
{
struct netup_ci_state *state = en50221->data;
struct cx23885_tsport *port = state->priv;
struct cx23885_dev *dev = port->dev;
u8 store;
int mem;
int ret;
if (0 != slot)
return -EINVAL;
if (state->current_ci_flag != flag) {
ret = netup_read_i2c(state->i2c_adap, state->ci_i2c_addr,
0, &store, 1);
if (ret != 0)
return ret;
store &= ~0x0c;
store |= flag;
ret = netup_write_i2c(state->i2c_adap, state->ci_i2c_addr,
0, &store, 1);
if (ret != 0)
return ret;
}
state->current_ci_flag = flag;
mutex_lock(&dev->gpio_lock);
/* write addr */
cx_write(MC417_OEN, NETUP_EN_ALL);
cx_write(MC417_RWD, NETUP_CTRL_OFF |
NETUP_ADLO | (0xff & addr));
cx_clear(MC417_RWD, NETUP_ADLO);
cx_write(MC417_RWD, NETUP_CTRL_OFF |
NETUP_ADHI | (0xff & (addr >> 8)));
cx_clear(MC417_RWD, NETUP_ADHI);
if (read) { /* data in */
cx_write(MC417_OEN, NETUP_EN_ALL | NETUP_DATA);
} else /* data out */
cx_write(MC417_RWD, NETUP_CTRL_OFF | data);
/* choose chip */
cx_clear(MC417_RWD,
(state->ci_i2c_addr == 0x40) ? NETUP_CS0 : NETUP_CS1);
/* read/write */
cx_clear(MC417_RWD, (read) ? NETUP_RD : NETUP_WR);
mem = netup_ci_get_mem(dev);
mutex_unlock(&dev->gpio_lock);
if (!read)
if (mem < 0)
return -EREMOTEIO;
ci_dbg_print("%s: %s: chipaddr=[0x%x] addr=[0x%02x], %s=%x\n", __func__,
(read) ? "read" : "write", state->ci_i2c_addr, addr,
(flag == NETUP_CI_CTL) ? "ctl" : "mem",
(read) ? mem : data);
if (read)
return mem;
return 0;
}
int netup_ci_read_attribute_mem(struct dvb_ca_en50221 *en50221,
int slot, int addr)
{
return netup_ci_op_cam(en50221, slot, 0, NETUP_CI_RD, addr, 0);
}
int netup_ci_write_attribute_mem(struct dvb_ca_en50221 *en50221,
int slot, int addr, u8 data)
{
return netup_ci_op_cam(en50221, slot, 0, 0, addr, data);
}
int netup_ci_read_cam_ctl(struct dvb_ca_en50221 *en50221, int slot,
u8 addr)
{
return netup_ci_op_cam(en50221, slot, NETUP_CI_CTL,
NETUP_CI_RD, addr, 0);
}
int netup_ci_write_cam_ctl(struct dvb_ca_en50221 *en50221, int slot,
u8 addr, u8 data)
{
return netup_ci_op_cam(en50221, slot, NETUP_CI_CTL, 0, addr, data);
}
int netup_ci_slot_reset(struct dvb_ca_en50221 *en50221, int slot)
{
struct netup_ci_state *state = en50221->data;
u8 buf = 0x80;
int ret;
if (0 != slot)
return -EINVAL;
udelay(500);
ret = netup_write_i2c(state->i2c_adap, state->ci_i2c_addr,
0, &buf, 1);
if (ret != 0)
return ret;
udelay(500);
buf = 0x00;
ret = netup_write_i2c(state->i2c_adap, state->ci_i2c_addr,
0, &buf, 1);
msleep(1000);
dvb_ca_en50221_camready_irq(&state->ca, 0);
return 0;
}
int netup_ci_slot_shutdown(struct dvb_ca_en50221 *en50221, int slot)
{
/* not implemented */
return 0;
}
static int netup_ci_set_irq(struct dvb_ca_en50221 *en50221, u8 irq_mode)
{
struct netup_ci_state *state = en50221->data;
int ret;
if (irq_mode == state->current_irq_mode)
return 0;
ci_dbg_print("%s: chipaddr=[0x%x] setting ci IRQ to [0x%x] \n",
__func__, state->ci_i2c_addr, irq_mode);
ret = netup_write_i2c(state->i2c_adap, state->ci_i2c_addr,
0x1b, &irq_mode, 1);
if (ret != 0)
return ret;
state->current_irq_mode = irq_mode;
return 0;
}
int netup_ci_slot_ts_ctl(struct dvb_ca_en50221 *en50221, int slot)
{
struct netup_ci_state *state = en50221->data;
u8 buf;
if (0 != slot)
return -EINVAL;
netup_read_i2c(state->i2c_adap, state->ci_i2c_addr,
0, &buf, 1);
buf |= 0x60;
return netup_write_i2c(state->i2c_adap, state->ci_i2c_addr,
0, &buf, 1);
}
/* work handler */
static void netup_read_ci_status(struct work_struct *work)
{
struct netup_ci_state *state =
container_of(work, struct netup_ci_state, work);
u8 buf[33];
int ret;
/* CAM module IRQ processing. fast operation */
dvb_ca_en50221_frda_irq(&state->ca, 0);
/* CAM module INSERT/REMOVE processing. slow operation because of i2c
* transfers */
if (time_after(jiffies, state->next_status_checked_time)
|| !state->status) {
ret = netup_read_i2c(state->i2c_adap, state->ci_i2c_addr,
0, &buf[0], 33);
state->next_status_checked_time = jiffies
+ msecs_to_jiffies(1000);
if (ret != 0)
return;
ci_dbg_print("%s: Slot Status Addr=[0x%04x], "
"Reg=[0x%02x], data=%02x, "
"TS config = %02x\n", __func__,
state->ci_i2c_addr, 0, buf[0],
buf[0]);
if (buf[0] & 1)
state->status = DVB_CA_EN50221_POLL_CAM_PRESENT |
DVB_CA_EN50221_POLL_CAM_READY;
else
state->status = 0;
}
}
/* CI irq handler */
int netup_ci_slot_status(struct cx23885_dev *dev, u32 pci_status)
{
struct cx23885_tsport *port = NULL;
struct netup_ci_state *state = NULL;
ci_dbg_print("%s:\n", __func__);
if (0 == (pci_status & (PCI_MSK_GPIO0 | PCI_MSK_GPIO1)))
return 0;
if (pci_status & PCI_MSK_GPIO0) {
port = &dev->ts1;
state = port->port_priv;
schedule_work(&state->work);
ci_dbg_print("%s: Wakeup CI0\n", __func__);
}
if (pci_status & PCI_MSK_GPIO1) {
port = &dev->ts2;
state = port->port_priv;
schedule_work(&state->work);
ci_dbg_print("%s: Wakeup CI1\n", __func__);
}
return 1;
}
int netup_poll_ci_slot_status(struct dvb_ca_en50221 *en50221,
int slot, int open)
{
struct netup_ci_state *state = en50221->data;
if (0 != slot)
return -EINVAL;
netup_ci_set_irq(en50221, open ? (NETUP_IRQ_DETAM | ci_irq_flags())
: NETUP_IRQ_DETAM);
return state->status;
}
int netup_ci_init(struct cx23885_tsport *port)
{
struct netup_ci_state *state;
u8 cimax_init[34] = {
0x00, /* module A control*/
0x00, /* auto select mask high A */
0x00, /* auto select mask low A */
0x00, /* auto select pattern high A */
0x00, /* auto select pattern low A */
0x44, /* memory access time A */
0x00, /* invert input A */
0x00, /* RFU */
0x00, /* RFU */
0x00, /* module B control*/
0x00, /* auto select mask high B */
0x00, /* auto select mask low B */
0x00, /* auto select pattern high B */
0x00, /* auto select pattern low B */
0x44, /* memory access time B */
0x00, /* invert input B */
0x00, /* RFU */
0x00, /* RFU */
0x00, /* auto select mask high Ext */
0x00, /* auto select mask low Ext */
0x00, /* auto select pattern high Ext */
0x00, /* auto select pattern low Ext */
0x00, /* RFU */
0x02, /* destination - module A */
0x01, /* power on (use it like store place) */
0x00, /* RFU */
0x00, /* int status read only */
ci_irq_flags() | NETUP_IRQ_DETAM, /* DETAM, IRQAM unmasked */
0x05, /* EXTINT=active-high, INT=push-pull */
0x00, /* USCG1 */
0x04, /* ack active low */
0x00, /* LOCK = 0 */
0x33, /* serial mode, rising in, rising out, MSB first*/
0x31, /* synchronization */
};
int ret;
ci_dbg_print("%s\n", __func__);
state = kzalloc(sizeof(struct netup_ci_state), GFP_KERNEL);
if (!state) {
ci_dbg_print("%s: Unable create CI structure!\n", __func__);
ret = -ENOMEM;
goto err;
}
port->port_priv = state;
switch (port->nr) {
case 1:
state->ci_i2c_addr = 0x40;
break;
case 2:
state->ci_i2c_addr = 0x41;
break;
}
state->i2c_adap = &port->dev->i2c_bus[0].i2c_adap;
state->ca.owner = THIS_MODULE;
state->ca.read_attribute_mem = netup_ci_read_attribute_mem;
state->ca.write_attribute_mem = netup_ci_write_attribute_mem;
state->ca.read_cam_control = netup_ci_read_cam_ctl;
state->ca.write_cam_control = netup_ci_write_cam_ctl;
state->ca.slot_reset = netup_ci_slot_reset;
state->ca.slot_shutdown = netup_ci_slot_shutdown;
state->ca.slot_ts_enable = netup_ci_slot_ts_ctl;
state->ca.poll_slot_status = netup_poll_ci_slot_status;
state->ca.data = state;
state->priv = port;
state->current_irq_mode = ci_irq_flags() | NETUP_IRQ_DETAM;
ret = netup_write_i2c(state->i2c_adap, state->ci_i2c_addr,
0, &cimax_init[0], 34);
/* lock registers */
ret |= netup_write_i2c(state->i2c_adap, state->ci_i2c_addr,
0x1f, &cimax_init[0x18], 1);
/* power on slots */
ret |= netup_write_i2c(state->i2c_adap, state->ci_i2c_addr,
0x18, &cimax_init[0x18], 1);
if (0 != ret)
goto err;
ret = dvb_ca_en50221_init(&port->frontends.adapter,
&state->ca,
/* flags */ 0,
/* n_slots */ 1);
if (0 != ret)
goto err;
INIT_WORK(&state->work, netup_read_ci_status);
schedule_work(&state->work);
ci_dbg_print("%s: CI initialized!\n", __func__);
return 0;
err:
ci_dbg_print("%s: Cannot initialize CI: Error %d.\n", __func__, ret);
kfree(state);
return ret;
}
void netup_ci_exit(struct cx23885_tsport *port)
{
struct netup_ci_state *state;
if (NULL == port)
return;
state = (struct netup_ci_state *)port->port_priv;
if (NULL == state)
return;
if (NULL == state->ca.data)
return;
dvb_ca_en50221_release(&state->ca);
kfree(state);
}
| gpl-2.0 |
rupesh1mb/linux | drivers/media/pci/cx23885/netup-init.c | 1593 | 2656 | /*
* netup-init.c
*
* NetUP Dual DVB-S2 CI driver
*
* Copyright (C) 2009 NetUP Inc.
* Copyright (C) 2009 Igor M. Liplianin <liplianin@netup.ru>
* Copyright (C) 2009 Abylay Ospan <aospan@netup.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.
*/
#include "cx23885.h"
#include "netup-init.h"
static void i2c_av_write(struct i2c_adapter *i2c, u16 reg, u8 val)
{
int ret;
u8 buf[3];
struct i2c_msg msg = {
.addr = 0x88 >> 1,
.flags = 0,
.buf = buf,
.len = 3
};
buf[0] = reg >> 8;
buf[1] = reg & 0xff;
buf[2] = val;
ret = i2c_transfer(i2c, &msg, 1);
if (ret != 1)
printk(KERN_ERR "%s: i2c write error!\n", __func__);
}
static void i2c_av_write4(struct i2c_adapter *i2c, u16 reg, u32 val)
{
int ret;
u8 buf[6];
struct i2c_msg msg = {
.addr = 0x88 >> 1,
.flags = 0,
.buf = buf,
.len = 6
};
buf[0] = reg >> 8;
buf[1] = reg & 0xff;
buf[2] = val & 0xff;
buf[3] = (val >> 8) & 0xff;
buf[4] = (val >> 16) & 0xff;
buf[5] = val >> 24;
ret = i2c_transfer(i2c, &msg, 1);
if (ret != 1)
printk(KERN_ERR "%s: i2c write error!\n", __func__);
}
static u8 i2c_av_read(struct i2c_adapter *i2c, u16 reg)
{
int ret;
u8 buf[2];
struct i2c_msg msg = {
.addr = 0x88 >> 1,
.flags = 0,
.buf = buf,
.len = 2
};
buf[0] = reg >> 8;
buf[1] = reg & 0xff;
ret = i2c_transfer(i2c, &msg, 1);
if (ret != 1)
printk(KERN_ERR "%s: i2c write error!\n", __func__);
msg.flags = I2C_M_RD;
msg.len = 1;
ret = i2c_transfer(i2c, &msg, 1);
if (ret != 1)
printk(KERN_ERR "%s: i2c read error!\n", __func__);
return buf[0];
}
static void i2c_av_and_or(struct i2c_adapter *i2c, u16 reg, unsigned and_mask,
u8 or_value)
{
i2c_av_write(i2c, reg, (i2c_av_read(i2c, reg) & and_mask) | or_value);
}
/* set 27MHz on AUX_CLK */
void netup_initialize(struct cx23885_dev *dev)
{
struct cx23885_i2c *i2c_bus = &dev->i2c_bus[2];
struct i2c_adapter *i2c = &i2c_bus->i2c_adap;
/* Stop microcontroller */
i2c_av_and_or(i2c, 0x803, ~0x10, 0x00);
/* Aux PLL frac for 27 MHz */
i2c_av_write4(i2c, 0x114, 0xea0eb3);
/* Aux PLL int for 27 MHz */
i2c_av_write4(i2c, 0x110, 0x090319);
/* start microcontroller */
i2c_av_and_or(i2c, 0x803, ~0x10, 0x10);
}
| gpl-2.0 |
AlmightyMegadeth00/kernel_minnow | drivers/pinctrl/sh-pfc/pfc-sh7372.c | 2105 | 63615 | /*
* sh7372 processor support - PFC hardware block
*
* Copyright (C) 2010 Kuninori Morimoto <morimoto.kuninori@renesas.com>
*
* Based on
* sh7367 processor support - PFC hardware block
* Copyright (C) 2010 Magnus Damm
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/kernel.h>
#include <mach/irqs.h>
#include <mach/sh7372.h>
#include "sh_pfc.h"
#define CPU_ALL_PORT(fn, pfx, sfx) \
PORT_10(fn, pfx, sfx), PORT_90(fn, pfx, sfx), \
PORT_10(fn, pfx##10, sfx), PORT_10(fn, pfx##11, sfx), \
PORT_10(fn, pfx##12, sfx), PORT_10(fn, pfx##13, sfx), \
PORT_10(fn, pfx##14, sfx), PORT_10(fn, pfx##15, sfx), \
PORT_10(fn, pfx##16, sfx), PORT_10(fn, pfx##17, sfx), \
PORT_10(fn, pfx##18, sfx), PORT_1(fn, pfx##190, sfx)
enum {
PINMUX_RESERVED = 0,
/* PORT0_DATA -> PORT190_DATA */
PINMUX_DATA_BEGIN,
PORT_ALL(DATA),
PINMUX_DATA_END,
/* PORT0_IN -> PORT190_IN */
PINMUX_INPUT_BEGIN,
PORT_ALL(IN),
PINMUX_INPUT_END,
/* PORT0_IN_PU -> PORT190_IN_PU */
PINMUX_INPUT_PULLUP_BEGIN,
PORT_ALL(IN_PU),
PINMUX_INPUT_PULLUP_END,
/* PORT0_IN_PD -> PORT190_IN_PD */
PINMUX_INPUT_PULLDOWN_BEGIN,
PORT_ALL(IN_PD),
PINMUX_INPUT_PULLDOWN_END,
/* PORT0_OUT -> PORT190_OUT */
PINMUX_OUTPUT_BEGIN,
PORT_ALL(OUT),
PINMUX_OUTPUT_END,
PINMUX_FUNCTION_BEGIN,
PORT_ALL(FN_IN), /* PORT0_FN_IN -> PORT190_FN_IN */
PORT_ALL(FN_OUT), /* PORT0_FN_OUT -> PORT190_FN_OUT */
PORT_ALL(FN0), /* PORT0_FN0 -> PORT190_FN0 */
PORT_ALL(FN1), /* PORT0_FN1 -> PORT190_FN1 */
PORT_ALL(FN2), /* PORT0_FN2 -> PORT190_FN2 */
PORT_ALL(FN3), /* PORT0_FN3 -> PORT190_FN3 */
PORT_ALL(FN4), /* PORT0_FN4 -> PORT190_FN4 */
PORT_ALL(FN5), /* PORT0_FN5 -> PORT190_FN5 */
PORT_ALL(FN6), /* PORT0_FN6 -> PORT190_FN6 */
PORT_ALL(FN7), /* PORT0_FN7 -> PORT190_FN7 */
MSEL1CR_31_0, MSEL1CR_31_1,
MSEL1CR_30_0, MSEL1CR_30_1,
MSEL1CR_29_0, MSEL1CR_29_1,
MSEL1CR_28_0, MSEL1CR_28_1,
MSEL1CR_27_0, MSEL1CR_27_1,
MSEL1CR_26_0, MSEL1CR_26_1,
MSEL1CR_16_0, MSEL1CR_16_1,
MSEL1CR_15_0, MSEL1CR_15_1,
MSEL1CR_14_0, MSEL1CR_14_1,
MSEL1CR_13_0, MSEL1CR_13_1,
MSEL1CR_12_0, MSEL1CR_12_1,
MSEL1CR_9_0, MSEL1CR_9_1,
MSEL1CR_8_0, MSEL1CR_8_1,
MSEL1CR_7_0, MSEL1CR_7_1,
MSEL1CR_6_0, MSEL1CR_6_1,
MSEL1CR_4_0, MSEL1CR_4_1,
MSEL1CR_3_0, MSEL1CR_3_1,
MSEL1CR_2_0, MSEL1CR_2_1,
MSEL1CR_0_0, MSEL1CR_0_1,
MSEL3CR_27_0, MSEL3CR_27_1,
MSEL3CR_26_0, MSEL3CR_26_1,
MSEL3CR_21_0, MSEL3CR_21_1,
MSEL3CR_20_0, MSEL3CR_20_1,
MSEL3CR_15_0, MSEL3CR_15_1,
MSEL3CR_9_0, MSEL3CR_9_1,
MSEL3CR_6_0, MSEL3CR_6_1,
MSEL4CR_19_0, MSEL4CR_19_1,
MSEL4CR_18_0, MSEL4CR_18_1,
MSEL4CR_17_0, MSEL4CR_17_1,
MSEL4CR_16_0, MSEL4CR_16_1,
MSEL4CR_15_0, MSEL4CR_15_1,
MSEL4CR_14_0, MSEL4CR_14_1,
MSEL4CR_10_0, MSEL4CR_10_1,
MSEL4CR_6_0, MSEL4CR_6_1,
MSEL4CR_4_0, MSEL4CR_4_1,
MSEL4CR_1_0, MSEL4CR_1_1,
PINMUX_FUNCTION_END,
PINMUX_MARK_BEGIN,
/* IRQ */
IRQ0_6_MARK, IRQ0_162_MARK, IRQ1_MARK, IRQ2_4_MARK,
IRQ2_5_MARK, IRQ3_8_MARK, IRQ3_16_MARK, IRQ4_17_MARK,
IRQ4_163_MARK, IRQ5_MARK, IRQ6_39_MARK, IRQ6_164_MARK,
IRQ7_40_MARK, IRQ7_167_MARK, IRQ8_41_MARK, IRQ8_168_MARK,
IRQ9_42_MARK, IRQ9_169_MARK, IRQ10_MARK, IRQ11_MARK,
IRQ12_80_MARK, IRQ12_137_MARK, IRQ13_81_MARK, IRQ13_145_MARK,
IRQ14_82_MARK, IRQ14_146_MARK, IRQ15_83_MARK, IRQ15_147_MARK,
IRQ16_84_MARK, IRQ16_170_MARK, IRQ17_MARK, IRQ18_MARK,
IRQ19_MARK, IRQ20_MARK, IRQ21_MARK, IRQ22_MARK,
IRQ23_MARK, IRQ24_MARK, IRQ25_MARK, IRQ26_121_MARK,
IRQ26_172_MARK, IRQ27_122_MARK, IRQ27_180_MARK, IRQ28_123_MARK,
IRQ28_181_MARK, IRQ29_129_MARK, IRQ29_182_MARK, IRQ30_130_MARK,
IRQ30_183_MARK, IRQ31_138_MARK, IRQ31_184_MARK,
/* MSIOF0 */
MSIOF0_TSYNC_MARK, MSIOF0_TSCK_MARK, MSIOF0_RXD_MARK,
MSIOF0_RSCK_MARK, MSIOF0_RSYNC_MARK, MSIOF0_MCK0_MARK,
MSIOF0_MCK1_MARK, MSIOF0_SS1_MARK, MSIOF0_SS2_MARK,
MSIOF0_TXD_MARK,
/* MSIOF1 */
MSIOF1_TSCK_39_MARK, MSIOF1_TSYNC_40_MARK,
MSIOF1_TSCK_88_MARK, MSIOF1_TSYNC_89_MARK,
MSIOF1_TXD_41_MARK, MSIOF1_RXD_42_MARK,
MSIOF1_TXD_90_MARK, MSIOF1_RXD_91_MARK,
MSIOF1_SS1_43_MARK, MSIOF1_SS2_44_MARK,
MSIOF1_SS1_92_MARK, MSIOF1_SS2_93_MARK,
MSIOF1_RSCK_MARK, MSIOF1_RSYNC_MARK,
MSIOF1_MCK0_MARK, MSIOF1_MCK1_MARK,
/* MSIOF2 */
MSIOF2_RSCK_MARK, MSIOF2_RSYNC_MARK, MSIOF2_MCK0_MARK,
MSIOF2_MCK1_MARK, MSIOF2_SS1_MARK, MSIOF2_SS2_MARK,
MSIOF2_TSYNC_MARK, MSIOF2_TSCK_MARK, MSIOF2_RXD_MARK,
MSIOF2_TXD_MARK,
/* BBIF1 */
BBIF1_RXD_MARK, BBIF1_TSYNC_MARK, BBIF1_TSCK_MARK,
BBIF1_TXD_MARK, BBIF1_RSCK_MARK, BBIF1_RSYNC_MARK,
BBIF1_FLOW_MARK, BB_RX_FLOW_N_MARK,
/* BBIF2 */
BBIF2_TSCK1_MARK, BBIF2_TSYNC1_MARK,
BBIF2_TXD1_MARK, BBIF2_RXD_MARK,
/* FSI */
FSIACK_MARK, FSIBCK_MARK, FSIAILR_MARK, FSIAIBT_MARK,
FSIAISLD_MARK, FSIAOMC_MARK, FSIAOLR_MARK, FSIAOBT_MARK,
FSIAOSLD_MARK, FSIASPDIF_11_MARK, FSIASPDIF_15_MARK,
/* FMSI */
FMSOCK_MARK, FMSOOLR_MARK, FMSIOLR_MARK, FMSOOBT_MARK,
FMSIOBT_MARK, FMSOSLD_MARK, FMSOILR_MARK, FMSIILR_MARK,
FMSOIBT_MARK, FMSIIBT_MARK, FMSISLD_MARK, FMSICK_MARK,
/* SCIFA0 */
SCIFA0_TXD_MARK, SCIFA0_RXD_MARK, SCIFA0_SCK_MARK,
SCIFA0_RTS_MARK, SCIFA0_CTS_MARK,
/* SCIFA1 */
SCIFA1_TXD_MARK, SCIFA1_RXD_MARK, SCIFA1_SCK_MARK,
SCIFA1_RTS_MARK, SCIFA1_CTS_MARK,
/* SCIFA2 */
SCIFA2_CTS1_MARK, SCIFA2_RTS1_MARK, SCIFA2_TXD1_MARK,
SCIFA2_RXD1_MARK, SCIFA2_SCK1_MARK,
/* SCIFA3 */
SCIFA3_CTS_43_MARK, SCIFA3_CTS_140_MARK, SCIFA3_RTS_44_MARK,
SCIFA3_RTS_141_MARK, SCIFA3_SCK_MARK, SCIFA3_TXD_MARK,
SCIFA3_RXD_MARK,
/* SCIFA4 */
SCIFA4_RXD_MARK, SCIFA4_TXD_MARK,
/* SCIFA5 */
SCIFA5_RXD_MARK, SCIFA5_TXD_MARK,
/* SCIFB */
SCIFB_SCK_MARK, SCIFB_RTS_MARK, SCIFB_CTS_MARK,
SCIFB_TXD_MARK, SCIFB_RXD_MARK,
/* CEU */
VIO_HD_MARK, VIO_CKO1_MARK, VIO_CKO2_MARK, VIO_VD_MARK,
VIO_CLK_MARK, VIO_FIELD_MARK, VIO_CKO_MARK,
VIO_D0_MARK, VIO_D1_MARK, VIO_D2_MARK, VIO_D3_MARK,
VIO_D4_MARK, VIO_D5_MARK, VIO_D6_MARK, VIO_D7_MARK,
VIO_D8_MARK, VIO_D9_MARK, VIO_D10_MARK, VIO_D11_MARK,
VIO_D12_MARK, VIO_D13_MARK, VIO_D14_MARK, VIO_D15_MARK,
/* USB0 */
IDIN_0_MARK, EXTLP_0_MARK, OVCN2_0_MARK, PWEN_0_MARK,
OVCN_0_MARK, VBUS0_0_MARK,
/* USB1 */
IDIN_1_18_MARK, IDIN_1_113_MARK,
PWEN_1_115_MARK, PWEN_1_138_MARK,
OVCN_1_114_MARK, OVCN_1_162_MARK,
EXTLP_1_MARK, OVCN2_1_MARK,
VBUS0_1_MARK,
/* GPIO */
GPI0_MARK, GPI1_MARK, GPO0_MARK, GPO1_MARK,
/* BSC */
BS_MARK, WE1_MARK,
CKO_MARK, WAIT_MARK, RDWR_MARK,
A0_MARK, A1_MARK, A2_MARK, A3_MARK,
A6_MARK, A7_MARK, A8_MARK, A9_MARK,
A10_MARK, A11_MARK, A12_MARK, A13_MARK,
A14_MARK, A15_MARK, A16_MARK, A17_MARK,
A18_MARK, A19_MARK, A20_MARK, A21_MARK,
A22_MARK, A23_MARK, A24_MARK, A25_MARK,
A26_MARK,
CS0_MARK, CS2_MARK, CS4_MARK,
CS5A_MARK, CS5B_MARK, CS6A_MARK,
/* BSC/FLCTL */
RD_FSC_MARK, WE0_FWE_MARK, A4_FOE_MARK, A5_FCDE_MARK,
D0_NAF0_MARK, D1_NAF1_MARK, D2_NAF2_MARK, D3_NAF3_MARK,
D4_NAF4_MARK, D5_NAF5_MARK, D6_NAF6_MARK, D7_NAF7_MARK,
D8_NAF8_MARK, D9_NAF9_MARK, D10_NAF10_MARK, D11_NAF11_MARK,
D12_NAF12_MARK, D13_NAF13_MARK, D14_NAF14_MARK, D15_NAF15_MARK,
/* MMCIF(1) */
MMCD0_0_MARK, MMCD0_1_MARK, MMCD0_2_MARK, MMCD0_3_MARK,
MMCD0_4_MARK, MMCD0_5_MARK, MMCD0_6_MARK, MMCD0_7_MARK,
MMCCMD0_MARK, MMCCLK0_MARK,
/* MMCIF(2) */
MMCD1_0_MARK, MMCD1_1_MARK, MMCD1_2_MARK, MMCD1_3_MARK,
MMCD1_4_MARK, MMCD1_5_MARK, MMCD1_6_MARK, MMCD1_7_MARK,
MMCCLK1_MARK, MMCCMD1_MARK,
/* SPU2 */
VINT_I_MARK,
/* FLCTL */
FCE1_MARK, FCE0_MARK, FRB_MARK,
/* HSI */
GP_RX_FLAG_MARK, GP_RX_DATA_MARK, GP_TX_READY_MARK,
GP_RX_WAKE_MARK, MP_TX_FLAG_MARK, MP_TX_DATA_MARK,
MP_RX_READY_MARK, MP_TX_WAKE_MARK,
/* MFI */
MFIv6_MARK,
MFIv4_MARK,
MEMC_CS0_MARK, MEMC_BUSCLK_MEMC_A0_MARK,
MEMC_CS1_MEMC_A1_MARK, MEMC_ADV_MEMC_DREQ0_MARK,
MEMC_WAIT_MEMC_DREQ1_MARK, MEMC_NOE_MARK,
MEMC_NWE_MARK, MEMC_INT_MARK,
MEMC_AD0_MARK, MEMC_AD1_MARK, MEMC_AD2_MARK,
MEMC_AD3_MARK, MEMC_AD4_MARK, MEMC_AD5_MARK,
MEMC_AD6_MARK, MEMC_AD7_MARK, MEMC_AD8_MARK,
MEMC_AD9_MARK, MEMC_AD10_MARK, MEMC_AD11_MARK,
MEMC_AD12_MARK, MEMC_AD13_MARK, MEMC_AD14_MARK,
MEMC_AD15_MARK,
/* SIM */
SIM_RST_MARK, SIM_CLK_MARK, SIM_D_MARK,
/* TPU */
TPU0TO0_MARK, TPU0TO1_MARK,
TPU0TO2_93_MARK, TPU0TO2_99_MARK,
TPU0TO3_MARK,
/* I2C2 */
I2C_SCL2_MARK, I2C_SDA2_MARK,
/* I2C3(1) */
I2C_SCL3_MARK, I2C_SDA3_MARK,
/* I2C3(2) */
I2C_SCL3S_MARK, I2C_SDA3S_MARK,
/* I2C4(2) */
I2C_SCL4_MARK, I2C_SDA4_MARK,
/* I2C4(2) */
I2C_SCL4S_MARK, I2C_SDA4S_MARK,
/* KEYSC */
KEYOUT0_MARK, KEYIN0_121_MARK, KEYIN0_136_MARK,
KEYOUT1_MARK, KEYIN1_122_MARK, KEYIN1_135_MARK,
KEYOUT2_MARK, KEYIN2_123_MARK, KEYIN2_134_MARK,
KEYOUT3_MARK, KEYIN3_124_MARK, KEYIN3_133_MARK,
KEYOUT4_MARK, KEYIN4_MARK,
KEYOUT5_MARK, KEYIN5_MARK,
KEYOUT6_MARK, KEYIN6_MARK,
KEYOUT7_MARK, KEYIN7_MARK,
/* LCDC */
LCDC0_SELECT_MARK,
LCDC1_SELECT_MARK,
LCDHSYN_MARK, LCDCS_MARK, LCDVSYN_MARK, LCDDCK_MARK,
LCDWR_MARK, LCDRD_MARK, LCDDISP_MARK, LCDRS_MARK,
LCDLCLK_MARK, LCDDON_MARK,
LCDD0_MARK, LCDD1_MARK, LCDD2_MARK, LCDD3_MARK,
LCDD4_MARK, LCDD5_MARK, LCDD6_MARK, LCDD7_MARK,
LCDD8_MARK, LCDD9_MARK, LCDD10_MARK, LCDD11_MARK,
LCDD12_MARK, LCDD13_MARK, LCDD14_MARK, LCDD15_MARK,
LCDD16_MARK, LCDD17_MARK, LCDD18_MARK, LCDD19_MARK,
LCDD20_MARK, LCDD21_MARK, LCDD22_MARK, LCDD23_MARK,
/* IRDA */
IRDA_OUT_MARK, IRDA_IN_MARK, IRDA_FIRSEL_MARK,
IROUT_139_MARK, IROUT_140_MARK,
/* TSIF1 */
TS0_1SELECT_MARK,
TS0_2SELECT_MARK,
TS1_1SELECT_MARK,
TS1_2SELECT_MARK,
TS_SPSYNC1_MARK, TS_SDAT1_MARK,
TS_SDEN1_MARK, TS_SCK1_MARK,
/* TSIF2 */
TS_SPSYNC2_MARK, TS_SDAT2_MARK,
TS_SDEN2_MARK, TS_SCK2_MARK,
/* HDMI */
HDMI_HPD_MARK, HDMI_CEC_MARK,
/* SDHI0 */
SDHICLK0_MARK, SDHICD0_MARK,
SDHICMD0_MARK, SDHIWP0_MARK,
SDHID0_0_MARK, SDHID0_1_MARK,
SDHID0_2_MARK, SDHID0_3_MARK,
/* SDHI1 */
SDHICLK1_MARK, SDHICMD1_MARK, SDHID1_0_MARK,
SDHID1_1_MARK, SDHID1_2_MARK, SDHID1_3_MARK,
/* SDHI2 */
SDHICLK2_MARK, SDHICMD2_MARK, SDHID2_0_MARK,
SDHID2_1_MARK, SDHID2_2_MARK, SDHID2_3_MARK,
/* SDENC */
SDENC_CPG_MARK,
SDENC_DV_CLKI_MARK,
PINMUX_MARK_END,
};
static const pinmux_enum_t pinmux_data[] = {
/* specify valid pin states for each pin in GPIO mode */
PORT_DATA_IO_PD(0), PORT_DATA_IO_PD(1),
PORT_DATA_O(2), PORT_DATA_I_PD(3),
PORT_DATA_I_PD(4), PORT_DATA_I_PD(5),
PORT_DATA_IO_PU_PD(6), PORT_DATA_I_PD(7),
PORT_DATA_IO_PD(8), PORT_DATA_O(9),
PORT_DATA_O(10), PORT_DATA_O(11),
PORT_DATA_IO_PU_PD(12), PORT_DATA_IO_PD(13),
PORT_DATA_IO_PD(14), PORT_DATA_O(15),
PORT_DATA_IO_PD(16), PORT_DATA_IO_PD(17),
PORT_DATA_I_PD(18), PORT_DATA_IO(19),
PORT_DATA_IO(20), PORT_DATA_IO(21),
PORT_DATA_IO(22), PORT_DATA_IO(23),
PORT_DATA_IO(24), PORT_DATA_IO(25),
PORT_DATA_IO(26), PORT_DATA_IO(27),
PORT_DATA_IO(28), PORT_DATA_IO(29),
PORT_DATA_IO(30), PORT_DATA_IO(31),
PORT_DATA_IO(32), PORT_DATA_IO(33),
PORT_DATA_IO(34), PORT_DATA_IO(35),
PORT_DATA_IO(36), PORT_DATA_IO(37),
PORT_DATA_IO(38), PORT_DATA_IO(39),
PORT_DATA_IO(40), PORT_DATA_IO(41),
PORT_DATA_IO(42), PORT_DATA_IO(43),
PORT_DATA_IO(44), PORT_DATA_IO(45),
PORT_DATA_IO_PU(46), PORT_DATA_IO_PU(47),
PORT_DATA_IO_PU(48), PORT_DATA_IO_PU(49),
PORT_DATA_IO_PU(50), PORT_DATA_IO_PU(51),
PORT_DATA_IO_PU(52), PORT_DATA_IO_PU(53),
PORT_DATA_IO_PU(54), PORT_DATA_IO_PU(55),
PORT_DATA_IO_PU(56), PORT_DATA_IO_PU(57),
PORT_DATA_IO_PU(58), PORT_DATA_IO_PU(59),
PORT_DATA_IO_PU(60), PORT_DATA_IO_PU(61),
PORT_DATA_IO(62), PORT_DATA_O(63),
PORT_DATA_O(64), PORT_DATA_IO_PU(65),
PORT_DATA_O(66), PORT_DATA_IO_PU(67), /*66?*/
PORT_DATA_O(68), PORT_DATA_IO(69),
PORT_DATA_IO(70), PORT_DATA_IO(71),
PORT_DATA_O(72), PORT_DATA_I_PU(73),
PORT_DATA_I_PU_PD(74), PORT_DATA_IO_PU_PD(75),
PORT_DATA_IO_PU_PD(76), PORT_DATA_IO_PU_PD(77),
PORT_DATA_IO_PU_PD(78), PORT_DATA_IO_PU_PD(79),
PORT_DATA_IO_PU_PD(80), PORT_DATA_IO_PU_PD(81),
PORT_DATA_IO_PU_PD(82), PORT_DATA_IO_PU_PD(83),
PORT_DATA_IO_PU_PD(84), PORT_DATA_IO_PU_PD(85),
PORT_DATA_IO_PU_PD(86), PORT_DATA_IO_PU_PD(87),
PORT_DATA_IO_PU_PD(88), PORT_DATA_IO_PU_PD(89),
PORT_DATA_IO_PU_PD(90), PORT_DATA_IO_PU_PD(91),
PORT_DATA_IO_PU_PD(92), PORT_DATA_IO_PU_PD(93),
PORT_DATA_IO_PU_PD(94), PORT_DATA_IO_PU_PD(95),
PORT_DATA_IO_PU(96), PORT_DATA_IO_PU_PD(97),
PORT_DATA_IO_PU_PD(98), PORT_DATA_O(99), /*99?*/
PORT_DATA_IO_PD(100), PORT_DATA_IO_PD(101),
PORT_DATA_IO_PD(102), PORT_DATA_IO_PD(103),
PORT_DATA_IO_PD(104), PORT_DATA_IO_PD(105),
PORT_DATA_IO_PU(106), PORT_DATA_IO_PU(107),
PORT_DATA_IO_PU(108), PORT_DATA_IO_PU(109),
PORT_DATA_IO_PU(110), PORT_DATA_IO_PU(111),
PORT_DATA_IO_PD(112), PORT_DATA_IO_PD(113),
PORT_DATA_IO_PU(114), PORT_DATA_IO_PU(115),
PORT_DATA_IO_PU(116), PORT_DATA_IO_PU(117),
PORT_DATA_IO_PU(118), PORT_DATA_IO_PU(119),
PORT_DATA_IO_PU(120), PORT_DATA_IO_PD(121),
PORT_DATA_IO_PD(122), PORT_DATA_IO_PD(123),
PORT_DATA_IO_PD(124), PORT_DATA_IO_PD(125),
PORT_DATA_IO_PD(126), PORT_DATA_IO_PD(127),
PORT_DATA_IO_PD(128), PORT_DATA_IO_PU_PD(129),
PORT_DATA_IO_PU_PD(130), PORT_DATA_IO_PU_PD(131),
PORT_DATA_IO_PU_PD(132), PORT_DATA_IO_PU_PD(133),
PORT_DATA_IO_PU_PD(134), PORT_DATA_IO_PU_PD(135),
PORT_DATA_IO_PD(136), PORT_DATA_IO_PD(137),
PORT_DATA_IO_PD(138), PORT_DATA_IO_PD(139),
PORT_DATA_IO_PD(140), PORT_DATA_IO_PD(141),
PORT_DATA_IO_PD(142), PORT_DATA_IO_PU_PD(143),
PORT_DATA_IO_PD(144), PORT_DATA_IO_PD(145),
PORT_DATA_IO_PD(146), PORT_DATA_IO_PD(147),
PORT_DATA_IO_PD(148), PORT_DATA_IO_PD(149),
PORT_DATA_IO_PD(150), PORT_DATA_IO_PD(151),
PORT_DATA_IO_PU_PD(152), PORT_DATA_I_PD(153),
PORT_DATA_IO_PU_PD(154), PORT_DATA_I_PD(155),
PORT_DATA_IO_PD(156), PORT_DATA_IO_PD(157),
PORT_DATA_I_PD(158), PORT_DATA_IO_PD(159),
PORT_DATA_O(160), PORT_DATA_IO_PD(161),
PORT_DATA_IO_PD(162), PORT_DATA_IO_PD(163),
PORT_DATA_I_PD(164), PORT_DATA_IO_PD(165),
PORT_DATA_I_PD(166), PORT_DATA_I_PD(167),
PORT_DATA_I_PD(168), PORT_DATA_I_PD(169),
PORT_DATA_I_PD(170), PORT_DATA_O(171),
PORT_DATA_IO_PU_PD(172), PORT_DATA_IO_PU_PD(173),
PORT_DATA_IO_PU_PD(174), PORT_DATA_IO_PU_PD(175),
PORT_DATA_IO_PU_PD(176), PORT_DATA_IO_PU_PD(177),
PORT_DATA_IO_PU_PD(178), PORT_DATA_O(179),
PORT_DATA_IO_PU_PD(180), PORT_DATA_IO_PU_PD(181),
PORT_DATA_IO_PU_PD(182), PORT_DATA_IO_PU_PD(183),
PORT_DATA_IO_PU_PD(184), PORT_DATA_O(185),
PORT_DATA_IO_PU_PD(186), PORT_DATA_IO_PU_PD(187),
PORT_DATA_IO_PU_PD(188), PORT_DATA_IO_PU_PD(189),
PORT_DATA_IO_PU_PD(190),
/* IRQ */
PINMUX_DATA(IRQ0_6_MARK, PORT6_FN0, MSEL1CR_0_0),
PINMUX_DATA(IRQ0_162_MARK, PORT162_FN0, MSEL1CR_0_1),
PINMUX_DATA(IRQ1_MARK, PORT12_FN0),
PINMUX_DATA(IRQ2_4_MARK, PORT4_FN0, MSEL1CR_2_0),
PINMUX_DATA(IRQ2_5_MARK, PORT5_FN0, MSEL1CR_2_1),
PINMUX_DATA(IRQ3_8_MARK, PORT8_FN0, MSEL1CR_3_0),
PINMUX_DATA(IRQ3_16_MARK, PORT16_FN0, MSEL1CR_3_1),
PINMUX_DATA(IRQ4_17_MARK, PORT17_FN0, MSEL1CR_4_0),
PINMUX_DATA(IRQ4_163_MARK, PORT163_FN0, MSEL1CR_4_1),
PINMUX_DATA(IRQ5_MARK, PORT18_FN0),
PINMUX_DATA(IRQ6_39_MARK, PORT39_FN0, MSEL1CR_6_0),
PINMUX_DATA(IRQ6_164_MARK, PORT164_FN0, MSEL1CR_6_1),
PINMUX_DATA(IRQ7_40_MARK, PORT40_FN0, MSEL1CR_7_1),
PINMUX_DATA(IRQ7_167_MARK, PORT167_FN0, MSEL1CR_7_0),
PINMUX_DATA(IRQ8_41_MARK, PORT41_FN0, MSEL1CR_8_1),
PINMUX_DATA(IRQ8_168_MARK, PORT168_FN0, MSEL1CR_8_0),
PINMUX_DATA(IRQ9_42_MARK, PORT42_FN0, MSEL1CR_9_0),
PINMUX_DATA(IRQ9_169_MARK, PORT169_FN0, MSEL1CR_9_1),
PINMUX_DATA(IRQ10_MARK, PORT65_FN0, MSEL1CR_9_1),
PINMUX_DATA(IRQ11_MARK, PORT67_FN0),
PINMUX_DATA(IRQ12_80_MARK, PORT80_FN0, MSEL1CR_12_0),
PINMUX_DATA(IRQ12_137_MARK, PORT137_FN0, MSEL1CR_12_1),
PINMUX_DATA(IRQ13_81_MARK, PORT81_FN0, MSEL1CR_13_0),
PINMUX_DATA(IRQ13_145_MARK, PORT145_FN0, MSEL1CR_13_1),
PINMUX_DATA(IRQ14_82_MARK, PORT82_FN0, MSEL1CR_14_0),
PINMUX_DATA(IRQ14_146_MARK, PORT146_FN0, MSEL1CR_14_1),
PINMUX_DATA(IRQ15_83_MARK, PORT83_FN0, MSEL1CR_15_0),
PINMUX_DATA(IRQ15_147_MARK, PORT147_FN0, MSEL1CR_15_1),
PINMUX_DATA(IRQ16_84_MARK, PORT84_FN0, MSEL1CR_16_0),
PINMUX_DATA(IRQ16_170_MARK, PORT170_FN0, MSEL1CR_16_1),
PINMUX_DATA(IRQ17_MARK, PORT85_FN0),
PINMUX_DATA(IRQ18_MARK, PORT86_FN0),
PINMUX_DATA(IRQ19_MARK, PORT87_FN0),
PINMUX_DATA(IRQ20_MARK, PORT92_FN0),
PINMUX_DATA(IRQ21_MARK, PORT93_FN0),
PINMUX_DATA(IRQ22_MARK, PORT94_FN0),
PINMUX_DATA(IRQ23_MARK, PORT95_FN0),
PINMUX_DATA(IRQ24_MARK, PORT112_FN0),
PINMUX_DATA(IRQ25_MARK, PORT119_FN0),
PINMUX_DATA(IRQ26_121_MARK, PORT121_FN0, MSEL1CR_26_1),
PINMUX_DATA(IRQ26_172_MARK, PORT172_FN0, MSEL1CR_26_0),
PINMUX_DATA(IRQ27_122_MARK, PORT122_FN0, MSEL1CR_27_1),
PINMUX_DATA(IRQ27_180_MARK, PORT180_FN0, MSEL1CR_27_0),
PINMUX_DATA(IRQ28_123_MARK, PORT123_FN0, MSEL1CR_28_1),
PINMUX_DATA(IRQ28_181_MARK, PORT181_FN0, MSEL1CR_28_0),
PINMUX_DATA(IRQ29_129_MARK, PORT129_FN0, MSEL1CR_29_1),
PINMUX_DATA(IRQ29_182_MARK, PORT182_FN0, MSEL1CR_29_0),
PINMUX_DATA(IRQ30_130_MARK, PORT130_FN0, MSEL1CR_30_1),
PINMUX_DATA(IRQ30_183_MARK, PORT183_FN0, MSEL1CR_30_0),
PINMUX_DATA(IRQ31_138_MARK, PORT138_FN0, MSEL1CR_31_1),
PINMUX_DATA(IRQ31_184_MARK, PORT184_FN0, MSEL1CR_31_0),
/* Function 1 */
PINMUX_DATA(BBIF2_TSCK1_MARK, PORT0_FN1),
PINMUX_DATA(BBIF2_TSYNC1_MARK, PORT1_FN1),
PINMUX_DATA(BBIF2_TXD1_MARK, PORT2_FN1),
PINMUX_DATA(BBIF2_RXD_MARK, PORT3_FN1),
PINMUX_DATA(FSIACK_MARK, PORT4_FN1),
PINMUX_DATA(FSIAILR_MARK, PORT5_FN1),
PINMUX_DATA(FSIAIBT_MARK, PORT6_FN1),
PINMUX_DATA(FSIAISLD_MARK, PORT7_FN1),
PINMUX_DATA(FSIAOMC_MARK, PORT8_FN1),
PINMUX_DATA(FSIAOLR_MARK, PORT9_FN1),
PINMUX_DATA(FSIAOBT_MARK, PORT10_FN1),
PINMUX_DATA(FSIAOSLD_MARK, PORT11_FN1),
PINMUX_DATA(FMSOCK_MARK, PORT12_FN1),
PINMUX_DATA(FMSOOLR_MARK, PORT13_FN1),
PINMUX_DATA(FMSOOBT_MARK, PORT14_FN1),
PINMUX_DATA(FMSOSLD_MARK, PORT15_FN1),
PINMUX_DATA(FMSOILR_MARK, PORT16_FN1),
PINMUX_DATA(FMSOIBT_MARK, PORT17_FN1),
PINMUX_DATA(FMSISLD_MARK, PORT18_FN1),
PINMUX_DATA(A0_MARK, PORT19_FN1),
PINMUX_DATA(A1_MARK, PORT20_FN1),
PINMUX_DATA(A2_MARK, PORT21_FN1),
PINMUX_DATA(A3_MARK, PORT22_FN1),
PINMUX_DATA(A4_FOE_MARK, PORT23_FN1),
PINMUX_DATA(A5_FCDE_MARK, PORT24_FN1),
PINMUX_DATA(A6_MARK, PORT25_FN1),
PINMUX_DATA(A7_MARK, PORT26_FN1),
PINMUX_DATA(A8_MARK, PORT27_FN1),
PINMUX_DATA(A9_MARK, PORT28_FN1),
PINMUX_DATA(A10_MARK, PORT29_FN1),
PINMUX_DATA(A11_MARK, PORT30_FN1),
PINMUX_DATA(A12_MARK, PORT31_FN1),
PINMUX_DATA(A13_MARK, PORT32_FN1),
PINMUX_DATA(A14_MARK, PORT33_FN1),
PINMUX_DATA(A15_MARK, PORT34_FN1),
PINMUX_DATA(A16_MARK, PORT35_FN1),
PINMUX_DATA(A17_MARK, PORT36_FN1),
PINMUX_DATA(A18_MARK, PORT37_FN1),
PINMUX_DATA(A19_MARK, PORT38_FN1),
PINMUX_DATA(A20_MARK, PORT39_FN1),
PINMUX_DATA(A21_MARK, PORT40_FN1),
PINMUX_DATA(A22_MARK, PORT41_FN1),
PINMUX_DATA(A23_MARK, PORT42_FN1),
PINMUX_DATA(A24_MARK, PORT43_FN1),
PINMUX_DATA(A25_MARK, PORT44_FN1),
PINMUX_DATA(A26_MARK, PORT45_FN1),
PINMUX_DATA(D0_NAF0_MARK, PORT46_FN1),
PINMUX_DATA(D1_NAF1_MARK, PORT47_FN1),
PINMUX_DATA(D2_NAF2_MARK, PORT48_FN1),
PINMUX_DATA(D3_NAF3_MARK, PORT49_FN1),
PINMUX_DATA(D4_NAF4_MARK, PORT50_FN1),
PINMUX_DATA(D5_NAF5_MARK, PORT51_FN1),
PINMUX_DATA(D6_NAF6_MARK, PORT52_FN1),
PINMUX_DATA(D7_NAF7_MARK, PORT53_FN1),
PINMUX_DATA(D8_NAF8_MARK, PORT54_FN1),
PINMUX_DATA(D9_NAF9_MARK, PORT55_FN1),
PINMUX_DATA(D10_NAF10_MARK, PORT56_FN1),
PINMUX_DATA(D11_NAF11_MARK, PORT57_FN1),
PINMUX_DATA(D12_NAF12_MARK, PORT58_FN1),
PINMUX_DATA(D13_NAF13_MARK, PORT59_FN1),
PINMUX_DATA(D14_NAF14_MARK, PORT60_FN1),
PINMUX_DATA(D15_NAF15_MARK, PORT61_FN1),
PINMUX_DATA(CS0_MARK, PORT62_FN1),
PINMUX_DATA(CS2_MARK, PORT63_FN1),
PINMUX_DATA(CS4_MARK, PORT64_FN1),
PINMUX_DATA(CS5A_MARK, PORT65_FN1),
PINMUX_DATA(CS5B_MARK, PORT66_FN1),
PINMUX_DATA(CS6A_MARK, PORT67_FN1),
PINMUX_DATA(FCE0_MARK, PORT68_FN1),
PINMUX_DATA(RD_FSC_MARK, PORT69_FN1),
PINMUX_DATA(WE0_FWE_MARK, PORT70_FN1),
PINMUX_DATA(WE1_MARK, PORT71_FN1),
PINMUX_DATA(CKO_MARK, PORT72_FN1),
PINMUX_DATA(FRB_MARK, PORT73_FN1),
PINMUX_DATA(WAIT_MARK, PORT74_FN1),
PINMUX_DATA(RDWR_MARK, PORT75_FN1),
PINMUX_DATA(MEMC_AD0_MARK, PORT76_FN1),
PINMUX_DATA(MEMC_AD1_MARK, PORT77_FN1),
PINMUX_DATA(MEMC_AD2_MARK, PORT78_FN1),
PINMUX_DATA(MEMC_AD3_MARK, PORT79_FN1),
PINMUX_DATA(MEMC_AD4_MARK, PORT80_FN1),
PINMUX_DATA(MEMC_AD5_MARK, PORT81_FN1),
PINMUX_DATA(MEMC_AD6_MARK, PORT82_FN1),
PINMUX_DATA(MEMC_AD7_MARK, PORT83_FN1),
PINMUX_DATA(MEMC_AD8_MARK, PORT84_FN1),
PINMUX_DATA(MEMC_AD9_MARK, PORT85_FN1),
PINMUX_DATA(MEMC_AD10_MARK, PORT86_FN1),
PINMUX_DATA(MEMC_AD11_MARK, PORT87_FN1),
PINMUX_DATA(MEMC_AD12_MARK, PORT88_FN1),
PINMUX_DATA(MEMC_AD13_MARK, PORT89_FN1),
PINMUX_DATA(MEMC_AD14_MARK, PORT90_FN1),
PINMUX_DATA(MEMC_AD15_MARK, PORT91_FN1),
PINMUX_DATA(MEMC_CS0_MARK, PORT92_FN1),
PINMUX_DATA(MEMC_BUSCLK_MEMC_A0_MARK, PORT93_FN1),
PINMUX_DATA(MEMC_CS1_MEMC_A1_MARK, PORT94_FN1),
PINMUX_DATA(MEMC_ADV_MEMC_DREQ0_MARK, PORT95_FN1),
PINMUX_DATA(MEMC_WAIT_MEMC_DREQ1_MARK, PORT96_FN1),
PINMUX_DATA(MEMC_NOE_MARK, PORT97_FN1),
PINMUX_DATA(MEMC_NWE_MARK, PORT98_FN1),
PINMUX_DATA(MEMC_INT_MARK, PORT99_FN1),
PINMUX_DATA(VIO_VD_MARK, PORT100_FN1),
PINMUX_DATA(VIO_HD_MARK, PORT101_FN1),
PINMUX_DATA(VIO_D0_MARK, PORT102_FN1),
PINMUX_DATA(VIO_D1_MARK, PORT103_FN1),
PINMUX_DATA(VIO_D2_MARK, PORT104_FN1),
PINMUX_DATA(VIO_D3_MARK, PORT105_FN1),
PINMUX_DATA(VIO_D4_MARK, PORT106_FN1),
PINMUX_DATA(VIO_D5_MARK, PORT107_FN1),
PINMUX_DATA(VIO_D6_MARK, PORT108_FN1),
PINMUX_DATA(VIO_D7_MARK, PORT109_FN1),
PINMUX_DATA(VIO_D8_MARK, PORT110_FN1),
PINMUX_DATA(VIO_D9_MARK, PORT111_FN1),
PINMUX_DATA(VIO_D10_MARK, PORT112_FN1),
PINMUX_DATA(VIO_D11_MARK, PORT113_FN1),
PINMUX_DATA(VIO_D12_MARK, PORT114_FN1),
PINMUX_DATA(VIO_D13_MARK, PORT115_FN1),
PINMUX_DATA(VIO_D14_MARK, PORT116_FN1),
PINMUX_DATA(VIO_D15_MARK, PORT117_FN1),
PINMUX_DATA(VIO_CLK_MARK, PORT118_FN1),
PINMUX_DATA(VIO_FIELD_MARK, PORT119_FN1),
PINMUX_DATA(VIO_CKO_MARK, PORT120_FN1),
PINMUX_DATA(LCDD0_MARK, PORT121_FN1),
PINMUX_DATA(LCDD1_MARK, PORT122_FN1),
PINMUX_DATA(LCDD2_MARK, PORT123_FN1),
PINMUX_DATA(LCDD3_MARK, PORT124_FN1),
PINMUX_DATA(LCDD4_MARK, PORT125_FN1),
PINMUX_DATA(LCDD5_MARK, PORT126_FN1),
PINMUX_DATA(LCDD6_MARK, PORT127_FN1),
PINMUX_DATA(LCDD7_MARK, PORT128_FN1),
PINMUX_DATA(LCDD8_MARK, PORT129_FN1),
PINMUX_DATA(LCDD9_MARK, PORT130_FN1),
PINMUX_DATA(LCDD10_MARK, PORT131_FN1),
PINMUX_DATA(LCDD11_MARK, PORT132_FN1),
PINMUX_DATA(LCDD12_MARK, PORT133_FN1),
PINMUX_DATA(LCDD13_MARK, PORT134_FN1),
PINMUX_DATA(LCDD14_MARK, PORT135_FN1),
PINMUX_DATA(LCDD15_MARK, PORT136_FN1),
PINMUX_DATA(LCDD16_MARK, PORT137_FN1),
PINMUX_DATA(LCDD17_MARK, PORT138_FN1),
PINMUX_DATA(LCDD18_MARK, PORT139_FN1),
PINMUX_DATA(LCDD19_MARK, PORT140_FN1),
PINMUX_DATA(LCDD20_MARK, PORT141_FN1),
PINMUX_DATA(LCDD21_MARK, PORT142_FN1),
PINMUX_DATA(LCDD22_MARK, PORT143_FN1),
PINMUX_DATA(LCDD23_MARK, PORT144_FN1),
PINMUX_DATA(LCDHSYN_MARK, PORT145_FN1),
PINMUX_DATA(LCDVSYN_MARK, PORT146_FN1),
PINMUX_DATA(LCDDCK_MARK, PORT147_FN1),
PINMUX_DATA(LCDRD_MARK, PORT148_FN1),
PINMUX_DATA(LCDDISP_MARK, PORT149_FN1),
PINMUX_DATA(LCDLCLK_MARK, PORT150_FN1),
PINMUX_DATA(LCDDON_MARK, PORT151_FN1),
PINMUX_DATA(SCIFA0_TXD_MARK, PORT152_FN1),
PINMUX_DATA(SCIFA0_RXD_MARK, PORT153_FN1),
PINMUX_DATA(SCIFA1_TXD_MARK, PORT154_FN1),
PINMUX_DATA(SCIFA1_RXD_MARK, PORT155_FN1),
PINMUX_DATA(TS_SPSYNC1_MARK, PORT156_FN1),
PINMUX_DATA(TS_SDAT1_MARK, PORT157_FN1),
PINMUX_DATA(TS_SDEN1_MARK, PORT158_FN1),
PINMUX_DATA(TS_SCK1_MARK, PORT159_FN1),
PINMUX_DATA(TPU0TO0_MARK, PORT160_FN1),
PINMUX_DATA(TPU0TO1_MARK, PORT161_FN1),
PINMUX_DATA(SCIFB_SCK_MARK, PORT162_FN1),
PINMUX_DATA(SCIFB_RTS_MARK, PORT163_FN1),
PINMUX_DATA(SCIFB_CTS_MARK, PORT164_FN1),
PINMUX_DATA(SCIFB_TXD_MARK, PORT165_FN1),
PINMUX_DATA(SCIFB_RXD_MARK, PORT166_FN1),
PINMUX_DATA(VBUS0_0_MARK, PORT167_FN1),
PINMUX_DATA(VBUS0_1_MARK, PORT168_FN1),
PINMUX_DATA(HDMI_HPD_MARK, PORT169_FN1),
PINMUX_DATA(HDMI_CEC_MARK, PORT170_FN1),
PINMUX_DATA(SDHICLK0_MARK, PORT171_FN1),
PINMUX_DATA(SDHICD0_MARK, PORT172_FN1),
PINMUX_DATA(SDHID0_0_MARK, PORT173_FN1),
PINMUX_DATA(SDHID0_1_MARK, PORT174_FN1),
PINMUX_DATA(SDHID0_2_MARK, PORT175_FN1),
PINMUX_DATA(SDHID0_3_MARK, PORT176_FN1),
PINMUX_DATA(SDHICMD0_MARK, PORT177_FN1),
PINMUX_DATA(SDHIWP0_MARK, PORT178_FN1),
PINMUX_DATA(SDHICLK1_MARK, PORT179_FN1),
PINMUX_DATA(SDHID1_0_MARK, PORT180_FN1),
PINMUX_DATA(SDHID1_1_MARK, PORT181_FN1),
PINMUX_DATA(SDHID1_2_MARK, PORT182_FN1),
PINMUX_DATA(SDHID1_3_MARK, PORT183_FN1),
PINMUX_DATA(SDHICMD1_MARK, PORT184_FN1),
PINMUX_DATA(SDHICLK2_MARK, PORT185_FN1),
PINMUX_DATA(SDHID2_0_MARK, PORT186_FN1),
PINMUX_DATA(SDHID2_1_MARK, PORT187_FN1),
PINMUX_DATA(SDHID2_2_MARK, PORT188_FN1),
PINMUX_DATA(SDHID2_3_MARK, PORT189_FN1),
PINMUX_DATA(SDHICMD2_MARK, PORT190_FN1),
/* Function 2 */
PINMUX_DATA(FSIBCK_MARK, PORT4_FN2),
PINMUX_DATA(SCIFA4_RXD_MARK, PORT5_FN2),
PINMUX_DATA(SCIFA4_TXD_MARK, PORT6_FN2),
PINMUX_DATA(SCIFA5_RXD_MARK, PORT8_FN2),
PINMUX_DATA(FSIASPDIF_11_MARK, PORT11_FN2),
PINMUX_DATA(SCIFA5_TXD_MARK, PORT12_FN2),
PINMUX_DATA(FMSIOLR_MARK, PORT13_FN2),
PINMUX_DATA(FMSIOBT_MARK, PORT14_FN2),
PINMUX_DATA(FSIASPDIF_15_MARK, PORT15_FN2),
PINMUX_DATA(FMSIILR_MARK, PORT16_FN2),
PINMUX_DATA(FMSIIBT_MARK, PORT17_FN2),
PINMUX_DATA(BS_MARK, PORT19_FN2),
PINMUX_DATA(MSIOF0_TSYNC_MARK, PORT36_FN2),
PINMUX_DATA(MSIOF0_TSCK_MARK, PORT37_FN2),
PINMUX_DATA(MSIOF0_RXD_MARK, PORT38_FN2),
PINMUX_DATA(MSIOF0_RSCK_MARK, PORT39_FN2),
PINMUX_DATA(MSIOF0_RSYNC_MARK, PORT40_FN2),
PINMUX_DATA(MSIOF0_MCK0_MARK, PORT41_FN2),
PINMUX_DATA(MSIOF0_MCK1_MARK, PORT42_FN2),
PINMUX_DATA(MSIOF0_SS1_MARK, PORT43_FN2),
PINMUX_DATA(MSIOF0_SS2_MARK, PORT44_FN2),
PINMUX_DATA(MSIOF0_TXD_MARK, PORT45_FN2),
PINMUX_DATA(FMSICK_MARK, PORT65_FN2),
PINMUX_DATA(FCE1_MARK, PORT66_FN2),
PINMUX_DATA(BBIF1_RXD_MARK, PORT76_FN2),
PINMUX_DATA(BBIF1_TSYNC_MARK, PORT77_FN2),
PINMUX_DATA(BBIF1_TSCK_MARK, PORT78_FN2),
PINMUX_DATA(BBIF1_TXD_MARK, PORT79_FN2),
PINMUX_DATA(BBIF1_RSCK_MARK, PORT80_FN2),
PINMUX_DATA(BBIF1_RSYNC_MARK, PORT81_FN2),
PINMUX_DATA(BBIF1_FLOW_MARK, PORT82_FN2),
PINMUX_DATA(BB_RX_FLOW_N_MARK, PORT83_FN2),
PINMUX_DATA(MSIOF1_RSCK_MARK, PORT84_FN2),
PINMUX_DATA(MSIOF1_RSYNC_MARK, PORT85_FN2),
PINMUX_DATA(MSIOF1_MCK0_MARK, PORT86_FN2),
PINMUX_DATA(MSIOF1_MCK1_MARK, PORT87_FN2),
PINMUX_DATA(MSIOF1_TSCK_88_MARK, PORT88_FN2, MSEL4CR_10_1),
PINMUX_DATA(MSIOF1_TSYNC_89_MARK, PORT89_FN2, MSEL4CR_10_1),
PINMUX_DATA(MSIOF1_TXD_90_MARK, PORT90_FN2, MSEL4CR_10_1),
PINMUX_DATA(MSIOF1_RXD_91_MARK, PORT91_FN2, MSEL4CR_10_1),
PINMUX_DATA(MSIOF1_SS1_92_MARK, PORT92_FN2, MSEL4CR_10_1),
PINMUX_DATA(MSIOF1_SS2_93_MARK, PORT93_FN2, MSEL4CR_10_1),
PINMUX_DATA(SCIFA2_CTS1_MARK, PORT94_FN2),
PINMUX_DATA(SCIFA2_RTS1_MARK, PORT95_FN2),
PINMUX_DATA(SCIFA2_TXD1_MARK, PORT96_FN2),
PINMUX_DATA(SCIFA2_RXD1_MARK, PORT97_FN2),
PINMUX_DATA(SCIFA2_SCK1_MARK, PORT98_FN2),
PINMUX_DATA(I2C_SCL2_MARK, PORT110_FN2),
PINMUX_DATA(I2C_SDA2_MARK, PORT111_FN2),
PINMUX_DATA(I2C_SCL3_MARK, PORT114_FN2, MSEL4CR_16_1),
PINMUX_DATA(I2C_SDA3_MARK, PORT115_FN2, MSEL4CR_16_1),
PINMUX_DATA(I2C_SCL4_MARK, PORT116_FN2, MSEL4CR_17_1),
PINMUX_DATA(I2C_SDA4_MARK, PORT117_FN2, MSEL4CR_17_1),
PINMUX_DATA(MSIOF2_RSCK_MARK, PORT134_FN2),
PINMUX_DATA(MSIOF2_RSYNC_MARK, PORT135_FN2),
PINMUX_DATA(MSIOF2_MCK0_MARK, PORT136_FN2),
PINMUX_DATA(MSIOF2_MCK1_MARK, PORT137_FN2),
PINMUX_DATA(MSIOF2_SS1_MARK, PORT138_FN2),
PINMUX_DATA(MSIOF2_SS2_MARK, PORT139_FN2),
PINMUX_DATA(SCIFA3_CTS_140_MARK, PORT140_FN2, MSEL3CR_9_1),
PINMUX_DATA(SCIFA3_RTS_141_MARK, PORT141_FN2),
PINMUX_DATA(SCIFA3_SCK_MARK, PORT142_FN2),
PINMUX_DATA(SCIFA3_TXD_MARK, PORT143_FN2),
PINMUX_DATA(SCIFA3_RXD_MARK, PORT144_FN2),
PINMUX_DATA(MSIOF2_TSYNC_MARK, PORT148_FN2),
PINMUX_DATA(MSIOF2_TSCK_MARK, PORT149_FN2),
PINMUX_DATA(MSIOF2_RXD_MARK, PORT150_FN2),
PINMUX_DATA(MSIOF2_TXD_MARK, PORT151_FN2),
PINMUX_DATA(SCIFA0_SCK_MARK, PORT156_FN2),
PINMUX_DATA(SCIFA0_RTS_MARK, PORT157_FN2),
PINMUX_DATA(SCIFA0_CTS_MARK, PORT158_FN2),
PINMUX_DATA(SCIFA1_SCK_MARK, PORT159_FN2),
PINMUX_DATA(SCIFA1_RTS_MARK, PORT160_FN2),
PINMUX_DATA(SCIFA1_CTS_MARK, PORT161_FN2),
/* Function 3 */
PINMUX_DATA(VIO_CKO1_MARK, PORT16_FN3),
PINMUX_DATA(VIO_CKO2_MARK, PORT17_FN3),
PINMUX_DATA(IDIN_1_18_MARK, PORT18_FN3, MSEL4CR_14_1),
PINMUX_DATA(MSIOF1_TSCK_39_MARK, PORT39_FN3, MSEL4CR_10_0),
PINMUX_DATA(MSIOF1_TSYNC_40_MARK, PORT40_FN3, MSEL4CR_10_0),
PINMUX_DATA(MSIOF1_TXD_41_MARK, PORT41_FN3, MSEL4CR_10_0),
PINMUX_DATA(MSIOF1_RXD_42_MARK, PORT42_FN3, MSEL4CR_10_0),
PINMUX_DATA(MSIOF1_SS1_43_MARK, PORT43_FN3, MSEL4CR_10_0),
PINMUX_DATA(MSIOF1_SS2_44_MARK, PORT44_FN3, MSEL4CR_10_0),
PINMUX_DATA(MMCD1_0_MARK, PORT54_FN3, MSEL4CR_15_1),
PINMUX_DATA(MMCD1_1_MARK, PORT55_FN3, MSEL4CR_15_1),
PINMUX_DATA(MMCD1_2_MARK, PORT56_FN3, MSEL4CR_15_1),
PINMUX_DATA(MMCD1_3_MARK, PORT57_FN3, MSEL4CR_15_1),
PINMUX_DATA(MMCD1_4_MARK, PORT58_FN3, MSEL4CR_15_1),
PINMUX_DATA(MMCD1_5_MARK, PORT59_FN3, MSEL4CR_15_1),
PINMUX_DATA(MMCD1_6_MARK, PORT60_FN3, MSEL4CR_15_1),
PINMUX_DATA(MMCD1_7_MARK, PORT61_FN3, MSEL4CR_15_1),
PINMUX_DATA(VINT_I_MARK, PORT65_FN3),
PINMUX_DATA(MMCCLK1_MARK, PORT66_FN3, MSEL4CR_15_1),
PINMUX_DATA(MMCCMD1_MARK, PORT67_FN3, MSEL4CR_15_1),
PINMUX_DATA(TPU0TO2_93_MARK, PORT93_FN3),
PINMUX_DATA(TPU0TO2_99_MARK, PORT99_FN3),
PINMUX_DATA(TPU0TO3_MARK, PORT112_FN3),
PINMUX_DATA(IDIN_0_MARK, PORT113_FN3),
PINMUX_DATA(EXTLP_0_MARK, PORT114_FN3),
PINMUX_DATA(OVCN2_0_MARK, PORT115_FN3),
PINMUX_DATA(PWEN_0_MARK, PORT116_FN3),
PINMUX_DATA(OVCN_0_MARK, PORT117_FN3),
PINMUX_DATA(KEYOUT7_MARK, PORT121_FN3),
PINMUX_DATA(KEYOUT6_MARK, PORT122_FN3),
PINMUX_DATA(KEYOUT5_MARK, PORT123_FN3),
PINMUX_DATA(KEYOUT4_MARK, PORT124_FN3),
PINMUX_DATA(KEYOUT3_MARK, PORT125_FN3),
PINMUX_DATA(KEYOUT2_MARK, PORT126_FN3),
PINMUX_DATA(KEYOUT1_MARK, PORT127_FN3),
PINMUX_DATA(KEYOUT0_MARK, PORT128_FN3),
PINMUX_DATA(KEYIN7_MARK, PORT129_FN3),
PINMUX_DATA(KEYIN6_MARK, PORT130_FN3),
PINMUX_DATA(KEYIN5_MARK, PORT131_FN3),
PINMUX_DATA(KEYIN4_MARK, PORT132_FN3),
PINMUX_DATA(KEYIN3_133_MARK, PORT133_FN3, MSEL4CR_18_0),
PINMUX_DATA(KEYIN2_134_MARK, PORT134_FN3, MSEL4CR_18_0),
PINMUX_DATA(KEYIN1_135_MARK, PORT135_FN3, MSEL4CR_18_0),
PINMUX_DATA(KEYIN0_136_MARK, PORT136_FN3, MSEL4CR_18_0),
PINMUX_DATA(TS_SPSYNC2_MARK, PORT137_FN3),
PINMUX_DATA(IROUT_139_MARK, PORT139_FN3),
PINMUX_DATA(IRDA_OUT_MARK, PORT140_FN3),
PINMUX_DATA(IRDA_IN_MARK, PORT141_FN3),
PINMUX_DATA(IRDA_FIRSEL_MARK, PORT142_FN3),
PINMUX_DATA(TS_SDAT2_MARK, PORT145_FN3),
PINMUX_DATA(TS_SDEN2_MARK, PORT146_FN3),
PINMUX_DATA(TS_SCK2_MARK, PORT147_FN3),
/* Function 4 */
PINMUX_DATA(SCIFA3_CTS_43_MARK, PORT43_FN4, MSEL3CR_9_0),
PINMUX_DATA(SCIFA3_RTS_44_MARK, PORT44_FN4),
PINMUX_DATA(GP_RX_FLAG_MARK, PORT76_FN4),
PINMUX_DATA(GP_RX_DATA_MARK, PORT77_FN4),
PINMUX_DATA(GP_TX_READY_MARK, PORT78_FN4),
PINMUX_DATA(GP_RX_WAKE_MARK, PORT79_FN4),
PINMUX_DATA(MP_TX_FLAG_MARK, PORT80_FN4),
PINMUX_DATA(MP_TX_DATA_MARK, PORT81_FN4),
PINMUX_DATA(MP_RX_READY_MARK, PORT82_FN4),
PINMUX_DATA(MP_TX_WAKE_MARK, PORT83_FN4),
PINMUX_DATA(MMCD0_0_MARK, PORT84_FN4, MSEL4CR_15_0),
PINMUX_DATA(MMCD0_1_MARK, PORT85_FN4, MSEL4CR_15_0),
PINMUX_DATA(MMCD0_2_MARK, PORT86_FN4, MSEL4CR_15_0),
PINMUX_DATA(MMCD0_3_MARK, PORT87_FN4, MSEL4CR_15_0),
PINMUX_DATA(MMCD0_4_MARK, PORT88_FN4, MSEL4CR_15_0),
PINMUX_DATA(MMCD0_5_MARK, PORT89_FN4, MSEL4CR_15_0),
PINMUX_DATA(MMCD0_6_MARK, PORT90_FN4, MSEL4CR_15_0),
PINMUX_DATA(MMCD0_7_MARK, PORT91_FN4, MSEL4CR_15_0),
PINMUX_DATA(MMCCMD0_MARK, PORT92_FN4, MSEL4CR_15_0),
PINMUX_DATA(SIM_RST_MARK, PORT94_FN4),
PINMUX_DATA(SIM_CLK_MARK, PORT95_FN4),
PINMUX_DATA(SIM_D_MARK, PORT98_FN4),
PINMUX_DATA(MMCCLK0_MARK, PORT99_FN4, MSEL4CR_15_0),
PINMUX_DATA(IDIN_1_113_MARK, PORT113_FN4, MSEL4CR_14_0),
PINMUX_DATA(OVCN_1_114_MARK, PORT114_FN4, MSEL4CR_14_0),
PINMUX_DATA(PWEN_1_115_MARK, PORT115_FN4),
PINMUX_DATA(EXTLP_1_MARK, PORT116_FN4),
PINMUX_DATA(OVCN2_1_MARK, PORT117_FN4),
PINMUX_DATA(KEYIN0_121_MARK, PORT121_FN4, MSEL4CR_18_1),
PINMUX_DATA(KEYIN1_122_MARK, PORT122_FN4, MSEL4CR_18_1),
PINMUX_DATA(KEYIN2_123_MARK, PORT123_FN4, MSEL4CR_18_1),
PINMUX_DATA(KEYIN3_124_MARK, PORT124_FN4, MSEL4CR_18_1),
PINMUX_DATA(PWEN_1_138_MARK, PORT138_FN4),
PINMUX_DATA(IROUT_140_MARK, PORT140_FN4),
PINMUX_DATA(LCDCS_MARK, PORT145_FN4),
PINMUX_DATA(LCDWR_MARK, PORT147_FN4),
PINMUX_DATA(LCDRS_MARK, PORT149_FN4),
PINMUX_DATA(OVCN_1_162_MARK, PORT162_FN4, MSEL4CR_14_1),
/* Function 5 */
PINMUX_DATA(GPI0_MARK, PORT41_FN5),
PINMUX_DATA(GPI1_MARK, PORT42_FN5),
PINMUX_DATA(GPO0_MARK, PORT43_FN5),
PINMUX_DATA(GPO1_MARK, PORT44_FN5),
PINMUX_DATA(I2C_SCL3S_MARK, PORT137_FN5, MSEL4CR_16_0),
PINMUX_DATA(I2C_SDA3S_MARK, PORT145_FN5, MSEL4CR_16_0),
PINMUX_DATA(I2C_SCL4S_MARK, PORT146_FN5, MSEL4CR_17_0),
PINMUX_DATA(I2C_SDA4S_MARK, PORT147_FN5, MSEL4CR_17_0),
/* Function select */
PINMUX_DATA(LCDC0_SELECT_MARK, MSEL3CR_6_0),
PINMUX_DATA(LCDC1_SELECT_MARK, MSEL3CR_6_1),
PINMUX_DATA(TS0_1SELECT_MARK, MSEL3CR_21_0, MSEL3CR_20_0),
PINMUX_DATA(TS0_2SELECT_MARK, MSEL3CR_21_0, MSEL3CR_20_1),
PINMUX_DATA(TS1_1SELECT_MARK, MSEL3CR_27_0, MSEL3CR_26_0),
PINMUX_DATA(TS1_2SELECT_MARK, MSEL3CR_27_0, MSEL3CR_26_1),
PINMUX_DATA(SDENC_CPG_MARK, MSEL4CR_19_0),
PINMUX_DATA(SDENC_DV_CLKI_MARK, MSEL4CR_19_1),
PINMUX_DATA(MFIv6_MARK, MSEL4CR_6_0),
PINMUX_DATA(MFIv4_MARK, MSEL4CR_6_1),
};
static struct sh_pfc_pin pinmux_pins[] = {
GPIO_PORT_ALL(),
};
/* - MMCIF ------------------------------------------------------------------ */
static const unsigned int mmc0_data1_0_pins[] = {
/* D[0] */
84,
};
static const unsigned int mmc0_data1_0_mux[] = {
MMCD0_0_MARK,
};
static const unsigned int mmc0_data4_0_pins[] = {
/* D[0:3] */
84, 85, 86, 87,
};
static const unsigned int mmc0_data4_0_mux[] = {
MMCD0_0_MARK, MMCD0_1_MARK, MMCD0_2_MARK, MMCD0_3_MARK,
};
static const unsigned int mmc0_data8_0_pins[] = {
/* D[0:7] */
84, 85, 86, 87, 88, 89, 90, 91,
};
static const unsigned int mmc0_data8_0_mux[] = {
MMCD0_0_MARK, MMCD0_1_MARK, MMCD0_2_MARK, MMCD0_3_MARK,
MMCD0_4_MARK, MMCD0_5_MARK, MMCD0_6_MARK, MMCD0_7_MARK,
};
static const unsigned int mmc0_ctrl_0_pins[] = {
/* CMD, CLK */
92, 99,
};
static const unsigned int mmc0_ctrl_0_mux[] = {
MMCCMD0_MARK, MMCCLK0_MARK,
};
static const unsigned int mmc0_data1_1_pins[] = {
/* D[0] */
54,
};
static const unsigned int mmc0_data1_1_mux[] = {
MMCD1_0_MARK,
};
static const unsigned int mmc0_data4_1_pins[] = {
/* D[0:3] */
54, 55, 56, 57,
};
static const unsigned int mmc0_data4_1_mux[] = {
MMCD1_0_MARK, MMCD1_1_MARK, MMCD1_2_MARK, MMCD1_3_MARK,
};
static const unsigned int mmc0_data8_1_pins[] = {
/* D[0:7] */
54, 55, 56, 57, 58, 59, 60, 61,
};
static const unsigned int mmc0_data8_1_mux[] = {
MMCD1_0_MARK, MMCD1_1_MARK, MMCD1_2_MARK, MMCD1_3_MARK,
MMCD1_4_MARK, MMCD1_5_MARK, MMCD1_6_MARK, MMCD1_7_MARK,
};
static const unsigned int mmc0_ctrl_1_pins[] = {
/* CMD, CLK */
67, 66,
};
static const unsigned int mmc0_ctrl_1_mux[] = {
MMCCMD1_MARK, MMCCLK1_MARK,
};
/* - SDHI0 ------------------------------------------------------------------ */
static const unsigned int sdhi0_data1_pins[] = {
/* D0 */
173,
};
static const unsigned int sdhi0_data1_mux[] = {
SDHID0_0_MARK,
};
static const unsigned int sdhi0_data4_pins[] = {
/* D[0:3] */
173, 174, 175, 176,
};
static const unsigned int sdhi0_data4_mux[] = {
SDHID0_0_MARK, SDHID0_1_MARK, SDHID0_2_MARK, SDHID0_3_MARK,
};
static const unsigned int sdhi0_ctrl_pins[] = {
/* CMD, CLK */
177, 171,
};
static const unsigned int sdhi0_ctrl_mux[] = {
SDHICMD0_MARK, SDHICLK0_MARK,
};
static const unsigned int sdhi0_cd_pins[] = {
/* CD */
172,
};
static const unsigned int sdhi0_cd_mux[] = {
SDHICD0_MARK,
};
static const unsigned int sdhi0_wp_pins[] = {
/* WP */
178,
};
static const unsigned int sdhi0_wp_mux[] = {
SDHIWP0_MARK,
};
/* - SDHI1 ------------------------------------------------------------------ */
static const unsigned int sdhi1_data1_pins[] = {
/* D0 */
180,
};
static const unsigned int sdhi1_data1_mux[] = {
SDHID1_0_MARK,
};
static const unsigned int sdhi1_data4_pins[] = {
/* D[0:3] */
180, 181, 182, 183,
};
static const unsigned int sdhi1_data4_mux[] = {
SDHID1_0_MARK, SDHID1_1_MARK, SDHID1_2_MARK, SDHID1_3_MARK,
};
static const unsigned int sdhi1_ctrl_pins[] = {
/* CMD, CLK */
184, 179,
};
static const unsigned int sdhi1_ctrl_mux[] = {
SDHICMD1_MARK, SDHICLK1_MARK,
};
static const unsigned int sdhi2_data1_pins[] = {
/* D0 */
186,
};
static const unsigned int sdhi2_data1_mux[] = {
SDHID2_0_MARK,
};
static const unsigned int sdhi2_data4_pins[] = {
/* D[0:3] */
186, 187, 188, 189,
};
static const unsigned int sdhi2_data4_mux[] = {
SDHID2_0_MARK, SDHID2_1_MARK, SDHID2_2_MARK, SDHID2_3_MARK,
};
static const unsigned int sdhi2_ctrl_pins[] = {
/* CMD, CLK */
190, 185,
};
static const unsigned int sdhi2_ctrl_mux[] = {
SDHICMD2_MARK, SDHICLK2_MARK,
};
static const struct sh_pfc_pin_group pinmux_groups[] = {
SH_PFC_PIN_GROUP(mmc0_data1_0),
SH_PFC_PIN_GROUP(mmc0_data4_0),
SH_PFC_PIN_GROUP(mmc0_data8_0),
SH_PFC_PIN_GROUP(mmc0_ctrl_0),
SH_PFC_PIN_GROUP(mmc0_data1_1),
SH_PFC_PIN_GROUP(mmc0_data4_1),
SH_PFC_PIN_GROUP(mmc0_data8_1),
SH_PFC_PIN_GROUP(mmc0_ctrl_1),
SH_PFC_PIN_GROUP(sdhi0_data1),
SH_PFC_PIN_GROUP(sdhi0_data4),
SH_PFC_PIN_GROUP(sdhi0_ctrl),
SH_PFC_PIN_GROUP(sdhi0_cd),
SH_PFC_PIN_GROUP(sdhi0_wp),
SH_PFC_PIN_GROUP(sdhi1_data1),
SH_PFC_PIN_GROUP(sdhi1_data4),
SH_PFC_PIN_GROUP(sdhi1_ctrl),
SH_PFC_PIN_GROUP(sdhi2_data1),
SH_PFC_PIN_GROUP(sdhi2_data4),
SH_PFC_PIN_GROUP(sdhi2_ctrl),
};
static const char * const mmc0_groups[] = {
"mmc0_data1_0",
"mmc0_data4_0",
"mmc0_data8_0",
"mmc0_ctrl_0",
"mmc0_data1_1",
"mmc0_data4_1",
"mmc0_data8_1",
"mmc0_ctrl_1",
};
static const char * const sdhi0_groups[] = {
"sdhi0_data1",
"sdhi0_data4",
"sdhi0_ctrl",
"sdhi0_cd",
"sdhi0_wp",
};
static const char * const sdhi1_groups[] = {
"sdhi1_data1",
"sdhi1_data4",
"sdhi1_ctrl",
};
static const char * const sdhi2_groups[] = {
"sdhi2_data1",
"sdhi2_data4",
"sdhi2_ctrl",
};
static const struct sh_pfc_function pinmux_functions[] = {
SH_PFC_FUNCTION(mmc0),
SH_PFC_FUNCTION(sdhi0),
SH_PFC_FUNCTION(sdhi1),
SH_PFC_FUNCTION(sdhi2),
};
#define PINMUX_FN_BASE ARRAY_SIZE(pinmux_pins)
static const struct pinmux_func pinmux_func_gpios[] = {
/* IRQ */
GPIO_FN(IRQ0_6), GPIO_FN(IRQ0_162), GPIO_FN(IRQ1),
GPIO_FN(IRQ2_4), GPIO_FN(IRQ2_5), GPIO_FN(IRQ3_8),
GPIO_FN(IRQ3_16), GPIO_FN(IRQ4_17), GPIO_FN(IRQ4_163),
GPIO_FN(IRQ5), GPIO_FN(IRQ6_39), GPIO_FN(IRQ6_164),
GPIO_FN(IRQ7_40), GPIO_FN(IRQ7_167), GPIO_FN(IRQ8_41),
GPIO_FN(IRQ8_168), GPIO_FN(IRQ9_42), GPIO_FN(IRQ9_169),
GPIO_FN(IRQ10), GPIO_FN(IRQ11), GPIO_FN(IRQ12_80),
GPIO_FN(IRQ12_137), GPIO_FN(IRQ13_81), GPIO_FN(IRQ13_145),
GPIO_FN(IRQ14_82), GPIO_FN(IRQ14_146), GPIO_FN(IRQ15_83),
GPIO_FN(IRQ15_147), GPIO_FN(IRQ16_84), GPIO_FN(IRQ16_170),
GPIO_FN(IRQ17), GPIO_FN(IRQ18), GPIO_FN(IRQ19),
GPIO_FN(IRQ20), GPIO_FN(IRQ21), GPIO_FN(IRQ22),
GPIO_FN(IRQ23), GPIO_FN(IRQ24), GPIO_FN(IRQ25),
GPIO_FN(IRQ26_121), GPIO_FN(IRQ26_172), GPIO_FN(IRQ27_122),
GPIO_FN(IRQ27_180), GPIO_FN(IRQ28_123), GPIO_FN(IRQ28_181),
GPIO_FN(IRQ29_129), GPIO_FN(IRQ29_182), GPIO_FN(IRQ30_130),
GPIO_FN(IRQ30_183), GPIO_FN(IRQ31_138), GPIO_FN(IRQ31_184),
/* MSIOF0 */
GPIO_FN(MSIOF0_TSYNC), GPIO_FN(MSIOF0_TSCK), GPIO_FN(MSIOF0_RXD),
GPIO_FN(MSIOF0_RSCK), GPIO_FN(MSIOF0_RSYNC), GPIO_FN(MSIOF0_MCK0),
GPIO_FN(MSIOF0_MCK1), GPIO_FN(MSIOF0_SS1), GPIO_FN(MSIOF0_SS2),
GPIO_FN(MSIOF0_TXD),
/* MSIOF1 */
GPIO_FN(MSIOF1_TSCK_39), GPIO_FN(MSIOF1_TSCK_88),
GPIO_FN(MSIOF1_TSYNC_40), GPIO_FN(MSIOF1_TSYNC_89),
GPIO_FN(MSIOF1_TXD_41), GPIO_FN(MSIOF1_TXD_90),
GPIO_FN(MSIOF1_RXD_42), GPIO_FN(MSIOF1_RXD_91),
GPIO_FN(MSIOF1_SS1_43), GPIO_FN(MSIOF1_SS1_92),
GPIO_FN(MSIOF1_SS2_44), GPIO_FN(MSIOF1_SS2_93),
GPIO_FN(MSIOF1_RSCK), GPIO_FN(MSIOF1_RSYNC),
GPIO_FN(MSIOF1_MCK0), GPIO_FN(MSIOF1_MCK1),
/* MSIOF2 */
GPIO_FN(MSIOF2_RSCK), GPIO_FN(MSIOF2_RSYNC), GPIO_FN(MSIOF2_MCK0),
GPIO_FN(MSIOF2_MCK1), GPIO_FN(MSIOF2_SS1), GPIO_FN(MSIOF2_SS2),
GPIO_FN(MSIOF2_TSYNC), GPIO_FN(MSIOF2_TSCK), GPIO_FN(MSIOF2_RXD),
GPIO_FN(MSIOF2_TXD),
/* BBIF1 */
GPIO_FN(BBIF1_RXD), GPIO_FN(BBIF1_TSYNC), GPIO_FN(BBIF1_TSCK),
GPIO_FN(BBIF1_TXD), GPIO_FN(BBIF1_RSCK), GPIO_FN(BBIF1_RSYNC),
GPIO_FN(BBIF1_FLOW), GPIO_FN(BB_RX_FLOW_N),
/* BBIF2 */
GPIO_FN(BBIF2_TSCK1), GPIO_FN(BBIF2_TSYNC1),
GPIO_FN(BBIF2_TXD1), GPIO_FN(BBIF2_RXD),
/* FSI */
GPIO_FN(FSIACK), GPIO_FN(FSIBCK), GPIO_FN(FSIAILR),
GPIO_FN(FSIAIBT), GPIO_FN(FSIAISLD), GPIO_FN(FSIAOMC),
GPIO_FN(FSIAOLR), GPIO_FN(FSIAOBT), GPIO_FN(FSIAOSLD),
GPIO_FN(FSIASPDIF_11), GPIO_FN(FSIASPDIF_15),
/* FMSI */
GPIO_FN(FMSOCK), GPIO_FN(FMSOOLR), GPIO_FN(FMSIOLR),
GPIO_FN(FMSOOBT), GPIO_FN(FMSIOBT), GPIO_FN(FMSOSLD),
GPIO_FN(FMSOILR), GPIO_FN(FMSIILR), GPIO_FN(FMSOIBT),
GPIO_FN(FMSIIBT), GPIO_FN(FMSISLD), GPIO_FN(FMSICK),
/* SCIFA0 */
GPIO_FN(SCIFA0_TXD), GPIO_FN(SCIFA0_RXD), GPIO_FN(SCIFA0_SCK),
GPIO_FN(SCIFA0_RTS), GPIO_FN(SCIFA0_CTS),
/* SCIFA1 */
GPIO_FN(SCIFA1_TXD), GPIO_FN(SCIFA1_RXD), GPIO_FN(SCIFA1_SCK),
GPIO_FN(SCIFA1_RTS), GPIO_FN(SCIFA1_CTS),
/* SCIFA2 */
GPIO_FN(SCIFA2_CTS1), GPIO_FN(SCIFA2_RTS1), GPIO_FN(SCIFA2_TXD1),
GPIO_FN(SCIFA2_RXD1), GPIO_FN(SCIFA2_SCK1),
/* SCIFA3 */
GPIO_FN(SCIFA3_CTS_43), GPIO_FN(SCIFA3_CTS_140),
GPIO_FN(SCIFA3_RTS_44), GPIO_FN(SCIFA3_RTS_141),
GPIO_FN(SCIFA3_SCK), GPIO_FN(SCIFA3_TXD),
GPIO_FN(SCIFA3_RXD),
/* SCIFA4 */
GPIO_FN(SCIFA4_RXD), GPIO_FN(SCIFA4_TXD),
/* SCIFA5 */
GPIO_FN(SCIFA5_RXD), GPIO_FN(SCIFA5_TXD),
/* SCIFB */
GPIO_FN(SCIFB_SCK), GPIO_FN(SCIFB_RTS), GPIO_FN(SCIFB_CTS),
GPIO_FN(SCIFB_TXD), GPIO_FN(SCIFB_RXD),
/* CEU */
GPIO_FN(VIO_HD), GPIO_FN(VIO_CKO1), GPIO_FN(VIO_CKO2),
GPIO_FN(VIO_VD), GPIO_FN(VIO_CLK), GPIO_FN(VIO_FIELD),
GPIO_FN(VIO_CKO), GPIO_FN(VIO_D0), GPIO_FN(VIO_D1),
GPIO_FN(VIO_D2), GPIO_FN(VIO_D3), GPIO_FN(VIO_D4),
GPIO_FN(VIO_D5), GPIO_FN(VIO_D6), GPIO_FN(VIO_D7),
GPIO_FN(VIO_D8), GPIO_FN(VIO_D9), GPIO_FN(VIO_D10),
GPIO_FN(VIO_D11), GPIO_FN(VIO_D12), GPIO_FN(VIO_D13),
GPIO_FN(VIO_D14), GPIO_FN(VIO_D15),
/* USB0 */
GPIO_FN(IDIN_0), GPIO_FN(EXTLP_0), GPIO_FN(OVCN2_0),
GPIO_FN(PWEN_0), GPIO_FN(OVCN_0), GPIO_FN(VBUS0_0),
/* USB1 */
GPIO_FN(IDIN_1_18), GPIO_FN(IDIN_1_113),
GPIO_FN(OVCN_1_114), GPIO_FN(OVCN_1_162),
GPIO_FN(PWEN_1_115), GPIO_FN(PWEN_1_138),
GPIO_FN(EXTLP_1), GPIO_FN(OVCN2_1),
GPIO_FN(VBUS0_1),
/* GPIO */
GPIO_FN(GPI0), GPIO_FN(GPI1), GPIO_FN(GPO0), GPIO_FN(GPO1),
/* BSC */
GPIO_FN(BS), GPIO_FN(WE1), GPIO_FN(CKO),
GPIO_FN(WAIT), GPIO_FN(RDWR),
GPIO_FN(A0), GPIO_FN(A1), GPIO_FN(A2),
GPIO_FN(A3), GPIO_FN(A6), GPIO_FN(A7),
GPIO_FN(A8), GPIO_FN(A9), GPIO_FN(A10),
GPIO_FN(A11), GPIO_FN(A12), GPIO_FN(A13),
GPIO_FN(A14), GPIO_FN(A15), GPIO_FN(A16),
GPIO_FN(A17), GPIO_FN(A18), GPIO_FN(A19),
GPIO_FN(A20), GPIO_FN(A21), GPIO_FN(A22),
GPIO_FN(A23), GPIO_FN(A24), GPIO_FN(A25),
GPIO_FN(A26),
GPIO_FN(CS0), GPIO_FN(CS2), GPIO_FN(CS4),
GPIO_FN(CS5A), GPIO_FN(CS5B), GPIO_FN(CS6A),
/* BSC/FLCTL */
GPIO_FN(RD_FSC), GPIO_FN(WE0_FWE), GPIO_FN(A4_FOE),
GPIO_FN(A5_FCDE), GPIO_FN(D0_NAF0), GPIO_FN(D1_NAF1),
GPIO_FN(D2_NAF2), GPIO_FN(D3_NAF3), GPIO_FN(D4_NAF4),
GPIO_FN(D5_NAF5), GPIO_FN(D6_NAF6), GPIO_FN(D7_NAF7),
GPIO_FN(D8_NAF8), GPIO_FN(D9_NAF9), GPIO_FN(D10_NAF10),
GPIO_FN(D11_NAF11), GPIO_FN(D12_NAF12), GPIO_FN(D13_NAF13),
GPIO_FN(D14_NAF14), GPIO_FN(D15_NAF15),
/* SPU2 */
GPIO_FN(VINT_I),
/* FLCTL */
GPIO_FN(FCE1), GPIO_FN(FCE0), GPIO_FN(FRB),
/* HSI */
GPIO_FN(GP_RX_FLAG), GPIO_FN(GP_RX_DATA), GPIO_FN(GP_TX_READY),
GPIO_FN(GP_RX_WAKE), GPIO_FN(MP_TX_FLAG), GPIO_FN(MP_TX_DATA),
GPIO_FN(MP_RX_READY), GPIO_FN(MP_TX_WAKE),
/* MFI */
GPIO_FN(MFIv6),
GPIO_FN(MFIv4),
GPIO_FN(MEMC_BUSCLK_MEMC_A0), GPIO_FN(MEMC_ADV_MEMC_DREQ0),
GPIO_FN(MEMC_WAIT_MEMC_DREQ1), GPIO_FN(MEMC_CS1_MEMC_A1),
GPIO_FN(MEMC_CS0), GPIO_FN(MEMC_NOE),
GPIO_FN(MEMC_NWE), GPIO_FN(MEMC_INT),
GPIO_FN(MEMC_AD0), GPIO_FN(MEMC_AD1), GPIO_FN(MEMC_AD2),
GPIO_FN(MEMC_AD3), GPIO_FN(MEMC_AD4), GPIO_FN(MEMC_AD5),
GPIO_FN(MEMC_AD6), GPIO_FN(MEMC_AD7), GPIO_FN(MEMC_AD8),
GPIO_FN(MEMC_AD9), GPIO_FN(MEMC_AD10), GPIO_FN(MEMC_AD11),
GPIO_FN(MEMC_AD12), GPIO_FN(MEMC_AD13), GPIO_FN(MEMC_AD14),
GPIO_FN(MEMC_AD15),
/* SIM */
GPIO_FN(SIM_RST), GPIO_FN(SIM_CLK), GPIO_FN(SIM_D),
/* TPU */
GPIO_FN(TPU0TO0), GPIO_FN(TPU0TO1), GPIO_FN(TPU0TO2_93),
GPIO_FN(TPU0TO2_99), GPIO_FN(TPU0TO3),
/* I2C2 */
GPIO_FN(I2C_SCL2), GPIO_FN(I2C_SDA2),
/* I2C3(1) */
GPIO_FN(I2C_SCL3), GPIO_FN(I2C_SDA3),
/* I2C3(2) */
GPIO_FN(I2C_SCL3S), GPIO_FN(I2C_SDA3S),
/* I2C4(2) */
GPIO_FN(I2C_SCL4), GPIO_FN(I2C_SDA4),
/* I2C4(2) */
GPIO_FN(I2C_SCL4S), GPIO_FN(I2C_SDA4S),
/* KEYSC */
GPIO_FN(KEYOUT0), GPIO_FN(KEYIN0_121), GPIO_FN(KEYIN0_136),
GPIO_FN(KEYOUT1), GPIO_FN(KEYIN1_122), GPIO_FN(KEYIN1_135),
GPIO_FN(KEYOUT2), GPIO_FN(KEYIN2_123), GPIO_FN(KEYIN2_134),
GPIO_FN(KEYOUT3), GPIO_FN(KEYIN3_124), GPIO_FN(KEYIN3_133),
GPIO_FN(KEYOUT4), GPIO_FN(KEYIN4), GPIO_FN(KEYOUT5),
GPIO_FN(KEYIN5), GPIO_FN(KEYOUT6), GPIO_FN(KEYIN6),
GPIO_FN(KEYOUT7), GPIO_FN(KEYIN7),
/* LCDC */
GPIO_FN(LCDHSYN), GPIO_FN(LCDCS), GPIO_FN(LCDVSYN),
GPIO_FN(LCDDCK), GPIO_FN(LCDWR), GPIO_FN(LCDRD),
GPIO_FN(LCDDISP), GPIO_FN(LCDRS), GPIO_FN(LCDLCLK),
GPIO_FN(LCDDON),
GPIO_FN(LCDD0), GPIO_FN(LCDD1), GPIO_FN(LCDD2),
GPIO_FN(LCDD3), GPIO_FN(LCDD4), GPIO_FN(LCDD5),
GPIO_FN(LCDD6), GPIO_FN(LCDD7), GPIO_FN(LCDD8),
GPIO_FN(LCDD9), GPIO_FN(LCDD10), GPIO_FN(LCDD11),
GPIO_FN(LCDD12), GPIO_FN(LCDD13), GPIO_FN(LCDD14),
GPIO_FN(LCDD15), GPIO_FN(LCDD16), GPIO_FN(LCDD17),
GPIO_FN(LCDD18), GPIO_FN(LCDD19), GPIO_FN(LCDD20),
GPIO_FN(LCDD21), GPIO_FN(LCDD22), GPIO_FN(LCDD23),
GPIO_FN(LCDC0_SELECT),
GPIO_FN(LCDC1_SELECT),
/* IRDA */
GPIO_FN(IRDA_OUT), GPIO_FN(IRDA_IN), GPIO_FN(IRDA_FIRSEL),
GPIO_FN(IROUT_139), GPIO_FN(IROUT_140),
/* TSIF1 */
GPIO_FN(TS0_1SELECT),
GPIO_FN(TS0_2SELECT),
GPIO_FN(TS1_1SELECT),
GPIO_FN(TS1_2SELECT),
GPIO_FN(TS_SPSYNC1), GPIO_FN(TS_SDAT1),
GPIO_FN(TS_SDEN1), GPIO_FN(TS_SCK1),
/* TSIF2 */
GPIO_FN(TS_SPSYNC2), GPIO_FN(TS_SDAT2),
GPIO_FN(TS_SDEN2), GPIO_FN(TS_SCK2),
/* HDMI */
GPIO_FN(HDMI_HPD), GPIO_FN(HDMI_CEC),
/* SDENC */
GPIO_FN(SDENC_CPG),
GPIO_FN(SDENC_DV_CLKI),
};
static const struct pinmux_cfg_reg pinmux_config_regs[] = {
PORTCR(0, 0xE6051000), /* PORT0CR */
PORTCR(1, 0xE6051001), /* PORT1CR */
PORTCR(2, 0xE6051002), /* PORT2CR */
PORTCR(3, 0xE6051003), /* PORT3CR */
PORTCR(4, 0xE6051004), /* PORT4CR */
PORTCR(5, 0xE6051005), /* PORT5CR */
PORTCR(6, 0xE6051006), /* PORT6CR */
PORTCR(7, 0xE6051007), /* PORT7CR */
PORTCR(8, 0xE6051008), /* PORT8CR */
PORTCR(9, 0xE6051009), /* PORT9CR */
PORTCR(10, 0xE605100A), /* PORT10CR */
PORTCR(11, 0xE605100B), /* PORT11CR */
PORTCR(12, 0xE605100C), /* PORT12CR */
PORTCR(13, 0xE605100D), /* PORT13CR */
PORTCR(14, 0xE605100E), /* PORT14CR */
PORTCR(15, 0xE605100F), /* PORT15CR */
PORTCR(16, 0xE6051010), /* PORT16CR */
PORTCR(17, 0xE6051011), /* PORT17CR */
PORTCR(18, 0xE6051012), /* PORT18CR */
PORTCR(19, 0xE6051013), /* PORT19CR */
PORTCR(20, 0xE6051014), /* PORT20CR */
PORTCR(21, 0xE6051015), /* PORT21CR */
PORTCR(22, 0xE6051016), /* PORT22CR */
PORTCR(23, 0xE6051017), /* PORT23CR */
PORTCR(24, 0xE6051018), /* PORT24CR */
PORTCR(25, 0xE6051019), /* PORT25CR */
PORTCR(26, 0xE605101A), /* PORT26CR */
PORTCR(27, 0xE605101B), /* PORT27CR */
PORTCR(28, 0xE605101C), /* PORT28CR */
PORTCR(29, 0xE605101D), /* PORT29CR */
PORTCR(30, 0xE605101E), /* PORT30CR */
PORTCR(31, 0xE605101F), /* PORT31CR */
PORTCR(32, 0xE6051020), /* PORT32CR */
PORTCR(33, 0xE6051021), /* PORT33CR */
PORTCR(34, 0xE6051022), /* PORT34CR */
PORTCR(35, 0xE6051023), /* PORT35CR */
PORTCR(36, 0xE6051024), /* PORT36CR */
PORTCR(37, 0xE6051025), /* PORT37CR */
PORTCR(38, 0xE6051026), /* PORT38CR */
PORTCR(39, 0xE6051027), /* PORT39CR */
PORTCR(40, 0xE6051028), /* PORT40CR */
PORTCR(41, 0xE6051029), /* PORT41CR */
PORTCR(42, 0xE605102A), /* PORT42CR */
PORTCR(43, 0xE605102B), /* PORT43CR */
PORTCR(44, 0xE605102C), /* PORT44CR */
PORTCR(45, 0xE605102D), /* PORT45CR */
PORTCR(46, 0xE605202E), /* PORT46CR */
PORTCR(47, 0xE605202F), /* PORT47CR */
PORTCR(48, 0xE6052030), /* PORT48CR */
PORTCR(49, 0xE6052031), /* PORT49CR */
PORTCR(50, 0xE6052032), /* PORT50CR */
PORTCR(51, 0xE6052033), /* PORT51CR */
PORTCR(52, 0xE6052034), /* PORT52CR */
PORTCR(53, 0xE6052035), /* PORT53CR */
PORTCR(54, 0xE6052036), /* PORT54CR */
PORTCR(55, 0xE6052037), /* PORT55CR */
PORTCR(56, 0xE6052038), /* PORT56CR */
PORTCR(57, 0xE6052039), /* PORT57CR */
PORTCR(58, 0xE605203A), /* PORT58CR */
PORTCR(59, 0xE605203B), /* PORT59CR */
PORTCR(60, 0xE605203C), /* PORT60CR */
PORTCR(61, 0xE605203D), /* PORT61CR */
PORTCR(62, 0xE605203E), /* PORT62CR */
PORTCR(63, 0xE605203F), /* PORT63CR */
PORTCR(64, 0xE6052040), /* PORT64CR */
PORTCR(65, 0xE6052041), /* PORT65CR */
PORTCR(66, 0xE6052042), /* PORT66CR */
PORTCR(67, 0xE6052043), /* PORT67CR */
PORTCR(68, 0xE6052044), /* PORT68CR */
PORTCR(69, 0xE6052045), /* PORT69CR */
PORTCR(70, 0xE6052046), /* PORT70CR */
PORTCR(71, 0xE6052047), /* PORT71CR */
PORTCR(72, 0xE6052048), /* PORT72CR */
PORTCR(73, 0xE6052049), /* PORT73CR */
PORTCR(74, 0xE605204A), /* PORT74CR */
PORTCR(75, 0xE605204B), /* PORT75CR */
PORTCR(76, 0xE605004C), /* PORT76CR */
PORTCR(77, 0xE605004D), /* PORT77CR */
PORTCR(78, 0xE605004E), /* PORT78CR */
PORTCR(79, 0xE605004F), /* PORT79CR */
PORTCR(80, 0xE6050050), /* PORT80CR */
PORTCR(81, 0xE6050051), /* PORT81CR */
PORTCR(82, 0xE6050052), /* PORT82CR */
PORTCR(83, 0xE6050053), /* PORT83CR */
PORTCR(84, 0xE6050054), /* PORT84CR */
PORTCR(85, 0xE6050055), /* PORT85CR */
PORTCR(86, 0xE6050056), /* PORT86CR */
PORTCR(87, 0xE6050057), /* PORT87CR */
PORTCR(88, 0xE6050058), /* PORT88CR */
PORTCR(89, 0xE6050059), /* PORT89CR */
PORTCR(90, 0xE605005A), /* PORT90CR */
PORTCR(91, 0xE605005B), /* PORT91CR */
PORTCR(92, 0xE605005C), /* PORT92CR */
PORTCR(93, 0xE605005D), /* PORT93CR */
PORTCR(94, 0xE605005E), /* PORT94CR */
PORTCR(95, 0xE605005F), /* PORT95CR */
PORTCR(96, 0xE6050060), /* PORT96CR */
PORTCR(97, 0xE6050061), /* PORT97CR */
PORTCR(98, 0xE6050062), /* PORT98CR */
PORTCR(99, 0xE6050063), /* PORT99CR */
PORTCR(100, 0xE6053064), /* PORT100CR */
PORTCR(101, 0xE6053065), /* PORT101CR */
PORTCR(102, 0xE6053066), /* PORT102CR */
PORTCR(103, 0xE6053067), /* PORT103CR */
PORTCR(104, 0xE6053068), /* PORT104CR */
PORTCR(105, 0xE6053069), /* PORT105CR */
PORTCR(106, 0xE605306A), /* PORT106CR */
PORTCR(107, 0xE605306B), /* PORT107CR */
PORTCR(108, 0xE605306C), /* PORT108CR */
PORTCR(109, 0xE605306D), /* PORT109CR */
PORTCR(110, 0xE605306E), /* PORT110CR */
PORTCR(111, 0xE605306F), /* PORT111CR */
PORTCR(112, 0xE6053070), /* PORT112CR */
PORTCR(113, 0xE6053071), /* PORT113CR */
PORTCR(114, 0xE6053072), /* PORT114CR */
PORTCR(115, 0xE6053073), /* PORT115CR */
PORTCR(116, 0xE6053074), /* PORT116CR */
PORTCR(117, 0xE6053075), /* PORT117CR */
PORTCR(118, 0xE6053076), /* PORT118CR */
PORTCR(119, 0xE6053077), /* PORT119CR */
PORTCR(120, 0xE6053078), /* PORT120CR */
PORTCR(121, 0xE6050079), /* PORT121CR */
PORTCR(122, 0xE605007A), /* PORT122CR */
PORTCR(123, 0xE605007B), /* PORT123CR */
PORTCR(124, 0xE605007C), /* PORT124CR */
PORTCR(125, 0xE605007D), /* PORT125CR */
PORTCR(126, 0xE605007E), /* PORT126CR */
PORTCR(127, 0xE605007F), /* PORT127CR */
PORTCR(128, 0xE6050080), /* PORT128CR */
PORTCR(129, 0xE6050081), /* PORT129CR */
PORTCR(130, 0xE6050082), /* PORT130CR */
PORTCR(131, 0xE6050083), /* PORT131CR */
PORTCR(132, 0xE6050084), /* PORT132CR */
PORTCR(133, 0xE6050085), /* PORT133CR */
PORTCR(134, 0xE6050086), /* PORT134CR */
PORTCR(135, 0xE6050087), /* PORT135CR */
PORTCR(136, 0xE6050088), /* PORT136CR */
PORTCR(137, 0xE6050089), /* PORT137CR */
PORTCR(138, 0xE605008A), /* PORT138CR */
PORTCR(139, 0xE605008B), /* PORT139CR */
PORTCR(140, 0xE605008C), /* PORT140CR */
PORTCR(141, 0xE605008D), /* PORT141CR */
PORTCR(142, 0xE605008E), /* PORT142CR */
PORTCR(143, 0xE605008F), /* PORT143CR */
PORTCR(144, 0xE6050090), /* PORT144CR */
PORTCR(145, 0xE6050091), /* PORT145CR */
PORTCR(146, 0xE6050092), /* PORT146CR */
PORTCR(147, 0xE6050093), /* PORT147CR */
PORTCR(148, 0xE6050094), /* PORT148CR */
PORTCR(149, 0xE6050095), /* PORT149CR */
PORTCR(150, 0xE6050096), /* PORT150CR */
PORTCR(151, 0xE6050097), /* PORT151CR */
PORTCR(152, 0xE6053098), /* PORT152CR */
PORTCR(153, 0xE6053099), /* PORT153CR */
PORTCR(154, 0xE605309A), /* PORT154CR */
PORTCR(155, 0xE605309B), /* PORT155CR */
PORTCR(156, 0xE605009C), /* PORT156CR */
PORTCR(157, 0xE605009D), /* PORT157CR */
PORTCR(158, 0xE605009E), /* PORT158CR */
PORTCR(159, 0xE605009F), /* PORT159CR */
PORTCR(160, 0xE60500A0), /* PORT160CR */
PORTCR(161, 0xE60500A1), /* PORT161CR */
PORTCR(162, 0xE60500A2), /* PORT162CR */
PORTCR(163, 0xE60500A3), /* PORT163CR */
PORTCR(164, 0xE60500A4), /* PORT164CR */
PORTCR(165, 0xE60500A5), /* PORT165CR */
PORTCR(166, 0xE60500A6), /* PORT166CR */
PORTCR(167, 0xE60520A7), /* PORT167CR */
PORTCR(168, 0xE60520A8), /* PORT168CR */
PORTCR(169, 0xE60520A9), /* PORT169CR */
PORTCR(170, 0xE60520AA), /* PORT170CR */
PORTCR(171, 0xE60520AB), /* PORT171CR */
PORTCR(172, 0xE60520AC), /* PORT172CR */
PORTCR(173, 0xE60520AD), /* PORT173CR */
PORTCR(174, 0xE60520AE), /* PORT174CR */
PORTCR(175, 0xE60520AF), /* PORT175CR */
PORTCR(176, 0xE60520B0), /* PORT176CR */
PORTCR(177, 0xE60520B1), /* PORT177CR */
PORTCR(178, 0xE60520B2), /* PORT178CR */
PORTCR(179, 0xE60520B3), /* PORT179CR */
PORTCR(180, 0xE60520B4), /* PORT180CR */
PORTCR(181, 0xE60520B5), /* PORT181CR */
PORTCR(182, 0xE60520B6), /* PORT182CR */
PORTCR(183, 0xE60520B7), /* PORT183CR */
PORTCR(184, 0xE60520B8), /* PORT184CR */
PORTCR(185, 0xE60520B9), /* PORT185CR */
PORTCR(186, 0xE60520BA), /* PORT186CR */
PORTCR(187, 0xE60520BB), /* PORT187CR */
PORTCR(188, 0xE60520BC), /* PORT188CR */
PORTCR(189, 0xE60520BD), /* PORT189CR */
PORTCR(190, 0xE60520BE), /* PORT190CR */
{ PINMUX_CFG_REG("MSEL1CR", 0xE605800C, 32, 1) {
MSEL1CR_31_0, MSEL1CR_31_1,
MSEL1CR_30_0, MSEL1CR_30_1,
MSEL1CR_29_0, MSEL1CR_29_1,
MSEL1CR_28_0, MSEL1CR_28_1,
MSEL1CR_27_0, MSEL1CR_27_1,
MSEL1CR_26_0, MSEL1CR_26_1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
MSEL1CR_16_0, MSEL1CR_16_1,
MSEL1CR_15_0, MSEL1CR_15_1,
MSEL1CR_14_0, MSEL1CR_14_1,
MSEL1CR_13_0, MSEL1CR_13_1,
MSEL1CR_12_0, MSEL1CR_12_1,
0, 0, 0, 0,
MSEL1CR_9_0, MSEL1CR_9_1,
MSEL1CR_8_0, MSEL1CR_8_1,
MSEL1CR_7_0, MSEL1CR_7_1,
MSEL1CR_6_0, MSEL1CR_6_1,
0, 0,
MSEL1CR_4_0, MSEL1CR_4_1,
MSEL1CR_3_0, MSEL1CR_3_1,
MSEL1CR_2_0, MSEL1CR_2_1,
0, 0,
MSEL1CR_0_0, MSEL1CR_0_1,
}
},
{ PINMUX_CFG_REG("MSEL3CR", 0xE6058020, 32, 1) {
0, 0, 0, 0,
0, 0, 0, 0,
MSEL3CR_27_0, MSEL3CR_27_1,
MSEL3CR_26_0, MSEL3CR_26_1,
0, 0, 0, 0,
0, 0, 0, 0,
MSEL3CR_21_0, MSEL3CR_21_1,
MSEL3CR_20_0, MSEL3CR_20_1,
0, 0, 0, 0,
0, 0, 0, 0,
MSEL3CR_15_0, MSEL3CR_15_1,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0,
MSEL3CR_9_0, MSEL3CR_9_1,
0, 0, 0, 0,
MSEL3CR_6_0, MSEL3CR_6_1,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
}
},
{ PINMUX_CFG_REG("MSEL4CR", 0xE6058024, 32, 1) {
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
MSEL4CR_19_0, MSEL4CR_19_1,
MSEL4CR_18_0, MSEL4CR_18_1,
MSEL4CR_17_0, MSEL4CR_17_1,
MSEL4CR_16_0, MSEL4CR_16_1,
MSEL4CR_15_0, MSEL4CR_15_1,
MSEL4CR_14_0, MSEL4CR_14_1,
0, 0, 0, 0,
0, 0,
MSEL4CR_10_0, MSEL4CR_10_1,
0, 0, 0, 0,
0, 0,
MSEL4CR_6_0, MSEL4CR_6_1,
0, 0,
MSEL4CR_4_0, MSEL4CR_4_1,
0, 0, 0, 0,
MSEL4CR_1_0, MSEL4CR_1_1,
0, 0,
}
},
{ },
};
static const struct pinmux_data_reg pinmux_data_regs[] = {
{ PINMUX_DATA_REG("PORTL095_064DR", 0xE6054008, 32) {
PORT95_DATA, PORT94_DATA, PORT93_DATA, PORT92_DATA,
PORT91_DATA, PORT90_DATA, PORT89_DATA, PORT88_DATA,
PORT87_DATA, PORT86_DATA, PORT85_DATA, PORT84_DATA,
PORT83_DATA, PORT82_DATA, PORT81_DATA, PORT80_DATA,
PORT79_DATA, PORT78_DATA, PORT77_DATA, PORT76_DATA,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
}
},
{ PINMUX_DATA_REG("PORTL127_096DR", 0xE605400C, 32) {
PORT127_DATA, PORT126_DATA, PORT125_DATA, PORT124_DATA,
PORT123_DATA, PORT122_DATA, PORT121_DATA, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
PORT99_DATA, PORT98_DATA, PORT97_DATA, PORT96_DATA,
}
},
{ PINMUX_DATA_REG("PORTL159_128DR", 0xE6054010, 32) {
PORT159_DATA, PORT158_DATA, PORT157_DATA, PORT156_DATA,
0, 0, 0, 0,
PORT151_DATA, PORT150_DATA, PORT149_DATA, PORT148_DATA,
PORT147_DATA, PORT146_DATA, PORT145_DATA, PORT144_DATA,
PORT143_DATA, PORT142_DATA, PORT141_DATA, PORT140_DATA,
PORT139_DATA, PORT138_DATA, PORT137_DATA, PORT136_DATA,
PORT135_DATA, PORT134_DATA, PORT133_DATA, PORT132_DATA,
PORT131_DATA, PORT130_DATA, PORT129_DATA, PORT128_DATA,
}
},
{ PINMUX_DATA_REG("PORTL191_160DR", 0xE6054014, 32) {
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, PORT166_DATA, PORT165_DATA, PORT164_DATA,
PORT163_DATA, PORT162_DATA, PORT161_DATA, PORT160_DATA,
}
},
{ PINMUX_DATA_REG("PORTD031_000DR", 0xE6055000, 32) {
PORT31_DATA, PORT30_DATA, PORT29_DATA, PORT28_DATA,
PORT27_DATA, PORT26_DATA, PORT25_DATA, PORT24_DATA,
PORT23_DATA, PORT22_DATA, PORT21_DATA, PORT20_DATA,
PORT19_DATA, PORT18_DATA, PORT17_DATA, PORT16_DATA,
PORT15_DATA, PORT14_DATA, PORT13_DATA, PORT12_DATA,
PORT11_DATA, PORT10_DATA, PORT9_DATA, PORT8_DATA,
PORT7_DATA, PORT6_DATA, PORT5_DATA, PORT4_DATA,
PORT3_DATA, PORT2_DATA, PORT1_DATA, PORT0_DATA,
}
},
{ PINMUX_DATA_REG("PORTD063_032DR", 0xE6055004, 32) {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, PORT45_DATA, PORT44_DATA,
PORT43_DATA, PORT42_DATA, PORT41_DATA, PORT40_DATA,
PORT39_DATA, PORT38_DATA, PORT37_DATA, PORT36_DATA,
PORT35_DATA, PORT34_DATA, PORT33_DATA, PORT32_DATA,
}
},
{ PINMUX_DATA_REG("PORTR063_032DR", 0xE6056004, 32) {
PORT63_DATA, PORT62_DATA, PORT61_DATA, PORT60_DATA,
PORT59_DATA, PORT58_DATA, PORT57_DATA, PORT56_DATA,
PORT55_DATA, PORT54_DATA, PORT53_DATA, PORT52_DATA,
PORT51_DATA, PORT50_DATA, PORT49_DATA, PORT48_DATA,
PORT47_DATA, PORT46_DATA, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
}
},
{ PINMUX_DATA_REG("PORTR095_064DR", 0xE6056008, 32) {
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
PORT75_DATA, PORT74_DATA, PORT73_DATA, PORT72_DATA,
PORT71_DATA, PORT70_DATA, PORT69_DATA, PORT68_DATA,
PORT67_DATA, PORT66_DATA, PORT65_DATA, PORT64_DATA,
}
},
{ PINMUX_DATA_REG("PORTR191_160DR", 0xE6056014, 32) {
0, PORT190_DATA, PORT189_DATA, PORT188_DATA,
PORT187_DATA, PORT186_DATA, PORT185_DATA, PORT184_DATA,
PORT183_DATA, PORT182_DATA, PORT181_DATA, PORT180_DATA,
PORT179_DATA, PORT178_DATA, PORT177_DATA, PORT176_DATA,
PORT175_DATA, PORT174_DATA, PORT173_DATA, PORT172_DATA,
PORT171_DATA, PORT170_DATA, PORT169_DATA, PORT168_DATA,
PORT167_DATA, 0, 0, 0,
0, 0, 0, 0,
}
},
{ PINMUX_DATA_REG("PORTU127_096DR", 0xE605700C, 32) {
0, 0, 0, 0,
0, 0, 0, PORT120_DATA,
PORT119_DATA, PORT118_DATA, PORT117_DATA, PORT116_DATA,
PORT115_DATA, PORT114_DATA, PORT113_DATA, PORT112_DATA,
PORT111_DATA, PORT110_DATA, PORT109_DATA, PORT108_DATA,
PORT107_DATA, PORT106_DATA, PORT105_DATA, PORT104_DATA,
PORT103_DATA, PORT102_DATA, PORT101_DATA, PORT100_DATA,
0, 0, 0, 0,
}
},
{ PINMUX_DATA_REG("PORTU159_128DR", 0xE6057010, 32) {
0, 0, 0, 0,
PORT155_DATA, PORT154_DATA, PORT153_DATA, PORT152_DATA,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
}
},
{ },
};
#define EXT_IRQ16L(n) evt2irq(0x200 + ((n) << 5))
#define EXT_IRQ16H(n) evt2irq(0x3200 + (((n) - 16) << 5))
static const struct pinmux_irq pinmux_irqs[] = {
PINMUX_IRQ(EXT_IRQ16L(0), GPIO_PORT6, GPIO_PORT162),
PINMUX_IRQ(EXT_IRQ16L(1), GPIO_PORT12),
PINMUX_IRQ(EXT_IRQ16L(2), GPIO_PORT4, GPIO_PORT5),
PINMUX_IRQ(EXT_IRQ16L(3), GPIO_PORT8, GPIO_PORT16),
PINMUX_IRQ(EXT_IRQ16L(4), GPIO_PORT17, GPIO_PORT163),
PINMUX_IRQ(EXT_IRQ16L(5), GPIO_PORT18),
PINMUX_IRQ(EXT_IRQ16L(6), GPIO_PORT39, GPIO_PORT164),
PINMUX_IRQ(EXT_IRQ16L(7), GPIO_PORT40, GPIO_PORT167),
PINMUX_IRQ(EXT_IRQ16L(8), GPIO_PORT41, GPIO_PORT168),
PINMUX_IRQ(EXT_IRQ16L(9), GPIO_PORT42, GPIO_PORT169),
PINMUX_IRQ(EXT_IRQ16L(10), GPIO_PORT65),
PINMUX_IRQ(EXT_IRQ16L(11), GPIO_PORT67),
PINMUX_IRQ(EXT_IRQ16L(12), GPIO_PORT80, GPIO_PORT137),
PINMUX_IRQ(EXT_IRQ16L(13), GPIO_PORT81, GPIO_PORT145),
PINMUX_IRQ(EXT_IRQ16L(14), GPIO_PORT82, GPIO_PORT146),
PINMUX_IRQ(EXT_IRQ16L(15), GPIO_PORT83, GPIO_PORT147),
PINMUX_IRQ(EXT_IRQ16H(16), GPIO_PORT84, GPIO_PORT170),
PINMUX_IRQ(EXT_IRQ16H(17), GPIO_PORT85),
PINMUX_IRQ(EXT_IRQ16H(18), GPIO_PORT86),
PINMUX_IRQ(EXT_IRQ16H(19), GPIO_PORT87),
PINMUX_IRQ(EXT_IRQ16H(20), GPIO_PORT92),
PINMUX_IRQ(EXT_IRQ16H(21), GPIO_PORT93),
PINMUX_IRQ(EXT_IRQ16H(22), GPIO_PORT94),
PINMUX_IRQ(EXT_IRQ16H(23), GPIO_PORT95),
PINMUX_IRQ(EXT_IRQ16H(24), GPIO_PORT112),
PINMUX_IRQ(EXT_IRQ16H(25), GPIO_PORT119),
PINMUX_IRQ(EXT_IRQ16H(26), GPIO_PORT121, GPIO_PORT172),
PINMUX_IRQ(EXT_IRQ16H(27), GPIO_PORT122, GPIO_PORT180),
PINMUX_IRQ(EXT_IRQ16H(28), GPIO_PORT123, GPIO_PORT181),
PINMUX_IRQ(EXT_IRQ16H(29), GPIO_PORT129, GPIO_PORT182),
PINMUX_IRQ(EXT_IRQ16H(30), GPIO_PORT130, GPIO_PORT183),
PINMUX_IRQ(EXT_IRQ16H(31), GPIO_PORT138, GPIO_PORT184),
};
const struct sh_pfc_soc_info sh7372_pinmux_info = {
.name = "sh7372_pfc",
.input = { PINMUX_INPUT_BEGIN, PINMUX_INPUT_END },
.input_pu = { PINMUX_INPUT_PULLUP_BEGIN, PINMUX_INPUT_PULLUP_END },
.input_pd = { PINMUX_INPUT_PULLDOWN_BEGIN, PINMUX_INPUT_PULLDOWN_END },
.output = { PINMUX_OUTPUT_BEGIN, PINMUX_OUTPUT_END },
.function = { PINMUX_FUNCTION_BEGIN, PINMUX_FUNCTION_END },
.pins = pinmux_pins,
.nr_pins = ARRAY_SIZE(pinmux_pins),
.groups = pinmux_groups,
.nr_groups = ARRAY_SIZE(pinmux_groups),
.functions = pinmux_functions,
.nr_functions = ARRAY_SIZE(pinmux_functions),
.func_gpios = pinmux_func_gpios,
.nr_func_gpios = ARRAY_SIZE(pinmux_func_gpios),
.cfg_regs = pinmux_config_regs,
.data_regs = pinmux_data_regs,
.gpio_data = pinmux_data,
.gpio_data_size = ARRAY_SIZE(pinmux_data),
.gpio_irq = pinmux_irqs,
.gpio_irq_size = ARRAY_SIZE(pinmux_irqs),
};
| gpl-2.0 |
childofthehorn/android_kernel_oneplus_msm8994 | fs/dlm/ast.c | 2361 | 8243 | /******************************************************************************
*******************************************************************************
**
** Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
** Copyright (C) 2004-2010 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 "dlm_internal.h"
#include "lock.h"
#include "user.h"
static uint64_t dlm_cb_seq;
static DEFINE_SPINLOCK(dlm_cb_seq_spin);
static void dlm_dump_lkb_callbacks(struct dlm_lkb *lkb)
{
int i;
log_print("last_bast %x %llu flags %x mode %d sb %d %x",
lkb->lkb_id,
(unsigned long long)lkb->lkb_last_bast.seq,
lkb->lkb_last_bast.flags,
lkb->lkb_last_bast.mode,
lkb->lkb_last_bast.sb_status,
lkb->lkb_last_bast.sb_flags);
log_print("last_cast %x %llu flags %x mode %d sb %d %x",
lkb->lkb_id,
(unsigned long long)lkb->lkb_last_cast.seq,
lkb->lkb_last_cast.flags,
lkb->lkb_last_cast.mode,
lkb->lkb_last_cast.sb_status,
lkb->lkb_last_cast.sb_flags);
for (i = 0; i < DLM_CALLBACKS_SIZE; i++) {
log_print("cb %x %llu flags %x mode %d sb %d %x",
lkb->lkb_id,
(unsigned long long)lkb->lkb_callbacks[i].seq,
lkb->lkb_callbacks[i].flags,
lkb->lkb_callbacks[i].mode,
lkb->lkb_callbacks[i].sb_status,
lkb->lkb_callbacks[i].sb_flags);
}
}
int dlm_add_lkb_callback(struct dlm_lkb *lkb, uint32_t flags, int mode,
int status, uint32_t sbflags, uint64_t seq)
{
struct dlm_ls *ls = lkb->lkb_resource->res_ls;
uint64_t prev_seq;
int prev_mode;
int i, rv;
for (i = 0; i < DLM_CALLBACKS_SIZE; i++) {
if (lkb->lkb_callbacks[i].seq)
continue;
/*
* Suppress some redundant basts here, do more on removal.
* Don't even add a bast if the callback just before it
* is a bast for the same mode or a more restrictive mode.
* (the addional > PR check is needed for PR/CW inversion)
*/
if ((i > 0) && (flags & DLM_CB_BAST) &&
(lkb->lkb_callbacks[i-1].flags & DLM_CB_BAST)) {
prev_seq = lkb->lkb_callbacks[i-1].seq;
prev_mode = lkb->lkb_callbacks[i-1].mode;
if ((prev_mode == mode) ||
(prev_mode > mode && prev_mode > DLM_LOCK_PR)) {
log_debug(ls, "skip %x add bast %llu mode %d "
"for bast %llu mode %d",
lkb->lkb_id,
(unsigned long long)seq,
mode,
(unsigned long long)prev_seq,
prev_mode);
rv = 0;
goto out;
}
}
lkb->lkb_callbacks[i].seq = seq;
lkb->lkb_callbacks[i].flags = flags;
lkb->lkb_callbacks[i].mode = mode;
lkb->lkb_callbacks[i].sb_status = status;
lkb->lkb_callbacks[i].sb_flags = (sbflags & 0x000000FF);
rv = 0;
break;
}
if (i == DLM_CALLBACKS_SIZE) {
log_error(ls, "no callbacks %x %llu flags %x mode %d sb %d %x",
lkb->lkb_id, (unsigned long long)seq,
flags, mode, status, sbflags);
dlm_dump_lkb_callbacks(lkb);
rv = -1;
goto out;
}
out:
return rv;
}
int dlm_rem_lkb_callback(struct dlm_ls *ls, struct dlm_lkb *lkb,
struct dlm_callback *cb, int *resid)
{
int i, rv;
*resid = 0;
if (!lkb->lkb_callbacks[0].seq) {
rv = -ENOENT;
goto out;
}
/* oldest undelivered cb is callbacks[0] */
memcpy(cb, &lkb->lkb_callbacks[0], sizeof(struct dlm_callback));
memset(&lkb->lkb_callbacks[0], 0, sizeof(struct dlm_callback));
/* shift others down */
for (i = 1; i < DLM_CALLBACKS_SIZE; i++) {
if (!lkb->lkb_callbacks[i].seq)
break;
memcpy(&lkb->lkb_callbacks[i-1], &lkb->lkb_callbacks[i],
sizeof(struct dlm_callback));
memset(&lkb->lkb_callbacks[i], 0, sizeof(struct dlm_callback));
(*resid)++;
}
/* if cb is a bast, it should be skipped if the blocking mode is
compatible with the last granted mode */
if ((cb->flags & DLM_CB_BAST) && lkb->lkb_last_cast.seq) {
if (dlm_modes_compat(cb->mode, lkb->lkb_last_cast.mode)) {
cb->flags |= DLM_CB_SKIP;
log_debug(ls, "skip %x bast %llu mode %d "
"for cast %llu mode %d",
lkb->lkb_id,
(unsigned long long)cb->seq,
cb->mode,
(unsigned long long)lkb->lkb_last_cast.seq,
lkb->lkb_last_cast.mode);
rv = 0;
goto out;
}
}
if (cb->flags & DLM_CB_CAST) {
memcpy(&lkb->lkb_last_cast, cb, sizeof(struct dlm_callback));
lkb->lkb_last_cast_time = ktime_get();
}
if (cb->flags & DLM_CB_BAST) {
memcpy(&lkb->lkb_last_bast, cb, sizeof(struct dlm_callback));
lkb->lkb_last_bast_time = ktime_get();
}
rv = 0;
out:
return rv;
}
void dlm_add_cb(struct dlm_lkb *lkb, uint32_t flags, int mode, int status,
uint32_t sbflags)
{
struct dlm_ls *ls = lkb->lkb_resource->res_ls;
uint64_t new_seq, prev_seq;
int rv;
spin_lock(&dlm_cb_seq_spin);
new_seq = ++dlm_cb_seq;
spin_unlock(&dlm_cb_seq_spin);
if (lkb->lkb_flags & DLM_IFL_USER) {
dlm_user_add_ast(lkb, flags, mode, status, sbflags, new_seq);
return;
}
mutex_lock(&lkb->lkb_cb_mutex);
prev_seq = lkb->lkb_callbacks[0].seq;
rv = dlm_add_lkb_callback(lkb, flags, mode, status, sbflags, new_seq);
if (rv < 0)
goto out;
if (!prev_seq) {
kref_get(&lkb->lkb_ref);
if (test_bit(LSFL_CB_DELAY, &ls->ls_flags)) {
mutex_lock(&ls->ls_cb_mutex);
list_add(&lkb->lkb_cb_list, &ls->ls_cb_delay);
mutex_unlock(&ls->ls_cb_mutex);
} else {
queue_work(ls->ls_callback_wq, &lkb->lkb_cb_work);
}
}
out:
mutex_unlock(&lkb->lkb_cb_mutex);
}
void dlm_callback_work(struct work_struct *work)
{
struct dlm_lkb *lkb = container_of(work, struct dlm_lkb, lkb_cb_work);
struct dlm_ls *ls = lkb->lkb_resource->res_ls;
void (*castfn) (void *astparam);
void (*bastfn) (void *astparam, int mode);
struct dlm_callback callbacks[DLM_CALLBACKS_SIZE];
int i, rv, resid;
memset(&callbacks, 0, sizeof(callbacks));
mutex_lock(&lkb->lkb_cb_mutex);
if (!lkb->lkb_callbacks[0].seq) {
/* no callback work exists, shouldn't happen */
log_error(ls, "dlm_callback_work %x no work", lkb->lkb_id);
dlm_print_lkb(lkb);
dlm_dump_lkb_callbacks(lkb);
}
for (i = 0; i < DLM_CALLBACKS_SIZE; i++) {
rv = dlm_rem_lkb_callback(ls, lkb, &callbacks[i], &resid);
if (rv < 0)
break;
}
if (resid) {
/* cbs remain, loop should have removed all, shouldn't happen */
log_error(ls, "dlm_callback_work %x resid %d", lkb->lkb_id,
resid);
dlm_print_lkb(lkb);
dlm_dump_lkb_callbacks(lkb);
}
mutex_unlock(&lkb->lkb_cb_mutex);
castfn = lkb->lkb_astfn;
bastfn = lkb->lkb_bastfn;
for (i = 0; i < DLM_CALLBACKS_SIZE; i++) {
if (!callbacks[i].seq)
break;
if (callbacks[i].flags & DLM_CB_SKIP) {
continue;
} else if (callbacks[i].flags & DLM_CB_BAST) {
bastfn(lkb->lkb_astparam, callbacks[i].mode);
} else if (callbacks[i].flags & DLM_CB_CAST) {
lkb->lkb_lksb->sb_status = callbacks[i].sb_status;
lkb->lkb_lksb->sb_flags = callbacks[i].sb_flags;
castfn(lkb->lkb_astparam);
}
}
/* undo kref_get from dlm_add_callback, may cause lkb to be freed */
dlm_put_lkb(lkb);
}
int dlm_callback_start(struct dlm_ls *ls)
{
ls->ls_callback_wq = alloc_workqueue("dlm_callback",
WQ_UNBOUND |
WQ_MEM_RECLAIM |
WQ_NON_REENTRANT,
0);
if (!ls->ls_callback_wq) {
log_print("can't start dlm_callback workqueue");
return -ENOMEM;
}
return 0;
}
void dlm_callback_stop(struct dlm_ls *ls)
{
if (ls->ls_callback_wq)
destroy_workqueue(ls->ls_callback_wq);
}
void dlm_callback_suspend(struct dlm_ls *ls)
{
set_bit(LSFL_CB_DELAY, &ls->ls_flags);
if (ls->ls_callback_wq)
flush_workqueue(ls->ls_callback_wq);
}
void dlm_callback_resume(struct dlm_ls *ls)
{
struct dlm_lkb *lkb, *safe;
int count = 0;
clear_bit(LSFL_CB_DELAY, &ls->ls_flags);
if (!ls->ls_callback_wq)
return;
mutex_lock(&ls->ls_cb_mutex);
list_for_each_entry_safe(lkb, safe, &ls->ls_cb_delay, lkb_cb_list) {
list_del_init(&lkb->lkb_cb_list);
queue_work(ls->ls_callback_wq, &lkb->lkb_cb_work);
count++;
}
mutex_unlock(&ls->ls_cb_mutex);
if (count)
log_debug(ls, "dlm_callback_resume %d", count);
}
| gpl-2.0 |
keecker/kernel_msm-3.10 | sound/soc/codecs/wm8983.c | 2617 | 38271 | /*
* wm8983.c -- WM8983 ALSA SoC Audio driver
*
* Copyright 2011 Wolfson Microelectronics plc
*
* Author: Dimitris Papastamos <dp@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 version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/pm.h>
#include <linux/i2c.h>
#include <linux/regmap.h>
#include <linux/spi/spi.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/initval.h>
#include <sound/tlv.h>
#include "wm8983.h"
static const struct reg_default wm8983_defaults[] = {
{ 0x01, 0x0000 }, /* R1 - Power management 1 */
{ 0x02, 0x0000 }, /* R2 - Power management 2 */
{ 0x03, 0x0000 }, /* R3 - Power management 3 */
{ 0x04, 0x0050 }, /* R4 - Audio Interface */
{ 0x05, 0x0000 }, /* R5 - Companding control */
{ 0x06, 0x0140 }, /* R6 - Clock Gen control */
{ 0x07, 0x0000 }, /* R7 - Additional control */
{ 0x08, 0x0000 }, /* R8 - GPIO Control */
{ 0x09, 0x0000 }, /* R9 - Jack Detect Control 1 */
{ 0x0A, 0x0000 }, /* R10 - DAC Control */
{ 0x0B, 0x00FF }, /* R11 - Left DAC digital Vol */
{ 0x0C, 0x00FF }, /* R12 - Right DAC digital vol */
{ 0x0D, 0x0000 }, /* R13 - Jack Detect Control 2 */
{ 0x0E, 0x0100 }, /* R14 - ADC Control */
{ 0x0F, 0x00FF }, /* R15 - Left ADC Digital Vol */
{ 0x10, 0x00FF }, /* R16 - Right ADC Digital Vol */
{ 0x12, 0x012C }, /* R18 - EQ1 - low shelf */
{ 0x13, 0x002C }, /* R19 - EQ2 - peak 1 */
{ 0x14, 0x002C }, /* R20 - EQ3 - peak 2 */
{ 0x15, 0x002C }, /* R21 - EQ4 - peak 3 */
{ 0x16, 0x002C }, /* R22 - EQ5 - high shelf */
{ 0x18, 0x0032 }, /* R24 - DAC Limiter 1 */
{ 0x19, 0x0000 }, /* R25 - DAC Limiter 2 */
{ 0x1B, 0x0000 }, /* R27 - Notch Filter 1 */
{ 0x1C, 0x0000 }, /* R28 - Notch Filter 2 */
{ 0x1D, 0x0000 }, /* R29 - Notch Filter 3 */
{ 0x1E, 0x0000 }, /* R30 - Notch Filter 4 */
{ 0x20, 0x0038 }, /* R32 - ALC control 1 */
{ 0x21, 0x000B }, /* R33 - ALC control 2 */
{ 0x22, 0x0032 }, /* R34 - ALC control 3 */
{ 0x23, 0x0000 }, /* R35 - Noise Gate */
{ 0x24, 0x0008 }, /* R36 - PLL N */
{ 0x25, 0x000C }, /* R37 - PLL K 1 */
{ 0x26, 0x0093 }, /* R38 - PLL K 2 */
{ 0x27, 0x00E9 }, /* R39 - PLL K 3 */
{ 0x29, 0x0000 }, /* R41 - 3D control */
{ 0x2A, 0x0000 }, /* R42 - OUT4 to ADC */
{ 0x2B, 0x0000 }, /* R43 - Beep control */
{ 0x2C, 0x0033 }, /* R44 - Input ctrl */
{ 0x2D, 0x0010 }, /* R45 - Left INP PGA gain ctrl */
{ 0x2E, 0x0010 }, /* R46 - Right INP PGA gain ctrl */
{ 0x2F, 0x0100 }, /* R47 - Left ADC BOOST ctrl */
{ 0x30, 0x0100 }, /* R48 - Right ADC BOOST ctrl */
{ 0x31, 0x0002 }, /* R49 - Output ctrl */
{ 0x32, 0x0001 }, /* R50 - Left mixer ctrl */
{ 0x33, 0x0001 }, /* R51 - Right mixer ctrl */
{ 0x34, 0x0039 }, /* R52 - LOUT1 (HP) volume ctrl */
{ 0x35, 0x0039 }, /* R53 - ROUT1 (HP) volume ctrl */
{ 0x36, 0x0039 }, /* R54 - LOUT2 (SPK) volume ctrl */
{ 0x37, 0x0039 }, /* R55 - ROUT2 (SPK) volume ctrl */
{ 0x38, 0x0001 }, /* R56 - OUT3 mixer ctrl */
{ 0x39, 0x0001 }, /* R57 - OUT4 (MONO) mix ctrl */
{ 0x3D, 0x0000 }, /* R61 - BIAS CTRL */
};
static const struct wm8983_reg_access {
u16 read; /* Mask of readable bits */
u16 write; /* Mask of writable bits */
} wm8983_access_masks[WM8983_MAX_REGISTER + 1] = {
[0x00] = { 0x0000, 0x01FF }, /* R0 - Software Reset */
[0x01] = { 0x0000, 0x01FF }, /* R1 - Power management 1 */
[0x02] = { 0x0000, 0x01FF }, /* R2 - Power management 2 */
[0x03] = { 0x0000, 0x01EF }, /* R3 - Power management 3 */
[0x04] = { 0x0000, 0x01FF }, /* R4 - Audio Interface */
[0x05] = { 0x0000, 0x003F }, /* R5 - Companding control */
[0x06] = { 0x0000, 0x01FD }, /* R6 - Clock Gen control */
[0x07] = { 0x0000, 0x000F }, /* R7 - Additional control */
[0x08] = { 0x0000, 0x003F }, /* R8 - GPIO Control */
[0x09] = { 0x0000, 0x0070 }, /* R9 - Jack Detect Control 1 */
[0x0A] = { 0x0000, 0x004F }, /* R10 - DAC Control */
[0x0B] = { 0x0000, 0x01FF }, /* R11 - Left DAC digital Vol */
[0x0C] = { 0x0000, 0x01FF }, /* R12 - Right DAC digital vol */
[0x0D] = { 0x0000, 0x00FF }, /* R13 - Jack Detect Control 2 */
[0x0E] = { 0x0000, 0x01FB }, /* R14 - ADC Control */
[0x0F] = { 0x0000, 0x01FF }, /* R15 - Left ADC Digital Vol */
[0x10] = { 0x0000, 0x01FF }, /* R16 - Right ADC Digital Vol */
[0x12] = { 0x0000, 0x017F }, /* R18 - EQ1 - low shelf */
[0x13] = { 0x0000, 0x017F }, /* R19 - EQ2 - peak 1 */
[0x14] = { 0x0000, 0x017F }, /* R20 - EQ3 - peak 2 */
[0x15] = { 0x0000, 0x017F }, /* R21 - EQ4 - peak 3 */
[0x16] = { 0x0000, 0x007F }, /* R22 - EQ5 - high shelf */
[0x18] = { 0x0000, 0x01FF }, /* R24 - DAC Limiter 1 */
[0x19] = { 0x0000, 0x007F }, /* R25 - DAC Limiter 2 */
[0x1B] = { 0x0000, 0x01FF }, /* R27 - Notch Filter 1 */
[0x1C] = { 0x0000, 0x017F }, /* R28 - Notch Filter 2 */
[0x1D] = { 0x0000, 0x017F }, /* R29 - Notch Filter 3 */
[0x1E] = { 0x0000, 0x017F }, /* R30 - Notch Filter 4 */
[0x20] = { 0x0000, 0x01BF }, /* R32 - ALC control 1 */
[0x21] = { 0x0000, 0x00FF }, /* R33 - ALC control 2 */
[0x22] = { 0x0000, 0x01FF }, /* R34 - ALC control 3 */
[0x23] = { 0x0000, 0x000F }, /* R35 - Noise Gate */
[0x24] = { 0x0000, 0x001F }, /* R36 - PLL N */
[0x25] = { 0x0000, 0x003F }, /* R37 - PLL K 1 */
[0x26] = { 0x0000, 0x01FF }, /* R38 - PLL K 2 */
[0x27] = { 0x0000, 0x01FF }, /* R39 - PLL K 3 */
[0x29] = { 0x0000, 0x000F }, /* R41 - 3D control */
[0x2A] = { 0x0000, 0x01E7 }, /* R42 - OUT4 to ADC */
[0x2B] = { 0x0000, 0x01BF }, /* R43 - Beep control */
[0x2C] = { 0x0000, 0x0177 }, /* R44 - Input ctrl */
[0x2D] = { 0x0000, 0x01FF }, /* R45 - Left INP PGA gain ctrl */
[0x2E] = { 0x0000, 0x01FF }, /* R46 - Right INP PGA gain ctrl */
[0x2F] = { 0x0000, 0x0177 }, /* R47 - Left ADC BOOST ctrl */
[0x30] = { 0x0000, 0x0177 }, /* R48 - Right ADC BOOST ctrl */
[0x31] = { 0x0000, 0x007F }, /* R49 - Output ctrl */
[0x32] = { 0x0000, 0x01FF }, /* R50 - Left mixer ctrl */
[0x33] = { 0x0000, 0x01FF }, /* R51 - Right mixer ctrl */
[0x34] = { 0x0000, 0x01FF }, /* R52 - LOUT1 (HP) volume ctrl */
[0x35] = { 0x0000, 0x01FF }, /* R53 - ROUT1 (HP) volume ctrl */
[0x36] = { 0x0000, 0x01FF }, /* R54 - LOUT2 (SPK) volume ctrl */
[0x37] = { 0x0000, 0x01FF }, /* R55 - ROUT2 (SPK) volume ctrl */
[0x38] = { 0x0000, 0x004F }, /* R56 - OUT3 mixer ctrl */
[0x39] = { 0x0000, 0x00FF }, /* R57 - OUT4 (MONO) mix ctrl */
[0x3D] = { 0x0000, 0x0100 } /* R61 - BIAS CTRL */
};
/* vol/gain update regs */
static const int vol_update_regs[] = {
WM8983_LEFT_DAC_DIGITAL_VOL,
WM8983_RIGHT_DAC_DIGITAL_VOL,
WM8983_LEFT_ADC_DIGITAL_VOL,
WM8983_RIGHT_ADC_DIGITAL_VOL,
WM8983_LOUT1_HP_VOLUME_CTRL,
WM8983_ROUT1_HP_VOLUME_CTRL,
WM8983_LOUT2_SPK_VOLUME_CTRL,
WM8983_ROUT2_SPK_VOLUME_CTRL,
WM8983_LEFT_INP_PGA_GAIN_CTRL,
WM8983_RIGHT_INP_PGA_GAIN_CTRL
};
struct wm8983_priv {
struct regmap *regmap;
u32 sysclk;
u32 bclk;
};
static const struct {
int div;
int ratio;
} fs_ratios[] = {
{ 10, 128 },
{ 15, 192 },
{ 20, 256 },
{ 30, 384 },
{ 40, 512 },
{ 60, 768 },
{ 80, 1024 },
{ 120, 1536 }
};
static const int srates[] = { 48000, 32000, 24000, 16000, 12000, 8000 };
static const int bclk_divs[] = {
1, 2, 4, 8, 16, 32
};
static int eqmode_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol);
static int eqmode_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol);
static const DECLARE_TLV_DB_SCALE(dac_tlv, -12700, 50, 1);
static const DECLARE_TLV_DB_SCALE(adc_tlv, -12700, 50, 1);
static const DECLARE_TLV_DB_SCALE(out_tlv, -5700, 100, 0);
static const DECLARE_TLV_DB_SCALE(lim_thresh_tlv, -600, 100, 0);
static const DECLARE_TLV_DB_SCALE(lim_boost_tlv, 0, 100, 0);
static const DECLARE_TLV_DB_SCALE(alc_min_tlv, -1200, 600, 0);
static const DECLARE_TLV_DB_SCALE(alc_max_tlv, -675, 600, 0);
static const DECLARE_TLV_DB_SCALE(alc_tar_tlv, -2250, 150, 0);
static const DECLARE_TLV_DB_SCALE(pga_vol_tlv, -1200, 75, 0);
static const DECLARE_TLV_DB_SCALE(boost_tlv, -1200, 300, 1);
static const DECLARE_TLV_DB_SCALE(eq_tlv, -1200, 100, 0);
static const DECLARE_TLV_DB_SCALE(aux_tlv, -1500, 300, 0);
static const DECLARE_TLV_DB_SCALE(bypass_tlv, -1500, 300, 0);
static const DECLARE_TLV_DB_SCALE(pga_boost_tlv, 0, 2000, 0);
static const char *alc_sel_text[] = { "Off", "Right", "Left", "Stereo" };
static const SOC_ENUM_SINGLE_DECL(alc_sel, WM8983_ALC_CONTROL_1, 7,
alc_sel_text);
static const char *alc_mode_text[] = { "ALC", "Limiter" };
static const SOC_ENUM_SINGLE_DECL(alc_mode, WM8983_ALC_CONTROL_3, 8,
alc_mode_text);
static const char *filter_mode_text[] = { "Audio", "Application" };
static const SOC_ENUM_SINGLE_DECL(filter_mode, WM8983_ADC_CONTROL, 7,
filter_mode_text);
static const char *eq_bw_text[] = { "Narrow", "Wide" };
static const char *eqmode_text[] = { "Capture", "Playback" };
static const SOC_ENUM_SINGLE_EXT_DECL(eqmode, eqmode_text);
static const char *eq1_cutoff_text[] = {
"80Hz", "105Hz", "135Hz", "175Hz"
};
static const SOC_ENUM_SINGLE_DECL(eq1_cutoff, WM8983_EQ1_LOW_SHELF, 5,
eq1_cutoff_text);
static const char *eq2_cutoff_text[] = {
"230Hz", "300Hz", "385Hz", "500Hz"
};
static const SOC_ENUM_SINGLE_DECL(eq2_bw, WM8983_EQ2_PEAK_1, 8, eq_bw_text);
static const SOC_ENUM_SINGLE_DECL(eq2_cutoff, WM8983_EQ2_PEAK_1, 5,
eq2_cutoff_text);
static const char *eq3_cutoff_text[] = {
"650Hz", "850Hz", "1.1kHz", "1.4kHz"
};
static const SOC_ENUM_SINGLE_DECL(eq3_bw, WM8983_EQ3_PEAK_2, 8, eq_bw_text);
static const SOC_ENUM_SINGLE_DECL(eq3_cutoff, WM8983_EQ3_PEAK_2, 5,
eq3_cutoff_text);
static const char *eq4_cutoff_text[] = {
"1.8kHz", "2.4kHz", "3.2kHz", "4.1kHz"
};
static const SOC_ENUM_SINGLE_DECL(eq4_bw, WM8983_EQ4_PEAK_3, 8, eq_bw_text);
static const SOC_ENUM_SINGLE_DECL(eq4_cutoff, WM8983_EQ4_PEAK_3, 5,
eq4_cutoff_text);
static const char *eq5_cutoff_text[] = {
"5.3kHz", "6.9kHz", "9kHz", "11.7kHz"
};
static const SOC_ENUM_SINGLE_DECL(eq5_cutoff, WM8983_EQ5_HIGH_SHELF, 5,
eq5_cutoff_text);
static const char *depth_3d_text[] = {
"Off",
"6.67%",
"13.3%",
"20%",
"26.7%",
"33.3%",
"40%",
"46.6%",
"53.3%",
"60%",
"66.7%",
"73.3%",
"80%",
"86.7%",
"93.3%",
"100%"
};
static const SOC_ENUM_SINGLE_DECL(depth_3d, WM8983_3D_CONTROL, 0,
depth_3d_text);
static const struct snd_kcontrol_new wm8983_snd_controls[] = {
SOC_SINGLE("Digital Loopback Switch", WM8983_COMPANDING_CONTROL,
0, 1, 0),
SOC_ENUM("ALC Capture Function", alc_sel),
SOC_SINGLE_TLV("ALC Capture Max Volume", WM8983_ALC_CONTROL_1,
3, 7, 0, alc_max_tlv),
SOC_SINGLE_TLV("ALC Capture Min Volume", WM8983_ALC_CONTROL_1,
0, 7, 0, alc_min_tlv),
SOC_SINGLE_TLV("ALC Capture Target Volume", WM8983_ALC_CONTROL_2,
0, 15, 0, alc_tar_tlv),
SOC_SINGLE("ALC Capture Attack", WM8983_ALC_CONTROL_3, 0, 10, 0),
SOC_SINGLE("ALC Capture Hold", WM8983_ALC_CONTROL_2, 4, 10, 0),
SOC_SINGLE("ALC Capture Decay", WM8983_ALC_CONTROL_3, 4, 10, 0),
SOC_ENUM("ALC Mode", alc_mode),
SOC_SINGLE("ALC Capture NG Switch", WM8983_NOISE_GATE,
3, 1, 0),
SOC_SINGLE("ALC Capture NG Threshold", WM8983_NOISE_GATE,
0, 7, 1),
SOC_DOUBLE_R_TLV("Capture Volume", WM8983_LEFT_ADC_DIGITAL_VOL,
WM8983_RIGHT_ADC_DIGITAL_VOL, 0, 255, 0, adc_tlv),
SOC_DOUBLE_R("Capture PGA ZC Switch", WM8983_LEFT_INP_PGA_GAIN_CTRL,
WM8983_RIGHT_INP_PGA_GAIN_CTRL, 7, 1, 0),
SOC_DOUBLE_R_TLV("Capture PGA Volume", WM8983_LEFT_INP_PGA_GAIN_CTRL,
WM8983_RIGHT_INP_PGA_GAIN_CTRL, 0, 63, 0, pga_vol_tlv),
SOC_DOUBLE_R_TLV("Capture PGA Boost Volume",
WM8983_LEFT_ADC_BOOST_CTRL, WM8983_RIGHT_ADC_BOOST_CTRL,
8, 1, 0, pga_boost_tlv),
SOC_DOUBLE("ADC Inversion Switch", WM8983_ADC_CONTROL, 0, 1, 1, 0),
SOC_SINGLE("ADC 128x Oversampling Switch", WM8983_ADC_CONTROL, 8, 1, 0),
SOC_DOUBLE_R_TLV("Playback Volume", WM8983_LEFT_DAC_DIGITAL_VOL,
WM8983_RIGHT_DAC_DIGITAL_VOL, 0, 255, 0, dac_tlv),
SOC_SINGLE("DAC Playback Limiter Switch", WM8983_DAC_LIMITER_1, 8, 1, 0),
SOC_SINGLE("DAC Playback Limiter Decay", WM8983_DAC_LIMITER_1, 4, 10, 0),
SOC_SINGLE("DAC Playback Limiter Attack", WM8983_DAC_LIMITER_1, 0, 11, 0),
SOC_SINGLE_TLV("DAC Playback Limiter Threshold", WM8983_DAC_LIMITER_2,
4, 7, 1, lim_thresh_tlv),
SOC_SINGLE_TLV("DAC Playback Limiter Boost Volume", WM8983_DAC_LIMITER_2,
0, 12, 0, lim_boost_tlv),
SOC_DOUBLE("DAC Inversion Switch", WM8983_DAC_CONTROL, 0, 1, 1, 0),
SOC_SINGLE("DAC Auto Mute Switch", WM8983_DAC_CONTROL, 2, 1, 0),
SOC_SINGLE("DAC 128x Oversampling Switch", WM8983_DAC_CONTROL, 3, 1, 0),
SOC_DOUBLE_R_TLV("Headphone Playback Volume", WM8983_LOUT1_HP_VOLUME_CTRL,
WM8983_ROUT1_HP_VOLUME_CTRL, 0, 63, 0, out_tlv),
SOC_DOUBLE_R("Headphone Playback ZC Switch", WM8983_LOUT1_HP_VOLUME_CTRL,
WM8983_ROUT1_HP_VOLUME_CTRL, 7, 1, 0),
SOC_DOUBLE_R("Headphone Switch", WM8983_LOUT1_HP_VOLUME_CTRL,
WM8983_ROUT1_HP_VOLUME_CTRL, 6, 1, 1),
SOC_DOUBLE_R_TLV("Speaker Playback Volume", WM8983_LOUT2_SPK_VOLUME_CTRL,
WM8983_ROUT2_SPK_VOLUME_CTRL, 0, 63, 0, out_tlv),
SOC_DOUBLE_R("Speaker Playback ZC Switch", WM8983_LOUT2_SPK_VOLUME_CTRL,
WM8983_ROUT2_SPK_VOLUME_CTRL, 7, 1, 0),
SOC_DOUBLE_R("Speaker Switch", WM8983_LOUT2_SPK_VOLUME_CTRL,
WM8983_ROUT2_SPK_VOLUME_CTRL, 6, 1, 1),
SOC_SINGLE("OUT3 Switch", WM8983_OUT3_MIXER_CTRL,
6, 1, 1),
SOC_SINGLE("OUT4 Switch", WM8983_OUT4_MONO_MIX_CTRL,
6, 1, 1),
SOC_SINGLE("High Pass Filter Switch", WM8983_ADC_CONTROL, 8, 1, 0),
SOC_ENUM("High Pass Filter Mode", filter_mode),
SOC_SINGLE("High Pass Filter Cutoff", WM8983_ADC_CONTROL, 4, 7, 0),
SOC_DOUBLE_R_TLV("Aux Bypass Volume",
WM8983_LEFT_MIXER_CTRL, WM8983_RIGHT_MIXER_CTRL, 6, 7, 0,
aux_tlv),
SOC_DOUBLE_R_TLV("Input PGA Bypass Volume",
WM8983_LEFT_MIXER_CTRL, WM8983_RIGHT_MIXER_CTRL, 2, 7, 0,
bypass_tlv),
SOC_ENUM_EXT("Equalizer Function", eqmode, eqmode_get, eqmode_put),
SOC_ENUM("EQ1 Cutoff", eq1_cutoff),
SOC_SINGLE_TLV("EQ1 Volume", WM8983_EQ1_LOW_SHELF, 0, 24, 1, eq_tlv),
SOC_ENUM("EQ2 Bandwidth", eq2_bw),
SOC_ENUM("EQ2 Cutoff", eq2_cutoff),
SOC_SINGLE_TLV("EQ2 Volume", WM8983_EQ2_PEAK_1, 0, 24, 1, eq_tlv),
SOC_ENUM("EQ3 Bandwidth", eq3_bw),
SOC_ENUM("EQ3 Cutoff", eq3_cutoff),
SOC_SINGLE_TLV("EQ3 Volume", WM8983_EQ3_PEAK_2, 0, 24, 1, eq_tlv),
SOC_ENUM("EQ4 Bandwidth", eq4_bw),
SOC_ENUM("EQ4 Cutoff", eq4_cutoff),
SOC_SINGLE_TLV("EQ4 Volume", WM8983_EQ4_PEAK_3, 0, 24, 1, eq_tlv),
SOC_ENUM("EQ5 Cutoff", eq5_cutoff),
SOC_SINGLE_TLV("EQ5 Volume", WM8983_EQ5_HIGH_SHELF, 0, 24, 1, eq_tlv),
SOC_ENUM("3D Depth", depth_3d),
};
static const struct snd_kcontrol_new left_out_mixer[] = {
SOC_DAPM_SINGLE("Line Switch", WM8983_LEFT_MIXER_CTRL, 1, 1, 0),
SOC_DAPM_SINGLE("Aux Switch", WM8983_LEFT_MIXER_CTRL, 5, 1, 0),
SOC_DAPM_SINGLE("PCM Switch", WM8983_LEFT_MIXER_CTRL, 0, 1, 0),
};
static const struct snd_kcontrol_new right_out_mixer[] = {
SOC_DAPM_SINGLE("Line Switch", WM8983_RIGHT_MIXER_CTRL, 1, 1, 0),
SOC_DAPM_SINGLE("Aux Switch", WM8983_RIGHT_MIXER_CTRL, 5, 1, 0),
SOC_DAPM_SINGLE("PCM Switch", WM8983_RIGHT_MIXER_CTRL, 0, 1, 0),
};
static const struct snd_kcontrol_new left_input_mixer[] = {
SOC_DAPM_SINGLE("L2 Switch", WM8983_INPUT_CTRL, 2, 1, 0),
SOC_DAPM_SINGLE("MicN Switch", WM8983_INPUT_CTRL, 1, 1, 0),
SOC_DAPM_SINGLE("MicP Switch", WM8983_INPUT_CTRL, 0, 1, 0),
};
static const struct snd_kcontrol_new right_input_mixer[] = {
SOC_DAPM_SINGLE("R2 Switch", WM8983_INPUT_CTRL, 6, 1, 0),
SOC_DAPM_SINGLE("MicN Switch", WM8983_INPUT_CTRL, 5, 1, 0),
SOC_DAPM_SINGLE("MicP Switch", WM8983_INPUT_CTRL, 4, 1, 0),
};
static const struct snd_kcontrol_new left_boost_mixer[] = {
SOC_DAPM_SINGLE_TLV("L2 Volume", WM8983_LEFT_ADC_BOOST_CTRL,
4, 7, 0, boost_tlv),
SOC_DAPM_SINGLE_TLV("AUXL Volume", WM8983_LEFT_ADC_BOOST_CTRL,
0, 7, 0, boost_tlv)
};
static const struct snd_kcontrol_new out3_mixer[] = {
SOC_DAPM_SINGLE("LMIX2OUT3 Switch", WM8983_OUT3_MIXER_CTRL,
1, 1, 0),
SOC_DAPM_SINGLE("LDAC2OUT3 Switch", WM8983_OUT3_MIXER_CTRL,
0, 1, 0),
};
static const struct snd_kcontrol_new out4_mixer[] = {
SOC_DAPM_SINGLE("LMIX2OUT4 Switch", WM8983_OUT4_MONO_MIX_CTRL,
4, 1, 0),
SOC_DAPM_SINGLE("RMIX2OUT4 Switch", WM8983_OUT4_MONO_MIX_CTRL,
1, 1, 0),
SOC_DAPM_SINGLE("LDAC2OUT4 Switch", WM8983_OUT4_MONO_MIX_CTRL,
3, 1, 0),
SOC_DAPM_SINGLE("RDAC2OUT4 Switch", WM8983_OUT4_MONO_MIX_CTRL,
0, 1, 0),
};
static const struct snd_kcontrol_new right_boost_mixer[] = {
SOC_DAPM_SINGLE_TLV("R2 Volume", WM8983_RIGHT_ADC_BOOST_CTRL,
4, 7, 0, boost_tlv),
SOC_DAPM_SINGLE_TLV("AUXR Volume", WM8983_RIGHT_ADC_BOOST_CTRL,
0, 7, 0, boost_tlv)
};
static const struct snd_soc_dapm_widget wm8983_dapm_widgets[] = {
SND_SOC_DAPM_DAC("Left DAC", "Left Playback", WM8983_POWER_MANAGEMENT_3,
0, 0),
SND_SOC_DAPM_DAC("Right DAC", "Right Playback", WM8983_POWER_MANAGEMENT_3,
1, 0),
SND_SOC_DAPM_ADC("Left ADC", "Left Capture", WM8983_POWER_MANAGEMENT_2,
0, 0),
SND_SOC_DAPM_ADC("Right ADC", "Right Capture", WM8983_POWER_MANAGEMENT_2,
1, 0),
SND_SOC_DAPM_MIXER("Left Output Mixer", WM8983_POWER_MANAGEMENT_3,
2, 0, left_out_mixer, ARRAY_SIZE(left_out_mixer)),
SND_SOC_DAPM_MIXER("Right Output Mixer", WM8983_POWER_MANAGEMENT_3,
3, 0, right_out_mixer, ARRAY_SIZE(right_out_mixer)),
SND_SOC_DAPM_MIXER("Left Input Mixer", WM8983_POWER_MANAGEMENT_2,
2, 0, left_input_mixer, ARRAY_SIZE(left_input_mixer)),
SND_SOC_DAPM_MIXER("Right Input Mixer", WM8983_POWER_MANAGEMENT_2,
3, 0, right_input_mixer, ARRAY_SIZE(right_input_mixer)),
SND_SOC_DAPM_MIXER("Left Boost Mixer", WM8983_POWER_MANAGEMENT_2,
4, 0, left_boost_mixer, ARRAY_SIZE(left_boost_mixer)),
SND_SOC_DAPM_MIXER("Right Boost Mixer", WM8983_POWER_MANAGEMENT_2,
5, 0, right_boost_mixer, ARRAY_SIZE(right_boost_mixer)),
SND_SOC_DAPM_MIXER("OUT3 Mixer", WM8983_POWER_MANAGEMENT_1,
6, 0, out3_mixer, ARRAY_SIZE(out3_mixer)),
SND_SOC_DAPM_MIXER("OUT4 Mixer", WM8983_POWER_MANAGEMENT_1,
7, 0, out4_mixer, ARRAY_SIZE(out4_mixer)),
SND_SOC_DAPM_PGA("Left Capture PGA", WM8983_LEFT_INP_PGA_GAIN_CTRL,
6, 1, NULL, 0),
SND_SOC_DAPM_PGA("Right Capture PGA", WM8983_RIGHT_INP_PGA_GAIN_CTRL,
6, 1, NULL, 0),
SND_SOC_DAPM_PGA("Left Headphone Out", WM8983_POWER_MANAGEMENT_2,
7, 0, NULL, 0),
SND_SOC_DAPM_PGA("Right Headphone Out", WM8983_POWER_MANAGEMENT_2,
8, 0, NULL, 0),
SND_SOC_DAPM_PGA("Left Speaker Out", WM8983_POWER_MANAGEMENT_3,
5, 0, NULL, 0),
SND_SOC_DAPM_PGA("Right Speaker Out", WM8983_POWER_MANAGEMENT_3,
6, 0, NULL, 0),
SND_SOC_DAPM_PGA("OUT3 Out", WM8983_POWER_MANAGEMENT_3,
7, 0, NULL, 0),
SND_SOC_DAPM_PGA("OUT4 Out", WM8983_POWER_MANAGEMENT_3,
8, 0, NULL, 0),
SND_SOC_DAPM_SUPPLY("Mic Bias", WM8983_POWER_MANAGEMENT_1, 4, 0,
NULL, 0),
SND_SOC_DAPM_INPUT("LIN"),
SND_SOC_DAPM_INPUT("LIP"),
SND_SOC_DAPM_INPUT("RIN"),
SND_SOC_DAPM_INPUT("RIP"),
SND_SOC_DAPM_INPUT("AUXL"),
SND_SOC_DAPM_INPUT("AUXR"),
SND_SOC_DAPM_INPUT("L2"),
SND_SOC_DAPM_INPUT("R2"),
SND_SOC_DAPM_OUTPUT("HPL"),
SND_SOC_DAPM_OUTPUT("HPR"),
SND_SOC_DAPM_OUTPUT("SPKL"),
SND_SOC_DAPM_OUTPUT("SPKR"),
SND_SOC_DAPM_OUTPUT("OUT3"),
SND_SOC_DAPM_OUTPUT("OUT4")
};
static const struct snd_soc_dapm_route wm8983_audio_map[] = {
{ "OUT3 Mixer", "LMIX2OUT3 Switch", "Left Output Mixer" },
{ "OUT3 Mixer", "LDAC2OUT3 Switch", "Left DAC" },
{ "OUT3 Out", NULL, "OUT3 Mixer" },
{ "OUT3", NULL, "OUT3 Out" },
{ "OUT4 Mixer", "LMIX2OUT4 Switch", "Left Output Mixer" },
{ "OUT4 Mixer", "RMIX2OUT4 Switch", "Right Output Mixer" },
{ "OUT4 Mixer", "LDAC2OUT4 Switch", "Left DAC" },
{ "OUT4 Mixer", "RDAC2OUT4 Switch", "Right DAC" },
{ "OUT4 Out", NULL, "OUT4 Mixer" },
{ "OUT4", NULL, "OUT4 Out" },
{ "Right Output Mixer", "PCM Switch", "Right DAC" },
{ "Right Output Mixer", "Aux Switch", "AUXR" },
{ "Right Output Mixer", "Line Switch", "Right Boost Mixer" },
{ "Left Output Mixer", "PCM Switch", "Left DAC" },
{ "Left Output Mixer", "Aux Switch", "AUXL" },
{ "Left Output Mixer", "Line Switch", "Left Boost Mixer" },
{ "Right Headphone Out", NULL, "Right Output Mixer" },
{ "HPR", NULL, "Right Headphone Out" },
{ "Left Headphone Out", NULL, "Left Output Mixer" },
{ "HPL", NULL, "Left Headphone Out" },
{ "Right Speaker Out", NULL, "Right Output Mixer" },
{ "SPKR", NULL, "Right Speaker Out" },
{ "Left Speaker Out", NULL, "Left Output Mixer" },
{ "SPKL", NULL, "Left Speaker Out" },
{ "Right ADC", NULL, "Right Boost Mixer" },
{ "Right Boost Mixer", "AUXR Volume", "AUXR" },
{ "Right Boost Mixer", NULL, "Right Capture PGA" },
{ "Right Boost Mixer", "R2 Volume", "R2" },
{ "Left ADC", NULL, "Left Boost Mixer" },
{ "Left Boost Mixer", "AUXL Volume", "AUXL" },
{ "Left Boost Mixer", NULL, "Left Capture PGA" },
{ "Left Boost Mixer", "L2 Volume", "L2" },
{ "Right Capture PGA", NULL, "Right Input Mixer" },
{ "Left Capture PGA", NULL, "Left Input Mixer" },
{ "Right Input Mixer", "R2 Switch", "R2" },
{ "Right Input Mixer", "MicN Switch", "RIN" },
{ "Right Input Mixer", "MicP Switch", "RIP" },
{ "Left Input Mixer", "L2 Switch", "L2" },
{ "Left Input Mixer", "MicN Switch", "LIN" },
{ "Left Input Mixer", "MicP Switch", "LIP" },
};
static int eqmode_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
unsigned int reg;
reg = snd_soc_read(codec, WM8983_EQ1_LOW_SHELF);
if (reg & WM8983_EQ3DMODE)
ucontrol->value.integer.value[0] = 1;
else
ucontrol->value.integer.value[0] = 0;
return 0;
}
static int eqmode_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
unsigned int regpwr2, regpwr3;
unsigned int reg_eq;
if (ucontrol->value.integer.value[0] != 0
&& ucontrol->value.integer.value[0] != 1)
return -EINVAL;
reg_eq = snd_soc_read(codec, WM8983_EQ1_LOW_SHELF);
switch ((reg_eq & WM8983_EQ3DMODE) >> WM8983_EQ3DMODE_SHIFT) {
case 0:
if (!ucontrol->value.integer.value[0])
return 0;
break;
case 1:
if (ucontrol->value.integer.value[0])
return 0;
break;
}
regpwr2 = snd_soc_read(codec, WM8983_POWER_MANAGEMENT_2);
regpwr3 = snd_soc_read(codec, WM8983_POWER_MANAGEMENT_3);
/* disable the DACs and ADCs */
snd_soc_update_bits(codec, WM8983_POWER_MANAGEMENT_2,
WM8983_ADCENR_MASK | WM8983_ADCENL_MASK, 0);
snd_soc_update_bits(codec, WM8983_POWER_MANAGEMENT_3,
WM8983_DACENR_MASK | WM8983_DACENL_MASK, 0);
/* set the desired eqmode */
snd_soc_update_bits(codec, WM8983_EQ1_LOW_SHELF,
WM8983_EQ3DMODE_MASK,
ucontrol->value.integer.value[0]
<< WM8983_EQ3DMODE_SHIFT);
/* restore DAC/ADC configuration */
snd_soc_write(codec, WM8983_POWER_MANAGEMENT_2, regpwr2);
snd_soc_write(codec, WM8983_POWER_MANAGEMENT_3, regpwr3);
return 0;
}
static bool wm8983_readable(struct device *dev, unsigned int reg)
{
if (reg > WM8983_MAX_REGISTER)
return 0;
return wm8983_access_masks[reg].read != 0;
}
static int wm8983_dac_mute(struct snd_soc_dai *dai, int mute)
{
struct snd_soc_codec *codec = dai->codec;
return snd_soc_update_bits(codec, WM8983_DAC_CONTROL,
WM8983_SOFTMUTE_MASK,
!!mute << WM8983_SOFTMUTE_SHIFT);
}
static int wm8983_set_fmt(struct snd_soc_dai *dai, unsigned int fmt)
{
struct snd_soc_codec *codec = dai->codec;
u16 format, master, bcp, lrp;
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_I2S:
format = 0x2;
break;
case SND_SOC_DAIFMT_RIGHT_J:
format = 0x0;
break;
case SND_SOC_DAIFMT_LEFT_J:
format = 0x1;
break;
case SND_SOC_DAIFMT_DSP_A:
case SND_SOC_DAIFMT_DSP_B:
format = 0x3;
break;
default:
dev_err(dai->dev, "Unknown dai format\n");
return -EINVAL;
}
snd_soc_update_bits(codec, WM8983_AUDIO_INTERFACE,
WM8983_FMT_MASK, format << WM8983_FMT_SHIFT);
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBM_CFM:
master = 1;
break;
case SND_SOC_DAIFMT_CBS_CFS:
master = 0;
break;
default:
dev_err(dai->dev, "Unknown master/slave configuration\n");
return -EINVAL;
}
snd_soc_update_bits(codec, WM8983_CLOCK_GEN_CONTROL,
WM8983_MS_MASK, master << WM8983_MS_SHIFT);
/* FIXME: We don't currently support DSP A/B modes */
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_DSP_A:
case SND_SOC_DAIFMT_DSP_B:
dev_err(dai->dev, "DSP A/B modes are not supported\n");
return -EINVAL;
default:
break;
}
bcp = lrp = 0;
switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
case SND_SOC_DAIFMT_NB_NF:
break;
case SND_SOC_DAIFMT_IB_IF:
bcp = lrp = 1;
break;
case SND_SOC_DAIFMT_IB_NF:
bcp = 1;
break;
case SND_SOC_DAIFMT_NB_IF:
lrp = 1;
break;
default:
dev_err(dai->dev, "Unknown polarity configuration\n");
return -EINVAL;
}
snd_soc_update_bits(codec, WM8983_AUDIO_INTERFACE,
WM8983_LRCP_MASK, lrp << WM8983_LRCP_SHIFT);
snd_soc_update_bits(codec, WM8983_AUDIO_INTERFACE,
WM8983_BCP_MASK, bcp << WM8983_BCP_SHIFT);
return 0;
}
static int wm8983_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
int i;
struct snd_soc_codec *codec = dai->codec;
struct wm8983_priv *wm8983 = snd_soc_codec_get_drvdata(codec);
u16 blen, srate_idx;
u32 tmp;
int srate_best;
int ret;
ret = snd_soc_params_to_bclk(params);
if (ret < 0) {
dev_err(codec->dev, "Failed to convert params to bclk: %d\n", ret);
return ret;
}
wm8983->bclk = ret;
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
blen = 0x0;
break;
case SNDRV_PCM_FORMAT_S20_3LE:
blen = 0x1;
break;
case SNDRV_PCM_FORMAT_S24_LE:
blen = 0x2;
break;
case SNDRV_PCM_FORMAT_S32_LE:
blen = 0x3;
break;
default:
dev_err(dai->dev, "Unsupported word length %u\n",
params_format(params));
return -EINVAL;
}
snd_soc_update_bits(codec, WM8983_AUDIO_INTERFACE,
WM8983_WL_MASK, blen << WM8983_WL_SHIFT);
/*
* match to the nearest possible sample rate and rely
* on the array index to configure the SR register
*/
srate_idx = 0;
srate_best = abs(srates[0] - params_rate(params));
for (i = 1; i < ARRAY_SIZE(srates); ++i) {
if (abs(srates[i] - params_rate(params)) >= srate_best)
continue;
srate_idx = i;
srate_best = abs(srates[i] - params_rate(params));
}
dev_dbg(dai->dev, "Selected SRATE = %d\n", srates[srate_idx]);
snd_soc_update_bits(codec, WM8983_ADDITIONAL_CONTROL,
WM8983_SR_MASK, srate_idx << WM8983_SR_SHIFT);
dev_dbg(dai->dev, "Target BCLK = %uHz\n", wm8983->bclk);
dev_dbg(dai->dev, "SYSCLK = %uHz\n", wm8983->sysclk);
for (i = 0; i < ARRAY_SIZE(fs_ratios); ++i) {
if (wm8983->sysclk / params_rate(params)
== fs_ratios[i].ratio)
break;
}
if (i == ARRAY_SIZE(fs_ratios)) {
dev_err(dai->dev, "Unable to configure MCLK ratio %u/%u\n",
wm8983->sysclk, params_rate(params));
return -EINVAL;
}
dev_dbg(dai->dev, "MCLK ratio = %dfs\n", fs_ratios[i].ratio);
snd_soc_update_bits(codec, WM8983_CLOCK_GEN_CONTROL,
WM8983_MCLKDIV_MASK, i << WM8983_MCLKDIV_SHIFT);
/* select the appropriate bclk divider */
tmp = (wm8983->sysclk / fs_ratios[i].div) * 10;
for (i = 0; i < ARRAY_SIZE(bclk_divs); ++i) {
if (wm8983->bclk == tmp / bclk_divs[i])
break;
}
if (i == ARRAY_SIZE(bclk_divs)) {
dev_err(dai->dev, "No matching BCLK divider found\n");
return -EINVAL;
}
dev_dbg(dai->dev, "BCLK div = %d\n", i);
snd_soc_update_bits(codec, WM8983_CLOCK_GEN_CONTROL,
WM8983_BCLKDIV_MASK, i << WM8983_BCLKDIV_SHIFT);
return 0;
}
struct pll_div {
u32 div2:1;
u32 n:4;
u32 k:24;
};
#define FIXED_PLL_SIZE ((1ULL << 24) * 10)
static int pll_factors(struct pll_div *pll_div, unsigned int target,
unsigned int source)
{
u64 Kpart;
unsigned long int K, Ndiv, Nmod;
pll_div->div2 = 0;
Ndiv = target / source;
if (Ndiv < 6) {
source >>= 1;
pll_div->div2 = 1;
Ndiv = target / source;
}
if (Ndiv < 6 || Ndiv > 12) {
printk(KERN_ERR "%s: WM8983 N value is not within"
" the recommended range: %lu\n", __func__, Ndiv);
return -EINVAL;
}
pll_div->n = Ndiv;
Nmod = target % source;
Kpart = FIXED_PLL_SIZE * (u64)Nmod;
do_div(Kpart, source);
K = Kpart & 0xffffffff;
if ((K % 10) >= 5)
K += 5;
K /= 10;
pll_div->k = K;
return 0;
}
static int wm8983_set_pll(struct snd_soc_dai *dai, int pll_id,
int source, unsigned int freq_in,
unsigned int freq_out)
{
int ret;
struct snd_soc_codec *codec;
struct pll_div pll_div;
codec = dai->codec;
if (!freq_in || !freq_out) {
/* disable the PLL */
snd_soc_update_bits(codec, WM8983_POWER_MANAGEMENT_1,
WM8983_PLLEN_MASK, 0);
return 0;
} else {
ret = pll_factors(&pll_div, freq_out * 4 * 2, freq_in);
if (ret)
return ret;
/* disable the PLL before re-programming it */
snd_soc_update_bits(codec, WM8983_POWER_MANAGEMENT_1,
WM8983_PLLEN_MASK, 0);
/* set PLLN and PRESCALE */
snd_soc_write(codec, WM8983_PLL_N,
(pll_div.div2 << WM8983_PLL_PRESCALE_SHIFT)
| pll_div.n);
/* set PLLK */
snd_soc_write(codec, WM8983_PLL_K_3, pll_div.k & 0x1ff);
snd_soc_write(codec, WM8983_PLL_K_2, (pll_div.k >> 9) & 0x1ff);
snd_soc_write(codec, WM8983_PLL_K_1, (pll_div.k >> 18));
/* enable the PLL */
snd_soc_update_bits(codec, WM8983_POWER_MANAGEMENT_1,
WM8983_PLLEN_MASK, WM8983_PLLEN);
}
return 0;
}
static int wm8983_set_sysclk(struct snd_soc_dai *dai,
int clk_id, unsigned int freq, int dir)
{
struct snd_soc_codec *codec = dai->codec;
struct wm8983_priv *wm8983 = snd_soc_codec_get_drvdata(codec);
switch (clk_id) {
case WM8983_CLKSRC_MCLK:
snd_soc_update_bits(codec, WM8983_CLOCK_GEN_CONTROL,
WM8983_CLKSEL_MASK, 0);
break;
case WM8983_CLKSRC_PLL:
snd_soc_update_bits(codec, WM8983_CLOCK_GEN_CONTROL,
WM8983_CLKSEL_MASK, WM8983_CLKSEL);
break;
default:
dev_err(dai->dev, "Unknown clock source: %d\n", clk_id);
return -EINVAL;
}
wm8983->sysclk = freq;
return 0;
}
static int wm8983_set_bias_level(struct snd_soc_codec *codec,
enum snd_soc_bias_level level)
{
struct wm8983_priv *wm8983 = snd_soc_codec_get_drvdata(codec);
int ret;
switch (level) {
case SND_SOC_BIAS_ON:
case SND_SOC_BIAS_PREPARE:
/* VMID at 100k */
snd_soc_update_bits(codec, WM8983_POWER_MANAGEMENT_1,
WM8983_VMIDSEL_MASK,
1 << WM8983_VMIDSEL_SHIFT);
break;
case SND_SOC_BIAS_STANDBY:
if (codec->dapm.bias_level == SND_SOC_BIAS_OFF) {
ret = regcache_sync(wm8983->regmap);
if (ret < 0) {
dev_err(codec->dev, "Failed to sync cache: %d\n", ret);
return ret;
}
/* enable anti-pop features */
snd_soc_update_bits(codec, WM8983_OUT4_TO_ADC,
WM8983_POBCTRL_MASK | WM8983_DELEN_MASK,
WM8983_POBCTRL | WM8983_DELEN);
/* enable thermal shutdown */
snd_soc_update_bits(codec, WM8983_OUTPUT_CTRL,
WM8983_TSDEN_MASK, WM8983_TSDEN);
/* enable BIASEN */
snd_soc_update_bits(codec, WM8983_POWER_MANAGEMENT_1,
WM8983_BIASEN_MASK, WM8983_BIASEN);
/* VMID at 100k */
snd_soc_update_bits(codec, WM8983_POWER_MANAGEMENT_1,
WM8983_VMIDSEL_MASK,
1 << WM8983_VMIDSEL_SHIFT);
msleep(250);
/* disable anti-pop features */
snd_soc_update_bits(codec, WM8983_OUT4_TO_ADC,
WM8983_POBCTRL_MASK |
WM8983_DELEN_MASK, 0);
}
/* VMID at 500k */
snd_soc_update_bits(codec, WM8983_POWER_MANAGEMENT_1,
WM8983_VMIDSEL_MASK,
2 << WM8983_VMIDSEL_SHIFT);
break;
case SND_SOC_BIAS_OFF:
/* disable thermal shutdown */
snd_soc_update_bits(codec, WM8983_OUTPUT_CTRL,
WM8983_TSDEN_MASK, 0);
/* disable VMIDSEL and BIASEN */
snd_soc_update_bits(codec, WM8983_POWER_MANAGEMENT_1,
WM8983_VMIDSEL_MASK | WM8983_BIASEN_MASK,
0);
/* wait for VMID to discharge */
msleep(100);
snd_soc_write(codec, WM8983_POWER_MANAGEMENT_1, 0);
snd_soc_write(codec, WM8983_POWER_MANAGEMENT_2, 0);
snd_soc_write(codec, WM8983_POWER_MANAGEMENT_3, 0);
break;
}
codec->dapm.bias_level = level;
return 0;
}
#ifdef CONFIG_PM
static int wm8983_suspend(struct snd_soc_codec *codec)
{
wm8983_set_bias_level(codec, SND_SOC_BIAS_OFF);
return 0;
}
static int wm8983_resume(struct snd_soc_codec *codec)
{
wm8983_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
return 0;
}
#else
#define wm8983_suspend NULL
#define wm8983_resume NULL
#endif
static int wm8983_remove(struct snd_soc_codec *codec)
{
wm8983_set_bias_level(codec, SND_SOC_BIAS_OFF);
return 0;
}
static int wm8983_probe(struct snd_soc_codec *codec)
{
int ret;
int i;
ret = snd_soc_codec_set_cache_io(codec, 7, 9, SND_SOC_REGMAP);
if (ret < 0) {
dev_err(codec->dev, "Failed to set cache i/o: %d\n", ret);
return ret;
}
ret = snd_soc_write(codec, WM8983_SOFTWARE_RESET, 0);
if (ret < 0) {
dev_err(codec->dev, "Failed to issue reset: %d\n", ret);
return ret;
}
/* set the vol/gain update bits */
for (i = 0; i < ARRAY_SIZE(vol_update_regs); ++i)
snd_soc_update_bits(codec, vol_update_regs[i],
0x100, 0x100);
/* mute all outputs and set PGAs to minimum gain */
for (i = WM8983_LOUT1_HP_VOLUME_CTRL;
i <= WM8983_OUT4_MONO_MIX_CTRL; ++i)
snd_soc_update_bits(codec, i, 0x40, 0x40);
/* enable soft mute */
snd_soc_update_bits(codec, WM8983_DAC_CONTROL,
WM8983_SOFTMUTE_MASK,
WM8983_SOFTMUTE);
/* enable BIASCUT */
snd_soc_update_bits(codec, WM8983_BIAS_CTRL,
WM8983_BIASCUT, WM8983_BIASCUT);
return 0;
}
static const struct snd_soc_dai_ops wm8983_dai_ops = {
.digital_mute = wm8983_dac_mute,
.hw_params = wm8983_hw_params,
.set_fmt = wm8983_set_fmt,
.set_sysclk = wm8983_set_sysclk,
.set_pll = wm8983_set_pll
};
#define WM8983_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE | \
SNDRV_PCM_FMTBIT_S24_LE | SNDRV_PCM_FMTBIT_S32_LE)
static struct snd_soc_dai_driver wm8983_dai = {
.name = "wm8983-hifi",
.playback = {
.stream_name = "Playback",
.channels_min = 2,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_8000_48000,
.formats = WM8983_FORMATS,
},
.capture = {
.stream_name = "Capture",
.channels_min = 2,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_8000_48000,
.formats = WM8983_FORMATS,
},
.ops = &wm8983_dai_ops,
.symmetric_rates = 1
};
static struct snd_soc_codec_driver soc_codec_dev_wm8983 = {
.probe = wm8983_probe,
.remove = wm8983_remove,
.suspend = wm8983_suspend,
.resume = wm8983_resume,
.set_bias_level = wm8983_set_bias_level,
.controls = wm8983_snd_controls,
.num_controls = ARRAY_SIZE(wm8983_snd_controls),
.dapm_widgets = wm8983_dapm_widgets,
.num_dapm_widgets = ARRAY_SIZE(wm8983_dapm_widgets),
.dapm_routes = wm8983_audio_map,
.num_dapm_routes = ARRAY_SIZE(wm8983_audio_map),
};
static const struct regmap_config wm8983_regmap = {
.reg_bits = 7,
.val_bits = 9,
.reg_defaults = wm8983_defaults,
.num_reg_defaults = ARRAY_SIZE(wm8983_defaults),
.cache_type = REGCACHE_RBTREE,
.readable_reg = wm8983_readable,
};
#if defined(CONFIG_SPI_MASTER)
static int wm8983_spi_probe(struct spi_device *spi)
{
struct wm8983_priv *wm8983;
int ret;
wm8983 = devm_kzalloc(&spi->dev, sizeof *wm8983, GFP_KERNEL);
if (!wm8983)
return -ENOMEM;
wm8983->regmap = devm_regmap_init_spi(spi, &wm8983_regmap);
if (IS_ERR(wm8983->regmap)) {
ret = PTR_ERR(wm8983->regmap);
dev_err(&spi->dev, "Failed to init regmap: %d\n", ret);
return ret;
}
spi_set_drvdata(spi, wm8983);
ret = snd_soc_register_codec(&spi->dev,
&soc_codec_dev_wm8983, &wm8983_dai, 1);
return ret;
}
static int wm8983_spi_remove(struct spi_device *spi)
{
snd_soc_unregister_codec(&spi->dev);
return 0;
}
static struct spi_driver wm8983_spi_driver = {
.driver = {
.name = "wm8983",
.owner = THIS_MODULE,
},
.probe = wm8983_spi_probe,
.remove = wm8983_spi_remove
};
#endif
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
static int wm8983_i2c_probe(struct i2c_client *i2c,
const struct i2c_device_id *id)
{
struct wm8983_priv *wm8983;
int ret;
wm8983 = devm_kzalloc(&i2c->dev, sizeof *wm8983, GFP_KERNEL);
if (!wm8983)
return -ENOMEM;
wm8983->regmap = devm_regmap_init_i2c(i2c, &wm8983_regmap);
if (IS_ERR(wm8983->regmap)) {
ret = PTR_ERR(wm8983->regmap);
dev_err(&i2c->dev, "Failed to init regmap: %d\n", ret);
return ret;
}
i2c_set_clientdata(i2c, wm8983);
ret = snd_soc_register_codec(&i2c->dev,
&soc_codec_dev_wm8983, &wm8983_dai, 1);
return ret;
}
static int wm8983_i2c_remove(struct i2c_client *client)
{
snd_soc_unregister_codec(&client->dev);
return 0;
}
static const struct i2c_device_id wm8983_i2c_id[] = {
{ "wm8983", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, wm8983_i2c_id);
static struct i2c_driver wm8983_i2c_driver = {
.driver = {
.name = "wm8983",
.owner = THIS_MODULE,
},
.probe = wm8983_i2c_probe,
.remove = wm8983_i2c_remove,
.id_table = wm8983_i2c_id
};
#endif
static int __init wm8983_modinit(void)
{
int ret = 0;
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
ret = i2c_add_driver(&wm8983_i2c_driver);
if (ret) {
printk(KERN_ERR "Failed to register wm8983 I2C driver: %d\n",
ret);
}
#endif
#if defined(CONFIG_SPI_MASTER)
ret = spi_register_driver(&wm8983_spi_driver);
if (ret != 0) {
printk(KERN_ERR "Failed to register wm8983 SPI driver: %d\n",
ret);
}
#endif
return ret;
}
module_init(wm8983_modinit);
static void __exit wm8983_exit(void)
{
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
i2c_del_driver(&wm8983_i2c_driver);
#endif
#if defined(CONFIG_SPI_MASTER)
spi_unregister_driver(&wm8983_spi_driver);
#endif
}
module_exit(wm8983_exit);
MODULE_DESCRIPTION("ASoC WM8983 driver");
MODULE_AUTHOR("Dimitris Papastamos <dp@opensource.wolfsonmicro.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
digitaleric-google/GCG-2.6.39 | drivers/leds/leds-lp3944.c | 4153 | 11398 | /*
* leds-lp3944.c - driver for National Semiconductor LP3944 Funlight Chip
*
* Copyright (C) 2009 Antonio Ospite <ospite@studenti.unina.it>
*
* 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.
*
*/
/*
* I2C driver for National Semiconductor LP3944 Funlight Chip
* http://www.national.com/pf/LP/LP3944.html
*
* This helper chip can drive up to 8 leds, with two programmable DIM modes;
* it could even be used as a gpio expander but this driver assumes it is used
* as a led controller.
*
* The DIM modes are used to set _blink_ patterns for leds, the pattern is
* specified supplying two parameters:
* - period: from 0s to 1.6s
* - duty cycle: percentage of the period the led is on, from 0 to 100
*
* LP3944 can be found on Motorola A910 smartphone, where it drives the rgb
* leds, the camera flash light and the displays backlights.
*/
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include <linux/leds.h>
#include <linux/mutex.h>
#include <linux/workqueue.h>
#include <linux/leds-lp3944.h>
/* Read Only Registers */
#define LP3944_REG_INPUT1 0x00 /* LEDs 0-7 InputRegister (Read Only) */
#define LP3944_REG_REGISTER1 0x01 /* None (Read Only) */
#define LP3944_REG_PSC0 0x02 /* Frequency Prescaler 0 (R/W) */
#define LP3944_REG_PWM0 0x03 /* PWM Register 0 (R/W) */
#define LP3944_REG_PSC1 0x04 /* Frequency Prescaler 1 (R/W) */
#define LP3944_REG_PWM1 0x05 /* PWM Register 1 (R/W) */
#define LP3944_REG_LS0 0x06 /* LEDs 0-3 Selector (R/W) */
#define LP3944_REG_LS1 0x07 /* LEDs 4-7 Selector (R/W) */
/* These registers are not used to control leds in LP3944, they can store
* arbitrary values which the chip will ignore.
*/
#define LP3944_REG_REGISTER8 0x08
#define LP3944_REG_REGISTER9 0x09
#define LP3944_DIM0 0
#define LP3944_DIM1 1
/* period in ms */
#define LP3944_PERIOD_MIN 0
#define LP3944_PERIOD_MAX 1600
/* duty cycle is a percentage */
#define LP3944_DUTY_CYCLE_MIN 0
#define LP3944_DUTY_CYCLE_MAX 100
#define ldev_to_led(c) container_of(c, struct lp3944_led_data, ldev)
/* Saved data */
struct lp3944_led_data {
u8 id;
enum lp3944_type type;
enum lp3944_status status;
struct led_classdev ldev;
struct i2c_client *client;
struct work_struct work;
};
struct lp3944_data {
struct mutex lock;
struct i2c_client *client;
struct lp3944_led_data leds[LP3944_LEDS_MAX];
};
static int lp3944_reg_read(struct i2c_client *client, u8 reg, u8 *value)
{
int tmp;
tmp = i2c_smbus_read_byte_data(client, reg);
if (tmp < 0)
return -EINVAL;
*value = tmp;
return 0;
}
static int lp3944_reg_write(struct i2c_client *client, u8 reg, u8 value)
{
return i2c_smbus_write_byte_data(client, reg, value);
}
/**
* Set the period for DIM status
*
* @client: the i2c client
* @dim: either LP3944_DIM0 or LP3944_DIM1
* @period: period of a blink, that is a on/off cycle, expressed in ms.
*/
static int lp3944_dim_set_period(struct i2c_client *client, u8 dim, u16 period)
{
u8 psc_reg;
u8 psc_value;
int err;
if (dim == LP3944_DIM0)
psc_reg = LP3944_REG_PSC0;
else if (dim == LP3944_DIM1)
psc_reg = LP3944_REG_PSC1;
else
return -EINVAL;
/* Convert period to Prescaler value */
if (period > LP3944_PERIOD_MAX)
return -EINVAL;
psc_value = (period * 255) / LP3944_PERIOD_MAX;
err = lp3944_reg_write(client, psc_reg, psc_value);
return err;
}
/**
* Set the duty cycle for DIM status
*
* @client: the i2c client
* @dim: either LP3944_DIM0 or LP3944_DIM1
* @duty_cycle: percentage of a period during which a led is ON
*/
static int lp3944_dim_set_dutycycle(struct i2c_client *client, u8 dim,
u8 duty_cycle)
{
u8 pwm_reg;
u8 pwm_value;
int err;
if (dim == LP3944_DIM0)
pwm_reg = LP3944_REG_PWM0;
else if (dim == LP3944_DIM1)
pwm_reg = LP3944_REG_PWM1;
else
return -EINVAL;
/* Convert duty cycle to PWM value */
if (duty_cycle > LP3944_DUTY_CYCLE_MAX)
return -EINVAL;
pwm_value = (duty_cycle * 255) / LP3944_DUTY_CYCLE_MAX;
err = lp3944_reg_write(client, pwm_reg, pwm_value);
return err;
}
/**
* Set the led status
*
* @led: a lp3944_led_data structure
* @status: one of LP3944_LED_STATUS_OFF
* LP3944_LED_STATUS_ON
* LP3944_LED_STATUS_DIM0
* LP3944_LED_STATUS_DIM1
*/
static int lp3944_led_set(struct lp3944_led_data *led, u8 status)
{
struct lp3944_data *data = i2c_get_clientdata(led->client);
u8 id = led->id;
u8 reg;
u8 val = 0;
int err;
dev_dbg(&led->client->dev, "%s: %s, status before normalization:%d\n",
__func__, led->ldev.name, status);
switch (id) {
case LP3944_LED0:
case LP3944_LED1:
case LP3944_LED2:
case LP3944_LED3:
reg = LP3944_REG_LS0;
break;
case LP3944_LED4:
case LP3944_LED5:
case LP3944_LED6:
case LP3944_LED7:
id -= LP3944_LED4;
reg = LP3944_REG_LS1;
break;
default:
return -EINVAL;
}
if (status > LP3944_LED_STATUS_DIM1)
return -EINVAL;
/* invert only 0 and 1, leave unchanged the other values,
* remember we are abusing status to set blink patterns
*/
if (led->type == LP3944_LED_TYPE_LED_INVERTED && status < 2)
status = 1 - status;
mutex_lock(&data->lock);
lp3944_reg_read(led->client, reg, &val);
val &= ~(LP3944_LED_STATUS_MASK << (id << 1));
val |= (status << (id << 1));
dev_dbg(&led->client->dev, "%s: %s, reg:%d id:%d status:%d val:%#x\n",
__func__, led->ldev.name, reg, id, status, val);
/* set led status */
err = lp3944_reg_write(led->client, reg, val);
mutex_unlock(&data->lock);
return err;
}
static int lp3944_led_set_blink(struct led_classdev *led_cdev,
unsigned long *delay_on,
unsigned long *delay_off)
{
struct lp3944_led_data *led = ldev_to_led(led_cdev);
u16 period;
u8 duty_cycle;
int err;
/* units are in ms */
if (*delay_on + *delay_off > LP3944_PERIOD_MAX)
return -EINVAL;
if (*delay_on == 0 && *delay_off == 0) {
/* Special case: the leds subsystem requires a default user
* friendly blink pattern for the LED. Let's blink the led
* slowly (1Hz).
*/
*delay_on = 500;
*delay_off = 500;
}
period = (*delay_on) + (*delay_off);
/* duty_cycle is the percentage of period during which the led is ON */
duty_cycle = 100 * (*delay_on) / period;
/* invert duty cycle for inverted leds, this has the same effect of
* swapping delay_on and delay_off
*/
if (led->type == LP3944_LED_TYPE_LED_INVERTED)
duty_cycle = 100 - duty_cycle;
/* NOTE: using always the first DIM mode, this means that all leds
* will have the same blinking pattern.
*
* We could find a way later to have two leds blinking in hardware
* with different patterns at the same time, falling back to software
* control for the other ones.
*/
err = lp3944_dim_set_period(led->client, LP3944_DIM0, period);
if (err)
return err;
err = lp3944_dim_set_dutycycle(led->client, LP3944_DIM0, duty_cycle);
if (err)
return err;
dev_dbg(&led->client->dev, "%s: OK hardware accelerated blink!\n",
__func__);
led->status = LP3944_LED_STATUS_DIM0;
schedule_work(&led->work);
return 0;
}
static void lp3944_led_set_brightness(struct led_classdev *led_cdev,
enum led_brightness brightness)
{
struct lp3944_led_data *led = ldev_to_led(led_cdev);
dev_dbg(&led->client->dev, "%s: %s, %d\n",
__func__, led_cdev->name, brightness);
led->status = brightness;
schedule_work(&led->work);
}
static void lp3944_led_work(struct work_struct *work)
{
struct lp3944_led_data *led;
led = container_of(work, struct lp3944_led_data, work);
lp3944_led_set(led, led->status);
}
static int lp3944_configure(struct i2c_client *client,
struct lp3944_data *data,
struct lp3944_platform_data *pdata)
{
int i, err = 0;
for (i = 0; i < pdata->leds_size; i++) {
struct lp3944_led *pled = &pdata->leds[i];
struct lp3944_led_data *led = &data->leds[i];
led->client = client;
led->id = i;
switch (pled->type) {
case LP3944_LED_TYPE_LED:
case LP3944_LED_TYPE_LED_INVERTED:
led->type = pled->type;
led->status = pled->status;
led->ldev.name = pled->name;
led->ldev.max_brightness = 1;
led->ldev.brightness_set = lp3944_led_set_brightness;
led->ldev.blink_set = lp3944_led_set_blink;
led->ldev.flags = LED_CORE_SUSPENDRESUME;
INIT_WORK(&led->work, lp3944_led_work);
err = led_classdev_register(&client->dev, &led->ldev);
if (err < 0) {
dev_err(&client->dev,
"couldn't register LED %s\n",
led->ldev.name);
goto exit;
}
/* to expose the default value to userspace */
led->ldev.brightness = led->status;
/* Set the default led status */
err = lp3944_led_set(led, led->status);
if (err < 0) {
dev_err(&client->dev,
"%s couldn't set STATUS %d\n",
led->ldev.name, led->status);
goto exit;
}
break;
case LP3944_LED_TYPE_NONE:
default:
break;
}
}
return 0;
exit:
if (i > 0)
for (i = i - 1; i >= 0; i--)
switch (pdata->leds[i].type) {
case LP3944_LED_TYPE_LED:
case LP3944_LED_TYPE_LED_INVERTED:
led_classdev_unregister(&data->leds[i].ldev);
cancel_work_sync(&data->leds[i].work);
break;
case LP3944_LED_TYPE_NONE:
default:
break;
}
return err;
}
static int __devinit lp3944_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct lp3944_platform_data *lp3944_pdata = client->dev.platform_data;
struct lp3944_data *data;
int err;
if (lp3944_pdata == NULL) {
dev_err(&client->dev, "no platform data\n");
return -EINVAL;
}
/* Let's see whether this adapter can support what we need. */
if (!i2c_check_functionality(client->adapter,
I2C_FUNC_SMBUS_BYTE_DATA)) {
dev_err(&client->dev, "insufficient functionality!\n");
return -ENODEV;
}
data = kzalloc(sizeof(struct lp3944_data), GFP_KERNEL);
if (!data)
return -ENOMEM;
data->client = client;
i2c_set_clientdata(client, data);
mutex_init(&data->lock);
err = lp3944_configure(client, data, lp3944_pdata);
if (err < 0) {
kfree(data);
return err;
}
dev_info(&client->dev, "lp3944 enabled\n");
return 0;
}
static int __devexit lp3944_remove(struct i2c_client *client)
{
struct lp3944_platform_data *pdata = client->dev.platform_data;
struct lp3944_data *data = i2c_get_clientdata(client);
int i;
for (i = 0; i < pdata->leds_size; i++)
switch (data->leds[i].type) {
case LP3944_LED_TYPE_LED:
case LP3944_LED_TYPE_LED_INVERTED:
led_classdev_unregister(&data->leds[i].ldev);
cancel_work_sync(&data->leds[i].work);
break;
case LP3944_LED_TYPE_NONE:
default:
break;
}
kfree(data);
return 0;
}
/* lp3944 i2c driver struct */
static const struct i2c_device_id lp3944_id[] = {
{"lp3944", 0},
{}
};
MODULE_DEVICE_TABLE(i2c, lp3944_id);
static struct i2c_driver lp3944_driver = {
.driver = {
.name = "lp3944",
},
.probe = lp3944_probe,
.remove = __devexit_p(lp3944_remove),
.id_table = lp3944_id,
};
static int __init lp3944_module_init(void)
{
return i2c_add_driver(&lp3944_driver);
}
static void __exit lp3944_module_exit(void)
{
i2c_del_driver(&lp3944_driver);
}
module_init(lp3944_module_init);
module_exit(lp3944_module_exit);
MODULE_AUTHOR("Antonio Ospite <ospite@studenti.unina.it>");
MODULE_DESCRIPTION("LP3944 Fun Light Chip");
MODULE_LICENSE("GPL");
| gpl-2.0 |
angpysha/KitKatExtendedKernel | arch/sh/boards/mach-ap325rxa/setup.c | 4409 | 16623 | /*
* Renesas - AP-325RXA
* (Compatible with Algo System ., LTD. - AP-320A)
*
* Copyright (C) 2008 Renesas Solutions Corp.
* Author : Yusuke Goda <goda.yuske@renesas.com>
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/device.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/mmc/host.h>
#include <linux/mmc/sh_mobile_sdhi.h>
#include <linux/mtd/physmap.h>
#include <linux/mtd/sh_flctl.h>
#include <linux/delay.h>
#include <linux/i2c.h>
#include <linux/smsc911x.h>
#include <linux/gpio.h>
#include <linux/videodev2.h>
#include <media/ov772x.h>
#include <media/soc_camera.h>
#include <media/soc_camera_platform.h>
#include <media/sh_mobile_ceu.h>
#include <video/sh_mobile_lcdc.h>
#include <asm/io.h>
#include <asm/clock.h>
#include <asm/suspend.h>
#include <cpu/sh7723.h>
static struct smsc911x_platform_config smsc911x_config = {
.phy_interface = PHY_INTERFACE_MODE_MII,
.irq_polarity = SMSC911X_IRQ_POLARITY_ACTIVE_LOW,
.irq_type = SMSC911X_IRQ_TYPE_OPEN_DRAIN,
.flags = SMSC911X_USE_32BIT,
};
static struct resource smsc9118_resources[] = {
[0] = {
.start = 0xb6080000,
.end = 0xb60fffff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 35,
.end = 35,
.flags = IORESOURCE_IRQ,
}
};
static struct platform_device smsc9118_device = {
.name = "smsc911x",
.id = -1,
.num_resources = ARRAY_SIZE(smsc9118_resources),
.resource = smsc9118_resources,
.dev = {
.platform_data = &smsc911x_config,
},
};
/*
* AP320 and AP325RXA has CPLD data in NOR Flash(0xA80000-0xABFFFF).
* If this area erased, this board can not boot.
*/
static struct mtd_partition ap325rxa_nor_flash_partitions[] = {
{
.name = "uboot",
.offset = 0,
.size = (1 * 1024 * 1024),
.mask_flags = MTD_WRITEABLE, /* Read-only */
}, {
.name = "kernel",
.offset = MTDPART_OFS_APPEND,
.size = (2 * 1024 * 1024),
}, {
.name = "free-area0",
.offset = MTDPART_OFS_APPEND,
.size = ((7 * 1024 * 1024) + (512 * 1024)),
}, {
.name = "CPLD-Data",
.offset = MTDPART_OFS_APPEND,
.mask_flags = MTD_WRITEABLE, /* Read-only */
.size = (1024 * 128 * 2),
}, {
.name = "free-area1",
.offset = MTDPART_OFS_APPEND,
.size = MTDPART_SIZ_FULL,
},
};
static struct physmap_flash_data ap325rxa_nor_flash_data = {
.width = 2,
.parts = ap325rxa_nor_flash_partitions,
.nr_parts = ARRAY_SIZE(ap325rxa_nor_flash_partitions),
};
static struct resource ap325rxa_nor_flash_resources[] = {
[0] = {
.name = "NOR Flash",
.start = 0x00000000,
.end = 0x00ffffff,
.flags = IORESOURCE_MEM,
}
};
static struct platform_device ap325rxa_nor_flash_device = {
.name = "physmap-flash",
.resource = ap325rxa_nor_flash_resources,
.num_resources = ARRAY_SIZE(ap325rxa_nor_flash_resources),
.dev = {
.platform_data = &ap325rxa_nor_flash_data,
},
};
static struct mtd_partition nand_partition_info[] = {
{
.name = "nand_data",
.offset = 0,
.size = MTDPART_SIZ_FULL,
},
};
static struct resource nand_flash_resources[] = {
[0] = {
.start = 0xa4530000,
.end = 0xa45300ff,
.flags = IORESOURCE_MEM,
}
};
static struct sh_flctl_platform_data nand_flash_data = {
.parts = nand_partition_info,
.nr_parts = ARRAY_SIZE(nand_partition_info),
.flcmncr_val = FCKSEL_E | TYPESEL_SET | NANWF_E,
.has_hwecc = 1,
};
static struct platform_device nand_flash_device = {
.name = "sh_flctl",
.resource = nand_flash_resources,
.num_resources = ARRAY_SIZE(nand_flash_resources),
.dev = {
.platform_data = &nand_flash_data,
},
};
#define FPGA_LCDREG 0xB4100180
#define FPGA_BKLREG 0xB4100212
#define FPGA_LCDREG_VAL 0x0018
#define PORT_MSELCRB 0xA4050182
#define PORT_HIZCRC 0xA405015C
#define PORT_DRVCRA 0xA405018A
#define PORT_DRVCRB 0xA405018C
static int ap320_wvga_set_brightness(int brightness)
{
if (brightness) {
gpio_set_value(GPIO_PTS3, 0);
__raw_writew(0x100, FPGA_BKLREG);
} else {
__raw_writew(0, FPGA_BKLREG);
gpio_set_value(GPIO_PTS3, 1);
}
return 0;
}
static int ap320_wvga_get_brightness(void)
{
return gpio_get_value(GPIO_PTS3);
}
static void ap320_wvga_power_on(void)
{
msleep(100);
/* ASD AP-320/325 LCD ON */
__raw_writew(FPGA_LCDREG_VAL, FPGA_LCDREG);
}
static void ap320_wvga_power_off(void)
{
/* ASD AP-320/325 LCD OFF */
__raw_writew(0, FPGA_LCDREG);
}
static const struct fb_videomode ap325rxa_lcdc_modes[] = {
{
.name = "LB070WV1",
.xres = 800,
.yres = 480,
.left_margin = 32,
.right_margin = 160,
.hsync_len = 8,
.upper_margin = 63,
.lower_margin = 80,
.vsync_len = 1,
.sync = 0, /* hsync and vsync are active low */
},
};
static struct sh_mobile_lcdc_info lcdc_info = {
.clock_source = LCDC_CLK_EXTERNAL,
.ch[0] = {
.chan = LCDC_CHAN_MAINLCD,
.fourcc = V4L2_PIX_FMT_RGB565,
.interface_type = RGB18,
.clock_divider = 1,
.lcd_modes = ap325rxa_lcdc_modes,
.num_modes = ARRAY_SIZE(ap325rxa_lcdc_modes),
.panel_cfg = {
.width = 152, /* 7.0 inch */
.height = 91,
.display_on = ap320_wvga_power_on,
.display_off = ap320_wvga_power_off,
},
.bl_info = {
.name = "sh_mobile_lcdc_bl",
.max_brightness = 1,
.set_brightness = ap320_wvga_set_brightness,
.get_brightness = ap320_wvga_get_brightness,
},
}
};
static struct resource lcdc_resources[] = {
[0] = {
.name = "LCDC",
.start = 0xfe940000, /* P4-only space */
.end = 0xfe942fff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 28,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device lcdc_device = {
.name = "sh_mobile_lcdc_fb",
.num_resources = ARRAY_SIZE(lcdc_resources),
.resource = lcdc_resources,
.dev = {
.platform_data = &lcdc_info,
},
};
static void camera_power(int val)
{
gpio_set_value(GPIO_PTZ5, val); /* RST_CAM/RSTB */
mdelay(10);
}
#ifdef CONFIG_I2C
/* support for the old ncm03j camera */
static unsigned char camera_ncm03j_magic[] =
{
0x87, 0x00, 0x88, 0x08, 0x89, 0x01, 0x8A, 0xE8,
0x1D, 0x00, 0x1E, 0x8A, 0x21, 0x00, 0x33, 0x36,
0x36, 0x60, 0x37, 0x08, 0x3B, 0x31, 0x44, 0x0F,
0x46, 0xF0, 0x4B, 0x28, 0x4C, 0x21, 0x4D, 0x55,
0x4E, 0x1B, 0x4F, 0xC7, 0x50, 0xFC, 0x51, 0x12,
0x58, 0x02, 0x66, 0xC0, 0x67, 0x46, 0x6B, 0xA0,
0x6C, 0x34, 0x7E, 0x25, 0x7F, 0x25, 0x8D, 0x0F,
0x92, 0x40, 0x93, 0x04, 0x94, 0x26, 0x95, 0x0A,
0x99, 0x03, 0x9A, 0xF0, 0x9B, 0x14, 0x9D, 0x7A,
0xC5, 0x02, 0xD6, 0x07, 0x59, 0x00, 0x5A, 0x1A,
0x5B, 0x2A, 0x5C, 0x37, 0x5D, 0x42, 0x5E, 0x56,
0xC8, 0x00, 0xC9, 0x1A, 0xCA, 0x2A, 0xCB, 0x37,
0xCC, 0x42, 0xCD, 0x56, 0xCE, 0x00, 0xCF, 0x1A,
0xD0, 0x2A, 0xD1, 0x37, 0xD2, 0x42, 0xD3, 0x56,
0x5F, 0x68, 0x60, 0x87, 0x61, 0xA3, 0x62, 0xBC,
0x63, 0xD4, 0x64, 0xEA, 0xD6, 0x0F,
};
static int camera_probe(void)
{
struct i2c_adapter *a = i2c_get_adapter(0);
struct i2c_msg msg;
int ret;
if (!a)
return -ENODEV;
camera_power(1);
msg.addr = 0x6e;
msg.buf = camera_ncm03j_magic;
msg.len = 2;
msg.flags = 0;
ret = i2c_transfer(a, &msg, 1);
camera_power(0);
return ret;
}
static int camera_set_capture(struct soc_camera_platform_info *info,
int enable)
{
struct i2c_adapter *a = i2c_get_adapter(0);
struct i2c_msg msg;
int ret = 0;
int i;
camera_power(0);
if (!enable)
return 0; /* no disable for now */
camera_power(1);
for (i = 0; i < ARRAY_SIZE(camera_ncm03j_magic); i += 2) {
u_int8_t buf[8];
msg.addr = 0x6e;
msg.buf = buf;
msg.len = 2;
msg.flags = 0;
buf[0] = camera_ncm03j_magic[i];
buf[1] = camera_ncm03j_magic[i + 1];
ret = (ret < 0) ? ret : i2c_transfer(a, &msg, 1);
}
return ret;
}
static int ap325rxa_camera_add(struct soc_camera_device *icd);
static void ap325rxa_camera_del(struct soc_camera_device *icd);
static struct soc_camera_platform_info camera_info = {
.format_name = "UYVY",
.format_depth = 16,
.format = {
.code = V4L2_MBUS_FMT_UYVY8_2X8,
.colorspace = V4L2_COLORSPACE_SMPTE170M,
.field = V4L2_FIELD_NONE,
.width = 640,
.height = 480,
},
.mbus_param = V4L2_MBUS_PCLK_SAMPLE_RISING | V4L2_MBUS_MASTER |
V4L2_MBUS_VSYNC_ACTIVE_HIGH | V4L2_MBUS_HSYNC_ACTIVE_HIGH |
V4L2_MBUS_DATA_ACTIVE_HIGH,
.mbus_type = V4L2_MBUS_PARALLEL,
.set_capture = camera_set_capture,
};
static struct soc_camera_link camera_link = {
.bus_id = 0,
.add_device = ap325rxa_camera_add,
.del_device = ap325rxa_camera_del,
.module_name = "soc_camera_platform",
.priv = &camera_info,
};
static struct platform_device *camera_device;
static void ap325rxa_camera_release(struct device *dev)
{
soc_camera_platform_release(&camera_device);
}
static int ap325rxa_camera_add(struct soc_camera_device *icd)
{
int ret = soc_camera_platform_add(icd, &camera_device, &camera_link,
ap325rxa_camera_release, 0);
if (ret < 0)
return ret;
ret = camera_probe();
if (ret < 0)
soc_camera_platform_del(icd, camera_device, &camera_link);
return ret;
}
static void ap325rxa_camera_del(struct soc_camera_device *icd)
{
soc_camera_platform_del(icd, camera_device, &camera_link);
}
#endif /* CONFIG_I2C */
static int ov7725_power(struct device *dev, int mode)
{
camera_power(0);
if (mode)
camera_power(1);
return 0;
}
static struct sh_mobile_ceu_info sh_mobile_ceu_info = {
.flags = SH_CEU_FLAG_USE_8BIT_BUS,
};
static struct resource ceu_resources[] = {
[0] = {
.name = "CEU",
.start = 0xfe910000,
.end = 0xfe91009f,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 52,
.flags = IORESOURCE_IRQ,
},
[2] = {
/* place holder for contiguous memory */
},
};
static struct platform_device ceu_device = {
.name = "sh_mobile_ceu",
.id = 0, /* "ceu0" clock */
.num_resources = ARRAY_SIZE(ceu_resources),
.resource = ceu_resources,
.dev = {
.platform_data = &sh_mobile_ceu_info,
},
};
static struct resource sdhi0_cn3_resources[] = {
[0] = {
.name = "SDHI0",
.start = 0x04ce0000,
.end = 0x04ce00ff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 100,
.flags = IORESOURCE_IRQ,
},
};
static struct sh_mobile_sdhi_info sdhi0_cn3_data = {
.tmio_caps = MMC_CAP_SDIO_IRQ,
};
static struct platform_device sdhi0_cn3_device = {
.name = "sh_mobile_sdhi",
.id = 0, /* "sdhi0" clock */
.num_resources = ARRAY_SIZE(sdhi0_cn3_resources),
.resource = sdhi0_cn3_resources,
.dev = {
.platform_data = &sdhi0_cn3_data,
},
};
static struct resource sdhi1_cn7_resources[] = {
[0] = {
.name = "SDHI1",
.start = 0x04cf0000,
.end = 0x04cf00ff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 23,
.flags = IORESOURCE_IRQ,
},
};
static struct sh_mobile_sdhi_info sdhi1_cn7_data = {
.tmio_caps = MMC_CAP_SDIO_IRQ,
};
static struct platform_device sdhi1_cn7_device = {
.name = "sh_mobile_sdhi",
.id = 1, /* "sdhi1" clock */
.num_resources = ARRAY_SIZE(sdhi1_cn7_resources),
.resource = sdhi1_cn7_resources,
.dev = {
.platform_data = &sdhi1_cn7_data,
},
};
static struct i2c_board_info __initdata ap325rxa_i2c_devices[] = {
{
I2C_BOARD_INFO("pcf8563", 0x51),
},
};
static struct i2c_board_info ap325rxa_i2c_camera[] = {
{
I2C_BOARD_INFO("ov772x", 0x21),
},
};
static struct ov772x_camera_info ov7725_info = {
.flags = OV772X_FLAG_VFLIP | OV772X_FLAG_HFLIP,
.edgectrl = OV772X_AUTO_EDGECTRL(0xf, 0),
};
static struct soc_camera_link ov7725_link = {
.bus_id = 0,
.power = ov7725_power,
.board_info = &ap325rxa_i2c_camera[0],
.i2c_adapter_id = 0,
.priv = &ov7725_info,
};
static struct platform_device ap325rxa_camera[] = {
{
.name = "soc-camera-pdrv",
.id = 0,
.dev = {
.platform_data = &ov7725_link,
},
}, {
.name = "soc-camera-pdrv",
.id = 1,
.dev = {
.platform_data = &camera_link,
},
},
};
static struct platform_device *ap325rxa_devices[] __initdata = {
&smsc9118_device,
&ap325rxa_nor_flash_device,
&lcdc_device,
&ceu_device,
&nand_flash_device,
&sdhi0_cn3_device,
&sdhi1_cn7_device,
&ap325rxa_camera[0],
&ap325rxa_camera[1],
};
extern char ap325rxa_sdram_enter_start;
extern char ap325rxa_sdram_enter_end;
extern char ap325rxa_sdram_leave_start;
extern char ap325rxa_sdram_leave_end;
static int __init ap325rxa_devices_setup(void)
{
/* register board specific self-refresh code */
sh_mobile_register_self_refresh(SUSP_SH_STANDBY | SUSP_SH_SF,
&ap325rxa_sdram_enter_start,
&ap325rxa_sdram_enter_end,
&ap325rxa_sdram_leave_start,
&ap325rxa_sdram_leave_end);
/* LD3 and LD4 LEDs */
gpio_request(GPIO_PTX5, NULL); /* RUN */
gpio_direction_output(GPIO_PTX5, 1);
gpio_export(GPIO_PTX5, 0);
gpio_request(GPIO_PTX4, NULL); /* INDICATOR */
gpio_direction_output(GPIO_PTX4, 0);
gpio_export(GPIO_PTX4, 0);
/* SW1 input */
gpio_request(GPIO_PTF7, NULL); /* MODE */
gpio_direction_input(GPIO_PTF7);
gpio_export(GPIO_PTF7, 0);
/* LCDC */
gpio_request(GPIO_FN_LCDD15, NULL);
gpio_request(GPIO_FN_LCDD14, NULL);
gpio_request(GPIO_FN_LCDD13, NULL);
gpio_request(GPIO_FN_LCDD12, NULL);
gpio_request(GPIO_FN_LCDD11, NULL);
gpio_request(GPIO_FN_LCDD10, NULL);
gpio_request(GPIO_FN_LCDD9, NULL);
gpio_request(GPIO_FN_LCDD8, NULL);
gpio_request(GPIO_FN_LCDD7, NULL);
gpio_request(GPIO_FN_LCDD6, NULL);
gpio_request(GPIO_FN_LCDD5, NULL);
gpio_request(GPIO_FN_LCDD4, NULL);
gpio_request(GPIO_FN_LCDD3, NULL);
gpio_request(GPIO_FN_LCDD2, NULL);
gpio_request(GPIO_FN_LCDD1, NULL);
gpio_request(GPIO_FN_LCDD0, NULL);
gpio_request(GPIO_FN_LCDLCLK_PTR, NULL);
gpio_request(GPIO_FN_LCDDCK, NULL);
gpio_request(GPIO_FN_LCDVEPWC, NULL);
gpio_request(GPIO_FN_LCDVCPWC, NULL);
gpio_request(GPIO_FN_LCDVSYN, NULL);
gpio_request(GPIO_FN_LCDHSYN, NULL);
gpio_request(GPIO_FN_LCDDISP, NULL);
gpio_request(GPIO_FN_LCDDON, NULL);
/* LCD backlight */
gpio_request(GPIO_PTS3, NULL);
gpio_direction_output(GPIO_PTS3, 1);
/* CEU */
gpio_request(GPIO_FN_VIO_CLK2, NULL);
gpio_request(GPIO_FN_VIO_VD2, NULL);
gpio_request(GPIO_FN_VIO_HD2, NULL);
gpio_request(GPIO_FN_VIO_FLD, NULL);
gpio_request(GPIO_FN_VIO_CKO, NULL);
gpio_request(GPIO_FN_VIO_D15, NULL);
gpio_request(GPIO_FN_VIO_D14, NULL);
gpio_request(GPIO_FN_VIO_D13, NULL);
gpio_request(GPIO_FN_VIO_D12, NULL);
gpio_request(GPIO_FN_VIO_D11, NULL);
gpio_request(GPIO_FN_VIO_D10, NULL);
gpio_request(GPIO_FN_VIO_D9, NULL);
gpio_request(GPIO_FN_VIO_D8, NULL);
gpio_request(GPIO_PTZ7, NULL);
gpio_direction_output(GPIO_PTZ7, 0); /* OE_CAM */
gpio_request(GPIO_PTZ6, NULL);
gpio_direction_output(GPIO_PTZ6, 0); /* STBY_CAM */
gpio_request(GPIO_PTZ5, NULL);
gpio_direction_output(GPIO_PTZ5, 0); /* RST_CAM */
gpio_request(GPIO_PTZ4, NULL);
gpio_direction_output(GPIO_PTZ4, 0); /* SADDR */
__raw_writew(__raw_readw(PORT_MSELCRB) & ~0x0001, PORT_MSELCRB);
/* FLCTL */
gpio_request(GPIO_FN_FCE, NULL);
gpio_request(GPIO_FN_NAF7, NULL);
gpio_request(GPIO_FN_NAF6, NULL);
gpio_request(GPIO_FN_NAF5, NULL);
gpio_request(GPIO_FN_NAF4, NULL);
gpio_request(GPIO_FN_NAF3, NULL);
gpio_request(GPIO_FN_NAF2, NULL);
gpio_request(GPIO_FN_NAF1, NULL);
gpio_request(GPIO_FN_NAF0, NULL);
gpio_request(GPIO_FN_FCDE, NULL);
gpio_request(GPIO_FN_FOE, NULL);
gpio_request(GPIO_FN_FSC, NULL);
gpio_request(GPIO_FN_FWE, NULL);
gpio_request(GPIO_FN_FRB, NULL);
__raw_writew(0, PORT_HIZCRC);
__raw_writew(0xFFFF, PORT_DRVCRA);
__raw_writew(0xFFFF, PORT_DRVCRB);
platform_resource_setup_memory(&ceu_device, "ceu", 4 << 20);
/* SDHI0 - CN3 - SD CARD */
gpio_request(GPIO_FN_SDHI0CD_PTD, NULL);
gpio_request(GPIO_FN_SDHI0WP_PTD, NULL);
gpio_request(GPIO_FN_SDHI0D3_PTD, NULL);
gpio_request(GPIO_FN_SDHI0D2_PTD, NULL);
gpio_request(GPIO_FN_SDHI0D1_PTD, NULL);
gpio_request(GPIO_FN_SDHI0D0_PTD, NULL);
gpio_request(GPIO_FN_SDHI0CMD_PTD, NULL);
gpio_request(GPIO_FN_SDHI0CLK_PTD, NULL);
/* SDHI1 - CN7 - MICRO SD CARD */
gpio_request(GPIO_FN_SDHI1CD, NULL);
gpio_request(GPIO_FN_SDHI1D3, NULL);
gpio_request(GPIO_FN_SDHI1D2, NULL);
gpio_request(GPIO_FN_SDHI1D1, NULL);
gpio_request(GPIO_FN_SDHI1D0, NULL);
gpio_request(GPIO_FN_SDHI1CMD, NULL);
gpio_request(GPIO_FN_SDHI1CLK, NULL);
i2c_register_board_info(0, ap325rxa_i2c_devices,
ARRAY_SIZE(ap325rxa_i2c_devices));
return platform_add_devices(ap325rxa_devices,
ARRAY_SIZE(ap325rxa_devices));
}
arch_initcall(ap325rxa_devices_setup);
/* Return the board specific boot mode pin configuration */
static int ap325rxa_mode_pins(void)
{
/* MD0=0, MD1=0, MD2=0: Clock Mode 0
* MD3=0: 16-bit Area0 Bus Width
* MD5=1: Little Endian
* TSTMD=1, MD8=1: Test Mode Disabled
*/
return MODE_PIN5 | MODE_PIN8;
}
static struct sh_machine_vector mv_ap325rxa __initmv = {
.mv_name = "AP-325RXA",
.mv_mode_pins = ap325rxa_mode_pins,
};
| gpl-2.0 |
TheTypoMaster/ubuntu-utopic | drivers/watchdog/f71808e_wdt.c | 4409 | 20887 | /***************************************************************************
* Copyright (C) 2006 by Hans Edgington <hans@edgington.nl> *
* Copyright (C) 2007-2009 Hans de Goede <hdegoede@redhat.com> *
* Copyright (C) 2010 Giel van Schijndel <me@mortis.eu> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 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/err.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/ioport.h>
#include <linux/miscdevice.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/notifier.h>
#include <linux/reboot.h>
#include <linux/uaccess.h>
#include <linux/watchdog.h>
#define DRVNAME "f71808e_wdt"
#define SIO_F71808FG_LD_WDT 0x07 /* Watchdog timer logical device */
#define SIO_UNLOCK_KEY 0x87 /* Key to enable Super-I/O */
#define SIO_LOCK_KEY 0xAA /* Key to diasble Super-I/O */
#define SIO_REG_LDSEL 0x07 /* Logical device select */
#define SIO_REG_DEVID 0x20 /* Device ID (2 bytes) */
#define SIO_REG_DEVREV 0x22 /* Device revision */
#define SIO_REG_MANID 0x23 /* Fintek ID (2 bytes) */
#define SIO_REG_ROM_ADDR_SEL 0x27 /* ROM address select */
#define SIO_REG_MFUNCT1 0x29 /* Multi function select 1 */
#define SIO_REG_MFUNCT2 0x2a /* Multi function select 2 */
#define SIO_REG_MFUNCT3 0x2b /* Multi function select 3 */
#define SIO_REG_ENABLE 0x30 /* Logical device enable */
#define SIO_REG_ADDR 0x60 /* Logical device address (2 bytes) */
#define SIO_FINTEK_ID 0x1934 /* Manufacturers ID */
#define SIO_F71808_ID 0x0901 /* Chipset ID */
#define SIO_F71858_ID 0x0507 /* Chipset ID */
#define SIO_F71862_ID 0x0601 /* Chipset ID */
#define SIO_F71869_ID 0x0814 /* Chipset ID */
#define SIO_F71869A_ID 0x1007 /* Chipset ID */
#define SIO_F71882_ID 0x0541 /* Chipset ID */
#define SIO_F71889_ID 0x0723 /* Chipset ID */
#define F71808FG_REG_WDO_CONF 0xf0
#define F71808FG_REG_WDT_CONF 0xf5
#define F71808FG_REG_WD_TIME 0xf6
#define F71808FG_FLAG_WDOUT_EN 7
#define F71808FG_FLAG_WDTMOUT_STS 5
#define F71808FG_FLAG_WD_EN 5
#define F71808FG_FLAG_WD_PULSE 4
#define F71808FG_FLAG_WD_UNIT 3
/* Default values */
#define WATCHDOG_TIMEOUT 60 /* 1 minute default timeout */
#define WATCHDOG_MAX_TIMEOUT (60 * 255)
#define WATCHDOG_PULSE_WIDTH 125 /* 125 ms, default pulse width for
watchdog signal */
#define WATCHDOG_F71862FG_PIN 63 /* default watchdog reset output
pin number 63 */
static unsigned short force_id;
module_param(force_id, ushort, 0);
MODULE_PARM_DESC(force_id, "Override the detected device ID");
static const int max_timeout = WATCHDOG_MAX_TIMEOUT;
static int timeout = WATCHDOG_TIMEOUT; /* default timeout in seconds */
module_param(timeout, int, 0);
MODULE_PARM_DESC(timeout,
"Watchdog timeout in seconds. 1<= timeout <="
__MODULE_STRING(WATCHDOG_MAX_TIMEOUT) " (default="
__MODULE_STRING(WATCHDOG_TIMEOUT) ")");
static unsigned int pulse_width = WATCHDOG_PULSE_WIDTH;
module_param(pulse_width, uint, 0);
MODULE_PARM_DESC(pulse_width,
"Watchdog signal pulse width. 0(=level), 1 ms, 25 ms, 125 ms or 5000 ms"
" (default=" __MODULE_STRING(WATCHDOG_PULSE_WIDTH) ")");
static unsigned int f71862fg_pin = WATCHDOG_F71862FG_PIN;
module_param(f71862fg_pin, uint, 0);
MODULE_PARM_DESC(f71862fg_pin,
"Watchdog f71862fg reset output pin configuration. Choose pin 56 or 63"
" (default=" __MODULE_STRING(WATCHDOG_F71862FG_PIN)")");
static bool nowayout = WATCHDOG_NOWAYOUT;
module_param(nowayout, bool, 0444);
MODULE_PARM_DESC(nowayout, "Disable watchdog shutdown on close");
static unsigned int start_withtimeout;
module_param(start_withtimeout, uint, 0);
MODULE_PARM_DESC(start_withtimeout, "Start watchdog timer on module load with"
" given initial timeout. Zero (default) disables this feature.");
enum chips { f71808fg, f71858fg, f71862fg, f71869, f71882fg, f71889fg };
static const char *f71808e_names[] = {
"f71808fg",
"f71858fg",
"f71862fg",
"f71869",
"f71882fg",
"f71889fg",
};
/* Super-I/O Function prototypes */
static inline int superio_inb(int base, int reg);
static inline int superio_inw(int base, int reg);
static inline void superio_outb(int base, int reg, u8 val);
static inline void superio_set_bit(int base, int reg, int bit);
static inline void superio_clear_bit(int base, int reg, int bit);
static inline int superio_enter(int base);
static inline void superio_select(int base, int ld);
static inline void superio_exit(int base);
struct watchdog_data {
unsigned short sioaddr;
enum chips type;
unsigned long opened;
struct mutex lock;
char expect_close;
struct watchdog_info ident;
unsigned short timeout;
u8 timer_val; /* content for the wd_time register */
char minutes_mode;
u8 pulse_val; /* pulse width flag */
char pulse_mode; /* enable pulse output mode? */
char caused_reboot; /* last reboot was by the watchdog */
};
static struct watchdog_data watchdog = {
.lock = __MUTEX_INITIALIZER(watchdog.lock),
};
/* Super I/O functions */
static inline int superio_inb(int base, int reg)
{
outb(reg, base);
return inb(base + 1);
}
static int superio_inw(int base, int reg)
{
int val;
val = superio_inb(base, reg) << 8;
val |= superio_inb(base, reg + 1);
return val;
}
static inline void superio_outb(int base, int reg, u8 val)
{
outb(reg, base);
outb(val, base + 1);
}
static inline void superio_set_bit(int base, int reg, int bit)
{
unsigned long val = superio_inb(base, reg);
__set_bit(bit, &val);
superio_outb(base, reg, val);
}
static inline void superio_clear_bit(int base, int reg, int bit)
{
unsigned long val = superio_inb(base, reg);
__clear_bit(bit, &val);
superio_outb(base, reg, val);
}
static inline int superio_enter(int base)
{
/* Don't step on other drivers' I/O space by accident */
if (!request_muxed_region(base, 2, DRVNAME)) {
pr_err("I/O address 0x%04x already in use\n", (int)base);
return -EBUSY;
}
/* according to the datasheet the key must be sent twice! */
outb(SIO_UNLOCK_KEY, base);
outb(SIO_UNLOCK_KEY, base);
return 0;
}
static inline void superio_select(int base, int ld)
{
outb(SIO_REG_LDSEL, base);
outb(ld, base + 1);
}
static inline void superio_exit(int base)
{
outb(SIO_LOCK_KEY, base);
release_region(base, 2);
}
static int watchdog_set_timeout(int timeout)
{
if (timeout <= 0
|| timeout > max_timeout) {
pr_err("watchdog timeout out of range\n");
return -EINVAL;
}
mutex_lock(&watchdog.lock);
watchdog.timeout = timeout;
if (timeout > 0xff) {
watchdog.timer_val = DIV_ROUND_UP(timeout, 60);
watchdog.minutes_mode = true;
} else {
watchdog.timer_val = timeout;
watchdog.minutes_mode = false;
}
mutex_unlock(&watchdog.lock);
return 0;
}
static int watchdog_set_pulse_width(unsigned int pw)
{
int err = 0;
mutex_lock(&watchdog.lock);
if (pw <= 1) {
watchdog.pulse_val = 0;
} else if (pw <= 25) {
watchdog.pulse_val = 1;
} else if (pw <= 125) {
watchdog.pulse_val = 2;
} else if (pw <= 5000) {
watchdog.pulse_val = 3;
} else {
pr_err("pulse width out of range\n");
err = -EINVAL;
goto exit_unlock;
}
watchdog.pulse_mode = pw;
exit_unlock:
mutex_unlock(&watchdog.lock);
return err;
}
static int watchdog_keepalive(void)
{
int err = 0;
mutex_lock(&watchdog.lock);
err = superio_enter(watchdog.sioaddr);
if (err)
goto exit_unlock;
superio_select(watchdog.sioaddr, SIO_F71808FG_LD_WDT);
if (watchdog.minutes_mode)
/* select minutes for timer units */
superio_set_bit(watchdog.sioaddr, F71808FG_REG_WDT_CONF,
F71808FG_FLAG_WD_UNIT);
else
/* select seconds for timer units */
superio_clear_bit(watchdog.sioaddr, F71808FG_REG_WDT_CONF,
F71808FG_FLAG_WD_UNIT);
/* Set timer value */
superio_outb(watchdog.sioaddr, F71808FG_REG_WD_TIME,
watchdog.timer_val);
superio_exit(watchdog.sioaddr);
exit_unlock:
mutex_unlock(&watchdog.lock);
return err;
}
static int f71862fg_pin_configure(unsigned short ioaddr)
{
/* When ioaddr is non-zero the calling function has to take care of
mutex handling and superio preparation! */
if (f71862fg_pin == 63) {
if (ioaddr) {
/* SPI must be disabled first to use this pin! */
superio_clear_bit(ioaddr, SIO_REG_ROM_ADDR_SEL, 6);
superio_set_bit(ioaddr, SIO_REG_MFUNCT3, 4);
}
} else if (f71862fg_pin == 56) {
if (ioaddr)
superio_set_bit(ioaddr, SIO_REG_MFUNCT1, 1);
} else {
pr_err("Invalid argument f71862fg_pin=%d\n", f71862fg_pin);
return -EINVAL;
}
return 0;
}
static int watchdog_start(void)
{
/* Make sure we don't die as soon as the watchdog is enabled below */
int err = watchdog_keepalive();
if (err)
return err;
mutex_lock(&watchdog.lock);
err = superio_enter(watchdog.sioaddr);
if (err)
goto exit_unlock;
superio_select(watchdog.sioaddr, SIO_F71808FG_LD_WDT);
/* Watchdog pin configuration */
switch (watchdog.type) {
case f71808fg:
/* Set pin 21 to GPIO23/WDTRST#, then to WDTRST# */
superio_clear_bit(watchdog.sioaddr, SIO_REG_MFUNCT2, 3);
superio_clear_bit(watchdog.sioaddr, SIO_REG_MFUNCT3, 3);
break;
case f71862fg:
err = f71862fg_pin_configure(watchdog.sioaddr);
if (err)
goto exit_superio;
break;
case f71869:
/* GPIO14 --> WDTRST# */
superio_clear_bit(watchdog.sioaddr, SIO_REG_MFUNCT1, 4);
break;
case f71882fg:
/* Set pin 56 to WDTRST# */
superio_set_bit(watchdog.sioaddr, SIO_REG_MFUNCT1, 1);
break;
case f71889fg:
/* set pin 40 to WDTRST# */
superio_outb(watchdog.sioaddr, SIO_REG_MFUNCT3,
superio_inb(watchdog.sioaddr, SIO_REG_MFUNCT3) & 0xcf);
break;
default:
/*
* 'default' label to shut up the compiler and catch
* programmer errors
*/
err = -ENODEV;
goto exit_superio;
}
superio_select(watchdog.sioaddr, SIO_F71808FG_LD_WDT);
superio_set_bit(watchdog.sioaddr, SIO_REG_ENABLE, 0);
superio_set_bit(watchdog.sioaddr, F71808FG_REG_WDO_CONF,
F71808FG_FLAG_WDOUT_EN);
superio_set_bit(watchdog.sioaddr, F71808FG_REG_WDT_CONF,
F71808FG_FLAG_WD_EN);
if (watchdog.pulse_mode) {
/* Select "pulse" output mode with given duration */
u8 wdt_conf = superio_inb(watchdog.sioaddr,
F71808FG_REG_WDT_CONF);
/* Set WD_PSWIDTH bits (1:0) */
wdt_conf = (wdt_conf & 0xfc) | (watchdog.pulse_val & 0x03);
/* Set WD_PULSE to "pulse" mode */
wdt_conf |= BIT(F71808FG_FLAG_WD_PULSE);
superio_outb(watchdog.sioaddr, F71808FG_REG_WDT_CONF,
wdt_conf);
} else {
/* Select "level" output mode */
superio_clear_bit(watchdog.sioaddr, F71808FG_REG_WDT_CONF,
F71808FG_FLAG_WD_PULSE);
}
exit_superio:
superio_exit(watchdog.sioaddr);
exit_unlock:
mutex_unlock(&watchdog.lock);
return err;
}
static int watchdog_stop(void)
{
int err = 0;
mutex_lock(&watchdog.lock);
err = superio_enter(watchdog.sioaddr);
if (err)
goto exit_unlock;
superio_select(watchdog.sioaddr, SIO_F71808FG_LD_WDT);
superio_clear_bit(watchdog.sioaddr, F71808FG_REG_WDT_CONF,
F71808FG_FLAG_WD_EN);
superio_exit(watchdog.sioaddr);
exit_unlock:
mutex_unlock(&watchdog.lock);
return err;
}
static int watchdog_get_status(void)
{
int status = 0;
mutex_lock(&watchdog.lock);
status = (watchdog.caused_reboot) ? WDIOF_CARDRESET : 0;
mutex_unlock(&watchdog.lock);
return status;
}
static bool watchdog_is_running(void)
{
/*
* if we fail to determine the watchdog's status assume it to be
* running to be on the safe side
*/
bool is_running = true;
mutex_lock(&watchdog.lock);
if (superio_enter(watchdog.sioaddr))
goto exit_unlock;
superio_select(watchdog.sioaddr, SIO_F71808FG_LD_WDT);
is_running = (superio_inb(watchdog.sioaddr, SIO_REG_ENABLE) & BIT(0))
&& (superio_inb(watchdog.sioaddr, F71808FG_REG_WDT_CONF)
& F71808FG_FLAG_WD_EN);
superio_exit(watchdog.sioaddr);
exit_unlock:
mutex_unlock(&watchdog.lock);
return is_running;
}
/* /dev/watchdog api */
static int watchdog_open(struct inode *inode, struct file *file)
{
int err;
/* If the watchdog is alive we don't need to start it again */
if (test_and_set_bit(0, &watchdog.opened))
return -EBUSY;
err = watchdog_start();
if (err) {
clear_bit(0, &watchdog.opened);
return err;
}
if (nowayout)
__module_get(THIS_MODULE);
watchdog.expect_close = 0;
return nonseekable_open(inode, file);
}
static int watchdog_release(struct inode *inode, struct file *file)
{
clear_bit(0, &watchdog.opened);
if (!watchdog.expect_close) {
watchdog_keepalive();
pr_crit("Unexpected close, not stopping watchdog!\n");
} else if (!nowayout) {
watchdog_stop();
}
return 0;
}
/*
* watchdog_write:
* @file: file handle to the watchdog
* @buf: buffer to write
* @count: count of bytes
* @ppos: pointer to the position to write. No seeks allowed
*
* A write to a watchdog device is defined as a keepalive signal. Any
* write of data will do, as we we don't define content meaning.
*/
static ssize_t watchdog_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
if (count) {
if (!nowayout) {
size_t i;
/* In case it was set long ago */
bool expect_close = false;
for (i = 0; i != count; i++) {
char c;
if (get_user(c, buf + i))
return -EFAULT;
expect_close = (c == 'V');
}
/* Properly order writes across fork()ed processes */
mutex_lock(&watchdog.lock);
watchdog.expect_close = expect_close;
mutex_unlock(&watchdog.lock);
}
/* someone wrote to us, we should restart timer */
watchdog_keepalive();
}
return count;
}
/*
* watchdog_ioctl:
* @inode: inode of the device
* @file: file handle to the device
* @cmd: watchdog command
* @arg: argument pointer
*
* The watchdog API defines a common set of functions for all watchdogs
* according to their available features.
*/
static long watchdog_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
int status;
int new_options;
int new_timeout;
union {
struct watchdog_info __user *ident;
int __user *i;
} uarg;
uarg.i = (int __user *)arg;
switch (cmd) {
case WDIOC_GETSUPPORT:
return copy_to_user(uarg.ident, &watchdog.ident,
sizeof(watchdog.ident)) ? -EFAULT : 0;
case WDIOC_GETSTATUS:
status = watchdog_get_status();
if (status < 0)
return status;
return put_user(status, uarg.i);
case WDIOC_GETBOOTSTATUS:
return put_user(0, uarg.i);
case WDIOC_SETOPTIONS:
if (get_user(new_options, uarg.i))
return -EFAULT;
if (new_options & WDIOS_DISABLECARD)
watchdog_stop();
if (new_options & WDIOS_ENABLECARD)
return watchdog_start();
case WDIOC_KEEPALIVE:
watchdog_keepalive();
return 0;
case WDIOC_SETTIMEOUT:
if (get_user(new_timeout, uarg.i))
return -EFAULT;
if (watchdog_set_timeout(new_timeout))
return -EINVAL;
watchdog_keepalive();
/* Fall */
case WDIOC_GETTIMEOUT:
return put_user(watchdog.timeout, uarg.i);
default:
return -ENOTTY;
}
}
static int watchdog_notify_sys(struct notifier_block *this, unsigned long code,
void *unused)
{
if (code == SYS_DOWN || code == SYS_HALT)
watchdog_stop();
return NOTIFY_DONE;
}
static const struct file_operations watchdog_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.open = watchdog_open,
.release = watchdog_release,
.write = watchdog_write,
.unlocked_ioctl = watchdog_ioctl,
};
static struct miscdevice watchdog_miscdev = {
.minor = WATCHDOG_MINOR,
.name = "watchdog",
.fops = &watchdog_fops,
};
static struct notifier_block watchdog_notifier = {
.notifier_call = watchdog_notify_sys,
};
static int __init watchdog_init(int sioaddr)
{
int wdt_conf, err = 0;
/* No need to lock watchdog.lock here because no entry points
* into the module have been registered yet.
*/
watchdog.sioaddr = sioaddr;
watchdog.ident.options = WDIOC_SETTIMEOUT
| WDIOF_MAGICCLOSE
| WDIOF_KEEPALIVEPING;
snprintf(watchdog.ident.identity,
sizeof(watchdog.ident.identity), "%s watchdog",
f71808e_names[watchdog.type]);
err = superio_enter(sioaddr);
if (err)
return err;
superio_select(watchdog.sioaddr, SIO_F71808FG_LD_WDT);
wdt_conf = superio_inb(sioaddr, F71808FG_REG_WDT_CONF);
watchdog.caused_reboot = wdt_conf & F71808FG_FLAG_WDTMOUT_STS;
superio_exit(sioaddr);
err = watchdog_set_timeout(timeout);
if (err)
return err;
err = watchdog_set_pulse_width(pulse_width);
if (err)
return err;
err = register_reboot_notifier(&watchdog_notifier);
if (err)
return err;
err = misc_register(&watchdog_miscdev);
if (err) {
pr_err("cannot register miscdev on minor=%d\n",
watchdog_miscdev.minor);
goto exit_reboot;
}
if (start_withtimeout) {
if (start_withtimeout <= 0
|| start_withtimeout > max_timeout) {
pr_err("starting timeout out of range\n");
err = -EINVAL;
goto exit_miscdev;
}
err = watchdog_start();
if (err) {
pr_err("cannot start watchdog timer\n");
goto exit_miscdev;
}
mutex_lock(&watchdog.lock);
err = superio_enter(sioaddr);
if (err)
goto exit_unlock;
superio_select(watchdog.sioaddr, SIO_F71808FG_LD_WDT);
if (start_withtimeout > 0xff) {
/* select minutes for timer units */
superio_set_bit(sioaddr, F71808FG_REG_WDT_CONF,
F71808FG_FLAG_WD_UNIT);
superio_outb(sioaddr, F71808FG_REG_WD_TIME,
DIV_ROUND_UP(start_withtimeout, 60));
} else {
/* select seconds for timer units */
superio_clear_bit(sioaddr, F71808FG_REG_WDT_CONF,
F71808FG_FLAG_WD_UNIT);
superio_outb(sioaddr, F71808FG_REG_WD_TIME,
start_withtimeout);
}
superio_exit(sioaddr);
mutex_unlock(&watchdog.lock);
if (nowayout)
__module_get(THIS_MODULE);
pr_info("watchdog started with initial timeout of %u sec\n",
start_withtimeout);
}
return 0;
exit_unlock:
mutex_unlock(&watchdog.lock);
exit_miscdev:
misc_deregister(&watchdog_miscdev);
exit_reboot:
unregister_reboot_notifier(&watchdog_notifier);
return err;
}
static int __init f71808e_find(int sioaddr)
{
u16 devid;
int err = superio_enter(sioaddr);
if (err)
return err;
devid = superio_inw(sioaddr, SIO_REG_MANID);
if (devid != SIO_FINTEK_ID) {
pr_debug("Not a Fintek device\n");
err = -ENODEV;
goto exit;
}
devid = force_id ? force_id : superio_inw(sioaddr, SIO_REG_DEVID);
switch (devid) {
case SIO_F71808_ID:
watchdog.type = f71808fg;
break;
case SIO_F71862_ID:
watchdog.type = f71862fg;
err = f71862fg_pin_configure(0); /* validate module parameter */
break;
case SIO_F71869_ID:
case SIO_F71869A_ID:
watchdog.type = f71869;
break;
case SIO_F71882_ID:
watchdog.type = f71882fg;
break;
case SIO_F71889_ID:
watchdog.type = f71889fg;
break;
case SIO_F71858_ID:
/* Confirmed (by datasheet) not to have a watchdog. */
err = -ENODEV;
goto exit;
default:
pr_info("Unrecognized Fintek device: %04x\n",
(unsigned int)devid);
err = -ENODEV;
goto exit;
}
pr_info("Found %s watchdog chip, revision %d\n",
f71808e_names[watchdog.type],
(int)superio_inb(sioaddr, SIO_REG_DEVREV));
exit:
superio_exit(sioaddr);
return err;
}
static int __init f71808e_init(void)
{
static const unsigned short addrs[] = { 0x2e, 0x4e };
int err = -ENODEV;
int i;
for (i = 0; i < ARRAY_SIZE(addrs); i++) {
err = f71808e_find(addrs[i]);
if (err == 0)
break;
}
if (i == ARRAY_SIZE(addrs))
return err;
return watchdog_init(addrs[i]);
}
static void __exit f71808e_exit(void)
{
if (watchdog_is_running()) {
pr_warn("Watchdog timer still running, stopping it\n");
watchdog_stop();
}
misc_deregister(&watchdog_miscdev);
unregister_reboot_notifier(&watchdog_notifier);
}
MODULE_DESCRIPTION("F71808E Watchdog Driver");
MODULE_AUTHOR("Giel van Schijndel <me@mortis.eu>");
MODULE_LICENSE("GPL");
module_init(f71808e_init);
module_exit(f71808e_exit);
| gpl-2.0 |
randomstuffpaul/android_kernel_samsung_klimtwifi | drivers/pci/xen-pcifront.c | 4921 | 27189 | /*
* Xen PCI Frontend.
*
* Author: Ryan Wilson <hap9@epoch.ncsc.mil>
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <xen/xenbus.h>
#include <xen/events.h>
#include <xen/grant_table.h>
#include <xen/page.h>
#include <linux/spinlock.h>
#include <linux/pci.h>
#include <linux/msi.h>
#include <xen/interface/io/pciif.h>
#include <asm/xen/pci.h>
#include <linux/interrupt.h>
#include <linux/atomic.h>
#include <linux/workqueue.h>
#include <linux/bitops.h>
#include <linux/time.h>
#define INVALID_GRANT_REF (0)
#define INVALID_EVTCHN (-1)
struct pci_bus_entry {
struct list_head list;
struct pci_bus *bus;
};
#define _PDEVB_op_active (0)
#define PDEVB_op_active (1 << (_PDEVB_op_active))
struct pcifront_device {
struct xenbus_device *xdev;
struct list_head root_buses;
int evtchn;
int gnt_ref;
int irq;
/* Lock this when doing any operations in sh_info */
spinlock_t sh_info_lock;
struct xen_pci_sharedinfo *sh_info;
struct work_struct op_work;
unsigned long flags;
};
struct pcifront_sd {
int domain;
struct pcifront_device *pdev;
};
static inline struct pcifront_device *
pcifront_get_pdev(struct pcifront_sd *sd)
{
return sd->pdev;
}
static inline void pcifront_init_sd(struct pcifront_sd *sd,
unsigned int domain, unsigned int bus,
struct pcifront_device *pdev)
{
sd->domain = domain;
sd->pdev = pdev;
}
static DEFINE_SPINLOCK(pcifront_dev_lock);
static struct pcifront_device *pcifront_dev;
static int verbose_request;
module_param(verbose_request, int, 0644);
static int errno_to_pcibios_err(int errno)
{
switch (errno) {
case XEN_PCI_ERR_success:
return PCIBIOS_SUCCESSFUL;
case XEN_PCI_ERR_dev_not_found:
return PCIBIOS_DEVICE_NOT_FOUND;
case XEN_PCI_ERR_invalid_offset:
case XEN_PCI_ERR_op_failed:
return PCIBIOS_BAD_REGISTER_NUMBER;
case XEN_PCI_ERR_not_implemented:
return PCIBIOS_FUNC_NOT_SUPPORTED;
case XEN_PCI_ERR_access_denied:
return PCIBIOS_SET_FAILED;
}
return errno;
}
static inline void schedule_pcifront_aer_op(struct pcifront_device *pdev)
{
if (test_bit(_XEN_PCIB_active, (unsigned long *)&pdev->sh_info->flags)
&& !test_and_set_bit(_PDEVB_op_active, &pdev->flags)) {
dev_dbg(&pdev->xdev->dev, "schedule aer frontend job\n");
schedule_work(&pdev->op_work);
}
}
static int do_pci_op(struct pcifront_device *pdev, struct xen_pci_op *op)
{
int err = 0;
struct xen_pci_op *active_op = &pdev->sh_info->op;
unsigned long irq_flags;
evtchn_port_t port = pdev->evtchn;
unsigned irq = pdev->irq;
s64 ns, ns_timeout;
struct timeval tv;
spin_lock_irqsave(&pdev->sh_info_lock, irq_flags);
memcpy(active_op, op, sizeof(struct xen_pci_op));
/* Go */
wmb();
set_bit(_XEN_PCIF_active, (unsigned long *)&pdev->sh_info->flags);
notify_remote_via_evtchn(port);
/*
* We set a poll timeout of 3 seconds but give up on return after
* 2 seconds. It is better to time out too late rather than too early
* (in the latter case we end up continually re-executing poll() with a
* timeout in the past). 1s difference gives plenty of slack for error.
*/
do_gettimeofday(&tv);
ns_timeout = timeval_to_ns(&tv) + 2 * (s64)NSEC_PER_SEC;
xen_clear_irq_pending(irq);
while (test_bit(_XEN_PCIF_active,
(unsigned long *)&pdev->sh_info->flags)) {
xen_poll_irq_timeout(irq, jiffies + 3*HZ);
xen_clear_irq_pending(irq);
do_gettimeofday(&tv);
ns = timeval_to_ns(&tv);
if (ns > ns_timeout) {
dev_err(&pdev->xdev->dev,
"pciback not responding!!!\n");
clear_bit(_XEN_PCIF_active,
(unsigned long *)&pdev->sh_info->flags);
err = XEN_PCI_ERR_dev_not_found;
goto out;
}
}
/*
* We might lose backend service request since we
* reuse same evtchn with pci_conf backend response. So re-schedule
* aer pcifront service.
*/
if (test_bit(_XEN_PCIB_active,
(unsigned long *)&pdev->sh_info->flags)) {
dev_err(&pdev->xdev->dev,
"schedule aer pcifront service\n");
schedule_pcifront_aer_op(pdev);
}
memcpy(op, active_op, sizeof(struct xen_pci_op));
err = op->err;
out:
spin_unlock_irqrestore(&pdev->sh_info_lock, irq_flags);
return err;
}
/* Access to this function is spinlocked in drivers/pci/access.c */
static int pcifront_bus_read(struct pci_bus *bus, unsigned int devfn,
int where, int size, u32 *val)
{
int err = 0;
struct xen_pci_op op = {
.cmd = XEN_PCI_OP_conf_read,
.domain = pci_domain_nr(bus),
.bus = bus->number,
.devfn = devfn,
.offset = where,
.size = size,
};
struct pcifront_sd *sd = bus->sysdata;
struct pcifront_device *pdev = pcifront_get_pdev(sd);
if (verbose_request)
dev_info(&pdev->xdev->dev,
"read dev=%04x:%02x:%02x.%d - offset %x size %d\n",
pci_domain_nr(bus), bus->number, PCI_SLOT(devfn),
PCI_FUNC(devfn), where, size);
err = do_pci_op(pdev, &op);
if (likely(!err)) {
if (verbose_request)
dev_info(&pdev->xdev->dev, "read got back value %x\n",
op.value);
*val = op.value;
} else if (err == -ENODEV) {
/* No device here, pretend that it just returned 0 */
err = 0;
*val = 0;
}
return errno_to_pcibios_err(err);
}
/* Access to this function is spinlocked in drivers/pci/access.c */
static int pcifront_bus_write(struct pci_bus *bus, unsigned int devfn,
int where, int size, u32 val)
{
struct xen_pci_op op = {
.cmd = XEN_PCI_OP_conf_write,
.domain = pci_domain_nr(bus),
.bus = bus->number,
.devfn = devfn,
.offset = where,
.size = size,
.value = val,
};
struct pcifront_sd *sd = bus->sysdata;
struct pcifront_device *pdev = pcifront_get_pdev(sd);
if (verbose_request)
dev_info(&pdev->xdev->dev,
"write dev=%04x:%02x:%02x.%d - "
"offset %x size %d val %x\n",
pci_domain_nr(bus), bus->number,
PCI_SLOT(devfn), PCI_FUNC(devfn), where, size, val);
return errno_to_pcibios_err(do_pci_op(pdev, &op));
}
struct pci_ops pcifront_bus_ops = {
.read = pcifront_bus_read,
.write = pcifront_bus_write,
};
#ifdef CONFIG_PCI_MSI
static int pci_frontend_enable_msix(struct pci_dev *dev,
int vector[], int nvec)
{
int err;
int i;
struct xen_pci_op op = {
.cmd = XEN_PCI_OP_enable_msix,
.domain = pci_domain_nr(dev->bus),
.bus = dev->bus->number,
.devfn = dev->devfn,
.value = nvec,
};
struct pcifront_sd *sd = dev->bus->sysdata;
struct pcifront_device *pdev = pcifront_get_pdev(sd);
struct msi_desc *entry;
if (nvec > SH_INFO_MAX_VEC) {
dev_err(&dev->dev, "too much vector for pci frontend: %x."
" Increase SH_INFO_MAX_VEC.\n", nvec);
return -EINVAL;
}
i = 0;
list_for_each_entry(entry, &dev->msi_list, list) {
op.msix_entries[i].entry = entry->msi_attrib.entry_nr;
/* Vector is useless at this point. */
op.msix_entries[i].vector = -1;
i++;
}
err = do_pci_op(pdev, &op);
if (likely(!err)) {
if (likely(!op.value)) {
/* we get the result */
for (i = 0; i < nvec; i++) {
if (op.msix_entries[i].vector <= 0) {
dev_warn(&dev->dev, "MSI-X entry %d is invalid: %d!\n",
i, op.msix_entries[i].vector);
err = -EINVAL;
vector[i] = -1;
continue;
}
vector[i] = op.msix_entries[i].vector;
}
} else {
printk(KERN_DEBUG "enable msix get value %x\n",
op.value);
err = op.value;
}
} else {
dev_err(&dev->dev, "enable msix get err %x\n", err);
}
return err;
}
static void pci_frontend_disable_msix(struct pci_dev *dev)
{
int err;
struct xen_pci_op op = {
.cmd = XEN_PCI_OP_disable_msix,
.domain = pci_domain_nr(dev->bus),
.bus = dev->bus->number,
.devfn = dev->devfn,
};
struct pcifront_sd *sd = dev->bus->sysdata;
struct pcifront_device *pdev = pcifront_get_pdev(sd);
err = do_pci_op(pdev, &op);
/* What should do for error ? */
if (err)
dev_err(&dev->dev, "pci_disable_msix get err %x\n", err);
}
static int pci_frontend_enable_msi(struct pci_dev *dev, int vector[])
{
int err;
struct xen_pci_op op = {
.cmd = XEN_PCI_OP_enable_msi,
.domain = pci_domain_nr(dev->bus),
.bus = dev->bus->number,
.devfn = dev->devfn,
};
struct pcifront_sd *sd = dev->bus->sysdata;
struct pcifront_device *pdev = pcifront_get_pdev(sd);
err = do_pci_op(pdev, &op);
if (likely(!err)) {
vector[0] = op.value;
if (op.value <= 0) {
dev_warn(&dev->dev, "MSI entry is invalid: %d!\n",
op.value);
err = -EINVAL;
vector[0] = -1;
}
} else {
dev_err(&dev->dev, "pci frontend enable msi failed for dev "
"%x:%x\n", op.bus, op.devfn);
err = -EINVAL;
}
return err;
}
static void pci_frontend_disable_msi(struct pci_dev *dev)
{
int err;
struct xen_pci_op op = {
.cmd = XEN_PCI_OP_disable_msi,
.domain = pci_domain_nr(dev->bus),
.bus = dev->bus->number,
.devfn = dev->devfn,
};
struct pcifront_sd *sd = dev->bus->sysdata;
struct pcifront_device *pdev = pcifront_get_pdev(sd);
err = do_pci_op(pdev, &op);
if (err == XEN_PCI_ERR_dev_not_found) {
/* XXX No response from backend, what shall we do? */
printk(KERN_DEBUG "get no response from backend for disable MSI\n");
return;
}
if (err)
/* how can pciback notify us fail? */
printk(KERN_DEBUG "get fake response frombackend\n");
}
static struct xen_pci_frontend_ops pci_frontend_ops = {
.enable_msi = pci_frontend_enable_msi,
.disable_msi = pci_frontend_disable_msi,
.enable_msix = pci_frontend_enable_msix,
.disable_msix = pci_frontend_disable_msix,
};
static void pci_frontend_registrar(int enable)
{
if (enable)
xen_pci_frontend = &pci_frontend_ops;
else
xen_pci_frontend = NULL;
};
#else
static inline void pci_frontend_registrar(int enable) { };
#endif /* CONFIG_PCI_MSI */
/* Claim resources for the PCI frontend as-is, backend won't allow changes */
static int pcifront_claim_resource(struct pci_dev *dev, void *data)
{
struct pcifront_device *pdev = data;
int i;
struct resource *r;
for (i = 0; i < PCI_NUM_RESOURCES; i++) {
r = &dev->resource[i];
if (!r->parent && r->start && r->flags) {
dev_info(&pdev->xdev->dev, "claiming resource %s/%d\n",
pci_name(dev), i);
if (pci_claim_resource(dev, i)) {
dev_err(&pdev->xdev->dev, "Could not claim resource %s/%d! "
"Device offline. Try using e820_host=1 in the guest config.\n",
pci_name(dev), i);
}
}
}
return 0;
}
static int __devinit pcifront_scan_bus(struct pcifront_device *pdev,
unsigned int domain, unsigned int bus,
struct pci_bus *b)
{
struct pci_dev *d;
unsigned int devfn;
/* Scan the bus for functions and add.
* We omit handling of PCI bridge attachment because pciback prevents
* bridges from being exported.
*/
for (devfn = 0; devfn < 0x100; devfn++) {
d = pci_get_slot(b, devfn);
if (d) {
/* Device is already known. */
pci_dev_put(d);
continue;
}
d = pci_scan_single_device(b, devfn);
if (d)
dev_info(&pdev->xdev->dev, "New device on "
"%04x:%02x:%02x.%d found.\n", domain, bus,
PCI_SLOT(devfn), PCI_FUNC(devfn));
}
return 0;
}
static int __devinit pcifront_scan_root(struct pcifront_device *pdev,
unsigned int domain, unsigned int bus)
{
struct pci_bus *b;
struct pcifront_sd *sd = NULL;
struct pci_bus_entry *bus_entry = NULL;
int err = 0;
#ifndef CONFIG_PCI_DOMAINS
if (domain != 0) {
dev_err(&pdev->xdev->dev,
"PCI Root in non-zero PCI Domain! domain=%d\n", domain);
dev_err(&pdev->xdev->dev,
"Please compile with CONFIG_PCI_DOMAINS\n");
err = -EINVAL;
goto err_out;
}
#endif
dev_info(&pdev->xdev->dev, "Creating PCI Frontend Bus %04x:%02x\n",
domain, bus);
bus_entry = kmalloc(sizeof(*bus_entry), GFP_KERNEL);
sd = kmalloc(sizeof(*sd), GFP_KERNEL);
if (!bus_entry || !sd) {
err = -ENOMEM;
goto err_out;
}
pcifront_init_sd(sd, domain, bus, pdev);
b = pci_scan_bus_parented(&pdev->xdev->dev, bus,
&pcifront_bus_ops, sd);
if (!b) {
dev_err(&pdev->xdev->dev,
"Error creating PCI Frontend Bus!\n");
err = -ENOMEM;
goto err_out;
}
bus_entry->bus = b;
list_add(&bus_entry->list, &pdev->root_buses);
/* pci_scan_bus_parented skips devices which do not have a have
* devfn==0. The pcifront_scan_bus enumerates all devfn. */
err = pcifront_scan_bus(pdev, domain, bus, b);
/* Claim resources before going "live" with our devices */
pci_walk_bus(b, pcifront_claim_resource, pdev);
/* Create SysFS and notify udev of the devices. Aka: "going live" */
pci_bus_add_devices(b);
return err;
err_out:
kfree(bus_entry);
kfree(sd);
return err;
}
static int __devinit pcifront_rescan_root(struct pcifront_device *pdev,
unsigned int domain, unsigned int bus)
{
int err;
struct pci_bus *b;
#ifndef CONFIG_PCI_DOMAINS
if (domain != 0) {
dev_err(&pdev->xdev->dev,
"PCI Root in non-zero PCI Domain! domain=%d\n", domain);
dev_err(&pdev->xdev->dev,
"Please compile with CONFIG_PCI_DOMAINS\n");
return -EINVAL;
}
#endif
dev_info(&pdev->xdev->dev, "Rescanning PCI Frontend Bus %04x:%02x\n",
domain, bus);
b = pci_find_bus(domain, bus);
if (!b)
/* If the bus is unknown, create it. */
return pcifront_scan_root(pdev, domain, bus);
err = pcifront_scan_bus(pdev, domain, bus, b);
/* Claim resources before going "live" with our devices */
pci_walk_bus(b, pcifront_claim_resource, pdev);
/* Create SysFS and notify udev of the devices. Aka: "going live" */
pci_bus_add_devices(b);
return err;
}
static void free_root_bus_devs(struct pci_bus *bus)
{
struct pci_dev *dev;
while (!list_empty(&bus->devices)) {
dev = container_of(bus->devices.next, struct pci_dev,
bus_list);
dev_dbg(&dev->dev, "removing device\n");
pci_stop_and_remove_bus_device(dev);
}
}
static void pcifront_free_roots(struct pcifront_device *pdev)
{
struct pci_bus_entry *bus_entry, *t;
dev_dbg(&pdev->xdev->dev, "cleaning up root buses\n");
list_for_each_entry_safe(bus_entry, t, &pdev->root_buses, list) {
list_del(&bus_entry->list);
free_root_bus_devs(bus_entry->bus);
kfree(bus_entry->bus->sysdata);
device_unregister(bus_entry->bus->bridge);
pci_remove_bus(bus_entry->bus);
kfree(bus_entry);
}
}
static pci_ers_result_t pcifront_common_process(int cmd,
struct pcifront_device *pdev,
pci_channel_state_t state)
{
pci_ers_result_t result;
struct pci_driver *pdrv;
int bus = pdev->sh_info->aer_op.bus;
int devfn = pdev->sh_info->aer_op.devfn;
struct pci_dev *pcidev;
int flag = 0;
dev_dbg(&pdev->xdev->dev,
"pcifront AER process: cmd %x (bus:%x, devfn%x)",
cmd, bus, devfn);
result = PCI_ERS_RESULT_NONE;
pcidev = pci_get_bus_and_slot(bus, devfn);
if (!pcidev || !pcidev->driver) {
dev_err(&pdev->xdev->dev, "device or AER driver is NULL\n");
if (pcidev)
pci_dev_put(pcidev);
return result;
}
pdrv = pcidev->driver;
if (pdrv) {
if (pdrv->err_handler && pdrv->err_handler->error_detected) {
dev_dbg(&pcidev->dev,
"trying to call AER service\n");
if (pcidev) {
flag = 1;
switch (cmd) {
case XEN_PCI_OP_aer_detected:
result = pdrv->err_handler->
error_detected(pcidev, state);
break;
case XEN_PCI_OP_aer_mmio:
result = pdrv->err_handler->
mmio_enabled(pcidev);
break;
case XEN_PCI_OP_aer_slotreset:
result = pdrv->err_handler->
slot_reset(pcidev);
break;
case XEN_PCI_OP_aer_resume:
pdrv->err_handler->resume(pcidev);
break;
default:
dev_err(&pdev->xdev->dev,
"bad request in aer recovery "
"operation!\n");
}
}
}
}
if (!flag)
result = PCI_ERS_RESULT_NONE;
return result;
}
static void pcifront_do_aer(struct work_struct *data)
{
struct pcifront_device *pdev =
container_of(data, struct pcifront_device, op_work);
int cmd = pdev->sh_info->aer_op.cmd;
pci_channel_state_t state =
(pci_channel_state_t)pdev->sh_info->aer_op.err;
/*If a pci_conf op is in progress,
we have to wait until it is done before service aer op*/
dev_dbg(&pdev->xdev->dev,
"pcifront service aer bus %x devfn %x\n",
pdev->sh_info->aer_op.bus, pdev->sh_info->aer_op.devfn);
pdev->sh_info->aer_op.err = pcifront_common_process(cmd, pdev, state);
/* Post the operation to the guest. */
wmb();
clear_bit(_XEN_PCIB_active, (unsigned long *)&pdev->sh_info->flags);
notify_remote_via_evtchn(pdev->evtchn);
/*in case of we lost an aer request in four lines time_window*/
smp_mb__before_clear_bit();
clear_bit(_PDEVB_op_active, &pdev->flags);
smp_mb__after_clear_bit();
schedule_pcifront_aer_op(pdev);
}
static irqreturn_t pcifront_handler_aer(int irq, void *dev)
{
struct pcifront_device *pdev = dev;
schedule_pcifront_aer_op(pdev);
return IRQ_HANDLED;
}
static int pcifront_connect(struct pcifront_device *pdev)
{
int err = 0;
spin_lock(&pcifront_dev_lock);
if (!pcifront_dev) {
dev_info(&pdev->xdev->dev, "Installing PCI frontend\n");
pcifront_dev = pdev;
} else {
dev_err(&pdev->xdev->dev, "PCI frontend already installed!\n");
err = -EEXIST;
}
spin_unlock(&pcifront_dev_lock);
return err;
}
static void pcifront_disconnect(struct pcifront_device *pdev)
{
spin_lock(&pcifront_dev_lock);
if (pdev == pcifront_dev) {
dev_info(&pdev->xdev->dev,
"Disconnecting PCI Frontend Buses\n");
pcifront_dev = NULL;
}
spin_unlock(&pcifront_dev_lock);
}
static struct pcifront_device *alloc_pdev(struct xenbus_device *xdev)
{
struct pcifront_device *pdev;
pdev = kzalloc(sizeof(struct pcifront_device), GFP_KERNEL);
if (pdev == NULL)
goto out;
pdev->sh_info =
(struct xen_pci_sharedinfo *)__get_free_page(GFP_KERNEL);
if (pdev->sh_info == NULL) {
kfree(pdev);
pdev = NULL;
goto out;
}
pdev->sh_info->flags = 0;
/*Flag for registering PV AER handler*/
set_bit(_XEN_PCIB_AERHANDLER, (void *)&pdev->sh_info->flags);
dev_set_drvdata(&xdev->dev, pdev);
pdev->xdev = xdev;
INIT_LIST_HEAD(&pdev->root_buses);
spin_lock_init(&pdev->sh_info_lock);
pdev->evtchn = INVALID_EVTCHN;
pdev->gnt_ref = INVALID_GRANT_REF;
pdev->irq = -1;
INIT_WORK(&pdev->op_work, pcifront_do_aer);
dev_dbg(&xdev->dev, "Allocated pdev @ 0x%p pdev->sh_info @ 0x%p\n",
pdev, pdev->sh_info);
out:
return pdev;
}
static void free_pdev(struct pcifront_device *pdev)
{
dev_dbg(&pdev->xdev->dev, "freeing pdev @ 0x%p\n", pdev);
pcifront_free_roots(pdev);
cancel_work_sync(&pdev->op_work);
if (pdev->irq >= 0)
unbind_from_irqhandler(pdev->irq, pdev);
if (pdev->evtchn != INVALID_EVTCHN)
xenbus_free_evtchn(pdev->xdev, pdev->evtchn);
if (pdev->gnt_ref != INVALID_GRANT_REF)
gnttab_end_foreign_access(pdev->gnt_ref, 0 /* r/w page */,
(unsigned long)pdev->sh_info);
else
free_page((unsigned long)pdev->sh_info);
dev_set_drvdata(&pdev->xdev->dev, NULL);
kfree(pdev);
}
static int pcifront_publish_info(struct pcifront_device *pdev)
{
int err = 0;
struct xenbus_transaction trans;
err = xenbus_grant_ring(pdev->xdev, virt_to_mfn(pdev->sh_info));
if (err < 0)
goto out;
pdev->gnt_ref = err;
err = xenbus_alloc_evtchn(pdev->xdev, &pdev->evtchn);
if (err)
goto out;
err = bind_evtchn_to_irqhandler(pdev->evtchn, pcifront_handler_aer,
0, "pcifront", pdev);
if (err < 0)
return err;
pdev->irq = err;
do_publish:
err = xenbus_transaction_start(&trans);
if (err) {
xenbus_dev_fatal(pdev->xdev, err,
"Error writing configuration for backend "
"(start transaction)");
goto out;
}
err = xenbus_printf(trans, pdev->xdev->nodename,
"pci-op-ref", "%u", pdev->gnt_ref);
if (!err)
err = xenbus_printf(trans, pdev->xdev->nodename,
"event-channel", "%u", pdev->evtchn);
if (!err)
err = xenbus_printf(trans, pdev->xdev->nodename,
"magic", XEN_PCI_MAGIC);
if (err) {
xenbus_transaction_end(trans, 1);
xenbus_dev_fatal(pdev->xdev, err,
"Error writing configuration for backend");
goto out;
} else {
err = xenbus_transaction_end(trans, 0);
if (err == -EAGAIN)
goto do_publish;
else if (err) {
xenbus_dev_fatal(pdev->xdev, err,
"Error completing transaction "
"for backend");
goto out;
}
}
xenbus_switch_state(pdev->xdev, XenbusStateInitialised);
dev_dbg(&pdev->xdev->dev, "publishing successful!\n");
out:
return err;
}
static int __devinit pcifront_try_connect(struct pcifront_device *pdev)
{
int err = -EFAULT;
int i, num_roots, len;
char str[64];
unsigned int domain, bus;
/* Only connect once */
if (xenbus_read_driver_state(pdev->xdev->nodename) !=
XenbusStateInitialised)
goto out;
err = pcifront_connect(pdev);
if (err) {
xenbus_dev_fatal(pdev->xdev, err,
"Error connecting PCI Frontend");
goto out;
}
err = xenbus_scanf(XBT_NIL, pdev->xdev->otherend,
"root_num", "%d", &num_roots);
if (err == -ENOENT) {
xenbus_dev_error(pdev->xdev, err,
"No PCI Roots found, trying 0000:00");
err = pcifront_scan_root(pdev, 0, 0);
num_roots = 0;
} else if (err != 1) {
if (err == 0)
err = -EINVAL;
xenbus_dev_fatal(pdev->xdev, err,
"Error reading number of PCI roots");
goto out;
}
for (i = 0; i < num_roots; i++) {
len = snprintf(str, sizeof(str), "root-%d", i);
if (unlikely(len >= (sizeof(str) - 1))) {
err = -ENOMEM;
goto out;
}
err = xenbus_scanf(XBT_NIL, pdev->xdev->otherend, str,
"%x:%x", &domain, &bus);
if (err != 2) {
if (err >= 0)
err = -EINVAL;
xenbus_dev_fatal(pdev->xdev, err,
"Error reading PCI root %d", i);
goto out;
}
err = pcifront_scan_root(pdev, domain, bus);
if (err) {
xenbus_dev_fatal(pdev->xdev, err,
"Error scanning PCI root %04x:%02x",
domain, bus);
goto out;
}
}
err = xenbus_switch_state(pdev->xdev, XenbusStateConnected);
out:
return err;
}
static int pcifront_try_disconnect(struct pcifront_device *pdev)
{
int err = 0;
enum xenbus_state prev_state;
prev_state = xenbus_read_driver_state(pdev->xdev->nodename);
if (prev_state >= XenbusStateClosing)
goto out;
if (prev_state == XenbusStateConnected) {
pcifront_free_roots(pdev);
pcifront_disconnect(pdev);
}
err = xenbus_switch_state(pdev->xdev, XenbusStateClosed);
out:
return err;
}
static int __devinit pcifront_attach_devices(struct pcifront_device *pdev)
{
int err = -EFAULT;
int i, num_roots, len;
unsigned int domain, bus;
char str[64];
if (xenbus_read_driver_state(pdev->xdev->nodename) !=
XenbusStateReconfiguring)
goto out;
err = xenbus_scanf(XBT_NIL, pdev->xdev->otherend,
"root_num", "%d", &num_roots);
if (err == -ENOENT) {
xenbus_dev_error(pdev->xdev, err,
"No PCI Roots found, trying 0000:00");
err = pcifront_rescan_root(pdev, 0, 0);
num_roots = 0;
} else if (err != 1) {
if (err == 0)
err = -EINVAL;
xenbus_dev_fatal(pdev->xdev, err,
"Error reading number of PCI roots");
goto out;
}
for (i = 0; i < num_roots; i++) {
len = snprintf(str, sizeof(str), "root-%d", i);
if (unlikely(len >= (sizeof(str) - 1))) {
err = -ENOMEM;
goto out;
}
err = xenbus_scanf(XBT_NIL, pdev->xdev->otherend, str,
"%x:%x", &domain, &bus);
if (err != 2) {
if (err >= 0)
err = -EINVAL;
xenbus_dev_fatal(pdev->xdev, err,
"Error reading PCI root %d", i);
goto out;
}
err = pcifront_rescan_root(pdev, domain, bus);
if (err) {
xenbus_dev_fatal(pdev->xdev, err,
"Error scanning PCI root %04x:%02x",
domain, bus);
goto out;
}
}
xenbus_switch_state(pdev->xdev, XenbusStateConnected);
out:
return err;
}
static int pcifront_detach_devices(struct pcifront_device *pdev)
{
int err = 0;
int i, num_devs;
unsigned int domain, bus, slot, func;
struct pci_bus *pci_bus;
struct pci_dev *pci_dev;
char str[64];
if (xenbus_read_driver_state(pdev->xdev->nodename) !=
XenbusStateConnected)
goto out;
err = xenbus_scanf(XBT_NIL, pdev->xdev->otherend, "num_devs", "%d",
&num_devs);
if (err != 1) {
if (err >= 0)
err = -EINVAL;
xenbus_dev_fatal(pdev->xdev, err,
"Error reading number of PCI devices");
goto out;
}
/* Find devices being detached and remove them. */
for (i = 0; i < num_devs; i++) {
int l, state;
l = snprintf(str, sizeof(str), "state-%d", i);
if (unlikely(l >= (sizeof(str) - 1))) {
err = -ENOMEM;
goto out;
}
err = xenbus_scanf(XBT_NIL, pdev->xdev->otherend, str, "%d",
&state);
if (err != 1)
state = XenbusStateUnknown;
if (state != XenbusStateClosing)
continue;
/* Remove device. */
l = snprintf(str, sizeof(str), "vdev-%d", i);
if (unlikely(l >= (sizeof(str) - 1))) {
err = -ENOMEM;
goto out;
}
err = xenbus_scanf(XBT_NIL, pdev->xdev->otherend, str,
"%x:%x:%x.%x", &domain, &bus, &slot, &func);
if (err != 4) {
if (err >= 0)
err = -EINVAL;
xenbus_dev_fatal(pdev->xdev, err,
"Error reading PCI device %d", i);
goto out;
}
pci_bus = pci_find_bus(domain, bus);
if (!pci_bus) {
dev_dbg(&pdev->xdev->dev, "Cannot get bus %04x:%02x\n",
domain, bus);
continue;
}
pci_dev = pci_get_slot(pci_bus, PCI_DEVFN(slot, func));
if (!pci_dev) {
dev_dbg(&pdev->xdev->dev,
"Cannot get PCI device %04x:%02x:%02x.%d\n",
domain, bus, slot, func);
continue;
}
pci_stop_and_remove_bus_device(pci_dev);
pci_dev_put(pci_dev);
dev_dbg(&pdev->xdev->dev,
"PCI device %04x:%02x:%02x.%d removed.\n",
domain, bus, slot, func);
}
err = xenbus_switch_state(pdev->xdev, XenbusStateReconfiguring);
out:
return err;
}
static void __init_refok pcifront_backend_changed(struct xenbus_device *xdev,
enum xenbus_state be_state)
{
struct pcifront_device *pdev = dev_get_drvdata(&xdev->dev);
switch (be_state) {
case XenbusStateUnknown:
case XenbusStateInitialising:
case XenbusStateInitWait:
case XenbusStateInitialised:
case XenbusStateClosed:
break;
case XenbusStateConnected:
pcifront_try_connect(pdev);
break;
case XenbusStateClosing:
dev_warn(&xdev->dev, "backend going away!\n");
pcifront_try_disconnect(pdev);
break;
case XenbusStateReconfiguring:
pcifront_detach_devices(pdev);
break;
case XenbusStateReconfigured:
pcifront_attach_devices(pdev);
break;
}
}
static int pcifront_xenbus_probe(struct xenbus_device *xdev,
const struct xenbus_device_id *id)
{
int err = 0;
struct pcifront_device *pdev = alloc_pdev(xdev);
if (pdev == NULL) {
err = -ENOMEM;
xenbus_dev_fatal(xdev, err,
"Error allocating pcifront_device struct");
goto out;
}
err = pcifront_publish_info(pdev);
if (err)
free_pdev(pdev);
out:
return err;
}
static int pcifront_xenbus_remove(struct xenbus_device *xdev)
{
struct pcifront_device *pdev = dev_get_drvdata(&xdev->dev);
if (pdev)
free_pdev(pdev);
return 0;
}
static const struct xenbus_device_id xenpci_ids[] = {
{"pci"},
{""},
};
static DEFINE_XENBUS_DRIVER(xenpci, "pcifront",
.probe = pcifront_xenbus_probe,
.remove = pcifront_xenbus_remove,
.otherend_changed = pcifront_backend_changed,
);
static int __init pcifront_init(void)
{
if (!xen_pv_domain() || xen_initial_domain())
return -ENODEV;
pci_frontend_registrar(1 /* enable */);
return xenbus_register_frontend(&xenpci_driver);
}
static void __exit pcifront_cleanup(void)
{
xenbus_unregister_driver(&xenpci_driver);
pci_frontend_registrar(0 /* disable */);
}
module_init(pcifront_init);
module_exit(pcifront_cleanup);
MODULE_DESCRIPTION("Xen PCI passthrough frontend.");
MODULE_LICENSE("GPL");
MODULE_ALIAS("xen:pci");
| gpl-2.0 |
govindraj-raja/linux-omap | drivers/staging/media/as102/as10x_cmd_cfg.c | 5177 | 5836 | /*
* Abilis Systems Single DVB-T Receiver
* Copyright (C) 2008 Pierrick Hascoet <pierrick.hascoet@abilis.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/kernel.h>
#include "as102_drv.h"
#include "as10x_types.h"
#include "as10x_cmd.h"
/***************************/
/* FUNCTION DEFINITION */
/***************************/
/**
* as10x_cmd_get_context - Send get context command to AS10x
* @adap: pointer to AS10x bus adapter
* @tag: context tag
* @pvalue: pointer where to store context value read
*
* Return 0 on success or negative value in case of error.
*/
int as10x_cmd_get_context(struct as10x_bus_adapter_t *adap, uint16_t tag,
uint32_t *pvalue)
{
int error;
struct as10x_cmd_t *pcmd, *prsp;
ENTER();
pcmd = adap->cmd;
prsp = adap->rsp;
/* prepare command */
as10x_cmd_build(pcmd, (++adap->cmd_xid),
sizeof(pcmd->body.context.req));
/* fill command */
pcmd->body.context.req.proc_id = cpu_to_le16(CONTROL_PROC_CONTEXT);
pcmd->body.context.req.tag = cpu_to_le16(tag);
pcmd->body.context.req.type = cpu_to_le16(GET_CONTEXT_DATA);
/* send command */
if (adap->ops->xfer_cmd) {
error = adap->ops->xfer_cmd(adap,
(uint8_t *) pcmd,
sizeof(pcmd->body.context.req)
+ HEADER_SIZE,
(uint8_t *) prsp,
sizeof(prsp->body.context.rsp)
+ HEADER_SIZE);
} else {
error = AS10X_CMD_ERROR;
}
if (error < 0)
goto out;
/* parse response: context command do not follow the common response */
/* structure -> specific handling response parse required */
error = as10x_context_rsp_parse(prsp, CONTROL_PROC_CONTEXT_RSP);
if (error == 0) {
/* Response OK -> get response data */
*pvalue = le32_to_cpu(prsp->body.context.rsp.reg_val.u.value32);
/* value returned is always a 32-bit value */
}
out:
LEAVE();
return error;
}
/**
* as10x_cmd_set_context - send set context command to AS10x
* @adap: pointer to AS10x bus adapter
* @tag: context tag
* @value: value to set in context
*
* Return 0 on success or negative value in case of error.
*/
int as10x_cmd_set_context(struct as10x_bus_adapter_t *adap, uint16_t tag,
uint32_t value)
{
int error;
struct as10x_cmd_t *pcmd, *prsp;
ENTER();
pcmd = adap->cmd;
prsp = adap->rsp;
/* prepare command */
as10x_cmd_build(pcmd, (++adap->cmd_xid),
sizeof(pcmd->body.context.req));
/* fill command */
pcmd->body.context.req.proc_id = cpu_to_le16(CONTROL_PROC_CONTEXT);
/* pcmd->body.context.req.reg_val.mode initialization is not required */
pcmd->body.context.req.reg_val.u.value32 = cpu_to_le32(value);
pcmd->body.context.req.tag = cpu_to_le16(tag);
pcmd->body.context.req.type = cpu_to_le16(SET_CONTEXT_DATA);
/* send command */
if (adap->ops->xfer_cmd) {
error = adap->ops->xfer_cmd(adap,
(uint8_t *) pcmd,
sizeof(pcmd->body.context.req)
+ HEADER_SIZE,
(uint8_t *) prsp,
sizeof(prsp->body.context.rsp)
+ HEADER_SIZE);
} else {
error = AS10X_CMD_ERROR;
}
if (error < 0)
goto out;
/* parse response: context command do not follow the common response */
/* structure -> specific handling response parse required */
error = as10x_context_rsp_parse(prsp, CONTROL_PROC_CONTEXT_RSP);
out:
LEAVE();
return error;
}
/**
* as10x_cmd_eLNA_change_mode - send eLNA change mode command to AS10x
* @adap: pointer to AS10x bus adapter
* @mode: mode selected:
* - ON : 0x0 => eLNA always ON
* - OFF : 0x1 => eLNA always OFF
* - AUTO : 0x2 => eLNA follow hysteresis parameters
* to be ON or OFF
*
* Return 0 on success or negative value in case of error.
*/
int as10x_cmd_eLNA_change_mode(struct as10x_bus_adapter_t *adap, uint8_t mode)
{
int error;
struct as10x_cmd_t *pcmd, *prsp;
ENTER();
pcmd = adap->cmd;
prsp = adap->rsp;
/* prepare command */
as10x_cmd_build(pcmd, (++adap->cmd_xid),
sizeof(pcmd->body.cfg_change_mode.req));
/* fill command */
pcmd->body.cfg_change_mode.req.proc_id =
cpu_to_le16(CONTROL_PROC_ELNA_CHANGE_MODE);
pcmd->body.cfg_change_mode.req.mode = mode;
/* send command */
if (adap->ops->xfer_cmd) {
error = adap->ops->xfer_cmd(adap, (uint8_t *) pcmd,
sizeof(pcmd->body.cfg_change_mode.req)
+ HEADER_SIZE, (uint8_t *) prsp,
sizeof(prsp->body.cfg_change_mode.rsp)
+ HEADER_SIZE);
} else {
error = AS10X_CMD_ERROR;
}
if (error < 0)
goto out;
/* parse response */
error = as10x_rsp_parse(prsp, CONTROL_PROC_ELNA_CHANGE_MODE_RSP);
out:
LEAVE();
return error;
}
/**
* as10x_context_rsp_parse - Parse context command response
* @prsp: pointer to AS10x command response buffer
* @proc_id: id of the command
*
* Since the contex command reponse does not follow the common
* response, a specific parse function is required.
* Return 0 on success or negative value in case of error.
*/
int as10x_context_rsp_parse(struct as10x_cmd_t *prsp, uint16_t proc_id)
{
int err;
err = prsp->body.context.rsp.error;
if ((err == 0) &&
(le16_to_cpu(prsp->body.context.rsp.proc_id) == proc_id)) {
return 0;
}
return AS10X_CMD_ERROR;
}
| gpl-2.0 |
SyNtheticNightmar3/android_kernel_asus_flo | drivers/parport/parport_ip32.c | 7481 | 68661 | /* Low-level parallel port routines for built-in port on SGI IP32
*
* Author: Arnaud Giersch <arnaud.giersch@free.fr>
*
* Based on parport_pc.c by
* Phil Blundell, Tim Waugh, Jose Renau, David Campbell,
* Andrea Arcangeli, et al.
*
* Thanks to Ilya A. Volynets-Evenbakh for his help.
*
* Copyright (C) 2005, 2006 Arnaud Giersch.
*
* 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.
*/
/* Current status:
*
* Basic SPP and PS2 modes are supported.
* Support for parallel port IRQ is present.
* Hardware SPP (a.k.a. compatibility), EPP, and ECP modes are
* supported.
* SPP/ECP FIFO can be driven in PIO or DMA mode. PIO mode can work with
* or without interrupt support.
*
* Hardware ECP mode is not fully implemented (ecp_read_data and
* ecp_write_addr are actually missing).
*
* To do:
*
* Fully implement ECP mode.
* EPP and ECP mode need to be tested. I currently do not own any
* peripheral supporting these extended mode, and cannot test them.
* If DMA mode works well, decide if support for PIO FIFO modes should be
* dropped.
* Use the io{read,write} family functions when they become available in
* the linux-mips.org tree. Note: the MIPS specific functions readsb()
* and writesb() are to be translated by ioread8_rep() and iowrite8_rep()
* respectively.
*/
/* The built-in parallel port on the SGI 02 workstation (a.k.a. IP32) is an
* IEEE 1284 parallel port driven by a Texas Instrument TL16PIR552PH chip[1].
* This chip supports SPP, bidirectional, EPP and ECP modes. It has a 16 byte
* FIFO buffer and supports DMA transfers.
*
* [1] http://focus.ti.com/docs/prod/folders/print/tl16pir552.html
*
* Theoretically, we could simply use the parport_pc module. It is however
* not so simple. The parport_pc code assumes that the parallel port
* registers are port-mapped. On the O2, they are memory-mapped.
* Furthermore, each register is replicated on 256 consecutive addresses (as
* it is for the built-in serial ports on the same chip).
*/
/*--- Some configuration defines ---------------------------------------*/
/* DEBUG_PARPORT_IP32
* 0 disable debug
* 1 standard level: pr_debug1 is enabled
* 2 parport_ip32_dump_state is enabled
* >=3 verbose level: pr_debug is enabled
*/
#if !defined(DEBUG_PARPORT_IP32)
# define DEBUG_PARPORT_IP32 0 /* 0 (disabled) for production */
#endif
/*----------------------------------------------------------------------*/
/* Setup DEBUG macros. This is done before any includes, just in case we
* activate pr_debug() with DEBUG_PARPORT_IP32 >= 3.
*/
#if DEBUG_PARPORT_IP32 == 1
# warning DEBUG_PARPORT_IP32 == 1
#elif DEBUG_PARPORT_IP32 == 2
# warning DEBUG_PARPORT_IP32 == 2
#elif DEBUG_PARPORT_IP32 >= 3
# warning DEBUG_PARPORT_IP32 >= 3
# if !defined(DEBUG)
# define DEBUG /* enable pr_debug() in kernel.h */
# endif
#endif
#include <linux/completion.h>
#include <linux/delay.h>
#include <linux/dma-mapping.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/jiffies.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/parport.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/stddef.h>
#include <linux/types.h>
#include <asm/io.h>
#include <asm/ip32/ip32_ints.h>
#include <asm/ip32/mace.h>
/*--- Global variables -------------------------------------------------*/
/* Verbose probing on by default for debugging. */
#if DEBUG_PARPORT_IP32 >= 1
# define DEFAULT_VERBOSE_PROBING 1
#else
# define DEFAULT_VERBOSE_PROBING 0
#endif
/* Default prefix for printk */
#define PPIP32 "parport_ip32: "
/*
* These are the module parameters:
* @features: bit mask of features to enable/disable
* (all enabled by default)
* @verbose_probing: log chit-chat during initialization
*/
#define PARPORT_IP32_ENABLE_IRQ (1U << 0)
#define PARPORT_IP32_ENABLE_DMA (1U << 1)
#define PARPORT_IP32_ENABLE_SPP (1U << 2)
#define PARPORT_IP32_ENABLE_EPP (1U << 3)
#define PARPORT_IP32_ENABLE_ECP (1U << 4)
static unsigned int features = ~0U;
static bool verbose_probing = DEFAULT_VERBOSE_PROBING;
/* We do not support more than one port. */
static struct parport *this_port = NULL;
/* Timing constants for FIFO modes. */
#define FIFO_NFAULT_TIMEOUT 100 /* milliseconds */
#define FIFO_POLLING_INTERVAL 50 /* microseconds */
/*--- I/O register definitions -----------------------------------------*/
/**
* struct parport_ip32_regs - virtual addresses of parallel port registers
* @data: Data Register
* @dsr: Device Status Register
* @dcr: Device Control Register
* @eppAddr: EPP Address Register
* @eppData0: EPP Data Register 0
* @eppData1: EPP Data Register 1
* @eppData2: EPP Data Register 2
* @eppData3: EPP Data Register 3
* @ecpAFifo: ECP Address FIFO
* @fifo: General FIFO register. The same address is used for:
* - cFifo, the Parallel Port DATA FIFO
* - ecpDFifo, the ECP Data FIFO
* - tFifo, the ECP Test FIFO
* @cnfgA: Configuration Register A
* @cnfgB: Configuration Register B
* @ecr: Extended Control Register
*/
struct parport_ip32_regs {
void __iomem *data;
void __iomem *dsr;
void __iomem *dcr;
void __iomem *eppAddr;
void __iomem *eppData0;
void __iomem *eppData1;
void __iomem *eppData2;
void __iomem *eppData3;
void __iomem *ecpAFifo;
void __iomem *fifo;
void __iomem *cnfgA;
void __iomem *cnfgB;
void __iomem *ecr;
};
/* Device Status Register */
#define DSR_nBUSY (1U << 7) /* PARPORT_STATUS_BUSY */
#define DSR_nACK (1U << 6) /* PARPORT_STATUS_ACK */
#define DSR_PERROR (1U << 5) /* PARPORT_STATUS_PAPEROUT */
#define DSR_SELECT (1U << 4) /* PARPORT_STATUS_SELECT */
#define DSR_nFAULT (1U << 3) /* PARPORT_STATUS_ERROR */
#define DSR_nPRINT (1U << 2) /* specific to TL16PIR552 */
/* #define DSR_reserved (1U << 1) */
#define DSR_TIMEOUT (1U << 0) /* EPP timeout */
/* Device Control Register */
/* #define DCR_reserved (1U << 7) | (1U << 6) */
#define DCR_DIR (1U << 5) /* direction */
#define DCR_IRQ (1U << 4) /* interrupt on nAck */
#define DCR_SELECT (1U << 3) /* PARPORT_CONTROL_SELECT */
#define DCR_nINIT (1U << 2) /* PARPORT_CONTROL_INIT */
#define DCR_AUTOFD (1U << 1) /* PARPORT_CONTROL_AUTOFD */
#define DCR_STROBE (1U << 0) /* PARPORT_CONTROL_STROBE */
/* ECP Configuration Register A */
#define CNFGA_IRQ (1U << 7)
#define CNFGA_ID_MASK ((1U << 6) | (1U << 5) | (1U << 4))
#define CNFGA_ID_SHIFT 4
#define CNFGA_ID_16 (00U << CNFGA_ID_SHIFT)
#define CNFGA_ID_8 (01U << CNFGA_ID_SHIFT)
#define CNFGA_ID_32 (02U << CNFGA_ID_SHIFT)
/* #define CNFGA_reserved (1U << 3) */
#define CNFGA_nBYTEINTRANS (1U << 2)
#define CNFGA_PWORDLEFT ((1U << 1) | (1U << 0))
/* ECP Configuration Register B */
#define CNFGB_COMPRESS (1U << 7)
#define CNFGB_INTRVAL (1U << 6)
#define CNFGB_IRQ_MASK ((1U << 5) | (1U << 4) | (1U << 3))
#define CNFGB_IRQ_SHIFT 3
#define CNFGB_DMA_MASK ((1U << 2) | (1U << 1) | (1U << 0))
#define CNFGB_DMA_SHIFT 0
/* Extended Control Register */
#define ECR_MODE_MASK ((1U << 7) | (1U << 6) | (1U << 5))
#define ECR_MODE_SHIFT 5
#define ECR_MODE_SPP (00U << ECR_MODE_SHIFT)
#define ECR_MODE_PS2 (01U << ECR_MODE_SHIFT)
#define ECR_MODE_PPF (02U << ECR_MODE_SHIFT)
#define ECR_MODE_ECP (03U << ECR_MODE_SHIFT)
#define ECR_MODE_EPP (04U << ECR_MODE_SHIFT)
/* #define ECR_MODE_reserved (05U << ECR_MODE_SHIFT) */
#define ECR_MODE_TST (06U << ECR_MODE_SHIFT)
#define ECR_MODE_CFG (07U << ECR_MODE_SHIFT)
#define ECR_nERRINTR (1U << 4)
#define ECR_DMAEN (1U << 3)
#define ECR_SERVINTR (1U << 2)
#define ECR_F_FULL (1U << 1)
#define ECR_F_EMPTY (1U << 0)
/*--- Private data -----------------------------------------------------*/
/**
* enum parport_ip32_irq_mode - operation mode of interrupt handler
* @PARPORT_IP32_IRQ_FWD: forward interrupt to the upper parport layer
* @PARPORT_IP32_IRQ_HERE: interrupt is handled locally
*/
enum parport_ip32_irq_mode { PARPORT_IP32_IRQ_FWD, PARPORT_IP32_IRQ_HERE };
/**
* struct parport_ip32_private - private stuff for &struct parport
* @regs: register addresses
* @dcr_cache: cached contents of DCR
* @dcr_writable: bit mask of writable DCR bits
* @pword: number of bytes per PWord
* @fifo_depth: number of PWords that FIFO will hold
* @readIntrThreshold: minimum number of PWords we can read
* if we get an interrupt
* @writeIntrThreshold: minimum number of PWords we can write
* if we get an interrupt
* @irq_mode: operation mode of interrupt handler for this port
* @irq_complete: mutex used to wait for an interrupt to occur
*/
struct parport_ip32_private {
struct parport_ip32_regs regs;
unsigned int dcr_cache;
unsigned int dcr_writable;
unsigned int pword;
unsigned int fifo_depth;
unsigned int readIntrThreshold;
unsigned int writeIntrThreshold;
enum parport_ip32_irq_mode irq_mode;
struct completion irq_complete;
};
/*--- Debug code -------------------------------------------------------*/
/*
* pr_debug1 - print debug messages
*
* This is like pr_debug(), but is defined for %DEBUG_PARPORT_IP32 >= 1
*/
#if DEBUG_PARPORT_IP32 >= 1
# define pr_debug1(...) printk(KERN_DEBUG __VA_ARGS__)
#else /* DEBUG_PARPORT_IP32 < 1 */
# define pr_debug1(...) do { } while (0)
#endif
/*
* pr_trace, pr_trace1 - trace function calls
* @p: pointer to &struct parport
* @fmt: printk format string
* @...: parameters for format string
*
* Macros used to trace function calls. The given string is formatted after
* function name. pr_trace() uses pr_debug(), and pr_trace1() uses
* pr_debug1(). __pr_trace() is the low-level macro and is not to be used
* directly.
*/
#define __pr_trace(pr, p, fmt, ...) \
pr("%s: %s" fmt "\n", \
({ const struct parport *__p = (p); \
__p ? __p->name : "parport_ip32"; }), \
__func__ , ##__VA_ARGS__)
#define pr_trace(p, fmt, ...) __pr_trace(pr_debug, p, fmt , ##__VA_ARGS__)
#define pr_trace1(p, fmt, ...) __pr_trace(pr_debug1, p, fmt , ##__VA_ARGS__)
/*
* __pr_probe, pr_probe - print message if @verbose_probing is true
* @p: pointer to &struct parport
* @fmt: printk format string
* @...: parameters for format string
*
* For new lines, use pr_probe(). Use __pr_probe() for continued lines.
*/
#define __pr_probe(...) \
do { if (verbose_probing) printk(__VA_ARGS__); } while (0)
#define pr_probe(p, fmt, ...) \
__pr_probe(KERN_INFO PPIP32 "0x%lx: " fmt, (p)->base , ##__VA_ARGS__)
/*
* parport_ip32_dump_state - print register status of parport
* @p: pointer to &struct parport
* @str: string to add in message
* @show_ecp_config: shall we dump ECP configuration registers too?
*
* This function is only here for debugging purpose, and should be used with
* care. Reading the parallel port registers may have undesired side effects.
* Especially if @show_ecp_config is true, the parallel port is resetted.
* This function is only defined if %DEBUG_PARPORT_IP32 >= 2.
*/
#if DEBUG_PARPORT_IP32 >= 2
static void parport_ip32_dump_state(struct parport *p, char *str,
unsigned int show_ecp_config)
{
struct parport_ip32_private * const priv = p->physport->private_data;
unsigned int i;
printk(KERN_DEBUG PPIP32 "%s: state (%s):\n", p->name, str);
{
static const char ecr_modes[8][4] = {"SPP", "PS2", "PPF",
"ECP", "EPP", "???",
"TST", "CFG"};
unsigned int ecr = readb(priv->regs.ecr);
printk(KERN_DEBUG PPIP32 " ecr=0x%02x", ecr);
printk(" %s",
ecr_modes[(ecr & ECR_MODE_MASK) >> ECR_MODE_SHIFT]);
if (ecr & ECR_nERRINTR)
printk(",nErrIntrEn");
if (ecr & ECR_DMAEN)
printk(",dmaEn");
if (ecr & ECR_SERVINTR)
printk(",serviceIntr");
if (ecr & ECR_F_FULL)
printk(",f_full");
if (ecr & ECR_F_EMPTY)
printk(",f_empty");
printk("\n");
}
if (show_ecp_config) {
unsigned int oecr, cnfgA, cnfgB;
oecr = readb(priv->regs.ecr);
writeb(ECR_MODE_PS2, priv->regs.ecr);
writeb(ECR_MODE_CFG, priv->regs.ecr);
cnfgA = readb(priv->regs.cnfgA);
cnfgB = readb(priv->regs.cnfgB);
writeb(ECR_MODE_PS2, priv->regs.ecr);
writeb(oecr, priv->regs.ecr);
printk(KERN_DEBUG PPIP32 " cnfgA=0x%02x", cnfgA);
printk(" ISA-%s", (cnfgA & CNFGA_IRQ) ? "Level" : "Pulses");
switch (cnfgA & CNFGA_ID_MASK) {
case CNFGA_ID_8:
printk(",8 bits");
break;
case CNFGA_ID_16:
printk(",16 bits");
break;
case CNFGA_ID_32:
printk(",32 bits");
break;
default:
printk(",unknown ID");
break;
}
if (!(cnfgA & CNFGA_nBYTEINTRANS))
printk(",ByteInTrans");
if ((cnfgA & CNFGA_ID_MASK) != CNFGA_ID_8)
printk(",%d byte%s left", cnfgA & CNFGA_PWORDLEFT,
((cnfgA & CNFGA_PWORDLEFT) > 1) ? "s" : "");
printk("\n");
printk(KERN_DEBUG PPIP32 " cnfgB=0x%02x", cnfgB);
printk(" irq=%u,dma=%u",
(cnfgB & CNFGB_IRQ_MASK) >> CNFGB_IRQ_SHIFT,
(cnfgB & CNFGB_DMA_MASK) >> CNFGB_DMA_SHIFT);
printk(",intrValue=%d", !!(cnfgB & CNFGB_INTRVAL));
if (cnfgB & CNFGB_COMPRESS)
printk(",compress");
printk("\n");
}
for (i = 0; i < 2; i++) {
unsigned int dcr = i ? priv->dcr_cache : readb(priv->regs.dcr);
printk(KERN_DEBUG PPIP32 " dcr(%s)=0x%02x",
i ? "soft" : "hard", dcr);
printk(" %s", (dcr & DCR_DIR) ? "rev" : "fwd");
if (dcr & DCR_IRQ)
printk(",ackIntEn");
if (!(dcr & DCR_SELECT))
printk(",nSelectIn");
if (dcr & DCR_nINIT)
printk(",nInit");
if (!(dcr & DCR_AUTOFD))
printk(",nAutoFD");
if (!(dcr & DCR_STROBE))
printk(",nStrobe");
printk("\n");
}
#define sep (f++ ? ',' : ' ')
{
unsigned int f = 0;
unsigned int dsr = readb(priv->regs.dsr);
printk(KERN_DEBUG PPIP32 " dsr=0x%02x", dsr);
if (!(dsr & DSR_nBUSY))
printk("%cBusy", sep);
if (dsr & DSR_nACK)
printk("%cnAck", sep);
if (dsr & DSR_PERROR)
printk("%cPError", sep);
if (dsr & DSR_SELECT)
printk("%cSelect", sep);
if (dsr & DSR_nFAULT)
printk("%cnFault", sep);
if (!(dsr & DSR_nPRINT))
printk("%c(Print)", sep);
if (dsr & DSR_TIMEOUT)
printk("%cTimeout", sep);
printk("\n");
}
#undef sep
}
#else /* DEBUG_PARPORT_IP32 < 2 */
#define parport_ip32_dump_state(...) do { } while (0)
#endif
/*
* CHECK_EXTRA_BITS - track and log extra bits
* @p: pointer to &struct parport
* @b: byte to inspect
* @m: bit mask of authorized bits
*
* This is used to track and log extra bits that should not be there in
* parport_ip32_write_control() and parport_ip32_frob_control(). It is only
* defined if %DEBUG_PARPORT_IP32 >= 1.
*/
#if DEBUG_PARPORT_IP32 >= 1
#define CHECK_EXTRA_BITS(p, b, m) \
do { \
unsigned int __b = (b), __m = (m); \
if (__b & ~__m) \
pr_debug1(PPIP32 "%s: extra bits in %s(%s): " \
"0x%02x/0x%02x\n", \
(p)->name, __func__, #b, __b, __m); \
} while (0)
#else /* DEBUG_PARPORT_IP32 < 1 */
#define CHECK_EXTRA_BITS(...) do { } while (0)
#endif
/*--- IP32 parallel port DMA operations --------------------------------*/
/**
* struct parport_ip32_dma_data - private data needed for DMA operation
* @dir: DMA direction (from or to device)
* @buf: buffer physical address
* @len: buffer length
* @next: address of next bytes to DMA transfer
* @left: number of bytes remaining
* @ctx: next context to write (0: context_a; 1: context_b)
* @irq_on: are the DMA IRQs currently enabled?
* @lock: spinlock to protect access to the structure
*/
struct parport_ip32_dma_data {
enum dma_data_direction dir;
dma_addr_t buf;
dma_addr_t next;
size_t len;
size_t left;
unsigned int ctx;
unsigned int irq_on;
spinlock_t lock;
};
static struct parport_ip32_dma_data parport_ip32_dma;
/**
* parport_ip32_dma_setup_context - setup next DMA context
* @limit: maximum data size for the context
*
* The alignment constraints must be verified in caller function, and the
* parameter @limit must be set accordingly.
*/
static void parport_ip32_dma_setup_context(unsigned int limit)
{
unsigned long flags;
spin_lock_irqsave(&parport_ip32_dma.lock, flags);
if (parport_ip32_dma.left > 0) {
/* Note: ctxreg is "volatile" here only because
* mace->perif.ctrl.parport.context_a and context_b are
* "volatile". */
volatile u64 __iomem *ctxreg = (parport_ip32_dma.ctx == 0) ?
&mace->perif.ctrl.parport.context_a :
&mace->perif.ctrl.parport.context_b;
u64 count;
u64 ctxval;
if (parport_ip32_dma.left <= limit) {
count = parport_ip32_dma.left;
ctxval = MACEPAR_CONTEXT_LASTFLAG;
} else {
count = limit;
ctxval = 0;
}
pr_trace(NULL,
"(%u): 0x%04x:0x%04x, %u -> %u%s",
limit,
(unsigned int)parport_ip32_dma.buf,
(unsigned int)parport_ip32_dma.next,
(unsigned int)count,
parport_ip32_dma.ctx, ctxval ? "*" : "");
ctxval |= parport_ip32_dma.next &
MACEPAR_CONTEXT_BASEADDR_MASK;
ctxval |= ((count - 1) << MACEPAR_CONTEXT_DATALEN_SHIFT) &
MACEPAR_CONTEXT_DATALEN_MASK;
writeq(ctxval, ctxreg);
parport_ip32_dma.next += count;
parport_ip32_dma.left -= count;
parport_ip32_dma.ctx ^= 1U;
}
/* If there is nothing more to send, disable IRQs to avoid to
* face an IRQ storm which can lock the machine. Disable them
* only once. */
if (parport_ip32_dma.left == 0 && parport_ip32_dma.irq_on) {
pr_debug(PPIP32 "IRQ off (ctx)\n");
disable_irq_nosync(MACEISA_PAR_CTXA_IRQ);
disable_irq_nosync(MACEISA_PAR_CTXB_IRQ);
parport_ip32_dma.irq_on = 0;
}
spin_unlock_irqrestore(&parport_ip32_dma.lock, flags);
}
/**
* parport_ip32_dma_interrupt - DMA interrupt handler
* @irq: interrupt number
* @dev_id: unused
*/
static irqreturn_t parport_ip32_dma_interrupt(int irq, void *dev_id)
{
if (parport_ip32_dma.left)
pr_trace(NULL, "(%d): ctx=%d", irq, parport_ip32_dma.ctx);
parport_ip32_dma_setup_context(MACEPAR_CONTEXT_DATA_BOUND);
return IRQ_HANDLED;
}
#if DEBUG_PARPORT_IP32
static irqreturn_t parport_ip32_merr_interrupt(int irq, void *dev_id)
{
pr_trace1(NULL, "(%d)", irq);
return IRQ_HANDLED;
}
#endif
/**
* parport_ip32_dma_start - begins a DMA transfer
* @dir: DMA direction: DMA_TO_DEVICE or DMA_FROM_DEVICE
* @addr: pointer to data buffer
* @count: buffer size
*
* Calls to parport_ip32_dma_start() and parport_ip32_dma_stop() must be
* correctly balanced.
*/
static int parport_ip32_dma_start(enum dma_data_direction dir,
void *addr, size_t count)
{
unsigned int limit;
u64 ctrl;
pr_trace(NULL, "(%d, %lu)", dir, (unsigned long)count);
/* FIXME - add support for DMA_FROM_DEVICE. In this case, buffer must
* be 64 bytes aligned. */
BUG_ON(dir != DMA_TO_DEVICE);
/* Reset DMA controller */
ctrl = MACEPAR_CTLSTAT_RESET;
writeq(ctrl, &mace->perif.ctrl.parport.cntlstat);
/* DMA IRQs should normally be enabled */
if (!parport_ip32_dma.irq_on) {
WARN_ON(1);
enable_irq(MACEISA_PAR_CTXA_IRQ);
enable_irq(MACEISA_PAR_CTXB_IRQ);
parport_ip32_dma.irq_on = 1;
}
/* Prepare DMA pointers */
parport_ip32_dma.dir = dir;
parport_ip32_dma.buf = dma_map_single(NULL, addr, count, dir);
parport_ip32_dma.len = count;
parport_ip32_dma.next = parport_ip32_dma.buf;
parport_ip32_dma.left = parport_ip32_dma.len;
parport_ip32_dma.ctx = 0;
/* Setup DMA direction and first two contexts */
ctrl = (dir == DMA_TO_DEVICE) ? 0 : MACEPAR_CTLSTAT_DIRECTION;
writeq(ctrl, &mace->perif.ctrl.parport.cntlstat);
/* Single transfer should not cross a 4K page boundary */
limit = MACEPAR_CONTEXT_DATA_BOUND -
(parport_ip32_dma.next & (MACEPAR_CONTEXT_DATA_BOUND - 1));
parport_ip32_dma_setup_context(limit);
parport_ip32_dma_setup_context(MACEPAR_CONTEXT_DATA_BOUND);
/* Real start of DMA transfer */
ctrl |= MACEPAR_CTLSTAT_ENABLE;
writeq(ctrl, &mace->perif.ctrl.parport.cntlstat);
return 0;
}
/**
* parport_ip32_dma_stop - ends a running DMA transfer
*
* Calls to parport_ip32_dma_start() and parport_ip32_dma_stop() must be
* correctly balanced.
*/
static void parport_ip32_dma_stop(void)
{
u64 ctx_a;
u64 ctx_b;
u64 ctrl;
u64 diag;
size_t res[2]; /* {[0] = res_a, [1] = res_b} */
pr_trace(NULL, "()");
/* Disable IRQs */
spin_lock_irq(&parport_ip32_dma.lock);
if (parport_ip32_dma.irq_on) {
pr_debug(PPIP32 "IRQ off (stop)\n");
disable_irq_nosync(MACEISA_PAR_CTXA_IRQ);
disable_irq_nosync(MACEISA_PAR_CTXB_IRQ);
parport_ip32_dma.irq_on = 0;
}
spin_unlock_irq(&parport_ip32_dma.lock);
/* Force IRQ synchronization, even if the IRQs were disabled
* elsewhere. */
synchronize_irq(MACEISA_PAR_CTXA_IRQ);
synchronize_irq(MACEISA_PAR_CTXB_IRQ);
/* Stop DMA transfer */
ctrl = readq(&mace->perif.ctrl.parport.cntlstat);
ctrl &= ~MACEPAR_CTLSTAT_ENABLE;
writeq(ctrl, &mace->perif.ctrl.parport.cntlstat);
/* Adjust residue (parport_ip32_dma.left) */
ctx_a = readq(&mace->perif.ctrl.parport.context_a);
ctx_b = readq(&mace->perif.ctrl.parport.context_b);
ctrl = readq(&mace->perif.ctrl.parport.cntlstat);
diag = readq(&mace->perif.ctrl.parport.diagnostic);
res[0] = (ctrl & MACEPAR_CTLSTAT_CTXA_VALID) ?
1 + ((ctx_a & MACEPAR_CONTEXT_DATALEN_MASK) >>
MACEPAR_CONTEXT_DATALEN_SHIFT) :
0;
res[1] = (ctrl & MACEPAR_CTLSTAT_CTXB_VALID) ?
1 + ((ctx_b & MACEPAR_CONTEXT_DATALEN_MASK) >>
MACEPAR_CONTEXT_DATALEN_SHIFT) :
0;
if (diag & MACEPAR_DIAG_DMACTIVE)
res[(diag & MACEPAR_DIAG_CTXINUSE) != 0] =
1 + ((diag & MACEPAR_DIAG_CTRMASK) >>
MACEPAR_DIAG_CTRSHIFT);
parport_ip32_dma.left += res[0] + res[1];
/* Reset DMA controller, and re-enable IRQs */
ctrl = MACEPAR_CTLSTAT_RESET;
writeq(ctrl, &mace->perif.ctrl.parport.cntlstat);
pr_debug(PPIP32 "IRQ on (stop)\n");
enable_irq(MACEISA_PAR_CTXA_IRQ);
enable_irq(MACEISA_PAR_CTXB_IRQ);
parport_ip32_dma.irq_on = 1;
dma_unmap_single(NULL, parport_ip32_dma.buf, parport_ip32_dma.len,
parport_ip32_dma.dir);
}
/**
* parport_ip32_dma_get_residue - get residue from last DMA transfer
*
* Returns the number of bytes remaining from last DMA transfer.
*/
static inline size_t parport_ip32_dma_get_residue(void)
{
return parport_ip32_dma.left;
}
/**
* parport_ip32_dma_register - initialize DMA engine
*
* Returns zero for success.
*/
static int parport_ip32_dma_register(void)
{
int err;
spin_lock_init(&parport_ip32_dma.lock);
parport_ip32_dma.irq_on = 1;
/* Reset DMA controller */
writeq(MACEPAR_CTLSTAT_RESET, &mace->perif.ctrl.parport.cntlstat);
/* Request IRQs */
err = request_irq(MACEISA_PAR_CTXA_IRQ, parport_ip32_dma_interrupt,
0, "parport_ip32", NULL);
if (err)
goto fail_a;
err = request_irq(MACEISA_PAR_CTXB_IRQ, parport_ip32_dma_interrupt,
0, "parport_ip32", NULL);
if (err)
goto fail_b;
#if DEBUG_PARPORT_IP32
/* FIXME - what is this IRQ for? */
err = request_irq(MACEISA_PAR_MERR_IRQ, parport_ip32_merr_interrupt,
0, "parport_ip32", NULL);
if (err)
goto fail_merr;
#endif
return 0;
#if DEBUG_PARPORT_IP32
fail_merr:
free_irq(MACEISA_PAR_CTXB_IRQ, NULL);
#endif
fail_b:
free_irq(MACEISA_PAR_CTXA_IRQ, NULL);
fail_a:
return err;
}
/**
* parport_ip32_dma_unregister - release and free resources for DMA engine
*/
static void parport_ip32_dma_unregister(void)
{
#if DEBUG_PARPORT_IP32
free_irq(MACEISA_PAR_MERR_IRQ, NULL);
#endif
free_irq(MACEISA_PAR_CTXB_IRQ, NULL);
free_irq(MACEISA_PAR_CTXA_IRQ, NULL);
}
/*--- Interrupt handlers and associates --------------------------------*/
/**
* parport_ip32_wakeup - wakes up code waiting for an interrupt
* @p: pointer to &struct parport
*/
static inline void parport_ip32_wakeup(struct parport *p)
{
struct parport_ip32_private * const priv = p->physport->private_data;
complete(&priv->irq_complete);
}
/**
* parport_ip32_interrupt - interrupt handler
* @irq: interrupt number
* @dev_id: pointer to &struct parport
*
* Caught interrupts are forwarded to the upper parport layer if IRQ_mode is
* %PARPORT_IP32_IRQ_FWD.
*/
static irqreturn_t parport_ip32_interrupt(int irq, void *dev_id)
{
struct parport * const p = dev_id;
struct parport_ip32_private * const priv = p->physport->private_data;
enum parport_ip32_irq_mode irq_mode = priv->irq_mode;
switch (irq_mode) {
case PARPORT_IP32_IRQ_FWD:
return parport_irq_handler(irq, dev_id);
case PARPORT_IP32_IRQ_HERE:
parport_ip32_wakeup(p);
break;
}
return IRQ_HANDLED;
}
/*--- Some utility function to manipulate ECR register -----------------*/
/**
* parport_ip32_read_econtrol - read contents of the ECR register
* @p: pointer to &struct parport
*/
static inline unsigned int parport_ip32_read_econtrol(struct parport *p)
{
struct parport_ip32_private * const priv = p->physport->private_data;
return readb(priv->regs.ecr);
}
/**
* parport_ip32_write_econtrol - write new contents to the ECR register
* @p: pointer to &struct parport
* @c: new value to write
*/
static inline void parport_ip32_write_econtrol(struct parport *p,
unsigned int c)
{
struct parport_ip32_private * const priv = p->physport->private_data;
writeb(c, priv->regs.ecr);
}
/**
* parport_ip32_frob_econtrol - change bits from the ECR register
* @p: pointer to &struct parport
* @mask: bit mask of bits to change
* @val: new value for changed bits
*
* Read from the ECR, mask out the bits in @mask, exclusive-or with the bits
* in @val, and write the result to the ECR.
*/
static inline void parport_ip32_frob_econtrol(struct parport *p,
unsigned int mask,
unsigned int val)
{
unsigned int c;
c = (parport_ip32_read_econtrol(p) & ~mask) ^ val;
parport_ip32_write_econtrol(p, c);
}
/**
* parport_ip32_set_mode - change mode of ECP port
* @p: pointer to &struct parport
* @mode: new mode to write in ECR
*
* ECR is reset in a sane state (interrupts and DMA disabled), and placed in
* mode @mode. Go through PS2 mode if needed.
*/
static void parport_ip32_set_mode(struct parport *p, unsigned int mode)
{
unsigned int omode;
mode &= ECR_MODE_MASK;
omode = parport_ip32_read_econtrol(p) & ECR_MODE_MASK;
if (!(mode == ECR_MODE_SPP || mode == ECR_MODE_PS2
|| omode == ECR_MODE_SPP || omode == ECR_MODE_PS2)) {
/* We have to go through PS2 mode */
unsigned int ecr = ECR_MODE_PS2 | ECR_nERRINTR | ECR_SERVINTR;
parport_ip32_write_econtrol(p, ecr);
}
parport_ip32_write_econtrol(p, mode | ECR_nERRINTR | ECR_SERVINTR);
}
/*--- Basic functions needed for parport -------------------------------*/
/**
* parport_ip32_read_data - return current contents of the DATA register
* @p: pointer to &struct parport
*/
static inline unsigned char parport_ip32_read_data(struct parport *p)
{
struct parport_ip32_private * const priv = p->physport->private_data;
return readb(priv->regs.data);
}
/**
* parport_ip32_write_data - set new contents for the DATA register
* @p: pointer to &struct parport
* @d: new value to write
*/
static inline void parport_ip32_write_data(struct parport *p, unsigned char d)
{
struct parport_ip32_private * const priv = p->physport->private_data;
writeb(d, priv->regs.data);
}
/**
* parport_ip32_read_status - return current contents of the DSR register
* @p: pointer to &struct parport
*/
static inline unsigned char parport_ip32_read_status(struct parport *p)
{
struct parport_ip32_private * const priv = p->physport->private_data;
return readb(priv->regs.dsr);
}
/**
* __parport_ip32_read_control - return cached contents of the DCR register
* @p: pointer to &struct parport
*/
static inline unsigned int __parport_ip32_read_control(struct parport *p)
{
struct parport_ip32_private * const priv = p->physport->private_data;
return priv->dcr_cache; /* use soft copy */
}
/**
* __parport_ip32_write_control - set new contents for the DCR register
* @p: pointer to &struct parport
* @c: new value to write
*/
static inline void __parport_ip32_write_control(struct parport *p,
unsigned int c)
{
struct parport_ip32_private * const priv = p->physport->private_data;
CHECK_EXTRA_BITS(p, c, priv->dcr_writable);
c &= priv->dcr_writable; /* only writable bits */
writeb(c, priv->regs.dcr);
priv->dcr_cache = c; /* update soft copy */
}
/**
* __parport_ip32_frob_control - change bits from the DCR register
* @p: pointer to &struct parport
* @mask: bit mask of bits to change
* @val: new value for changed bits
*
* This is equivalent to read from the DCR, mask out the bits in @mask,
* exclusive-or with the bits in @val, and write the result to the DCR.
* Actually, the cached contents of the DCR is used.
*/
static inline void __parport_ip32_frob_control(struct parport *p,
unsigned int mask,
unsigned int val)
{
unsigned int c;
c = (__parport_ip32_read_control(p) & ~mask) ^ val;
__parport_ip32_write_control(p, c);
}
/**
* parport_ip32_read_control - return cached contents of the DCR register
* @p: pointer to &struct parport
*
* The return value is masked so as to only return the value of %DCR_STROBE,
* %DCR_AUTOFD, %DCR_nINIT, and %DCR_SELECT.
*/
static inline unsigned char parport_ip32_read_control(struct parport *p)
{
const unsigned int rm =
DCR_STROBE | DCR_AUTOFD | DCR_nINIT | DCR_SELECT;
return __parport_ip32_read_control(p) & rm;
}
/**
* parport_ip32_write_control - set new contents for the DCR register
* @p: pointer to &struct parport
* @c: new value to write
*
* The value is masked so as to only change the value of %DCR_STROBE,
* %DCR_AUTOFD, %DCR_nINIT, and %DCR_SELECT.
*/
static inline void parport_ip32_write_control(struct parport *p,
unsigned char c)
{
const unsigned int wm =
DCR_STROBE | DCR_AUTOFD | DCR_nINIT | DCR_SELECT;
CHECK_EXTRA_BITS(p, c, wm);
__parport_ip32_frob_control(p, wm, c & wm);
}
/**
* parport_ip32_frob_control - change bits from the DCR register
* @p: pointer to &struct parport
* @mask: bit mask of bits to change
* @val: new value for changed bits
*
* This differs from __parport_ip32_frob_control() in that it only allows to
* change the value of %DCR_STROBE, %DCR_AUTOFD, %DCR_nINIT, and %DCR_SELECT.
*/
static inline unsigned char parport_ip32_frob_control(struct parport *p,
unsigned char mask,
unsigned char val)
{
const unsigned int wm =
DCR_STROBE | DCR_AUTOFD | DCR_nINIT | DCR_SELECT;
CHECK_EXTRA_BITS(p, mask, wm);
CHECK_EXTRA_BITS(p, val, wm);
__parport_ip32_frob_control(p, mask & wm, val & wm);
return parport_ip32_read_control(p);
}
/**
* parport_ip32_disable_irq - disable interrupts on the rising edge of nACK
* @p: pointer to &struct parport
*/
static inline void parport_ip32_disable_irq(struct parport *p)
{
__parport_ip32_frob_control(p, DCR_IRQ, 0);
}
/**
* parport_ip32_enable_irq - enable interrupts on the rising edge of nACK
* @p: pointer to &struct parport
*/
static inline void parport_ip32_enable_irq(struct parport *p)
{
__parport_ip32_frob_control(p, DCR_IRQ, DCR_IRQ);
}
/**
* parport_ip32_data_forward - enable host-to-peripheral communications
* @p: pointer to &struct parport
*
* Enable the data line drivers, for 8-bit host-to-peripheral communications.
*/
static inline void parport_ip32_data_forward(struct parport *p)
{
__parport_ip32_frob_control(p, DCR_DIR, 0);
}
/**
* parport_ip32_data_reverse - enable peripheral-to-host communications
* @p: pointer to &struct parport
*
* Place the data bus in a high impedance state, if @p->modes has the
* PARPORT_MODE_TRISTATE bit set.
*/
static inline void parport_ip32_data_reverse(struct parport *p)
{
__parport_ip32_frob_control(p, DCR_DIR, DCR_DIR);
}
/**
* parport_ip32_init_state - for core parport code
* @dev: pointer to &struct pardevice
* @s: pointer to &struct parport_state to initialize
*/
static void parport_ip32_init_state(struct pardevice *dev,
struct parport_state *s)
{
s->u.ip32.dcr = DCR_SELECT | DCR_nINIT;
s->u.ip32.ecr = ECR_MODE_PS2 | ECR_nERRINTR | ECR_SERVINTR;
}
/**
* parport_ip32_save_state - for core parport code
* @p: pointer to &struct parport
* @s: pointer to &struct parport_state to save state to
*/
static void parport_ip32_save_state(struct parport *p,
struct parport_state *s)
{
s->u.ip32.dcr = __parport_ip32_read_control(p);
s->u.ip32.ecr = parport_ip32_read_econtrol(p);
}
/**
* parport_ip32_restore_state - for core parport code
* @p: pointer to &struct parport
* @s: pointer to &struct parport_state to restore state from
*/
static void parport_ip32_restore_state(struct parport *p,
struct parport_state *s)
{
parport_ip32_set_mode(p, s->u.ip32.ecr & ECR_MODE_MASK);
parport_ip32_write_econtrol(p, s->u.ip32.ecr);
__parport_ip32_write_control(p, s->u.ip32.dcr);
}
/*--- EPP mode functions -----------------------------------------------*/
/**
* parport_ip32_clear_epp_timeout - clear Timeout bit in EPP mode
* @p: pointer to &struct parport
*
* Returns 1 if the Timeout bit is clear, and 0 otherwise.
*/
static unsigned int parport_ip32_clear_epp_timeout(struct parport *p)
{
struct parport_ip32_private * const priv = p->physport->private_data;
unsigned int cleared;
if (!(parport_ip32_read_status(p) & DSR_TIMEOUT))
cleared = 1;
else {
unsigned int r;
/* To clear timeout some chips require double read */
parport_ip32_read_status(p);
r = parport_ip32_read_status(p);
/* Some reset by writing 1 */
writeb(r | DSR_TIMEOUT, priv->regs.dsr);
/* Others by writing 0 */
writeb(r & ~DSR_TIMEOUT, priv->regs.dsr);
r = parport_ip32_read_status(p);
cleared = !(r & DSR_TIMEOUT);
}
pr_trace(p, "(): %s", cleared ? "cleared" : "failed");
return cleared;
}
/**
* parport_ip32_epp_read - generic EPP read function
* @eppreg: I/O register to read from
* @p: pointer to &struct parport
* @buf: buffer to store read data
* @len: length of buffer @buf
* @flags: may be PARPORT_EPP_FAST
*/
static size_t parport_ip32_epp_read(void __iomem *eppreg,
struct parport *p, void *buf,
size_t len, int flags)
{
struct parport_ip32_private * const priv = p->physport->private_data;
size_t got;
parport_ip32_set_mode(p, ECR_MODE_EPP);
parport_ip32_data_reverse(p);
parport_ip32_write_control(p, DCR_nINIT);
if ((flags & PARPORT_EPP_FAST) && (len > 1)) {
readsb(eppreg, buf, len);
if (readb(priv->regs.dsr) & DSR_TIMEOUT) {
parport_ip32_clear_epp_timeout(p);
return -EIO;
}
got = len;
} else {
u8 *bufp = buf;
for (got = 0; got < len; got++) {
*bufp++ = readb(eppreg);
if (readb(priv->regs.dsr) & DSR_TIMEOUT) {
parport_ip32_clear_epp_timeout(p);
break;
}
}
}
parport_ip32_data_forward(p);
parport_ip32_set_mode(p, ECR_MODE_PS2);
return got;
}
/**
* parport_ip32_epp_write - generic EPP write function
* @eppreg: I/O register to write to
* @p: pointer to &struct parport
* @buf: buffer of data to write
* @len: length of buffer @buf
* @flags: may be PARPORT_EPP_FAST
*/
static size_t parport_ip32_epp_write(void __iomem *eppreg,
struct parport *p, const void *buf,
size_t len, int flags)
{
struct parport_ip32_private * const priv = p->physport->private_data;
size_t written;
parport_ip32_set_mode(p, ECR_MODE_EPP);
parport_ip32_data_forward(p);
parport_ip32_write_control(p, DCR_nINIT);
if ((flags & PARPORT_EPP_FAST) && (len > 1)) {
writesb(eppreg, buf, len);
if (readb(priv->regs.dsr) & DSR_TIMEOUT) {
parport_ip32_clear_epp_timeout(p);
return -EIO;
}
written = len;
} else {
const u8 *bufp = buf;
for (written = 0; written < len; written++) {
writeb(*bufp++, eppreg);
if (readb(priv->regs.dsr) & DSR_TIMEOUT) {
parport_ip32_clear_epp_timeout(p);
break;
}
}
}
parport_ip32_set_mode(p, ECR_MODE_PS2);
return written;
}
/**
* parport_ip32_epp_read_data - read a block of data in EPP mode
* @p: pointer to &struct parport
* @buf: buffer to store read data
* @len: length of buffer @buf
* @flags: may be PARPORT_EPP_FAST
*/
static size_t parport_ip32_epp_read_data(struct parport *p, void *buf,
size_t len, int flags)
{
struct parport_ip32_private * const priv = p->physport->private_data;
return parport_ip32_epp_read(priv->regs.eppData0, p, buf, len, flags);
}
/**
* parport_ip32_epp_write_data - write a block of data in EPP mode
* @p: pointer to &struct parport
* @buf: buffer of data to write
* @len: length of buffer @buf
* @flags: may be PARPORT_EPP_FAST
*/
static size_t parport_ip32_epp_write_data(struct parport *p, const void *buf,
size_t len, int flags)
{
struct parport_ip32_private * const priv = p->physport->private_data;
return parport_ip32_epp_write(priv->regs.eppData0, p, buf, len, flags);
}
/**
* parport_ip32_epp_read_addr - read a block of addresses in EPP mode
* @p: pointer to &struct parport
* @buf: buffer to store read data
* @len: length of buffer @buf
* @flags: may be PARPORT_EPP_FAST
*/
static size_t parport_ip32_epp_read_addr(struct parport *p, void *buf,
size_t len, int flags)
{
struct parport_ip32_private * const priv = p->physport->private_data;
return parport_ip32_epp_read(priv->regs.eppAddr, p, buf, len, flags);
}
/**
* parport_ip32_epp_write_addr - write a block of addresses in EPP mode
* @p: pointer to &struct parport
* @buf: buffer of data to write
* @len: length of buffer @buf
* @flags: may be PARPORT_EPP_FAST
*/
static size_t parport_ip32_epp_write_addr(struct parport *p, const void *buf,
size_t len, int flags)
{
struct parport_ip32_private * const priv = p->physport->private_data;
return parport_ip32_epp_write(priv->regs.eppAddr, p, buf, len, flags);
}
/*--- ECP mode functions (FIFO) ----------------------------------------*/
/**
* parport_ip32_fifo_wait_break - check if the waiting function should return
* @p: pointer to &struct parport
* @expire: timeout expiring date, in jiffies
*
* parport_ip32_fifo_wait_break() checks if the waiting function should return
* immediately or not. The break conditions are:
* - expired timeout;
* - a pending signal;
* - nFault asserted low.
* This function also calls cond_resched().
*/
static unsigned int parport_ip32_fifo_wait_break(struct parport *p,
unsigned long expire)
{
cond_resched();
if (time_after(jiffies, expire)) {
pr_debug1(PPIP32 "%s: FIFO write timed out\n", p->name);
return 1;
}
if (signal_pending(current)) {
pr_debug1(PPIP32 "%s: Signal pending\n", p->name);
return 1;
}
if (!(parport_ip32_read_status(p) & DSR_nFAULT)) {
pr_debug1(PPIP32 "%s: nFault asserted low\n", p->name);
return 1;
}
return 0;
}
/**
* parport_ip32_fwp_wait_polling - wait for FIFO to empty (polling)
* @p: pointer to &struct parport
*
* Returns the number of bytes that can safely be written in the FIFO. A
* return value of zero means that the calling function should terminate as
* fast as possible.
*/
static unsigned int parport_ip32_fwp_wait_polling(struct parport *p)
{
struct parport_ip32_private * const priv = p->physport->private_data;
struct parport * const physport = p->physport;
unsigned long expire;
unsigned int count;
unsigned int ecr;
expire = jiffies + physport->cad->timeout;
count = 0;
while (1) {
if (parport_ip32_fifo_wait_break(p, expire))
break;
/* Check FIFO state. We do nothing when the FIFO is nor full,
* nor empty. It appears that the FIFO full bit is not always
* reliable, the FIFO state is sometimes wrongly reported, and
* the chip gets confused if we give it another byte. */
ecr = parport_ip32_read_econtrol(p);
if (ecr & ECR_F_EMPTY) {
/* FIFO is empty, fill it up */
count = priv->fifo_depth;
break;
}
/* Wait a moment... */
udelay(FIFO_POLLING_INTERVAL);
} /* while (1) */
return count;
}
/**
* parport_ip32_fwp_wait_interrupt - wait for FIFO to empty (interrupt-driven)
* @p: pointer to &struct parport
*
* Returns the number of bytes that can safely be written in the FIFO. A
* return value of zero means that the calling function should terminate as
* fast as possible.
*/
static unsigned int parport_ip32_fwp_wait_interrupt(struct parport *p)
{
static unsigned int lost_interrupt = 0;
struct parport_ip32_private * const priv = p->physport->private_data;
struct parport * const physport = p->physport;
unsigned long nfault_timeout;
unsigned long expire;
unsigned int count;
unsigned int ecr;
nfault_timeout = min((unsigned long)physport->cad->timeout,
msecs_to_jiffies(FIFO_NFAULT_TIMEOUT));
expire = jiffies + physport->cad->timeout;
count = 0;
while (1) {
if (parport_ip32_fifo_wait_break(p, expire))
break;
/* Initialize mutex used to take interrupts into account */
INIT_COMPLETION(priv->irq_complete);
/* Enable serviceIntr */
parport_ip32_frob_econtrol(p, ECR_SERVINTR, 0);
/* Enabling serviceIntr while the FIFO is empty does not
* always generate an interrupt, so check for emptiness
* now. */
ecr = parport_ip32_read_econtrol(p);
if (!(ecr & ECR_F_EMPTY)) {
/* FIFO is not empty: wait for an interrupt or a
* timeout to occur */
wait_for_completion_interruptible_timeout(
&priv->irq_complete, nfault_timeout);
ecr = parport_ip32_read_econtrol(p);
if ((ecr & ECR_F_EMPTY) && !(ecr & ECR_SERVINTR)
&& !lost_interrupt) {
printk(KERN_WARNING PPIP32
"%s: lost interrupt in %s\n",
p->name, __func__);
lost_interrupt = 1;
}
}
/* Disable serviceIntr */
parport_ip32_frob_econtrol(p, ECR_SERVINTR, ECR_SERVINTR);
/* Check FIFO state */
if (ecr & ECR_F_EMPTY) {
/* FIFO is empty, fill it up */
count = priv->fifo_depth;
break;
} else if (ecr & ECR_SERVINTR) {
/* FIFO is not empty, but we know that can safely push
* writeIntrThreshold bytes into it */
count = priv->writeIntrThreshold;
break;
}
/* FIFO is not empty, and we did not get any interrupt.
* Either it's time to check for nFault, or a signal is
* pending. This is verified in
* parport_ip32_fifo_wait_break(), so we continue the loop. */
} /* while (1) */
return count;
}
/**
* parport_ip32_fifo_write_block_pio - write a block of data (PIO mode)
* @p: pointer to &struct parport
* @buf: buffer of data to write
* @len: length of buffer @buf
*
* Uses PIO to write the contents of the buffer @buf into the parallel port
* FIFO. Returns the number of bytes that were actually written. It can work
* with or without the help of interrupts. The parallel port must be
* correctly initialized before calling parport_ip32_fifo_write_block_pio().
*/
static size_t parport_ip32_fifo_write_block_pio(struct parport *p,
const void *buf, size_t len)
{
struct parport_ip32_private * const priv = p->physport->private_data;
const u8 *bufp = buf;
size_t left = len;
priv->irq_mode = PARPORT_IP32_IRQ_HERE;
while (left > 0) {
unsigned int count;
count = (p->irq == PARPORT_IRQ_NONE) ?
parport_ip32_fwp_wait_polling(p) :
parport_ip32_fwp_wait_interrupt(p);
if (count == 0)
break; /* Transmission should be stopped */
if (count > left)
count = left;
if (count == 1) {
writeb(*bufp, priv->regs.fifo);
bufp++, left--;
} else {
writesb(priv->regs.fifo, bufp, count);
bufp += count, left -= count;
}
}
priv->irq_mode = PARPORT_IP32_IRQ_FWD;
return len - left;
}
/**
* parport_ip32_fifo_write_block_dma - write a block of data (DMA mode)
* @p: pointer to &struct parport
* @buf: buffer of data to write
* @len: length of buffer @buf
*
* Uses DMA to write the contents of the buffer @buf into the parallel port
* FIFO. Returns the number of bytes that were actually written. The
* parallel port must be correctly initialized before calling
* parport_ip32_fifo_write_block_dma().
*/
static size_t parport_ip32_fifo_write_block_dma(struct parport *p,
const void *buf, size_t len)
{
struct parport_ip32_private * const priv = p->physport->private_data;
struct parport * const physport = p->physport;
unsigned long nfault_timeout;
unsigned long expire;
size_t written;
unsigned int ecr;
priv->irq_mode = PARPORT_IP32_IRQ_HERE;
parport_ip32_dma_start(DMA_TO_DEVICE, (void *)buf, len);
INIT_COMPLETION(priv->irq_complete);
parport_ip32_frob_econtrol(p, ECR_DMAEN | ECR_SERVINTR, ECR_DMAEN);
nfault_timeout = min((unsigned long)physport->cad->timeout,
msecs_to_jiffies(FIFO_NFAULT_TIMEOUT));
expire = jiffies + physport->cad->timeout;
while (1) {
if (parport_ip32_fifo_wait_break(p, expire))
break;
wait_for_completion_interruptible_timeout(&priv->irq_complete,
nfault_timeout);
ecr = parport_ip32_read_econtrol(p);
if (ecr & ECR_SERVINTR)
break; /* DMA transfer just finished */
}
parport_ip32_dma_stop();
written = len - parport_ip32_dma_get_residue();
priv->irq_mode = PARPORT_IP32_IRQ_FWD;
return written;
}
/**
* parport_ip32_fifo_write_block - write a block of data
* @p: pointer to &struct parport
* @buf: buffer of data to write
* @len: length of buffer @buf
*
* Uses PIO or DMA to write the contents of the buffer @buf into the parallel
* p FIFO. Returns the number of bytes that were actually written.
*/
static size_t parport_ip32_fifo_write_block(struct parport *p,
const void *buf, size_t len)
{
size_t written = 0;
if (len)
/* FIXME - Maybe some threshold value should be set for @len
* under which we revert to PIO mode? */
written = (p->modes & PARPORT_MODE_DMA) ?
parport_ip32_fifo_write_block_dma(p, buf, len) :
parport_ip32_fifo_write_block_pio(p, buf, len);
return written;
}
/**
* parport_ip32_drain_fifo - wait for FIFO to empty
* @p: pointer to &struct parport
* @timeout: timeout, in jiffies
*
* This function waits for FIFO to empty. It returns 1 when FIFO is empty, or
* 0 if the timeout @timeout is reached before, or if a signal is pending.
*/
static unsigned int parport_ip32_drain_fifo(struct parport *p,
unsigned long timeout)
{
unsigned long expire = jiffies + timeout;
unsigned int polling_interval;
unsigned int counter;
/* Busy wait for approx. 200us */
for (counter = 0; counter < 40; counter++) {
if (parport_ip32_read_econtrol(p) & ECR_F_EMPTY)
break;
if (time_after(jiffies, expire))
break;
if (signal_pending(current))
break;
udelay(5);
}
/* Poll slowly. Polling interval starts with 1 millisecond, and is
* increased exponentially until 128. */
polling_interval = 1; /* msecs */
while (!(parport_ip32_read_econtrol(p) & ECR_F_EMPTY)) {
if (time_after_eq(jiffies, expire))
break;
msleep_interruptible(polling_interval);
if (signal_pending(current))
break;
if (polling_interval < 128)
polling_interval *= 2;
}
return !!(parport_ip32_read_econtrol(p) & ECR_F_EMPTY);
}
/**
* parport_ip32_get_fifo_residue - reset FIFO
* @p: pointer to &struct parport
* @mode: current operation mode (ECR_MODE_PPF or ECR_MODE_ECP)
*
* This function resets FIFO, and returns the number of bytes remaining in it.
*/
static unsigned int parport_ip32_get_fifo_residue(struct parport *p,
unsigned int mode)
{
struct parport_ip32_private * const priv = p->physport->private_data;
unsigned int residue;
unsigned int cnfga;
/* FIXME - We are missing one byte if the printer is off-line. I
* don't know how to detect this. It looks that the full bit is not
* always reliable. For the moment, the problem is avoided in most
* cases by testing for BUSY in parport_ip32_compat_write_data().
*/
if (parport_ip32_read_econtrol(p) & ECR_F_EMPTY)
residue = 0;
else {
pr_debug1(PPIP32 "%s: FIFO is stuck\n", p->name);
/* Stop all transfers.
*
* Microsoft's document instructs to drive DCR_STROBE to 0,
* but it doesn't work (at least in Compatibility mode, not
* tested in ECP mode). Switching directly to Test mode (as
* in parport_pc) is not an option: it does confuse the port,
* ECP service interrupts are no more working after that. A
* hard reset is then needed to revert to a sane state.
*
* Let's hope that the FIFO is really stuck and that the
* peripheral doesn't wake up now.
*/
parport_ip32_frob_control(p, DCR_STROBE, 0);
/* Fill up FIFO */
for (residue = priv->fifo_depth; residue > 0; residue--) {
if (parport_ip32_read_econtrol(p) & ECR_F_FULL)
break;
writeb(0x00, priv->regs.fifo);
}
}
if (residue)
pr_debug1(PPIP32 "%s: %d PWord%s left in FIFO\n",
p->name, residue,
(residue == 1) ? " was" : "s were");
/* Now reset the FIFO */
parport_ip32_set_mode(p, ECR_MODE_PS2);
/* Host recovery for ECP mode */
if (mode == ECR_MODE_ECP) {
parport_ip32_data_reverse(p);
parport_ip32_frob_control(p, DCR_nINIT, 0);
if (parport_wait_peripheral(p, DSR_PERROR, 0))
pr_debug1(PPIP32 "%s: PEerror timeout 1 in %s\n",
p->name, __func__);
parport_ip32_frob_control(p, DCR_STROBE, DCR_STROBE);
parport_ip32_frob_control(p, DCR_nINIT, DCR_nINIT);
if (parport_wait_peripheral(p, DSR_PERROR, DSR_PERROR))
pr_debug1(PPIP32 "%s: PEerror timeout 2 in %s\n",
p->name, __func__);
}
/* Adjust residue if needed */
parport_ip32_set_mode(p, ECR_MODE_CFG);
cnfga = readb(priv->regs.cnfgA);
if (!(cnfga & CNFGA_nBYTEINTRANS)) {
pr_debug1(PPIP32 "%s: cnfgA contains 0x%02x\n",
p->name, cnfga);
pr_debug1(PPIP32 "%s: Accounting for extra byte\n",
p->name);
residue++;
}
/* Don't care about partial PWords since we do not support
* PWord != 1 byte. */
/* Back to forward PS2 mode. */
parport_ip32_set_mode(p, ECR_MODE_PS2);
parport_ip32_data_forward(p);
return residue;
}
/**
* parport_ip32_compat_write_data - write a block of data in SPP mode
* @p: pointer to &struct parport
* @buf: buffer of data to write
* @len: length of buffer @buf
* @flags: ignored
*/
static size_t parport_ip32_compat_write_data(struct parport *p,
const void *buf, size_t len,
int flags)
{
static unsigned int ready_before = 1;
struct parport_ip32_private * const priv = p->physport->private_data;
struct parport * const physport = p->physport;
size_t written = 0;
/* Special case: a timeout of zero means we cannot call schedule().
* Also if O_NONBLOCK is set then use the default implementation. */
if (physport->cad->timeout <= PARPORT_INACTIVITY_O_NONBLOCK)
return parport_ieee1284_write_compat(p, buf, len, flags);
/* Reset FIFO, go in forward mode, and disable ackIntEn */
parport_ip32_set_mode(p, ECR_MODE_PS2);
parport_ip32_write_control(p, DCR_SELECT | DCR_nINIT);
parport_ip32_data_forward(p);
parport_ip32_disable_irq(p);
parport_ip32_set_mode(p, ECR_MODE_PPF);
physport->ieee1284.phase = IEEE1284_PH_FWD_DATA;
/* Wait for peripheral to become ready */
if (parport_wait_peripheral(p, DSR_nBUSY | DSR_nFAULT,
DSR_nBUSY | DSR_nFAULT)) {
/* Avoid to flood the logs */
if (ready_before)
printk(KERN_INFO PPIP32 "%s: not ready in %s\n",
p->name, __func__);
ready_before = 0;
goto stop;
}
ready_before = 1;
written = parport_ip32_fifo_write_block(p, buf, len);
/* Wait FIFO to empty. Timeout is proportional to FIFO_depth. */
parport_ip32_drain_fifo(p, physport->cad->timeout * priv->fifo_depth);
/* Check for a potential residue */
written -= parport_ip32_get_fifo_residue(p, ECR_MODE_PPF);
/* Then, wait for BUSY to get low. */
if (parport_wait_peripheral(p, DSR_nBUSY, DSR_nBUSY))
printk(KERN_DEBUG PPIP32 "%s: BUSY timeout in %s\n",
p->name, __func__);
stop:
/* Reset FIFO */
parport_ip32_set_mode(p, ECR_MODE_PS2);
physport->ieee1284.phase = IEEE1284_PH_FWD_IDLE;
return written;
}
/*
* FIXME - Insert here parport_ip32_ecp_read_data().
*/
/**
* parport_ip32_ecp_write_data - write a block of data in ECP mode
* @p: pointer to &struct parport
* @buf: buffer of data to write
* @len: length of buffer @buf
* @flags: ignored
*/
static size_t parport_ip32_ecp_write_data(struct parport *p,
const void *buf, size_t len,
int flags)
{
static unsigned int ready_before = 1;
struct parport_ip32_private * const priv = p->physport->private_data;
struct parport * const physport = p->physport;
size_t written = 0;
/* Special case: a timeout of zero means we cannot call schedule().
* Also if O_NONBLOCK is set then use the default implementation. */
if (physport->cad->timeout <= PARPORT_INACTIVITY_O_NONBLOCK)
return parport_ieee1284_ecp_write_data(p, buf, len, flags);
/* Negotiate to forward mode if necessary. */
if (physport->ieee1284.phase != IEEE1284_PH_FWD_IDLE) {
/* Event 47: Set nInit high. */
parport_ip32_frob_control(p, DCR_nINIT | DCR_AUTOFD,
DCR_nINIT | DCR_AUTOFD);
/* Event 49: PError goes high. */
if (parport_wait_peripheral(p, DSR_PERROR, DSR_PERROR)) {
printk(KERN_DEBUG PPIP32 "%s: PError timeout in %s",
p->name, __func__);
physport->ieee1284.phase = IEEE1284_PH_ECP_DIR_UNKNOWN;
return 0;
}
}
/* Reset FIFO, go in forward mode, and disable ackIntEn */
parport_ip32_set_mode(p, ECR_MODE_PS2);
parport_ip32_write_control(p, DCR_SELECT | DCR_nINIT);
parport_ip32_data_forward(p);
parport_ip32_disable_irq(p);
parport_ip32_set_mode(p, ECR_MODE_ECP);
physport->ieee1284.phase = IEEE1284_PH_FWD_DATA;
/* Wait for peripheral to become ready */
if (parport_wait_peripheral(p, DSR_nBUSY | DSR_nFAULT,
DSR_nBUSY | DSR_nFAULT)) {
/* Avoid to flood the logs */
if (ready_before)
printk(KERN_INFO PPIP32 "%s: not ready in %s\n",
p->name, __func__);
ready_before = 0;
goto stop;
}
ready_before = 1;
written = parport_ip32_fifo_write_block(p, buf, len);
/* Wait FIFO to empty. Timeout is proportional to FIFO_depth. */
parport_ip32_drain_fifo(p, physport->cad->timeout * priv->fifo_depth);
/* Check for a potential residue */
written -= parport_ip32_get_fifo_residue(p, ECR_MODE_ECP);
/* Then, wait for BUSY to get low. */
if (parport_wait_peripheral(p, DSR_nBUSY, DSR_nBUSY))
printk(KERN_DEBUG PPIP32 "%s: BUSY timeout in %s\n",
p->name, __func__);
stop:
/* Reset FIFO */
parport_ip32_set_mode(p, ECR_MODE_PS2);
physport->ieee1284.phase = IEEE1284_PH_FWD_IDLE;
return written;
}
/*
* FIXME - Insert here parport_ip32_ecp_write_addr().
*/
/*--- Default parport operations ---------------------------------------*/
static __initdata struct parport_operations parport_ip32_ops = {
.write_data = parport_ip32_write_data,
.read_data = parport_ip32_read_data,
.write_control = parport_ip32_write_control,
.read_control = parport_ip32_read_control,
.frob_control = parport_ip32_frob_control,
.read_status = parport_ip32_read_status,
.enable_irq = parport_ip32_enable_irq,
.disable_irq = parport_ip32_disable_irq,
.data_forward = parport_ip32_data_forward,
.data_reverse = parport_ip32_data_reverse,
.init_state = parport_ip32_init_state,
.save_state = parport_ip32_save_state,
.restore_state = parport_ip32_restore_state,
.epp_write_data = parport_ieee1284_epp_write_data,
.epp_read_data = parport_ieee1284_epp_read_data,
.epp_write_addr = parport_ieee1284_epp_write_addr,
.epp_read_addr = parport_ieee1284_epp_read_addr,
.ecp_write_data = parport_ieee1284_ecp_write_data,
.ecp_read_data = parport_ieee1284_ecp_read_data,
.ecp_write_addr = parport_ieee1284_ecp_write_addr,
.compat_write_data = parport_ieee1284_write_compat,
.nibble_read_data = parport_ieee1284_read_nibble,
.byte_read_data = parport_ieee1284_read_byte,
.owner = THIS_MODULE,
};
/*--- Device detection -------------------------------------------------*/
/**
* parport_ip32_ecp_supported - check for an ECP port
* @p: pointer to the &parport structure
*
* Returns 1 if an ECP port is found, and 0 otherwise. This function actually
* checks if an Extended Control Register seems to be present. On successful
* return, the port is placed in SPP mode.
*/
static __init unsigned int parport_ip32_ecp_supported(struct parport *p)
{
struct parport_ip32_private * const priv = p->physport->private_data;
unsigned int ecr;
ecr = ECR_MODE_PS2 | ECR_nERRINTR | ECR_SERVINTR;
writeb(ecr, priv->regs.ecr);
if (readb(priv->regs.ecr) != (ecr | ECR_F_EMPTY))
goto fail;
pr_probe(p, "Found working ECR register\n");
parport_ip32_set_mode(p, ECR_MODE_SPP);
parport_ip32_write_control(p, DCR_SELECT | DCR_nINIT);
return 1;
fail:
pr_probe(p, "ECR register not found\n");
return 0;
}
/**
* parport_ip32_fifo_supported - check for FIFO parameters
* @p: pointer to the &parport structure
*
* Check for FIFO parameters of an Extended Capabilities Port. Returns 1 on
* success, and 0 otherwise. Adjust FIFO parameters in the parport structure.
* On return, the port is placed in SPP mode.
*/
static __init unsigned int parport_ip32_fifo_supported(struct parport *p)
{
struct parport_ip32_private * const priv = p->physport->private_data;
unsigned int configa, configb;
unsigned int pword;
unsigned int i;
/* Configuration mode */
parport_ip32_set_mode(p, ECR_MODE_CFG);
configa = readb(priv->regs.cnfgA);
configb = readb(priv->regs.cnfgB);
/* Find out PWord size */
switch (configa & CNFGA_ID_MASK) {
case CNFGA_ID_8:
pword = 1;
break;
case CNFGA_ID_16:
pword = 2;
break;
case CNFGA_ID_32:
pword = 4;
break;
default:
pr_probe(p, "Unknown implementation ID: 0x%0x\n",
(configa & CNFGA_ID_MASK) >> CNFGA_ID_SHIFT);
goto fail;
break;
}
if (pword != 1) {
pr_probe(p, "Unsupported PWord size: %u\n", pword);
goto fail;
}
priv->pword = pword;
pr_probe(p, "PWord is %u bits\n", 8 * priv->pword);
/* Check for compression support */
writeb(configb | CNFGB_COMPRESS, priv->regs.cnfgB);
if (readb(priv->regs.cnfgB) & CNFGB_COMPRESS)
pr_probe(p, "Hardware compression detected (unsupported)\n");
writeb(configb & ~CNFGB_COMPRESS, priv->regs.cnfgB);
/* Reset FIFO and go in test mode (no interrupt, no DMA) */
parport_ip32_set_mode(p, ECR_MODE_TST);
/* FIFO must be empty now */
if (!(readb(priv->regs.ecr) & ECR_F_EMPTY)) {
pr_probe(p, "FIFO not reset\n");
goto fail;
}
/* Find out FIFO depth. */
priv->fifo_depth = 0;
for (i = 0; i < 1024; i++) {
if (readb(priv->regs.ecr) & ECR_F_FULL) {
/* FIFO full */
priv->fifo_depth = i;
break;
}
writeb((u8)i, priv->regs.fifo);
}
if (i >= 1024) {
pr_probe(p, "Can't fill FIFO\n");
goto fail;
}
if (!priv->fifo_depth) {
pr_probe(p, "Can't get FIFO depth\n");
goto fail;
}
pr_probe(p, "FIFO is %u PWords deep\n", priv->fifo_depth);
/* Enable interrupts */
parport_ip32_frob_econtrol(p, ECR_SERVINTR, 0);
/* Find out writeIntrThreshold: number of PWords we know we can write
* if we get an interrupt. */
priv->writeIntrThreshold = 0;
for (i = 0; i < priv->fifo_depth; i++) {
if (readb(priv->regs.fifo) != (u8)i) {
pr_probe(p, "Invalid data in FIFO\n");
goto fail;
}
if (!priv->writeIntrThreshold
&& readb(priv->regs.ecr) & ECR_SERVINTR)
/* writeIntrThreshold reached */
priv->writeIntrThreshold = i + 1;
if (i + 1 < priv->fifo_depth
&& readb(priv->regs.ecr) & ECR_F_EMPTY) {
/* FIFO empty before the last byte? */
pr_probe(p, "Data lost in FIFO\n");
goto fail;
}
}
if (!priv->writeIntrThreshold) {
pr_probe(p, "Can't get writeIntrThreshold\n");
goto fail;
}
pr_probe(p, "writeIntrThreshold is %u\n", priv->writeIntrThreshold);
/* FIFO must be empty now */
if (!(readb(priv->regs.ecr) & ECR_F_EMPTY)) {
pr_probe(p, "Can't empty FIFO\n");
goto fail;
}
/* Reset FIFO */
parport_ip32_set_mode(p, ECR_MODE_PS2);
/* Set reverse direction (must be in PS2 mode) */
parport_ip32_data_reverse(p);
/* Test FIFO, no interrupt, no DMA */
parport_ip32_set_mode(p, ECR_MODE_TST);
/* Enable interrupts */
parport_ip32_frob_econtrol(p, ECR_SERVINTR, 0);
/* Find out readIntrThreshold: number of PWords we can read if we get
* an interrupt. */
priv->readIntrThreshold = 0;
for (i = 0; i < priv->fifo_depth; i++) {
writeb(0xaa, priv->regs.fifo);
if (readb(priv->regs.ecr) & ECR_SERVINTR) {
/* readIntrThreshold reached */
priv->readIntrThreshold = i + 1;
break;
}
}
if (!priv->readIntrThreshold) {
pr_probe(p, "Can't get readIntrThreshold\n");
goto fail;
}
pr_probe(p, "readIntrThreshold is %u\n", priv->readIntrThreshold);
/* Reset ECR */
parport_ip32_set_mode(p, ECR_MODE_PS2);
parport_ip32_data_forward(p);
parport_ip32_set_mode(p, ECR_MODE_SPP);
return 1;
fail:
priv->fifo_depth = 0;
parport_ip32_set_mode(p, ECR_MODE_SPP);
return 0;
}
/*--- Initialization code ----------------------------------------------*/
/**
* parport_ip32_make_isa_registers - compute (ISA) register addresses
* @regs: pointer to &struct parport_ip32_regs to fill
* @base: base address of standard and EPP registers
* @base_hi: base address of ECP registers
* @regshift: how much to shift register offset by
*
* Compute register addresses, according to the ISA standard. The addresses
* of the standard and EPP registers are computed from address @base. The
* addresses of the ECP registers are computed from address @base_hi.
*/
static void __init
parport_ip32_make_isa_registers(struct parport_ip32_regs *regs,
void __iomem *base, void __iomem *base_hi,
unsigned int regshift)
{
#define r_base(offset) ((u8 __iomem *)base + ((offset) << regshift))
#define r_base_hi(offset) ((u8 __iomem *)base_hi + ((offset) << regshift))
*regs = (struct parport_ip32_regs){
.data = r_base(0),
.dsr = r_base(1),
.dcr = r_base(2),
.eppAddr = r_base(3),
.eppData0 = r_base(4),
.eppData1 = r_base(5),
.eppData2 = r_base(6),
.eppData3 = r_base(7),
.ecpAFifo = r_base(0),
.fifo = r_base_hi(0),
.cnfgA = r_base_hi(0),
.cnfgB = r_base_hi(1),
.ecr = r_base_hi(2)
};
#undef r_base_hi
#undef r_base
}
/**
* parport_ip32_probe_port - probe and register IP32 built-in parallel port
*
* Returns the new allocated &parport structure. On error, an error code is
* encoded in return value with the ERR_PTR function.
*/
static __init struct parport *parport_ip32_probe_port(void)
{
struct parport_ip32_regs regs;
struct parport_ip32_private *priv = NULL;
struct parport_operations *ops = NULL;
struct parport *p = NULL;
int err;
parport_ip32_make_isa_registers(®s, &mace->isa.parallel,
&mace->isa.ecp1284, 8 /* regshift */);
ops = kmalloc(sizeof(struct parport_operations), GFP_KERNEL);
priv = kmalloc(sizeof(struct parport_ip32_private), GFP_KERNEL);
p = parport_register_port(0, PARPORT_IRQ_NONE, PARPORT_DMA_NONE, ops);
if (ops == NULL || priv == NULL || p == NULL) {
err = -ENOMEM;
goto fail;
}
p->base = MACE_BASE + offsetof(struct sgi_mace, isa.parallel);
p->base_hi = MACE_BASE + offsetof(struct sgi_mace, isa.ecp1284);
p->private_data = priv;
*ops = parport_ip32_ops;
*priv = (struct parport_ip32_private){
.regs = regs,
.dcr_writable = DCR_DIR | DCR_SELECT | DCR_nINIT |
DCR_AUTOFD | DCR_STROBE,
.irq_mode = PARPORT_IP32_IRQ_FWD,
};
init_completion(&priv->irq_complete);
/* Probe port. */
if (!parport_ip32_ecp_supported(p)) {
err = -ENODEV;
goto fail;
}
parport_ip32_dump_state(p, "begin init", 0);
/* We found what looks like a working ECR register. Simply assume
* that all modes are correctly supported. Enable basic modes. */
p->modes = PARPORT_MODE_PCSPP | PARPORT_MODE_SAFEININT;
p->modes |= PARPORT_MODE_TRISTATE;
if (!parport_ip32_fifo_supported(p)) {
printk(KERN_WARNING PPIP32
"%s: error: FIFO disabled\n", p->name);
/* Disable hardware modes depending on a working FIFO. */
features &= ~PARPORT_IP32_ENABLE_SPP;
features &= ~PARPORT_IP32_ENABLE_ECP;
/* DMA is not needed if FIFO is not supported. */
features &= ~PARPORT_IP32_ENABLE_DMA;
}
/* Request IRQ */
if (features & PARPORT_IP32_ENABLE_IRQ) {
int irq = MACEISA_PARALLEL_IRQ;
if (request_irq(irq, parport_ip32_interrupt, 0, p->name, p)) {
printk(KERN_WARNING PPIP32
"%s: error: IRQ disabled\n", p->name);
/* DMA cannot work without interrupts. */
features &= ~PARPORT_IP32_ENABLE_DMA;
} else {
pr_probe(p, "Interrupt support enabled\n");
p->irq = irq;
priv->dcr_writable |= DCR_IRQ;
}
}
/* Allocate DMA resources */
if (features & PARPORT_IP32_ENABLE_DMA) {
if (parport_ip32_dma_register())
printk(KERN_WARNING PPIP32
"%s: error: DMA disabled\n", p->name);
else {
pr_probe(p, "DMA support enabled\n");
p->dma = 0; /* arbitrary value != PARPORT_DMA_NONE */
p->modes |= PARPORT_MODE_DMA;
}
}
if (features & PARPORT_IP32_ENABLE_SPP) {
/* Enable compatibility FIFO mode */
p->ops->compat_write_data = parport_ip32_compat_write_data;
p->modes |= PARPORT_MODE_COMPAT;
pr_probe(p, "Hardware support for SPP mode enabled\n");
}
if (features & PARPORT_IP32_ENABLE_EPP) {
/* Set up access functions to use EPP hardware. */
p->ops->epp_read_data = parport_ip32_epp_read_data;
p->ops->epp_write_data = parport_ip32_epp_write_data;
p->ops->epp_read_addr = parport_ip32_epp_read_addr;
p->ops->epp_write_addr = parport_ip32_epp_write_addr;
p->modes |= PARPORT_MODE_EPP;
pr_probe(p, "Hardware support for EPP mode enabled\n");
}
if (features & PARPORT_IP32_ENABLE_ECP) {
/* Enable ECP FIFO mode */
p->ops->ecp_write_data = parport_ip32_ecp_write_data;
/* FIXME - not implemented */
/* p->ops->ecp_read_data = parport_ip32_ecp_read_data; */
/* p->ops->ecp_write_addr = parport_ip32_ecp_write_addr; */
p->modes |= PARPORT_MODE_ECP;
pr_probe(p, "Hardware support for ECP mode enabled\n");
}
/* Initialize the port with sensible values */
parport_ip32_set_mode(p, ECR_MODE_PS2);
parport_ip32_write_control(p, DCR_SELECT | DCR_nINIT);
parport_ip32_data_forward(p);
parport_ip32_disable_irq(p);
parport_ip32_write_data(p, 0x00);
parport_ip32_dump_state(p, "end init", 0);
/* Print out what we found */
printk(KERN_INFO "%s: SGI IP32 at 0x%lx (0x%lx)",
p->name, p->base, p->base_hi);
if (p->irq != PARPORT_IRQ_NONE)
printk(", irq %d", p->irq);
printk(" [");
#define printmode(x) if (p->modes & PARPORT_MODE_##x) \
printk("%s%s", f++ ? "," : "", #x)
{
unsigned int f = 0;
printmode(PCSPP);
printmode(TRISTATE);
printmode(COMPAT);
printmode(EPP);
printmode(ECP);
printmode(DMA);
}
#undef printmode
printk("]\n");
parport_announce_port(p);
return p;
fail:
if (p)
parport_put_port(p);
kfree(priv);
kfree(ops);
return ERR_PTR(err);
}
/**
* parport_ip32_unregister_port - unregister a parallel port
* @p: pointer to the &struct parport
*
* Unregisters a parallel port and free previously allocated resources
* (memory, IRQ, ...).
*/
static __exit void parport_ip32_unregister_port(struct parport *p)
{
struct parport_ip32_private * const priv = p->physport->private_data;
struct parport_operations *ops = p->ops;
parport_remove_port(p);
if (p->modes & PARPORT_MODE_DMA)
parport_ip32_dma_unregister();
if (p->irq != PARPORT_IRQ_NONE)
free_irq(p->irq, p);
parport_put_port(p);
kfree(priv);
kfree(ops);
}
/**
* parport_ip32_init - module initialization function
*/
static int __init parport_ip32_init(void)
{
pr_info(PPIP32 "SGI IP32 built-in parallel port driver v0.6\n");
this_port = parport_ip32_probe_port();
return IS_ERR(this_port) ? PTR_ERR(this_port) : 0;
}
/**
* parport_ip32_exit - module termination function
*/
static void __exit parport_ip32_exit(void)
{
parport_ip32_unregister_port(this_port);
}
/*--- Module stuff -----------------------------------------------------*/
MODULE_AUTHOR("Arnaud Giersch <arnaud.giersch@free.fr>");
MODULE_DESCRIPTION("SGI IP32 built-in parallel port driver");
MODULE_LICENSE("GPL");
MODULE_VERSION("0.6"); /* update in parport_ip32_init() too */
module_init(parport_ip32_init);
module_exit(parport_ip32_exit);
module_param(verbose_probing, bool, S_IRUGO);
MODULE_PARM_DESC(verbose_probing, "Log chit-chat during initialization");
module_param(features, uint, S_IRUGO);
MODULE_PARM_DESC(features,
"Bit mask of features to enable"
", bit 0: IRQ support"
", bit 1: DMA support"
", bit 2: hardware SPP mode"
", bit 3: hardware EPP mode"
", bit 4: hardware ECP mode");
/*--- Inform (X)Emacs about preferred coding style ---------------------*/
/*
* Local Variables:
* mode: c
* c-file-style: "linux"
* indent-tabs-mode: t
* tab-width: 8
* fill-column: 78
* ispell-local-dictionary: "american"
* End:
*/
| gpl-2.0 |
byzvulture/Z5S_NX503A_KitKat_kernel | arch/arm/mach-omap2/clkt2xxx_osc.c | 7993 | 1989 | /*
* OMAP2xxx osc_clk-specific clock code
*
* Copyright (C) 2005-2008 Texas Instruments, Inc.
* Copyright (C) 2004-2010 Nokia Corporation
*
* Contacts:
* Richard Woodruff <r-woodruff2@ti.com>
* Paul Walmsley
*
* Based on earlier work by Tuukka Tikkanen, Tony Lindgren,
* Gordon McNutt and RidgeRun, 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.
*/
#undef DEBUG
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <plat/clock.h>
#include "clock.h"
#include "clock2xxx.h"
#include "prm2xxx_3xxx.h"
#include "prm-regbits-24xx.h"
/*
* XXX This does not actually enable the osc_ck, since the osc_ck must
* be running for this function to be called. Instead, this function
* is used to disable an autoidle mode on the osc_ck. The existing
* clk_enable/clk_disable()-based usecounting for osc_ck should be
* replaced with autoidle-based usecounting.
*/
static int omap2_enable_osc_ck(struct clk *clk)
{
u32 pcc;
pcc = __raw_readl(prcm_clksrc_ctrl);
__raw_writel(pcc & ~OMAP_AUTOEXTCLKMODE_MASK, prcm_clksrc_ctrl);
return 0;
}
/*
* XXX This does not actually disable the osc_ck, since doing so would
* immediately halt the system. Instead, this function is used to
* enable an autoidle mode on the osc_ck. The existing
* clk_enable/clk_disable()-based usecounting for osc_ck should be
* replaced with autoidle-based usecounting.
*/
static void omap2_disable_osc_ck(struct clk *clk)
{
u32 pcc;
pcc = __raw_readl(prcm_clksrc_ctrl);
__raw_writel(pcc | OMAP_AUTOEXTCLKMODE_MASK, prcm_clksrc_ctrl);
}
const struct clkops clkops_oscck = {
.enable = omap2_enable_osc_ck,
.disable = omap2_disable_osc_ck,
};
unsigned long omap2_osc_clk_recalc(struct clk *clk)
{
return omap2xxx_get_apll_clkin() * omap2xxx_get_sysclkdiv();
}
| gpl-2.0 |
upndwn4par/graviton_n5_kernel | drivers/ide/hpt366.c | 8249 | 43126 | /*
* Copyright (C) 1999-2003 Andre Hedrick <andre@linux-ide.org>
* Portions Copyright (C) 2001 Sun Microsystems, Inc.
* Portions Copyright (C) 2003 Red Hat Inc
* Portions Copyright (C) 2007 Bartlomiej Zolnierkiewicz
* Portions Copyright (C) 2005-2009 MontaVista Software, Inc.
*
* Thanks to HighPoint Technologies for their assistance, and hardware.
* Special Thanks to Jon Burchmore in SanDiego for the deep pockets, his
* donation of an ABit BP6 mainboard, processor, and memory acellerated
* development and support.
*
*
* HighPoint has its own drivers (open source except for the RAID part)
* available from http://www.highpoint-tech.com/USA_new/service_support.htm
* This may be useful to anyone wanting to work on this driver, however do not
* trust them too much since the code tends to become less and less meaningful
* as the time passes... :-/
*
* Note that final HPT370 support was done by force extraction of GPL.
*
* - add function for getting/setting power status of drive
* - the HPT370's state machine can get confused. reset it before each dma
* xfer to prevent that from happening.
* - reset state engine whenever we get an error.
* - check for busmaster state at end of dma.
* - use new highpoint timings.
* - detect bus speed using highpoint register.
* - use pll if we don't have a clock table. added a 66MHz table that's
* just 2x the 33MHz table.
* - removed turnaround. NOTE: we never want to switch between pll and
* pci clocks as the chip can glitch in those cases. the highpoint
* approved workaround slows everything down too much to be useful. in
* addition, we would have to serialize access to each chip.
* Adrian Sun <a.sun@sun.com>
*
* add drive timings for 66MHz PCI bus,
* fix ATA Cable signal detection, fix incorrect /proc info
* add /proc display for per-drive PIO/DMA/UDMA mode and
* per-channel ATA-33/66 Cable detect.
* Duncan Laurie <void@sun.com>
*
* fixup /proc output for multiple controllers
* Tim Hockin <thockin@sun.com>
*
* On hpt366:
* Reset the hpt366 on error, reset on dma
* Fix disabling Fast Interrupt hpt366.
* Mike Waychison <crlf@sun.com>
*
* Added support for 372N clocking and clock switching. The 372N needs
* different clocks on read/write. This requires overloading rw_disk and
* other deeply crazy things. Thanks to <http://www.hoerstreich.de> for
* keeping me sane.
* Alan Cox <alan@lxorguk.ukuu.org.uk>
*
* - fix the clock turnaround code: it was writing to the wrong ports when
* called for the secondary channel, caching the current clock mode per-
* channel caused the cached register value to get out of sync with the
* actual one, the channels weren't serialized, the turnaround shouldn't
* be done on 66 MHz PCI bus
* - disable UltraATA/100 for HPT370 by default as the 33 MHz clock being used
* does not allow for this speed anyway
* - avoid touching disabled channels (e.g. HPT371/N are single channel chips,
* their primary channel is kind of virtual, it isn't tied to any pins)
* - fix/remove bad/unused timing tables and use one set of tables for the whole
* HPT37x chip family; save space by introducing the separate transfer mode
* table in which the mode lookup is done
* - use f_CNT value saved by the HighPoint BIOS as reading it directly gives
* the wrong PCI frequency since DPLL has already been calibrated by BIOS;
* read it only from the function 0 of HPT374 chips
* - fix the hotswap code: it caused RESET- to glitch when tristating the bus,
* and for HPT36x the obsolete HDIO_TRISTATE_HWIF handler was called instead
* - pass to init_chipset() handlers a copy of the IDE PCI device structure as
* they tamper with its fields
* - pass to the init_setup handlers a copy of the ide_pci_device_t structure
* since they may tamper with its fields
* - prefix the driver startup messages with the real chip name
* - claim the extra 240 bytes of I/O space for all chips
* - optimize the UltraDMA filtering and the drive list lookup code
* - use pci_get_slot() to get to the function 1 of HPT36x/374
* - cache offset of the channel's misc. control registers (MCRs) being used
* throughout the driver
* - only touch the relevant MCR when detecting the cable type on HPT374's
* function 1
* - rename all the register related variables consistently
* - move all the interrupt twiddling code from the speedproc handlers into
* init_hwif_hpt366(), also grouping all the DMA related code together there
* - merge HPT36x/HPT37x speedproc handlers, fix PIO timing register mask and
* separate the UltraDMA and MWDMA masks there to avoid changing PIO timings
* when setting an UltraDMA mode
* - fix hpt3xx_tune_drive() to set the PIO mode requested, not always select
* the best possible one
* - clean up DMA timeout handling for HPT370
* - switch to using the enumeration type to differ between the numerous chip
* variants, matching PCI device/revision ID with the chip type early, at the
* init_setup stage
* - extend the hpt_info structure to hold the DPLL and PCI clock frequencies,
* stop duplicating it for each channel by storing the pointer in the pci_dev
* structure: first, at the init_setup stage, point it to a static "template"
* with only the chip type and its specific base DPLL frequency, the highest
* UltraDMA mode, and the chip settings table pointer filled, then, at the
* init_chipset stage, allocate per-chip instance and fill it with the rest
* of the necessary information
* - get rid of the constant thresholds in the HPT37x PCI clock detection code,
* switch to calculating PCI clock frequency based on the chip's base DPLL
* frequency
* - switch to using the DPLL clock and enable UltraATA/133 mode by default on
* anything newer than HPT370/A (except HPT374 that is not capable of this
* mode according to the manual)
* - fold PCI clock detection and DPLL setup code into init_chipset_hpt366(),
* also fixing the interchanged 25/40 MHz PCI clock cases for HPT36x chips;
* unify HPT36x/37x timing setup code and the speedproc handlers by joining
* the register setting lists into the table indexed by the clock selected
* - set the correct hwif->ultra_mask for each individual chip
* - add Ultra and MW DMA mode filtering for the HPT37[24] based SATA cards
* - stop resetting HPT370's state machine before each DMA transfer as that has
* caused more harm than good
* Sergei Shtylyov, <sshtylyov@ru.mvista.com> or <source@mvista.com>
*/
#include <linux/types.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/blkdev.h>
#include <linux/interrupt.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/ide.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include <asm/io.h>
#define DRV_NAME "hpt366"
/* various tuning parameters */
#undef HPT_RESET_STATE_ENGINE
#undef HPT_DELAY_INTERRUPT
static const char *bad_ata100_5[] = {
"IBM-DTLA-307075",
"IBM-DTLA-307060",
"IBM-DTLA-307045",
"IBM-DTLA-307030",
"IBM-DTLA-307020",
"IBM-DTLA-307015",
"IBM-DTLA-305040",
"IBM-DTLA-305030",
"IBM-DTLA-305020",
"IC35L010AVER07-0",
"IC35L020AVER07-0",
"IC35L030AVER07-0",
"IC35L040AVER07-0",
"IC35L060AVER07-0",
"WDC AC310200R",
NULL
};
static const char *bad_ata66_4[] = {
"IBM-DTLA-307075",
"IBM-DTLA-307060",
"IBM-DTLA-307045",
"IBM-DTLA-307030",
"IBM-DTLA-307020",
"IBM-DTLA-307015",
"IBM-DTLA-305040",
"IBM-DTLA-305030",
"IBM-DTLA-305020",
"IC35L010AVER07-0",
"IC35L020AVER07-0",
"IC35L030AVER07-0",
"IC35L040AVER07-0",
"IC35L060AVER07-0",
"WDC AC310200R",
"MAXTOR STM3320620A",
NULL
};
static const char *bad_ata66_3[] = {
"WDC AC310200R",
NULL
};
static const char *bad_ata33[] = {
"Maxtor 92720U8", "Maxtor 92040U6", "Maxtor 91360U4", "Maxtor 91020U3", "Maxtor 90845U3", "Maxtor 90650U2",
"Maxtor 91360D8", "Maxtor 91190D7", "Maxtor 91020D6", "Maxtor 90845D5", "Maxtor 90680D4", "Maxtor 90510D3", "Maxtor 90340D2",
"Maxtor 91152D8", "Maxtor 91008D7", "Maxtor 90845D6", "Maxtor 90840D6", "Maxtor 90720D5", "Maxtor 90648D5", "Maxtor 90576D4",
"Maxtor 90510D4",
"Maxtor 90432D3", "Maxtor 90288D2", "Maxtor 90256D2",
"Maxtor 91000D8", "Maxtor 90910D8", "Maxtor 90875D7", "Maxtor 90840D7", "Maxtor 90750D6", "Maxtor 90625D5", "Maxtor 90500D4",
"Maxtor 91728D8", "Maxtor 91512D7", "Maxtor 91303D6", "Maxtor 91080D5", "Maxtor 90845D4", "Maxtor 90680D4", "Maxtor 90648D3", "Maxtor 90432D2",
NULL
};
static u8 xfer_speeds[] = {
XFER_UDMA_6,
XFER_UDMA_5,
XFER_UDMA_4,
XFER_UDMA_3,
XFER_UDMA_2,
XFER_UDMA_1,
XFER_UDMA_0,
XFER_MW_DMA_2,
XFER_MW_DMA_1,
XFER_MW_DMA_0,
XFER_PIO_4,
XFER_PIO_3,
XFER_PIO_2,
XFER_PIO_1,
XFER_PIO_0
};
/* Key for bus clock timings
* 36x 37x
* bits bits
* 0:3 0:3 data_high_time. Inactive time of DIOW_/DIOR_ for PIO and MW DMA.
* cycles = value + 1
* 4:7 4:8 data_low_time. Active time of DIOW_/DIOR_ for PIO and MW DMA.
* cycles = value + 1
* 8:11 9:12 cmd_high_time. Inactive time of DIOW_/DIOR_ during task file
* register access.
* 12:15 13:17 cmd_low_time. Active time of DIOW_/DIOR_ during task file
* register access.
* 16:18 18:20 udma_cycle_time. Clock cycles for UDMA xfer.
* - 21 CLK frequency: 0=ATA clock, 1=dual ATA clock.
* 19:21 22:24 pre_high_time. Time to initialize the 1st cycle for PIO and
* MW DMA xfer.
* 22:24 25:27 cmd_pre_high_time. Time to initialize the 1st PIO cycle for
* task file register access.
* 28 28 UDMA enable.
* 29 29 DMA enable.
* 30 30 PIO MST enable. If set, the chip is in bus master mode during
* PIO xfer.
* 31 31 FIFO enable.
*/
static u32 forty_base_hpt36x[] = {
/* XFER_UDMA_6 */ 0x900fd943,
/* XFER_UDMA_5 */ 0x900fd943,
/* XFER_UDMA_4 */ 0x900fd943,
/* XFER_UDMA_3 */ 0x900ad943,
/* XFER_UDMA_2 */ 0x900bd943,
/* XFER_UDMA_1 */ 0x9008d943,
/* XFER_UDMA_0 */ 0x9008d943,
/* XFER_MW_DMA_2 */ 0xa008d943,
/* XFER_MW_DMA_1 */ 0xa010d955,
/* XFER_MW_DMA_0 */ 0xa010d9fc,
/* XFER_PIO_4 */ 0xc008d963,
/* XFER_PIO_3 */ 0xc010d974,
/* XFER_PIO_2 */ 0xc010d997,
/* XFER_PIO_1 */ 0xc010d9c7,
/* XFER_PIO_0 */ 0xc018d9d9
};
static u32 thirty_three_base_hpt36x[] = {
/* XFER_UDMA_6 */ 0x90c9a731,
/* XFER_UDMA_5 */ 0x90c9a731,
/* XFER_UDMA_4 */ 0x90c9a731,
/* XFER_UDMA_3 */ 0x90cfa731,
/* XFER_UDMA_2 */ 0x90caa731,
/* XFER_UDMA_1 */ 0x90cba731,
/* XFER_UDMA_0 */ 0x90c8a731,
/* XFER_MW_DMA_2 */ 0xa0c8a731,
/* XFER_MW_DMA_1 */ 0xa0c8a732, /* 0xa0c8a733 */
/* XFER_MW_DMA_0 */ 0xa0c8a797,
/* XFER_PIO_4 */ 0xc0c8a731,
/* XFER_PIO_3 */ 0xc0c8a742,
/* XFER_PIO_2 */ 0xc0d0a753,
/* XFER_PIO_1 */ 0xc0d0a7a3, /* 0xc0d0a793 */
/* XFER_PIO_0 */ 0xc0d0a7aa /* 0xc0d0a7a7 */
};
static u32 twenty_five_base_hpt36x[] = {
/* XFER_UDMA_6 */ 0x90c98521,
/* XFER_UDMA_5 */ 0x90c98521,
/* XFER_UDMA_4 */ 0x90c98521,
/* XFER_UDMA_3 */ 0x90cf8521,
/* XFER_UDMA_2 */ 0x90cf8521,
/* XFER_UDMA_1 */ 0x90cb8521,
/* XFER_UDMA_0 */ 0x90cb8521,
/* XFER_MW_DMA_2 */ 0xa0ca8521,
/* XFER_MW_DMA_1 */ 0xa0ca8532,
/* XFER_MW_DMA_0 */ 0xa0ca8575,
/* XFER_PIO_4 */ 0xc0ca8521,
/* XFER_PIO_3 */ 0xc0ca8532,
/* XFER_PIO_2 */ 0xc0ca8542,
/* XFER_PIO_1 */ 0xc0d08572,
/* XFER_PIO_0 */ 0xc0d08585
};
/*
* The following are the new timing tables with PIO mode data/taskfile transfer
* overclocking fixed...
*/
/* This table is taken from the HPT370 data manual rev. 1.02 */
static u32 thirty_three_base_hpt37x[] = {
/* XFER_UDMA_6 */ 0x16455031, /* 0x16655031 ?? */
/* XFER_UDMA_5 */ 0x16455031,
/* XFER_UDMA_4 */ 0x16455031,
/* XFER_UDMA_3 */ 0x166d5031,
/* XFER_UDMA_2 */ 0x16495031,
/* XFER_UDMA_1 */ 0x164d5033,
/* XFER_UDMA_0 */ 0x16515097,
/* XFER_MW_DMA_2 */ 0x26515031,
/* XFER_MW_DMA_1 */ 0x26515033,
/* XFER_MW_DMA_0 */ 0x26515097,
/* XFER_PIO_4 */ 0x06515021,
/* XFER_PIO_3 */ 0x06515022,
/* XFER_PIO_2 */ 0x06515033,
/* XFER_PIO_1 */ 0x06915065,
/* XFER_PIO_0 */ 0x06d1508a
};
static u32 fifty_base_hpt37x[] = {
/* XFER_UDMA_6 */ 0x1a861842,
/* XFER_UDMA_5 */ 0x1a861842,
/* XFER_UDMA_4 */ 0x1aae1842,
/* XFER_UDMA_3 */ 0x1a8e1842,
/* XFER_UDMA_2 */ 0x1a0e1842,
/* XFER_UDMA_1 */ 0x1a161854,
/* XFER_UDMA_0 */ 0x1a1a18ea,
/* XFER_MW_DMA_2 */ 0x2a821842,
/* XFER_MW_DMA_1 */ 0x2a821854,
/* XFER_MW_DMA_0 */ 0x2a8218ea,
/* XFER_PIO_4 */ 0x0a821842,
/* XFER_PIO_3 */ 0x0a821843,
/* XFER_PIO_2 */ 0x0a821855,
/* XFER_PIO_1 */ 0x0ac218a8,
/* XFER_PIO_0 */ 0x0b02190c
};
static u32 sixty_six_base_hpt37x[] = {
/* XFER_UDMA_6 */ 0x1c86fe62,
/* XFER_UDMA_5 */ 0x1caefe62, /* 0x1c8afe62 */
/* XFER_UDMA_4 */ 0x1c8afe62,
/* XFER_UDMA_3 */ 0x1c8efe62,
/* XFER_UDMA_2 */ 0x1c92fe62,
/* XFER_UDMA_1 */ 0x1c9afe62,
/* XFER_UDMA_0 */ 0x1c82fe62,
/* XFER_MW_DMA_2 */ 0x2c82fe62,
/* XFER_MW_DMA_1 */ 0x2c82fe66,
/* XFER_MW_DMA_0 */ 0x2c82ff2e,
/* XFER_PIO_4 */ 0x0c82fe62,
/* XFER_PIO_3 */ 0x0c82fe84,
/* XFER_PIO_2 */ 0x0c82fea6,
/* XFER_PIO_1 */ 0x0d02ff26,
/* XFER_PIO_0 */ 0x0d42ff7f
};
#define HPT371_ALLOW_ATA133_6 1
#define HPT302_ALLOW_ATA133_6 1
#define HPT372_ALLOW_ATA133_6 1
#define HPT370_ALLOW_ATA100_5 0
#define HPT366_ALLOW_ATA66_4 1
#define HPT366_ALLOW_ATA66_3 1
/* Supported ATA clock frequencies */
enum ata_clock {
ATA_CLOCK_25MHZ,
ATA_CLOCK_33MHZ,
ATA_CLOCK_40MHZ,
ATA_CLOCK_50MHZ,
ATA_CLOCK_66MHZ,
NUM_ATA_CLOCKS
};
struct hpt_timings {
u32 pio_mask;
u32 dma_mask;
u32 ultra_mask;
u32 *clock_table[NUM_ATA_CLOCKS];
};
/*
* Hold all the HighPoint chip information in one place.
*/
struct hpt_info {
char *chip_name; /* Chip name */
u8 chip_type; /* Chip type */
u8 udma_mask; /* Allowed UltraDMA modes mask. */
u8 dpll_clk; /* DPLL clock in MHz */
u8 pci_clk; /* PCI clock in MHz */
struct hpt_timings *timings; /* Chipset timing data */
u8 clock; /* ATA clock selected */
};
/* Supported HighPoint chips */
enum {
HPT36x,
HPT370,
HPT370A,
HPT374,
HPT372,
HPT372A,
HPT302,
HPT371,
HPT372N,
HPT302N,
HPT371N
};
static struct hpt_timings hpt36x_timings = {
.pio_mask = 0xc1f8ffff,
.dma_mask = 0x303800ff,
.ultra_mask = 0x30070000,
.clock_table = {
[ATA_CLOCK_25MHZ] = twenty_five_base_hpt36x,
[ATA_CLOCK_33MHZ] = thirty_three_base_hpt36x,
[ATA_CLOCK_40MHZ] = forty_base_hpt36x,
[ATA_CLOCK_50MHZ] = NULL,
[ATA_CLOCK_66MHZ] = NULL
}
};
static struct hpt_timings hpt37x_timings = {
.pio_mask = 0xcfc3ffff,
.dma_mask = 0x31c001ff,
.ultra_mask = 0x303c0000,
.clock_table = {
[ATA_CLOCK_25MHZ] = NULL,
[ATA_CLOCK_33MHZ] = thirty_three_base_hpt37x,
[ATA_CLOCK_40MHZ] = NULL,
[ATA_CLOCK_50MHZ] = fifty_base_hpt37x,
[ATA_CLOCK_66MHZ] = sixty_six_base_hpt37x
}
};
static const struct hpt_info hpt36x __devinitdata = {
.chip_name = "HPT36x",
.chip_type = HPT36x,
.udma_mask = HPT366_ALLOW_ATA66_3 ? (HPT366_ALLOW_ATA66_4 ? ATA_UDMA4 : ATA_UDMA3) : ATA_UDMA2,
.dpll_clk = 0, /* no DPLL */
.timings = &hpt36x_timings
};
static const struct hpt_info hpt370 __devinitdata = {
.chip_name = "HPT370",
.chip_type = HPT370,
.udma_mask = HPT370_ALLOW_ATA100_5 ? ATA_UDMA5 : ATA_UDMA4,
.dpll_clk = 48,
.timings = &hpt37x_timings
};
static const struct hpt_info hpt370a __devinitdata = {
.chip_name = "HPT370A",
.chip_type = HPT370A,
.udma_mask = HPT370_ALLOW_ATA100_5 ? ATA_UDMA5 : ATA_UDMA4,
.dpll_clk = 48,
.timings = &hpt37x_timings
};
static const struct hpt_info hpt374 __devinitdata = {
.chip_name = "HPT374",
.chip_type = HPT374,
.udma_mask = ATA_UDMA5,
.dpll_clk = 48,
.timings = &hpt37x_timings
};
static const struct hpt_info hpt372 __devinitdata = {
.chip_name = "HPT372",
.chip_type = HPT372,
.udma_mask = HPT372_ALLOW_ATA133_6 ? ATA_UDMA6 : ATA_UDMA5,
.dpll_clk = 55,
.timings = &hpt37x_timings
};
static const struct hpt_info hpt372a __devinitdata = {
.chip_name = "HPT372A",
.chip_type = HPT372A,
.udma_mask = HPT372_ALLOW_ATA133_6 ? ATA_UDMA6 : ATA_UDMA5,
.dpll_clk = 66,
.timings = &hpt37x_timings
};
static const struct hpt_info hpt302 __devinitdata = {
.chip_name = "HPT302",
.chip_type = HPT302,
.udma_mask = HPT302_ALLOW_ATA133_6 ? ATA_UDMA6 : ATA_UDMA5,
.dpll_clk = 66,
.timings = &hpt37x_timings
};
static const struct hpt_info hpt371 __devinitdata = {
.chip_name = "HPT371",
.chip_type = HPT371,
.udma_mask = HPT371_ALLOW_ATA133_6 ? ATA_UDMA6 : ATA_UDMA5,
.dpll_clk = 66,
.timings = &hpt37x_timings
};
static const struct hpt_info hpt372n __devinitdata = {
.chip_name = "HPT372N",
.chip_type = HPT372N,
.udma_mask = HPT372_ALLOW_ATA133_6 ? ATA_UDMA6 : ATA_UDMA5,
.dpll_clk = 77,
.timings = &hpt37x_timings
};
static const struct hpt_info hpt302n __devinitdata = {
.chip_name = "HPT302N",
.chip_type = HPT302N,
.udma_mask = HPT302_ALLOW_ATA133_6 ? ATA_UDMA6 : ATA_UDMA5,
.dpll_clk = 77,
.timings = &hpt37x_timings
};
static const struct hpt_info hpt371n __devinitdata = {
.chip_name = "HPT371N",
.chip_type = HPT371N,
.udma_mask = HPT371_ALLOW_ATA133_6 ? ATA_UDMA6 : ATA_UDMA5,
.dpll_clk = 77,
.timings = &hpt37x_timings
};
static int check_in_drive_list(ide_drive_t *drive, const char **list)
{
char *m = (char *)&drive->id[ATA_ID_PROD];
while (*list)
if (!strcmp(*list++, m))
return 1;
return 0;
}
static struct hpt_info *hpt3xx_get_info(struct device *dev)
{
struct ide_host *host = dev_get_drvdata(dev);
struct hpt_info *info = (struct hpt_info *)host->host_priv;
return dev == host->dev[1] ? info + 1 : info;
}
/*
* The Marvell bridge chips used on the HighPoint SATA cards do not seem
* to support the UltraDMA modes 1, 2, and 3 as well as any MWDMA modes...
*/
static u8 hpt3xx_udma_filter(ide_drive_t *drive)
{
ide_hwif_t *hwif = drive->hwif;
struct hpt_info *info = hpt3xx_get_info(hwif->dev);
u8 mask = hwif->ultra_mask;
switch (info->chip_type) {
case HPT36x:
if (!HPT366_ALLOW_ATA66_4 ||
check_in_drive_list(drive, bad_ata66_4))
mask = ATA_UDMA3;
if (!HPT366_ALLOW_ATA66_3 ||
check_in_drive_list(drive, bad_ata66_3))
mask = ATA_UDMA2;
break;
case HPT370:
if (!HPT370_ALLOW_ATA100_5 ||
check_in_drive_list(drive, bad_ata100_5))
mask = ATA_UDMA4;
break;
case HPT370A:
if (!HPT370_ALLOW_ATA100_5 ||
check_in_drive_list(drive, bad_ata100_5))
return ATA_UDMA4;
case HPT372 :
case HPT372A:
case HPT372N:
case HPT374 :
if (ata_id_is_sata(drive->id))
mask &= ~0x0e;
/* Fall thru */
default:
return mask;
}
return check_in_drive_list(drive, bad_ata33) ? 0x00 : mask;
}
static u8 hpt3xx_mdma_filter(ide_drive_t *drive)
{
ide_hwif_t *hwif = drive->hwif;
struct hpt_info *info = hpt3xx_get_info(hwif->dev);
switch (info->chip_type) {
case HPT372 :
case HPT372A:
case HPT372N:
case HPT374 :
if (ata_id_is_sata(drive->id))
return 0x00;
/* Fall thru */
default:
return 0x07;
}
}
static u32 get_speed_setting(u8 speed, struct hpt_info *info)
{
int i;
/*
* Lookup the transfer mode table to get the index into
* the timing table.
*
* NOTE: For XFER_PIO_SLOW, PIO mode 0 timings will be used.
*/
for (i = 0; i < ARRAY_SIZE(xfer_speeds) - 1; i++)
if (xfer_speeds[i] == speed)
break;
return info->timings->clock_table[info->clock][i];
}
static void hpt3xx_set_mode(ide_hwif_t *hwif, ide_drive_t *drive)
{
struct pci_dev *dev = to_pci_dev(hwif->dev);
struct hpt_info *info = hpt3xx_get_info(hwif->dev);
struct hpt_timings *t = info->timings;
u8 itr_addr = 0x40 + (drive->dn * 4);
u32 old_itr = 0;
const u8 speed = drive->dma_mode;
u32 new_itr = get_speed_setting(speed, info);
u32 itr_mask = speed < XFER_MW_DMA_0 ? t->pio_mask :
(speed < XFER_UDMA_0 ? t->dma_mask :
t->ultra_mask);
pci_read_config_dword(dev, itr_addr, &old_itr);
new_itr = (old_itr & ~itr_mask) | (new_itr & itr_mask);
/*
* Disable on-chip PIO FIFO/buffer (and PIO MST mode as well)
* to avoid problems handling I/O errors later
*/
new_itr &= ~0xc0000000;
pci_write_config_dword(dev, itr_addr, new_itr);
}
static void hpt3xx_set_pio_mode(ide_hwif_t *hwif, ide_drive_t *drive)
{
drive->dma_mode = drive->pio_mode;
hpt3xx_set_mode(hwif, drive);
}
static void hpt3xx_maskproc(ide_drive_t *drive, int mask)
{
ide_hwif_t *hwif = drive->hwif;
struct pci_dev *dev = to_pci_dev(hwif->dev);
struct hpt_info *info = hpt3xx_get_info(hwif->dev);
if ((drive->dev_flags & IDE_DFLAG_NIEN_QUIRK) == 0)
return;
if (info->chip_type >= HPT370) {
u8 scr1 = 0;
pci_read_config_byte(dev, 0x5a, &scr1);
if (((scr1 & 0x10) >> 4) != mask) {
if (mask)
scr1 |= 0x10;
else
scr1 &= ~0x10;
pci_write_config_byte(dev, 0x5a, scr1);
}
} else if (mask)
disable_irq(hwif->irq);
else
enable_irq(hwif->irq);
}
/*
* This is specific to the HPT366 UDMA chipset
* by HighPoint|Triones Technologies, Inc.
*/
static void hpt366_dma_lost_irq(ide_drive_t *drive)
{
struct pci_dev *dev = to_pci_dev(drive->hwif->dev);
u8 mcr1 = 0, mcr3 = 0, scr1 = 0;
pci_read_config_byte(dev, 0x50, &mcr1);
pci_read_config_byte(dev, 0x52, &mcr3);
pci_read_config_byte(dev, 0x5a, &scr1);
printk("%s: (%s) mcr1=0x%02x, mcr3=0x%02x, scr1=0x%02x\n",
drive->name, __func__, mcr1, mcr3, scr1);
if (scr1 & 0x10)
pci_write_config_byte(dev, 0x5a, scr1 & ~0x10);
ide_dma_lost_irq(drive);
}
static void hpt370_clear_engine(ide_drive_t *drive)
{
ide_hwif_t *hwif = drive->hwif;
struct pci_dev *dev = to_pci_dev(hwif->dev);
pci_write_config_byte(dev, hwif->select_data, 0x37);
udelay(10);
}
static void hpt370_irq_timeout(ide_drive_t *drive)
{
ide_hwif_t *hwif = drive->hwif;
struct pci_dev *dev = to_pci_dev(hwif->dev);
u16 bfifo = 0;
u8 dma_cmd;
pci_read_config_word(dev, hwif->select_data + 2, &bfifo);
printk(KERN_DEBUG "%s: %d bytes in FIFO\n", drive->name, bfifo & 0x1ff);
/* get DMA command mode */
dma_cmd = inb(hwif->dma_base + ATA_DMA_CMD);
/* stop DMA */
outb(dma_cmd & ~ATA_DMA_START, hwif->dma_base + ATA_DMA_CMD);
hpt370_clear_engine(drive);
}
static void hpt370_dma_start(ide_drive_t *drive)
{
#ifdef HPT_RESET_STATE_ENGINE
hpt370_clear_engine(drive);
#endif
ide_dma_start(drive);
}
static int hpt370_dma_end(ide_drive_t *drive)
{
ide_hwif_t *hwif = drive->hwif;
u8 dma_stat = inb(hwif->dma_base + ATA_DMA_STATUS);
if (dma_stat & ATA_DMA_ACTIVE) {
/* wait a little */
udelay(20);
dma_stat = inb(hwif->dma_base + ATA_DMA_STATUS);
if (dma_stat & ATA_DMA_ACTIVE)
hpt370_irq_timeout(drive);
}
return ide_dma_end(drive);
}
/* returns 1 if DMA IRQ issued, 0 otherwise */
static int hpt374_dma_test_irq(ide_drive_t *drive)
{
ide_hwif_t *hwif = drive->hwif;
struct pci_dev *dev = to_pci_dev(hwif->dev);
u16 bfifo = 0;
u8 dma_stat;
pci_read_config_word(dev, hwif->select_data + 2, &bfifo);
if (bfifo & 0x1FF) {
// printk("%s: %d bytes in FIFO\n", drive->name, bfifo);
return 0;
}
dma_stat = inb(hwif->dma_base + ATA_DMA_STATUS);
/* return 1 if INTR asserted */
if (dma_stat & ATA_DMA_INTR)
return 1;
return 0;
}
static int hpt374_dma_end(ide_drive_t *drive)
{
ide_hwif_t *hwif = drive->hwif;
struct pci_dev *dev = to_pci_dev(hwif->dev);
u8 mcr = 0, mcr_addr = hwif->select_data;
u8 bwsr = 0, mask = hwif->channel ? 0x02 : 0x01;
pci_read_config_byte(dev, 0x6a, &bwsr);
pci_read_config_byte(dev, mcr_addr, &mcr);
if (bwsr & mask)
pci_write_config_byte(dev, mcr_addr, mcr | 0x30);
return ide_dma_end(drive);
}
/**
* hpt3xxn_set_clock - perform clock switching dance
* @hwif: hwif to switch
* @mode: clocking mode (0x21 for write, 0x23 otherwise)
*
* Switch the DPLL clock on the HPT3xxN devices. This is a right mess.
*/
static void hpt3xxn_set_clock(ide_hwif_t *hwif, u8 mode)
{
unsigned long base = hwif->extra_base;
u8 scr2 = inb(base + 0x6b);
if ((scr2 & 0x7f) == mode)
return;
/* Tristate the bus */
outb(0x80, base + 0x63);
outb(0x80, base + 0x67);
/* Switch clock and reset channels */
outb(mode, base + 0x6b);
outb(0xc0, base + 0x69);
/*
* Reset the state machines.
* NOTE: avoid accidentally enabling the disabled channels.
*/
outb(inb(base + 0x60) | 0x32, base + 0x60);
outb(inb(base + 0x64) | 0x32, base + 0x64);
/* Complete reset */
outb(0x00, base + 0x69);
/* Reconnect channels to bus */
outb(0x00, base + 0x63);
outb(0x00, base + 0x67);
}
/**
* hpt3xxn_rw_disk - prepare for I/O
* @drive: drive for command
* @rq: block request structure
*
* This is called when a disk I/O is issued to HPT3xxN.
* We need it because of the clock switching.
*/
static void hpt3xxn_rw_disk(ide_drive_t *drive, struct request *rq)
{
hpt3xxn_set_clock(drive->hwif, rq_data_dir(rq) ? 0x21 : 0x23);
}
/**
* hpt37x_calibrate_dpll - calibrate the DPLL
* @dev: PCI device
*
* Perform a calibration cycle on the DPLL.
* Returns 1 if this succeeds
*/
static int hpt37x_calibrate_dpll(struct pci_dev *dev, u16 f_low, u16 f_high)
{
u32 dpll = (f_high << 16) | f_low | 0x100;
u8 scr2;
int i;
pci_write_config_dword(dev, 0x5c, dpll);
/* Wait for oscillator ready */
for(i = 0; i < 0x5000; ++i) {
udelay(50);
pci_read_config_byte(dev, 0x5b, &scr2);
if (scr2 & 0x80)
break;
}
/* See if it stays ready (we'll just bail out if it's not yet) */
for(i = 0; i < 0x1000; ++i) {
pci_read_config_byte(dev, 0x5b, &scr2);
/* DPLL destabilized? */
if(!(scr2 & 0x80))
return 0;
}
/* Turn off tuning, we have the DPLL set */
pci_read_config_dword (dev, 0x5c, &dpll);
pci_write_config_dword(dev, 0x5c, (dpll & ~0x100));
return 1;
}
static void hpt3xx_disable_fast_irq(struct pci_dev *dev, u8 mcr_addr)
{
struct ide_host *host = pci_get_drvdata(dev);
struct hpt_info *info = host->host_priv + (&dev->dev == host->dev[1]);
u8 chip_type = info->chip_type;
u8 new_mcr, old_mcr = 0;
/*
* Disable the "fast interrupt" prediction. Don't hold off
* on interrupts. (== 0x01 despite what the docs say)
*/
pci_read_config_byte(dev, mcr_addr + 1, &old_mcr);
if (chip_type >= HPT374)
new_mcr = old_mcr & ~0x07;
else if (chip_type >= HPT370) {
new_mcr = old_mcr;
new_mcr &= ~0x02;
#ifdef HPT_DELAY_INTERRUPT
new_mcr &= ~0x01;
#else
new_mcr |= 0x01;
#endif
} else /* HPT366 and HPT368 */
new_mcr = old_mcr & ~0x80;
if (new_mcr != old_mcr)
pci_write_config_byte(dev, mcr_addr + 1, new_mcr);
}
static int init_chipset_hpt366(struct pci_dev *dev)
{
unsigned long io_base = pci_resource_start(dev, 4);
struct hpt_info *info = hpt3xx_get_info(&dev->dev);
const char *name = DRV_NAME;
u8 pci_clk, dpll_clk = 0; /* PCI and DPLL clock in MHz */
u8 chip_type;
enum ata_clock clock;
chip_type = info->chip_type;
pci_write_config_byte(dev, PCI_CACHE_LINE_SIZE, (L1_CACHE_BYTES / 4));
pci_write_config_byte(dev, PCI_LATENCY_TIMER, 0x78);
pci_write_config_byte(dev, PCI_MIN_GNT, 0x08);
pci_write_config_byte(dev, PCI_MAX_LAT, 0x08);
/*
* First, try to estimate the PCI clock frequency...
*/
if (chip_type >= HPT370) {
u8 scr1 = 0;
u16 f_cnt = 0;
u32 temp = 0;
/* Interrupt force enable. */
pci_read_config_byte(dev, 0x5a, &scr1);
if (scr1 & 0x10)
pci_write_config_byte(dev, 0x5a, scr1 & ~0x10);
/*
* HighPoint does this for HPT372A.
* NOTE: This register is only writeable via I/O space.
*/
if (chip_type == HPT372A)
outb(0x0e, io_base + 0x9c);
/*
* Default to PCI clock. Make sure MA15/16 are set to output
* to prevent drives having problems with 40-pin cables.
*/
pci_write_config_byte(dev, 0x5b, 0x23);
/*
* We'll have to read f_CNT value in order to determine
* the PCI clock frequency according to the following ratio:
*
* f_CNT = Fpci * 192 / Fdpll
*
* First try reading the register in which the HighPoint BIOS
* saves f_CNT value before reprogramming the DPLL from its
* default setting (which differs for the various chips).
*
* NOTE: This register is only accessible via I/O space;
* HPT374 BIOS only saves it for the function 0, so we have to
* always read it from there -- no need to check the result of
* pci_get_slot() for the function 0 as the whole device has
* been already "pinned" (via function 1) in init_setup_hpt374()
*/
if (chip_type == HPT374 && (PCI_FUNC(dev->devfn) & 1)) {
struct pci_dev *dev1 = pci_get_slot(dev->bus,
dev->devfn - 1);
unsigned long io_base = pci_resource_start(dev1, 4);
temp = inl(io_base + 0x90);
pci_dev_put(dev1);
} else
temp = inl(io_base + 0x90);
/*
* In case the signature check fails, we'll have to
* resort to reading the f_CNT register itself in hopes
* that nobody has touched the DPLL yet...
*/
if ((temp & 0xFFFFF000) != 0xABCDE000) {
int i;
printk(KERN_WARNING "%s %s: no clock data saved by "
"BIOS\n", name, pci_name(dev));
/* Calculate the average value of f_CNT. */
for (temp = i = 0; i < 128; i++) {
pci_read_config_word(dev, 0x78, &f_cnt);
temp += f_cnt & 0x1ff;
mdelay(1);
}
f_cnt = temp / 128;
} else
f_cnt = temp & 0x1ff;
dpll_clk = info->dpll_clk;
pci_clk = (f_cnt * dpll_clk) / 192;
/* Clamp PCI clock to bands. */
if (pci_clk < 40)
pci_clk = 33;
else if(pci_clk < 45)
pci_clk = 40;
else if(pci_clk < 55)
pci_clk = 50;
else
pci_clk = 66;
printk(KERN_INFO "%s %s: DPLL base: %d MHz, f_CNT: %d, "
"assuming %d MHz PCI\n", name, pci_name(dev),
dpll_clk, f_cnt, pci_clk);
} else {
u32 itr1 = 0;
pci_read_config_dword(dev, 0x40, &itr1);
/* Detect PCI clock by looking at cmd_high_time. */
switch((itr1 >> 8) & 0x07) {
case 0x09:
pci_clk = 40;
break;
case 0x05:
pci_clk = 25;
break;
case 0x07:
default:
pci_clk = 33;
break;
}
}
/* Let's assume we'll use PCI clock for the ATA clock... */
switch (pci_clk) {
case 25:
clock = ATA_CLOCK_25MHZ;
break;
case 33:
default:
clock = ATA_CLOCK_33MHZ;
break;
case 40:
clock = ATA_CLOCK_40MHZ;
break;
case 50:
clock = ATA_CLOCK_50MHZ;
break;
case 66:
clock = ATA_CLOCK_66MHZ;
break;
}
/*
* Only try the DPLL if we don't have a table for the PCI clock that
* we are running at for HPT370/A, always use it for anything newer...
*
* NOTE: Using the internal DPLL results in slow reads on 33 MHz PCI.
* We also don't like using the DPLL because this causes glitches
* on PRST-/SRST- when the state engine gets reset...
*/
if (chip_type >= HPT374 || info->timings->clock_table[clock] == NULL) {
u16 f_low, delta = pci_clk < 50 ? 2 : 4;
int adjust;
/*
* Select 66 MHz DPLL clock only if UltraATA/133 mode is
* supported/enabled, use 50 MHz DPLL clock otherwise...
*/
if (info->udma_mask == ATA_UDMA6) {
dpll_clk = 66;
clock = ATA_CLOCK_66MHZ;
} else if (dpll_clk) { /* HPT36x chips don't have DPLL */
dpll_clk = 50;
clock = ATA_CLOCK_50MHZ;
}
if (info->timings->clock_table[clock] == NULL) {
printk(KERN_ERR "%s %s: unknown bus timing!\n",
name, pci_name(dev));
return -EIO;
}
/* Select the DPLL clock. */
pci_write_config_byte(dev, 0x5b, 0x21);
/*
* Adjust the DPLL based upon PCI clock, enable it,
* and wait for stabilization...
*/
f_low = (pci_clk * 48) / dpll_clk;
for (adjust = 0; adjust < 8; adjust++) {
if(hpt37x_calibrate_dpll(dev, f_low, f_low + delta))
break;
/*
* See if it'll settle at a fractionally different clock
*/
if (adjust & 1)
f_low -= adjust >> 1;
else
f_low += adjust >> 1;
}
if (adjust == 8) {
printk(KERN_ERR "%s %s: DPLL did not stabilize!\n",
name, pci_name(dev));
return -EIO;
}
printk(KERN_INFO "%s %s: using %d MHz DPLL clock\n",
name, pci_name(dev), dpll_clk);
} else {
/* Mark the fact that we're not using the DPLL. */
dpll_clk = 0;
printk(KERN_INFO "%s %s: using %d MHz PCI clock\n",
name, pci_name(dev), pci_clk);
}
/* Store the clock frequencies. */
info->dpll_clk = dpll_clk;
info->pci_clk = pci_clk;
info->clock = clock;
if (chip_type >= HPT370) {
u8 mcr1, mcr4;
/*
* Reset the state engines.
* NOTE: Avoid accidentally enabling the disabled channels.
*/
pci_read_config_byte (dev, 0x50, &mcr1);
pci_read_config_byte (dev, 0x54, &mcr4);
pci_write_config_byte(dev, 0x50, (mcr1 | 0x32));
pci_write_config_byte(dev, 0x54, (mcr4 | 0x32));
udelay(100);
}
/*
* On HPT371N, if ATA clock is 66 MHz we must set bit 2 in
* the MISC. register to stretch the UltraDMA Tss timing.
* NOTE: This register is only writeable via I/O space.
*/
if (chip_type == HPT371N && clock == ATA_CLOCK_66MHZ)
outb(inb(io_base + 0x9c) | 0x04, io_base + 0x9c);
hpt3xx_disable_fast_irq(dev, 0x50);
hpt3xx_disable_fast_irq(dev, 0x54);
return 0;
}
static u8 hpt3xx_cable_detect(ide_hwif_t *hwif)
{
struct pci_dev *dev = to_pci_dev(hwif->dev);
struct hpt_info *info = hpt3xx_get_info(hwif->dev);
u8 chip_type = info->chip_type;
u8 scr1 = 0, ata66 = hwif->channel ? 0x01 : 0x02;
/*
* The HPT37x uses the CBLID pins as outputs for MA15/MA16
* address lines to access an external EEPROM. To read valid
* cable detect state the pins must be enabled as inputs.
*/
if (chip_type == HPT374 && (PCI_FUNC(dev->devfn) & 1)) {
/*
* HPT374 PCI function 1
* - set bit 15 of reg 0x52 to enable TCBLID as input
* - set bit 15 of reg 0x56 to enable FCBLID as input
*/
u8 mcr_addr = hwif->select_data + 2;
u16 mcr;
pci_read_config_word(dev, mcr_addr, &mcr);
pci_write_config_word(dev, mcr_addr, mcr | 0x8000);
/* Debounce, then read cable ID register */
udelay(10);
pci_read_config_byte(dev, 0x5a, &scr1);
pci_write_config_word(dev, mcr_addr, mcr);
} else if (chip_type >= HPT370) {
/*
* HPT370/372 and 374 pcifn 0
* - clear bit 0 of reg 0x5b to enable P/SCBLID as inputs
*/
u8 scr2 = 0;
pci_read_config_byte(dev, 0x5b, &scr2);
pci_write_config_byte(dev, 0x5b, scr2 & ~1);
/* Debounce, then read cable ID register */
udelay(10);
pci_read_config_byte(dev, 0x5a, &scr1);
pci_write_config_byte(dev, 0x5b, scr2);
} else
pci_read_config_byte(dev, 0x5a, &scr1);
return (scr1 & ata66) ? ATA_CBL_PATA40 : ATA_CBL_PATA80;
}
static void __devinit init_hwif_hpt366(ide_hwif_t *hwif)
{
struct hpt_info *info = hpt3xx_get_info(hwif->dev);
u8 chip_type = info->chip_type;
/* Cache the channel's MISC. control registers' offset */
hwif->select_data = hwif->channel ? 0x54 : 0x50;
/*
* HPT3xxN chips have some complications:
*
* - on 33 MHz PCI we must clock switch
* - on 66 MHz PCI we must NOT use the PCI clock
*/
if (chip_type >= HPT372N && info->dpll_clk && info->pci_clk < 66) {
/*
* Clock is shared between the channels,
* so we'll have to serialize them... :-(
*/
hwif->host->host_flags |= IDE_HFLAG_SERIALIZE;
hwif->rw_disk = &hpt3xxn_rw_disk;
}
}
static int __devinit init_dma_hpt366(ide_hwif_t *hwif,
const struct ide_port_info *d)
{
struct pci_dev *dev = to_pci_dev(hwif->dev);
unsigned long flags, base = ide_pci_dma_base(hwif, d);
u8 dma_old, dma_new, masterdma = 0, slavedma = 0;
if (base == 0)
return -1;
hwif->dma_base = base;
if (ide_pci_check_simplex(hwif, d) < 0)
return -1;
if (ide_pci_set_master(dev, d->name) < 0)
return -1;
dma_old = inb(base + 2);
local_irq_save(flags);
dma_new = dma_old;
pci_read_config_byte(dev, hwif->channel ? 0x4b : 0x43, &masterdma);
pci_read_config_byte(dev, hwif->channel ? 0x4f : 0x47, &slavedma);
if (masterdma & 0x30) dma_new |= 0x20;
if ( slavedma & 0x30) dma_new |= 0x40;
if (dma_new != dma_old)
outb(dma_new, base + 2);
local_irq_restore(flags);
printk(KERN_INFO " %s: BM-DMA at 0x%04lx-0x%04lx\n",
hwif->name, base, base + 7);
hwif->extra_base = base + (hwif->channel ? 8 : 16);
if (ide_allocate_dma_engine(hwif))
return -1;
return 0;
}
static void __devinit hpt374_init(struct pci_dev *dev, struct pci_dev *dev2)
{
if (dev2->irq != dev->irq) {
/* FIXME: we need a core pci_set_interrupt() */
dev2->irq = dev->irq;
printk(KERN_INFO DRV_NAME " %s: PCI config space interrupt "
"fixed\n", pci_name(dev2));
}
}
static void __devinit hpt371_init(struct pci_dev *dev)
{
u8 mcr1 = 0;
/*
* HPT371 chips physically have only one channel, the secondary one,
* but the primary channel registers do exist! Go figure...
* So, we manually disable the non-existing channel here
* (if the BIOS hasn't done this already).
*/
pci_read_config_byte(dev, 0x50, &mcr1);
if (mcr1 & 0x04)
pci_write_config_byte(dev, 0x50, mcr1 & ~0x04);
}
static int __devinit hpt36x_init(struct pci_dev *dev, struct pci_dev *dev2)
{
u8 mcr1 = 0, pin1 = 0, pin2 = 0;
/*
* Now we'll have to force both channels enabled if
* at least one of them has been enabled by BIOS...
*/
pci_read_config_byte(dev, 0x50, &mcr1);
if (mcr1 & 0x30)
pci_write_config_byte(dev, 0x50, mcr1 | 0x30);
pci_read_config_byte(dev, PCI_INTERRUPT_PIN, &pin1);
pci_read_config_byte(dev2, PCI_INTERRUPT_PIN, &pin2);
if (pin1 != pin2 && dev->irq == dev2->irq) {
printk(KERN_INFO DRV_NAME " %s: onboard version of chipset, "
"pin1=%d pin2=%d\n", pci_name(dev), pin1, pin2);
return 1;
}
return 0;
}
#define IDE_HFLAGS_HPT3XX \
(IDE_HFLAG_NO_ATAPI_DMA | \
IDE_HFLAG_OFF_BOARD)
static const struct ide_port_ops hpt3xx_port_ops = {
.set_pio_mode = hpt3xx_set_pio_mode,
.set_dma_mode = hpt3xx_set_mode,
.maskproc = hpt3xx_maskproc,
.mdma_filter = hpt3xx_mdma_filter,
.udma_filter = hpt3xx_udma_filter,
.cable_detect = hpt3xx_cable_detect,
};
static const struct ide_dma_ops hpt37x_dma_ops = {
.dma_host_set = ide_dma_host_set,
.dma_setup = ide_dma_setup,
.dma_start = ide_dma_start,
.dma_end = hpt374_dma_end,
.dma_test_irq = hpt374_dma_test_irq,
.dma_lost_irq = ide_dma_lost_irq,
.dma_timer_expiry = ide_dma_sff_timer_expiry,
.dma_sff_read_status = ide_dma_sff_read_status,
};
static const struct ide_dma_ops hpt370_dma_ops = {
.dma_host_set = ide_dma_host_set,
.dma_setup = ide_dma_setup,
.dma_start = hpt370_dma_start,
.dma_end = hpt370_dma_end,
.dma_test_irq = ide_dma_test_irq,
.dma_lost_irq = ide_dma_lost_irq,
.dma_timer_expiry = ide_dma_sff_timer_expiry,
.dma_clear = hpt370_irq_timeout,
.dma_sff_read_status = ide_dma_sff_read_status,
};
static const struct ide_dma_ops hpt36x_dma_ops = {
.dma_host_set = ide_dma_host_set,
.dma_setup = ide_dma_setup,
.dma_start = ide_dma_start,
.dma_end = ide_dma_end,
.dma_test_irq = ide_dma_test_irq,
.dma_lost_irq = hpt366_dma_lost_irq,
.dma_timer_expiry = ide_dma_sff_timer_expiry,
.dma_sff_read_status = ide_dma_sff_read_status,
};
static const struct ide_port_info hpt366_chipsets[] __devinitdata = {
{ /* 0: HPT36x */
.name = DRV_NAME,
.init_chipset = init_chipset_hpt366,
.init_hwif = init_hwif_hpt366,
.init_dma = init_dma_hpt366,
/*
* HPT36x chips have one channel per function and have
* both channel enable bits located differently and visible
* to both functions -- really stupid design decision... :-(
* Bit 4 is for the primary channel, bit 5 for the secondary.
*/
.enablebits = {{0x50,0x10,0x10}, {0x54,0x04,0x04}},
.port_ops = &hpt3xx_port_ops,
.dma_ops = &hpt36x_dma_ops,
.host_flags = IDE_HFLAGS_HPT3XX | IDE_HFLAG_SINGLE,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
},
{ /* 1: HPT3xx */
.name = DRV_NAME,
.init_chipset = init_chipset_hpt366,
.init_hwif = init_hwif_hpt366,
.init_dma = init_dma_hpt366,
.enablebits = {{0x50,0x04,0x04}, {0x54,0x04,0x04}},
.port_ops = &hpt3xx_port_ops,
.dma_ops = &hpt37x_dma_ops,
.host_flags = IDE_HFLAGS_HPT3XX,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
}
};
/**
* hpt366_init_one - called when an HPT366 is found
* @dev: the hpt366 device
* @id: the matching pci id
*
* Called when the PCI registration layer (or the IDE initialization)
* finds a device matching our IDE device tables.
*/
static int __devinit hpt366_init_one(struct pci_dev *dev, const struct pci_device_id *id)
{
const struct hpt_info *info = NULL;
struct hpt_info *dyn_info;
struct pci_dev *dev2 = NULL;
struct ide_port_info d;
u8 idx = id->driver_data;
u8 rev = dev->revision;
int ret;
if ((idx == 0 || idx == 4) && (PCI_FUNC(dev->devfn) & 1))
return -ENODEV;
switch (idx) {
case 0:
if (rev < 3)
info = &hpt36x;
else {
switch (min_t(u8, rev, 6)) {
case 3: info = &hpt370; break;
case 4: info = &hpt370a; break;
case 5: info = &hpt372; break;
case 6: info = &hpt372n; break;
}
idx++;
}
break;
case 1:
info = (rev > 1) ? &hpt372n : &hpt372a;
break;
case 2:
info = (rev > 1) ? &hpt302n : &hpt302;
break;
case 3:
hpt371_init(dev);
info = (rev > 1) ? &hpt371n : &hpt371;
break;
case 4:
info = &hpt374;
break;
case 5:
info = &hpt372n;
break;
}
printk(KERN_INFO DRV_NAME ": %s chipset detected\n", info->chip_name);
d = hpt366_chipsets[min_t(u8, idx, 1)];
d.udma_mask = info->udma_mask;
/* fixup ->dma_ops for HPT370/HPT370A */
if (info == &hpt370 || info == &hpt370a)
d.dma_ops = &hpt370_dma_ops;
if (info == &hpt36x || info == &hpt374)
dev2 = pci_get_slot(dev->bus, dev->devfn + 1);
dyn_info = kzalloc(sizeof(*dyn_info) * (dev2 ? 2 : 1), GFP_KERNEL);
if (dyn_info == NULL) {
printk(KERN_ERR "%s %s: out of memory!\n",
d.name, pci_name(dev));
pci_dev_put(dev2);
return -ENOMEM;
}
/*
* Copy everything from a static "template" structure
* to just allocated per-chip hpt_info structure.
*/
memcpy(dyn_info, info, sizeof(*dyn_info));
if (dev2) {
memcpy(dyn_info + 1, info, sizeof(*dyn_info));
if (info == &hpt374)
hpt374_init(dev, dev2);
else {
if (hpt36x_init(dev, dev2))
d.host_flags &= ~IDE_HFLAG_NON_BOOTABLE;
}
ret = ide_pci_init_two(dev, dev2, &d, dyn_info);
if (ret < 0) {
pci_dev_put(dev2);
kfree(dyn_info);
}
return ret;
}
ret = ide_pci_init_one(dev, &d, dyn_info);
if (ret < 0)
kfree(dyn_info);
return ret;
}
static void __devexit hpt366_remove(struct pci_dev *dev)
{
struct ide_host *host = pci_get_drvdata(dev);
struct ide_info *info = host->host_priv;
struct pci_dev *dev2 = host->dev[1] ? to_pci_dev(host->dev[1]) : NULL;
ide_pci_remove(dev);
pci_dev_put(dev2);
kfree(info);
}
static const struct pci_device_id hpt366_pci_tbl[] __devinitconst = {
{ PCI_VDEVICE(TTI, PCI_DEVICE_ID_TTI_HPT366), 0 },
{ PCI_VDEVICE(TTI, PCI_DEVICE_ID_TTI_HPT372), 1 },
{ PCI_VDEVICE(TTI, PCI_DEVICE_ID_TTI_HPT302), 2 },
{ PCI_VDEVICE(TTI, PCI_DEVICE_ID_TTI_HPT371), 3 },
{ PCI_VDEVICE(TTI, PCI_DEVICE_ID_TTI_HPT374), 4 },
{ PCI_VDEVICE(TTI, PCI_DEVICE_ID_TTI_HPT372N), 5 },
{ 0, },
};
MODULE_DEVICE_TABLE(pci, hpt366_pci_tbl);
static struct pci_driver hpt366_pci_driver = {
.name = "HPT366_IDE",
.id_table = hpt366_pci_tbl,
.probe = hpt366_init_one,
.remove = __devexit_p(hpt366_remove),
.suspend = ide_pci_suspend,
.resume = ide_pci_resume,
};
static int __init hpt366_ide_init(void)
{
return ide_pci_register_driver(&hpt366_pci_driver);
}
static void __exit hpt366_ide_exit(void)
{
pci_unregister_driver(&hpt366_pci_driver);
}
module_init(hpt366_ide_init);
module_exit(hpt366_ide_exit);
MODULE_AUTHOR("Andre Hedrick");
MODULE_DESCRIPTION("PCI driver module for Highpoint HPT366 IDE");
MODULE_LICENSE("GPL");
| gpl-2.0 |
nimengyu2/ti-arm9-linux-03.21.00.04 | fs/fscache/cache.c | 9785 | 11054 | /* FS-Cache cache handling
*
* 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 License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#define FSCACHE_DEBUG_LEVEL CACHE
#include <linux/module.h>
#include <linux/slab.h>
#include "internal.h"
LIST_HEAD(fscache_cache_list);
DECLARE_RWSEM(fscache_addremove_sem);
DECLARE_WAIT_QUEUE_HEAD(fscache_cache_cleared_wq);
EXPORT_SYMBOL(fscache_cache_cleared_wq);
static LIST_HEAD(fscache_cache_tag_list);
/*
* look up a cache tag
*/
struct fscache_cache_tag *__fscache_lookup_cache_tag(const char *name)
{
struct fscache_cache_tag *tag, *xtag;
/* firstly check for the existence of the tag under read lock */
down_read(&fscache_addremove_sem);
list_for_each_entry(tag, &fscache_cache_tag_list, link) {
if (strcmp(tag->name, name) == 0) {
atomic_inc(&tag->usage);
up_read(&fscache_addremove_sem);
return tag;
}
}
up_read(&fscache_addremove_sem);
/* the tag does not exist - create a candidate */
xtag = kzalloc(sizeof(*xtag) + strlen(name) + 1, GFP_KERNEL);
if (!xtag)
/* return a dummy tag if out of memory */
return ERR_PTR(-ENOMEM);
atomic_set(&xtag->usage, 1);
strcpy(xtag->name, name);
/* write lock, search again and add if still not present */
down_write(&fscache_addremove_sem);
list_for_each_entry(tag, &fscache_cache_tag_list, link) {
if (strcmp(tag->name, name) == 0) {
atomic_inc(&tag->usage);
up_write(&fscache_addremove_sem);
kfree(xtag);
return tag;
}
}
list_add_tail(&xtag->link, &fscache_cache_tag_list);
up_write(&fscache_addremove_sem);
return xtag;
}
/*
* release a reference to a cache tag
*/
void __fscache_release_cache_tag(struct fscache_cache_tag *tag)
{
if (tag != ERR_PTR(-ENOMEM)) {
down_write(&fscache_addremove_sem);
if (atomic_dec_and_test(&tag->usage))
list_del_init(&tag->link);
else
tag = NULL;
up_write(&fscache_addremove_sem);
kfree(tag);
}
}
/*
* select a cache in which to store an object
* - the cache addremove semaphore must be at least read-locked by the caller
* - the object will never be an index
*/
struct fscache_cache *fscache_select_cache_for_object(
struct fscache_cookie *cookie)
{
struct fscache_cache_tag *tag;
struct fscache_object *object;
struct fscache_cache *cache;
_enter("");
if (list_empty(&fscache_cache_list)) {
_leave(" = NULL [no cache]");
return NULL;
}
/* we check the parent to determine the cache to use */
spin_lock(&cookie->lock);
/* the first in the parent's backing list should be the preferred
* cache */
if (!hlist_empty(&cookie->backing_objects)) {
object = hlist_entry(cookie->backing_objects.first,
struct fscache_object, cookie_link);
cache = object->cache;
if (object->state >= FSCACHE_OBJECT_DYING ||
test_bit(FSCACHE_IOERROR, &cache->flags))
cache = NULL;
spin_unlock(&cookie->lock);
_leave(" = %p [parent]", cache);
return cache;
}
/* the parent is unbacked */
if (cookie->def->type != FSCACHE_COOKIE_TYPE_INDEX) {
/* cookie not an index and is unbacked */
spin_unlock(&cookie->lock);
_leave(" = NULL [cookie ub,ni]");
return NULL;
}
spin_unlock(&cookie->lock);
if (!cookie->def->select_cache)
goto no_preference;
/* ask the netfs for its preference */
tag = cookie->def->select_cache(cookie->parent->netfs_data,
cookie->netfs_data);
if (!tag)
goto no_preference;
if (tag == ERR_PTR(-ENOMEM)) {
_leave(" = NULL [nomem tag]");
return NULL;
}
if (!tag->cache) {
_leave(" = NULL [unbacked tag]");
return NULL;
}
if (test_bit(FSCACHE_IOERROR, &tag->cache->flags))
return NULL;
_leave(" = %p [specific]", tag->cache);
return tag->cache;
no_preference:
/* netfs has no preference - just select first cache */
cache = list_entry(fscache_cache_list.next,
struct fscache_cache, link);
_leave(" = %p [first]", cache);
return cache;
}
/**
* fscache_init_cache - Initialise a cache record
* @cache: The cache record to be initialised
* @ops: The cache operations to be installed in that record
* @idfmt: Format string to define identifier
* @...: sprintf-style arguments
*
* Initialise a record of a cache and fill in the name.
*
* See Documentation/filesystems/caching/backend-api.txt for a complete
* description.
*/
void fscache_init_cache(struct fscache_cache *cache,
const struct fscache_cache_ops *ops,
const char *idfmt,
...)
{
va_list va;
memset(cache, 0, sizeof(*cache));
cache->ops = ops;
va_start(va, idfmt);
vsnprintf(cache->identifier, sizeof(cache->identifier), idfmt, va);
va_end(va);
INIT_WORK(&cache->op_gc, fscache_operation_gc);
INIT_LIST_HEAD(&cache->link);
INIT_LIST_HEAD(&cache->object_list);
INIT_LIST_HEAD(&cache->op_gc_list);
spin_lock_init(&cache->object_list_lock);
spin_lock_init(&cache->op_gc_list_lock);
}
EXPORT_SYMBOL(fscache_init_cache);
/**
* fscache_add_cache - Declare a cache as being open for business
* @cache: The record describing the cache
* @ifsdef: The record of the cache object describing the top-level index
* @tagname: The tag describing this cache
*
* Add a cache to the system, making it available for netfs's to use.
*
* See Documentation/filesystems/caching/backend-api.txt for a complete
* description.
*/
int fscache_add_cache(struct fscache_cache *cache,
struct fscache_object *ifsdef,
const char *tagname)
{
struct fscache_cache_tag *tag;
BUG_ON(!cache->ops);
BUG_ON(!ifsdef);
cache->flags = 0;
ifsdef->event_mask = ULONG_MAX & ~(1 << FSCACHE_OBJECT_EV_CLEARED);
ifsdef->state = FSCACHE_OBJECT_ACTIVE;
if (!tagname)
tagname = cache->identifier;
BUG_ON(!tagname[0]);
_enter("{%s.%s},,%s", cache->ops->name, cache->identifier, tagname);
/* we use the cache tag to uniquely identify caches */
tag = __fscache_lookup_cache_tag(tagname);
if (IS_ERR(tag))
goto nomem;
if (test_and_set_bit(FSCACHE_TAG_RESERVED, &tag->flags))
goto tag_in_use;
cache->kobj = kobject_create_and_add(tagname, fscache_root);
if (!cache->kobj)
goto error;
ifsdef->cookie = &fscache_fsdef_index;
ifsdef->cache = cache;
cache->fsdef = ifsdef;
down_write(&fscache_addremove_sem);
tag->cache = cache;
cache->tag = tag;
/* add the cache to the list */
list_add(&cache->link, &fscache_cache_list);
/* add the cache's netfs definition index object to the cache's
* list */
spin_lock(&cache->object_list_lock);
list_add_tail(&ifsdef->cache_link, &cache->object_list);
spin_unlock(&cache->object_list_lock);
fscache_objlist_add(ifsdef);
/* add the cache's netfs definition index object to the top level index
* cookie as a known backing object */
spin_lock(&fscache_fsdef_index.lock);
hlist_add_head(&ifsdef->cookie_link,
&fscache_fsdef_index.backing_objects);
atomic_inc(&fscache_fsdef_index.usage);
/* done */
spin_unlock(&fscache_fsdef_index.lock);
up_write(&fscache_addremove_sem);
printk(KERN_NOTICE "FS-Cache: Cache \"%s\" added (type %s)\n",
cache->tag->name, cache->ops->name);
kobject_uevent(cache->kobj, KOBJ_ADD);
_leave(" = 0 [%s]", cache->identifier);
return 0;
tag_in_use:
printk(KERN_ERR "FS-Cache: Cache tag '%s' already in use\n", tagname);
__fscache_release_cache_tag(tag);
_leave(" = -EXIST");
return -EEXIST;
error:
__fscache_release_cache_tag(tag);
_leave(" = -EINVAL");
return -EINVAL;
nomem:
_leave(" = -ENOMEM");
return -ENOMEM;
}
EXPORT_SYMBOL(fscache_add_cache);
/**
* fscache_io_error - Note a cache I/O error
* @cache: The record describing the cache
*
* Note that an I/O error occurred in a cache and that it should no longer be
* used for anything. This also reports the error into the kernel log.
*
* See Documentation/filesystems/caching/backend-api.txt for a complete
* description.
*/
void fscache_io_error(struct fscache_cache *cache)
{
set_bit(FSCACHE_IOERROR, &cache->flags);
printk(KERN_ERR "FS-Cache: Cache %s stopped due to I/O error\n",
cache->ops->name);
}
EXPORT_SYMBOL(fscache_io_error);
/*
* request withdrawal of all the objects in a cache
* - all the objects being withdrawn are moved onto the supplied list
*/
static void fscache_withdraw_all_objects(struct fscache_cache *cache,
struct list_head *dying_objects)
{
struct fscache_object *object;
spin_lock(&cache->object_list_lock);
while (!list_empty(&cache->object_list)) {
object = list_entry(cache->object_list.next,
struct fscache_object, cache_link);
list_move_tail(&object->cache_link, dying_objects);
_debug("withdraw %p", object->cookie);
spin_lock(&object->lock);
spin_unlock(&cache->object_list_lock);
fscache_raise_event(object, FSCACHE_OBJECT_EV_WITHDRAW);
spin_unlock(&object->lock);
cond_resched();
spin_lock(&cache->object_list_lock);
}
spin_unlock(&cache->object_list_lock);
}
/**
* fscache_withdraw_cache - Withdraw a cache from the active service
* @cache: The record describing the cache
*
* Withdraw a cache from service, unbinding all its cache objects from the
* netfs cookies they're currently representing.
*
* See Documentation/filesystems/caching/backend-api.txt for a complete
* description.
*/
void fscache_withdraw_cache(struct fscache_cache *cache)
{
LIST_HEAD(dying_objects);
_enter("");
printk(KERN_NOTICE "FS-Cache: Withdrawing cache \"%s\"\n",
cache->tag->name);
/* make the cache unavailable for cookie acquisition */
if (test_and_set_bit(FSCACHE_CACHE_WITHDRAWN, &cache->flags))
BUG();
down_write(&fscache_addremove_sem);
list_del_init(&cache->link);
cache->tag->cache = NULL;
up_write(&fscache_addremove_sem);
/* make sure all pages pinned by operations on behalf of the netfs are
* written to disk */
fscache_stat(&fscache_n_cop_sync_cache);
cache->ops->sync_cache(cache);
fscache_stat_d(&fscache_n_cop_sync_cache);
/* dissociate all the netfs pages backed by this cache from the block
* mappings in the cache */
fscache_stat(&fscache_n_cop_dissociate_pages);
cache->ops->dissociate_pages(cache);
fscache_stat_d(&fscache_n_cop_dissociate_pages);
/* we now have to destroy all the active objects pertaining to this
* cache - which we do by passing them off to thread pool to be
* disposed of */
_debug("destroy");
fscache_withdraw_all_objects(cache, &dying_objects);
/* wait for all extant objects to finish their outstanding operations
* and go away */
_debug("wait for finish");
wait_event(fscache_cache_cleared_wq,
atomic_read(&cache->object_count) == 0);
_debug("wait for clearance");
wait_event(fscache_cache_cleared_wq,
list_empty(&cache->object_list));
_debug("cleared");
ASSERT(list_empty(&dying_objects));
kobject_put(cache->kobj);
clear_bit(FSCACHE_TAG_RESERVED, &cache->tag->flags);
fscache_release_cache_tag(cache->tag);
cache->tag = NULL;
_leave("");
}
EXPORT_SYMBOL(fscache_withdraw_cache);
| gpl-2.0 |
acuicultor/Radioactive-kernel-HAM | arch/x86/math-emu/reg_compare.c | 13881 | 8289 | /*---------------------------------------------------------------------------+
| reg_compare.c |
| |
| Compare two floating point registers |
| |
| Copyright (C) 1992,1993,1994,1997 |
| W. Metzenthen, 22 Parker St, Ormond, Vic 3163, Australia |
| E-mail billm@suburbia.net |
| |
| |
+---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------+
| compare() is the core FPU_REG comparison function |
+---------------------------------------------------------------------------*/
#include "fpu_system.h"
#include "exception.h"
#include "fpu_emu.h"
#include "control_w.h"
#include "status_w.h"
static int compare(FPU_REG const *b, int tagb)
{
int diff, exp0, expb;
u_char st0_tag;
FPU_REG *st0_ptr;
FPU_REG x, y;
u_char st0_sign, signb = getsign(b);
st0_ptr = &st(0);
st0_tag = FPU_gettag0();
st0_sign = getsign(st0_ptr);
if (tagb == TAG_Special)
tagb = FPU_Special(b);
if (st0_tag == TAG_Special)
st0_tag = FPU_Special(st0_ptr);
if (((st0_tag != TAG_Valid) && (st0_tag != TW_Denormal))
|| ((tagb != TAG_Valid) && (tagb != TW_Denormal))) {
if (st0_tag == TAG_Zero) {
if (tagb == TAG_Zero)
return COMP_A_eq_B;
if (tagb == TAG_Valid)
return ((signb ==
SIGN_POS) ? COMP_A_lt_B : COMP_A_gt_B);
if (tagb == TW_Denormal)
return ((signb ==
SIGN_POS) ? COMP_A_lt_B : COMP_A_gt_B)
| COMP_Denormal;
} else if (tagb == TAG_Zero) {
if (st0_tag == TAG_Valid)
return ((st0_sign ==
SIGN_POS) ? COMP_A_gt_B : COMP_A_lt_B);
if (st0_tag == TW_Denormal)
return ((st0_sign ==
SIGN_POS) ? COMP_A_gt_B : COMP_A_lt_B)
| COMP_Denormal;
}
if (st0_tag == TW_Infinity) {
if ((tagb == TAG_Valid) || (tagb == TAG_Zero))
return ((st0_sign ==
SIGN_POS) ? COMP_A_gt_B : COMP_A_lt_B);
else if (tagb == TW_Denormal)
return ((st0_sign ==
SIGN_POS) ? COMP_A_gt_B : COMP_A_lt_B)
| COMP_Denormal;
else if (tagb == TW_Infinity) {
/* The 80486 book says that infinities can be equal! */
return (st0_sign == signb) ? COMP_A_eq_B :
((st0_sign ==
SIGN_POS) ? COMP_A_gt_B : COMP_A_lt_B);
}
/* Fall through to the NaN code */
} else if (tagb == TW_Infinity) {
if ((st0_tag == TAG_Valid) || (st0_tag == TAG_Zero))
return ((signb ==
SIGN_POS) ? COMP_A_lt_B : COMP_A_gt_B);
if (st0_tag == TW_Denormal)
return ((signb ==
SIGN_POS) ? COMP_A_lt_B : COMP_A_gt_B)
| COMP_Denormal;
/* Fall through to the NaN code */
}
/* The only possibility now should be that one of the arguments
is a NaN */
if ((st0_tag == TW_NaN) || (tagb == TW_NaN)) {
int signalling = 0, unsupported = 0;
if (st0_tag == TW_NaN) {
signalling =
(st0_ptr->sigh & 0xc0000000) == 0x80000000;
unsupported = !((exponent(st0_ptr) == EXP_OVER)
&& (st0_ptr->
sigh & 0x80000000));
}
if (tagb == TW_NaN) {
signalling |=
(b->sigh & 0xc0000000) == 0x80000000;
unsupported |= !((exponent(b) == EXP_OVER)
&& (b->sigh & 0x80000000));
}
if (signalling || unsupported)
return COMP_No_Comp | COMP_SNaN | COMP_NaN;
else
/* Neither is a signaling NaN */
return COMP_No_Comp | COMP_NaN;
}
EXCEPTION(EX_Invalid);
}
if (st0_sign != signb) {
return ((st0_sign == SIGN_POS) ? COMP_A_gt_B : COMP_A_lt_B)
| (((st0_tag == TW_Denormal) || (tagb == TW_Denormal)) ?
COMP_Denormal : 0);
}
if ((st0_tag == TW_Denormal) || (tagb == TW_Denormal)) {
FPU_to_exp16(st0_ptr, &x);
FPU_to_exp16(b, &y);
st0_ptr = &x;
b = &y;
exp0 = exponent16(st0_ptr);
expb = exponent16(b);
} else {
exp0 = exponent(st0_ptr);
expb = exponent(b);
}
#ifdef PARANOID
if (!(st0_ptr->sigh & 0x80000000))
EXCEPTION(EX_Invalid);
if (!(b->sigh & 0x80000000))
EXCEPTION(EX_Invalid);
#endif /* PARANOID */
diff = exp0 - expb;
if (diff == 0) {
diff = st0_ptr->sigh - b->sigh; /* Works only if ms bits are
identical */
if (diff == 0) {
diff = st0_ptr->sigl > b->sigl;
if (diff == 0)
diff = -(st0_ptr->sigl < b->sigl);
}
}
if (diff > 0) {
return ((st0_sign == SIGN_POS) ? COMP_A_gt_B : COMP_A_lt_B)
| (((st0_tag == TW_Denormal) || (tagb == TW_Denormal)) ?
COMP_Denormal : 0);
}
if (diff < 0) {
return ((st0_sign == SIGN_POS) ? COMP_A_lt_B : COMP_A_gt_B)
| (((st0_tag == TW_Denormal) || (tagb == TW_Denormal)) ?
COMP_Denormal : 0);
}
return COMP_A_eq_B
| (((st0_tag == TW_Denormal) || (tagb == TW_Denormal)) ?
COMP_Denormal : 0);
}
/* This function requires that st(0) is not empty */
int FPU_compare_st_data(FPU_REG const *loaded_data, u_char loaded_tag)
{
int f = 0, c;
c = compare(loaded_data, loaded_tag);
if (c & COMP_NaN) {
EXCEPTION(EX_Invalid);
f = SW_C3 | SW_C2 | SW_C0;
} else
switch (c & 7) {
case COMP_A_lt_B:
f = SW_C0;
break;
case COMP_A_eq_B:
f = SW_C3;
break;
case COMP_A_gt_B:
f = 0;
break;
case COMP_No_Comp:
f = SW_C3 | SW_C2 | SW_C0;
break;
#ifdef PARANOID
default:
EXCEPTION(EX_INTERNAL | 0x121);
f = SW_C3 | SW_C2 | SW_C0;
break;
#endif /* PARANOID */
}
setcc(f);
if (c & COMP_Denormal) {
return denormal_operand() < 0;
}
return 0;
}
static int compare_st_st(int nr)
{
int f = 0, c;
FPU_REG *st_ptr;
if (!NOT_EMPTY(0) || !NOT_EMPTY(nr)) {
setcc(SW_C3 | SW_C2 | SW_C0);
/* Stack fault */
EXCEPTION(EX_StackUnder);
return !(control_word & CW_Invalid);
}
st_ptr = &st(nr);
c = compare(st_ptr, FPU_gettagi(nr));
if (c & COMP_NaN) {
setcc(SW_C3 | SW_C2 | SW_C0);
EXCEPTION(EX_Invalid);
return !(control_word & CW_Invalid);
} else
switch (c & 7) {
case COMP_A_lt_B:
f = SW_C0;
break;
case COMP_A_eq_B:
f = SW_C3;
break;
case COMP_A_gt_B:
f = 0;
break;
case COMP_No_Comp:
f = SW_C3 | SW_C2 | SW_C0;
break;
#ifdef PARANOID
default:
EXCEPTION(EX_INTERNAL | 0x122);
f = SW_C3 | SW_C2 | SW_C0;
break;
#endif /* PARANOID */
}
setcc(f);
if (c & COMP_Denormal) {
return denormal_operand() < 0;
}
return 0;
}
static int compare_u_st_st(int nr)
{
int f = 0, c;
FPU_REG *st_ptr;
if (!NOT_EMPTY(0) || !NOT_EMPTY(nr)) {
setcc(SW_C3 | SW_C2 | SW_C0);
/* Stack fault */
EXCEPTION(EX_StackUnder);
return !(control_word & CW_Invalid);
}
st_ptr = &st(nr);
c = compare(st_ptr, FPU_gettagi(nr));
if (c & COMP_NaN) {
setcc(SW_C3 | SW_C2 | SW_C0);
if (c & COMP_SNaN) { /* This is the only difference between
un-ordered and ordinary comparisons */
EXCEPTION(EX_Invalid);
return !(control_word & CW_Invalid);
}
return 0;
} else
switch (c & 7) {
case COMP_A_lt_B:
f = SW_C0;
break;
case COMP_A_eq_B:
f = SW_C3;
break;
case COMP_A_gt_B:
f = 0;
break;
case COMP_No_Comp:
f = SW_C3 | SW_C2 | SW_C0;
break;
#ifdef PARANOID
default:
EXCEPTION(EX_INTERNAL | 0x123);
f = SW_C3 | SW_C2 | SW_C0;
break;
#endif /* PARANOID */
}
setcc(f);
if (c & COMP_Denormal) {
return denormal_operand() < 0;
}
return 0;
}
/*---------------------------------------------------------------------------*/
void fcom_st(void)
{
/* fcom st(i) */
compare_st_st(FPU_rm);
}
void fcompst(void)
{
/* fcomp st(i) */
if (!compare_st_st(FPU_rm))
FPU_pop();
}
void fcompp(void)
{
/* fcompp */
if (FPU_rm != 1) {
FPU_illegal();
return;
}
if (!compare_st_st(1))
poppop();
}
void fucom_(void)
{
/* fucom st(i) */
compare_u_st_st(FPU_rm);
}
void fucomp(void)
{
/* fucomp st(i) */
if (!compare_u_st_st(FPU_rm))
FPU_pop();
}
void fucompp(void)
{
/* fucompp */
if (FPU_rm == 1) {
if (!compare_u_st_st(1))
poppop();
} else
FPU_illegal();
}
| gpl-2.0 |
8l/Bcachefs | fs/fscache/main.c | 58 | 2888 | /* General filesystem local caching manager
*
* Copyright (C) 2004-2007 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#define FSCACHE_DEBUG_LEVEL CACHE
#include <linux/module.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/completion.h>
#include <linux/slab.h>
#include "internal.h"
MODULE_DESCRIPTION("FS Cache Manager");
MODULE_AUTHOR("Red Hat, Inc.");
MODULE_LICENSE("GPL");
unsigned fscache_defer_lookup = 1;
module_param_named(defer_lookup, fscache_defer_lookup, uint,
S_IWUSR | S_IRUGO);
MODULE_PARM_DESC(fscache_defer_lookup,
"Defer cookie lookup to background thread");
unsigned fscache_defer_create = 1;
module_param_named(defer_create, fscache_defer_create, uint,
S_IWUSR | S_IRUGO);
MODULE_PARM_DESC(fscache_defer_create,
"Defer cookie creation to background thread");
unsigned fscache_debug;
module_param_named(debug, fscache_debug, uint,
S_IWUSR | S_IRUGO);
MODULE_PARM_DESC(fscache_debug,
"FS-Cache debugging mask");
struct kobject *fscache_root;
/*
* initialise the fs caching module
*/
static int __init fscache_init(void)
{
int ret;
ret = slow_work_register_user();
if (ret < 0)
goto error_slow_work;
ret = fscache_proc_init();
if (ret < 0)
goto error_proc;
fscache_cookie_jar = kmem_cache_create("fscache_cookie_jar",
sizeof(struct fscache_cookie),
0,
0,
fscache_cookie_init_once);
if (!fscache_cookie_jar) {
printk(KERN_NOTICE
"FS-Cache: Failed to allocate a cookie jar\n");
ret = -ENOMEM;
goto error_cookie_jar;
}
fscache_root = kobject_create_and_add("fscache", kernel_kobj);
if (!fscache_root)
goto error_kobj;
printk(KERN_NOTICE "FS-Cache: Loaded\n");
return 0;
error_kobj:
kmem_cache_destroy(fscache_cookie_jar);
error_cookie_jar:
fscache_proc_cleanup();
error_proc:
slow_work_unregister_user();
error_slow_work:
return ret;
}
fs_initcall(fscache_init);
/*
* clean up on module removal
*/
static void __exit fscache_exit(void)
{
_enter("");
kobject_put(fscache_root);
kmem_cache_destroy(fscache_cookie_jar);
fscache_proc_cleanup();
slow_work_unregister_user();
printk(KERN_NOTICE "FS-Cache: Unloaded\n");
}
module_exit(fscache_exit);
/*
* wait_on_bit() sleep function for uninterruptible waiting
*/
int fscache_wait_bit(void *flags)
{
schedule();
return 0;
}
EXPORT_SYMBOL(fscache_wait_bit);
/*
* wait_on_bit() sleep function for interruptible waiting
*/
int fscache_wait_bit_interruptible(void *flags)
{
schedule();
return signal_pending(current);
}
EXPORT_SYMBOL(fscache_wait_bit_interruptible);
| gpl-2.0 |
oldzhu/linux | drivers/gpu/drm/rcar-du/rcar_du_lvdscon.c | 58 | 3408 | /*
* rcar_du_lvdscon.c -- R-Car Display Unit LVDS Connector
*
* Copyright (C) 2013-2014 Renesas Electronics Corporation
*
* Contact: Laurent Pinchart (laurent.pinchart@ideasonboard.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 <drm/drmP.h>
#include <drm/drm_atomic_helper.h>
#include <drm/drm_crtc.h>
#include <drm/drm_crtc_helper.h>
#include <video/display_timing.h>
#include <video/of_display_timing.h>
#include <video/videomode.h>
#include "rcar_du_drv.h"
#include "rcar_du_encoder.h"
#include "rcar_du_kms.h"
#include "rcar_du_lvdscon.h"
struct rcar_du_lvds_connector {
struct rcar_du_connector connector;
struct {
unsigned int width_mm; /* Panel width in mm */
unsigned int height_mm; /* Panel height in mm */
struct videomode mode;
} panel;
};
#define to_rcar_lvds_connector(c) \
container_of(c, struct rcar_du_lvds_connector, connector.connector)
static int rcar_du_lvds_connector_get_modes(struct drm_connector *connector)
{
struct rcar_du_lvds_connector *lvdscon =
to_rcar_lvds_connector(connector);
struct drm_display_mode *mode;
mode = drm_mode_create(connector->dev);
if (mode == NULL)
return 0;
mode->type = DRM_MODE_TYPE_PREFERRED | DRM_MODE_TYPE_DRIVER;
drm_display_mode_from_videomode(&lvdscon->panel.mode, mode);
drm_mode_probed_add(connector, mode);
return 1;
}
static const struct drm_connector_helper_funcs connector_helper_funcs = {
.get_modes = rcar_du_lvds_connector_get_modes,
};
static const struct drm_connector_funcs connector_funcs = {
.dpms = drm_atomic_helper_connector_dpms,
.reset = drm_atomic_helper_connector_reset,
.fill_modes = drm_helper_probe_single_connector_modes,
.destroy = drm_connector_cleanup,
.atomic_duplicate_state = drm_atomic_helper_connector_duplicate_state,
.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
};
int rcar_du_lvds_connector_init(struct rcar_du_device *rcdu,
struct rcar_du_encoder *renc,
const struct device_node *np)
{
struct drm_encoder *encoder = rcar_encoder_to_drm_encoder(renc);
struct rcar_du_lvds_connector *lvdscon;
struct drm_connector *connector;
struct display_timing timing;
int ret;
lvdscon = devm_kzalloc(rcdu->dev, sizeof(*lvdscon), GFP_KERNEL);
if (lvdscon == NULL)
return -ENOMEM;
ret = of_get_display_timing(np, "panel-timing", &timing);
if (ret < 0)
return ret;
videomode_from_timing(&timing, &lvdscon->panel.mode);
of_property_read_u32(np, "width-mm", &lvdscon->panel.width_mm);
of_property_read_u32(np, "height-mm", &lvdscon->panel.height_mm);
connector = &lvdscon->connector.connector;
connector->display_info.width_mm = lvdscon->panel.width_mm;
connector->display_info.height_mm = lvdscon->panel.height_mm;
ret = drm_connector_init(rcdu->ddev, connector, &connector_funcs,
DRM_MODE_CONNECTOR_LVDS);
if (ret < 0)
return ret;
drm_connector_helper_add(connector, &connector_helper_funcs);
connector->dpms = DRM_MODE_DPMS_OFF;
drm_object_property_set_value(&connector->base,
rcdu->ddev->mode_config.dpms_property, DRM_MODE_DPMS_OFF);
ret = drm_mode_connector_attach_encoder(connector, encoder);
if (ret < 0)
return ret;
lvdscon->connector.encoder = renc;
return 0;
}
| gpl-2.0 |
TheTypoMaster/ubuntu-utopic | drivers/staging/cxt1e1/musycc.c | 58 | 50243 | static unsigned int max_intcnt;
static unsigned int max_bh;
/*-----------------------------------------------------------------------------
* musycc.c -
*
* Copyright (C) 2007 One Stop Systems, Inc.
* Copyright (C) 2003-2006 SBE, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* For further information, contact via email: support@onestopsystems.com
* One Stop Systems, Inc. Escondido, California U.S.A.
*-----------------------------------------------------------------------------
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/types.h>
#include "pmcc4_sysdep.h"
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/init.h>
#include "sbecom_inline_linux.h"
#include "libsbew.h"
#include "pmcc4_private.h"
#include "pmcc4.h"
#include "musycc.h"
#define sd_find_chan(ci,ch) c4_find_chan(ch)
/*******************************************************************/
/* global driver variables */
extern ci_t *c4_list;
extern int drvr_state;
extern int cxt1e1_max_mru;
extern int cxt1e1_max_mtu;
extern int max_rxdesc_used;
extern int max_txdesc_used;
extern ci_t *CI; /* dummy pointr to board ZEROE's data - DEBUG
* USAGE */
/*******************************************************************/
/* forward references */
void c4_fifo_free(mpi_t *, int);
void c4_wk_chan_restart(mch_t *);
void musycc_bh_tx_eom(mpi_t *, int);
int musycc_chan_up(ci_t *, int);
status_t __init musycc_init(ci_t *);
void musycc_intr_bh_tasklet(ci_t *);
void musycc_serv_req(mpi_t *, u_int32_t);
void musycc_update_timeslots(mpi_t *);
/*******************************************************************/
static int
musycc_dump_rxbuffer_ring(mch_t *ch, int lockit)
{
struct mdesc *m;
unsigned long flags = 0;
u_int32_t status;
int n;
#ifdef RLD_DUMP_BUFDATA
u_int32_t *dp;
int len = 0;
#endif
if (lockit)
spin_lock_irqsave(&ch->ch_rxlock, flags);
if (ch->rxd_num == 0)
pr_info(" ZERO receive buffers allocated for this channel.");
else {
FLUSH_MEM_READ();
m = &ch->mdr[ch->rxix_irq_srv];
for (n = ch->rxd_num; n; n--) {
status = le32_to_cpu(m->status);
pr_info("%c %08lx[%2d]: sts %08x (%c%c%c%c:%d.) Data [%08x] Next [%08x]\n",
(m == &ch->mdr[ch->rxix_irq_srv]) ? 'F' : ' ',
(unsigned long) m, n,
status,
m->data ? (status & HOST_RX_OWNED ? 'H' : 'M') : '-',
status & POLL_DISABLED ? 'P' : '-',
status & EOBIRQ_ENABLE ? 'b' : '-',
status & EOMIRQ_ENABLE ? 'm' : '-',
status & LENGTH_MASK,
le32_to_cpu(m->data), le32_to_cpu(m->next));
#ifdef RLD_DUMP_BUFDATA
len = status & LENGTH_MASK;
#if 1
if (m->data && (status & HOST_RX_OWNED))
#else
/* always dump regardless of valid RX data */
if (m->data)
#endif
{
dp = (u_int32_t *)OS_phystov((void *)(le32_to_cpu(m->data)));
if (len >= 0x10)
pr_info(" %x[%x]: %08X %08X %08X %08x\n",
(u_int32_t)dp, len,
*dp, *(dp + 1),
*(dp + 2), *(dp + 3));
else if (len >= 0x08)
pr_info(" %x[%x]: %08X %08X\n",
(u_int32_t)dp, len,
*dp, *(dp + 1));
else
pr_info(" %x[%x]: %08X\n",
(u_int32_t)dp,
len, *dp);
}
#endif
m = m->snext;
}
}
pr_info("\n");
if (lockit)
spin_unlock_irqrestore(&ch->ch_rxlock, flags);
return 0;
}
static int
musycc_dump_txbuffer_ring(mch_t *ch, int lockit)
{
struct mdesc *m;
unsigned long flags = 0;
u_int32_t status;
int n;
#ifdef RLD_DUMP_BUFDATA
u_int32_t *dp;
int len = 0;
#endif
if (lockit)
spin_lock_irqsave(&ch->ch_txlock, flags);
if (ch->txd_num == 0)
pr_info(" ZERO transmit buffers allocated for this channel.");
else {
FLUSH_MEM_READ();
m = ch->txd_irq_srv;
for (n = ch->txd_num; n; n--) {
status = le32_to_cpu(m->status);
pr_info("%c%c %08lx[%2d]: sts %08x (%c%c%c%c:%d.) Data [%08x] Next [%08x]\n",
(m == ch->txd_usr_add) ? 'F' : ' ',
(m == ch->txd_irq_srv) ? 'L' : ' ',
(unsigned long) m, n,
status,
m->data ? (status & MUSYCC_TX_OWNED ? 'M' : 'H') : '-',
status & POLL_DISABLED ? 'P' : '-',
status & EOBIRQ_ENABLE ? 'b' : '-',
status & EOMIRQ_ENABLE ? 'm' : '-',
status & LENGTH_MASK,
le32_to_cpu(m->data), le32_to_cpu(m->next));
#ifdef RLD_DUMP_BUFDATA
len = status & LENGTH_MASK;
if (m->data) {
dp = (u_int32_t *)OS_phystov((void *)(le32_to_cpu(m->data)));
if (len >= 0x10)
pr_info(" %x[%x]: %08X %08X %08X %08x\n",
(u_int32_t) dp, len,
*dp, *(dp + 1),
*(dp + 2), *(dp + 3));
else if (len >= 0x08)
pr_info(" %x[%x]: %08X %08X\n",
(u_int32_t)dp, len,
*dp, *(dp + 1));
else
pr_info(" %x[%x]: %08X\n",
(u_int32_t)dp, len, *dp);
}
#endif
m = m->snext;
}
} /* -for- */
pr_info("\n");
if (lockit)
spin_unlock_irqrestore(&ch->ch_txlock, flags);
return 0;
}
/*
* The following supports a backdoor debug facility which can be used to
* display the state of a board's channel.
*/
status_t
musycc_dump_ring(ci_t *ci, unsigned int chan)
{
mch_t *ch;
int bh;
if (chan >= MAX_CHANS_USED)
return SBE_DRVR_FAIL; /* E2BIG */
bh = atomic_read(&ci->bh_pending);
pr_info(">> bh_pend %d [%d] ihead %d itail %d [%d] th_cnt %d bh_cnt %d wdcnt %d note %d\n",
bh, max_bh, ci->iqp_headx, ci->iqp_tailx, max_intcnt,
ci->intlog.drvr_intr_thcount,
ci->intlog.drvr_intr_bhcount,
ci->wdcount, ci->wd_notify);
max_bh = 0; /* reset counter */
max_intcnt = 0; /* reset counter */
ch = sd_find_chan(dummy, chan);
if (!ch) {
pr_info(">> musycc_dump_ring: channel %d not up.\n", chan);
return ENOENT;
}
pr_info(">> CI %p CHANNEL %3d @ %p: state %x status/p %x/%x\n",
ci, chan, ch, ch->state,
ch->status, ch->p.status);
pr_info("--------------------------------\n");
pr_info("TX Buffer Ring - Channel %d, txd_num %d. (bd/ch pend %d %d), TXD required %d, txpkt %lu\n",
chan, ch->txd_num,
(u_int32_t)atomic_read(&ci->tx_pending),
(u_int32_t)atomic_read(&ch->tx_pending),
ch->txd_required, ch->s.tx_packets);
pr_info("++ User 0x%p IRQ_SRV 0x%p USR_ADD 0x%p QStopped %x, start_tx %x tx_full %d txd_free %d mode %x\n",
ch->user, ch->txd_irq_srv, ch->txd_usr_add,
sd_queue_stopped(ch->user),
ch->ch_start_tx, ch->tx_full, ch->txd_free, ch->p.chan_mode);
musycc_dump_txbuffer_ring(ch, 1);
pr_info("RX Buffer Ring - Channel %d, rxd_num %d. IRQ_SRV[%d] 0x%p, start_rx %x rxpkt %lu\n",
chan, ch->rxd_num, ch->rxix_irq_srv,
&ch->mdr[ch->rxix_irq_srv], ch->ch_start_rx, ch->s.rx_packets);
musycc_dump_rxbuffer_ring(ch, 1);
return SBE_DRVR_SUCCESS;
}
status_t
musycc_dump_rings(ci_t *ci, unsigned int start_chan)
{
unsigned int chan;
for (chan = start_chan; chan < (start_chan + 5); chan++)
musycc_dump_ring(ci, chan);
return SBE_DRVR_SUCCESS;
}
/*
* NOTE on musycc_init_mdt(): These MUSYCC writes are only operational after
* a MUSYCC GROUP_INIT command has been issued.
*/
void
musycc_init_mdt(mpi_t *pi)
{
u_int32_t *addr, cfg;
int i;
/*
* This Idle Code insertion takes effect prior to channel's first
* transmitted message. After that, each message contains its own Idle
* Code information which is to be issued after the message is
* transmitted (Ref.MUSYCC 5.2.2.3: MCENBL bit in Group Configuration
* Descriptor).
*/
addr = (u_int32_t *) ((u_long) pi->reg + MUSYCC_MDT_BASE03_ADDR);
cfg = CFG_CH_FLAG_7E << IDLE_CODE;
for (i = 0; i < 32; addr++, i++)
pci_write_32(addr, cfg);
}
/* Set TX thp to the next unprocessed md */
void
musycc_update_tx_thp(mch_t *ch)
{
struct mdesc *md;
unsigned long flags;
spin_lock_irqsave(&ch->ch_txlock, flags);
while (1) {
md = ch->txd_irq_srv;
FLUSH_MEM_READ();
if (!md->data) {
/* No MDs with buffers to process */
spin_unlock_irqrestore(&ch->ch_txlock, flags);
return;
}
if ((le32_to_cpu(md->status)) & MUSYCC_TX_OWNED) {
/* this is the MD to restart TX with */
break;
}
/*
* Otherwise, we have a valid, host-owned message descriptor which
* has been successfully transmitted and whose buffer can be freed,
* so... process this MD, it's owned by the host. (This might give
* as a new, updated txd_irq_srv.)
*/
musycc_bh_tx_eom(ch->up, ch->gchan);
}
md = ch->txd_irq_srv;
ch->up->regram->thp[ch->gchan] = cpu_to_le32(OS_vtophys(md));
FLUSH_MEM_WRITE();
if (ch->tx_full) {
ch->tx_full = 0;
ch->txd_required = 0;
sd_enable_xmit(ch->user); /* re-enable to catch flow controlled
* channel */
}
spin_unlock_irqrestore(&ch->ch_txlock, flags);
#ifdef RLD_TRANS_DEBUG
pr_info("++ musycc_update_tx_thp[%d]: setting thp = %p, sts %x\n",
ch->channum, md, md->status);
#endif
}
/*
* This is the workq task executed by the OS when our queue_work() is
* scheduled and run. It can fire off either RX or TX ACTIVATION depending
* upon the channel's ch_start_tx and ch_start_rx variables. This routine
* is implemented as a work queue so that the call to the service request is
* able to sleep, awaiting an interrupt acknowledgment response (SACK) from
* the hardware.
*/
void
musycc_wq_chan_restart(void *arg) /* channel private structure */
{
mch_t *ch;
mpi_t *pi;
struct mdesc *md;
#if defined(RLD_TRANS_DEBUG) || defined(RLD_RXACT_DEBUG)
static int hereb4 = 7;
#endif
ch = container_of(arg, struct c4_chan_info, ch_work);
pi = ch->up;
#ifdef RLD_TRANS_DEBUG
pr_info("wq_chan_restart[%d]: start_RT[%d/%d] status %x\n",
ch->channum, ch->ch_start_rx, ch->ch_start_tx, ch->status);
#endif
/**********************************/
/** check for RX restart request **/
/**********************************/
if ((ch->ch_start_rx) && (ch->status & RX_ENABLED)) {
ch->ch_start_rx = 0;
#if defined(RLD_TRANS_DEBUG) || defined(RLD_RXACT_DEBUG)
if (hereb4) { /* RLD DEBUG */
hereb4--;
#ifdef RLD_TRANS_DEBUG
md = &ch->mdr[ch->rxix_irq_srv];
pr_info("++ musycc_wq_chan_restart[%d] CHAN RX ACTIVATE: rxix_irq_srv %d, md %p sts %x, rxpkt %lu\n",
ch->channum, ch->rxix_irq_srv, md,
le32_to_cpu(md->status), ch->s.rx_packets);
#elif defined(RLD_RXACT_DEBUG)
md = &ch->mdr[ch->rxix_irq_srv];
pr_info("++ musycc_wq_chan_restart[%d] CHAN RX ACTIVATE: rxix_irq_srv %d, md %p sts %x, rxpkt %lu\n",
ch->channum, ch->rxix_irq_srv,
md, le32_to_cpu(md->status),
ch->s.rx_packets);
musycc_dump_rxbuffer_ring(ch, 1); /* RLD DEBUG */
#endif
}
#endif
musycc_serv_req(pi, SR_CHANNEL_ACTIVATE |
SR_RX_DIRECTION | ch->gchan);
}
/**********************************/
/** check for TX restart request **/
/**********************************/
if ((ch->ch_start_tx) && (ch->status & TX_ENABLED)) {
/* find next unprocessed message, then set TX thp to it */
musycc_update_tx_thp(ch);
md = ch->txd_irq_srv;
if (!md) {
#ifdef RLD_TRANS_DEBUG
pr_info("-- musycc_wq_chan_restart[%d]: WARNING, starting NULL md\n",
ch->channum);
#endif
} else if (md->data && ((le32_to_cpu(md->status)) &
MUSYCC_TX_OWNED)) {
ch->ch_start_tx = 0;
#ifdef RLD_TRANS_DEBUG
pr_info("++ musycc_wq_chan_restart() CHAN TX ACTIVATE: chan %d txd_irq_srv %p = sts %x, txpkt %lu\n",
ch->channum, ch->txd_irq_srv,
ch->txd_irq_srv->status, ch->s.tx_packets);
#endif
musycc_serv_req(pi, SR_CHANNEL_ACTIVATE |
SR_TX_DIRECTION | ch->gchan);
}
#ifdef RLD_RESTART_DEBUG
else {
/* retain request to start until retried and we have data to xmit */
pr_info("-- musycc_wq_chan_restart[%d]: DELAYED due to md %p sts %x data %x, start_tx %x\n",
ch->channum, md,
le32_to_cpu(md->status),
le32_to_cpu(md->data), ch->ch_start_tx);
musycc_dump_txbuffer_ring(ch, 0);
}
#endif
}
}
/*
* Channel restart either fires of a workqueue request (2.6) or lodges a
* watchdog activation sequence (2.4).
*/
void
musycc_chan_restart(mch_t *ch)
{
#ifdef RLD_RESTART_DEBUG
pr_info("++ musycc_chan_restart[%d]: txd_irq_srv @ %p = sts %x\n",
ch->channum, ch->txd_irq_srv, ch->txd_irq_srv->status);
#endif
/* 2.6 - find next unprocessed message, then set TX thp to it */
#ifdef RLD_RESTART_DEBUG
pr_info(">> musycc_chan_restart: scheduling Chan %x workQ @ %p\n",
ch->channum, &ch->ch_work);
#endif
c4_wk_chan_restart(ch); /* work queue mechanism fires off: Ref:
* musycc_wq_chan_restart () */
}
void
rld_put_led(mpi_t *pi, u_int32_t ledval)
{
static u_int32_t led;
if (ledval == 0)
led = 0;
else
led |= ledval;
/* RLD DEBUG TRANHANG */
pci_write_32((u_int32_t *) &pi->up->cpldbase->leds, led);
}
#define MUSYCC_SR_RETRY_CNT 9
void
musycc_serv_req(mpi_t *pi, u_int32_t req)
{
volatile u_int32_t r;
int rcnt;
/*
* PORT NOTE: Semaphore protect service loop guarantees only a single
* operation at a time. Per MUSYCC Manual - "Issuing service requests to
* the same channel group without first receiving ACK from each request
* may cause the host to lose track of which service request has been
* acknowledged."
*/
SD_SEM_TAKE(&pi->sr_sem_busy, "serv"); /* only 1 thru here, per
* group */
if (pi->sr_last == req) {
#ifdef RLD_TRANS_DEBUG
pr_info(">> same SR, Port %d Req %x\n", pi->portnum, req);
#endif
/*
* The most likely repeated request is the channel activation command
* which follows the occurrence of a Transparent mode TX ONR or a
* BUFF error. If the previous command was a CHANNEL ACTIVATE,
* precede it with a NOOP command in order maintain coherent control
* of this current (re)ACTIVATE.
*/
r = (pi->sr_last & ~SR_GCHANNEL_MASK);
if ((r == (SR_CHANNEL_ACTIVATE | SR_TX_DIRECTION)) ||
(r == (SR_CHANNEL_ACTIVATE | SR_RX_DIRECTION))) {
#ifdef RLD_TRANS_DEBUG
pr_info(">> same CHAN ACT SR, Port %d Req %x => issue SR_NOOP CMD\n", pi->portnum, req);
#endif
/* allow this next request */
SD_SEM_GIVE(&pi->sr_sem_busy);
musycc_serv_req(pi, SR_NOOP);
/* relock & continue w/ original req */
SD_SEM_TAKE(&pi->sr_sem_busy, "serv");
} else if (req == SR_NOOP) {
/* no need to issue back-to-back
* SR_NOOP commands at this time
*/
#ifdef RLD_TRANS_DEBUG
pr_info(">> same Port SR_NOOP skipped, Port %d\n",
pi->portnum);
#endif
/* allow this next request */
SD_SEM_GIVE(&pi->sr_sem_busy);
return;
}
}
rcnt = 0;
pi->sr_last = req;
rewrite:
pci_write_32((u_int32_t *) &pi->reg->srd, req);
FLUSH_MEM_WRITE();
/*
* Per MUSYCC Manual, Section 6.1,2 - "When writing an SCR service
* request, the host must ensure at least one PCI bus clock cycle has
* elapsed before writing another service request. To meet this minimum
* elapsed service request write timing interval, it is recommended that
* the host follow any SCR write with another operation which reads from
* the same address."
*/
/* adhere to write timing imposition */
r = pci_read_32((u_int32_t *) &pi->reg->srd);
if ((r != req) && (req != SR_CHIP_RESET) &&
(++rcnt <= MUSYCC_SR_RETRY_CNT)) {
if (cxt1e1_log_level >= LOG_MONITOR)
pr_info("%s: %d - reissue srv req/last %x/%x (hdw reads %x), Chan %d.\n",
pi->up->devname, rcnt, req, pi->sr_last, r,
(pi->portnum * MUSYCC_NCHANS) + (req & 0x1f));
/* this delay helps reduce reissue counts
* (reason not yet researched)
*/
OS_uwait_dummy();
goto rewrite;
}
if (rcnt > MUSYCC_SR_RETRY_CNT) {
pr_warning("%s: failed service request (#%d)= %x, group %d.\n",
pi->up->devname, MUSYCC_SR_RETRY_CNT,
req, pi->portnum);
SD_SEM_GIVE(&pi->sr_sem_busy); /* allow any next request */
return;
}
if (req == SR_CHIP_RESET) {
/*
* PORT NOTE: the CHIP_RESET command is NOT ack'd by the MUSYCC, thus
* the upcoming delay is used. Though the MUSYCC documentation
* suggests a read-after-write would supply the required delay, it's
* unclear what CPU/BUS clock speeds might have been assumed when
* suggesting this 'lack of ACK' workaround. Thus the use of uwait.
*/
OS_uwait(100000, "icard"); /* 100ms */
} else {
FLUSH_MEM_READ();
/* sleep until SACK interrupt occurs */
SD_SEM_TAKE(&pi->sr_sem_wait, "sakack");
}
SD_SEM_GIVE(&pi->sr_sem_busy); /* allow any next request */
}
#ifdef SBE_PMCC4_ENABLE
void
musycc_update_timeslots(mpi_t *pi)
{
int i, ch;
char e1mode = IS_FRAME_ANY_E1(pi->p.port_mode);
for (i = 0; i < 32; i++) {
int usedby = 0, last = 0, ts, j, bits[8];
u_int8_t lastval = 0;
if (((i == 0) && e1mode) || /* disable if E1 mode */
((i == 16) && ((pi->p.port_mode == CFG_FRAME_E1CRC_CAS) ||
(pi->p.port_mode == CFG_FRAME_E1CRC_CAS_AMI))) ||
((i > 23) && (!e1mode))) /* disable if T1 mode */
/* make tslot unavailable for this mode */
pi->tsm[i] = 0xff;
else
/* make tslot available for assignment */
pi->tsm[i] = 0x00;
for (j = 0; j < 8; j++)
bits[j] = -1;
for (ch = 0; ch < MUSYCC_NCHANS; ch++) {
if ((pi->chan[ch]->state == UP) &&
(pi->chan[ch]->p.bitmask[i])) {
usedby++;
last = ch;
lastval = pi->chan[ch]->p.bitmask[i];
for (j = 0; j < 8; j++)
if (lastval & (1 << j))
bits[j] = ch;
pi->tsm[i] |= lastval;
}
}
if (!usedby)
ts = 0;
else if ((usedby == 1) && (lastval == 0xff))
ts = (4 << 5) | last;
else if ((usedby == 1) && (lastval == 0x7f))
ts = (5 << 5) | last;
else {
int idx;
if (bits[0] < 0)
ts = (6 << 5) | (idx = last);
else
ts = (7 << 5) | (idx = bits[0]);
for (j = 1; j < 8; j++) {
pi->regram->rscm[idx * 8 + j] =
(bits[j] < 0) ? 0 : (0x80 | bits[j]);
pi->regram->tscm[idx * 8 + j] =
(bits[j] < 0) ? 0 : (0x80 | bits[j]);
}
}
pi->regram->rtsm[i] = ts;
pi->regram->ttsm[i] = ts;
}
FLUSH_MEM_WRITE();
musycc_serv_req(pi, SR_TIMESLOT_MAP | SR_RX_DIRECTION);
musycc_serv_req(pi, SR_TIMESLOT_MAP | SR_TX_DIRECTION);
musycc_serv_req(pi, SR_SUBCHANNEL_MAP | SR_RX_DIRECTION);
musycc_serv_req(pi, SR_SUBCHANNEL_MAP | SR_TX_DIRECTION);
}
#endif
#ifdef SBE_WAN256T3_ENABLE
void
musycc_update_timeslots(mpi_t *pi)
{
mch_t *ch;
u_int8_t ts, hmask, tsen;
int gchan;
int i;
#ifdef SBE_PMCC4_ENABLE
hmask = (0x1f << pi->up->p.hypersize) & 0x1f;
#endif
#ifdef SBE_WAN256T3_ENABLE
hmask = (0x1f << hyperdummy) & 0x1f;
#endif
for (i = 0; i < 128; i++) {
gchan = ((pi->portnum * MUSYCC_NCHANS) +
(i & hmask)) % MUSYCC_NCHANS;
ch = pi->chan[gchan];
if (ch->p.mode_56k)
tsen = MODE_56KBPS;
else
tsen = MODE_64KBPS; /* also the default */
ts = ((pi->portnum % 4) == (i / 32)) ? (tsen << 5) | (i & hmask) : 0;
pi->regram->rtsm[i] = ts;
pi->regram->ttsm[i] = ts;
}
FLUSH_MEM_WRITE();
musycc_serv_req(pi, SR_TIMESLOT_MAP | SR_RX_DIRECTION);
musycc_serv_req(pi, SR_TIMESLOT_MAP | SR_TX_DIRECTION);
}
#endif
/*
* This routine converts a generic library channel configuration parameter
* into a hardware specific register value (IE. MUSYCC CCD Register).
*/
u_int32_t
musycc_chan_proto(int proto)
{
int reg;
switch (proto) {
case CFG_CH_PROTO_TRANS: /* 0 */
reg = MUSYCC_CCD_TRANS;
break;
case CFG_CH_PROTO_SS7: /* 1 */
reg = MUSYCC_CCD_SS7;
break;
default:
case CFG_CH_PROTO_ISLP_MODE: /* 4 */
case CFG_CH_PROTO_HDLC_FCS16: /* 2 */
reg = MUSYCC_CCD_HDLC_FCS16;
break;
case CFG_CH_PROTO_HDLC_FCS32: /* 3 */
reg = MUSYCC_CCD_HDLC_FCS32;
break;
}
return reg;
}
#ifdef SBE_WAN256T3_ENABLE
static void __init
musycc_init_port(mpi_t *pi)
{
pci_write_32((u_int32_t *) &pi->reg->gbp, OS_vtophys(pi->regram));
pi->regram->grcd =
__constant_cpu_to_le32(MUSYCC_GRCD_RX_ENABLE |
MUSYCC_GRCD_TX_ENABLE |
MUSYCC_GRCD_SF_ALIGN |
MUSYCC_GRCD_SUBCHAN_DISABLE |
MUSYCC_GRCD_OOFMP_DISABLE |
MUSYCC_GRCD_COFAIRQ_DISABLE |
MUSYCC_GRCD_MC_ENABLE |
(MUSYCC_GRCD_POLLTH_32 << MUSYCC_GRCD_POLLTH_SHIFT));
pi->regram->pcd =
__constant_cpu_to_le32(MUSYCC_PCD_E1X4_MODE |
MUSYCC_PCD_TXDATA_RISING |
MUSYCC_PCD_TX_DRIVEN);
/* Message length descriptor */
pi->regram->mld = __constant_cpu_to_le32(cxt1e1_max_mru | (cxt1e1_max_mru << 16));
FLUSH_MEM_WRITE();
musycc_serv_req(pi, SR_GROUP_INIT | SR_RX_DIRECTION);
musycc_serv_req(pi, SR_GROUP_INIT | SR_TX_DIRECTION);
musycc_init_mdt(pi);
musycc_update_timeslots(pi);
}
#endif
status_t __init
musycc_init(ci_t *ci)
{
char *regaddr; /* temp for address boundary calculations */
int i, gchan;
OS_sem_init(&ci->sem_wdbusy, SEM_AVAILABLE); /* watchdog exclusion */
/*
* Per MUSYCC manual, Section 6.3.4 - "The host must allocate a dword
* aligned memory segment for interrupt queue pointers."
*/
#define INT_QUEUE_BOUNDARY 4
regaddr = kzalloc((INT_QUEUE_SIZE + 1) * sizeof(u_int32_t),
GFP_KERNEL | GFP_DMA);
if (!regaddr)
return -ENOMEM;
ci->iqd_p_saved = regaddr; /* save orig value for free's usage */
/* this calculates closest boundary */
ci->iqd_p = (u_int32_t *) ((unsigned long)(regaddr + INT_QUEUE_BOUNDARY - 1) &
(~(INT_QUEUE_BOUNDARY - 1)));
for (i = 0; i < INT_QUEUE_SIZE; i++)
ci->iqd_p[i] = __constant_cpu_to_le32(INT_EMPTY_ENTRY);
for (i = 0; i < ci->max_port; i++) {
mpi_t *pi = &ci->port[i];
/*
* Per MUSYCC manual, Section 6.3.2 - "The host must allocate a 2KB
* bound memory segment for Channel Group 0."
*/
#define GROUP_BOUNDARY 0x800
regaddr = kzalloc(sizeof(struct musycc_groupr) + GROUP_BOUNDARY,
GFP_KERNEL | GFP_DMA);
if (!regaddr) {
for (gchan = 0; gchan < i; gchan++) {
pi = &ci->port[gchan];
kfree(pi->reg);
pi->reg = NULL;
}
return -ENOMEM;
}
pi->regram_saved = regaddr; /* save orig value for free's usage */
/* this calculates closest boundary */
pi->regram = (struct musycc_groupr *) ((unsigned long)(regaddr + GROUP_BOUNDARY - 1) &
(~(GROUP_BOUNDARY - 1)));
}
/* any board centric MUSYCC commands will use group ZERO as its "home" */
ci->regram = ci->port[0].regram;
musycc_serv_req(&ci->port[0], SR_CHIP_RESET);
pci_write_32((u_int32_t *) &ci->reg->gbp, OS_vtophys(ci->regram));
pci_flush_write(ci);
#ifdef CONFIG_SBE_PMCC4_NCOMM
ci->regram->__glcd = __constant_cpu_to_le32(GCD_MAGIC);
#else
/* standard driver POLLS for INTB via CPLD register */
ci->regram->__glcd = __constant_cpu_to_le32(GCD_MAGIC |
MUSYCC_GCD_INTB_DISABLE);
#endif
ci->regram->__iqp = cpu_to_le32(OS_vtophys(&ci->iqd_p[0]));
ci->regram->__iql = __constant_cpu_to_le32(INT_QUEUE_SIZE - 1);
pci_write_32((u_int32_t *) &ci->reg->dacbp, 0);
FLUSH_MEM_WRITE();
ci->state = C_RUNNING; /* mark as full interrupt processing
* available */
musycc_serv_req(&ci->port[0], SR_GLOBAL_INIT); /* FIRST INTERRUPT ! */
/* sanity check settable parameters */
if (cxt1e1_max_mru > 0xffe) {
pr_warning("Maximum allowed MRU exceeded, resetting %d to %d.\n",
cxt1e1_max_mru, 0xffe);
cxt1e1_max_mru = 0xffe;
}
if (cxt1e1_max_mtu > 0xffe) {
pr_warning("Maximum allowed MTU exceeded, resetting %d to %d.\n",
cxt1e1_max_mtu, 0xffe);
cxt1e1_max_mtu = 0xffe;
}
#ifdef SBE_WAN256T3_ENABLE
for (i = 0; i < MUSYCC_NPORTS; i++)
musycc_init_port(&ci->port[i]);
#endif
return SBE_DRVR_SUCCESS; /* no error */
}
void
musycc_bh_tx_eom(mpi_t *pi, int gchan)
{
mch_t *ch;
struct mdesc *md;
volatile u_int32_t status;
ch = pi->chan[gchan];
if (!ch || ch->state != UP) {
if (cxt1e1_log_level >= LOG_ERROR)
pr_info("%s: intr: xmit EOM on uninitialized channel %d\n",
pi->up->devname, gchan);
}
if (!ch || !ch->mdt)
return; /* note: mdt==0 implies a malloc()
* failure w/in chan_up() routine */
do {
FLUSH_MEM_READ();
md = ch->txd_irq_srv;
status = le32_to_cpu(md->status);
/*
* Note: Per MUSYCC Ref 6.4.9, the host does not poll a host-owned
* Transmit Buffer Descriptor during Transparent Mode.
*/
if (status & MUSYCC_TX_OWNED) {
int readCount, loopCount;
/***********************************************************/
/* HW Bug Fix */
/* ---------- */
/* Under certain PCI Bus loading conditions, the data */
/* associated with an update of Shared Memory is delayed */
/* relative to its PCI Interrupt. This is caught when */
/* the host determines it does not yet OWN the descriptor. */
/***********************************************************/
readCount = 0;
while (status & MUSYCC_TX_OWNED) {
for (loopCount = 0; loopCount < 0x30; loopCount++)
/* use call to avoid optimization
* removal of dummy delay */
OS_uwait_dummy();
FLUSH_MEM_READ();
status = le32_to_cpu(md->status);
if (readCount++ > 40)
break; /* don't wait any longer */
}
if (status & MUSYCC_TX_OWNED) {
if (cxt1e1_log_level >= LOG_MONITOR) {
pr_info("%s: Port %d Chan %2d - unexpected TX msg ownership intr (md %p sts %x)\n",
pi->up->devname, pi->portnum,
ch->channum, md, status);
pr_info("++ User 0x%p IRQ_SRV 0x%p USR_ADD 0x%p QStopped %x, start_tx %x tx_full %d txd_free %d mode %x\n",
ch->user, ch->txd_irq_srv,
ch->txd_usr_add,
sd_queue_stopped(ch->user),
ch->ch_start_tx, ch->tx_full,
ch->txd_free, ch->p.chan_mode);
musycc_dump_txbuffer_ring(ch, 0);
}
break; /* Not our mdesc, done */
} else {
if (cxt1e1_log_level >= LOG_MONITOR)
pr_info("%s: Port %d Chan %2d - recovered TX msg ownership [%d] (md %p sts %x)\n",
pi->up->devname, pi->portnum,
ch->channum, readCount,
md, status);
}
}
ch->txd_irq_srv = md->snext;
md->data = 0;
if (md->mem_token) {
/* upcount channel */
atomic_sub(OS_mem_token_tlen(md->mem_token),
&ch->tx_pending);
/* upcount card */
atomic_sub(OS_mem_token_tlen(md->mem_token),
&pi->up->tx_pending);
#ifdef SBE_WAN256T3_ENABLE
if (!atomic_read(&pi->up->tx_pending))
wan256t3_led(pi->up, LED_TX, 0);
#endif
OS_mem_token_free_irq(md->mem_token);
md->mem_token = NULL;
}
md->status = 0;
#ifdef RLD_TXFULL_DEBUG
if (cxt1e1_log_level >= LOG_MONITOR2)
pr_info("~~ tx_eom: tx_full %x txd_free %d -> %d\n",
ch->tx_full, ch->txd_free, ch->txd_free + 1);
#endif
++ch->txd_free;
FLUSH_MEM_WRITE();
if ((ch->p.chan_mode != CFG_CH_PROTO_TRANS) &&
(status & EOBIRQ_ENABLE)) {
if (cxt1e1_log_level >= LOG_MONITOR)
pr_info("%s: Mode (%x) incorrect EOB status (%x)\n",
pi->up->devname, ch->p.chan_mode,
status);
if ((status & EOMIRQ_ENABLE) == 0)
break;
}
} while ((ch->p.chan_mode != CFG_CH_PROTO_TRANS) &&
((status & EOMIRQ_ENABLE) == 0));
/*
* NOTE: (The above 'while' is coupled w/ previous 'do', way above.) Each
* Transparent data buffer has the EOB bit, and NOT the EOM bit, set and
* will furthermore have a separate IQD associated with each messages
* buffer.
*/
FLUSH_MEM_READ();
/*
* Smooth flow control hysterisis by maintaining task stoppage until half
* the available write buffers are available.
*/
if (ch->tx_full && (ch->txd_free >= (ch->txd_num / 2))) {
/*
* Then, only releave task stoppage if we actually have enough
* buffers to service the last requested packet. It may require MORE
* than half the available!
*/
if (ch->txd_free >= ch->txd_required) {
#ifdef RLD_TXFULL_DEBUG
if (cxt1e1_log_level >= LOG_MONITOR2)
pr_info("tx_eom[%d]: enable xmit tx_full no more, txd_free %d txd_num/2 %d\n",
ch->channum,
ch->txd_free, ch->txd_num / 2);
#endif
ch->tx_full = 0;
ch->txd_required = 0;
/* re-enable to catch flow controlled channel */
sd_enable_xmit(ch->user);
}
}
#ifdef RLD_TXFULL_DEBUG
else if (ch->tx_full) {
if (cxt1e1_log_level >= LOG_MONITOR2)
pr_info("tx_eom[%d]: bypass TX enable though room available? (txd_free %d txd_num/2 %d)\n",
ch->channum,
ch->txd_free, ch->txd_num / 2);
}
#endif
FLUSH_MEM_WRITE();
}
static void
musycc_bh_rx_eom(mpi_t *pi, int gchan)
{
mch_t *ch;
void *m, *m2;
struct mdesc *md;
volatile u_int32_t status;
u_int32_t error;
ch = pi->chan[gchan];
if (!ch || ch->state != UP) {
if (cxt1e1_log_level > LOG_ERROR)
pr_info("%s: intr: receive EOM on uninitialized channel %d\n",
pi->up->devname, gchan);
return;
}
if (!ch->mdr)
return; /* can this happen ? */
for (;;) {
FLUSH_MEM_READ();
md = &ch->mdr[ch->rxix_irq_srv];
status = le32_to_cpu(md->status);
if (!(status & HOST_RX_OWNED))
break; /* Not our mdesc, done */
m = md->mem_token;
error = (status >> 16) & 0xf;
if (error == 0) {
{
m2 = OS_mem_token_alloc(cxt1e1_max_mru);
if (m2) {
/* substitute the mbuf+cluster */
md->mem_token = m2;
md->data = cpu_to_le32(OS_vtophys(
OS_mem_token_data(m2)));
/* pass the received mbuf upward */
sd_recv_consume(m, status & LENGTH_MASK,
ch->user);
ch->s.rx_packets++;
ch->s.rx_bytes += status & LENGTH_MASK;
} else
ch->s.rx_dropped++;
}
} else if (error == ERR_FCS)
ch->s.rx_crc_errors++;
else if (error == ERR_ALIGN)
ch->s.rx_missed_errors++;
else if (error == ERR_ABT)
ch->s.rx_missed_errors++;
else if (error == ERR_LNG)
ch->s.rx_length_errors++;
else if (error == ERR_SHT)
ch->s.rx_length_errors++;
FLUSH_MEM_WRITE();
status = cxt1e1_max_mru;
if (ch->p.chan_mode == CFG_CH_PROTO_TRANS)
status |= EOBIRQ_ENABLE;
md->status = cpu_to_le32(status);
/* Check next mdesc in the ring */
if (++ch->rxix_irq_srv >= ch->rxd_num)
ch->rxix_irq_srv = 0;
FLUSH_MEM_WRITE();
}
}
irqreturn_t
musycc_intr_th_handler(void *devp)
{
ci_t *ci = (ci_t *) devp;
volatile u_int32_t status, currInt = 0;
u_int32_t nextInt, intCnt;
/*
* Hardware not available, potential interrupt hang. But since interrupt
* might be shared, just return.
*/
if (ci->state == C_INIT)
return IRQ_NONE;
/*
* Marked as hardware available. Don't service interrupts, just clear the
* event.
*/
if (ci->state == C_IDLE) {
status = pci_read_32((u_int32_t *) &ci->reg->isd);
/* clear the interrupt but process nothing else */
pci_write_32((u_int32_t *) &ci->reg->isd, status);
return IRQ_HANDLED;
}
FLUSH_PCI_READ();
FLUSH_MEM_READ();
status = pci_read_32((u_int32_t *) &ci->reg->isd);
nextInt = INTRPTS_NEXTINT(status);
intCnt = INTRPTS_INTCNT(status);
ci->intlog.drvr_intr_thcount++;
/*********************************************************/
/* HW Bug Fix */
/* ---------- */
/* Under certain PCI Bus loading conditions, the */
/* MUSYCC looses the data associated with an update */
/* of its ISD and erroneously returns the immediately */
/* preceding 'nextInt' value. However, the 'intCnt' */
/* value appears to be correct. By not starting service */
/* where the 'missing' 'nextInt' SHOULD point causes */
/* the IQD not to be serviced - the 'not serviced' */
/* entries then remain and continue to increase as more */
/* incorrect ISD's are encountered. */
/*********************************************************/
if (nextInt != INTRPTS_NEXTINT(ci->intlog.this_status_new)) {
if (cxt1e1_log_level >= LOG_MONITOR) {
pr_info("%s: note - updated ISD from %08x to %08x\n",
ci->devname, status,
(status & (~INTRPTS_NEXTINT_M)) |
ci->intlog.this_status_new);
}
/*
* Replace bogus status with software corrected value.
*
* It's not known whether, during this problem occurrence, if the
* INTFULL bit is correctly reported or not.
*/
status = (status & (~INTRPTS_NEXTINT_M)) |
(ci->intlog.this_status_new);
nextInt = INTRPTS_NEXTINT(status);
}
/**********************************************/
/* Cn847x Bug Fix */
/* -------------- */
/* Fix for inability to write back same index */
/* as read for a full interrupt queue. */
/**********************************************/
if (intCnt == INT_QUEUE_SIZE)
currInt = ((intCnt - 1) + nextInt) & (INT_QUEUE_SIZE - 1);
else
/************************************************/
/* Interrupt Write Location Issues */
/* ------------------------------- */
/* When the interrupt status descriptor is */
/* written, the interrupt line is de-asserted */
/* by the Cn847x. In the case of MIPS */
/* microprocessors, this must occur at the */
/* beginning of the interrupt handler so that */
/* the interrupt handle is not re-entered due */
/* to interrupt dis-assertion latency. */
/* In the case of all other processors, this */
/* action should occur at the end of the */
/* interrupt handler to avoid overwriting the */
/* interrupt queue. */
/************************************************/
if (intCnt)
currInt = (intCnt + nextInt) & (INT_QUEUE_SIZE - 1);
else {
/*
* NOTE: Servicing an interrupt whose ISD contains a count of ZERO
* can be indicative of a Shared Interrupt chain. Our driver can be
* called from the system's interrupt handler as a matter of the OS
* walking the chain. As the chain is walked, the interrupt will
* eventually be serviced by the correct driver/handler.
*/
return IRQ_NONE;
}
ci->iqp_tailx = currInt;
currInt <<= INTRPTS_NEXTINT_S;
ci->intlog.last_status_new = ci->intlog.this_status_new;
ci->intlog.this_status_new = currInt;
if ((cxt1e1_log_level >= LOG_WARN) && (status & INTRPTS_INTFULL_M))
pr_info("%s: Interrupt queue full condition occurred\n",
ci->devname);
if (cxt1e1_log_level >= LOG_DEBUG)
pr_info("%s: interrupts pending, isd @ 0x%p: %x curr %d cnt %d NEXT %d\n",
ci->devname, &ci->reg->isd,
status, nextInt, intCnt,
(intCnt + nextInt) & (INT_QUEUE_SIZE - 1));
FLUSH_MEM_WRITE();
#if defined(SBE_ISR_TASKLET)
pci_write_32((u_int32_t *) &ci->reg->isd, currInt);
atomic_inc(&ci->bh_pending);
tasklet_schedule(&ci->ci_musycc_isr_tasklet);
#elif defined(SBE_ISR_IMMEDIATE)
pci_write_32((u_int32_t *) &ci->reg->isd, currInt);
atomic_inc(&ci->bh_pending);
queue_task(&ci->ci_musycc_isr_tq, &tq_immediate);
mark_bh(IMMEDIATE_BH);
#elif defined(SBE_ISR_INLINE)
(void) musycc_intr_bh_tasklet(ci);
pci_write_32((u_int32_t *) &ci->reg->isd, currInt);
#endif
return IRQ_HANDLED;
}
#if defined(SBE_ISR_IMMEDIATE)
unsigned long
#else
void
#endif
musycc_intr_bh_tasklet(ci_t *ci)
{
mpi_t *pi;
mch_t *ch;
unsigned int intCnt;
volatile u_int32_t currInt = 0;
volatile unsigned int headx, tailx;
int readCount, loopCount;
int group, gchan, event, err, tx;
u_int32_t badInt = INT_EMPTY_ENTRY;
u_int32_t badInt2 = INT_EMPTY_ENTRY2;
/*
* Hardware not available, potential interrupt hang. But since interrupt
* might be shared, just return.
*/
if ((drvr_state != SBE_DRVR_AVAILABLE) || (ci->state == C_INIT)) {
#if defined(SBE_ISR_IMMEDIATE)
return 0L;
#else
return;
#endif
}
#if defined(SBE_ISR_TASKLET) || defined(SBE_ISR_IMMEDIATE)
if (drvr_state != SBE_DRVR_AVAILABLE) {
#if defined(SBE_ISR_TASKLET)
return;
#elif defined(SBE_ISR_IMMEDIATE)
return 0L;
#endif
}
#elif defined(SBE_ISR_INLINE)
/* no semaphore taken, no double checks */
#endif
ci->intlog.drvr_intr_bhcount++;
FLUSH_MEM_READ();
{
unsigned int bh = atomic_read(&ci->bh_pending);
max_bh = max(bh, max_bh);
}
atomic_set(&ci->bh_pending, 0);/* if here, no longer pending */
while ((headx = ci->iqp_headx) != (tailx = ci->iqp_tailx)) {
intCnt = (tailx >= headx) ? (tailx - headx) : (tailx - headx + INT_QUEUE_SIZE);
currInt = le32_to_cpu(ci->iqd_p[headx]);
max_intcnt = max(intCnt, max_intcnt); /* RLD DEBUG */
/**************************************************/
/* HW Bug Fix */
/* ---------- */
/* The following code checks for the condition */
/* of interrupt assertion before interrupt */
/* queue update. This is a problem on several */
/* PCI-Local bridge chips found on some products. */
/**************************************************/
readCount = 0;
if ((currInt == badInt) || (currInt == badInt2))
ci->intlog.drvr_int_failure++;
while ((currInt == badInt) || (currInt == badInt2)) {
for (loopCount = 0; loopCount < 0x30; loopCount++)
/* use call to avoid optimization
* removal of dummy delay
*/
OS_uwait_dummy();
FLUSH_MEM_READ();
currInt = le32_to_cpu(ci->iqd_p[headx]);
if (readCount++ > 20)
break;
}
/* catch failure of Bug Fix checking */
if ((currInt == badInt) || (currInt == badInt2)) {
if (cxt1e1_log_level >= LOG_WARN)
pr_info("%s: Illegal Interrupt Detected @ 0x%p, mod %d.)\n",
ci->devname, &ci->iqd_p[headx], headx);
/*
* If the descriptor has not recovered, then leaving the EMPTY
* entry set will not signal to the MUSYCC that this descriptor
* has been serviced. The Interrupt Queue can then start losing
* available descriptors and MUSYCC eventually encounters and
* reports the INTFULL condition. Per manual, changing any bit
* marks descriptor as available, thus the use of different
* EMPTY_ENTRY values.
*/
if (currInt == badInt)
ci->iqd_p[headx] = __constant_cpu_to_le32(INT_EMPTY_ENTRY2);
else
ci->iqd_p[headx] = __constant_cpu_to_le32(INT_EMPTY_ENTRY);
/* insure wrapness */
ci->iqp_headx = (headx + 1) & (INT_QUEUE_SIZE - 1);
FLUSH_MEM_WRITE();
FLUSH_MEM_READ();
continue;
}
group = INTRPT_GRP(currInt);
gchan = INTRPT_CH(currInt);
event = INTRPT_EVENT(currInt);
err = INTRPT_ERROR(currInt);
tx = currInt & INTRPT_DIR_M;
ci->iqd_p[headx] = __constant_cpu_to_le32(INT_EMPTY_ENTRY);
FLUSH_MEM_WRITE();
if (cxt1e1_log_level >= LOG_DEBUG) {
if (err != 0)
pr_info(" %08x -> err: %2d,", currInt, err);
pr_info("+ interrupt event: %d, grp: %d, chan: %2d, side: %cX\n",
event, group, gchan, tx ? 'T' : 'R');
}
/* notice that here we assume 1-1 group - port mapping */
pi = &ci->port[group];
ch = pi->chan[gchan];
switch (event) {
case EVE_SACK: /* Service Request Acknowledge */
if (cxt1e1_log_level >= LOG_DEBUG) {
volatile u_int32_t r;
r = pci_read_32((u_int32_t *) &pi->reg->srd);
pr_info("- SACK cmd: %08x (hdw= %08x)\n",
pi->sr_last, r);
}
/* wake up waiting process */
SD_SEM_GIVE(&pi->sr_sem_wait);
break;
case EVE_CHABT: /* Change To Abort Code (0x7e -> 0xff) */
case EVE_CHIC: /* Change To Idle Code (0xff -> 0x7e) */
break;
case EVE_EOM: /* End Of Message */
case EVE_EOB: /* End Of Buffer (Transparent mode) */
if (tx)
musycc_bh_tx_eom(pi, gchan);
else
musycc_bh_rx_eom(pi, gchan);
/*
* MUSYCC Interrupt Descriptor section states that EOB and EOM
* can be combined with the NONE error (as well as others). So
* drop thru to catch this...
*/
case EVE_NONE:
if (err == ERR_SHT)
ch->s.rx_length_errors++;
break;
default:
if (cxt1e1_log_level >= LOG_WARN)
pr_info("%s: unexpected interrupt event: %d, iqd[%d]: %08x, port: %d\n", ci->devname,
event, headx, currInt, group);
break;
} /* switch on event */
/*
* Per MUSYCC Manual, Section 6.4.8.3 [Transmit Errors], TX errors
* are service-affecting and require action to resume normal
* bit-level processing.
*/
switch (err) {
case ERR_ONR:
/*
* Per MUSYCC manual, Section 6.4.8.3 [Transmit Errors], this
* error requires Transmit channel reactivation.
*
* Per MUSYCC manual, Section 6.4.8.4 [Receive Errors], this error
* requires Receive channel reactivation.
*/
if (tx) {
/*
* TX ONR Error only occurs when channel is configured for
* Transparent Mode. However, this code will catch and
* re-activate on ANY TX ONR error.
*/
/*
* Set flag to re-enable on any next transmit attempt.
*/
ch->ch_start_tx = CH_START_TX_ONR;
#ifdef RLD_TRANS_DEBUG
if (1 || cxt1e1_log_level >= LOG_MONITOR)
#else
if (cxt1e1_log_level >= LOG_MONITOR)
#endif
{
pr_info("%s: TX buffer underflow [ONR] on channel %d, mode %x QStopped %x free %d\n",
ci->devname, ch->channum,
ch->p.chan_mode,
sd_queue_stopped(ch->user),
ch->txd_free);
#ifdef RLD_DEBUG
/* problem = ONR on HDLC mode */
if (ch->p.chan_mode == 2) {
pr_info("++ Failed Last %x Next %x QStopped %x, start_tx %x tx_full %d txd_free %d mode %x\n",
(u_int32_t)ch->txd_irq_srv,
(u_int32_t)ch->txd_usr_add,
sd_queue_stopped(ch->user),
ch->ch_start_tx,
ch->tx_full,
ch->txd_free,
ch->p.chan_mode);
musycc_dump_txbuffer_ring(ch, 0);
}
#endif
}
} else { /* RX buffer overrun */
/*
* Per MUSYCC manual, Section 6.4.8.4 [Receive Errors],
* channel recovery for this RX ONR error IS required. It is
* also suggested to increase the number of receive buffers
* for this channel. Receive channel reactivation IS
* required, and data has been lost.
*/
ch->s.rx_over_errors++;
ch->ch_start_rx = CH_START_RX_ONR;
if (cxt1e1_log_level >= LOG_WARN) {
pr_info("%s: RX buffer overflow [ONR] on channel %d, mode %x\n",
ci->devname, ch->channum,
ch->p.chan_mode);
#ifdef RLD_DEBUG
musycc_dump_rxbuffer_ring(ch, 0);
#endif
}
}
musycc_chan_restart(ch);
break;
case ERR_BUF:
if (tx) {
ch->s.tx_fifo_errors++;
ch->ch_start_tx = CH_START_TX_BUF;
/*
* Per MUSYCC manual, Section 6.4.8.3 [Transmit Errors],
* this BUFF error requires Transmit channel reactivation.
*/
if (cxt1e1_log_level >= LOG_MONITOR)
pr_info("%s: TX buffer underrun [BUFF] on channel %d, mode %x\n",
ci->devname, ch->channum,
ch->p.chan_mode);
} else { /* RX buffer overrun */
ch->s.rx_over_errors++;
/*
* Per MUSYCC manual, Section 6.4.8.4 [Receive Errors], HDLC
* mode requires NO recovery for this RX BUFF error is
* required. It is suggested to increase the FIFO buffer
* space for this channel. Receive channel reactivation is
* not required, but data has been lost.
*/
if (cxt1e1_log_level >= LOG_WARN)
pr_info("%s: RX buffer overrun [BUFF] on channel %d, mode %x\n",
ci->devname, ch->channum,
ch->p.chan_mode);
/*
* Per MUSYCC manual, Section 6.4.9.4 [Receive Errors],
* Transparent mode DOES require recovery for the RX BUFF
* error. It is suggested to increase the FIFO buffer space
* for this channel. Receive channel reactivation IS
* required and data has been lost.
*/
if (ch->p.chan_mode == CFG_CH_PROTO_TRANS)
ch->ch_start_rx = CH_START_RX_BUF;
}
if (tx || (ch->p.chan_mode == CFG_CH_PROTO_TRANS))
musycc_chan_restart(ch);
break;
default:
break;
} /* switch on err */
/* Check for interrupt lost condition */
if ((currInt & INTRPT_ILOST_M) &&
(cxt1e1_log_level >= LOG_ERROR))
pr_info("%s: Interrupt queue overflow - ILOST asserted\n",
ci->devname);
/* insure wrapness */
ci->iqp_headx = (headx + 1) & (INT_QUEUE_SIZE - 1);
FLUSH_MEM_WRITE();
FLUSH_MEM_READ();
} /* while */
if ((cxt1e1_log_level >= LOG_MONITOR2) &&
(ci->iqp_headx != ci->iqp_tailx)) {
int bh;
bh = atomic_read(&CI->bh_pending);
pr_info("_bh_: late arrivals, head %d != tail %d, pending %d\n",
ci->iqp_headx, ci->iqp_tailx, bh);
}
#if defined(SBE_ISR_IMMEDIATE)
return 0L;
#endif
/* else, nothing returned */
}
#ifdef SBE_PMCC4_ENABLE
status_t
musycc_chan_down(ci_t *dummy, int channum)
{
mpi_t *pi;
mch_t *ch;
int i, gchan;
ch = sd_find_chan(dummy, channum);
if (!ch)
return -EINVAL;
pi = ch->up;
gchan = ch->gchan;
/* Deactivate the channel */
musycc_serv_req(pi, SR_CHANNEL_DEACTIVATE | SR_RX_DIRECTION | gchan);
ch->ch_start_rx = 0;
musycc_serv_req(pi, SR_CHANNEL_DEACTIVATE | SR_TX_DIRECTION | gchan);
ch->ch_start_tx = 0;
if (ch->state == DOWN)
return 0;
ch->state = DOWN;
pi->regram->thp[gchan] = 0;
pi->regram->tmp[gchan] = 0;
pi->regram->rhp[gchan] = 0;
pi->regram->rmp[gchan] = 0;
FLUSH_MEM_WRITE();
for (i = 0; i < ch->txd_num; i++)
if (ch->mdt[i].mem_token)
OS_mem_token_free(ch->mdt[i].mem_token);
for (i = 0; i < ch->rxd_num; i++)
if (ch->mdr[i].mem_token)
OS_mem_token_free(ch->mdr[i].mem_token);
kfree(ch->mdr);
ch->mdr = NULL;
ch->rxd_num = 0;
kfree(ch->mdt);
ch->mdt = NULL;
ch->txd_num = 0;
musycc_update_timeslots(pi);
c4_fifo_free(pi, ch->gchan);
pi->openchans--;
return 0;
}
#endif
int
musycc_start_xmit(ci_t *ci, int channum, void *mem_token)
{
mch_t *ch;
struct mdesc *md;
void *m2;
int txd_need_cnt;
u_int32_t len;
ch = sd_find_chan(ci, channum);
if (!ch)
return -ENOENT;
/* full interrupt processing available */
if (ci->state != C_RUNNING)
return -EINVAL;
if (ch->state != UP)
return -EINVAL;
/* how else to flag unwritable state ? */
if (!(ch->status & TX_ENABLED))
return -EROFS;
#ifdef RLD_TRANS_DEBUG
if (1 || cxt1e1_log_level >= LOG_MONITOR2)
#else
if (cxt1e1_log_level >= LOG_MONITOR2)
#endif
{
pr_info("++ start_xmt[%d]: state %x start %x full %d free %d required %d stopped %x\n",
channum, ch->state, ch->ch_start_tx, ch->tx_full,
ch->txd_free, ch->txd_required,
sd_queue_stopped(ch->user));
}
/***********************************************/
/** Determine total amount of data to be sent **/
/***********************************************/
m2 = mem_token;
txd_need_cnt = 0;
for (len = OS_mem_token_tlen(m2); len > 0;
m2 = (void *) OS_mem_token_next(m2)) {
if (!OS_mem_token_len(m2))
continue;
txd_need_cnt++;
len -= OS_mem_token_len(m2);
}
if (txd_need_cnt == 0) {
if (cxt1e1_log_level >= LOG_MONITOR2)
pr_info("%s channel %d: no TX data in User buffer\n",
ci->devname, channum);
OS_mem_token_free(mem_token);
return 0; /* no data to send */
}
/*************************************************/
/** Are there sufficient descriptors available? **/
/*************************************************/
if (txd_need_cnt > ch->txd_num) { /* never enough descriptors for this
* large a buffer */
if (cxt1e1_log_level >= LOG_DEBUG)
pr_info("start_xmit: discarding buffer, insufficient descriptor cnt %d, need %d.\n",
ch->txd_num, txd_need_cnt + 1);
ch->s.tx_dropped++;
OS_mem_token_free(mem_token);
return 0;
}
/************************************************************/
/** flow control the line if not enough descriptors remain **/
/************************************************************/
if (txd_need_cnt > ch->txd_free) {
if (cxt1e1_log_level >= LOG_MONITOR2)
pr_info("start_xmit[%d]: EBUSY - need more descriptors, have %d of %d need %d\n",
channum, ch->txd_free,
ch->txd_num, txd_need_cnt);
ch->tx_full = 1;
ch->txd_required = txd_need_cnt;
sd_disable_xmit(ch->user);
return -EBUSY; /* tell user to try again later */
}
/**************************************************/
/** Put the user data into MUSYCC data buffer(s) **/
/**************************************************/
m2 = mem_token;
md = ch->txd_usr_add; /* get current available descriptor */
for (len = OS_mem_token_tlen(m2); len > 0; m2 = OS_mem_token_next(m2)) {
int u = OS_mem_token_len(m2);
if (!u)
continue;
len -= u;
/*
* Enable following chunks, yet wait to enable the FIRST chunk until
* after ALL subsequent chunks are setup.
*/
if (md != ch->txd_usr_add) /* not first chunk */
/* transfer ownership from HOST to MUSYCC */
u |= MUSYCC_TX_OWNED;
if (len) /* not last chunk */
u |= EOBIRQ_ENABLE;
else if (ch->p.chan_mode == CFG_CH_PROTO_TRANS) {
/*
* Per MUSYCC Ref 6.4.9 for Transparent Mode, the host must
* always clear EOMIRQ_ENABLE in every Transmit Buffer Descriptor
* (IE. don't set herein).
*/
u |= EOBIRQ_ENABLE;
} else
u |= EOMIRQ_ENABLE; /* EOM, last HDLC chunk */
/* last chunk in hdlc mode */
u |= (ch->p.idlecode << IDLE_CODE);
if (ch->p.pad_fill_count) {
u |= (PADFILL_ENABLE | (ch->p.pad_fill_count << EXTRA_FLAGS));
}
/* Fill in mds on last segment, others set ZERO
* so that entire token is removed ONLY when ALL
* segments have been transmitted.
*/
md->mem_token = len ? NULL : mem_token;
md->data = cpu_to_le32(OS_vtophys(OS_mem_token_data(m2)));
FLUSH_MEM_WRITE();
md->status = cpu_to_le32(u);
--ch->txd_free;
md = md->snext;
}
FLUSH_MEM_WRITE();
/*
* Now transfer ownership of first chunk from HOST to MUSYCC in order to
* fire-off this XMIT.
*/
ch->txd_usr_add->status |= __constant_cpu_to_le32(MUSYCC_TX_OWNED);
FLUSH_MEM_WRITE();
ch->txd_usr_add = md;
len = OS_mem_token_tlen(mem_token);
atomic_add(len, &ch->tx_pending);
atomic_add(len, &ci->tx_pending);
ch->s.tx_packets++;
ch->s.tx_bytes += len;
/*
* If an ONR was seen, then channel requires poking to restart
* transmission.
*/
if (ch->ch_start_tx)
musycc_chan_restart(ch);
#ifdef SBE_WAN256T3_ENABLE
wan256t3_led(ci, LED_TX, LEDV_G);
#endif
return 0;
}
/*** End-of-File ***/
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.