repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
AnguisCaptor/PwnKernel_Hammerhead | fs/ext4/block_validity.c | 7006 | 6813 | /*
* linux/fs/ext4/block_validity.c
*
* Copyright (C) 2009
* Theodore Ts'o (tytso@mit.edu)
*
* Track which blocks in the filesystem are metadata blocks that
* should never be used as data blocks by files or directories.
*/
#include <linux/time.h>
#include <linux/fs.h>
#include <linux/namei.h>
#include <linux/quotaops.h>
#include <linux/buffer_head.h>
#include <linux/swap.h>
#include <linux/pagemap.h>
#include <linux/blkdev.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include "ext4.h"
struct ext4_system_zone {
struct rb_node node;
ext4_fsblk_t start_blk;
unsigned int count;
};
static struct kmem_cache *ext4_system_zone_cachep;
int __init ext4_init_system_zone(void)
{
ext4_system_zone_cachep = KMEM_CACHE(ext4_system_zone, 0);
if (ext4_system_zone_cachep == NULL)
return -ENOMEM;
return 0;
}
void ext4_exit_system_zone(void)
{
kmem_cache_destroy(ext4_system_zone_cachep);
}
static inline int can_merge(struct ext4_system_zone *entry1,
struct ext4_system_zone *entry2)
{
if ((entry1->start_blk + entry1->count) == entry2->start_blk)
return 1;
return 0;
}
/*
* Mark a range of blocks as belonging to the "system zone" --- that
* is, filesystem metadata blocks which should never be used by
* inodes.
*/
static int add_system_zone(struct ext4_sb_info *sbi,
ext4_fsblk_t start_blk,
unsigned int count)
{
struct ext4_system_zone *new_entry = NULL, *entry;
struct rb_node **n = &sbi->system_blks.rb_node, *node;
struct rb_node *parent = NULL, *new_node = NULL;
while (*n) {
parent = *n;
entry = rb_entry(parent, struct ext4_system_zone, node);
if (start_blk < entry->start_blk)
n = &(*n)->rb_left;
else if (start_blk >= (entry->start_blk + entry->count))
n = &(*n)->rb_right;
else {
if (start_blk + count > (entry->start_blk +
entry->count))
entry->count = (start_blk + count -
entry->start_blk);
new_node = *n;
new_entry = rb_entry(new_node, struct ext4_system_zone,
node);
break;
}
}
if (!new_entry) {
new_entry = kmem_cache_alloc(ext4_system_zone_cachep,
GFP_KERNEL);
if (!new_entry)
return -ENOMEM;
new_entry->start_blk = start_blk;
new_entry->count = count;
new_node = &new_entry->node;
rb_link_node(new_node, parent, n);
rb_insert_color(new_node, &sbi->system_blks);
}
/* Can we merge to the left? */
node = rb_prev(new_node);
if (node) {
entry = rb_entry(node, struct ext4_system_zone, node);
if (can_merge(entry, new_entry)) {
new_entry->start_blk = entry->start_blk;
new_entry->count += entry->count;
rb_erase(node, &sbi->system_blks);
kmem_cache_free(ext4_system_zone_cachep, entry);
}
}
/* Can we merge to the right? */
node = rb_next(new_node);
if (node) {
entry = rb_entry(node, struct ext4_system_zone, node);
if (can_merge(new_entry, entry)) {
new_entry->count += entry->count;
rb_erase(node, &sbi->system_blks);
kmem_cache_free(ext4_system_zone_cachep, entry);
}
}
return 0;
}
static void debug_print_tree(struct ext4_sb_info *sbi)
{
struct rb_node *node;
struct ext4_system_zone *entry;
int first = 1;
printk(KERN_INFO "System zones: ");
node = rb_first(&sbi->system_blks);
while (node) {
entry = rb_entry(node, struct ext4_system_zone, node);
printk("%s%llu-%llu", first ? "" : ", ",
entry->start_blk, entry->start_blk + entry->count - 1);
first = 0;
node = rb_next(node);
}
printk("\n");
}
int ext4_setup_system_zone(struct super_block *sb)
{
ext4_group_t ngroups = ext4_get_groups_count(sb);
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_group_desc *gdp;
ext4_group_t i;
int flex_size = ext4_flex_bg_size(sbi);
int ret;
if (!test_opt(sb, BLOCK_VALIDITY)) {
if (EXT4_SB(sb)->system_blks.rb_node)
ext4_release_system_zone(sb);
return 0;
}
if (EXT4_SB(sb)->system_blks.rb_node)
return 0;
for (i=0; i < ngroups; i++) {
if (ext4_bg_has_super(sb, i) &&
((i < 5) || ((i % flex_size) == 0)))
add_system_zone(sbi, ext4_group_first_block_no(sb, i),
ext4_bg_num_gdb(sb, i) + 1);
gdp = ext4_get_group_desc(sb, i, NULL);
ret = add_system_zone(sbi, ext4_block_bitmap(sb, gdp), 1);
if (ret)
return ret;
ret = add_system_zone(sbi, ext4_inode_bitmap(sb, gdp), 1);
if (ret)
return ret;
ret = add_system_zone(sbi, ext4_inode_table(sb, gdp),
sbi->s_itb_per_group);
if (ret)
return ret;
}
if (test_opt(sb, DEBUG))
debug_print_tree(EXT4_SB(sb));
return 0;
}
/* Called when the filesystem is unmounted */
void ext4_release_system_zone(struct super_block *sb)
{
struct rb_node *n = EXT4_SB(sb)->system_blks.rb_node;
struct rb_node *parent;
struct ext4_system_zone *entry;
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);
entry = rb_entry(n, struct ext4_system_zone, node);
kmem_cache_free(ext4_system_zone_cachep, entry);
if (!parent)
EXT4_SB(sb)->system_blks = RB_ROOT;
else if (parent->rb_left == n)
parent->rb_left = NULL;
else if (parent->rb_right == n)
parent->rb_right = NULL;
n = parent;
}
EXT4_SB(sb)->system_blks = RB_ROOT;
}
/*
* Returns 1 if the passed-in block region (start_blk,
* start_blk+count) is valid; 0 if some part of the block region
* overlaps with filesystem metadata blocks.
*/
int ext4_data_block_valid(struct ext4_sb_info *sbi, ext4_fsblk_t start_blk,
unsigned int count)
{
struct ext4_system_zone *entry;
struct rb_node *n = sbi->system_blks.rb_node;
if ((start_blk <= le32_to_cpu(sbi->s_es->s_first_data_block)) ||
(start_blk + count < start_blk) ||
(start_blk + count > ext4_blocks_count(sbi->s_es))) {
sbi->s_es->s_last_error_block = cpu_to_le64(start_blk);
return 0;
}
while (n) {
entry = rb_entry(n, struct ext4_system_zone, node);
if (start_blk + count - 1 < entry->start_blk)
n = n->rb_left;
else if (start_blk >= (entry->start_blk + entry->count))
n = n->rb_right;
else {
sbi->s_es->s_last_error_block = cpu_to_le64(start_blk);
return 0;
}
}
return 1;
}
int ext4_check_blockref(const char *function, unsigned int line,
struct inode *inode, __le32 *p, unsigned int max)
{
struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
__le32 *bref = p;
unsigned int blk;
while (bref < p+max) {
blk = le32_to_cpu(*bref++);
if (blk &&
unlikely(!ext4_data_block_valid(EXT4_SB(inode->i_sb),
blk, 1))) {
es->s_last_error_block = cpu_to_le64(blk);
ext4_error_inode(inode, function, line, blk,
"invalid block");
return -EIO;
}
}
return 0;
}
| gpl-2.0 |
garwynn/D710BST_FL24_Kernel | drivers/usb/host/uhci-pci.c | 7774 | 8353 | /*
* UHCI HCD (Host Controller Driver) PCI Bus Glue.
*
* Extracted from uhci-hcd.c:
* Maintainer: Alan Stern <stern@rowland.harvard.edu>
*
* (C) Copyright 1999 Linus Torvalds
* (C) Copyright 1999-2002 Johannes Erdfelt, johannes@erdfelt.com
* (C) Copyright 1999 Randy Dunlap
* (C) Copyright 1999 Georg Acher, acher@in.tum.de
* (C) Copyright 1999 Deti Fliegl, deti@fliegl.de
* (C) Copyright 1999 Thomas Sailer, sailer@ife.ee.ethz.ch
* (C) Copyright 1999 Roman Weissgaerber, weissg@vienna.at
* (C) Copyright 2000 Yggdrasil Computing, Inc. (port of new PCI interface
* support from usb-ohci.c by Adam Richter, adam@yggdrasil.com).
* (C) Copyright 1999 Gregory P. Smith (from usb-ohci.c)
* (C) Copyright 2004-2007 Alan Stern, stern@rowland.harvard.edu
*/
#include "pci-quirks.h"
/*
* Make sure the controller is completely inactive, unable to
* generate interrupts or do DMA.
*/
static void uhci_pci_reset_hc(struct uhci_hcd *uhci)
{
uhci_reset_hc(to_pci_dev(uhci_dev(uhci)), uhci->io_addr);
}
/*
* Initialize a controller that was newly discovered or has just been
* resumed. In either case we can't be sure of its previous state.
*
* Returns: 1 if the controller was reset, 0 otherwise.
*/
static int uhci_pci_check_and_reset_hc(struct uhci_hcd *uhci)
{
return uhci_check_and_reset_hc(to_pci_dev(uhci_dev(uhci)),
uhci->io_addr);
}
/*
* Store the basic register settings needed by the controller.
* This function is called at the end of configure_hc in uhci-hcd.c.
*/
static void uhci_pci_configure_hc(struct uhci_hcd *uhci)
{
struct pci_dev *pdev = to_pci_dev(uhci_dev(uhci));
/* Enable PIRQ */
pci_write_config_word(pdev, USBLEGSUP, USBLEGSUP_DEFAULT);
/* Disable platform-specific non-PME# wakeup */
if (pdev->vendor == PCI_VENDOR_ID_INTEL)
pci_write_config_byte(pdev, USBRES_INTEL, 0);
}
static int uhci_pci_resume_detect_interrupts_are_broken(struct uhci_hcd *uhci)
{
int port;
switch (to_pci_dev(uhci_dev(uhci))->vendor) {
default:
break;
case PCI_VENDOR_ID_GENESYS:
/* Genesys Logic's GL880S controllers don't generate
* resume-detect interrupts.
*/
return 1;
case PCI_VENDOR_ID_INTEL:
/* Some of Intel's USB controllers have a bug that causes
* resume-detect interrupts if any port has an over-current
* condition. To make matters worse, some motherboards
* hardwire unused USB ports' over-current inputs active!
* To prevent problems, we will not enable resume-detect
* interrupts if any ports are OC.
*/
for (port = 0; port < uhci->rh_numports; ++port) {
if (inw(uhci->io_addr + USBPORTSC1 + port * 2) &
USBPORTSC_OC)
return 1;
}
break;
}
return 0;
}
static int uhci_pci_global_suspend_mode_is_broken(struct uhci_hcd *uhci)
{
int port;
const char *sys_info;
static const char bad_Asus_board[] = "A7V8X";
/* One of Asus's motherboards has a bug which causes it to
* wake up immediately from suspend-to-RAM if any of the ports
* are connected. In such cases we will not set EGSM.
*/
sys_info = dmi_get_system_info(DMI_BOARD_NAME);
if (sys_info && !strcmp(sys_info, bad_Asus_board)) {
for (port = 0; port < uhci->rh_numports; ++port) {
if (inw(uhci->io_addr + USBPORTSC1 + port * 2) &
USBPORTSC_CCS)
return 1;
}
}
return 0;
}
static int uhci_pci_init(struct usb_hcd *hcd)
{
struct uhci_hcd *uhci = hcd_to_uhci(hcd);
uhci->io_addr = (unsigned long) hcd->rsrc_start;
uhci->rh_numports = uhci_count_ports(hcd);
/* Intel controllers report the OverCurrent bit active on.
* VIA controllers report it active off, so we'll adjust the
* bit value. (It's not standardized in the UHCI spec.)
*/
if (to_pci_dev(uhci_dev(uhci))->vendor == PCI_VENDOR_ID_VIA)
uhci->oc_low = 1;
/* HP's server management chip requires a longer port reset delay. */
if (to_pci_dev(uhci_dev(uhci))->vendor == PCI_VENDOR_ID_HP)
uhci->wait_for_hp = 1;
/* Set up pointers to PCI-specific functions */
uhci->reset_hc = uhci_pci_reset_hc;
uhci->check_and_reset_hc = uhci_pci_check_and_reset_hc;
uhci->configure_hc = uhci_pci_configure_hc;
uhci->resume_detect_interrupts_are_broken =
uhci_pci_resume_detect_interrupts_are_broken;
uhci->global_suspend_mode_is_broken =
uhci_pci_global_suspend_mode_is_broken;
/* Kick BIOS off this hardware and reset if the controller
* isn't already safely quiescent.
*/
check_and_reset_hc(uhci);
return 0;
}
/* Make sure the controller is quiescent and that we're not using it
* any more. This is mainly for the benefit of programs which, like kexec,
* expect the hardware to be idle: not doing DMA or generating IRQs.
*
* This routine may be called in a damaged or failing kernel. Hence we
* do not acquire the spinlock before shutting down the controller.
*/
static void uhci_shutdown(struct pci_dev *pdev)
{
struct usb_hcd *hcd = pci_get_drvdata(pdev);
uhci_hc_died(hcd_to_uhci(hcd));
}
#ifdef CONFIG_PM
static int uhci_pci_suspend(struct usb_hcd *hcd, bool do_wakeup)
{
struct uhci_hcd *uhci = hcd_to_uhci(hcd);
struct pci_dev *pdev = to_pci_dev(uhci_dev(uhci));
int rc = 0;
dev_dbg(uhci_dev(uhci), "%s\n", __func__);
spin_lock_irq(&uhci->lock);
if (!HCD_HW_ACCESSIBLE(hcd) || uhci->dead)
goto done_okay; /* Already suspended or dead */
if (uhci->rh_state > UHCI_RH_SUSPENDED) {
dev_warn(uhci_dev(uhci), "Root hub isn't suspended!\n");
rc = -EBUSY;
goto done;
};
/* All PCI host controllers are required to disable IRQ generation
* at the source, so we must turn off PIRQ.
*/
pci_write_config_word(pdev, USBLEGSUP, 0);
clear_bit(HCD_FLAG_POLL_RH, &hcd->flags);
/* Enable platform-specific non-PME# wakeup */
if (do_wakeup) {
if (pdev->vendor == PCI_VENDOR_ID_INTEL)
pci_write_config_byte(pdev, USBRES_INTEL,
USBPORT1EN | USBPORT2EN);
}
done_okay:
clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
done:
spin_unlock_irq(&uhci->lock);
return rc;
}
static int uhci_pci_resume(struct usb_hcd *hcd, bool hibernated)
{
struct uhci_hcd *uhci = hcd_to_uhci(hcd);
dev_dbg(uhci_dev(uhci), "%s\n", __func__);
/* Since we aren't in D3 any more, it's safe to set this flag
* even if the controller was dead.
*/
set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
spin_lock_irq(&uhci->lock);
/* Make sure resume from hibernation re-enumerates everything */
if (hibernated) {
uhci->reset_hc(uhci);
finish_reset(uhci);
}
/* The firmware may have changed the controller settings during
* a system wakeup. Check it and reconfigure to avoid problems.
*/
else {
check_and_reset_hc(uhci);
}
configure_hc(uhci);
/* Tell the core if the controller had to be reset */
if (uhci->rh_state == UHCI_RH_RESET)
usb_root_hub_lost_power(hcd->self.root_hub);
spin_unlock_irq(&uhci->lock);
/* If interrupts don't work and remote wakeup is enabled then
* the suspended root hub needs to be polled.
*/
if (!uhci->RD_enable && hcd->self.root_hub->do_remote_wakeup)
set_bit(HCD_FLAG_POLL_RH, &hcd->flags);
/* Does the root hub have a port wakeup pending? */
usb_hcd_poll_rh_status(hcd);
return 0;
}
#endif
static const struct hc_driver uhci_driver = {
.description = hcd_name,
.product_desc = "UHCI Host Controller",
.hcd_priv_size = sizeof(struct uhci_hcd),
/* Generic hardware linkage */
.irq = uhci_irq,
.flags = HCD_USB11,
/* Basic lifecycle operations */
.reset = uhci_pci_init,
.start = uhci_start,
#ifdef CONFIG_PM
.pci_suspend = uhci_pci_suspend,
.pci_resume = uhci_pci_resume,
.bus_suspend = uhci_rh_suspend,
.bus_resume = uhci_rh_resume,
#endif
.stop = uhci_stop,
.urb_enqueue = uhci_urb_enqueue,
.urb_dequeue = uhci_urb_dequeue,
.endpoint_disable = uhci_hcd_endpoint_disable,
.get_frame_number = uhci_hcd_get_frame_number,
.hub_status_data = uhci_hub_status_data,
.hub_control = uhci_hub_control,
};
static DEFINE_PCI_DEVICE_TABLE(uhci_pci_ids) = { {
/* handle any USB UHCI controller */
PCI_DEVICE_CLASS(PCI_CLASS_SERIAL_USB_UHCI, ~0),
.driver_data = (unsigned long) &uhci_driver,
}, { /* end: all zeroes */ }
};
MODULE_DEVICE_TABLE(pci, uhci_pci_ids);
static struct pci_driver uhci_pci_driver = {
.name = (char *)hcd_name,
.id_table = uhci_pci_ids,
.probe = usb_hcd_pci_probe,
.remove = usb_hcd_pci_remove,
.shutdown = uhci_shutdown,
#ifdef CONFIG_PM_SLEEP
.driver = {
.pm = &usb_hcd_pci_pm_ops
},
#endif
};
| gpl-2.0 |
The-Covenant/android_kernel_samsung_i927 | drivers/media/common/tuners/tda9887.c | 8030 | 18564 | #include <linux/module.h>
#include <linux/kernel.h>
#include <linux/i2c.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/delay.h>
#include <linux/videodev2.h>
#include <media/v4l2-common.h>
#include <media/tuner.h>
#include "tuner-i2c.h"
#include "tda9887.h"
/* Chips:
TDA9885 (PAL, NTSC)
TDA9886 (PAL, SECAM, NTSC)
TDA9887 (PAL, SECAM, NTSC, FM Radio)
Used as part of several tuners
*/
static int debug;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "enable verbose debug messages");
static DEFINE_MUTEX(tda9887_list_mutex);
static LIST_HEAD(hybrid_tuner_instance_list);
struct tda9887_priv {
struct tuner_i2c_props i2c_props;
struct list_head hybrid_tuner_instance_list;
unsigned char data[4];
unsigned int config;
unsigned int mode;
unsigned int audmode;
v4l2_std_id std;
bool standby;
};
/* ---------------------------------------------------------------------- */
#define UNSET (-1U)
struct tvnorm {
v4l2_std_id std;
char *name;
unsigned char b;
unsigned char c;
unsigned char e;
};
/* ---------------------------------------------------------------------- */
//
// TDA defines
//
//// first reg (b)
#define cVideoTrapBypassOFF 0x00 // bit b0
#define cVideoTrapBypassON 0x01 // bit b0
#define cAutoMuteFmInactive 0x00 // bit b1
#define cAutoMuteFmActive 0x02 // bit b1
#define cIntercarrier 0x00 // bit b2
#define cQSS 0x04 // bit b2
#define cPositiveAmTV 0x00 // bit b3:4
#define cFmRadio 0x08 // bit b3:4
#define cNegativeFmTV 0x10 // bit b3:4
#define cForcedMuteAudioON 0x20 // bit b5
#define cForcedMuteAudioOFF 0x00 // bit b5
#define cOutputPort1Active 0x00 // bit b6
#define cOutputPort1Inactive 0x40 // bit b6
#define cOutputPort2Active 0x00 // bit b7
#define cOutputPort2Inactive 0x80 // bit b7
//// second reg (c)
#define cDeemphasisOFF 0x00 // bit c5
#define cDeemphasisON 0x20 // bit c5
#define cDeemphasis75 0x00 // bit c6
#define cDeemphasis50 0x40 // bit c6
#define cAudioGain0 0x00 // bit c7
#define cAudioGain6 0x80 // bit c7
#define cTopMask 0x1f // bit c0:4
#define cTopDefault 0x10 // bit c0:4
//// third reg (e)
#define cAudioIF_4_5 0x00 // bit e0:1
#define cAudioIF_5_5 0x01 // bit e0:1
#define cAudioIF_6_0 0x02 // bit e0:1
#define cAudioIF_6_5 0x03 // bit e0:1
#define cVideoIFMask 0x1c // bit e2:4
/* Video IF selection in TV Mode (bit B3=0) */
#define cVideoIF_58_75 0x00 // bit e2:4
#define cVideoIF_45_75 0x04 // bit e2:4
#define cVideoIF_38_90 0x08 // bit e2:4
#define cVideoIF_38_00 0x0C // bit e2:4
#define cVideoIF_33_90 0x10 // bit e2:4
#define cVideoIF_33_40 0x14 // bit e2:4
#define cRadioIF_45_75 0x18 // bit e2:4
#define cRadioIF_38_90 0x1C // bit e2:4
/* IF1 selection in Radio Mode (bit B3=1) */
#define cRadioIF_33_30 0x00 // bit e2,4 (also 0x10,0x14)
#define cRadioIF_41_30 0x04 // bit e2,4
/* Output of AFC pin in radio mode when bit E7=1 */
#define cRadioAGC_SIF 0x00 // bit e3
#define cRadioAGC_FM 0x08 // bit e3
#define cTunerGainNormal 0x00 // bit e5
#define cTunerGainLow 0x20 // bit e5
#define cGating_18 0x00 // bit e6
#define cGating_36 0x40 // bit e6
#define cAgcOutON 0x80 // bit e7
#define cAgcOutOFF 0x00 // bit e7
/* ---------------------------------------------------------------------- */
static struct tvnorm tvnorms[] = {
{
.std = V4L2_STD_PAL_BG | V4L2_STD_PAL_H | V4L2_STD_PAL_N,
.name = "PAL-BGHN",
.b = ( cNegativeFmTV |
cQSS ),
.c = ( cDeemphasisON |
cDeemphasis50 |
cTopDefault),
.e = ( cGating_36 |
cAudioIF_5_5 |
cVideoIF_38_90 ),
},{
.std = V4L2_STD_PAL_I,
.name = "PAL-I",
.b = ( cNegativeFmTV |
cQSS ),
.c = ( cDeemphasisON |
cDeemphasis50 |
cTopDefault),
.e = ( cGating_36 |
cAudioIF_6_0 |
cVideoIF_38_90 ),
},{
.std = V4L2_STD_PAL_DK,
.name = "PAL-DK",
.b = ( cNegativeFmTV |
cQSS ),
.c = ( cDeemphasisON |
cDeemphasis50 |
cTopDefault),
.e = ( cGating_36 |
cAudioIF_6_5 |
cVideoIF_38_90 ),
},{
.std = V4L2_STD_PAL_M | V4L2_STD_PAL_Nc,
.name = "PAL-M/Nc",
.b = ( cNegativeFmTV |
cQSS ),
.c = ( cDeemphasisON |
cDeemphasis75 |
cTopDefault),
.e = ( cGating_36 |
cAudioIF_4_5 |
cVideoIF_45_75 ),
},{
.std = V4L2_STD_SECAM_B | V4L2_STD_SECAM_G | V4L2_STD_SECAM_H,
.name = "SECAM-BGH",
.b = ( cNegativeFmTV |
cQSS ),
.c = ( cTopDefault),
.e = ( cAudioIF_5_5 |
cVideoIF_38_90 ),
},{
.std = V4L2_STD_SECAM_L,
.name = "SECAM-L",
.b = ( cPositiveAmTV |
cQSS ),
.c = ( cTopDefault),
.e = ( cGating_36 |
cAudioIF_6_5 |
cVideoIF_38_90 ),
},{
.std = V4L2_STD_SECAM_LC,
.name = "SECAM-L'",
.b = ( cOutputPort2Inactive |
cPositiveAmTV |
cQSS ),
.c = ( cTopDefault),
.e = ( cGating_36 |
cAudioIF_6_5 |
cVideoIF_33_90 ),
},{
.std = V4L2_STD_SECAM_DK,
.name = "SECAM-DK",
.b = ( cNegativeFmTV |
cQSS ),
.c = ( cDeemphasisON |
cDeemphasis50 |
cTopDefault),
.e = ( cGating_36 |
cAudioIF_6_5 |
cVideoIF_38_90 ),
},{
.std = V4L2_STD_NTSC_M | V4L2_STD_NTSC_M_KR,
.name = "NTSC-M",
.b = ( cNegativeFmTV |
cQSS ),
.c = ( cDeemphasisON |
cDeemphasis75 |
cTopDefault),
.e = ( cGating_36 |
cAudioIF_4_5 |
cVideoIF_45_75 ),
},{
.std = V4L2_STD_NTSC_M_JP,
.name = "NTSC-M-JP",
.b = ( cNegativeFmTV |
cQSS ),
.c = ( cDeemphasisON |
cDeemphasis50 |
cTopDefault),
.e = ( cGating_36 |
cAudioIF_4_5 |
cVideoIF_58_75 ),
}
};
static struct tvnorm radio_stereo = {
.name = "Radio Stereo",
.b = ( cFmRadio |
cQSS ),
.c = ( cDeemphasisOFF |
cAudioGain6 |
cTopDefault),
.e = ( cTunerGainLow |
cAudioIF_5_5 |
cRadioIF_38_90 ),
};
static struct tvnorm radio_mono = {
.name = "Radio Mono",
.b = ( cFmRadio |
cQSS ),
.c = ( cDeemphasisON |
cDeemphasis75 |
cTopDefault),
.e = ( cTunerGainLow |
cAudioIF_5_5 |
cRadioIF_38_90 ),
};
/* ---------------------------------------------------------------------- */
static void dump_read_message(struct dvb_frontend *fe, unsigned char *buf)
{
struct tda9887_priv *priv = fe->analog_demod_priv;
static char *afc[16] = {
"- 12.5 kHz",
"- 37.5 kHz",
"- 62.5 kHz",
"- 87.5 kHz",
"-112.5 kHz",
"-137.5 kHz",
"-162.5 kHz",
"-187.5 kHz [min]",
"+187.5 kHz [max]",
"+162.5 kHz",
"+137.5 kHz",
"+112.5 kHz",
"+ 87.5 kHz",
"+ 62.5 kHz",
"+ 37.5 kHz",
"+ 12.5 kHz",
};
tuner_info("read: 0x%2x\n", buf[0]);
tuner_info(" after power on : %s\n", (buf[0] & 0x01) ? "yes" : "no");
tuner_info(" afc : %s\n", afc[(buf[0] >> 1) & 0x0f]);
tuner_info(" fmif level : %s\n", (buf[0] & 0x20) ? "high" : "low");
tuner_info(" afc window : %s\n", (buf[0] & 0x40) ? "in" : "out");
tuner_info(" vfi level : %s\n", (buf[0] & 0x80) ? "high" : "low");
}
static void dump_write_message(struct dvb_frontend *fe, unsigned char *buf)
{
struct tda9887_priv *priv = fe->analog_demod_priv;
static char *sound[4] = {
"AM/TV",
"FM/radio",
"FM/TV",
"FM/radio"
};
static char *adjust[32] = {
"-16", "-15", "-14", "-13", "-12", "-11", "-10", "-9",
"-8", "-7", "-6", "-5", "-4", "-3", "-2", "-1",
"0", "+1", "+2", "+3", "+4", "+5", "+6", "+7",
"+8", "+9", "+10", "+11", "+12", "+13", "+14", "+15"
};
static char *deemph[4] = {
"no", "no", "75", "50"
};
static char *carrier[4] = {
"4.5 MHz",
"5.5 MHz",
"6.0 MHz",
"6.5 MHz / AM"
};
static char *vif[8] = {
"58.75 MHz",
"45.75 MHz",
"38.9 MHz",
"38.0 MHz",
"33.9 MHz",
"33.4 MHz",
"45.75 MHz + pin13",
"38.9 MHz + pin13",
};
static char *rif[4] = {
"44 MHz",
"52 MHz",
"52 MHz",
"44 MHz",
};
tuner_info("write: byte B 0x%02x\n", buf[1]);
tuner_info(" B0 video mode : %s\n",
(buf[1] & 0x01) ? "video trap" : "sound trap");
tuner_info(" B1 auto mute fm : %s\n",
(buf[1] & 0x02) ? "yes" : "no");
tuner_info(" B2 carrier mode : %s\n",
(buf[1] & 0x04) ? "QSS" : "Intercarrier");
tuner_info(" B3-4 tv sound/radio : %s\n",
sound[(buf[1] & 0x18) >> 3]);
tuner_info(" B5 force mute audio: %s\n",
(buf[1] & 0x20) ? "yes" : "no");
tuner_info(" B6 output port 1 : %s\n",
(buf[1] & 0x40) ? "high (inactive)" : "low (active)");
tuner_info(" B7 output port 2 : %s\n",
(buf[1] & 0x80) ? "high (inactive)" : "low (active)");
tuner_info("write: byte C 0x%02x\n", buf[2]);
tuner_info(" C0-4 top adjustment : %s dB\n",
adjust[buf[2] & 0x1f]);
tuner_info(" C5-6 de-emphasis : %s\n",
deemph[(buf[2] & 0x60) >> 5]);
tuner_info(" C7 audio gain : %s\n",
(buf[2] & 0x80) ? "-6" : "0");
tuner_info("write: byte E 0x%02x\n", buf[3]);
tuner_info(" E0-1 sound carrier : %s\n",
carrier[(buf[3] & 0x03)]);
tuner_info(" E6 l pll gating : %s\n",
(buf[3] & 0x40) ? "36" : "13");
if (buf[1] & 0x08) {
/* radio */
tuner_info(" E2-4 video if : %s\n",
rif[(buf[3] & 0x0c) >> 2]);
tuner_info(" E7 vif agc output : %s\n",
(buf[3] & 0x80)
? ((buf[3] & 0x10) ? "fm-agc radio" :
"sif-agc radio")
: "fm radio carrier afc");
} else {
/* video */
tuner_info(" E2-4 video if : %s\n",
vif[(buf[3] & 0x1c) >> 2]);
tuner_info(" E5 tuner gain : %s\n",
(buf[3] & 0x80)
? ((buf[3] & 0x20) ? "external" : "normal")
: ((buf[3] & 0x20) ? "minimum" : "normal"));
tuner_info(" E7 vif agc output : %s\n",
(buf[3] & 0x80) ? ((buf[3] & 0x20)
? "pin3 port, pin22 vif agc out"
: "pin22 port, pin3 vif acg ext in")
: "pin3+pin22 port");
}
tuner_info("--\n");
}
/* ---------------------------------------------------------------------- */
static int tda9887_set_tvnorm(struct dvb_frontend *fe)
{
struct tda9887_priv *priv = fe->analog_demod_priv;
struct tvnorm *norm = NULL;
char *buf = priv->data;
int i;
if (priv->mode == V4L2_TUNER_RADIO) {
if (priv->audmode == V4L2_TUNER_MODE_MONO)
norm = &radio_mono;
else
norm = &radio_stereo;
} else {
for (i = 0; i < ARRAY_SIZE(tvnorms); i++) {
if (tvnorms[i].std & priv->std) {
norm = tvnorms+i;
break;
}
}
}
if (NULL == norm) {
tuner_dbg("Unsupported tvnorm entry - audio muted\n");
return -1;
}
tuner_dbg("configure for: %s\n", norm->name);
buf[1] = norm->b;
buf[2] = norm->c;
buf[3] = norm->e;
return 0;
}
static unsigned int port1 = UNSET;
static unsigned int port2 = UNSET;
static unsigned int qss = UNSET;
static unsigned int adjust = UNSET;
module_param(port1, int, 0644);
module_param(port2, int, 0644);
module_param(qss, int, 0644);
module_param(adjust, int, 0644);
static int tda9887_set_insmod(struct dvb_frontend *fe)
{
struct tda9887_priv *priv = fe->analog_demod_priv;
char *buf = priv->data;
if (UNSET != port1) {
if (port1)
buf[1] |= cOutputPort1Inactive;
else
buf[1] &= ~cOutputPort1Inactive;
}
if (UNSET != port2) {
if (port2)
buf[1] |= cOutputPort2Inactive;
else
buf[1] &= ~cOutputPort2Inactive;
}
if (UNSET != qss) {
if (qss)
buf[1] |= cQSS;
else
buf[1] &= ~cQSS;
}
if (adjust < 0x20) {
buf[2] &= ~cTopMask;
buf[2] |= adjust;
}
return 0;
}
static int tda9887_do_config(struct dvb_frontend *fe)
{
struct tda9887_priv *priv = fe->analog_demod_priv;
char *buf = priv->data;
if (priv->config & TDA9887_PORT1_ACTIVE)
buf[1] &= ~cOutputPort1Inactive;
if (priv->config & TDA9887_PORT1_INACTIVE)
buf[1] |= cOutputPort1Inactive;
if (priv->config & TDA9887_PORT2_ACTIVE)
buf[1] &= ~cOutputPort2Inactive;
if (priv->config & TDA9887_PORT2_INACTIVE)
buf[1] |= cOutputPort2Inactive;
if (priv->config & TDA9887_QSS)
buf[1] |= cQSS;
if (priv->config & TDA9887_INTERCARRIER)
buf[1] &= ~cQSS;
if (priv->config & TDA9887_AUTOMUTE)
buf[1] |= cAutoMuteFmActive;
if (priv->config & TDA9887_DEEMPHASIS_MASK) {
buf[2] &= ~0x60;
switch (priv->config & TDA9887_DEEMPHASIS_MASK) {
case TDA9887_DEEMPHASIS_NONE:
buf[2] |= cDeemphasisOFF;
break;
case TDA9887_DEEMPHASIS_50:
buf[2] |= cDeemphasisON | cDeemphasis50;
break;
case TDA9887_DEEMPHASIS_75:
buf[2] |= cDeemphasisON | cDeemphasis75;
break;
}
}
if (priv->config & TDA9887_TOP_SET) {
buf[2] &= ~cTopMask;
buf[2] |= (priv->config >> 8) & cTopMask;
}
if ((priv->config & TDA9887_INTERCARRIER_NTSC) &&
(priv->std & V4L2_STD_NTSC))
buf[1] &= ~cQSS;
if (priv->config & TDA9887_GATING_18)
buf[3] &= ~cGating_36;
if (priv->mode == V4L2_TUNER_RADIO) {
if (priv->config & TDA9887_RIF_41_3) {
buf[3] &= ~cVideoIFMask;
buf[3] |= cRadioIF_41_30;
}
if (priv->config & TDA9887_GAIN_NORMAL)
buf[3] &= ~cTunerGainLow;
}
return 0;
}
/* ---------------------------------------------------------------------- */
static int tda9887_status(struct dvb_frontend *fe)
{
struct tda9887_priv *priv = fe->analog_demod_priv;
unsigned char buf[1];
int rc;
memset(buf,0,sizeof(buf));
if (1 != (rc = tuner_i2c_xfer_recv(&priv->i2c_props,buf,1)))
tuner_info("i2c i/o error: rc == %d (should be 1)\n", rc);
dump_read_message(fe, buf);
return 0;
}
static void tda9887_configure(struct dvb_frontend *fe)
{
struct tda9887_priv *priv = fe->analog_demod_priv;
int rc;
memset(priv->data,0,sizeof(priv->data));
tda9887_set_tvnorm(fe);
/* A note on the port settings:
These settings tend to depend on the specifics of the board.
By default they are set to inactive (bit value 1) by this driver,
overwriting any changes made by the tvnorm. This means that it
is the responsibility of the module using the tda9887 to set
these values in case of changes in the tvnorm.
In many cases port 2 should be made active (0) when selecting
SECAM-L, and port 2 should remain inactive (1) for SECAM-L'.
For the other standards the tda9887 application note says that
the ports should be set to active (0), but, again, that may
differ depending on the precise hardware configuration.
*/
priv->data[1] |= cOutputPort1Inactive;
priv->data[1] |= cOutputPort2Inactive;
tda9887_do_config(fe);
tda9887_set_insmod(fe);
if (priv->standby)
priv->data[1] |= cForcedMuteAudioON;
tuner_dbg("writing: b=0x%02x c=0x%02x e=0x%02x\n",
priv->data[1], priv->data[2], priv->data[3]);
if (debug > 1)
dump_write_message(fe, priv->data);
if (4 != (rc = tuner_i2c_xfer_send(&priv->i2c_props,priv->data,4)))
tuner_info("i2c i/o error: rc == %d (should be 4)\n", rc);
if (debug > 2) {
msleep_interruptible(1000);
tda9887_status(fe);
}
}
/* ---------------------------------------------------------------------- */
static void tda9887_tuner_status(struct dvb_frontend *fe)
{
struct tda9887_priv *priv = fe->analog_demod_priv;
tuner_info("Data bytes: b=0x%02x c=0x%02x e=0x%02x\n",
priv->data[1], priv->data[2], priv->data[3]);
}
static int tda9887_get_afc(struct dvb_frontend *fe)
{
struct tda9887_priv *priv = fe->analog_demod_priv;
static int AFC_BITS_2_kHz[] = {
-12500, -37500, -62500, -97500,
-112500, -137500, -162500, -187500,
187500, 162500, 137500, 112500,
97500 , 62500, 37500 , 12500
};
int afc=0;
__u8 reg = 0;
if (1 == tuner_i2c_xfer_recv(&priv->i2c_props,®,1))
afc = AFC_BITS_2_kHz[(reg>>1)&0x0f];
return afc;
}
static void tda9887_standby(struct dvb_frontend *fe)
{
struct tda9887_priv *priv = fe->analog_demod_priv;
priv->standby = true;
tda9887_configure(fe);
}
static void tda9887_set_params(struct dvb_frontend *fe,
struct analog_parameters *params)
{
struct tda9887_priv *priv = fe->analog_demod_priv;
priv->standby = false;
priv->mode = params->mode;
priv->audmode = params->audmode;
priv->std = params->std;
tda9887_configure(fe);
}
static int tda9887_set_config(struct dvb_frontend *fe, void *priv_cfg)
{
struct tda9887_priv *priv = fe->analog_demod_priv;
priv->config = *(unsigned int *)priv_cfg;
tda9887_configure(fe);
return 0;
}
static void tda9887_release(struct dvb_frontend *fe)
{
struct tda9887_priv *priv = fe->analog_demod_priv;
mutex_lock(&tda9887_list_mutex);
if (priv)
hybrid_tuner_release_state(priv);
mutex_unlock(&tda9887_list_mutex);
fe->analog_demod_priv = NULL;
}
static struct analog_demod_ops tda9887_ops = {
.info = {
.name = "tda9887",
},
.set_params = tda9887_set_params,
.standby = tda9887_standby,
.tuner_status = tda9887_tuner_status,
.get_afc = tda9887_get_afc,
.release = tda9887_release,
.set_config = tda9887_set_config,
};
struct dvb_frontend *tda9887_attach(struct dvb_frontend *fe,
struct i2c_adapter *i2c_adap,
u8 i2c_addr)
{
struct tda9887_priv *priv = NULL;
int instance;
mutex_lock(&tda9887_list_mutex);
instance = hybrid_tuner_request_state(struct tda9887_priv, priv,
hybrid_tuner_instance_list,
i2c_adap, i2c_addr, "tda9887");
switch (instance) {
case 0:
mutex_unlock(&tda9887_list_mutex);
return NULL;
case 1:
fe->analog_demod_priv = priv;
priv->standby = true;
tuner_info("tda988[5/6/7] found\n");
break;
default:
fe->analog_demod_priv = priv;
break;
}
mutex_unlock(&tda9887_list_mutex);
memcpy(&fe->ops.analog_ops, &tda9887_ops,
sizeof(struct analog_demod_ops));
return fe;
}
EXPORT_SYMBOL_GPL(tda9887_attach);
MODULE_LICENSE("GPL");
/*
* Overrides for Emacs so that we follow Linus's tabbing style.
* ---------------------------------------------------------------------------
* Local variables:
* c-basic-offset: 8
* End:
*/
| gpl-2.0 |
Ander-Alvarez/android_kernel_motorola_msm8226 | drivers/media/common/tuners/tda9887.c | 8030 | 18564 | #include <linux/module.h>
#include <linux/kernel.h>
#include <linux/i2c.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/delay.h>
#include <linux/videodev2.h>
#include <media/v4l2-common.h>
#include <media/tuner.h>
#include "tuner-i2c.h"
#include "tda9887.h"
/* Chips:
TDA9885 (PAL, NTSC)
TDA9886 (PAL, SECAM, NTSC)
TDA9887 (PAL, SECAM, NTSC, FM Radio)
Used as part of several tuners
*/
static int debug;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "enable verbose debug messages");
static DEFINE_MUTEX(tda9887_list_mutex);
static LIST_HEAD(hybrid_tuner_instance_list);
struct tda9887_priv {
struct tuner_i2c_props i2c_props;
struct list_head hybrid_tuner_instance_list;
unsigned char data[4];
unsigned int config;
unsigned int mode;
unsigned int audmode;
v4l2_std_id std;
bool standby;
};
/* ---------------------------------------------------------------------- */
#define UNSET (-1U)
struct tvnorm {
v4l2_std_id std;
char *name;
unsigned char b;
unsigned char c;
unsigned char e;
};
/* ---------------------------------------------------------------------- */
//
// TDA defines
//
//// first reg (b)
#define cVideoTrapBypassOFF 0x00 // bit b0
#define cVideoTrapBypassON 0x01 // bit b0
#define cAutoMuteFmInactive 0x00 // bit b1
#define cAutoMuteFmActive 0x02 // bit b1
#define cIntercarrier 0x00 // bit b2
#define cQSS 0x04 // bit b2
#define cPositiveAmTV 0x00 // bit b3:4
#define cFmRadio 0x08 // bit b3:4
#define cNegativeFmTV 0x10 // bit b3:4
#define cForcedMuteAudioON 0x20 // bit b5
#define cForcedMuteAudioOFF 0x00 // bit b5
#define cOutputPort1Active 0x00 // bit b6
#define cOutputPort1Inactive 0x40 // bit b6
#define cOutputPort2Active 0x00 // bit b7
#define cOutputPort2Inactive 0x80 // bit b7
//// second reg (c)
#define cDeemphasisOFF 0x00 // bit c5
#define cDeemphasisON 0x20 // bit c5
#define cDeemphasis75 0x00 // bit c6
#define cDeemphasis50 0x40 // bit c6
#define cAudioGain0 0x00 // bit c7
#define cAudioGain6 0x80 // bit c7
#define cTopMask 0x1f // bit c0:4
#define cTopDefault 0x10 // bit c0:4
//// third reg (e)
#define cAudioIF_4_5 0x00 // bit e0:1
#define cAudioIF_5_5 0x01 // bit e0:1
#define cAudioIF_6_0 0x02 // bit e0:1
#define cAudioIF_6_5 0x03 // bit e0:1
#define cVideoIFMask 0x1c // bit e2:4
/* Video IF selection in TV Mode (bit B3=0) */
#define cVideoIF_58_75 0x00 // bit e2:4
#define cVideoIF_45_75 0x04 // bit e2:4
#define cVideoIF_38_90 0x08 // bit e2:4
#define cVideoIF_38_00 0x0C // bit e2:4
#define cVideoIF_33_90 0x10 // bit e2:4
#define cVideoIF_33_40 0x14 // bit e2:4
#define cRadioIF_45_75 0x18 // bit e2:4
#define cRadioIF_38_90 0x1C // bit e2:4
/* IF1 selection in Radio Mode (bit B3=1) */
#define cRadioIF_33_30 0x00 // bit e2,4 (also 0x10,0x14)
#define cRadioIF_41_30 0x04 // bit e2,4
/* Output of AFC pin in radio mode when bit E7=1 */
#define cRadioAGC_SIF 0x00 // bit e3
#define cRadioAGC_FM 0x08 // bit e3
#define cTunerGainNormal 0x00 // bit e5
#define cTunerGainLow 0x20 // bit e5
#define cGating_18 0x00 // bit e6
#define cGating_36 0x40 // bit e6
#define cAgcOutON 0x80 // bit e7
#define cAgcOutOFF 0x00 // bit e7
/* ---------------------------------------------------------------------- */
static struct tvnorm tvnorms[] = {
{
.std = V4L2_STD_PAL_BG | V4L2_STD_PAL_H | V4L2_STD_PAL_N,
.name = "PAL-BGHN",
.b = ( cNegativeFmTV |
cQSS ),
.c = ( cDeemphasisON |
cDeemphasis50 |
cTopDefault),
.e = ( cGating_36 |
cAudioIF_5_5 |
cVideoIF_38_90 ),
},{
.std = V4L2_STD_PAL_I,
.name = "PAL-I",
.b = ( cNegativeFmTV |
cQSS ),
.c = ( cDeemphasisON |
cDeemphasis50 |
cTopDefault),
.e = ( cGating_36 |
cAudioIF_6_0 |
cVideoIF_38_90 ),
},{
.std = V4L2_STD_PAL_DK,
.name = "PAL-DK",
.b = ( cNegativeFmTV |
cQSS ),
.c = ( cDeemphasisON |
cDeemphasis50 |
cTopDefault),
.e = ( cGating_36 |
cAudioIF_6_5 |
cVideoIF_38_90 ),
},{
.std = V4L2_STD_PAL_M | V4L2_STD_PAL_Nc,
.name = "PAL-M/Nc",
.b = ( cNegativeFmTV |
cQSS ),
.c = ( cDeemphasisON |
cDeemphasis75 |
cTopDefault),
.e = ( cGating_36 |
cAudioIF_4_5 |
cVideoIF_45_75 ),
},{
.std = V4L2_STD_SECAM_B | V4L2_STD_SECAM_G | V4L2_STD_SECAM_H,
.name = "SECAM-BGH",
.b = ( cNegativeFmTV |
cQSS ),
.c = ( cTopDefault),
.e = ( cAudioIF_5_5 |
cVideoIF_38_90 ),
},{
.std = V4L2_STD_SECAM_L,
.name = "SECAM-L",
.b = ( cPositiveAmTV |
cQSS ),
.c = ( cTopDefault),
.e = ( cGating_36 |
cAudioIF_6_5 |
cVideoIF_38_90 ),
},{
.std = V4L2_STD_SECAM_LC,
.name = "SECAM-L'",
.b = ( cOutputPort2Inactive |
cPositiveAmTV |
cQSS ),
.c = ( cTopDefault),
.e = ( cGating_36 |
cAudioIF_6_5 |
cVideoIF_33_90 ),
},{
.std = V4L2_STD_SECAM_DK,
.name = "SECAM-DK",
.b = ( cNegativeFmTV |
cQSS ),
.c = ( cDeemphasisON |
cDeemphasis50 |
cTopDefault),
.e = ( cGating_36 |
cAudioIF_6_5 |
cVideoIF_38_90 ),
},{
.std = V4L2_STD_NTSC_M | V4L2_STD_NTSC_M_KR,
.name = "NTSC-M",
.b = ( cNegativeFmTV |
cQSS ),
.c = ( cDeemphasisON |
cDeemphasis75 |
cTopDefault),
.e = ( cGating_36 |
cAudioIF_4_5 |
cVideoIF_45_75 ),
},{
.std = V4L2_STD_NTSC_M_JP,
.name = "NTSC-M-JP",
.b = ( cNegativeFmTV |
cQSS ),
.c = ( cDeemphasisON |
cDeemphasis50 |
cTopDefault),
.e = ( cGating_36 |
cAudioIF_4_5 |
cVideoIF_58_75 ),
}
};
static struct tvnorm radio_stereo = {
.name = "Radio Stereo",
.b = ( cFmRadio |
cQSS ),
.c = ( cDeemphasisOFF |
cAudioGain6 |
cTopDefault),
.e = ( cTunerGainLow |
cAudioIF_5_5 |
cRadioIF_38_90 ),
};
static struct tvnorm radio_mono = {
.name = "Radio Mono",
.b = ( cFmRadio |
cQSS ),
.c = ( cDeemphasisON |
cDeemphasis75 |
cTopDefault),
.e = ( cTunerGainLow |
cAudioIF_5_5 |
cRadioIF_38_90 ),
};
/* ---------------------------------------------------------------------- */
static void dump_read_message(struct dvb_frontend *fe, unsigned char *buf)
{
struct tda9887_priv *priv = fe->analog_demod_priv;
static char *afc[16] = {
"- 12.5 kHz",
"- 37.5 kHz",
"- 62.5 kHz",
"- 87.5 kHz",
"-112.5 kHz",
"-137.5 kHz",
"-162.5 kHz",
"-187.5 kHz [min]",
"+187.5 kHz [max]",
"+162.5 kHz",
"+137.5 kHz",
"+112.5 kHz",
"+ 87.5 kHz",
"+ 62.5 kHz",
"+ 37.5 kHz",
"+ 12.5 kHz",
};
tuner_info("read: 0x%2x\n", buf[0]);
tuner_info(" after power on : %s\n", (buf[0] & 0x01) ? "yes" : "no");
tuner_info(" afc : %s\n", afc[(buf[0] >> 1) & 0x0f]);
tuner_info(" fmif level : %s\n", (buf[0] & 0x20) ? "high" : "low");
tuner_info(" afc window : %s\n", (buf[0] & 0x40) ? "in" : "out");
tuner_info(" vfi level : %s\n", (buf[0] & 0x80) ? "high" : "low");
}
static void dump_write_message(struct dvb_frontend *fe, unsigned char *buf)
{
struct tda9887_priv *priv = fe->analog_demod_priv;
static char *sound[4] = {
"AM/TV",
"FM/radio",
"FM/TV",
"FM/radio"
};
static char *adjust[32] = {
"-16", "-15", "-14", "-13", "-12", "-11", "-10", "-9",
"-8", "-7", "-6", "-5", "-4", "-3", "-2", "-1",
"0", "+1", "+2", "+3", "+4", "+5", "+6", "+7",
"+8", "+9", "+10", "+11", "+12", "+13", "+14", "+15"
};
static char *deemph[4] = {
"no", "no", "75", "50"
};
static char *carrier[4] = {
"4.5 MHz",
"5.5 MHz",
"6.0 MHz",
"6.5 MHz / AM"
};
static char *vif[8] = {
"58.75 MHz",
"45.75 MHz",
"38.9 MHz",
"38.0 MHz",
"33.9 MHz",
"33.4 MHz",
"45.75 MHz + pin13",
"38.9 MHz + pin13",
};
static char *rif[4] = {
"44 MHz",
"52 MHz",
"52 MHz",
"44 MHz",
};
tuner_info("write: byte B 0x%02x\n", buf[1]);
tuner_info(" B0 video mode : %s\n",
(buf[1] & 0x01) ? "video trap" : "sound trap");
tuner_info(" B1 auto mute fm : %s\n",
(buf[1] & 0x02) ? "yes" : "no");
tuner_info(" B2 carrier mode : %s\n",
(buf[1] & 0x04) ? "QSS" : "Intercarrier");
tuner_info(" B3-4 tv sound/radio : %s\n",
sound[(buf[1] & 0x18) >> 3]);
tuner_info(" B5 force mute audio: %s\n",
(buf[1] & 0x20) ? "yes" : "no");
tuner_info(" B6 output port 1 : %s\n",
(buf[1] & 0x40) ? "high (inactive)" : "low (active)");
tuner_info(" B7 output port 2 : %s\n",
(buf[1] & 0x80) ? "high (inactive)" : "low (active)");
tuner_info("write: byte C 0x%02x\n", buf[2]);
tuner_info(" C0-4 top adjustment : %s dB\n",
adjust[buf[2] & 0x1f]);
tuner_info(" C5-6 de-emphasis : %s\n",
deemph[(buf[2] & 0x60) >> 5]);
tuner_info(" C7 audio gain : %s\n",
(buf[2] & 0x80) ? "-6" : "0");
tuner_info("write: byte E 0x%02x\n", buf[3]);
tuner_info(" E0-1 sound carrier : %s\n",
carrier[(buf[3] & 0x03)]);
tuner_info(" E6 l pll gating : %s\n",
(buf[3] & 0x40) ? "36" : "13");
if (buf[1] & 0x08) {
/* radio */
tuner_info(" E2-4 video if : %s\n",
rif[(buf[3] & 0x0c) >> 2]);
tuner_info(" E7 vif agc output : %s\n",
(buf[3] & 0x80)
? ((buf[3] & 0x10) ? "fm-agc radio" :
"sif-agc radio")
: "fm radio carrier afc");
} else {
/* video */
tuner_info(" E2-4 video if : %s\n",
vif[(buf[3] & 0x1c) >> 2]);
tuner_info(" E5 tuner gain : %s\n",
(buf[3] & 0x80)
? ((buf[3] & 0x20) ? "external" : "normal")
: ((buf[3] & 0x20) ? "minimum" : "normal"));
tuner_info(" E7 vif agc output : %s\n",
(buf[3] & 0x80) ? ((buf[3] & 0x20)
? "pin3 port, pin22 vif agc out"
: "pin22 port, pin3 vif acg ext in")
: "pin3+pin22 port");
}
tuner_info("--\n");
}
/* ---------------------------------------------------------------------- */
static int tda9887_set_tvnorm(struct dvb_frontend *fe)
{
struct tda9887_priv *priv = fe->analog_demod_priv;
struct tvnorm *norm = NULL;
char *buf = priv->data;
int i;
if (priv->mode == V4L2_TUNER_RADIO) {
if (priv->audmode == V4L2_TUNER_MODE_MONO)
norm = &radio_mono;
else
norm = &radio_stereo;
} else {
for (i = 0; i < ARRAY_SIZE(tvnorms); i++) {
if (tvnorms[i].std & priv->std) {
norm = tvnorms+i;
break;
}
}
}
if (NULL == norm) {
tuner_dbg("Unsupported tvnorm entry - audio muted\n");
return -1;
}
tuner_dbg("configure for: %s\n", norm->name);
buf[1] = norm->b;
buf[2] = norm->c;
buf[3] = norm->e;
return 0;
}
static unsigned int port1 = UNSET;
static unsigned int port2 = UNSET;
static unsigned int qss = UNSET;
static unsigned int adjust = UNSET;
module_param(port1, int, 0644);
module_param(port2, int, 0644);
module_param(qss, int, 0644);
module_param(adjust, int, 0644);
static int tda9887_set_insmod(struct dvb_frontend *fe)
{
struct tda9887_priv *priv = fe->analog_demod_priv;
char *buf = priv->data;
if (UNSET != port1) {
if (port1)
buf[1] |= cOutputPort1Inactive;
else
buf[1] &= ~cOutputPort1Inactive;
}
if (UNSET != port2) {
if (port2)
buf[1] |= cOutputPort2Inactive;
else
buf[1] &= ~cOutputPort2Inactive;
}
if (UNSET != qss) {
if (qss)
buf[1] |= cQSS;
else
buf[1] &= ~cQSS;
}
if (adjust < 0x20) {
buf[2] &= ~cTopMask;
buf[2] |= adjust;
}
return 0;
}
static int tda9887_do_config(struct dvb_frontend *fe)
{
struct tda9887_priv *priv = fe->analog_demod_priv;
char *buf = priv->data;
if (priv->config & TDA9887_PORT1_ACTIVE)
buf[1] &= ~cOutputPort1Inactive;
if (priv->config & TDA9887_PORT1_INACTIVE)
buf[1] |= cOutputPort1Inactive;
if (priv->config & TDA9887_PORT2_ACTIVE)
buf[1] &= ~cOutputPort2Inactive;
if (priv->config & TDA9887_PORT2_INACTIVE)
buf[1] |= cOutputPort2Inactive;
if (priv->config & TDA9887_QSS)
buf[1] |= cQSS;
if (priv->config & TDA9887_INTERCARRIER)
buf[1] &= ~cQSS;
if (priv->config & TDA9887_AUTOMUTE)
buf[1] |= cAutoMuteFmActive;
if (priv->config & TDA9887_DEEMPHASIS_MASK) {
buf[2] &= ~0x60;
switch (priv->config & TDA9887_DEEMPHASIS_MASK) {
case TDA9887_DEEMPHASIS_NONE:
buf[2] |= cDeemphasisOFF;
break;
case TDA9887_DEEMPHASIS_50:
buf[2] |= cDeemphasisON | cDeemphasis50;
break;
case TDA9887_DEEMPHASIS_75:
buf[2] |= cDeemphasisON | cDeemphasis75;
break;
}
}
if (priv->config & TDA9887_TOP_SET) {
buf[2] &= ~cTopMask;
buf[2] |= (priv->config >> 8) & cTopMask;
}
if ((priv->config & TDA9887_INTERCARRIER_NTSC) &&
(priv->std & V4L2_STD_NTSC))
buf[1] &= ~cQSS;
if (priv->config & TDA9887_GATING_18)
buf[3] &= ~cGating_36;
if (priv->mode == V4L2_TUNER_RADIO) {
if (priv->config & TDA9887_RIF_41_3) {
buf[3] &= ~cVideoIFMask;
buf[3] |= cRadioIF_41_30;
}
if (priv->config & TDA9887_GAIN_NORMAL)
buf[3] &= ~cTunerGainLow;
}
return 0;
}
/* ---------------------------------------------------------------------- */
static int tda9887_status(struct dvb_frontend *fe)
{
struct tda9887_priv *priv = fe->analog_demod_priv;
unsigned char buf[1];
int rc;
memset(buf,0,sizeof(buf));
if (1 != (rc = tuner_i2c_xfer_recv(&priv->i2c_props,buf,1)))
tuner_info("i2c i/o error: rc == %d (should be 1)\n", rc);
dump_read_message(fe, buf);
return 0;
}
static void tda9887_configure(struct dvb_frontend *fe)
{
struct tda9887_priv *priv = fe->analog_demod_priv;
int rc;
memset(priv->data,0,sizeof(priv->data));
tda9887_set_tvnorm(fe);
/* A note on the port settings:
These settings tend to depend on the specifics of the board.
By default they are set to inactive (bit value 1) by this driver,
overwriting any changes made by the tvnorm. This means that it
is the responsibility of the module using the tda9887 to set
these values in case of changes in the tvnorm.
In many cases port 2 should be made active (0) when selecting
SECAM-L, and port 2 should remain inactive (1) for SECAM-L'.
For the other standards the tda9887 application note says that
the ports should be set to active (0), but, again, that may
differ depending on the precise hardware configuration.
*/
priv->data[1] |= cOutputPort1Inactive;
priv->data[1] |= cOutputPort2Inactive;
tda9887_do_config(fe);
tda9887_set_insmod(fe);
if (priv->standby)
priv->data[1] |= cForcedMuteAudioON;
tuner_dbg("writing: b=0x%02x c=0x%02x e=0x%02x\n",
priv->data[1], priv->data[2], priv->data[3]);
if (debug > 1)
dump_write_message(fe, priv->data);
if (4 != (rc = tuner_i2c_xfer_send(&priv->i2c_props,priv->data,4)))
tuner_info("i2c i/o error: rc == %d (should be 4)\n", rc);
if (debug > 2) {
msleep_interruptible(1000);
tda9887_status(fe);
}
}
/* ---------------------------------------------------------------------- */
static void tda9887_tuner_status(struct dvb_frontend *fe)
{
struct tda9887_priv *priv = fe->analog_demod_priv;
tuner_info("Data bytes: b=0x%02x c=0x%02x e=0x%02x\n",
priv->data[1], priv->data[2], priv->data[3]);
}
static int tda9887_get_afc(struct dvb_frontend *fe)
{
struct tda9887_priv *priv = fe->analog_demod_priv;
static int AFC_BITS_2_kHz[] = {
-12500, -37500, -62500, -97500,
-112500, -137500, -162500, -187500,
187500, 162500, 137500, 112500,
97500 , 62500, 37500 , 12500
};
int afc=0;
__u8 reg = 0;
if (1 == tuner_i2c_xfer_recv(&priv->i2c_props,®,1))
afc = AFC_BITS_2_kHz[(reg>>1)&0x0f];
return afc;
}
static void tda9887_standby(struct dvb_frontend *fe)
{
struct tda9887_priv *priv = fe->analog_demod_priv;
priv->standby = true;
tda9887_configure(fe);
}
static void tda9887_set_params(struct dvb_frontend *fe,
struct analog_parameters *params)
{
struct tda9887_priv *priv = fe->analog_demod_priv;
priv->standby = false;
priv->mode = params->mode;
priv->audmode = params->audmode;
priv->std = params->std;
tda9887_configure(fe);
}
static int tda9887_set_config(struct dvb_frontend *fe, void *priv_cfg)
{
struct tda9887_priv *priv = fe->analog_demod_priv;
priv->config = *(unsigned int *)priv_cfg;
tda9887_configure(fe);
return 0;
}
static void tda9887_release(struct dvb_frontend *fe)
{
struct tda9887_priv *priv = fe->analog_demod_priv;
mutex_lock(&tda9887_list_mutex);
if (priv)
hybrid_tuner_release_state(priv);
mutex_unlock(&tda9887_list_mutex);
fe->analog_demod_priv = NULL;
}
static struct analog_demod_ops tda9887_ops = {
.info = {
.name = "tda9887",
},
.set_params = tda9887_set_params,
.standby = tda9887_standby,
.tuner_status = tda9887_tuner_status,
.get_afc = tda9887_get_afc,
.release = tda9887_release,
.set_config = tda9887_set_config,
};
struct dvb_frontend *tda9887_attach(struct dvb_frontend *fe,
struct i2c_adapter *i2c_adap,
u8 i2c_addr)
{
struct tda9887_priv *priv = NULL;
int instance;
mutex_lock(&tda9887_list_mutex);
instance = hybrid_tuner_request_state(struct tda9887_priv, priv,
hybrid_tuner_instance_list,
i2c_adap, i2c_addr, "tda9887");
switch (instance) {
case 0:
mutex_unlock(&tda9887_list_mutex);
return NULL;
case 1:
fe->analog_demod_priv = priv;
priv->standby = true;
tuner_info("tda988[5/6/7] found\n");
break;
default:
fe->analog_demod_priv = priv;
break;
}
mutex_unlock(&tda9887_list_mutex);
memcpy(&fe->ops.analog_ops, &tda9887_ops,
sizeof(struct analog_demod_ops));
return fe;
}
EXPORT_SYMBOL_GPL(tda9887_attach);
MODULE_LICENSE("GPL");
/*
* Overrides for Emacs so that we follow Linus's tabbing style.
* ---------------------------------------------------------------------------
* Local variables:
* c-basic-offset: 8
* End:
*/
| gpl-2.0 |
ptmr3/GalaxyS4_Kernel | drivers/media/dvb/bt8xx/bt878.c | 8030 | 15744 | /*
* bt878.c: part of the driver for the Pinnacle PCTV Sat DVB PCI card
*
* Copyright (C) 2002 Peter Hettkamp <peter.hettkamp@htp-tel.de>
*
* large parts based on the bttv driver
* Copyright (C) 1996,97,98 Ralph Metzler (rjkm@metzlerbros.de)
* & Marcus Metzler (mocm@metzlerbros.de)
* (c) 1999,2000 Gerd Knorr <kraxel@goldbach.in-berlin.de>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* Or, point your browser to http://www.gnu.org/copyleft/gpl.html
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/pci.h>
#include <asm/io.h>
#include <linux/ioport.h>
#include <asm/pgtable.h>
#include <asm/page.h>
#include <linux/types.h>
#include <linux/interrupt.h>
#include <linux/kmod.h>
#include <linux/vmalloc.h>
#include <linux/init.h>
#include "dmxdev.h"
#include "dvbdev.h"
#include "bt878.h"
#include "dst_priv.h"
/**************************************/
/* Miscellaneous utility definitions */
/**************************************/
static unsigned int bt878_verbose = 1;
static unsigned int bt878_debug;
module_param_named(verbose, bt878_verbose, int, 0444);
MODULE_PARM_DESC(verbose,
"verbose startup messages, default is 1 (yes)");
module_param_named(debug, bt878_debug, int, 0644);
MODULE_PARM_DESC(debug, "Turn on/off debugging, default is 0 (off).");
int bt878_num;
struct bt878 bt878[BT878_MAX];
EXPORT_SYMBOL(bt878_num);
EXPORT_SYMBOL(bt878);
#define btwrite(dat,adr) bmtwrite((dat), (bt->bt878_mem+(adr)))
#define btread(adr) bmtread(bt->bt878_mem+(adr))
#define btand(dat,adr) btwrite((dat) & btread(adr), adr)
#define btor(dat,adr) btwrite((dat) | btread(adr), adr)
#define btaor(dat,mask,adr) btwrite((dat) | ((mask) & btread(adr)), adr)
#if defined(dprintk)
#undef dprintk
#endif
#define dprintk(fmt, arg...) \
do { \
if (bt878_debug) \
printk(KERN_DEBUG fmt, ##arg); \
} while (0)
static void bt878_mem_free(struct bt878 *bt)
{
if (bt->buf_cpu) {
pci_free_consistent(bt->dev, bt->buf_size, bt->buf_cpu,
bt->buf_dma);
bt->buf_cpu = NULL;
}
if (bt->risc_cpu) {
pci_free_consistent(bt->dev, bt->risc_size, bt->risc_cpu,
bt->risc_dma);
bt->risc_cpu = NULL;
}
}
static int bt878_mem_alloc(struct bt878 *bt)
{
if (!bt->buf_cpu) {
bt->buf_size = 128 * 1024;
bt->buf_cpu =
pci_alloc_consistent(bt->dev, bt->buf_size,
&bt->buf_dma);
if (!bt->buf_cpu)
return -ENOMEM;
memset(bt->buf_cpu, 0, bt->buf_size);
}
if (!bt->risc_cpu) {
bt->risc_size = PAGE_SIZE;
bt->risc_cpu =
pci_alloc_consistent(bt->dev, bt->risc_size,
&bt->risc_dma);
if (!bt->risc_cpu) {
bt878_mem_free(bt);
return -ENOMEM;
}
memset(bt->risc_cpu, 0, bt->risc_size);
}
return 0;
}
/* RISC instructions */
#define RISC_WRITE (0x01 << 28)
#define RISC_JUMP (0x07 << 28)
#define RISC_SYNC (0x08 << 28)
/* RISC bits */
#define RISC_WR_SOL (1 << 27)
#define RISC_WR_EOL (1 << 26)
#define RISC_IRQ (1 << 24)
#define RISC_STATUS(status) ((((~status) & 0x0F) << 20) | ((status & 0x0F) << 16))
#define RISC_SYNC_RESYNC (1 << 15)
#define RISC_SYNC_FM1 0x06
#define RISC_SYNC_VRO 0x0C
#define RISC_FLUSH() bt->risc_pos = 0
#define RISC_INSTR(instr) bt->risc_cpu[bt->risc_pos++] = cpu_to_le32(instr)
static int bt878_make_risc(struct bt878 *bt)
{
bt->block_bytes = bt->buf_size >> 4;
bt->block_count = 1 << 4;
bt->line_bytes = bt->block_bytes;
bt->line_count = bt->block_count;
while (bt->line_bytes > 4095) {
bt->line_bytes >>= 1;
bt->line_count <<= 1;
}
if (bt->line_count > 255) {
printk(KERN_ERR "bt878: buffer size error!\n");
return -EINVAL;
}
return 0;
}
static void bt878_risc_program(struct bt878 *bt, u32 op_sync_orin)
{
u32 buf_pos = 0;
u32 line;
RISC_FLUSH();
RISC_INSTR(RISC_SYNC | RISC_SYNC_FM1 | op_sync_orin);
RISC_INSTR(0);
dprintk("bt878: risc len lines %u, bytes per line %u\n",
bt->line_count, bt->line_bytes);
for (line = 0; line < bt->line_count; line++) {
// At the beginning of every block we issue an IRQ with previous (finished) block number set
if (!(buf_pos % bt->block_bytes))
RISC_INSTR(RISC_WRITE | RISC_WR_SOL | RISC_WR_EOL |
RISC_IRQ |
RISC_STATUS(((buf_pos /
bt->block_bytes) +
(bt->block_count -
1)) %
bt->block_count) | bt->
line_bytes);
else
RISC_INSTR(RISC_WRITE | RISC_WR_SOL | RISC_WR_EOL |
bt->line_bytes);
RISC_INSTR(bt->buf_dma + buf_pos);
buf_pos += bt->line_bytes;
}
RISC_INSTR(RISC_SYNC | op_sync_orin | RISC_SYNC_VRO);
RISC_INSTR(0);
RISC_INSTR(RISC_JUMP);
RISC_INSTR(bt->risc_dma);
btwrite((bt->line_count << 16) | bt->line_bytes, BT878_APACK_LEN);
}
/*****************************/
/* Start/Stop grabbing funcs */
/*****************************/
void bt878_start(struct bt878 *bt, u32 controlreg, u32 op_sync_orin,
u32 irq_err_ignore)
{
u32 int_mask;
dprintk("bt878 debug: bt878_start (ctl=%8.8x)\n", controlreg);
/* complete the writing of the risc dma program now we have
* the card specifics
*/
bt878_risc_program(bt, op_sync_orin);
controlreg &= ~0x1f;
controlreg |= 0x1b;
btwrite(bt->risc_dma, BT878_ARISC_START);
/* original int mask had :
* 6 2 8 4 0
* 1111 1111 1000 0000 0000
* SCERR|OCERR|PABORT|RIPERR|FDSR|FTRGT|FBUS|RISCI
* Hacked for DST to:
* SCERR | OCERR | FDSR | FTRGT | FBUS | RISCI
*/
int_mask = BT878_ASCERR | BT878_AOCERR | BT878_APABORT |
BT878_ARIPERR | BT878_APPERR | BT878_AFDSR | BT878_AFTRGT |
BT878_AFBUS | BT878_ARISCI;
/* ignore pesky bits */
int_mask &= ~irq_err_ignore;
btwrite(int_mask, BT878_AINT_MASK);
btwrite(controlreg, BT878_AGPIO_DMA_CTL);
}
void bt878_stop(struct bt878 *bt)
{
u32 stat;
int i = 0;
dprintk("bt878 debug: bt878_stop\n");
btwrite(0, BT878_AINT_MASK);
btand(~0x13, BT878_AGPIO_DMA_CTL);
do {
stat = btread(BT878_AINT_STAT);
if (!(stat & BT878_ARISC_EN))
break;
i++;
} while (i < 500);
dprintk("bt878(%d) debug: bt878_stop, i=%d, stat=0x%8.8x\n",
bt->nr, i, stat);
}
EXPORT_SYMBOL(bt878_start);
EXPORT_SYMBOL(bt878_stop);
/*****************************/
/* Interrupt service routine */
/*****************************/
static irqreturn_t bt878_irq(int irq, void *dev_id)
{
u32 stat, astat, mask;
int count;
struct bt878 *bt;
bt = (struct bt878 *) dev_id;
count = 0;
while (1) {
stat = btread(BT878_AINT_STAT);
mask = btread(BT878_AINT_MASK);
if (!(astat = (stat & mask)))
return IRQ_NONE; /* this interrupt is not for me */
/* dprintk("bt878(%d) debug: irq count %d, stat 0x%8.8x, mask 0x%8.8x\n",bt->nr,count,stat,mask); */
btwrite(astat, BT878_AINT_STAT); /* try to clear interrupt condition */
if (astat & (BT878_ASCERR | BT878_AOCERR)) {
if (bt878_verbose) {
printk(KERN_INFO
"bt878(%d): irq%s%s risc_pc=%08x\n",
bt->nr,
(astat & BT878_ASCERR) ? " SCERR" :
"",
(astat & BT878_AOCERR) ? " OCERR" :
"", btread(BT878_ARISC_PC));
}
}
if (astat & (BT878_APABORT | BT878_ARIPERR | BT878_APPERR)) {
if (bt878_verbose) {
printk(KERN_INFO
"bt878(%d): irq%s%s%s risc_pc=%08x\n",
bt->nr,
(astat & BT878_APABORT) ? " PABORT" :
"",
(astat & BT878_ARIPERR) ? " RIPERR" :
"",
(astat & BT878_APPERR) ? " PPERR" :
"", btread(BT878_ARISC_PC));
}
}
if (astat & (BT878_AFDSR | BT878_AFTRGT | BT878_AFBUS)) {
if (bt878_verbose) {
printk(KERN_INFO
"bt878(%d): irq%s%s%s risc_pc=%08x\n",
bt->nr,
(astat & BT878_AFDSR) ? " FDSR" : "",
(astat & BT878_AFTRGT) ? " FTRGT" :
"",
(astat & BT878_AFBUS) ? " FBUS" : "",
btread(BT878_ARISC_PC));
}
}
if (astat & BT878_ARISCI) {
bt->finished_block = (stat & BT878_ARISCS) >> 28;
tasklet_schedule(&bt->tasklet);
break;
}
count++;
if (count > 20) {
btwrite(0, BT878_AINT_MASK);
printk(KERN_ERR
"bt878(%d): IRQ lockup, cleared int mask\n",
bt->nr);
break;
}
}
return IRQ_HANDLED;
}
int
bt878_device_control(struct bt878 *bt, unsigned int cmd, union dst_gpio_packet *mp)
{
int retval;
retval = 0;
if (mutex_lock_interruptible(&bt->gpio_lock))
return -ERESTARTSYS;
/* special gpio signal */
switch (cmd) {
case DST_IG_ENABLE:
// dprintk("dvb_bt8xx: dst enable mask 0x%02x enb 0x%02x \n", mp->dstg.enb.mask, mp->dstg.enb.enable);
retval = bttv_gpio_enable(bt->bttv_nr,
mp->enb.mask,
mp->enb.enable);
break;
case DST_IG_WRITE:
// dprintk("dvb_bt8xx: dst write gpio mask 0x%02x out 0x%02x\n", mp->dstg.outp.mask, mp->dstg.outp.highvals);
retval = bttv_write_gpio(bt->bttv_nr,
mp->outp.mask,
mp->outp.highvals);
break;
case DST_IG_READ:
/* read */
retval = bttv_read_gpio(bt->bttv_nr, &mp->rd.value);
// dprintk("dvb_bt8xx: dst read gpio 0x%02x\n", (unsigned)mp->dstg.rd.value);
break;
case DST_IG_TS:
/* Set packet size */
bt->TS_Size = mp->psize;
break;
default:
retval = -EINVAL;
break;
}
mutex_unlock(&bt->gpio_lock);
return retval;
}
EXPORT_SYMBOL(bt878_device_control);
#define BROOKTREE_878_DEVICE(vend, dev, name) \
{ \
.vendor = PCI_VENDOR_ID_BROOKTREE, \
.device = PCI_DEVICE_ID_BROOKTREE_878, \
.subvendor = (vend), .subdevice = (dev), \
.driver_data = (unsigned long) name \
}
static struct pci_device_id bt878_pci_tbl[] __devinitdata = {
BROOKTREE_878_DEVICE(0x0071, 0x0101, "Nebula Electronics DigiTV"),
BROOKTREE_878_DEVICE(0x1461, 0x0761, "AverMedia AverTV DVB-T 761"),
BROOKTREE_878_DEVICE(0x11bd, 0x001c, "Pinnacle PCTV Sat"),
BROOKTREE_878_DEVICE(0x11bd, 0x0026, "Pinnacle PCTV SAT CI"),
BROOKTREE_878_DEVICE(0x1822, 0x0001, "Twinhan VisionPlus DVB"),
BROOKTREE_878_DEVICE(0x270f, 0xfc00,
"ChainTech digitop DST-1000 DVB-S"),
BROOKTREE_878_DEVICE(0x1461, 0x0771, "AVermedia AverTV DVB-T 771"),
BROOKTREE_878_DEVICE(0x18ac, 0xdb10, "DViCO FusionHDTV DVB-T Lite"),
BROOKTREE_878_DEVICE(0x18ac, 0xdb11, "Ultraview DVB-T Lite"),
BROOKTREE_878_DEVICE(0x18ac, 0xd500, "DViCO FusionHDTV 5 Lite"),
BROOKTREE_878_DEVICE(0x7063, 0x2000, "pcHDTV HD-2000 TV"),
BROOKTREE_878_DEVICE(0x1822, 0x0026, "DNTV Live! Mini"),
{ }
};
MODULE_DEVICE_TABLE(pci, bt878_pci_tbl);
static const char * __devinit card_name(const struct pci_device_id *id)
{
return id->driver_data ? (const char *)id->driver_data : "Unknown";
}
/***********************/
/* PCI device handling */
/***********************/
static int __devinit bt878_probe(struct pci_dev *dev,
const struct pci_device_id *pci_id)
{
int result = 0;
unsigned char lat;
struct bt878 *bt;
#if defined(__powerpc__)
unsigned int cmd;
#endif
unsigned int cardid;
printk(KERN_INFO "bt878: Bt878 AUDIO function found (%d).\n",
bt878_num);
if (bt878_num >= BT878_MAX) {
printk(KERN_ERR "bt878: Too many devices inserted\n");
result = -ENOMEM;
goto fail0;
}
if (pci_enable_device(dev))
return -EIO;
cardid = dev->subsystem_device << 16;
cardid |= dev->subsystem_vendor;
printk(KERN_INFO "%s: card id=[0x%x],[ %s ] has DVB functions.\n",
__func__, cardid, card_name(pci_id));
bt = &bt878[bt878_num];
bt->dev = dev;
bt->nr = bt878_num;
bt->shutdown = 0;
bt->id = dev->device;
bt->irq = dev->irq;
bt->bt878_adr = pci_resource_start(dev, 0);
if (!request_mem_region(pci_resource_start(dev, 0),
pci_resource_len(dev, 0), "bt878")) {
result = -EBUSY;
goto fail0;
}
bt->revision = dev->revision;
pci_read_config_byte(dev, PCI_LATENCY_TIMER, &lat);
printk(KERN_INFO "bt878(%d): Bt%x (rev %d) at %02x:%02x.%x, ",
bt878_num, bt->id, bt->revision, dev->bus->number,
PCI_SLOT(dev->devfn), PCI_FUNC(dev->devfn));
printk("irq: %d, latency: %d, memory: 0x%lx\n",
bt->irq, lat, bt->bt878_adr);
#if defined(__powerpc__)
/* on OpenFirmware machines (PowerMac at least), PCI memory cycle */
/* response on cards with no firmware is not enabled by OF */
pci_read_config_dword(dev, PCI_COMMAND, &cmd);
cmd = (cmd | PCI_COMMAND_MEMORY);
pci_write_config_dword(dev, PCI_COMMAND, cmd);
#endif
#ifdef __sparc__
bt->bt878_mem = (unsigned char *) bt->bt878_adr;
#else
bt->bt878_mem = ioremap(bt->bt878_adr, 0x1000);
#endif
/* clear interrupt mask */
btwrite(0, BT848_INT_MASK);
result = request_irq(bt->irq, bt878_irq,
IRQF_SHARED | IRQF_DISABLED, "bt878",
(void *) bt);
if (result == -EINVAL) {
printk(KERN_ERR "bt878(%d): Bad irq number or handler\n",
bt878_num);
goto fail1;
}
if (result == -EBUSY) {
printk(KERN_ERR
"bt878(%d): IRQ %d busy, change your PnP config in BIOS\n",
bt878_num, bt->irq);
goto fail1;
}
if (result < 0)
goto fail1;
pci_set_master(dev);
pci_set_drvdata(dev, bt);
if ((result = bt878_mem_alloc(bt))) {
printk(KERN_ERR "bt878: failed to allocate memory!\n");
goto fail2;
}
bt878_make_risc(bt);
btwrite(0, BT878_AINT_MASK);
bt878_num++;
return 0;
fail2:
free_irq(bt->irq, bt);
fail1:
release_mem_region(pci_resource_start(bt->dev, 0),
pci_resource_len(bt->dev, 0));
fail0:
pci_disable_device(dev);
return result;
}
static void __devexit bt878_remove(struct pci_dev *pci_dev)
{
u8 command;
struct bt878 *bt = pci_get_drvdata(pci_dev);
if (bt878_verbose)
printk(KERN_INFO "bt878(%d): unloading\n", bt->nr);
/* turn off all capturing, DMA and IRQs */
btand(~0x13, BT878_AGPIO_DMA_CTL);
/* first disable interrupts before unmapping the memory! */
btwrite(0, BT878_AINT_MASK);
btwrite(~0U, BT878_AINT_STAT);
/* disable PCI bus-mastering */
pci_read_config_byte(bt->dev, PCI_COMMAND, &command);
/* Should this be &=~ ?? */
command &= ~PCI_COMMAND_MASTER;
pci_write_config_byte(bt->dev, PCI_COMMAND, command);
free_irq(bt->irq, bt);
printk(KERN_DEBUG "bt878_mem: 0x%p.\n", bt->bt878_mem);
if (bt->bt878_mem)
iounmap(bt->bt878_mem);
release_mem_region(pci_resource_start(bt->dev, 0),
pci_resource_len(bt->dev, 0));
/* wake up any waiting processes
because shutdown flag is set, no new processes (in this queue)
are expected
*/
bt->shutdown = 1;
bt878_mem_free(bt);
pci_set_drvdata(pci_dev, NULL);
pci_disable_device(pci_dev);
return;
}
static struct pci_driver bt878_pci_driver = {
.name = "bt878",
.id_table = bt878_pci_tbl,
.probe = bt878_probe,
.remove = __devexit_p(bt878_remove),
};
/*******************************/
/* Module management functions */
/*******************************/
static int __init bt878_init_module(void)
{
bt878_num = 0;
printk(KERN_INFO "bt878: AUDIO driver version %d.%d.%d loaded\n",
(BT878_VERSION_CODE >> 16) & 0xff,
(BT878_VERSION_CODE >> 8) & 0xff,
BT878_VERSION_CODE & 0xff);
return pci_register_driver(&bt878_pci_driver);
}
static void __exit bt878_cleanup_module(void)
{
pci_unregister_driver(&bt878_pci_driver);
}
module_init(bt878_init_module);
module_exit(bt878_cleanup_module);
MODULE_LICENSE("GPL");
/*
* Local variables:
* c-basic-offset: 8
* End:
*/
| gpl-2.0 |
d8ahazard/shooter-cm9-deviltoast | drivers/staging/comedi/drivers/mpc8260cpm.c | 8286 | 4459 | /*
comedi/drivers/mpc8260.c
driver for digital I/O pins on the MPC 8260 CPM module
COMEDI - Linux Control and Measurement Device Interface
Copyright (C) 2000,2001 David A. Schleef <ds@schleef.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
Driver: mpc8260cpm
Description: MPC8260 CPM module generic digital I/O lines
Devices: [Motorola] MPC8260 CPM (mpc8260cpm)
Author: ds
Status: experimental
Updated: Sat, 16 Mar 2002 17:34:48 -0800
This driver is specific to the Motorola MPC8260 processor, allowing
you to access the processor's generic digital I/O lines.
It is apparently missing some code.
*/
#include "../comedidev.h"
extern unsigned long mpc8260_dio_reserved[4];
struct mpc8260cpm_private {
int data;
};
#define devpriv ((struct mpc8260cpm_private *)dev->private)
static int mpc8260cpm_attach(struct comedi_device *dev,
struct comedi_devconfig *it);
static int mpc8260cpm_detach(struct comedi_device *dev);
static struct comedi_driver driver_mpc8260cpm = {
.driver_name = "mpc8260cpm",
.module = THIS_MODULE,
.attach = mpc8260cpm_attach,
.detach = mpc8260cpm_detach,
};
static int __init driver_mpc8260cpm_init_module(void)
{
return comedi_driver_register(&driver_mpc8260cpm);
}
static void __exit driver_mpc8260cpm_cleanup_module(void)
{
comedi_driver_unregister(&driver_mpc8260cpm);
}
module_init(driver_mpc8260cpm_init_module);
module_exit(driver_mpc8260cpm_cleanup_module);
static int mpc8260cpm_dio_config(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int mpc8260cpm_dio_bits(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int mpc8260cpm_attach(struct comedi_device *dev,
struct comedi_devconfig *it)
{
struct comedi_subdevice *s;
int i;
printk("comedi%d: mpc8260cpm: ", dev->minor);
dev->board_ptr = mpc8260cpm_boards + dev->board;
dev->board_name = thisboard->name;
if (alloc_private(dev, sizeof(struct mpc8260cpm_private)) < 0)
return -ENOMEM;
if (alloc_subdevices(dev, 4) < 0)
return -ENOMEM;
for (i = 0; i < 4; i++) {
s = dev->subdevices + i;
s->type = COMEDI_SUBD_DIO;
s->subdev_flags = SDF_READABLE | SDF_WRITABLE;
s->n_chan = 32;
s->maxdata = 1;
s->range_table = &range_digital;
s->insn_config = mpc8260cpm_dio_config;
s->insn_bits = mpc8260cpm_dio_bits;
}
return 1;
}
static int mpc8260cpm_detach(struct comedi_device *dev)
{
printk("comedi%d: mpc8260cpm: remove\n", dev->minor);
return 0;
}
static unsigned long *cpm_pdat(int port)
{
switch (port) {
case 0:
return &io->iop_pdata;
case 1:
return &io->iop_pdatb;
case 2:
return &io->iop_pdatc;
case 3:
return &io->iop_pdatd;
}
}
static int mpc8260cpm_dio_config(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int n;
unsigned int d;
unsigned int mask;
int port;
port = (int)s->private;
mask = 1 << CR_CHAN(insn->chanspec);
if (mask & cpm_reserved_bits[port]) {
return -EINVAL;
}
switch (data[0]) {
case INSN_CONFIG_DIO_OUTPUT:
s->io_bits |= mask;
break;
case INSN_CONFIG_DIO_INPUT:
s->io_bits &= ~mask;
break;
case INSN_CONFIG_DIO_QUERY:
data[1] = (s->io_bits & mask) ? COMEDI_OUTPUT : COMEDI_INPUT;
return insn->n;
break;
default:
return -EINVAL;
}
switch (port) {
case 0:
return &io->iop_pdira;
case 1:
return &io->iop_pdirb;
case 2:
return &io->iop_pdirc;
case 3:
return &io->iop_pdird;
}
return 1;
}
static int mpc8260cpm_dio_bits(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int port;
unsigned long *p;
p = cpm_pdat((int)s->private);
return 2;
}
| gpl-2.0 |
Evervolv/android_kernel_htc_msm7x30 | arch/arm/mach-omap1/i2c.c | 9054 | 1025 | /*
* Helper module for board specific I2C bus registration
*
* Copyright (C) 2009 Nokia Corporation.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <plat/i2c.h>
#include <plat/mux.h>
#include <plat/cpu.h>
void __init omap1_i2c_mux_pins(int bus_id)
{
if (cpu_is_omap7xx()) {
omap_cfg_reg(I2C_7XX_SDA);
omap_cfg_reg(I2C_7XX_SCL);
} else {
omap_cfg_reg(I2C_SDA);
omap_cfg_reg(I2C_SCL);
}
}
| gpl-2.0 |
LeonNardella/philips-pta-01 | arch/x86/mm/pf_in.c | 12126 | 10785 | /*
* Fault Injection Test harness (FI)
* Copyright (C) Intel Crop.
*
* 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.
*
*/
/* Id: pf_in.c,v 1.1.1.1 2002/11/12 05:56:32 brlock Exp
* Copyright by Intel Crop., 2002
* Louis Zhuang (louis.zhuang@intel.com)
*
* Bjorn Steinbrink (B.Steinbrink@gmx.de), 2007
*/
#include <linux/module.h>
#include <linux/ptrace.h> /* struct pt_regs */
#include "pf_in.h"
#ifdef __i386__
/* IA32 Manual 3, 2-1 */
static unsigned char prefix_codes[] = {
0xF0, 0xF2, 0xF3, 0x2E, 0x36, 0x3E, 0x26, 0x64,
0x65, 0x66, 0x67
};
/* IA32 Manual 3, 3-432*/
static unsigned int reg_rop[] = {
0x8A, 0x8B, 0xB60F, 0xB70F, 0xBE0F, 0xBF0F
};
static unsigned int reg_wop[] = { 0x88, 0x89, 0xAA, 0xAB };
static unsigned int imm_wop[] = { 0xC6, 0xC7 };
/* IA32 Manual 3, 3-432*/
static unsigned int rw8[] = { 0x88, 0x8A, 0xC6, 0xAA };
static unsigned int rw32[] = {
0x89, 0x8B, 0xC7, 0xB60F, 0xB70F, 0xBE0F, 0xBF0F, 0xAB
};
static unsigned int mw8[] = { 0x88, 0x8A, 0xC6, 0xB60F, 0xBE0F, 0xAA };
static unsigned int mw16[] = { 0xB70F, 0xBF0F };
static unsigned int mw32[] = { 0x89, 0x8B, 0xC7, 0xAB };
static unsigned int mw64[] = {};
#else /* not __i386__ */
static unsigned char prefix_codes[] = {
0x66, 0x67, 0x2E, 0x3E, 0x26, 0x64, 0x65, 0x36,
0xF0, 0xF3, 0xF2,
/* REX Prefixes */
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f
};
/* AMD64 Manual 3, Appendix A*/
static unsigned int reg_rop[] = {
0x8A, 0x8B, 0xB60F, 0xB70F, 0xBE0F, 0xBF0F
};
static unsigned int reg_wop[] = { 0x88, 0x89, 0xAA, 0xAB };
static unsigned int imm_wop[] = { 0xC6, 0xC7 };
static unsigned int rw8[] = { 0xC6, 0x88, 0x8A, 0xAA };
static unsigned int rw32[] = {
0xC7, 0x89, 0x8B, 0xB60F, 0xB70F, 0xBE0F, 0xBF0F, 0xAB
};
/* 8 bit only */
static unsigned int mw8[] = { 0xC6, 0x88, 0x8A, 0xB60F, 0xBE0F, 0xAA };
/* 16 bit only */
static unsigned int mw16[] = { 0xB70F, 0xBF0F };
/* 16 or 32 bit */
static unsigned int mw32[] = { 0xC7 };
/* 16, 32 or 64 bit */
static unsigned int mw64[] = { 0x89, 0x8B, 0xAB };
#endif /* not __i386__ */
struct prefix_bits {
unsigned shorted:1;
unsigned enlarged:1;
unsigned rexr:1;
unsigned rex:1;
};
static int skip_prefix(unsigned char *addr, struct prefix_bits *prf)
{
int i;
unsigned char *p = addr;
prf->shorted = 0;
prf->enlarged = 0;
prf->rexr = 0;
prf->rex = 0;
restart:
for (i = 0; i < ARRAY_SIZE(prefix_codes); i++) {
if (*p == prefix_codes[i]) {
if (*p == 0x66)
prf->shorted = 1;
#ifdef __amd64__
if ((*p & 0xf8) == 0x48)
prf->enlarged = 1;
if ((*p & 0xf4) == 0x44)
prf->rexr = 1;
if ((*p & 0xf0) == 0x40)
prf->rex = 1;
#endif
p++;
goto restart;
}
}
return (p - addr);
}
static int get_opcode(unsigned char *addr, unsigned int *opcode)
{
int len;
if (*addr == 0x0F) {
/* 0x0F is extension instruction */
*opcode = *(unsigned short *)addr;
len = 2;
} else {
*opcode = *addr;
len = 1;
}
return len;
}
#define CHECK_OP_TYPE(opcode, array, type) \
for (i = 0; i < ARRAY_SIZE(array); i++) { \
if (array[i] == opcode) { \
rv = type; \
goto exit; \
} \
}
enum reason_type get_ins_type(unsigned long ins_addr)
{
unsigned int opcode;
unsigned char *p;
struct prefix_bits prf;
int i;
enum reason_type rv = OTHERS;
p = (unsigned char *)ins_addr;
p += skip_prefix(p, &prf);
p += get_opcode(p, &opcode);
CHECK_OP_TYPE(opcode, reg_rop, REG_READ);
CHECK_OP_TYPE(opcode, reg_wop, REG_WRITE);
CHECK_OP_TYPE(opcode, imm_wop, IMM_WRITE);
exit:
return rv;
}
#undef CHECK_OP_TYPE
static unsigned int get_ins_reg_width(unsigned long ins_addr)
{
unsigned int opcode;
unsigned char *p;
struct prefix_bits prf;
int i;
p = (unsigned char *)ins_addr;
p += skip_prefix(p, &prf);
p += get_opcode(p, &opcode);
for (i = 0; i < ARRAY_SIZE(rw8); i++)
if (rw8[i] == opcode)
return 1;
for (i = 0; i < ARRAY_SIZE(rw32); i++)
if (rw32[i] == opcode)
return prf.shorted ? 2 : (prf.enlarged ? 8 : 4);
printk(KERN_ERR "mmiotrace: Unknown opcode 0x%02x\n", opcode);
return 0;
}
unsigned int get_ins_mem_width(unsigned long ins_addr)
{
unsigned int opcode;
unsigned char *p;
struct prefix_bits prf;
int i;
p = (unsigned char *)ins_addr;
p += skip_prefix(p, &prf);
p += get_opcode(p, &opcode);
for (i = 0; i < ARRAY_SIZE(mw8); i++)
if (mw8[i] == opcode)
return 1;
for (i = 0; i < ARRAY_SIZE(mw16); i++)
if (mw16[i] == opcode)
return 2;
for (i = 0; i < ARRAY_SIZE(mw32); i++)
if (mw32[i] == opcode)
return prf.shorted ? 2 : 4;
for (i = 0; i < ARRAY_SIZE(mw64); i++)
if (mw64[i] == opcode)
return prf.shorted ? 2 : (prf.enlarged ? 8 : 4);
printk(KERN_ERR "mmiotrace: Unknown opcode 0x%02x\n", opcode);
return 0;
}
/*
* Define register ident in mod/rm byte.
* Note: these are NOT the same as in ptrace-abi.h.
*/
enum {
arg_AL = 0,
arg_CL = 1,
arg_DL = 2,
arg_BL = 3,
arg_AH = 4,
arg_CH = 5,
arg_DH = 6,
arg_BH = 7,
arg_AX = 0,
arg_CX = 1,
arg_DX = 2,
arg_BX = 3,
arg_SP = 4,
arg_BP = 5,
arg_SI = 6,
arg_DI = 7,
#ifdef __amd64__
arg_R8 = 8,
arg_R9 = 9,
arg_R10 = 10,
arg_R11 = 11,
arg_R12 = 12,
arg_R13 = 13,
arg_R14 = 14,
arg_R15 = 15
#endif
};
static unsigned char *get_reg_w8(int no, int rex, struct pt_regs *regs)
{
unsigned char *rv = NULL;
switch (no) {
case arg_AL:
rv = (unsigned char *)®s->ax;
break;
case arg_BL:
rv = (unsigned char *)®s->bx;
break;
case arg_CL:
rv = (unsigned char *)®s->cx;
break;
case arg_DL:
rv = (unsigned char *)®s->dx;
break;
#ifdef __amd64__
case arg_R8:
rv = (unsigned char *)®s->r8;
break;
case arg_R9:
rv = (unsigned char *)®s->r9;
break;
case arg_R10:
rv = (unsigned char *)®s->r10;
break;
case arg_R11:
rv = (unsigned char *)®s->r11;
break;
case arg_R12:
rv = (unsigned char *)®s->r12;
break;
case arg_R13:
rv = (unsigned char *)®s->r13;
break;
case arg_R14:
rv = (unsigned char *)®s->r14;
break;
case arg_R15:
rv = (unsigned char *)®s->r15;
break;
#endif
default:
break;
}
if (rv)
return rv;
if (rex) {
/*
* If REX prefix exists, access low bytes of SI etc.
* instead of AH etc.
*/
switch (no) {
case arg_SI:
rv = (unsigned char *)®s->si;
break;
case arg_DI:
rv = (unsigned char *)®s->di;
break;
case arg_BP:
rv = (unsigned char *)®s->bp;
break;
case arg_SP:
rv = (unsigned char *)®s->sp;
break;
default:
break;
}
} else {
switch (no) {
case arg_AH:
rv = 1 + (unsigned char *)®s->ax;
break;
case arg_BH:
rv = 1 + (unsigned char *)®s->bx;
break;
case arg_CH:
rv = 1 + (unsigned char *)®s->cx;
break;
case arg_DH:
rv = 1 + (unsigned char *)®s->dx;
break;
default:
break;
}
}
if (!rv)
printk(KERN_ERR "mmiotrace: Error reg no# %d\n", no);
return rv;
}
static unsigned long *get_reg_w32(int no, struct pt_regs *regs)
{
unsigned long *rv = NULL;
switch (no) {
case arg_AX:
rv = ®s->ax;
break;
case arg_BX:
rv = ®s->bx;
break;
case arg_CX:
rv = ®s->cx;
break;
case arg_DX:
rv = ®s->dx;
break;
case arg_SP:
rv = ®s->sp;
break;
case arg_BP:
rv = ®s->bp;
break;
case arg_SI:
rv = ®s->si;
break;
case arg_DI:
rv = ®s->di;
break;
#ifdef __amd64__
case arg_R8:
rv = ®s->r8;
break;
case arg_R9:
rv = ®s->r9;
break;
case arg_R10:
rv = ®s->r10;
break;
case arg_R11:
rv = ®s->r11;
break;
case arg_R12:
rv = ®s->r12;
break;
case arg_R13:
rv = ®s->r13;
break;
case arg_R14:
rv = ®s->r14;
break;
case arg_R15:
rv = ®s->r15;
break;
#endif
default:
printk(KERN_ERR "mmiotrace: Error reg no# %d\n", no);
}
return rv;
}
unsigned long get_ins_reg_val(unsigned long ins_addr, struct pt_regs *regs)
{
unsigned int opcode;
int reg;
unsigned char *p;
struct prefix_bits prf;
int i;
p = (unsigned char *)ins_addr;
p += skip_prefix(p, &prf);
p += get_opcode(p, &opcode);
for (i = 0; i < ARRAY_SIZE(reg_rop); i++)
if (reg_rop[i] == opcode)
goto do_work;
for (i = 0; i < ARRAY_SIZE(reg_wop); i++)
if (reg_wop[i] == opcode)
goto do_work;
printk(KERN_ERR "mmiotrace: Not a register instruction, opcode "
"0x%02x\n", opcode);
goto err;
do_work:
/* for STOS, source register is fixed */
if (opcode == 0xAA || opcode == 0xAB) {
reg = arg_AX;
} else {
unsigned char mod_rm = *p;
reg = ((mod_rm >> 3) & 0x7) | (prf.rexr << 3);
}
switch (get_ins_reg_width(ins_addr)) {
case 1:
return *get_reg_w8(reg, prf.rex, regs);
case 2:
return *(unsigned short *)get_reg_w32(reg, regs);
case 4:
return *(unsigned int *)get_reg_w32(reg, regs);
#ifdef __amd64__
case 8:
return *(unsigned long *)get_reg_w32(reg, regs);
#endif
default:
printk(KERN_ERR "mmiotrace: Error width# %d\n", reg);
}
err:
return 0;
}
unsigned long get_ins_imm_val(unsigned long ins_addr)
{
unsigned int opcode;
unsigned char mod_rm;
unsigned char mod;
unsigned char *p;
struct prefix_bits prf;
int i;
p = (unsigned char *)ins_addr;
p += skip_prefix(p, &prf);
p += get_opcode(p, &opcode);
for (i = 0; i < ARRAY_SIZE(imm_wop); i++)
if (imm_wop[i] == opcode)
goto do_work;
printk(KERN_ERR "mmiotrace: Not an immediate instruction, opcode "
"0x%02x\n", opcode);
goto err;
do_work:
mod_rm = *p;
mod = mod_rm >> 6;
p++;
switch (mod) {
case 0:
/* if r/m is 5 we have a 32 disp (IA32 Manual 3, Table 2-2) */
/* AMD64: XXX Check for address size prefix? */
if ((mod_rm & 0x7) == 0x5)
p += 4;
break;
case 1:
p += 1;
break;
case 2:
p += 4;
break;
case 3:
default:
printk(KERN_ERR "mmiotrace: not a memory access instruction "
"at 0x%lx, rm_mod=0x%02x\n",
ins_addr, mod_rm);
}
switch (get_ins_reg_width(ins_addr)) {
case 1:
return *(unsigned char *)p;
case 2:
return *(unsigned short *)p;
case 4:
return *(unsigned int *)p;
#ifdef __amd64__
case 8:
return *(unsigned long *)p;
#endif
default:
printk(KERN_ERR "mmiotrace: Error: width.\n");
}
err:
return 0;
}
| gpl-2.0 |
vvtam/vlc | modules/lua/libs/messages.c | 95 | 3207 | /*****************************************************************************
* messages.c
*****************************************************************************
* Copyright (C) 2007-2008 the VideoLAN team
* $Id$
*
* Authors: Antoine Cellerier <dionoea at videolan tod org>
* Pierre d'Herbemont <pdherbemont # videolan.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 Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
/*****************************************************************************
* Preamble
*****************************************************************************/
#ifndef _GNU_SOURCE
# define _GNU_SOURCE
#endif
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <vlc_common.h>
#include <vlc_plugin.h>
#include <vlc_meta.h>
#include "../vlc.h"
#include "../libs.h"
/*****************************************************************************
* Messaging facilities
*****************************************************************************/
static int vlclua_msg_dbg( lua_State *L )
{
int i_top = lua_gettop( L );
vlc_object_t *p_this = vlclua_get_this( L );
int i;
for( i = 1; i <= i_top; i++ )
msg_Dbg( p_this, "%s", luaL_checkstring( L, i ) );
return 0;
}
static int vlclua_msg_warn( lua_State *L )
{
int i_top = lua_gettop( L );
vlc_object_t *p_this = vlclua_get_this( L );
int i;
for( i = 1; i <= i_top; i++ )
msg_Warn( p_this, "%s", luaL_checkstring( L, i ) );
return 0;
}
static int vlclua_msg_err( lua_State *L )
{
int i_top = lua_gettop( L );
vlc_object_t *p_this = vlclua_get_this( L );
int i;
for( i = 1; i <= i_top; i++ )
msg_Err( p_this, "%s", luaL_checkstring( L, i ) );
return 0;
}
static int vlclua_msg_info( lua_State *L )
{
int i_top = lua_gettop( L );
vlc_object_t *p_this = vlclua_get_this( L );
int i;
for( i = 1; i <= i_top; i++ )
msg_Info( p_this, "%s", luaL_checkstring( L, i ) );
return 0;
}
/*****************************************************************************
*
*****************************************************************************/
static const luaL_Reg vlclua_msg_reg[] = {
{ "dbg", vlclua_msg_dbg },
{ "warn", vlclua_msg_warn },
{ "err", vlclua_msg_err },
{ "info", vlclua_msg_info },
{ NULL, NULL }
};
void luaopen_msg( lua_State *L )
{
lua_newtable( L );
luaL_register( L, NULL, vlclua_msg_reg );
lua_setfield( L, -2, "msg" );
}
| gpl-2.0 |
AdrianHuang/linux-3.8.13 | arch/arm/mach-davinci/board-da850-evm.c | 95 | 39249 | /*
* TI DA850/OMAP-L138 EVM board
*
* Copyright (C) 2009 Texas Instruments Incorporated - http://www.ti.com/
*
* Derived from: arch/arm/mach-davinci/board-da830-evm.c
* Original Copyrights follow:
*
* 2007, 2009 (c) MontaVista Software, Inc. This file is licensed under
* the terms of the GNU General Public License version 2. This program
* is licensed "as is" without any warranty of any kind, whether express
* or implied.
*/
#include <linux/console.h>
#include <linux/delay.h>
#include <linux/gpio.h>
#include <linux/gpio_keys.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/i2c.h>
#include <linux/i2c/at24.h>
#include <linux/i2c/pca953x.h>
#include <linux/input.h>
#include <linux/input/tps6507x-ts.h>
#include <linux/mfd/tps6507x.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/partitions.h>
#include <linux/mtd/physmap.h>
#include <linux/platform_device.h>
#include <linux/platform_data/mtd-davinci.h>
#include <linux/platform_data/mtd-davinci-aemif.h>
#include <linux/platform_data/spi-davinci.h>
#include <linux/platform_data/uio_pruss.h>
#include <linux/regulator/machine.h>
#include <linux/regulator/tps6507x.h>
#include <linux/spi/spi.h>
#include <linux/spi/flash.h>
#include <linux/wl12xx.h>
#include <mach/cp_intc.h>
#include <mach/da8xx.h>
#include <mach/mux.h>
#include <mach/sram.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/system_info.h>
#include <media/tvp514x.h>
#include <media/adv7343.h>
#define DA850_EVM_PHY_ID "davinci_mdio-0:00"
#define DA850_LCD_PWR_PIN GPIO_TO_PIN(2, 8)
#define DA850_LCD_BL_PIN GPIO_TO_PIN(2, 15)
#define DA850_MMCSD_CD_PIN GPIO_TO_PIN(4, 0)
#define DA850_MMCSD_WP_PIN GPIO_TO_PIN(4, 1)
#define DA850_WLAN_EN GPIO_TO_PIN(6, 9)
#define DA850_WLAN_IRQ GPIO_TO_PIN(6, 10)
#define DA850_MII_MDIO_CLKEN_PIN GPIO_TO_PIN(2, 6)
static struct mtd_partition da850evm_spiflash_part[] = {
[0] = {
.name = "UBL",
.offset = 0,
.size = SZ_64K,
.mask_flags = MTD_WRITEABLE,
},
[1] = {
.name = "U-Boot",
.offset = MTDPART_OFS_APPEND,
.size = SZ_512K,
.mask_flags = MTD_WRITEABLE,
},
[2] = {
.name = "U-Boot-Env",
.offset = MTDPART_OFS_APPEND,
.size = SZ_64K,
.mask_flags = MTD_WRITEABLE,
},
[3] = {
.name = "Kernel",
.offset = MTDPART_OFS_APPEND,
.size = SZ_2M + SZ_512K,
.mask_flags = 0,
},
[4] = {
.name = "Filesystem",
.offset = MTDPART_OFS_APPEND,
.size = SZ_4M,
.mask_flags = 0,
},
[5] = {
.name = "MAC-Address",
.offset = SZ_8M - SZ_64K,
.size = SZ_64K,
.mask_flags = MTD_WRITEABLE,
},
};
static struct flash_platform_data da850evm_spiflash_data = {
.name = "m25p80",
.parts = da850evm_spiflash_part,
.nr_parts = ARRAY_SIZE(da850evm_spiflash_part),
.type = "m25p64",
};
static struct davinci_spi_config da850evm_spiflash_cfg = {
.io_type = SPI_IO_TYPE_DMA,
.c2tdelay = 8,
.t2cdelay = 8,
};
static struct spi_board_info da850evm_spi_info[] = {
{
.modalias = "m25p80",
.platform_data = &da850evm_spiflash_data,
.controller_data = &da850evm_spiflash_cfg,
.mode = SPI_MODE_0,
.max_speed_hz = 30000000,
.bus_num = 1,
.chip_select = 0,
},
};
#ifdef CONFIG_MTD
static void da850_evm_m25p80_notify_add(struct mtd_info *mtd)
{
char *mac_addr = davinci_soc_info.emac_pdata->mac_addr;
size_t retlen;
if (!strcmp(mtd->name, "MAC-Address")) {
mtd_read(mtd, 0, ETH_ALEN, &retlen, mac_addr);
if (retlen == ETH_ALEN)
pr_info("Read MAC addr from SPI Flash: %pM\n",
mac_addr);
}
}
static struct mtd_notifier da850evm_spi_notifier = {
.add = da850_evm_m25p80_notify_add,
};
static void da850_evm_setup_mac_addr(void)
{
register_mtd_user(&da850evm_spi_notifier);
}
#else
static void da850_evm_setup_mac_addr(void) { }
#endif
static struct mtd_partition da850_evm_norflash_partition[] = {
{
.name = "bootloaders + env",
.offset = 0,
.size = SZ_512K,
.mask_flags = MTD_WRITEABLE,
},
{
.name = "kernel",
.offset = MTDPART_OFS_APPEND,
.size = SZ_2M,
.mask_flags = 0,
},
{
.name = "filesystem",
.offset = MTDPART_OFS_APPEND,
.size = MTDPART_SIZ_FULL,
.mask_flags = 0,
},
};
static struct physmap_flash_data da850_evm_norflash_data = {
.width = 2,
.parts = da850_evm_norflash_partition,
.nr_parts = ARRAY_SIZE(da850_evm_norflash_partition),
};
static struct resource da850_evm_norflash_resource[] = {
{
.start = DA8XX_AEMIF_CS2_BASE,
.end = DA8XX_AEMIF_CS2_BASE + SZ_32M - 1,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device da850_evm_norflash_device = {
.name = "physmap-flash",
.id = 0,
.dev = {
.platform_data = &da850_evm_norflash_data,
},
.num_resources = 1,
.resource = da850_evm_norflash_resource,
};
static struct davinci_pm_config da850_pm_pdata = {
.sleepcount = 128,
};
static struct platform_device da850_pm_device = {
.name = "pm-davinci",
.dev = {
.platform_data = &da850_pm_pdata,
},
.id = -1,
};
/* DA850/OMAP-L138 EVM includes a 512 MByte large-page NAND flash
* (128K blocks). It may be used instead of the (default) SPI flash
* to boot, using TI's tools to install the secondary boot loader
* (UBL) and U-Boot.
*/
static struct mtd_partition da850_evm_nandflash_partition[] = {
{
.name = "u-boot env",
.offset = 0,
.size = SZ_128K,
.mask_flags = MTD_WRITEABLE,
},
{
.name = "UBL",
.offset = MTDPART_OFS_APPEND,
.size = SZ_128K,
.mask_flags = MTD_WRITEABLE,
},
{
.name = "u-boot",
.offset = MTDPART_OFS_APPEND,
.size = 4 * SZ_128K,
.mask_flags = MTD_WRITEABLE,
},
{
.name = "kernel",
.offset = 0x200000,
.size = SZ_2M,
.mask_flags = 0,
},
{
.name = "filesystem",
.offset = MTDPART_OFS_APPEND,
.size = MTDPART_SIZ_FULL,
.mask_flags = 0,
},
};
static struct davinci_aemif_timing da850_evm_nandflash_timing = {
.wsetup = 24,
.wstrobe = 21,
.whold = 14,
.rsetup = 19,
.rstrobe = 50,
.rhold = 0,
.ta = 20,
};
static struct davinci_nand_pdata da850_evm_nandflash_data = {
.parts = da850_evm_nandflash_partition,
.nr_parts = ARRAY_SIZE(da850_evm_nandflash_partition),
.ecc_mode = NAND_ECC_HW,
.ecc_bits = 4,
.bbt_options = NAND_BBT_USE_FLASH,
.timing = &da850_evm_nandflash_timing,
};
static struct resource da850_evm_nandflash_resource[] = {
{
.start = DA8XX_AEMIF_CS3_BASE,
.end = DA8XX_AEMIF_CS3_BASE + SZ_512K + 2 * SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
.start = DA8XX_AEMIF_CTL_BASE,
.end = DA8XX_AEMIF_CTL_BASE + SZ_32K - 1,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device da850_evm_nandflash_device = {
.name = "davinci_nand",
.id = 1,
.dev = {
.platform_data = &da850_evm_nandflash_data,
},
.num_resources = ARRAY_SIZE(da850_evm_nandflash_resource),
.resource = da850_evm_nandflash_resource,
};
static struct platform_device *da850_evm_devices[] = {
&da850_evm_nandflash_device,
&da850_evm_norflash_device,
};
#define DA8XX_AEMIF_CE2CFG_OFFSET 0x10
#define DA8XX_AEMIF_ASIZE_16BIT 0x1
static void __init da850_evm_init_nor(void)
{
void __iomem *aemif_addr;
aemif_addr = ioremap(DA8XX_AEMIF_CTL_BASE, SZ_32K);
/* Configure data bus width of CS2 to 16 bit */
writel(readl(aemif_addr + DA8XX_AEMIF_CE2CFG_OFFSET) |
DA8XX_AEMIF_ASIZE_16BIT,
aemif_addr + DA8XX_AEMIF_CE2CFG_OFFSET);
iounmap(aemif_addr);
}
static const short da850_evm_nand_pins[] = {
DA850_EMA_D_0, DA850_EMA_D_1, DA850_EMA_D_2, DA850_EMA_D_3,
DA850_EMA_D_4, DA850_EMA_D_5, DA850_EMA_D_6, DA850_EMA_D_7,
DA850_EMA_A_1, DA850_EMA_A_2, DA850_NEMA_CS_3, DA850_NEMA_CS_4,
DA850_NEMA_WE, DA850_NEMA_OE,
-1
};
static const short da850_evm_nor_pins[] = {
DA850_EMA_BA_1, DA850_EMA_CLK, DA850_EMA_WAIT_1, DA850_NEMA_CS_2,
DA850_NEMA_WE, DA850_NEMA_OE, DA850_EMA_D_0, DA850_EMA_D_1,
DA850_EMA_D_2, DA850_EMA_D_3, DA850_EMA_D_4, DA850_EMA_D_5,
DA850_EMA_D_6, DA850_EMA_D_7, DA850_EMA_D_8, DA850_EMA_D_9,
DA850_EMA_D_10, DA850_EMA_D_11, DA850_EMA_D_12, DA850_EMA_D_13,
DA850_EMA_D_14, DA850_EMA_D_15, DA850_EMA_A_0, DA850_EMA_A_1,
DA850_EMA_A_2, DA850_EMA_A_3, DA850_EMA_A_4, DA850_EMA_A_5,
DA850_EMA_A_6, DA850_EMA_A_7, DA850_EMA_A_8, DA850_EMA_A_9,
DA850_EMA_A_10, DA850_EMA_A_11, DA850_EMA_A_12, DA850_EMA_A_13,
DA850_EMA_A_14, DA850_EMA_A_15, DA850_EMA_A_16, DA850_EMA_A_17,
DA850_EMA_A_18, DA850_EMA_A_19, DA850_EMA_A_20, DA850_EMA_A_21,
DA850_EMA_A_22, DA850_EMA_A_23,
-1
};
#if defined(CONFIG_MMC_DAVINCI) || \
defined(CONFIG_MMC_DAVINCI_MODULE)
#define HAS_MMC 1
#else
#define HAS_MMC 0
#endif
static inline void da850_evm_setup_nor_nand(void)
{
int ret = 0;
if (!HAS_MMC) {
ret = davinci_cfg_reg_list(da850_evm_nand_pins);
if (ret)
pr_warning("da850_evm_init: nand mux setup failed: "
"%d\n", ret);
ret = davinci_cfg_reg_list(da850_evm_nor_pins);
if (ret)
pr_warning("da850_evm_init: nor mux setup failed: %d\n",
ret);
da850_evm_init_nor();
platform_add_devices(da850_evm_devices,
ARRAY_SIZE(da850_evm_devices));
}
}
#ifdef CONFIG_DA850_UI_RMII
static inline void da850_evm_setup_emac_rmii(int rmii_sel)
{
struct davinci_soc_info *soc_info = &davinci_soc_info;
soc_info->emac_pdata->rmii_en = 1;
gpio_set_value_cansleep(rmii_sel, 0);
}
#else
static inline void da850_evm_setup_emac_rmii(int rmii_sel) { }
#endif
#define DA850_KEYS_DEBOUNCE_MS 10
/*
* At 200ms polling interval it is possible to miss an
* event by tapping very lightly on the push button but most
* pushes do result in an event; longer intervals require the
* user to hold the button whereas shorter intervals require
* more CPU time for polling.
*/
#define DA850_GPIO_KEYS_POLL_MS 200
enum da850_evm_ui_exp_pins {
DA850_EVM_UI_EXP_SEL_C = 5,
DA850_EVM_UI_EXP_SEL_B,
DA850_EVM_UI_EXP_SEL_A,
DA850_EVM_UI_EXP_PB8,
DA850_EVM_UI_EXP_PB7,
DA850_EVM_UI_EXP_PB6,
DA850_EVM_UI_EXP_PB5,
DA850_EVM_UI_EXP_PB4,
DA850_EVM_UI_EXP_PB3,
DA850_EVM_UI_EXP_PB2,
DA850_EVM_UI_EXP_PB1,
};
static const char const *da850_evm_ui_exp[] = {
[DA850_EVM_UI_EXP_SEL_C] = "sel_c",
[DA850_EVM_UI_EXP_SEL_B] = "sel_b",
[DA850_EVM_UI_EXP_SEL_A] = "sel_a",
[DA850_EVM_UI_EXP_PB8] = "pb8",
[DA850_EVM_UI_EXP_PB7] = "pb7",
[DA850_EVM_UI_EXP_PB6] = "pb6",
[DA850_EVM_UI_EXP_PB5] = "pb5",
[DA850_EVM_UI_EXP_PB4] = "pb4",
[DA850_EVM_UI_EXP_PB3] = "pb3",
[DA850_EVM_UI_EXP_PB2] = "pb2",
[DA850_EVM_UI_EXP_PB1] = "pb1",
};
#define DA850_N_UI_PB 8
static struct gpio_keys_button da850_evm_ui_keys[] = {
[0 ... DA850_N_UI_PB - 1] = {
.type = EV_KEY,
.active_low = 1,
.wakeup = 0,
.debounce_interval = DA850_KEYS_DEBOUNCE_MS,
.code = -1, /* assigned at runtime */
.gpio = -1, /* assigned at runtime */
.desc = NULL, /* assigned at runtime */
},
};
static struct gpio_keys_platform_data da850_evm_ui_keys_pdata = {
.buttons = da850_evm_ui_keys,
.nbuttons = ARRAY_SIZE(da850_evm_ui_keys),
.poll_interval = DA850_GPIO_KEYS_POLL_MS,
};
static struct platform_device da850_evm_ui_keys_device = {
.name = "gpio-keys-polled",
.id = 0,
.dev = {
.platform_data = &da850_evm_ui_keys_pdata
},
};
static void da850_evm_ui_keys_init(unsigned gpio)
{
int i;
struct gpio_keys_button *button;
for (i = 0; i < DA850_N_UI_PB; i++) {
button = &da850_evm_ui_keys[i];
button->code = KEY_F8 - i;
button->desc = (char *)
da850_evm_ui_exp[DA850_EVM_UI_EXP_PB8 + i];
button->gpio = gpio + DA850_EVM_UI_EXP_PB8 + i;
}
}
#ifdef CONFIG_DA850_UI_SD_VIDEO_PORT
static inline void da850_evm_setup_video_port(int video_sel)
{
gpio_set_value_cansleep(video_sel, 0);
}
#else
static inline void da850_evm_setup_video_port(int video_sel) { }
#endif
static int da850_evm_ui_expander_setup(struct i2c_client *client, unsigned gpio,
unsigned ngpio, void *c)
{
int sel_a, sel_b, sel_c, ret;
sel_a = gpio + DA850_EVM_UI_EXP_SEL_A;
sel_b = gpio + DA850_EVM_UI_EXP_SEL_B;
sel_c = gpio + DA850_EVM_UI_EXP_SEL_C;
ret = gpio_request(sel_a, da850_evm_ui_exp[DA850_EVM_UI_EXP_SEL_A]);
if (ret) {
pr_warning("Cannot open UI expander pin %d\n", sel_a);
goto exp_setup_sela_fail;
}
ret = gpio_request(sel_b, da850_evm_ui_exp[DA850_EVM_UI_EXP_SEL_B]);
if (ret) {
pr_warning("Cannot open UI expander pin %d\n", sel_b);
goto exp_setup_selb_fail;
}
ret = gpio_request(sel_c, da850_evm_ui_exp[DA850_EVM_UI_EXP_SEL_C]);
if (ret) {
pr_warning("Cannot open UI expander pin %d\n", sel_c);
goto exp_setup_selc_fail;
}
/* deselect all functionalities */
gpio_direction_output(sel_a, 1);
gpio_direction_output(sel_b, 1);
gpio_direction_output(sel_c, 1);
da850_evm_ui_keys_init(gpio);
ret = platform_device_register(&da850_evm_ui_keys_device);
if (ret) {
pr_warning("Could not register UI GPIO expander push-buttons");
goto exp_setup_keys_fail;
}
pr_info("DA850/OMAP-L138 EVM UI card detected\n");
da850_evm_setup_nor_nand();
da850_evm_setup_emac_rmii(sel_a);
da850_evm_setup_video_port(sel_c);
return 0;
exp_setup_keys_fail:
gpio_free(sel_c);
exp_setup_selc_fail:
gpio_free(sel_b);
exp_setup_selb_fail:
gpio_free(sel_a);
exp_setup_sela_fail:
return ret;
}
static int da850_evm_ui_expander_teardown(struct i2c_client *client,
unsigned gpio, unsigned ngpio, void *c)
{
platform_device_unregister(&da850_evm_ui_keys_device);
/* deselect all functionalities */
gpio_set_value_cansleep(gpio + DA850_EVM_UI_EXP_SEL_C, 1);
gpio_set_value_cansleep(gpio + DA850_EVM_UI_EXP_SEL_B, 1);
gpio_set_value_cansleep(gpio + DA850_EVM_UI_EXP_SEL_A, 1);
gpio_free(gpio + DA850_EVM_UI_EXP_SEL_C);
gpio_free(gpio + DA850_EVM_UI_EXP_SEL_B);
gpio_free(gpio + DA850_EVM_UI_EXP_SEL_A);
return 0;
}
/* assign the baseboard expander's GPIOs after the UI board's */
#define DA850_UI_EXPANDER_N_GPIOS ARRAY_SIZE(da850_evm_ui_exp)
#define DA850_BB_EXPANDER_GPIO_BASE (DAVINCI_N_GPIO + DA850_UI_EXPANDER_N_GPIOS)
enum da850_evm_bb_exp_pins {
DA850_EVM_BB_EXP_DEEP_SLEEP_EN = 0,
DA850_EVM_BB_EXP_SW_RST,
DA850_EVM_BB_EXP_TP_23,
DA850_EVM_BB_EXP_TP_22,
DA850_EVM_BB_EXP_TP_21,
DA850_EVM_BB_EXP_USER_PB1,
DA850_EVM_BB_EXP_USER_LED2,
DA850_EVM_BB_EXP_USER_LED1,
DA850_EVM_BB_EXP_USER_SW1,
DA850_EVM_BB_EXP_USER_SW2,
DA850_EVM_BB_EXP_USER_SW3,
DA850_EVM_BB_EXP_USER_SW4,
DA850_EVM_BB_EXP_USER_SW5,
DA850_EVM_BB_EXP_USER_SW6,
DA850_EVM_BB_EXP_USER_SW7,
DA850_EVM_BB_EXP_USER_SW8
};
static const char const *da850_evm_bb_exp[] = {
[DA850_EVM_BB_EXP_DEEP_SLEEP_EN] = "deep_sleep_en",
[DA850_EVM_BB_EXP_SW_RST] = "sw_rst",
[DA850_EVM_BB_EXP_TP_23] = "tp_23",
[DA850_EVM_BB_EXP_TP_22] = "tp_22",
[DA850_EVM_BB_EXP_TP_21] = "tp_21",
[DA850_EVM_BB_EXP_USER_PB1] = "user_pb1",
[DA850_EVM_BB_EXP_USER_LED2] = "user_led2",
[DA850_EVM_BB_EXP_USER_LED1] = "user_led1",
[DA850_EVM_BB_EXP_USER_SW1] = "user_sw1",
[DA850_EVM_BB_EXP_USER_SW2] = "user_sw2",
[DA850_EVM_BB_EXP_USER_SW3] = "user_sw3",
[DA850_EVM_BB_EXP_USER_SW4] = "user_sw4",
[DA850_EVM_BB_EXP_USER_SW5] = "user_sw5",
[DA850_EVM_BB_EXP_USER_SW6] = "user_sw6",
[DA850_EVM_BB_EXP_USER_SW7] = "user_sw7",
[DA850_EVM_BB_EXP_USER_SW8] = "user_sw8",
};
#define DA850_N_BB_USER_SW 8
static struct gpio_keys_button da850_evm_bb_keys[] = {
[0] = {
.type = EV_KEY,
.active_low = 1,
.wakeup = 0,
.debounce_interval = DA850_KEYS_DEBOUNCE_MS,
.code = KEY_PROG1,
.desc = NULL, /* assigned at runtime */
.gpio = -1, /* assigned at runtime */
},
[1 ... DA850_N_BB_USER_SW] = {
.type = EV_SW,
.active_low = 1,
.wakeup = 0,
.debounce_interval = DA850_KEYS_DEBOUNCE_MS,
.code = -1, /* assigned at runtime */
.desc = NULL, /* assigned at runtime */
.gpio = -1, /* assigned at runtime */
},
};
static struct gpio_keys_platform_data da850_evm_bb_keys_pdata = {
.buttons = da850_evm_bb_keys,
.nbuttons = ARRAY_SIZE(da850_evm_bb_keys),
.poll_interval = DA850_GPIO_KEYS_POLL_MS,
};
static struct platform_device da850_evm_bb_keys_device = {
.name = "gpio-keys-polled",
.id = 1,
.dev = {
.platform_data = &da850_evm_bb_keys_pdata
},
};
static void da850_evm_bb_keys_init(unsigned gpio)
{
int i;
struct gpio_keys_button *button;
button = &da850_evm_bb_keys[0];
button->desc = (char *)
da850_evm_bb_exp[DA850_EVM_BB_EXP_USER_PB1];
button->gpio = gpio + DA850_EVM_BB_EXP_USER_PB1;
for (i = 0; i < DA850_N_BB_USER_SW; i++) {
button = &da850_evm_bb_keys[i + 1];
button->code = SW_LID + i;
button->desc = (char *)
da850_evm_bb_exp[DA850_EVM_BB_EXP_USER_SW1 + i];
button->gpio = gpio + DA850_EVM_BB_EXP_USER_SW1 + i;
}
}
#define DA850_N_BB_USER_LED 2
static struct gpio_led da850_evm_bb_leds[] = {
[0 ... DA850_N_BB_USER_LED - 1] = {
.active_low = 1,
.gpio = -1, /* assigned at runtime */
.name = NULL, /* assigned at runtime */
},
};
static struct gpio_led_platform_data da850_evm_bb_leds_pdata = {
.leds = da850_evm_bb_leds,
.num_leds = ARRAY_SIZE(da850_evm_bb_leds),
};
static struct platform_device da850_evm_bb_leds_device = {
.name = "leds-gpio",
.id = -1,
.dev = {
.platform_data = &da850_evm_bb_leds_pdata
}
};
static void da850_evm_bb_leds_init(unsigned gpio)
{
int i;
struct gpio_led *led;
for (i = 0; i < DA850_N_BB_USER_LED; i++) {
led = &da850_evm_bb_leds[i];
led->gpio = gpio + DA850_EVM_BB_EXP_USER_LED2 + i;
led->name =
da850_evm_bb_exp[DA850_EVM_BB_EXP_USER_LED2 + i];
}
}
static int da850_evm_bb_expander_setup(struct i2c_client *client,
unsigned gpio, unsigned ngpio,
void *c)
{
int ret;
/*
* Register the switches and pushbutton on the baseboard as a gpio-keys
* device.
*/
da850_evm_bb_keys_init(gpio);
ret = platform_device_register(&da850_evm_bb_keys_device);
if (ret) {
pr_warning("Could not register baseboard GPIO expander keys");
goto io_exp_setup_sw_fail;
}
da850_evm_bb_leds_init(gpio);
ret = platform_device_register(&da850_evm_bb_leds_device);
if (ret) {
pr_warning("Could not register baseboard GPIO expander LEDS");
goto io_exp_setup_leds_fail;
}
return 0;
io_exp_setup_leds_fail:
platform_device_unregister(&da850_evm_bb_keys_device);
io_exp_setup_sw_fail:
return ret;
}
static int da850_evm_bb_expander_teardown(struct i2c_client *client,
unsigned gpio, unsigned ngpio, void *c)
{
platform_device_unregister(&da850_evm_bb_leds_device);
platform_device_unregister(&da850_evm_bb_keys_device);
return 0;
}
static struct pca953x_platform_data da850_evm_ui_expander_info = {
.gpio_base = DAVINCI_N_GPIO,
.setup = da850_evm_ui_expander_setup,
.teardown = da850_evm_ui_expander_teardown,
.names = da850_evm_ui_exp,
};
static struct pca953x_platform_data da850_evm_bb_expander_info = {
.gpio_base = DA850_BB_EXPANDER_GPIO_BASE,
.setup = da850_evm_bb_expander_setup,
.teardown = da850_evm_bb_expander_teardown,
.names = da850_evm_bb_exp,
};
static struct i2c_board_info __initdata da850_evm_i2c_devices[] = {
{
I2C_BOARD_INFO("tlv320aic3x", 0x18),
},
{
I2C_BOARD_INFO("tca6416", 0x20),
.platform_data = &da850_evm_ui_expander_info,
},
{
I2C_BOARD_INFO("tca6416", 0x21),
.platform_data = &da850_evm_bb_expander_info,
},
};
static struct davinci_i2c_platform_data da850_evm_i2c_0_pdata = {
.bus_freq = 100, /* kHz */
.bus_delay = 0, /* usec */
};
static struct davinci_uart_config da850_evm_uart_config __initdata = {
.enabled_uarts = 0x7,
};
/* davinci da850 evm audio machine driver */
static u8 da850_iis_serializer_direction[] = {
INACTIVE_MODE, INACTIVE_MODE, INACTIVE_MODE, INACTIVE_MODE,
INACTIVE_MODE, INACTIVE_MODE, INACTIVE_MODE, INACTIVE_MODE,
INACTIVE_MODE, INACTIVE_MODE, INACTIVE_MODE, TX_MODE,
RX_MODE, INACTIVE_MODE, INACTIVE_MODE, INACTIVE_MODE,
};
static struct snd_platform_data da850_evm_snd_data = {
.tx_dma_offset = 0x2000,
.rx_dma_offset = 0x2000,
.op_mode = DAVINCI_MCASP_IIS_MODE,
.num_serializer = ARRAY_SIZE(da850_iis_serializer_direction),
.tdm_slots = 2,
.serial_dir = da850_iis_serializer_direction,
.asp_chan_q = EVENTQ_0,
.ram_chan_q = EVENTQ_1,
.version = MCASP_VERSION_2,
.txnumevt = 1,
.rxnumevt = 1,
.sram_size_playback = SZ_8K,
.sram_size_capture = SZ_8K,
};
static const short da850_evm_mcasp_pins[] __initconst = {
DA850_AHCLKX, DA850_ACLKX, DA850_AFSX,
DA850_AHCLKR, DA850_ACLKR, DA850_AFSR, DA850_AMUTE,
DA850_AXR_11, DA850_AXR_12,
-1
};
static int da850_evm_mmc_get_ro(int index)
{
return gpio_get_value(DA850_MMCSD_WP_PIN);
}
static int da850_evm_mmc_get_cd(int index)
{
return !gpio_get_value(DA850_MMCSD_CD_PIN);
}
static struct davinci_mmc_config da850_mmc_config = {
.get_ro = da850_evm_mmc_get_ro,
.get_cd = da850_evm_mmc_get_cd,
.wires = 4,
.max_freq = 50000000,
.caps = MMC_CAP_MMC_HIGHSPEED | MMC_CAP_SD_HIGHSPEED,
.version = MMC_CTLR_VERSION_2,
};
static const short da850_evm_mmcsd0_pins[] __initconst = {
DA850_MMCSD0_DAT_0, DA850_MMCSD0_DAT_1, DA850_MMCSD0_DAT_2,
DA850_MMCSD0_DAT_3, DA850_MMCSD0_CLK, DA850_MMCSD0_CMD,
DA850_GPIO4_0, DA850_GPIO4_1,
-1
};
static void da850_panel_power_ctrl(int val)
{
/* lcd backlight */
gpio_set_value(DA850_LCD_BL_PIN, val);
/* lcd power */
gpio_set_value(DA850_LCD_PWR_PIN, val);
}
static int da850_lcd_hw_init(void)
{
int status;
status = gpio_request(DA850_LCD_BL_PIN, "lcd bl\n");
if (status < 0)
return status;
status = gpio_request(DA850_LCD_PWR_PIN, "lcd pwr\n");
if (status < 0) {
gpio_free(DA850_LCD_BL_PIN);
return status;
}
gpio_direction_output(DA850_LCD_BL_PIN, 0);
gpio_direction_output(DA850_LCD_PWR_PIN, 0);
/* Switch off panel power and backlight */
da850_panel_power_ctrl(0);
/* Switch on panel power and backlight */
da850_panel_power_ctrl(1);
return 0;
}
/* TPS65070 voltage regulator support */
/* 3.3V */
static struct regulator_consumer_supply tps65070_dcdc1_consumers[] = {
{
.supply = "usb0_vdda33",
},
{
.supply = "usb1_vdda33",
},
};
/* 3.3V or 1.8V */
static struct regulator_consumer_supply tps65070_dcdc2_consumers[] = {
{
.supply = "dvdd3318_a",
},
{
.supply = "dvdd3318_b",
},
{
.supply = "dvdd3318_c",
},
};
/* 1.2V */
static struct regulator_consumer_supply tps65070_dcdc3_consumers[] = {
{
.supply = "cvdd",
},
};
/* 1.8V LDO */
static struct regulator_consumer_supply tps65070_ldo1_consumers[] = {
{
.supply = "sata_vddr",
},
{
.supply = "usb0_vdda18",
},
{
.supply = "usb1_vdda18",
},
{
.supply = "ddr_dvdd18",
},
};
/* 1.2V LDO */
static struct regulator_consumer_supply tps65070_ldo2_consumers[] = {
{
.supply = "sata_vdd",
},
{
.supply = "pll0_vdda",
},
{
.supply = "pll1_vdda",
},
{
.supply = "usbs_cvdd",
},
{
.supply = "vddarnwa1",
},
};
/* We take advantage of the fact that both defdcdc{2,3} are tied high */
static struct tps6507x_reg_platform_data tps6507x_platform_data = {
.defdcdc_default = true,
};
static struct regulator_init_data tps65070_regulator_data[] = {
/* dcdc1 */
{
.constraints = {
.min_uV = 3150000,
.max_uV = 3450000,
.valid_ops_mask = (REGULATOR_CHANGE_VOLTAGE |
REGULATOR_CHANGE_STATUS),
.boot_on = 1,
},
.num_consumer_supplies = ARRAY_SIZE(tps65070_dcdc1_consumers),
.consumer_supplies = tps65070_dcdc1_consumers,
},
/* dcdc2 */
{
.constraints = {
.min_uV = 1710000,
.max_uV = 3450000,
.valid_ops_mask = (REGULATOR_CHANGE_VOLTAGE |
REGULATOR_CHANGE_STATUS),
.boot_on = 1,
},
.num_consumer_supplies = ARRAY_SIZE(tps65070_dcdc2_consumers),
.consumer_supplies = tps65070_dcdc2_consumers,
.driver_data = &tps6507x_platform_data,
},
/* dcdc3 */
{
.constraints = {
.min_uV = 950000,
.max_uV = 1350000,
.valid_ops_mask = (REGULATOR_CHANGE_VOLTAGE |
REGULATOR_CHANGE_STATUS),
.boot_on = 1,
},
.num_consumer_supplies = ARRAY_SIZE(tps65070_dcdc3_consumers),
.consumer_supplies = tps65070_dcdc3_consumers,
.driver_data = &tps6507x_platform_data,
},
/* ldo1 */
{
.constraints = {
.min_uV = 1710000,
.max_uV = 1890000,
.valid_ops_mask = (REGULATOR_CHANGE_VOLTAGE |
REGULATOR_CHANGE_STATUS),
.boot_on = 1,
},
.num_consumer_supplies = ARRAY_SIZE(tps65070_ldo1_consumers),
.consumer_supplies = tps65070_ldo1_consumers,
},
/* ldo2 */
{
.constraints = {
.min_uV = 1140000,
.max_uV = 1320000,
.valid_ops_mask = (REGULATOR_CHANGE_VOLTAGE |
REGULATOR_CHANGE_STATUS),
.boot_on = 1,
},
.num_consumer_supplies = ARRAY_SIZE(tps65070_ldo2_consumers),
.consumer_supplies = tps65070_ldo2_consumers,
},
};
static struct touchscreen_init_data tps6507x_touchscreen_data = {
.poll_period = 30, /* ms between touch samples */
.min_pressure = 0x30, /* minimum pressure to trigger touch */
.vref = 0, /* turn off vref when not using A/D */
.vendor = 0, /* /sys/class/input/input?/id/vendor */
.product = 65070, /* /sys/class/input/input?/id/product */
.version = 0x100, /* /sys/class/input/input?/id/version */
};
static struct tps6507x_board tps_board = {
.tps6507x_pmic_init_data = &tps65070_regulator_data[0],
.tps6507x_ts_init_data = &tps6507x_touchscreen_data,
};
static struct i2c_board_info __initdata da850_evm_tps65070_info[] = {
{
I2C_BOARD_INFO("tps6507x", 0x48),
.platform_data = &tps_board,
},
};
static int __init pmic_tps65070_init(void)
{
return i2c_register_board_info(1, da850_evm_tps65070_info,
ARRAY_SIZE(da850_evm_tps65070_info));
}
static const short da850_evm_lcdc_pins[] = {
DA850_GPIO2_8, DA850_GPIO2_15,
-1
};
static const short da850_evm_mii_pins[] = {
DA850_MII_TXEN, DA850_MII_TXCLK, DA850_MII_COL, DA850_MII_TXD_3,
DA850_MII_TXD_2, DA850_MII_TXD_1, DA850_MII_TXD_0, DA850_MII_RXER,
DA850_MII_CRS, DA850_MII_RXCLK, DA850_MII_RXDV, DA850_MII_RXD_3,
DA850_MII_RXD_2, DA850_MII_RXD_1, DA850_MII_RXD_0, DA850_MDIO_CLK,
DA850_MDIO_D,
-1
};
static const short da850_evm_rmii_pins[] = {
DA850_RMII_TXD_0, DA850_RMII_TXD_1, DA850_RMII_TXEN,
DA850_RMII_CRS_DV, DA850_RMII_RXD_0, DA850_RMII_RXD_1,
DA850_RMII_RXER, DA850_RMII_MHZ_50_CLK, DA850_MDIO_CLK,
DA850_MDIO_D,
-1
};
static int __init da850_evm_config_emac(void)
{
void __iomem *cfg_chip3_base;
int ret;
u32 val;
struct davinci_soc_info *soc_info = &davinci_soc_info;
u8 rmii_en = soc_info->emac_pdata->rmii_en;
if (!machine_is_davinci_da850_evm())
return 0;
cfg_chip3_base = DA8XX_SYSCFG0_VIRT(DA8XX_CFGCHIP3_REG);
val = __raw_readl(cfg_chip3_base);
if (rmii_en) {
val |= BIT(8);
ret = davinci_cfg_reg_list(da850_evm_rmii_pins);
pr_info("EMAC: RMII PHY configured, MII PHY will not be"
" functional\n");
} else {
val &= ~BIT(8);
ret = davinci_cfg_reg_list(da850_evm_mii_pins);
pr_info("EMAC: MII PHY configured, RMII PHY will not be"
" functional\n");
}
if (ret)
pr_warning("da850_evm_init: cpgmac/rmii mux setup failed: %d\n",
ret);
/* configure the CFGCHIP3 register for RMII or MII */
__raw_writel(val, cfg_chip3_base);
ret = davinci_cfg_reg(DA850_GPIO2_6);
if (ret)
pr_warning("da850_evm_init:GPIO(2,6) mux setup "
"failed\n");
ret = gpio_request(DA850_MII_MDIO_CLKEN_PIN, "mdio_clk_en");
if (ret) {
pr_warning("Cannot open GPIO %d\n",
DA850_MII_MDIO_CLKEN_PIN);
return ret;
}
/* Enable/Disable MII MDIO clock */
gpio_direction_output(DA850_MII_MDIO_CLKEN_PIN, rmii_en);
soc_info->emac_pdata->phy_id = DA850_EVM_PHY_ID;
ret = da8xx_register_emac();
if (ret)
pr_warning("da850_evm_init: emac registration failed: %d\n",
ret);
return 0;
}
device_initcall(da850_evm_config_emac);
/*
* The following EDMA channels/slots are not being used by drivers (for
* example: Timer, GPIO, UART events etc) on da850/omap-l138 EVM, hence
* they are being reserved for codecs on the DSP side.
*/
static const s16 da850_dma0_rsv_chans[][2] = {
/* (offset, number) */
{ 8, 6},
{24, 4},
{30, 2},
{-1, -1}
};
static const s16 da850_dma0_rsv_slots[][2] = {
/* (offset, number) */
{ 8, 6},
{24, 4},
{30, 50},
{-1, -1}
};
static const s16 da850_dma1_rsv_chans[][2] = {
/* (offset, number) */
{ 0, 28},
{30, 2},
{-1, -1}
};
static const s16 da850_dma1_rsv_slots[][2] = {
/* (offset, number) */
{ 0, 28},
{30, 90},
{-1, -1}
};
static struct edma_rsv_info da850_edma_cc0_rsv = {
.rsv_chans = da850_dma0_rsv_chans,
.rsv_slots = da850_dma0_rsv_slots,
};
static struct edma_rsv_info da850_edma_cc1_rsv = {
.rsv_chans = da850_dma1_rsv_chans,
.rsv_slots = da850_dma1_rsv_slots,
};
static struct edma_rsv_info *da850_edma_rsv[2] = {
&da850_edma_cc0_rsv,
&da850_edma_cc1_rsv,
};
#ifdef CONFIG_CPU_FREQ
static __init int da850_evm_init_cpufreq(void)
{
switch (system_rev & 0xF) {
case 3:
da850_max_speed = 456000;
break;
case 2:
da850_max_speed = 408000;
break;
case 1:
da850_max_speed = 372000;
break;
}
return da850_register_cpufreq("pll0_sysclk3");
}
#else
static __init int da850_evm_init_cpufreq(void) { return 0; }
#endif
#if defined(CONFIG_DA850_UI_SD_VIDEO_PORT)
#define TVP5147_CH0 "tvp514x-0"
#define TVP5147_CH1 "tvp514x-1"
/* VPIF capture configuration */
static struct tvp514x_platform_data tvp5146_pdata = {
.clk_polarity = 0,
.hs_polarity = 1,
.vs_polarity = 1,
};
#define TVP514X_STD_ALL (V4L2_STD_NTSC | V4L2_STD_PAL)
static const struct vpif_input da850_ch0_inputs[] = {
{
.input = {
.index = 0,
.name = "Composite",
.type = V4L2_INPUT_TYPE_CAMERA,
.capabilities = V4L2_IN_CAP_STD,
.std = TVP514X_STD_ALL,
},
.input_route = INPUT_CVBS_VI2B,
.output_route = OUTPUT_10BIT_422_EMBEDDED_SYNC,
.subdev_name = TVP5147_CH0,
},
};
static const struct vpif_input da850_ch1_inputs[] = {
{
.input = {
.index = 0,
.name = "S-Video",
.type = V4L2_INPUT_TYPE_CAMERA,
.capabilities = V4L2_IN_CAP_STD,
.std = TVP514X_STD_ALL,
},
.input_route = INPUT_SVIDEO_VI2C_VI1C,
.output_route = OUTPUT_10BIT_422_EMBEDDED_SYNC,
.subdev_name = TVP5147_CH1,
},
};
static struct vpif_subdev_info da850_vpif_capture_sdev_info[] = {
{
.name = TVP5147_CH0,
.board_info = {
I2C_BOARD_INFO("tvp5146", 0x5d),
.platform_data = &tvp5146_pdata,
},
},
{
.name = TVP5147_CH1,
.board_info = {
I2C_BOARD_INFO("tvp5146", 0x5c),
.platform_data = &tvp5146_pdata,
},
},
};
static struct vpif_capture_config da850_vpif_capture_config = {
.subdev_info = da850_vpif_capture_sdev_info,
.subdev_count = ARRAY_SIZE(da850_vpif_capture_sdev_info),
.chan_config[0] = {
.inputs = da850_ch0_inputs,
.input_count = ARRAY_SIZE(da850_ch0_inputs),
.vpif_if = {
.if_type = VPIF_IF_BT656,
.hd_pol = 1,
.vd_pol = 1,
.fid_pol = 0,
},
},
.chan_config[1] = {
.inputs = da850_ch1_inputs,
.input_count = ARRAY_SIZE(da850_ch1_inputs),
.vpif_if = {
.if_type = VPIF_IF_BT656,
.hd_pol = 1,
.vd_pol = 1,
.fid_pol = 0,
},
},
.card_name = "DA850/OMAP-L138 Video Capture",
};
/* VPIF display configuration */
static struct vpif_subdev_info da850_vpif_subdev[] = {
{
.name = "adv7343",
.board_info = {
I2C_BOARD_INFO("adv7343", 0x2a),
},
},
};
static const struct vpif_output da850_ch0_outputs[] = {
{
.output = {
.index = 0,
.name = "Composite",
.type = V4L2_OUTPUT_TYPE_ANALOG,
.capabilities = V4L2_OUT_CAP_STD,
.std = V4L2_STD_ALL,
},
.subdev_name = "adv7343",
.output_route = ADV7343_COMPOSITE_ID,
},
{
.output = {
.index = 1,
.name = "S-Video",
.type = V4L2_OUTPUT_TYPE_ANALOG,
.capabilities = V4L2_OUT_CAP_STD,
.std = V4L2_STD_ALL,
},
.subdev_name = "adv7343",
.output_route = ADV7343_SVIDEO_ID,
},
};
static struct vpif_display_config da850_vpif_display_config = {
.subdevinfo = da850_vpif_subdev,
.subdev_count = ARRAY_SIZE(da850_vpif_subdev),
.chan_config[0] = {
.outputs = da850_ch0_outputs,
.output_count = ARRAY_SIZE(da850_ch0_outputs),
},
.card_name = "DA850/OMAP-L138 Video Display",
};
static __init void da850_vpif_init(void)
{
int ret;
ret = da850_register_vpif();
if (ret)
pr_warn("da850_evm_init: VPIF setup failed: %d\n", ret);
ret = davinci_cfg_reg_list(da850_vpif_capture_pins);
if (ret)
pr_warn("da850_evm_init: VPIF capture mux setup failed: %d\n",
ret);
ret = da850_register_vpif_capture(&da850_vpif_capture_config);
if (ret)
pr_warn("da850_evm_init: VPIF capture setup failed: %d\n", ret);
ret = davinci_cfg_reg_list(da850_vpif_display_pins);
if (ret)
pr_warn("da850_evm_init: VPIF display mux setup failed: %d\n",
ret);
ret = da850_register_vpif_display(&da850_vpif_display_config);
if (ret)
pr_warn("da850_evm_init: VPIF display setup failed: %d\n", ret);
}
#else
static __init void da850_vpif_init(void) {}
#endif
#ifdef CONFIG_DA850_WL12XX
static void wl12xx_set_power(int index, bool power_on)
{
static bool power_state;
pr_debug("Powering %s wl12xx", power_on ? "on" : "off");
if (power_on == power_state)
return;
power_state = power_on;
if (power_on) {
/* Power up sequence required for wl127x devices */
gpio_set_value(DA850_WLAN_EN, 1);
usleep_range(15000, 15000);
gpio_set_value(DA850_WLAN_EN, 0);
usleep_range(1000, 1000);
gpio_set_value(DA850_WLAN_EN, 1);
msleep(70);
} else {
gpio_set_value(DA850_WLAN_EN, 0);
}
}
static struct davinci_mmc_config da850_wl12xx_mmc_config = {
.set_power = wl12xx_set_power,
.wires = 4,
.max_freq = 25000000,
.caps = MMC_CAP_4_BIT_DATA | MMC_CAP_NONREMOVABLE |
MMC_CAP_POWER_OFF_CARD,
.version = MMC_CTLR_VERSION_2,
};
static const short da850_wl12xx_pins[] __initconst = {
DA850_MMCSD1_DAT_0, DA850_MMCSD1_DAT_1, DA850_MMCSD1_DAT_2,
DA850_MMCSD1_DAT_3, DA850_MMCSD1_CLK, DA850_MMCSD1_CMD,
DA850_GPIO6_9, DA850_GPIO6_10,
-1
};
static struct wl12xx_platform_data da850_wl12xx_wlan_data __initdata = {
.irq = -1,
.board_ref_clock = WL12XX_REFCLOCK_38,
.platform_quirks = WL12XX_PLATFORM_QUIRK_EDGE_IRQ,
};
static __init int da850_wl12xx_init(void)
{
int ret;
ret = davinci_cfg_reg_list(da850_wl12xx_pins);
if (ret) {
pr_err("wl12xx/mmc mux setup failed: %d\n", ret);
goto exit;
}
ret = da850_register_mmcsd1(&da850_wl12xx_mmc_config);
if (ret) {
pr_err("wl12xx/mmc registration failed: %d\n", ret);
goto exit;
}
ret = gpio_request_one(DA850_WLAN_EN, GPIOF_OUT_INIT_LOW, "wl12xx_en");
if (ret) {
pr_err("Could not request wl12xx enable gpio: %d\n", ret);
goto exit;
}
ret = gpio_request_one(DA850_WLAN_IRQ, GPIOF_IN, "wl12xx_irq");
if (ret) {
pr_err("Could not request wl12xx irq gpio: %d\n", ret);
goto free_wlan_en;
}
da850_wl12xx_wlan_data.irq = gpio_to_irq(DA850_WLAN_IRQ);
ret = wl12xx_set_platform_data(&da850_wl12xx_wlan_data);
if (ret) {
pr_err("Could not set wl12xx data: %d\n", ret);
goto free_wlan_irq;
}
return 0;
free_wlan_irq:
gpio_free(DA850_WLAN_IRQ);
free_wlan_en:
gpio_free(DA850_WLAN_EN);
exit:
return ret;
}
#else /* CONFIG_DA850_WL12XX */
static __init int da850_wl12xx_init(void)
{
return 0;
}
#endif /* CONFIG_DA850_WL12XX */
#define DA850EVM_SATA_REFCLKPN_RATE (100 * 1000 * 1000)
static __init void da850_evm_init(void)
{
int ret;
ret = pmic_tps65070_init();
if (ret)
pr_warning("da850_evm_init: TPS65070 PMIC init failed: %d\n",
ret);
ret = da850_register_edma(da850_edma_rsv);
if (ret)
pr_warning("da850_evm_init: edma registration failed: %d\n",
ret);
ret = davinci_cfg_reg_list(da850_i2c0_pins);
if (ret)
pr_warning("da850_evm_init: i2c0 mux setup failed: %d\n",
ret);
ret = da8xx_register_i2c(0, &da850_evm_i2c_0_pdata);
if (ret)
pr_warning("da850_evm_init: i2c0 registration failed: %d\n",
ret);
ret = da8xx_register_watchdog();
if (ret)
pr_warning("da830_evm_init: watchdog registration failed: %d\n",
ret);
if (HAS_MMC) {
ret = davinci_cfg_reg_list(da850_evm_mmcsd0_pins);
if (ret)
pr_warning("da850_evm_init: mmcsd0 mux setup failed:"
" %d\n", ret);
ret = gpio_request(DA850_MMCSD_CD_PIN, "MMC CD\n");
if (ret)
pr_warning("da850_evm_init: can not open GPIO %d\n",
DA850_MMCSD_CD_PIN);
gpio_direction_input(DA850_MMCSD_CD_PIN);
ret = gpio_request(DA850_MMCSD_WP_PIN, "MMC WP\n");
if (ret)
pr_warning("da850_evm_init: can not open GPIO %d\n",
DA850_MMCSD_WP_PIN);
gpio_direction_input(DA850_MMCSD_WP_PIN);
ret = da8xx_register_mmcsd0(&da850_mmc_config);
if (ret)
pr_warning("da850_evm_init: mmcsd0 registration failed:"
" %d\n", ret);
ret = da850_wl12xx_init();
if (ret)
pr_warning("da850_evm_init: wl12xx initialization"
" failed: %d\n", ret);
}
davinci_serial_init(&da850_evm_uart_config);
i2c_register_board_info(1, da850_evm_i2c_devices,
ARRAY_SIZE(da850_evm_i2c_devices));
/*
* shut down uart 0 and 1; they are not used on the board and
* accessing them causes endless "too much work in irq53" messages
* with arago fs
*/
__raw_writel(0, IO_ADDRESS(DA8XX_UART1_BASE) + 0x30);
__raw_writel(0, IO_ADDRESS(DA8XX_UART0_BASE) + 0x30);
ret = davinci_cfg_reg_list(da850_evm_mcasp_pins);
if (ret)
pr_warning("da850_evm_init: mcasp mux setup failed: %d\n",
ret);
da850_evm_snd_data.sram_pool = sram_get_gen_pool();
da8xx_register_mcasp(0, &da850_evm_snd_data);
ret = davinci_cfg_reg_list(da850_lcdcntl_pins);
if (ret)
pr_warning("da850_evm_init: lcdcntl mux setup failed: %d\n",
ret);
ret = da8xx_register_uio_pruss();
if (ret)
pr_warn("da850_evm_init: pruss initialization failed: %d\n",
ret);
/* Handle board specific muxing for LCD here */
ret = davinci_cfg_reg_list(da850_evm_lcdc_pins);
if (ret)
pr_warning("da850_evm_init: evm specific lcd mux setup "
"failed: %d\n", ret);
ret = da850_lcd_hw_init();
if (ret)
pr_warning("da850_evm_init: lcd initialization failed: %d\n",
ret);
sharp_lk043t1dg01_pdata.panel_power_ctrl = da850_panel_power_ctrl,
ret = da8xx_register_lcdc(&sharp_lk043t1dg01_pdata);
if (ret)
pr_warning("da850_evm_init: lcdc registration failed: %d\n",
ret);
ret = da8xx_register_rtc();
if (ret)
pr_warning("da850_evm_init: rtc setup failed: %d\n", ret);
ret = da850_evm_init_cpufreq();
if (ret)
pr_warning("da850_evm_init: cpufreq registration failed: %d\n",
ret);
ret = da8xx_register_cpuidle();
if (ret)
pr_warning("da850_evm_init: cpuidle registration failed: %d\n",
ret);
ret = da850_register_pm(&da850_pm_device);
if (ret)
pr_warning("da850_evm_init: suspend registration failed: %d\n",
ret);
da850_vpif_init();
ret = da8xx_register_spi(1, da850evm_spi_info,
ARRAY_SIZE(da850evm_spi_info));
if (ret)
pr_warning("da850_evm_init: spi 1 registration failed: %d\n",
ret);
ret = da850_register_sata(DA850EVM_SATA_REFCLKPN_RATE);
if (ret)
pr_warning("da850_evm_init: sata registration failed: %d\n",
ret);
da850_evm_setup_mac_addr();
}
#ifdef CONFIG_SERIAL_8250_CONSOLE
static int __init da850_evm_console_init(void)
{
if (!machine_is_davinci_da850_evm())
return 0;
return add_preferred_console("ttyS", 2, "115200");
}
console_initcall(da850_evm_console_init);
#endif
static void __init da850_evm_map_io(void)
{
da850_init();
}
MACHINE_START(DAVINCI_DA850_EVM, "DaVinci DA850/OMAP-L138/AM18x EVM")
.atag_offset = 0x100,
.map_io = da850_evm_map_io,
.init_irq = cp_intc_init,
.timer = &davinci_timer,
.init_machine = da850_evm_init,
.init_late = davinci_init_late,
.dma_zone_size = SZ_128M,
.restart = da8xx_restart,
MACHINE_END
| gpl-2.0 |
Brainiarc7/XenGT-Preview-kernel | drivers/crypto/caam/jr.c | 351 | 14251 | /*
* CAAM/SEC 4.x transport/backend driver
* JobR backend functionality
*
* Copyright 2008-2012 Freescale Semiconductor, Inc.
*/
#include <linux/of_irq.h>
#include <linux/of_address.h>
#include "compat.h"
#include "regs.h"
#include "jr.h"
#include "desc.h"
#include "intern.h"
struct jr_driver_data {
/* List of Physical JobR's with the Driver */
struct list_head jr_list;
spinlock_t jr_alloc_lock; /* jr_list lock */
} ____cacheline_aligned;
static struct jr_driver_data driver_data;
static int caam_reset_hw_jr(struct device *dev)
{
struct caam_drv_private_jr *jrp = dev_get_drvdata(dev);
unsigned int timeout = 100000;
/*
* mask interrupts since we are going to poll
* for reset completion status
*/
setbits32(&jrp->rregs->rconfig_lo, JRCFG_IMSK);
/* initiate flush (required prior to reset) */
wr_reg32(&jrp->rregs->jrcommand, JRCR_RESET);
while (((rd_reg32(&jrp->rregs->jrintstatus) & JRINT_ERR_HALT_MASK) ==
JRINT_ERR_HALT_INPROGRESS) && --timeout)
cpu_relax();
if ((rd_reg32(&jrp->rregs->jrintstatus) & JRINT_ERR_HALT_MASK) !=
JRINT_ERR_HALT_COMPLETE || timeout == 0) {
dev_err(dev, "failed to flush job ring %d\n", jrp->ridx);
return -EIO;
}
/* initiate reset */
timeout = 100000;
wr_reg32(&jrp->rregs->jrcommand, JRCR_RESET);
while ((rd_reg32(&jrp->rregs->jrcommand) & JRCR_RESET) && --timeout)
cpu_relax();
if (timeout == 0) {
dev_err(dev, "failed to reset job ring %d\n", jrp->ridx);
return -EIO;
}
/* unmask interrupts */
clrbits32(&jrp->rregs->rconfig_lo, JRCFG_IMSK);
return 0;
}
/*
* Shutdown JobR independent of platform property code
*/
int caam_jr_shutdown(struct device *dev)
{
struct caam_drv_private_jr *jrp = dev_get_drvdata(dev);
dma_addr_t inpbusaddr, outbusaddr;
int ret;
ret = caam_reset_hw_jr(dev);
tasklet_kill(&jrp->irqtask);
/* Release interrupt */
free_irq(jrp->irq, dev);
/* Free rings */
inpbusaddr = rd_reg64(&jrp->rregs->inpring_base);
outbusaddr = rd_reg64(&jrp->rregs->outring_base);
dma_free_coherent(dev, sizeof(dma_addr_t) * JOBR_DEPTH,
jrp->inpring, inpbusaddr);
dma_free_coherent(dev, sizeof(struct jr_outentry) * JOBR_DEPTH,
jrp->outring, outbusaddr);
kfree(jrp->entinfo);
return ret;
}
static int caam_jr_remove(struct platform_device *pdev)
{
int ret;
struct device *jrdev;
struct caam_drv_private_jr *jrpriv;
jrdev = &pdev->dev;
jrpriv = dev_get_drvdata(jrdev);
/*
* Return EBUSY if job ring already allocated.
*/
if (atomic_read(&jrpriv->tfm_count)) {
dev_err(jrdev, "Device is busy\n");
return -EBUSY;
}
/* Remove the node from Physical JobR list maintained by driver */
spin_lock(&driver_data.jr_alloc_lock);
list_del(&jrpriv->list_node);
spin_unlock(&driver_data.jr_alloc_lock);
/* Release ring */
ret = caam_jr_shutdown(jrdev);
if (ret)
dev_err(jrdev, "Failed to shut down job ring\n");
irq_dispose_mapping(jrpriv->irq);
return ret;
}
/* Main per-ring interrupt handler */
static irqreturn_t caam_jr_interrupt(int irq, void *st_dev)
{
struct device *dev = st_dev;
struct caam_drv_private_jr *jrp = dev_get_drvdata(dev);
u32 irqstate;
/*
* Check the output ring for ready responses, kick
* tasklet if jobs done.
*/
irqstate = rd_reg32(&jrp->rregs->jrintstatus);
if (!irqstate)
return IRQ_NONE;
/*
* If JobR error, we got more development work to do
* Flag a bug now, but we really need to shut down and
* restart the queue (and fix code).
*/
if (irqstate & JRINT_JR_ERROR) {
dev_err(dev, "job ring error: irqstate: %08x\n", irqstate);
BUG();
}
/* mask valid interrupts */
setbits32(&jrp->rregs->rconfig_lo, JRCFG_IMSK);
/* Have valid interrupt at this point, just ACK and trigger */
wr_reg32(&jrp->rregs->jrintstatus, irqstate);
preempt_disable();
tasklet_schedule(&jrp->irqtask);
preempt_enable();
return IRQ_HANDLED;
}
/* Deferred service handler, run as interrupt-fired tasklet */
static void caam_jr_dequeue(unsigned long devarg)
{
int hw_idx, sw_idx, i, head, tail;
struct device *dev = (struct device *)devarg;
struct caam_drv_private_jr *jrp = dev_get_drvdata(dev);
void (*usercall)(struct device *dev, u32 *desc, u32 status, void *arg);
u32 *userdesc, userstatus;
void *userarg;
while (rd_reg32(&jrp->rregs->outring_used)) {
head = ACCESS_ONCE(jrp->head);
spin_lock(&jrp->outlock);
sw_idx = tail = jrp->tail;
hw_idx = jrp->out_ring_read_index;
for (i = 0; CIRC_CNT(head, tail + i, JOBR_DEPTH) >= 1; i++) {
sw_idx = (tail + i) & (JOBR_DEPTH - 1);
smp_read_barrier_depends();
if (jrp->outring[hw_idx].desc ==
jrp->entinfo[sw_idx].desc_addr_dma)
break; /* found */
}
/* we should never fail to find a matching descriptor */
BUG_ON(CIRC_CNT(head, tail + i, JOBR_DEPTH) <= 0);
/* Unmap just-run descriptor so we can post-process */
dma_unmap_single(dev, jrp->outring[hw_idx].desc,
jrp->entinfo[sw_idx].desc_size,
DMA_TO_DEVICE);
/* mark completed, avoid matching on a recycled desc addr */
jrp->entinfo[sw_idx].desc_addr_dma = 0;
/* Stash callback params for use outside of lock */
usercall = jrp->entinfo[sw_idx].callbk;
userarg = jrp->entinfo[sw_idx].cbkarg;
userdesc = jrp->entinfo[sw_idx].desc_addr_virt;
userstatus = jrp->outring[hw_idx].jrstatus;
/* set done */
wr_reg32(&jrp->rregs->outring_rmvd, 1);
jrp->out_ring_read_index = (jrp->out_ring_read_index + 1) &
(JOBR_DEPTH - 1);
/*
* if this job completed out-of-order, do not increment
* the tail. Otherwise, increment tail by 1 plus the
* number of subsequent jobs already completed out-of-order
*/
if (sw_idx == tail) {
do {
tail = (tail + 1) & (JOBR_DEPTH - 1);
smp_read_barrier_depends();
} while (CIRC_CNT(head, tail, JOBR_DEPTH) >= 1 &&
jrp->entinfo[tail].desc_addr_dma == 0);
jrp->tail = tail;
}
spin_unlock(&jrp->outlock);
/* Finally, execute user's callback */
usercall(dev, userdesc, userstatus, userarg);
}
/* reenable / unmask IRQs */
clrbits32(&jrp->rregs->rconfig_lo, JRCFG_IMSK);
}
/**
* caam_jr_alloc() - Alloc a job ring for someone to use as needed.
*
* returns : pointer to the newly allocated physical
* JobR dev can be written to if successful.
**/
struct device *caam_jr_alloc(void)
{
struct caam_drv_private_jr *jrpriv, *min_jrpriv = NULL;
struct device *dev = NULL;
int min_tfm_cnt = INT_MAX;
int tfm_cnt;
spin_lock(&driver_data.jr_alloc_lock);
if (list_empty(&driver_data.jr_list)) {
spin_unlock(&driver_data.jr_alloc_lock);
return ERR_PTR(-ENODEV);
}
list_for_each_entry(jrpriv, &driver_data.jr_list, list_node) {
tfm_cnt = atomic_read(&jrpriv->tfm_count);
if (tfm_cnt < min_tfm_cnt) {
min_tfm_cnt = tfm_cnt;
min_jrpriv = jrpriv;
}
if (!min_tfm_cnt)
break;
}
if (min_jrpriv) {
atomic_inc(&min_jrpriv->tfm_count);
dev = min_jrpriv->dev;
}
spin_unlock(&driver_data.jr_alloc_lock);
return dev;
}
EXPORT_SYMBOL(caam_jr_alloc);
/**
* caam_jr_free() - Free the Job Ring
* @rdev - points to the dev that identifies the Job ring to
* be released.
**/
void caam_jr_free(struct device *rdev)
{
struct caam_drv_private_jr *jrpriv = dev_get_drvdata(rdev);
atomic_dec(&jrpriv->tfm_count);
}
EXPORT_SYMBOL(caam_jr_free);
/**
* caam_jr_enqueue() - Enqueue a job descriptor head. Returns 0 if OK,
* -EBUSY if the queue is full, -EIO if it cannot map the caller's
* descriptor.
* @dev: device of the job ring to be used. This device should have
* been assigned prior by caam_jr_register().
* @desc: points to a job descriptor that execute our request. All
* descriptors (and all referenced data) must be in a DMAable
* region, and all data references must be physical addresses
* accessible to CAAM (i.e. within a PAMU window granted
* to it).
* @cbk: pointer to a callback function to be invoked upon completion
* of this request. This has the form:
* callback(struct device *dev, u32 *desc, u32 stat, void *arg)
* where:
* @dev: contains the job ring device that processed this
* response.
* @desc: descriptor that initiated the request, same as
* "desc" being argued to caam_jr_enqueue().
* @status: untranslated status received from CAAM. See the
* reference manual for a detailed description of
* error meaning, or see the JRSTA definitions in the
* register header file
* @areq: optional pointer to an argument passed with the
* original request
* @areq: optional pointer to a user argument for use at callback
* time.
**/
int caam_jr_enqueue(struct device *dev, u32 *desc,
void (*cbk)(struct device *dev, u32 *desc,
u32 status, void *areq),
void *areq)
{
struct caam_drv_private_jr *jrp = dev_get_drvdata(dev);
struct caam_jrentry_info *head_entry;
int head, tail, desc_size;
dma_addr_t desc_dma;
desc_size = (*desc & HDR_JD_LENGTH_MASK) * sizeof(u32);
desc_dma = dma_map_single(dev, desc, desc_size, DMA_TO_DEVICE);
if (dma_mapping_error(dev, desc_dma)) {
dev_err(dev, "caam_jr_enqueue(): can't map jobdesc\n");
return -EIO;
}
spin_lock_bh(&jrp->inplock);
head = jrp->head;
tail = ACCESS_ONCE(jrp->tail);
if (!rd_reg32(&jrp->rregs->inpring_avail) ||
CIRC_SPACE(head, tail, JOBR_DEPTH) <= 0) {
spin_unlock_bh(&jrp->inplock);
dma_unmap_single(dev, desc_dma, desc_size, DMA_TO_DEVICE);
return -EBUSY;
}
head_entry = &jrp->entinfo[head];
head_entry->desc_addr_virt = desc;
head_entry->desc_size = desc_size;
head_entry->callbk = (void *)cbk;
head_entry->cbkarg = areq;
head_entry->desc_addr_dma = desc_dma;
jrp->inpring[jrp->inp_ring_write_index] = desc_dma;
smp_wmb();
jrp->inp_ring_write_index = (jrp->inp_ring_write_index + 1) &
(JOBR_DEPTH - 1);
jrp->head = (head + 1) & (JOBR_DEPTH - 1);
wr_reg32(&jrp->rregs->inpring_jobadd, 1);
spin_unlock_bh(&jrp->inplock);
return 0;
}
EXPORT_SYMBOL(caam_jr_enqueue);
/*
* Init JobR independent of platform property detection
*/
static int caam_jr_init(struct device *dev)
{
struct caam_drv_private_jr *jrp;
dma_addr_t inpbusaddr, outbusaddr;
int i, error;
jrp = dev_get_drvdata(dev);
tasklet_init(&jrp->irqtask, caam_jr_dequeue, (unsigned long)dev);
/* Connect job ring interrupt handler. */
error = request_irq(jrp->irq, caam_jr_interrupt, IRQF_SHARED,
dev_name(dev), dev);
if (error) {
dev_err(dev, "can't connect JobR %d interrupt (%d)\n",
jrp->ridx, jrp->irq);
irq_dispose_mapping(jrp->irq);
jrp->irq = 0;
return -EINVAL;
}
error = caam_reset_hw_jr(dev);
if (error)
return error;
jrp->inpring = dma_alloc_coherent(dev, sizeof(dma_addr_t) * JOBR_DEPTH,
&inpbusaddr, GFP_KERNEL);
jrp->outring = dma_alloc_coherent(dev, sizeof(struct jr_outentry) *
JOBR_DEPTH, &outbusaddr, GFP_KERNEL);
jrp->entinfo = kzalloc(sizeof(struct caam_jrentry_info) * JOBR_DEPTH,
GFP_KERNEL);
if ((jrp->inpring == NULL) || (jrp->outring == NULL) ||
(jrp->entinfo == NULL)) {
dev_err(dev, "can't allocate job rings for %d\n",
jrp->ridx);
return -ENOMEM;
}
for (i = 0; i < JOBR_DEPTH; i++)
jrp->entinfo[i].desc_addr_dma = !0;
/* Setup rings */
jrp->inp_ring_write_index = 0;
jrp->out_ring_read_index = 0;
jrp->head = 0;
jrp->tail = 0;
wr_reg64(&jrp->rregs->inpring_base, inpbusaddr);
wr_reg64(&jrp->rregs->outring_base, outbusaddr);
wr_reg32(&jrp->rregs->inpring_size, JOBR_DEPTH);
wr_reg32(&jrp->rregs->outring_size, JOBR_DEPTH);
jrp->ringsize = JOBR_DEPTH;
spin_lock_init(&jrp->inplock);
spin_lock_init(&jrp->outlock);
/* Select interrupt coalescing parameters */
setbits32(&jrp->rregs->rconfig_lo, JOBR_INTC |
(JOBR_INTC_COUNT_THLD << JRCFG_ICDCT_SHIFT) |
(JOBR_INTC_TIME_THLD << JRCFG_ICTT_SHIFT));
return 0;
}
/*
* Probe routine for each detected JobR subsystem.
*/
static int caam_jr_probe(struct platform_device *pdev)
{
struct device *jrdev;
struct device_node *nprop;
struct caam_job_ring __iomem *ctrl;
struct caam_drv_private_jr *jrpriv;
static int total_jobrs;
int error;
jrdev = &pdev->dev;
jrpriv = devm_kmalloc(jrdev, sizeof(struct caam_drv_private_jr),
GFP_KERNEL);
if (!jrpriv)
return -ENOMEM;
dev_set_drvdata(jrdev, jrpriv);
/* save ring identity relative to detection */
jrpriv->ridx = total_jobrs++;
nprop = pdev->dev.of_node;
/* Get configuration properties from device tree */
/* First, get register page */
ctrl = of_iomap(nprop, 0);
if (!ctrl) {
dev_err(jrdev, "of_iomap() failed\n");
return -ENOMEM;
}
jrpriv->rregs = (struct caam_job_ring __force *)ctrl;
if (sizeof(dma_addr_t) == sizeof(u64))
if (of_device_is_compatible(nprop, "fsl,sec-v5.0-job-ring"))
dma_set_mask_and_coherent(jrdev, DMA_BIT_MASK(40));
else
dma_set_mask_and_coherent(jrdev, DMA_BIT_MASK(36));
else
dma_set_mask_and_coherent(jrdev, DMA_BIT_MASK(32));
/* Identify the interrupt */
jrpriv->irq = irq_of_parse_and_map(nprop, 0);
/* Now do the platform independent part */
error = caam_jr_init(jrdev); /* now turn on hardware */
if (error)
return error;
jrpriv->dev = jrdev;
spin_lock(&driver_data.jr_alloc_lock);
list_add_tail(&jrpriv->list_node, &driver_data.jr_list);
spin_unlock(&driver_data.jr_alloc_lock);
atomic_set(&jrpriv->tfm_count, 0);
return 0;
}
static struct of_device_id caam_jr_match[] = {
{
.compatible = "fsl,sec-v4.0-job-ring",
},
{
.compatible = "fsl,sec4.0-job-ring",
},
{},
};
MODULE_DEVICE_TABLE(of, caam_jr_match);
static struct platform_driver caam_jr_driver = {
.driver = {
.name = "caam_jr",
.owner = THIS_MODULE,
.of_match_table = caam_jr_match,
},
.probe = caam_jr_probe,
.remove = caam_jr_remove,
};
static int __init jr_driver_init(void)
{
spin_lock_init(&driver_data.jr_alloc_lock);
INIT_LIST_HEAD(&driver_data.jr_list);
return platform_driver_register(&caam_jr_driver);
}
static void __exit jr_driver_exit(void)
{
platform_driver_unregister(&caam_jr_driver);
}
module_init(jr_driver_init);
module_exit(jr_driver_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("FSL CAAM JR request backend");
MODULE_AUTHOR("Freescale Semiconductor - NMG/STC");
| gpl-2.0 |
gshirishfree/linux | fs/stat.c | 607 | 12237 | /*
* linux/fs/stat.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*/
#include <linux/export.h>
#include <linux/mm.h>
#include <linux/errno.h>
#include <linux/file.h>
#include <linux/highuid.h>
#include <linux/fs.h>
#include <linux/namei.h>
#include <linux/security.h>
#include <linux/syscalls.h>
#include <linux/pagemap.h>
#include <asm/uaccess.h>
#include <asm/unistd.h>
void generic_fillattr(struct inode *inode, struct kstat *stat)
{
stat->dev = inode->i_sb->s_dev;
stat->ino = inode->i_ino;
stat->mode = inode->i_mode;
stat->nlink = inode->i_nlink;
stat->uid = inode->i_uid;
stat->gid = inode->i_gid;
stat->rdev = inode->i_rdev;
stat->size = i_size_read(inode);
stat->atime = inode->i_atime;
stat->mtime = inode->i_mtime;
stat->ctime = inode->i_ctime;
stat->blksize = (1 << inode->i_blkbits);
stat->blocks = inode->i_blocks;
}
EXPORT_SYMBOL(generic_fillattr);
/**
* vfs_getattr_nosec - getattr without security checks
* @path: file to get attributes from
* @stat: structure to return attributes in
*
* Get attributes without calling security_inode_getattr.
*
* Currently the only caller other than vfs_getattr is internal to the
* filehandle lookup code, which uses only the inode number and returns
* no attributes to any user. Any other code probably wants
* vfs_getattr.
*/
int vfs_getattr_nosec(struct path *path, struct kstat *stat)
{
struct inode *inode = d_backing_inode(path->dentry);
if (inode->i_op->getattr)
return inode->i_op->getattr(path->mnt, path->dentry, stat);
generic_fillattr(inode, stat);
return 0;
}
EXPORT_SYMBOL(vfs_getattr_nosec);
int vfs_getattr(struct path *path, struct kstat *stat)
{
int retval;
retval = security_inode_getattr(path);
if (retval)
return retval;
return vfs_getattr_nosec(path, stat);
}
EXPORT_SYMBOL(vfs_getattr);
int vfs_fstat(unsigned int fd, struct kstat *stat)
{
struct fd f = fdget_raw(fd);
int error = -EBADF;
if (f.file) {
error = vfs_getattr(&f.file->f_path, stat);
fdput(f);
}
return error;
}
EXPORT_SYMBOL(vfs_fstat);
int vfs_fstatat(int dfd, const char __user *filename, struct kstat *stat,
int flag)
{
struct path path;
int error = -EINVAL;
unsigned int lookup_flags = 0;
if ((flag & ~(AT_SYMLINK_NOFOLLOW | AT_NO_AUTOMOUNT |
AT_EMPTY_PATH)) != 0)
goto out;
if (!(flag & AT_SYMLINK_NOFOLLOW))
lookup_flags |= LOOKUP_FOLLOW;
if (flag & AT_EMPTY_PATH)
lookup_flags |= LOOKUP_EMPTY;
retry:
error = user_path_at(dfd, filename, lookup_flags, &path);
if (error)
goto out;
error = vfs_getattr(&path, stat);
path_put(&path);
if (retry_estale(error, lookup_flags)) {
lookup_flags |= LOOKUP_REVAL;
goto retry;
}
out:
return error;
}
EXPORT_SYMBOL(vfs_fstatat);
int vfs_stat(const char __user *name, struct kstat *stat)
{
return vfs_fstatat(AT_FDCWD, name, stat, 0);
}
EXPORT_SYMBOL(vfs_stat);
int vfs_lstat(const char __user *name, struct kstat *stat)
{
return vfs_fstatat(AT_FDCWD, name, stat, AT_SYMLINK_NOFOLLOW);
}
EXPORT_SYMBOL(vfs_lstat);
#ifdef __ARCH_WANT_OLD_STAT
/*
* For backward compatibility? Maybe this should be moved
* into arch/i386 instead?
*/
static int cp_old_stat(struct kstat *stat, struct __old_kernel_stat __user * statbuf)
{
static int warncount = 5;
struct __old_kernel_stat tmp;
if (warncount > 0) {
warncount--;
printk(KERN_WARNING "VFS: Warning: %s using old stat() call. Recompile your binary.\n",
current->comm);
} else if (warncount < 0) {
/* it's laughable, but... */
warncount = 0;
}
memset(&tmp, 0, sizeof(struct __old_kernel_stat));
tmp.st_dev = old_encode_dev(stat->dev);
tmp.st_ino = stat->ino;
if (sizeof(tmp.st_ino) < sizeof(stat->ino) && tmp.st_ino != stat->ino)
return -EOVERFLOW;
tmp.st_mode = stat->mode;
tmp.st_nlink = stat->nlink;
if (tmp.st_nlink != stat->nlink)
return -EOVERFLOW;
SET_UID(tmp.st_uid, from_kuid_munged(current_user_ns(), stat->uid));
SET_GID(tmp.st_gid, from_kgid_munged(current_user_ns(), stat->gid));
tmp.st_rdev = old_encode_dev(stat->rdev);
#if BITS_PER_LONG == 32
if (stat->size > MAX_NON_LFS)
return -EOVERFLOW;
#endif
tmp.st_size = stat->size;
tmp.st_atime = stat->atime.tv_sec;
tmp.st_mtime = stat->mtime.tv_sec;
tmp.st_ctime = stat->ctime.tv_sec;
return copy_to_user(statbuf,&tmp,sizeof(tmp)) ? -EFAULT : 0;
}
SYSCALL_DEFINE2(stat, const char __user *, filename,
struct __old_kernel_stat __user *, statbuf)
{
struct kstat stat;
int error;
error = vfs_stat(filename, &stat);
if (error)
return error;
return cp_old_stat(&stat, statbuf);
}
SYSCALL_DEFINE2(lstat, const char __user *, filename,
struct __old_kernel_stat __user *, statbuf)
{
struct kstat stat;
int error;
error = vfs_lstat(filename, &stat);
if (error)
return error;
return cp_old_stat(&stat, statbuf);
}
SYSCALL_DEFINE2(fstat, unsigned int, fd, struct __old_kernel_stat __user *, statbuf)
{
struct kstat stat;
int error = vfs_fstat(fd, &stat);
if (!error)
error = cp_old_stat(&stat, statbuf);
return error;
}
#endif /* __ARCH_WANT_OLD_STAT */
#if BITS_PER_LONG == 32
# define choose_32_64(a,b) a
#else
# define choose_32_64(a,b) b
#endif
#define valid_dev(x) choose_32_64(old_valid_dev,new_valid_dev)(x)
#define encode_dev(x) choose_32_64(old_encode_dev,new_encode_dev)(x)
#ifndef INIT_STRUCT_STAT_PADDING
# define INIT_STRUCT_STAT_PADDING(st) memset(&st, 0, sizeof(st))
#endif
static int cp_new_stat(struct kstat *stat, struct stat __user *statbuf)
{
struct stat tmp;
if (!valid_dev(stat->dev) || !valid_dev(stat->rdev))
return -EOVERFLOW;
#if BITS_PER_LONG == 32
if (stat->size > MAX_NON_LFS)
return -EOVERFLOW;
#endif
INIT_STRUCT_STAT_PADDING(tmp);
tmp.st_dev = encode_dev(stat->dev);
tmp.st_ino = stat->ino;
if (sizeof(tmp.st_ino) < sizeof(stat->ino) && tmp.st_ino != stat->ino)
return -EOVERFLOW;
tmp.st_mode = stat->mode;
tmp.st_nlink = stat->nlink;
if (tmp.st_nlink != stat->nlink)
return -EOVERFLOW;
SET_UID(tmp.st_uid, from_kuid_munged(current_user_ns(), stat->uid));
SET_GID(tmp.st_gid, from_kgid_munged(current_user_ns(), stat->gid));
tmp.st_rdev = encode_dev(stat->rdev);
tmp.st_size = stat->size;
tmp.st_atime = stat->atime.tv_sec;
tmp.st_mtime = stat->mtime.tv_sec;
tmp.st_ctime = stat->ctime.tv_sec;
#ifdef STAT_HAVE_NSEC
tmp.st_atime_nsec = stat->atime.tv_nsec;
tmp.st_mtime_nsec = stat->mtime.tv_nsec;
tmp.st_ctime_nsec = stat->ctime.tv_nsec;
#endif
tmp.st_blocks = stat->blocks;
tmp.st_blksize = stat->blksize;
return copy_to_user(statbuf,&tmp,sizeof(tmp)) ? -EFAULT : 0;
}
SYSCALL_DEFINE2(newstat, const char __user *, filename,
struct stat __user *, statbuf)
{
struct kstat stat;
int error = vfs_stat(filename, &stat);
if (error)
return error;
return cp_new_stat(&stat, statbuf);
}
SYSCALL_DEFINE2(newlstat, const char __user *, filename,
struct stat __user *, statbuf)
{
struct kstat stat;
int error;
error = vfs_lstat(filename, &stat);
if (error)
return error;
return cp_new_stat(&stat, statbuf);
}
#if !defined(__ARCH_WANT_STAT64) || defined(__ARCH_WANT_SYS_NEWFSTATAT)
SYSCALL_DEFINE4(newfstatat, int, dfd, const char __user *, filename,
struct stat __user *, statbuf, int, flag)
{
struct kstat stat;
int error;
error = vfs_fstatat(dfd, filename, &stat, flag);
if (error)
return error;
return cp_new_stat(&stat, statbuf);
}
#endif
SYSCALL_DEFINE2(newfstat, unsigned int, fd, struct stat __user *, statbuf)
{
struct kstat stat;
int error = vfs_fstat(fd, &stat);
if (!error)
error = cp_new_stat(&stat, statbuf);
return error;
}
SYSCALL_DEFINE4(readlinkat, int, dfd, const char __user *, pathname,
char __user *, buf, int, bufsiz)
{
struct path path;
int error;
int empty = 0;
unsigned int lookup_flags = LOOKUP_EMPTY;
if (bufsiz <= 0)
return -EINVAL;
retry:
error = user_path_at_empty(dfd, pathname, lookup_flags, &path, &empty);
if (!error) {
struct inode *inode = d_backing_inode(path.dentry);
error = empty ? -ENOENT : -EINVAL;
if (inode->i_op->readlink) {
error = security_inode_readlink(path.dentry);
if (!error) {
touch_atime(&path);
error = inode->i_op->readlink(path.dentry,
buf, bufsiz);
}
}
path_put(&path);
if (retry_estale(error, lookup_flags)) {
lookup_flags |= LOOKUP_REVAL;
goto retry;
}
}
return error;
}
SYSCALL_DEFINE3(readlink, const char __user *, path, char __user *, buf,
int, bufsiz)
{
return sys_readlinkat(AT_FDCWD, path, buf, bufsiz);
}
/* ---------- LFS-64 ----------- */
#if defined(__ARCH_WANT_STAT64) || defined(__ARCH_WANT_COMPAT_STAT64)
#ifndef INIT_STRUCT_STAT64_PADDING
# define INIT_STRUCT_STAT64_PADDING(st) memset(&st, 0, sizeof(st))
#endif
static long cp_new_stat64(struct kstat *stat, struct stat64 __user *statbuf)
{
struct stat64 tmp;
INIT_STRUCT_STAT64_PADDING(tmp);
#ifdef CONFIG_MIPS
/* mips has weird padding, so we don't get 64 bits there */
if (!new_valid_dev(stat->dev) || !new_valid_dev(stat->rdev))
return -EOVERFLOW;
tmp.st_dev = new_encode_dev(stat->dev);
tmp.st_rdev = new_encode_dev(stat->rdev);
#else
tmp.st_dev = huge_encode_dev(stat->dev);
tmp.st_rdev = huge_encode_dev(stat->rdev);
#endif
tmp.st_ino = stat->ino;
if (sizeof(tmp.st_ino) < sizeof(stat->ino) && tmp.st_ino != stat->ino)
return -EOVERFLOW;
#ifdef STAT64_HAS_BROKEN_ST_INO
tmp.__st_ino = stat->ino;
#endif
tmp.st_mode = stat->mode;
tmp.st_nlink = stat->nlink;
tmp.st_uid = from_kuid_munged(current_user_ns(), stat->uid);
tmp.st_gid = from_kgid_munged(current_user_ns(), stat->gid);
tmp.st_atime = stat->atime.tv_sec;
tmp.st_atime_nsec = stat->atime.tv_nsec;
tmp.st_mtime = stat->mtime.tv_sec;
tmp.st_mtime_nsec = stat->mtime.tv_nsec;
tmp.st_ctime = stat->ctime.tv_sec;
tmp.st_ctime_nsec = stat->ctime.tv_nsec;
tmp.st_size = stat->size;
tmp.st_blocks = stat->blocks;
tmp.st_blksize = stat->blksize;
return copy_to_user(statbuf,&tmp,sizeof(tmp)) ? -EFAULT : 0;
}
SYSCALL_DEFINE2(stat64, const char __user *, filename,
struct stat64 __user *, statbuf)
{
struct kstat stat;
int error = vfs_stat(filename, &stat);
if (!error)
error = cp_new_stat64(&stat, statbuf);
return error;
}
SYSCALL_DEFINE2(lstat64, const char __user *, filename,
struct stat64 __user *, statbuf)
{
struct kstat stat;
int error = vfs_lstat(filename, &stat);
if (!error)
error = cp_new_stat64(&stat, statbuf);
return error;
}
SYSCALL_DEFINE2(fstat64, unsigned long, fd, struct stat64 __user *, statbuf)
{
struct kstat stat;
int error = vfs_fstat(fd, &stat);
if (!error)
error = cp_new_stat64(&stat, statbuf);
return error;
}
SYSCALL_DEFINE4(fstatat64, int, dfd, const char __user *, filename,
struct stat64 __user *, statbuf, int, flag)
{
struct kstat stat;
int error;
error = vfs_fstatat(dfd, filename, &stat, flag);
if (error)
return error;
return cp_new_stat64(&stat, statbuf);
}
#endif /* __ARCH_WANT_STAT64 || __ARCH_WANT_COMPAT_STAT64 */
/* Caller is here responsible for sufficient locking (ie. inode->i_lock) */
void __inode_add_bytes(struct inode *inode, loff_t bytes)
{
inode->i_blocks += bytes >> 9;
bytes &= 511;
inode->i_bytes += bytes;
if (inode->i_bytes >= 512) {
inode->i_blocks++;
inode->i_bytes -= 512;
}
}
void inode_add_bytes(struct inode *inode, loff_t bytes)
{
spin_lock(&inode->i_lock);
__inode_add_bytes(inode, bytes);
spin_unlock(&inode->i_lock);
}
EXPORT_SYMBOL(inode_add_bytes);
void __inode_sub_bytes(struct inode *inode, loff_t bytes)
{
inode->i_blocks -= bytes >> 9;
bytes &= 511;
if (inode->i_bytes < bytes) {
inode->i_blocks--;
inode->i_bytes += 512;
}
inode->i_bytes -= bytes;
}
EXPORT_SYMBOL(__inode_sub_bytes);
void inode_sub_bytes(struct inode *inode, loff_t bytes)
{
spin_lock(&inode->i_lock);
__inode_sub_bytes(inode, bytes);
spin_unlock(&inode->i_lock);
}
EXPORT_SYMBOL(inode_sub_bytes);
loff_t inode_get_bytes(struct inode *inode)
{
loff_t ret;
spin_lock(&inode->i_lock);
ret = (((loff_t)inode->i_blocks) << 9) + inode->i_bytes;
spin_unlock(&inode->i_lock);
return ret;
}
EXPORT_SYMBOL(inode_get_bytes);
void inode_set_bytes(struct inode *inode, loff_t bytes)
{
/* Caller is here responsible for sufficient locking
* (ie. inode->i_lock) */
inode->i_blocks = bytes >> 9;
inode->i_bytes = bytes & 511;
}
EXPORT_SYMBOL(inode_set_bytes);
| gpl-2.0 |
TangxingZhou/linux | net/dccp/diag.c | 1119 | 2382 | /*
* net/dccp/diag.c
*
* An implementation of the DCCP protocol
* Arnaldo Carvalho de Melo <acme@mandriva.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/inet_diag.h>
#include "ccid.h"
#include "dccp.h"
static void dccp_get_info(struct sock *sk, struct tcp_info *info)
{
struct dccp_sock *dp = dccp_sk(sk);
const struct inet_connection_sock *icsk = inet_csk(sk);
memset(info, 0, sizeof(*info));
info->tcpi_state = sk->sk_state;
info->tcpi_retransmits = icsk->icsk_retransmits;
info->tcpi_probes = icsk->icsk_probes_out;
info->tcpi_backoff = icsk->icsk_backoff;
info->tcpi_pmtu = icsk->icsk_pmtu_cookie;
if (dp->dccps_hc_rx_ackvec != NULL)
info->tcpi_options |= TCPI_OPT_SACK;
if (dp->dccps_hc_rx_ccid != NULL)
ccid_hc_rx_get_info(dp->dccps_hc_rx_ccid, sk, info);
if (dp->dccps_hc_tx_ccid != NULL)
ccid_hc_tx_get_info(dp->dccps_hc_tx_ccid, sk, info);
}
static void dccp_diag_get_info(struct sock *sk, struct inet_diag_msg *r,
void *_info)
{
r->idiag_rqueue = r->idiag_wqueue = 0;
if (_info != NULL)
dccp_get_info(sk, _info);
}
static void dccp_diag_dump(struct sk_buff *skb, struct netlink_callback *cb,
const struct inet_diag_req_v2 *r, struct nlattr *bc)
{
inet_diag_dump_icsk(&dccp_hashinfo, skb, cb, r, bc);
}
static int dccp_diag_dump_one(struct sk_buff *in_skb,
const struct nlmsghdr *nlh,
const struct inet_diag_req_v2 *req)
{
return inet_diag_dump_one_icsk(&dccp_hashinfo, in_skb, nlh, req);
}
static const struct inet_diag_handler dccp_diag_handler = {
.dump = dccp_diag_dump,
.dump_one = dccp_diag_dump_one,
.idiag_get_info = dccp_diag_get_info,
.idiag_type = IPPROTO_DCCP,
.idiag_info_size = sizeof(struct tcp_info),
};
static int __init dccp_diag_init(void)
{
return inet_diag_register(&dccp_diag_handler);
}
static void __exit dccp_diag_fini(void)
{
inet_diag_unregister(&dccp_diag_handler);
}
module_init(dccp_diag_init);
module_exit(dccp_diag_fini);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Arnaldo Carvalho de Melo <acme@mandriva.com>");
MODULE_DESCRIPTION("DCCP inet_diag handler");
MODULE_ALIAS_NET_PF_PROTO_TYPE(PF_NETLINK, NETLINK_SOCK_DIAG, 2-33 /* AF_INET - IPPROTO_DCCP */);
| gpl-2.0 |
mrjaydee82/angler | drivers/edac/edac_mc_sysfs.c | 1375 | 29628 | /*
* edac_mc kernel module
* (C) 2005-2007 Linux Networx (http://lnxi.com)
*
* This file may be distributed under the terms of the
* GNU General Public License.
*
* Written Doug Thompson <norsk5@xmission.com> www.softwarebitmaker.com
*
* (c) 2012-2013 - Mauro Carvalho Chehab <mchehab@redhat.com>
* The entire API were re-written, and ported to use struct device
*
*/
#include <linux/ctype.h>
#include <linux/slab.h>
#include <linux/edac.h>
#include <linux/bug.h>
#include <linux/pm_runtime.h>
#include <linux/uaccess.h>
#include "edac_core.h"
#include "edac_module.h"
/* MC EDAC Controls, setable by module parameter, and sysfs */
static int edac_mc_log_ue = 1;
static int edac_mc_log_ce = 1;
static int edac_mc_panic_on_ue;
static int edac_mc_poll_msec = 1000;
/* Getter functions for above */
int edac_mc_get_log_ue(void)
{
return edac_mc_log_ue;
}
int edac_mc_get_log_ce(void)
{
return edac_mc_log_ce;
}
int edac_mc_get_panic_on_ue(void)
{
return edac_mc_panic_on_ue;
}
/* this is temporary */
int edac_mc_get_poll_msec(void)
{
return edac_mc_poll_msec;
}
static int edac_set_poll_msec(const char *val, struct kernel_param *kp)
{
unsigned long l;
int ret;
if (!val)
return -EINVAL;
ret = kstrtoul(val, 0, &l);
if (ret)
return ret;
if (l < 1000)
return -EINVAL;
*((unsigned long *)kp->arg) = l;
/* notify edac_mc engine to reset the poll period */
edac_mc_reset_delay_period(l);
return 0;
}
/* Parameter declarations for above */
module_param(edac_mc_panic_on_ue, int, 0644);
MODULE_PARM_DESC(edac_mc_panic_on_ue, "Panic on uncorrected error: 0=off 1=on");
module_param(edac_mc_log_ue, int, 0644);
MODULE_PARM_DESC(edac_mc_log_ue,
"Log uncorrectable error to console: 0=off 1=on");
module_param(edac_mc_log_ce, int, 0644);
MODULE_PARM_DESC(edac_mc_log_ce,
"Log correctable error to console: 0=off 1=on");
module_param_call(edac_mc_poll_msec, edac_set_poll_msec, param_get_int,
&edac_mc_poll_msec, 0644);
MODULE_PARM_DESC(edac_mc_poll_msec, "Polling period in milliseconds");
static struct device *mci_pdev;
/*
* various constants for Memory Controllers
*/
static const char * const mem_types[] = {
[MEM_EMPTY] = "Empty",
[MEM_RESERVED] = "Reserved",
[MEM_UNKNOWN] = "Unknown",
[MEM_FPM] = "FPM",
[MEM_EDO] = "EDO",
[MEM_BEDO] = "BEDO",
[MEM_SDR] = "Unbuffered-SDR",
[MEM_RDR] = "Registered-SDR",
[MEM_DDR] = "Unbuffered-DDR",
[MEM_RDDR] = "Registered-DDR",
[MEM_RMBS] = "RMBS",
[MEM_DDR2] = "Unbuffered-DDR2",
[MEM_FB_DDR2] = "FullyBuffered-DDR2",
[MEM_RDDR2] = "Registered-DDR2",
[MEM_XDR] = "XDR",
[MEM_DDR3] = "Unbuffered-DDR3",
[MEM_RDDR3] = "Registered-DDR3"
};
static const char * const dev_types[] = {
[DEV_UNKNOWN] = "Unknown",
[DEV_X1] = "x1",
[DEV_X2] = "x2",
[DEV_X4] = "x4",
[DEV_X8] = "x8",
[DEV_X16] = "x16",
[DEV_X32] = "x32",
[DEV_X64] = "x64"
};
static const char * const edac_caps[] = {
[EDAC_UNKNOWN] = "Unknown",
[EDAC_NONE] = "None",
[EDAC_RESERVED] = "Reserved",
[EDAC_PARITY] = "PARITY",
[EDAC_EC] = "EC",
[EDAC_SECDED] = "SECDED",
[EDAC_S2ECD2ED] = "S2ECD2ED",
[EDAC_S4ECD4ED] = "S4ECD4ED",
[EDAC_S8ECD8ED] = "S8ECD8ED",
[EDAC_S16ECD16ED] = "S16ECD16ED"
};
#ifdef CONFIG_EDAC_LEGACY_SYSFS
/*
* EDAC sysfs CSROW data structures and methods
*/
#define to_csrow(k) container_of(k, struct csrow_info, dev)
/*
* We need it to avoid namespace conflicts between the legacy API
* and the per-dimm/per-rank one
*/
#define DEVICE_ATTR_LEGACY(_name, _mode, _show, _store) \
static struct device_attribute dev_attr_legacy_##_name = __ATTR(_name, _mode, _show, _store)
struct dev_ch_attribute {
struct device_attribute attr;
int channel;
};
#define DEVICE_CHANNEL(_name, _mode, _show, _store, _var) \
struct dev_ch_attribute dev_attr_legacy_##_name = \
{ __ATTR(_name, _mode, _show, _store), (_var) }
#define to_channel(k) (container_of(k, struct dev_ch_attribute, attr)->channel)
/* Set of more default csrow<id> attribute show/store functions */
static ssize_t csrow_ue_count_show(struct device *dev,
struct device_attribute *mattr, char *data)
{
struct csrow_info *csrow = to_csrow(dev);
return sprintf(data, "%u\n", csrow->ue_count);
}
static ssize_t csrow_ce_count_show(struct device *dev,
struct device_attribute *mattr, char *data)
{
struct csrow_info *csrow = to_csrow(dev);
return sprintf(data, "%u\n", csrow->ce_count);
}
static ssize_t csrow_size_show(struct device *dev,
struct device_attribute *mattr, char *data)
{
struct csrow_info *csrow = to_csrow(dev);
int i;
u32 nr_pages = 0;
for (i = 0; i < csrow->nr_channels; i++)
nr_pages += csrow->channels[i]->dimm->nr_pages;
return sprintf(data, "%u\n", PAGES_TO_MiB(nr_pages));
}
static ssize_t csrow_mem_type_show(struct device *dev,
struct device_attribute *mattr, char *data)
{
struct csrow_info *csrow = to_csrow(dev);
return sprintf(data, "%s\n", mem_types[csrow->channels[0]->dimm->mtype]);
}
static ssize_t csrow_dev_type_show(struct device *dev,
struct device_attribute *mattr, char *data)
{
struct csrow_info *csrow = to_csrow(dev);
return sprintf(data, "%s\n", dev_types[csrow->channels[0]->dimm->dtype]);
}
static ssize_t csrow_edac_mode_show(struct device *dev,
struct device_attribute *mattr,
char *data)
{
struct csrow_info *csrow = to_csrow(dev);
return sprintf(data, "%s\n", edac_caps[csrow->channels[0]->dimm->edac_mode]);
}
/* show/store functions for DIMM Label attributes */
static ssize_t channel_dimm_label_show(struct device *dev,
struct device_attribute *mattr,
char *data)
{
struct csrow_info *csrow = to_csrow(dev);
unsigned chan = to_channel(mattr);
struct rank_info *rank = csrow->channels[chan];
/* if field has not been initialized, there is nothing to send */
if (!rank->dimm->label[0])
return 0;
return snprintf(data, EDAC_MC_LABEL_LEN, "%s\n",
rank->dimm->label);
}
static ssize_t channel_dimm_label_store(struct device *dev,
struct device_attribute *mattr,
const char *data, size_t count)
{
struct csrow_info *csrow = to_csrow(dev);
unsigned chan = to_channel(mattr);
struct rank_info *rank = csrow->channels[chan];
ssize_t max_size = 0;
max_size = min((ssize_t) count, (ssize_t) EDAC_MC_LABEL_LEN - 1);
strncpy(rank->dimm->label, data, max_size);
rank->dimm->label[max_size] = '\0';
return max_size;
}
/* show function for dynamic chX_ce_count attribute */
static ssize_t channel_ce_count_show(struct device *dev,
struct device_attribute *mattr, char *data)
{
struct csrow_info *csrow = to_csrow(dev);
unsigned chan = to_channel(mattr);
struct rank_info *rank = csrow->channels[chan];
return sprintf(data, "%u\n", rank->ce_count);
}
/* cwrow<id>/attribute files */
DEVICE_ATTR_LEGACY(size_mb, S_IRUGO, csrow_size_show, NULL);
DEVICE_ATTR_LEGACY(dev_type, S_IRUGO, csrow_dev_type_show, NULL);
DEVICE_ATTR_LEGACY(mem_type, S_IRUGO, csrow_mem_type_show, NULL);
DEVICE_ATTR_LEGACY(edac_mode, S_IRUGO, csrow_edac_mode_show, NULL);
DEVICE_ATTR_LEGACY(ue_count, S_IRUGO, csrow_ue_count_show, NULL);
DEVICE_ATTR_LEGACY(ce_count, S_IRUGO, csrow_ce_count_show, NULL);
/* default attributes of the CSROW<id> object */
static struct attribute *csrow_attrs[] = {
&dev_attr_legacy_dev_type.attr,
&dev_attr_legacy_mem_type.attr,
&dev_attr_legacy_edac_mode.attr,
&dev_attr_legacy_size_mb.attr,
&dev_attr_legacy_ue_count.attr,
&dev_attr_legacy_ce_count.attr,
NULL,
};
static struct attribute_group csrow_attr_grp = {
.attrs = csrow_attrs,
};
static const struct attribute_group *csrow_attr_groups[] = {
&csrow_attr_grp,
NULL
};
static void csrow_attr_release(struct device *dev)
{
struct csrow_info *csrow = container_of(dev, struct csrow_info, dev);
edac_dbg(1, "Releasing csrow device %s\n", dev_name(dev));
kfree(csrow);
}
static struct device_type csrow_attr_type = {
.groups = csrow_attr_groups,
.release = csrow_attr_release,
};
/*
* possible dynamic channel DIMM Label attribute files
*
*/
#define EDAC_NR_CHANNELS 6
DEVICE_CHANNEL(ch0_dimm_label, S_IRUGO | S_IWUSR,
channel_dimm_label_show, channel_dimm_label_store, 0);
DEVICE_CHANNEL(ch1_dimm_label, S_IRUGO | S_IWUSR,
channel_dimm_label_show, channel_dimm_label_store, 1);
DEVICE_CHANNEL(ch2_dimm_label, S_IRUGO | S_IWUSR,
channel_dimm_label_show, channel_dimm_label_store, 2);
DEVICE_CHANNEL(ch3_dimm_label, S_IRUGO | S_IWUSR,
channel_dimm_label_show, channel_dimm_label_store, 3);
DEVICE_CHANNEL(ch4_dimm_label, S_IRUGO | S_IWUSR,
channel_dimm_label_show, channel_dimm_label_store, 4);
DEVICE_CHANNEL(ch5_dimm_label, S_IRUGO | S_IWUSR,
channel_dimm_label_show, channel_dimm_label_store, 5);
/* Total possible dynamic DIMM Label attribute file table */
static struct device_attribute *dynamic_csrow_dimm_attr[] = {
&dev_attr_legacy_ch0_dimm_label.attr,
&dev_attr_legacy_ch1_dimm_label.attr,
&dev_attr_legacy_ch2_dimm_label.attr,
&dev_attr_legacy_ch3_dimm_label.attr,
&dev_attr_legacy_ch4_dimm_label.attr,
&dev_attr_legacy_ch5_dimm_label.attr
};
/* possible dynamic channel ce_count attribute files */
DEVICE_CHANNEL(ch0_ce_count, S_IRUGO,
channel_ce_count_show, NULL, 0);
DEVICE_CHANNEL(ch1_ce_count, S_IRUGO,
channel_ce_count_show, NULL, 1);
DEVICE_CHANNEL(ch2_ce_count, S_IRUGO,
channel_ce_count_show, NULL, 2);
DEVICE_CHANNEL(ch3_ce_count, S_IRUGO,
channel_ce_count_show, NULL, 3);
DEVICE_CHANNEL(ch4_ce_count, S_IRUGO,
channel_ce_count_show, NULL, 4);
DEVICE_CHANNEL(ch5_ce_count, S_IRUGO,
channel_ce_count_show, NULL, 5);
/* Total possible dynamic ce_count attribute file table */
static struct device_attribute *dynamic_csrow_ce_count_attr[] = {
&dev_attr_legacy_ch0_ce_count.attr,
&dev_attr_legacy_ch1_ce_count.attr,
&dev_attr_legacy_ch2_ce_count.attr,
&dev_attr_legacy_ch3_ce_count.attr,
&dev_attr_legacy_ch4_ce_count.attr,
&dev_attr_legacy_ch5_ce_count.attr
};
static inline int nr_pages_per_csrow(struct csrow_info *csrow)
{
int chan, nr_pages = 0;
for (chan = 0; chan < csrow->nr_channels; chan++)
nr_pages += csrow->channels[chan]->dimm->nr_pages;
return nr_pages;
}
/* Create a CSROW object under specifed edac_mc_device */
static int edac_create_csrow_object(struct mem_ctl_info *mci,
struct csrow_info *csrow, int index)
{
int err, chan;
if (csrow->nr_channels >= EDAC_NR_CHANNELS)
return -ENODEV;
csrow->dev.type = &csrow_attr_type;
csrow->dev.bus = mci->bus;
device_initialize(&csrow->dev);
csrow->dev.parent = &mci->dev;
csrow->mci = mci;
dev_set_name(&csrow->dev, "csrow%d", index);
dev_set_drvdata(&csrow->dev, csrow);
edac_dbg(0, "creating (virtual) csrow node %s\n",
dev_name(&csrow->dev));
err = device_add(&csrow->dev);
if (err < 0)
return err;
for (chan = 0; chan < csrow->nr_channels; chan++) {
/* Only expose populated DIMMs */
if (!csrow->channels[chan]->dimm->nr_pages)
continue;
err = device_create_file(&csrow->dev,
dynamic_csrow_dimm_attr[chan]);
if (err < 0)
goto error;
err = device_create_file(&csrow->dev,
dynamic_csrow_ce_count_attr[chan]);
if (err < 0) {
device_remove_file(&csrow->dev,
dynamic_csrow_dimm_attr[chan]);
goto error;
}
}
return 0;
error:
for (--chan; chan >= 0; chan--) {
device_remove_file(&csrow->dev,
dynamic_csrow_dimm_attr[chan]);
device_remove_file(&csrow->dev,
dynamic_csrow_ce_count_attr[chan]);
}
put_device(&csrow->dev);
return err;
}
/* Create a CSROW object under specifed edac_mc_device */
static int edac_create_csrow_objects(struct mem_ctl_info *mci)
{
int err, i, chan;
struct csrow_info *csrow;
for (i = 0; i < mci->nr_csrows; i++) {
csrow = mci->csrows[i];
if (!nr_pages_per_csrow(csrow))
continue;
err = edac_create_csrow_object(mci, mci->csrows[i], i);
if (err < 0) {
edac_dbg(1,
"failure: create csrow objects for csrow %d\n",
i);
goto error;
}
}
return 0;
error:
for (--i; i >= 0; i--) {
csrow = mci->csrows[i];
if (!nr_pages_per_csrow(csrow))
continue;
for (chan = csrow->nr_channels - 1; chan >= 0; chan--) {
if (!csrow->channels[chan]->dimm->nr_pages)
continue;
device_remove_file(&csrow->dev,
dynamic_csrow_dimm_attr[chan]);
device_remove_file(&csrow->dev,
dynamic_csrow_ce_count_attr[chan]);
}
put_device(&mci->csrows[i]->dev);
}
return err;
}
static void edac_delete_csrow_objects(struct mem_ctl_info *mci)
{
int i, chan;
struct csrow_info *csrow;
for (i = mci->nr_csrows - 1; i >= 0; i--) {
csrow = mci->csrows[i];
if (!nr_pages_per_csrow(csrow))
continue;
for (chan = csrow->nr_channels - 1; chan >= 0; chan--) {
if (!csrow->channels[chan]->dimm->nr_pages)
continue;
edac_dbg(1, "Removing csrow %d channel %d sysfs nodes\n",
i, chan);
device_remove_file(&csrow->dev,
dynamic_csrow_dimm_attr[chan]);
device_remove_file(&csrow->dev,
dynamic_csrow_ce_count_attr[chan]);
}
device_unregister(&mci->csrows[i]->dev);
}
}
#endif
/*
* Per-dimm (or per-rank) devices
*/
#define to_dimm(k) container_of(k, struct dimm_info, dev)
/* show/store functions for DIMM Label attributes */
static ssize_t dimmdev_location_show(struct device *dev,
struct device_attribute *mattr, char *data)
{
struct dimm_info *dimm = to_dimm(dev);
return edac_dimm_info_location(dimm, data, PAGE_SIZE);
}
static ssize_t dimmdev_label_show(struct device *dev,
struct device_attribute *mattr, char *data)
{
struct dimm_info *dimm = to_dimm(dev);
/* if field has not been initialized, there is nothing to send */
if (!dimm->label[0])
return 0;
return snprintf(data, EDAC_MC_LABEL_LEN, "%s\n", dimm->label);
}
static ssize_t dimmdev_label_store(struct device *dev,
struct device_attribute *mattr,
const char *data,
size_t count)
{
struct dimm_info *dimm = to_dimm(dev);
ssize_t max_size = 0;
max_size = min((ssize_t) count, (ssize_t) EDAC_MC_LABEL_LEN - 1);
strncpy(dimm->label, data, max_size);
dimm->label[max_size] = '\0';
return max_size;
}
static ssize_t dimmdev_size_show(struct device *dev,
struct device_attribute *mattr, char *data)
{
struct dimm_info *dimm = to_dimm(dev);
return sprintf(data, "%u\n", PAGES_TO_MiB(dimm->nr_pages));
}
static ssize_t dimmdev_mem_type_show(struct device *dev,
struct device_attribute *mattr, char *data)
{
struct dimm_info *dimm = to_dimm(dev);
return sprintf(data, "%s\n", mem_types[dimm->mtype]);
}
static ssize_t dimmdev_dev_type_show(struct device *dev,
struct device_attribute *mattr, char *data)
{
struct dimm_info *dimm = to_dimm(dev);
return sprintf(data, "%s\n", dev_types[dimm->dtype]);
}
static ssize_t dimmdev_edac_mode_show(struct device *dev,
struct device_attribute *mattr,
char *data)
{
struct dimm_info *dimm = to_dimm(dev);
return sprintf(data, "%s\n", edac_caps[dimm->edac_mode]);
}
/* dimm/rank attribute files */
static DEVICE_ATTR(dimm_label, S_IRUGO | S_IWUSR,
dimmdev_label_show, dimmdev_label_store);
static DEVICE_ATTR(dimm_location, S_IRUGO, dimmdev_location_show, NULL);
static DEVICE_ATTR(size, S_IRUGO, dimmdev_size_show, NULL);
static DEVICE_ATTR(dimm_mem_type, S_IRUGO, dimmdev_mem_type_show, NULL);
static DEVICE_ATTR(dimm_dev_type, S_IRUGO, dimmdev_dev_type_show, NULL);
static DEVICE_ATTR(dimm_edac_mode, S_IRUGO, dimmdev_edac_mode_show, NULL);
/* attributes of the dimm<id>/rank<id> object */
static struct attribute *dimm_attrs[] = {
&dev_attr_dimm_label.attr,
&dev_attr_dimm_location.attr,
&dev_attr_size.attr,
&dev_attr_dimm_mem_type.attr,
&dev_attr_dimm_dev_type.attr,
&dev_attr_dimm_edac_mode.attr,
NULL,
};
static struct attribute_group dimm_attr_grp = {
.attrs = dimm_attrs,
};
static const struct attribute_group *dimm_attr_groups[] = {
&dimm_attr_grp,
NULL
};
static void dimm_attr_release(struct device *dev)
{
struct dimm_info *dimm = container_of(dev, struct dimm_info, dev);
edac_dbg(1, "Releasing dimm device %s\n", dev_name(dev));
kfree(dimm);
}
static struct device_type dimm_attr_type = {
.groups = dimm_attr_groups,
.release = dimm_attr_release,
};
/* Create a DIMM object under specifed memory controller device */
static int edac_create_dimm_object(struct mem_ctl_info *mci,
struct dimm_info *dimm,
int index)
{
int err;
dimm->mci = mci;
dimm->dev.type = &dimm_attr_type;
dimm->dev.bus = mci->bus;
device_initialize(&dimm->dev);
dimm->dev.parent = &mci->dev;
if (mci->csbased)
dev_set_name(&dimm->dev, "rank%d", index);
else
dev_set_name(&dimm->dev, "dimm%d", index);
dev_set_drvdata(&dimm->dev, dimm);
pm_runtime_forbid(&mci->dev);
err = device_add(&dimm->dev);
edac_dbg(0, "creating rank/dimm device %s\n", dev_name(&dimm->dev));
return err;
}
/*
* Memory controller device
*/
#define to_mci(k) container_of(k, struct mem_ctl_info, dev)
static ssize_t mci_reset_counters_store(struct device *dev,
struct device_attribute *mattr,
const char *data, size_t count)
{
struct mem_ctl_info *mci = to_mci(dev);
int cnt, row, chan, i;
mci->ue_mc = 0;
mci->ce_mc = 0;
mci->ue_noinfo_count = 0;
mci->ce_noinfo_count = 0;
for (row = 0; row < mci->nr_csrows; row++) {
struct csrow_info *ri = mci->csrows[row];
ri->ue_count = 0;
ri->ce_count = 0;
for (chan = 0; chan < ri->nr_channels; chan++)
ri->channels[chan]->ce_count = 0;
}
cnt = 1;
for (i = 0; i < mci->n_layers; i++) {
cnt *= mci->layers[i].size;
memset(mci->ce_per_layer[i], 0, cnt * sizeof(u32));
memset(mci->ue_per_layer[i], 0, cnt * sizeof(u32));
}
mci->start_time = jiffies;
return count;
}
/* Memory scrubbing interface:
*
* A MC driver can limit the scrubbing bandwidth based on the CPU type.
* Therefore, ->set_sdram_scrub_rate should be made to return the actual
* bandwidth that is accepted or 0 when scrubbing is to be disabled.
*
* Negative value still means that an error has occurred while setting
* the scrub rate.
*/
static ssize_t mci_sdram_scrub_rate_store(struct device *dev,
struct device_attribute *mattr,
const char *data, size_t count)
{
struct mem_ctl_info *mci = to_mci(dev);
unsigned long bandwidth = 0;
int new_bw = 0;
if (strict_strtoul(data, 10, &bandwidth) < 0)
return -EINVAL;
new_bw = mci->set_sdram_scrub_rate(mci, bandwidth);
if (new_bw < 0) {
edac_printk(KERN_WARNING, EDAC_MC,
"Error setting scrub rate to: %lu\n", bandwidth);
return -EINVAL;
}
return count;
}
/*
* ->get_sdram_scrub_rate() return value semantics same as above.
*/
static ssize_t mci_sdram_scrub_rate_show(struct device *dev,
struct device_attribute *mattr,
char *data)
{
struct mem_ctl_info *mci = to_mci(dev);
int bandwidth = 0;
bandwidth = mci->get_sdram_scrub_rate(mci);
if (bandwidth < 0) {
edac_printk(KERN_DEBUG, EDAC_MC, "Error reading scrub rate\n");
return bandwidth;
}
return sprintf(data, "%d\n", bandwidth);
}
/* default attribute files for the MCI object */
static ssize_t mci_ue_count_show(struct device *dev,
struct device_attribute *mattr,
char *data)
{
struct mem_ctl_info *mci = to_mci(dev);
return sprintf(data, "%d\n", mci->ue_mc);
}
static ssize_t mci_ce_count_show(struct device *dev,
struct device_attribute *mattr,
char *data)
{
struct mem_ctl_info *mci = to_mci(dev);
return sprintf(data, "%d\n", mci->ce_mc);
}
static ssize_t mci_ce_noinfo_show(struct device *dev,
struct device_attribute *mattr,
char *data)
{
struct mem_ctl_info *mci = to_mci(dev);
return sprintf(data, "%d\n", mci->ce_noinfo_count);
}
static ssize_t mci_ue_noinfo_show(struct device *dev,
struct device_attribute *mattr,
char *data)
{
struct mem_ctl_info *mci = to_mci(dev);
return sprintf(data, "%d\n", mci->ue_noinfo_count);
}
static ssize_t mci_seconds_show(struct device *dev,
struct device_attribute *mattr,
char *data)
{
struct mem_ctl_info *mci = to_mci(dev);
return sprintf(data, "%ld\n", (jiffies - mci->start_time) / HZ);
}
static ssize_t mci_ctl_name_show(struct device *dev,
struct device_attribute *mattr,
char *data)
{
struct mem_ctl_info *mci = to_mci(dev);
return sprintf(data, "%s\n", mci->ctl_name);
}
static ssize_t mci_size_mb_show(struct device *dev,
struct device_attribute *mattr,
char *data)
{
struct mem_ctl_info *mci = to_mci(dev);
int total_pages = 0, csrow_idx, j;
for (csrow_idx = 0; csrow_idx < mci->nr_csrows; csrow_idx++) {
struct csrow_info *csrow = mci->csrows[csrow_idx];
for (j = 0; j < csrow->nr_channels; j++) {
struct dimm_info *dimm = csrow->channels[j]->dimm;
total_pages += dimm->nr_pages;
}
}
return sprintf(data, "%u\n", PAGES_TO_MiB(total_pages));
}
static ssize_t mci_max_location_show(struct device *dev,
struct device_attribute *mattr,
char *data)
{
struct mem_ctl_info *mci = to_mci(dev);
int i;
char *p = data;
for (i = 0; i < mci->n_layers; i++) {
p += sprintf(p, "%s %d ",
edac_layer_name[mci->layers[i].type],
mci->layers[i].size - 1);
}
return p - data;
}
#ifdef CONFIG_EDAC_DEBUG
static ssize_t edac_fake_inject_write(struct file *file,
const char __user *data,
size_t count, loff_t *ppos)
{
struct device *dev = file->private_data;
struct mem_ctl_info *mci = to_mci(dev);
static enum hw_event_mc_err_type type;
u16 errcount = mci->fake_inject_count;
if (!errcount)
errcount = 1;
type = mci->fake_inject_ue ? HW_EVENT_ERR_UNCORRECTED
: HW_EVENT_ERR_CORRECTED;
printk(KERN_DEBUG
"Generating %d %s fake error%s to %d.%d.%d to test core handling. NOTE: this won't test the driver-specific decoding logic.\n",
errcount,
(type == HW_EVENT_ERR_UNCORRECTED) ? "UE" : "CE",
errcount > 1 ? "s" : "",
mci->fake_inject_layer[0],
mci->fake_inject_layer[1],
mci->fake_inject_layer[2]
);
edac_mc_handle_error(type, mci, errcount, 0, 0, 0,
mci->fake_inject_layer[0],
mci->fake_inject_layer[1],
mci->fake_inject_layer[2],
"FAKE ERROR", "for EDAC testing only");
return count;
}
static const struct file_operations debug_fake_inject_fops = {
.open = simple_open,
.write = edac_fake_inject_write,
.llseek = generic_file_llseek,
};
#endif
/* default Control file */
DEVICE_ATTR(reset_counters, S_IWUSR, NULL, mci_reset_counters_store);
/* default Attribute files */
DEVICE_ATTR(mc_name, S_IRUGO, mci_ctl_name_show, NULL);
DEVICE_ATTR(size_mb, S_IRUGO, mci_size_mb_show, NULL);
DEVICE_ATTR(seconds_since_reset, S_IRUGO, mci_seconds_show, NULL);
DEVICE_ATTR(ue_noinfo_count, S_IRUGO, mci_ue_noinfo_show, NULL);
DEVICE_ATTR(ce_noinfo_count, S_IRUGO, mci_ce_noinfo_show, NULL);
DEVICE_ATTR(ue_count, S_IRUGO, mci_ue_count_show, NULL);
DEVICE_ATTR(ce_count, S_IRUGO, mci_ce_count_show, NULL);
DEVICE_ATTR(max_location, S_IRUGO, mci_max_location_show, NULL);
/* memory scrubber attribute file */
DEVICE_ATTR(sdram_scrub_rate, 0, NULL, NULL);
static struct attribute *mci_attrs[] = {
&dev_attr_reset_counters.attr,
&dev_attr_mc_name.attr,
&dev_attr_size_mb.attr,
&dev_attr_seconds_since_reset.attr,
&dev_attr_ue_noinfo_count.attr,
&dev_attr_ce_noinfo_count.attr,
&dev_attr_ue_count.attr,
&dev_attr_ce_count.attr,
&dev_attr_max_location.attr,
NULL
};
static struct attribute_group mci_attr_grp = {
.attrs = mci_attrs,
};
static const struct attribute_group *mci_attr_groups[] = {
&mci_attr_grp,
NULL
};
static void mci_attr_release(struct device *dev)
{
struct mem_ctl_info *mci = container_of(dev, struct mem_ctl_info, dev);
edac_dbg(1, "Releasing csrow device %s\n", dev_name(dev));
kfree(mci);
}
static struct device_type mci_attr_type = {
.groups = mci_attr_groups,
.release = mci_attr_release,
};
#ifdef CONFIG_EDAC_DEBUG
static struct dentry *edac_debugfs;
int __init edac_debugfs_init(void)
{
edac_debugfs = debugfs_create_dir("edac", NULL);
if (IS_ERR(edac_debugfs)) {
edac_debugfs = NULL;
return -ENOMEM;
}
return 0;
}
void __exit edac_debugfs_exit(void)
{
debugfs_remove(edac_debugfs);
}
int edac_create_debug_nodes(struct mem_ctl_info *mci)
{
struct dentry *d, *parent;
char name[80];
int i;
if (!edac_debugfs)
return -ENODEV;
d = debugfs_create_dir(mci->dev.kobj.name, edac_debugfs);
if (!d)
return -ENOMEM;
parent = d;
for (i = 0; i < mci->n_layers; i++) {
sprintf(name, "fake_inject_%s",
edac_layer_name[mci->layers[i].type]);
d = debugfs_create_u8(name, S_IRUGO | S_IWUSR, parent,
&mci->fake_inject_layer[i]);
if (!d)
goto nomem;
}
d = debugfs_create_bool("fake_inject_ue", S_IRUGO | S_IWUSR, parent,
&mci->fake_inject_ue);
if (!d)
goto nomem;
d = debugfs_create_u16("fake_inject_count", S_IRUGO | S_IWUSR, parent,
&mci->fake_inject_count);
if (!d)
goto nomem;
d = debugfs_create_file("fake_inject", S_IWUSR, parent,
&mci->dev,
&debug_fake_inject_fops);
if (!d)
goto nomem;
mci->debugfs = parent;
return 0;
nomem:
debugfs_remove(mci->debugfs);
return -ENOMEM;
}
#endif
/*
* Create a new Memory Controller kobject instance,
* mc<id> under the 'mc' directory
*
* Return:
* 0 Success
* !0 Failure
*/
int edac_create_sysfs_mci_device(struct mem_ctl_info *mci)
{
int i, err;
/*
* The memory controller needs its own bus, in order to avoid
* namespace conflicts at /sys/bus/edac.
*/
mci->bus->name = kasprintf(GFP_KERNEL, "mc%d", mci->mc_idx);
if (!mci->bus->name)
return -ENOMEM;
edac_dbg(0, "creating bus %s\n", mci->bus->name);
err = bus_register(mci->bus);
if (err < 0)
return err;
/* get the /sys/devices/system/edac subsys reference */
mci->dev.type = &mci_attr_type;
device_initialize(&mci->dev);
mci->dev.parent = mci_pdev;
mci->dev.bus = mci->bus;
dev_set_name(&mci->dev, "mc%d", mci->mc_idx);
dev_set_drvdata(&mci->dev, mci);
pm_runtime_forbid(&mci->dev);
edac_dbg(0, "creating device %s\n", dev_name(&mci->dev));
err = device_add(&mci->dev);
if (err < 0) {
edac_dbg(1, "failure: create device %s\n", dev_name(&mci->dev));
bus_unregister(mci->bus);
kfree(mci->bus->name);
return err;
}
if (mci->set_sdram_scrub_rate || mci->get_sdram_scrub_rate) {
if (mci->get_sdram_scrub_rate) {
dev_attr_sdram_scrub_rate.attr.mode |= S_IRUGO;
dev_attr_sdram_scrub_rate.show = &mci_sdram_scrub_rate_show;
}
if (mci->set_sdram_scrub_rate) {
dev_attr_sdram_scrub_rate.attr.mode |= S_IWUSR;
dev_attr_sdram_scrub_rate.store = &mci_sdram_scrub_rate_store;
}
err = device_create_file(&mci->dev,
&dev_attr_sdram_scrub_rate);
if (err) {
edac_dbg(1, "failure: create sdram_scrub_rate\n");
goto fail2;
}
}
/*
* Create the dimm/rank devices
*/
for (i = 0; i < mci->tot_dimms; i++) {
struct dimm_info *dimm = mci->dimms[i];
/* Only expose populated DIMMs */
if (dimm->nr_pages == 0)
continue;
#ifdef CONFIG_EDAC_DEBUG
edac_dbg(1, "creating dimm%d, located at ", i);
if (edac_debug_level >= 1) {
int lay;
for (lay = 0; lay < mci->n_layers; lay++)
printk(KERN_CONT "%s %d ",
edac_layer_name[mci->layers[lay].type],
dimm->location[lay]);
printk(KERN_CONT "\n");
}
#endif
err = edac_create_dimm_object(mci, dimm, i);
if (err) {
edac_dbg(1, "failure: create dimm %d obj\n", i);
goto fail;
}
}
#ifdef CONFIG_EDAC_LEGACY_SYSFS
err = edac_create_csrow_objects(mci);
if (err < 0)
goto fail;
#endif
#ifdef CONFIG_EDAC_DEBUG
edac_create_debug_nodes(mci);
#endif
return 0;
fail:
for (i--; i >= 0; i--) {
struct dimm_info *dimm = mci->dimms[i];
if (dimm->nr_pages == 0)
continue;
device_unregister(&dimm->dev);
}
fail2:
device_unregister(&mci->dev);
bus_unregister(mci->bus);
kfree(mci->bus->name);
return err;
}
/*
* remove a Memory Controller instance
*/
void edac_remove_sysfs_mci_device(struct mem_ctl_info *mci)
{
int i;
edac_dbg(0, "\n");
#ifdef CONFIG_EDAC_DEBUG
debugfs_remove(mci->debugfs);
#endif
#ifdef CONFIG_EDAC_LEGACY_SYSFS
edac_delete_csrow_objects(mci);
#endif
for (i = 0; i < mci->tot_dimms; i++) {
struct dimm_info *dimm = mci->dimms[i];
if (dimm->nr_pages == 0)
continue;
edac_dbg(0, "removing device %s\n", dev_name(&dimm->dev));
device_unregister(&dimm->dev);
}
}
void edac_unregister_sysfs(struct mem_ctl_info *mci)
{
edac_dbg(1, "Unregistering device %s\n", dev_name(&mci->dev));
device_unregister(&mci->dev);
bus_unregister(mci->bus);
kfree(mci->bus->name);
}
static void mc_attr_release(struct device *dev)
{
/*
* There's no container structure here, as this is just the mci
* parent device, used to create the /sys/devices/mc sysfs node.
* So, there are no attributes on it.
*/
edac_dbg(1, "Releasing device %s\n", dev_name(dev));
kfree(dev);
}
static struct device_type mc_attr_type = {
.release = mc_attr_release,
};
/*
* Init/exit code for the module. Basically, creates/removes /sys/class/rc
*/
int __init edac_mc_sysfs_init(void)
{
struct bus_type *edac_subsys;
int err;
/* get the /sys/devices/system/edac subsys reference */
edac_subsys = edac_get_sysfs_subsys();
if (edac_subsys == NULL) {
edac_dbg(1, "no edac_subsys\n");
err = -EINVAL;
goto out;
}
mci_pdev = kzalloc(sizeof(*mci_pdev), GFP_KERNEL);
if (!mci_pdev) {
err = -ENOMEM;
goto out_put_sysfs;
}
mci_pdev->bus = edac_subsys;
mci_pdev->type = &mc_attr_type;
device_initialize(mci_pdev);
dev_set_name(mci_pdev, "mc");
err = device_add(mci_pdev);
if (err < 0)
goto out_dev_free;
edac_dbg(0, "device %s created\n", dev_name(mci_pdev));
return 0;
out_dev_free:
kfree(mci_pdev);
out_put_sysfs:
edac_put_sysfs_subsys();
out:
return err;
}
void __exit edac_mc_sysfs_exit(void)
{
device_unregister(mci_pdev);
edac_put_sysfs_subsys();
}
| gpl-2.0 |
juju2013/fsl-linux | drivers/pwm/sysfs.c | 1375 | 7921 | /*
* A simple sysfs interface for the generic PWM framework
*
* Copyright (C) 2013 H Hartley Sweeten <hsweeten@visionengravers.com>
*
* Based on previous work by Lars Poeschel <poeschel@lemonage.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY 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/device.h>
#include <linux/mutex.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/kdev_t.h>
#include <linux/pwm.h>
struct pwm_export {
struct device child;
struct pwm_device *pwm;
};
static struct pwm_export *child_to_pwm_export(struct device *child)
{
return container_of(child, struct pwm_export, child);
}
static struct pwm_device *child_to_pwm_device(struct device *child)
{
struct pwm_export *export = child_to_pwm_export(child);
return export->pwm;
}
static ssize_t pwm_period_show(struct device *child,
struct device_attribute *attr,
char *buf)
{
const struct pwm_device *pwm = child_to_pwm_device(child);
return sprintf(buf, "%u\n", pwm->period);
}
static ssize_t pwm_period_store(struct device *child,
struct device_attribute *attr,
const char *buf, size_t size)
{
struct pwm_device *pwm = child_to_pwm_device(child);
unsigned int val;
int ret;
ret = kstrtouint(buf, 0, &val);
if (ret)
return ret;
ret = pwm_config(pwm, pwm->duty_cycle, val);
return ret ? : size;
}
static ssize_t pwm_duty_cycle_show(struct device *child,
struct device_attribute *attr,
char *buf)
{
const struct pwm_device *pwm = child_to_pwm_device(child);
return sprintf(buf, "%u\n", pwm->duty_cycle);
}
static ssize_t pwm_duty_cycle_store(struct device *child,
struct device_attribute *attr,
const char *buf, size_t size)
{
struct pwm_device *pwm = child_to_pwm_device(child);
unsigned int val;
int ret;
ret = kstrtouint(buf, 0, &val);
if (ret)
return ret;
ret = pwm_config(pwm, val, pwm->period);
return ret ? : size;
}
static ssize_t pwm_enable_show(struct device *child,
struct device_attribute *attr,
char *buf)
{
const struct pwm_device *pwm = child_to_pwm_device(child);
int enabled = test_bit(PWMF_ENABLED, &pwm->flags);
return sprintf(buf, "%d\n", enabled);
}
static ssize_t pwm_enable_store(struct device *child,
struct device_attribute *attr,
const char *buf, size_t size)
{
struct pwm_device *pwm = child_to_pwm_device(child);
int val, ret;
ret = kstrtoint(buf, 0, &val);
if (ret)
return ret;
switch (val) {
case 0:
pwm_disable(pwm);
break;
case 1:
ret = pwm_enable(pwm);
break;
default:
ret = -EINVAL;
break;
}
return ret ? : size;
}
static ssize_t pwm_polarity_show(struct device *child,
struct device_attribute *attr,
char *buf)
{
const struct pwm_device *pwm = child_to_pwm_device(child);
return sprintf(buf, "%s\n", pwm->polarity ? "inversed" : "normal");
}
static ssize_t pwm_polarity_store(struct device *child,
struct device_attribute *attr,
const char *buf, size_t size)
{
struct pwm_device *pwm = child_to_pwm_device(child);
enum pwm_polarity polarity;
int ret;
if (sysfs_streq(buf, "normal"))
polarity = PWM_POLARITY_NORMAL;
else if (sysfs_streq(buf, "inversed"))
polarity = PWM_POLARITY_INVERSED;
else
return -EINVAL;
ret = pwm_set_polarity(pwm, polarity);
return ret ? : size;
}
static DEVICE_ATTR(period, 0644, pwm_period_show, pwm_period_store);
static DEVICE_ATTR(duty_cycle, 0644, pwm_duty_cycle_show, pwm_duty_cycle_store);
static DEVICE_ATTR(enable, 0644, pwm_enable_show, pwm_enable_store);
static DEVICE_ATTR(polarity, 0644, pwm_polarity_show, pwm_polarity_store);
static struct attribute *pwm_attrs[] = {
&dev_attr_period.attr,
&dev_attr_duty_cycle.attr,
&dev_attr_enable.attr,
&dev_attr_polarity.attr,
NULL
};
ATTRIBUTE_GROUPS(pwm);
static void pwm_export_release(struct device *child)
{
struct pwm_export *export = child_to_pwm_export(child);
kfree(export);
}
static int pwm_export_child(struct device *parent, struct pwm_device *pwm)
{
struct pwm_export *export;
int ret;
if (test_and_set_bit(PWMF_EXPORTED, &pwm->flags))
return -EBUSY;
export = kzalloc(sizeof(*export), GFP_KERNEL);
if (!export) {
clear_bit(PWMF_EXPORTED, &pwm->flags);
return -ENOMEM;
}
export->pwm = pwm;
export->child.release = pwm_export_release;
export->child.parent = parent;
export->child.devt = MKDEV(0, 0);
export->child.groups = pwm_groups;
dev_set_name(&export->child, "pwm%u", pwm->hwpwm);
ret = device_register(&export->child);
if (ret) {
clear_bit(PWMF_EXPORTED, &pwm->flags);
kfree(export);
return ret;
}
return 0;
}
static int pwm_unexport_match(struct device *child, void *data)
{
return child_to_pwm_device(child) == data;
}
static int pwm_unexport_child(struct device *parent, struct pwm_device *pwm)
{
struct device *child;
if (!test_and_clear_bit(PWMF_EXPORTED, &pwm->flags))
return -ENODEV;
child = device_find_child(parent, pwm, pwm_unexport_match);
if (!child)
return -ENODEV;
/* for device_find_child() */
put_device(child);
device_unregister(child);
pwm_put(pwm);
return 0;
}
static ssize_t pwm_export_store(struct device *parent,
struct device_attribute *attr,
const char *buf, size_t len)
{
struct pwm_chip *chip = dev_get_drvdata(parent);
struct pwm_device *pwm;
unsigned int hwpwm;
int ret;
ret = kstrtouint(buf, 0, &hwpwm);
if (ret < 0)
return ret;
if (hwpwm >= chip->npwm)
return -ENODEV;
pwm = pwm_request_from_chip(chip, hwpwm, "sysfs");
if (IS_ERR(pwm))
return PTR_ERR(pwm);
ret = pwm_export_child(parent, pwm);
if (ret < 0)
pwm_put(pwm);
return ret ? : len;
}
static DEVICE_ATTR(export, 0200, NULL, pwm_export_store);
static ssize_t pwm_unexport_store(struct device *parent,
struct device_attribute *attr,
const char *buf, size_t len)
{
struct pwm_chip *chip = dev_get_drvdata(parent);
unsigned int hwpwm;
int ret;
ret = kstrtouint(buf, 0, &hwpwm);
if (ret < 0)
return ret;
if (hwpwm >= chip->npwm)
return -ENODEV;
ret = pwm_unexport_child(parent, &chip->pwms[hwpwm]);
return ret ? : len;
}
static DEVICE_ATTR(unexport, 0200, NULL, pwm_unexport_store);
static ssize_t npwm_show(struct device *parent, struct device_attribute *attr,
char *buf)
{
const struct pwm_chip *chip = dev_get_drvdata(parent);
return sprintf(buf, "%u\n", chip->npwm);
}
static DEVICE_ATTR_RO(npwm);
static struct attribute *pwm_chip_attrs[] = {
&dev_attr_export.attr,
&dev_attr_unexport.attr,
&dev_attr_npwm.attr,
NULL,
};
ATTRIBUTE_GROUPS(pwm_chip);
static struct class pwm_class = {
.name = "pwm",
.owner = THIS_MODULE,
.dev_groups = pwm_chip_groups,
};
static int pwmchip_sysfs_match(struct device *parent, const void *data)
{
return dev_get_drvdata(parent) == data;
}
void pwmchip_sysfs_export(struct pwm_chip *chip)
{
struct device *parent;
/*
* If device_create() fails the pwm_chip is still usable by
* the kernel its just not exported.
*/
parent = device_create(&pwm_class, chip->dev, MKDEV(0, 0), chip,
"pwmchip%d", chip->base);
if (IS_ERR(parent)) {
dev_warn(chip->dev,
"device_create failed for pwm_chip sysfs export\n");
}
}
void pwmchip_sysfs_unexport(struct pwm_chip *chip)
{
struct device *parent;
parent = class_find_device(&pwm_class, NULL, chip,
pwmchip_sysfs_match);
if (parent) {
/* for class_find_device() */
put_device(parent);
device_unregister(parent);
}
}
static int __init pwm_sysfs_init(void)
{
return class_register(&pwm_class);
}
subsys_initcall(pwm_sysfs_init);
| gpl-2.0 |
aj20010319/Breeze-MM-X3 | arch/sh/boards/board-sh7785lcr.c | 4703 | 8611 | /*
* Renesas Technology Corp. R0P7785LC0011RL Support.
*
* Copyright (C) 2008 Yoshihiro Shimoda
* Copyright (C) 2009 Paul Mundt
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/sm501.h>
#include <linux/sm501-regs.h>
#include <linux/fb.h>
#include <linux/mtd/physmap.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/i2c.h>
#include <linux/i2c-pca-platform.h>
#include <linux/i2c-algo-pca.h>
#include <linux/usb/r8a66597.h>
#include <linux/sh_intc.h>
#include <linux/irq.h>
#include <linux/io.h>
#include <linux/clk.h>
#include <linux/errno.h>
#include <mach/sh7785lcr.h>
#include <cpu/sh7785.h>
#include <asm/heartbeat.h>
#include <asm/clock.h>
#include <asm/bl_bit.h>
/*
* NOTE: This board has 2 physical memory maps.
* Please look at include/asm-sh/sh7785lcr.h or hardware manual.
*/
static struct resource heartbeat_resource = {
.start = PLD_LEDCR,
.end = PLD_LEDCR,
.flags = IORESOURCE_MEM | IORESOURCE_MEM_8BIT,
};
static struct platform_device heartbeat_device = {
.name = "heartbeat",
.id = -1,
.num_resources = 1,
.resource = &heartbeat_resource,
};
static struct mtd_partition nor_flash_partitions[] = {
{
.name = "loader",
.offset = 0x00000000,
.size = 512 * 1024,
},
{
.name = "bootenv",
.offset = MTDPART_OFS_APPEND,
.size = 512 * 1024,
},
{
.name = "kernel",
.offset = MTDPART_OFS_APPEND,
.size = 4 * 1024 * 1024,
},
{
.name = "data",
.offset = MTDPART_OFS_APPEND,
.size = MTDPART_SIZ_FULL,
},
};
static struct physmap_flash_data nor_flash_data = {
.width = 4,
.parts = nor_flash_partitions,
.nr_parts = ARRAY_SIZE(nor_flash_partitions),
};
static struct resource nor_flash_resources[] = {
[0] = {
.start = NOR_FLASH_ADDR,
.end = NOR_FLASH_ADDR + NOR_FLASH_SIZE - 1,
.flags = IORESOURCE_MEM,
}
};
static struct platform_device nor_flash_device = {
.name = "physmap-flash",
.dev = {
.platform_data = &nor_flash_data,
},
.num_resources = ARRAY_SIZE(nor_flash_resources),
.resource = nor_flash_resources,
};
static struct r8a66597_platdata r8a66597_data = {
.xtal = R8A66597_PLATDATA_XTAL_12MHZ,
.vif = 1,
};
static struct resource r8a66597_usb_host_resources[] = {
[0] = {
.start = R8A66597_ADDR,
.end = R8A66597_ADDR + R8A66597_SIZE - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = evt2irq(0x240),
.end = evt2irq(0x240),
.flags = IORESOURCE_IRQ | IRQF_TRIGGER_LOW,
},
};
static struct platform_device r8a66597_usb_host_device = {
.name = "r8a66597_hcd",
.id = -1,
.dev = {
.dma_mask = NULL,
.coherent_dma_mask = 0xffffffff,
.platform_data = &r8a66597_data,
},
.num_resources = ARRAY_SIZE(r8a66597_usb_host_resources),
.resource = r8a66597_usb_host_resources,
};
static struct resource sm501_resources[] = {
[0] = {
.start = SM107_MEM_ADDR,
.end = SM107_MEM_ADDR + SM107_MEM_SIZE - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = SM107_REG_ADDR,
.end = SM107_REG_ADDR + SM107_REG_SIZE - 1,
.flags = IORESOURCE_MEM,
},
[2] = {
.start = evt2irq(0x340),
.flags = IORESOURCE_IRQ,
},
};
static struct fb_videomode sm501_default_mode_crt = {
.pixclock = 35714, /* 28MHz */
.xres = 640,
.yres = 480,
.left_margin = 105,
.right_margin = 16,
.upper_margin = 33,
.lower_margin = 10,
.hsync_len = 39,
.vsync_len = 2,
.sync = FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
};
static struct fb_videomode sm501_default_mode_pnl = {
.pixclock = 40000, /* 25MHz */
.xres = 640,
.yres = 480,
.left_margin = 2,
.right_margin = 16,
.upper_margin = 33,
.lower_margin = 10,
.hsync_len = 39,
.vsync_len = 2,
.sync = 0,
};
static struct sm501_platdata_fbsub sm501_pdata_fbsub_pnl = {
.def_bpp = 16,
.def_mode = &sm501_default_mode_pnl,
.flags = SM501FB_FLAG_USE_INIT_MODE |
SM501FB_FLAG_USE_HWCURSOR |
SM501FB_FLAG_USE_HWACCEL |
SM501FB_FLAG_DISABLE_AT_EXIT |
SM501FB_FLAG_PANEL_NO_VBIASEN,
};
static struct sm501_platdata_fbsub sm501_pdata_fbsub_crt = {
.def_bpp = 16,
.def_mode = &sm501_default_mode_crt,
.flags = SM501FB_FLAG_USE_INIT_MODE |
SM501FB_FLAG_USE_HWCURSOR |
SM501FB_FLAG_USE_HWACCEL |
SM501FB_FLAG_DISABLE_AT_EXIT,
};
static struct sm501_platdata_fb sm501_fb_pdata = {
.fb_route = SM501_FB_OWN,
.fb_crt = &sm501_pdata_fbsub_crt,
.fb_pnl = &sm501_pdata_fbsub_pnl,
};
static struct sm501_initdata sm501_initdata = {
.gpio_high = {
.set = 0x00001fe0,
.mask = 0x0,
},
.devices = 0,
.mclk = 84 * 1000000,
.m1xclk = 112 * 1000000,
};
static struct sm501_platdata sm501_platform_data = {
.init = &sm501_initdata,
.fb = &sm501_fb_pdata,
};
static struct platform_device sm501_device = {
.name = "sm501",
.id = -1,
.dev = {
.platform_data = &sm501_platform_data,
},
.num_resources = ARRAY_SIZE(sm501_resources),
.resource = sm501_resources,
};
static struct resource i2c_proto_resources[] = {
[0] = {
.start = PCA9564_PROTO_32BIT_ADDR,
.end = PCA9564_PROTO_32BIT_ADDR + PCA9564_SIZE - 1,
.flags = IORESOURCE_MEM | IORESOURCE_MEM_8BIT,
},
[1] = {
.start = evt2irq(0x380),
.end = evt2irq(0x380),
.flags = IORESOURCE_IRQ,
},
};
static struct resource i2c_resources[] = {
[0] = {
.start = PCA9564_ADDR,
.end = PCA9564_ADDR + PCA9564_SIZE - 1,
.flags = IORESOURCE_MEM | IORESOURCE_MEM_8BIT,
},
[1] = {
.start = evt2irq(0x380),
.end = evt2irq(0x380),
.flags = IORESOURCE_IRQ,
},
};
static struct i2c_pca9564_pf_platform_data i2c_platform_data = {
.gpio = 0,
.i2c_clock_speed = I2C_PCA_CON_330kHz,
.timeout = HZ,
};
static struct platform_device i2c_device = {
.name = "i2c-pca-platform",
.id = -1,
.dev = {
.platform_data = &i2c_platform_data,
},
.num_resources = ARRAY_SIZE(i2c_resources),
.resource = i2c_resources,
};
static struct platform_device *sh7785lcr_devices[] __initdata = {
&heartbeat_device,
&nor_flash_device,
&r8a66597_usb_host_device,
&sm501_device,
&i2c_device,
};
static struct i2c_board_info __initdata sh7785lcr_i2c_devices[] = {
{
I2C_BOARD_INFO("r2025sd", 0x32),
},
};
static int __init sh7785lcr_devices_setup(void)
{
i2c_register_board_info(0, sh7785lcr_i2c_devices,
ARRAY_SIZE(sh7785lcr_i2c_devices));
if (mach_is_sh7785lcr_pt()) {
i2c_device.resource = i2c_proto_resources;
i2c_device.num_resources = ARRAY_SIZE(i2c_proto_resources);
}
return platform_add_devices(sh7785lcr_devices,
ARRAY_SIZE(sh7785lcr_devices));
}
device_initcall(sh7785lcr_devices_setup);
/* Initialize IRQ setting */
void __init init_sh7785lcr_IRQ(void)
{
plat_irq_setup_pins(IRQ_MODE_IRQ7654);
plat_irq_setup_pins(IRQ_MODE_IRQ3210);
}
static int sh7785lcr_clk_init(void)
{
struct clk *clk;
int ret;
clk = clk_get(NULL, "extal");
if (IS_ERR(clk))
return PTR_ERR(clk);
ret = clk_set_rate(clk, 33333333);
clk_put(clk);
return ret;
}
static void sh7785lcr_power_off(void)
{
unsigned char *p;
p = ioremap(PLD_POFCR, PLD_POFCR + 1);
if (!p) {
printk(KERN_ERR "%s: ioremap error.\n", __func__);
return;
}
*p = 0x01;
iounmap(p);
set_bl_bit();
while (1)
cpu_relax();
}
/* Initialize the board */
static void __init sh7785lcr_setup(char **cmdline_p)
{
void __iomem *sm501_reg;
printk(KERN_INFO "Renesas Technology Corp. R0P7785LC0011RL support.\n");
pm_power_off = sh7785lcr_power_off;
/* sm501 DRAM configuration */
sm501_reg = ioremap_nocache(SM107_REG_ADDR, SM501_DRAM_CONTROL);
if (!sm501_reg) {
printk(KERN_ERR "%s: ioremap error.\n", __func__);
return;
}
writel(0x000307c2, sm501_reg + SM501_DRAM_CONTROL);
iounmap(sm501_reg);
}
/* Return the board specific boot mode pin configuration */
static int sh7785lcr_mode_pins(void)
{
int value = 0;
/* These are the factory default settings of S1 and S2.
* If you change these dip switches then you will need to
* adjust the values below as well.
*/
value |= MODE_PIN4; /* Clock Mode 16 */
value |= MODE_PIN5; /* 32-bit Area0 bus width */
value |= MODE_PIN6; /* 32-bit Area0 bus width */
value |= MODE_PIN7; /* Area 0 SRAM interface [fixed] */
value |= MODE_PIN8; /* Little Endian */
value |= MODE_PIN9; /* Master Mode */
value |= MODE_PIN14; /* No PLL step-up */
return value;
}
/*
* The Machine Vector
*/
static struct sh_machine_vector mv_sh7785lcr __initmv = {
.mv_name = "SH7785LCR",
.mv_setup = sh7785lcr_setup,
.mv_clk_init = sh7785lcr_clk_init,
.mv_init_irq = init_sh7785lcr_IRQ,
.mv_mode_pins = sh7785lcr_mode_pins,
};
| gpl-2.0 |
bq/aquaris-E5-4G | arch/sh/boards/board-sh7785lcr.c | 4703 | 8611 | /*
* Renesas Technology Corp. R0P7785LC0011RL Support.
*
* Copyright (C) 2008 Yoshihiro Shimoda
* Copyright (C) 2009 Paul Mundt
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/sm501.h>
#include <linux/sm501-regs.h>
#include <linux/fb.h>
#include <linux/mtd/physmap.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/i2c.h>
#include <linux/i2c-pca-platform.h>
#include <linux/i2c-algo-pca.h>
#include <linux/usb/r8a66597.h>
#include <linux/sh_intc.h>
#include <linux/irq.h>
#include <linux/io.h>
#include <linux/clk.h>
#include <linux/errno.h>
#include <mach/sh7785lcr.h>
#include <cpu/sh7785.h>
#include <asm/heartbeat.h>
#include <asm/clock.h>
#include <asm/bl_bit.h>
/*
* NOTE: This board has 2 physical memory maps.
* Please look at include/asm-sh/sh7785lcr.h or hardware manual.
*/
static struct resource heartbeat_resource = {
.start = PLD_LEDCR,
.end = PLD_LEDCR,
.flags = IORESOURCE_MEM | IORESOURCE_MEM_8BIT,
};
static struct platform_device heartbeat_device = {
.name = "heartbeat",
.id = -1,
.num_resources = 1,
.resource = &heartbeat_resource,
};
static struct mtd_partition nor_flash_partitions[] = {
{
.name = "loader",
.offset = 0x00000000,
.size = 512 * 1024,
},
{
.name = "bootenv",
.offset = MTDPART_OFS_APPEND,
.size = 512 * 1024,
},
{
.name = "kernel",
.offset = MTDPART_OFS_APPEND,
.size = 4 * 1024 * 1024,
},
{
.name = "data",
.offset = MTDPART_OFS_APPEND,
.size = MTDPART_SIZ_FULL,
},
};
static struct physmap_flash_data nor_flash_data = {
.width = 4,
.parts = nor_flash_partitions,
.nr_parts = ARRAY_SIZE(nor_flash_partitions),
};
static struct resource nor_flash_resources[] = {
[0] = {
.start = NOR_FLASH_ADDR,
.end = NOR_FLASH_ADDR + NOR_FLASH_SIZE - 1,
.flags = IORESOURCE_MEM,
}
};
static struct platform_device nor_flash_device = {
.name = "physmap-flash",
.dev = {
.platform_data = &nor_flash_data,
},
.num_resources = ARRAY_SIZE(nor_flash_resources),
.resource = nor_flash_resources,
};
static struct r8a66597_platdata r8a66597_data = {
.xtal = R8A66597_PLATDATA_XTAL_12MHZ,
.vif = 1,
};
static struct resource r8a66597_usb_host_resources[] = {
[0] = {
.start = R8A66597_ADDR,
.end = R8A66597_ADDR + R8A66597_SIZE - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = evt2irq(0x240),
.end = evt2irq(0x240),
.flags = IORESOURCE_IRQ | IRQF_TRIGGER_LOW,
},
};
static struct platform_device r8a66597_usb_host_device = {
.name = "r8a66597_hcd",
.id = -1,
.dev = {
.dma_mask = NULL,
.coherent_dma_mask = 0xffffffff,
.platform_data = &r8a66597_data,
},
.num_resources = ARRAY_SIZE(r8a66597_usb_host_resources),
.resource = r8a66597_usb_host_resources,
};
static struct resource sm501_resources[] = {
[0] = {
.start = SM107_MEM_ADDR,
.end = SM107_MEM_ADDR + SM107_MEM_SIZE - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = SM107_REG_ADDR,
.end = SM107_REG_ADDR + SM107_REG_SIZE - 1,
.flags = IORESOURCE_MEM,
},
[2] = {
.start = evt2irq(0x340),
.flags = IORESOURCE_IRQ,
},
};
static struct fb_videomode sm501_default_mode_crt = {
.pixclock = 35714, /* 28MHz */
.xres = 640,
.yres = 480,
.left_margin = 105,
.right_margin = 16,
.upper_margin = 33,
.lower_margin = 10,
.hsync_len = 39,
.vsync_len = 2,
.sync = FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
};
static struct fb_videomode sm501_default_mode_pnl = {
.pixclock = 40000, /* 25MHz */
.xres = 640,
.yres = 480,
.left_margin = 2,
.right_margin = 16,
.upper_margin = 33,
.lower_margin = 10,
.hsync_len = 39,
.vsync_len = 2,
.sync = 0,
};
static struct sm501_platdata_fbsub sm501_pdata_fbsub_pnl = {
.def_bpp = 16,
.def_mode = &sm501_default_mode_pnl,
.flags = SM501FB_FLAG_USE_INIT_MODE |
SM501FB_FLAG_USE_HWCURSOR |
SM501FB_FLAG_USE_HWACCEL |
SM501FB_FLAG_DISABLE_AT_EXIT |
SM501FB_FLAG_PANEL_NO_VBIASEN,
};
static struct sm501_platdata_fbsub sm501_pdata_fbsub_crt = {
.def_bpp = 16,
.def_mode = &sm501_default_mode_crt,
.flags = SM501FB_FLAG_USE_INIT_MODE |
SM501FB_FLAG_USE_HWCURSOR |
SM501FB_FLAG_USE_HWACCEL |
SM501FB_FLAG_DISABLE_AT_EXIT,
};
static struct sm501_platdata_fb sm501_fb_pdata = {
.fb_route = SM501_FB_OWN,
.fb_crt = &sm501_pdata_fbsub_crt,
.fb_pnl = &sm501_pdata_fbsub_pnl,
};
static struct sm501_initdata sm501_initdata = {
.gpio_high = {
.set = 0x00001fe0,
.mask = 0x0,
},
.devices = 0,
.mclk = 84 * 1000000,
.m1xclk = 112 * 1000000,
};
static struct sm501_platdata sm501_platform_data = {
.init = &sm501_initdata,
.fb = &sm501_fb_pdata,
};
static struct platform_device sm501_device = {
.name = "sm501",
.id = -1,
.dev = {
.platform_data = &sm501_platform_data,
},
.num_resources = ARRAY_SIZE(sm501_resources),
.resource = sm501_resources,
};
static struct resource i2c_proto_resources[] = {
[0] = {
.start = PCA9564_PROTO_32BIT_ADDR,
.end = PCA9564_PROTO_32BIT_ADDR + PCA9564_SIZE - 1,
.flags = IORESOURCE_MEM | IORESOURCE_MEM_8BIT,
},
[1] = {
.start = evt2irq(0x380),
.end = evt2irq(0x380),
.flags = IORESOURCE_IRQ,
},
};
static struct resource i2c_resources[] = {
[0] = {
.start = PCA9564_ADDR,
.end = PCA9564_ADDR + PCA9564_SIZE - 1,
.flags = IORESOURCE_MEM | IORESOURCE_MEM_8BIT,
},
[1] = {
.start = evt2irq(0x380),
.end = evt2irq(0x380),
.flags = IORESOURCE_IRQ,
},
};
static struct i2c_pca9564_pf_platform_data i2c_platform_data = {
.gpio = 0,
.i2c_clock_speed = I2C_PCA_CON_330kHz,
.timeout = HZ,
};
static struct platform_device i2c_device = {
.name = "i2c-pca-platform",
.id = -1,
.dev = {
.platform_data = &i2c_platform_data,
},
.num_resources = ARRAY_SIZE(i2c_resources),
.resource = i2c_resources,
};
static struct platform_device *sh7785lcr_devices[] __initdata = {
&heartbeat_device,
&nor_flash_device,
&r8a66597_usb_host_device,
&sm501_device,
&i2c_device,
};
static struct i2c_board_info __initdata sh7785lcr_i2c_devices[] = {
{
I2C_BOARD_INFO("r2025sd", 0x32),
},
};
static int __init sh7785lcr_devices_setup(void)
{
i2c_register_board_info(0, sh7785lcr_i2c_devices,
ARRAY_SIZE(sh7785lcr_i2c_devices));
if (mach_is_sh7785lcr_pt()) {
i2c_device.resource = i2c_proto_resources;
i2c_device.num_resources = ARRAY_SIZE(i2c_proto_resources);
}
return platform_add_devices(sh7785lcr_devices,
ARRAY_SIZE(sh7785lcr_devices));
}
device_initcall(sh7785lcr_devices_setup);
/* Initialize IRQ setting */
void __init init_sh7785lcr_IRQ(void)
{
plat_irq_setup_pins(IRQ_MODE_IRQ7654);
plat_irq_setup_pins(IRQ_MODE_IRQ3210);
}
static int sh7785lcr_clk_init(void)
{
struct clk *clk;
int ret;
clk = clk_get(NULL, "extal");
if (IS_ERR(clk))
return PTR_ERR(clk);
ret = clk_set_rate(clk, 33333333);
clk_put(clk);
return ret;
}
static void sh7785lcr_power_off(void)
{
unsigned char *p;
p = ioremap(PLD_POFCR, PLD_POFCR + 1);
if (!p) {
printk(KERN_ERR "%s: ioremap error.\n", __func__);
return;
}
*p = 0x01;
iounmap(p);
set_bl_bit();
while (1)
cpu_relax();
}
/* Initialize the board */
static void __init sh7785lcr_setup(char **cmdline_p)
{
void __iomem *sm501_reg;
printk(KERN_INFO "Renesas Technology Corp. R0P7785LC0011RL support.\n");
pm_power_off = sh7785lcr_power_off;
/* sm501 DRAM configuration */
sm501_reg = ioremap_nocache(SM107_REG_ADDR, SM501_DRAM_CONTROL);
if (!sm501_reg) {
printk(KERN_ERR "%s: ioremap error.\n", __func__);
return;
}
writel(0x000307c2, sm501_reg + SM501_DRAM_CONTROL);
iounmap(sm501_reg);
}
/* Return the board specific boot mode pin configuration */
static int sh7785lcr_mode_pins(void)
{
int value = 0;
/* These are the factory default settings of S1 and S2.
* If you change these dip switches then you will need to
* adjust the values below as well.
*/
value |= MODE_PIN4; /* Clock Mode 16 */
value |= MODE_PIN5; /* 32-bit Area0 bus width */
value |= MODE_PIN6; /* 32-bit Area0 bus width */
value |= MODE_PIN7; /* Area 0 SRAM interface [fixed] */
value |= MODE_PIN8; /* Little Endian */
value |= MODE_PIN9; /* Master Mode */
value |= MODE_PIN14; /* No PLL step-up */
return value;
}
/*
* The Machine Vector
*/
static struct sh_machine_vector mv_sh7785lcr __initmv = {
.mv_name = "SH7785LCR",
.mv_setup = sh7785lcr_setup,
.mv_clk_init = sh7785lcr_clk_init,
.mv_init_irq = init_sh7785lcr_IRQ,
.mv_mode_pins = sh7785lcr_mode_pins,
};
| gpl-2.0 |
ShinySide/The-Imperius-Curse | drivers/block/drbd/drbd_receiver.c | 5983 | 131391 | /*
drbd_receiver.c
This file is part of DRBD by Philipp Reisner and Lars Ellenberg.
Copyright (C) 2001-2008, LINBIT Information Technologies GmbH.
Copyright (C) 1999-2008, Philipp Reisner <philipp.reisner@linbit.com>.
Copyright (C) 2002-2008, Lars Ellenberg <lars.ellenberg@linbit.com>.
drbd is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
drbd is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with drbd; see the file COPYING. If not, write to
the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <asm/uaccess.h>
#include <net/sock.h>
#include <linux/drbd.h>
#include <linux/fs.h>
#include <linux/file.h>
#include <linux/in.h>
#include <linux/mm.h>
#include <linux/memcontrol.h>
#include <linux/mm_inline.h>
#include <linux/slab.h>
#include <linux/pkt_sched.h>
#define __KERNEL_SYSCALLS__
#include <linux/unistd.h>
#include <linux/vmalloc.h>
#include <linux/random.h>
#include <linux/string.h>
#include <linux/scatterlist.h>
#include "drbd_int.h"
#include "drbd_req.h"
#include "drbd_vli.h"
enum finish_epoch {
FE_STILL_LIVE,
FE_DESTROYED,
FE_RECYCLED,
};
static int drbd_do_handshake(struct drbd_conf *mdev);
static int drbd_do_auth(struct drbd_conf *mdev);
static enum finish_epoch drbd_may_finish_epoch(struct drbd_conf *, struct drbd_epoch *, enum epoch_event);
static int e_end_block(struct drbd_conf *, struct drbd_work *, int);
#define GFP_TRY (__GFP_HIGHMEM | __GFP_NOWARN)
/*
* some helper functions to deal with single linked page lists,
* page->private being our "next" pointer.
*/
/* If at least n pages are linked at head, get n pages off.
* Otherwise, don't modify head, and return NULL.
* Locking is the responsibility of the caller.
*/
static struct page *page_chain_del(struct page **head, int n)
{
struct page *page;
struct page *tmp;
BUG_ON(!n);
BUG_ON(!head);
page = *head;
if (!page)
return NULL;
while (page) {
tmp = page_chain_next(page);
if (--n == 0)
break; /* found sufficient pages */
if (tmp == NULL)
/* insufficient pages, don't use any of them. */
return NULL;
page = tmp;
}
/* add end of list marker for the returned list */
set_page_private(page, 0);
/* actual return value, and adjustment of head */
page = *head;
*head = tmp;
return page;
}
/* may be used outside of locks to find the tail of a (usually short)
* "private" page chain, before adding it back to a global chain head
* with page_chain_add() under a spinlock. */
static struct page *page_chain_tail(struct page *page, int *len)
{
struct page *tmp;
int i = 1;
while ((tmp = page_chain_next(page)))
++i, page = tmp;
if (len)
*len = i;
return page;
}
static int page_chain_free(struct page *page)
{
struct page *tmp;
int i = 0;
page_chain_for_each_safe(page, tmp) {
put_page(page);
++i;
}
return i;
}
static void page_chain_add(struct page **head,
struct page *chain_first, struct page *chain_last)
{
#if 1
struct page *tmp;
tmp = page_chain_tail(chain_first, NULL);
BUG_ON(tmp != chain_last);
#endif
/* add chain to head */
set_page_private(chain_last, (unsigned long)*head);
*head = chain_first;
}
static struct page *drbd_pp_first_pages_or_try_alloc(struct drbd_conf *mdev, int number)
{
struct page *page = NULL;
struct page *tmp = NULL;
int i = 0;
/* Yes, testing drbd_pp_vacant outside the lock is racy.
* So what. It saves a spin_lock. */
if (drbd_pp_vacant >= number) {
spin_lock(&drbd_pp_lock);
page = page_chain_del(&drbd_pp_pool, number);
if (page)
drbd_pp_vacant -= number;
spin_unlock(&drbd_pp_lock);
if (page)
return page;
}
/* GFP_TRY, because we must not cause arbitrary write-out: in a DRBD
* "criss-cross" setup, that might cause write-out on some other DRBD,
* which in turn might block on the other node at this very place. */
for (i = 0; i < number; i++) {
tmp = alloc_page(GFP_TRY);
if (!tmp)
break;
set_page_private(tmp, (unsigned long)page);
page = tmp;
}
if (i == number)
return page;
/* Not enough pages immediately available this time.
* No need to jump around here, drbd_pp_alloc will retry this
* function "soon". */
if (page) {
tmp = page_chain_tail(page, NULL);
spin_lock(&drbd_pp_lock);
page_chain_add(&drbd_pp_pool, page, tmp);
drbd_pp_vacant += i;
spin_unlock(&drbd_pp_lock);
}
return NULL;
}
static void reclaim_net_ee(struct drbd_conf *mdev, struct list_head *to_be_freed)
{
struct drbd_epoch_entry *e;
struct list_head *le, *tle;
/* The EEs are always appended to the end of the list. Since
they are sent in order over the wire, they have to finish
in order. As soon as we see the first not finished we can
stop to examine the list... */
list_for_each_safe(le, tle, &mdev->net_ee) {
e = list_entry(le, struct drbd_epoch_entry, w.list);
if (drbd_ee_has_active_page(e))
break;
list_move(le, to_be_freed);
}
}
static void drbd_kick_lo_and_reclaim_net(struct drbd_conf *mdev)
{
LIST_HEAD(reclaimed);
struct drbd_epoch_entry *e, *t;
spin_lock_irq(&mdev->req_lock);
reclaim_net_ee(mdev, &reclaimed);
spin_unlock_irq(&mdev->req_lock);
list_for_each_entry_safe(e, t, &reclaimed, w.list)
drbd_free_net_ee(mdev, e);
}
/**
* drbd_pp_alloc() - Returns @number pages, retries forever (or until signalled)
* @mdev: DRBD device.
* @number: number of pages requested
* @retry: whether to retry, if not enough pages are available right now
*
* Tries to allocate number pages, first from our own page pool, then from
* the kernel, unless this allocation would exceed the max_buffers setting.
* Possibly retry until DRBD frees sufficient pages somewhere else.
*
* Returns a page chain linked via page->private.
*/
static struct page *drbd_pp_alloc(struct drbd_conf *mdev, unsigned number, bool retry)
{
struct page *page = NULL;
DEFINE_WAIT(wait);
/* Yes, we may run up to @number over max_buffers. If we
* follow it strictly, the admin will get it wrong anyways. */
if (atomic_read(&mdev->pp_in_use) < mdev->net_conf->max_buffers)
page = drbd_pp_first_pages_or_try_alloc(mdev, number);
while (page == NULL) {
prepare_to_wait(&drbd_pp_wait, &wait, TASK_INTERRUPTIBLE);
drbd_kick_lo_and_reclaim_net(mdev);
if (atomic_read(&mdev->pp_in_use) < mdev->net_conf->max_buffers) {
page = drbd_pp_first_pages_or_try_alloc(mdev, number);
if (page)
break;
}
if (!retry)
break;
if (signal_pending(current)) {
dev_warn(DEV, "drbd_pp_alloc interrupted!\n");
break;
}
schedule();
}
finish_wait(&drbd_pp_wait, &wait);
if (page)
atomic_add(number, &mdev->pp_in_use);
return page;
}
/* Must not be used from irq, as that may deadlock: see drbd_pp_alloc.
* Is also used from inside an other spin_lock_irq(&mdev->req_lock);
* Either links the page chain back to the global pool,
* or returns all pages to the system. */
static void drbd_pp_free(struct drbd_conf *mdev, struct page *page, int is_net)
{
atomic_t *a = is_net ? &mdev->pp_in_use_by_net : &mdev->pp_in_use;
int i;
if (drbd_pp_vacant > (DRBD_MAX_BIO_SIZE/PAGE_SIZE)*minor_count)
i = page_chain_free(page);
else {
struct page *tmp;
tmp = page_chain_tail(page, &i);
spin_lock(&drbd_pp_lock);
page_chain_add(&drbd_pp_pool, page, tmp);
drbd_pp_vacant += i;
spin_unlock(&drbd_pp_lock);
}
i = atomic_sub_return(i, a);
if (i < 0)
dev_warn(DEV, "ASSERTION FAILED: %s: %d < 0\n",
is_net ? "pp_in_use_by_net" : "pp_in_use", i);
wake_up(&drbd_pp_wait);
}
/*
You need to hold the req_lock:
_drbd_wait_ee_list_empty()
You must not have the req_lock:
drbd_free_ee()
drbd_alloc_ee()
drbd_init_ee()
drbd_release_ee()
drbd_ee_fix_bhs()
drbd_process_done_ee()
drbd_clear_done_ee()
drbd_wait_ee_list_empty()
*/
struct drbd_epoch_entry *drbd_alloc_ee(struct drbd_conf *mdev,
u64 id,
sector_t sector,
unsigned int data_size,
gfp_t gfp_mask) __must_hold(local)
{
struct drbd_epoch_entry *e;
struct page *page;
unsigned nr_pages = (data_size + PAGE_SIZE -1) >> PAGE_SHIFT;
if (drbd_insert_fault(mdev, DRBD_FAULT_AL_EE))
return NULL;
e = mempool_alloc(drbd_ee_mempool, gfp_mask & ~__GFP_HIGHMEM);
if (!e) {
if (!(gfp_mask & __GFP_NOWARN))
dev_err(DEV, "alloc_ee: Allocation of an EE failed\n");
return NULL;
}
page = drbd_pp_alloc(mdev, nr_pages, (gfp_mask & __GFP_WAIT));
if (!page)
goto fail;
INIT_HLIST_NODE(&e->collision);
e->epoch = NULL;
e->mdev = mdev;
e->pages = page;
atomic_set(&e->pending_bios, 0);
e->size = data_size;
e->flags = 0;
e->sector = sector;
e->block_id = id;
return e;
fail:
mempool_free(e, drbd_ee_mempool);
return NULL;
}
void drbd_free_some_ee(struct drbd_conf *mdev, struct drbd_epoch_entry *e, int is_net)
{
if (e->flags & EE_HAS_DIGEST)
kfree(e->digest);
drbd_pp_free(mdev, e->pages, is_net);
D_ASSERT(atomic_read(&e->pending_bios) == 0);
D_ASSERT(hlist_unhashed(&e->collision));
mempool_free(e, drbd_ee_mempool);
}
int drbd_release_ee(struct drbd_conf *mdev, struct list_head *list)
{
LIST_HEAD(work_list);
struct drbd_epoch_entry *e, *t;
int count = 0;
int is_net = list == &mdev->net_ee;
spin_lock_irq(&mdev->req_lock);
list_splice_init(list, &work_list);
spin_unlock_irq(&mdev->req_lock);
list_for_each_entry_safe(e, t, &work_list, w.list) {
drbd_free_some_ee(mdev, e, is_net);
count++;
}
return count;
}
/*
* This function is called from _asender only_
* but see also comments in _req_mod(,barrier_acked)
* and receive_Barrier.
*
* Move entries from net_ee to done_ee, if ready.
* Grab done_ee, call all callbacks, free the entries.
* The callbacks typically send out ACKs.
*/
static int drbd_process_done_ee(struct drbd_conf *mdev)
{
LIST_HEAD(work_list);
LIST_HEAD(reclaimed);
struct drbd_epoch_entry *e, *t;
int ok = (mdev->state.conn >= C_WF_REPORT_PARAMS);
spin_lock_irq(&mdev->req_lock);
reclaim_net_ee(mdev, &reclaimed);
list_splice_init(&mdev->done_ee, &work_list);
spin_unlock_irq(&mdev->req_lock);
list_for_each_entry_safe(e, t, &reclaimed, w.list)
drbd_free_net_ee(mdev, e);
/* possible callbacks here:
* e_end_block, and e_end_resync_block, e_send_discard_ack.
* all ignore the last argument.
*/
list_for_each_entry_safe(e, t, &work_list, w.list) {
/* list_del not necessary, next/prev members not touched */
ok = e->w.cb(mdev, &e->w, !ok) && ok;
drbd_free_ee(mdev, e);
}
wake_up(&mdev->ee_wait);
return ok;
}
void _drbd_wait_ee_list_empty(struct drbd_conf *mdev, struct list_head *head)
{
DEFINE_WAIT(wait);
/* avoids spin_lock/unlock
* and calling prepare_to_wait in the fast path */
while (!list_empty(head)) {
prepare_to_wait(&mdev->ee_wait, &wait, TASK_UNINTERRUPTIBLE);
spin_unlock_irq(&mdev->req_lock);
io_schedule();
finish_wait(&mdev->ee_wait, &wait);
spin_lock_irq(&mdev->req_lock);
}
}
void drbd_wait_ee_list_empty(struct drbd_conf *mdev, struct list_head *head)
{
spin_lock_irq(&mdev->req_lock);
_drbd_wait_ee_list_empty(mdev, head);
spin_unlock_irq(&mdev->req_lock);
}
/* see also kernel_accept; which is only present since 2.6.18.
* also we want to log which part of it failed, exactly */
static int drbd_accept(struct drbd_conf *mdev, const char **what,
struct socket *sock, struct socket **newsock)
{
struct sock *sk = sock->sk;
int err = 0;
*what = "listen";
err = sock->ops->listen(sock, 5);
if (err < 0)
goto out;
*what = "sock_create_lite";
err = sock_create_lite(sk->sk_family, sk->sk_type, sk->sk_protocol,
newsock);
if (err < 0)
goto out;
*what = "accept";
err = sock->ops->accept(sock, *newsock, 0);
if (err < 0) {
sock_release(*newsock);
*newsock = NULL;
goto out;
}
(*newsock)->ops = sock->ops;
out:
return err;
}
static int drbd_recv_short(struct drbd_conf *mdev, struct socket *sock,
void *buf, size_t size, int flags)
{
mm_segment_t oldfs;
struct kvec iov = {
.iov_base = buf,
.iov_len = size,
};
struct msghdr msg = {
.msg_iovlen = 1,
.msg_iov = (struct iovec *)&iov,
.msg_flags = (flags ? flags : MSG_WAITALL | MSG_NOSIGNAL)
};
int rv;
oldfs = get_fs();
set_fs(KERNEL_DS);
rv = sock_recvmsg(sock, &msg, size, msg.msg_flags);
set_fs(oldfs);
return rv;
}
static int drbd_recv(struct drbd_conf *mdev, void *buf, size_t size)
{
mm_segment_t oldfs;
struct kvec iov = {
.iov_base = buf,
.iov_len = size,
};
struct msghdr msg = {
.msg_iovlen = 1,
.msg_iov = (struct iovec *)&iov,
.msg_flags = MSG_WAITALL | MSG_NOSIGNAL
};
int rv;
oldfs = get_fs();
set_fs(KERNEL_DS);
for (;;) {
rv = sock_recvmsg(mdev->data.socket, &msg, size, msg.msg_flags);
if (rv == size)
break;
/* Note:
* ECONNRESET other side closed the connection
* ERESTARTSYS (on sock) we got a signal
*/
if (rv < 0) {
if (rv == -ECONNRESET)
dev_info(DEV, "sock was reset by peer\n");
else if (rv != -ERESTARTSYS)
dev_err(DEV, "sock_recvmsg returned %d\n", rv);
break;
} else if (rv == 0) {
dev_info(DEV, "sock was shut down by peer\n");
break;
} else {
/* signal came in, or peer/link went down,
* after we read a partial message
*/
/* D_ASSERT(signal_pending(current)); */
break;
}
};
set_fs(oldfs);
if (rv != size)
drbd_force_state(mdev, NS(conn, C_BROKEN_PIPE));
return rv;
}
/* quoting tcp(7):
* On individual connections, the socket buffer size must be set prior to the
* listen(2) or connect(2) calls in order to have it take effect.
* This is our wrapper to do so.
*/
static void drbd_setbufsize(struct socket *sock, unsigned int snd,
unsigned int rcv)
{
/* open coded SO_SNDBUF, SO_RCVBUF */
if (snd) {
sock->sk->sk_sndbuf = snd;
sock->sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
}
if (rcv) {
sock->sk->sk_rcvbuf = rcv;
sock->sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
}
}
static struct socket *drbd_try_connect(struct drbd_conf *mdev)
{
const char *what;
struct socket *sock;
struct sockaddr_in6 src_in6;
int err;
int disconnect_on_error = 1;
if (!get_net_conf(mdev))
return NULL;
what = "sock_create_kern";
err = sock_create_kern(((struct sockaddr *)mdev->net_conf->my_addr)->sa_family,
SOCK_STREAM, IPPROTO_TCP, &sock);
if (err < 0) {
sock = NULL;
goto out;
}
sock->sk->sk_rcvtimeo =
sock->sk->sk_sndtimeo = mdev->net_conf->try_connect_int*HZ;
drbd_setbufsize(sock, mdev->net_conf->sndbuf_size,
mdev->net_conf->rcvbuf_size);
/* explicitly bind to the configured IP as source IP
* for the outgoing connections.
* This is needed for multihomed hosts and to be
* able to use lo: interfaces for drbd.
* Make sure to use 0 as port number, so linux selects
* a free one dynamically.
*/
memcpy(&src_in6, mdev->net_conf->my_addr,
min_t(int, mdev->net_conf->my_addr_len, sizeof(src_in6)));
if (((struct sockaddr *)mdev->net_conf->my_addr)->sa_family == AF_INET6)
src_in6.sin6_port = 0;
else
((struct sockaddr_in *)&src_in6)->sin_port = 0; /* AF_INET & AF_SCI */
what = "bind before connect";
err = sock->ops->bind(sock,
(struct sockaddr *) &src_in6,
mdev->net_conf->my_addr_len);
if (err < 0)
goto out;
/* connect may fail, peer not yet available.
* stay C_WF_CONNECTION, don't go Disconnecting! */
disconnect_on_error = 0;
what = "connect";
err = sock->ops->connect(sock,
(struct sockaddr *)mdev->net_conf->peer_addr,
mdev->net_conf->peer_addr_len, 0);
out:
if (err < 0) {
if (sock) {
sock_release(sock);
sock = NULL;
}
switch (-err) {
/* timeout, busy, signal pending */
case ETIMEDOUT: case EAGAIN: case EINPROGRESS:
case EINTR: case ERESTARTSYS:
/* peer not (yet) available, network problem */
case ECONNREFUSED: case ENETUNREACH:
case EHOSTDOWN: case EHOSTUNREACH:
disconnect_on_error = 0;
break;
default:
dev_err(DEV, "%s failed, err = %d\n", what, err);
}
if (disconnect_on_error)
drbd_force_state(mdev, NS(conn, C_DISCONNECTING));
}
put_net_conf(mdev);
return sock;
}
static struct socket *drbd_wait_for_connect(struct drbd_conf *mdev)
{
int timeo, err;
struct socket *s_estab = NULL, *s_listen;
const char *what;
if (!get_net_conf(mdev))
return NULL;
what = "sock_create_kern";
err = sock_create_kern(((struct sockaddr *)mdev->net_conf->my_addr)->sa_family,
SOCK_STREAM, IPPROTO_TCP, &s_listen);
if (err) {
s_listen = NULL;
goto out;
}
timeo = mdev->net_conf->try_connect_int * HZ;
timeo += (random32() & 1) ? timeo / 7 : -timeo / 7; /* 28.5% random jitter */
s_listen->sk->sk_reuse = 1; /* SO_REUSEADDR */
s_listen->sk->sk_rcvtimeo = timeo;
s_listen->sk->sk_sndtimeo = timeo;
drbd_setbufsize(s_listen, mdev->net_conf->sndbuf_size,
mdev->net_conf->rcvbuf_size);
what = "bind before listen";
err = s_listen->ops->bind(s_listen,
(struct sockaddr *) mdev->net_conf->my_addr,
mdev->net_conf->my_addr_len);
if (err < 0)
goto out;
err = drbd_accept(mdev, &what, s_listen, &s_estab);
out:
if (s_listen)
sock_release(s_listen);
if (err < 0) {
if (err != -EAGAIN && err != -EINTR && err != -ERESTARTSYS) {
dev_err(DEV, "%s failed, err = %d\n", what, err);
drbd_force_state(mdev, NS(conn, C_DISCONNECTING));
}
}
put_net_conf(mdev);
return s_estab;
}
static int drbd_send_fp(struct drbd_conf *mdev,
struct socket *sock, enum drbd_packets cmd)
{
struct p_header80 *h = &mdev->data.sbuf.header.h80;
return _drbd_send_cmd(mdev, sock, cmd, h, sizeof(*h), 0);
}
static enum drbd_packets drbd_recv_fp(struct drbd_conf *mdev, struct socket *sock)
{
struct p_header80 *h = &mdev->data.rbuf.header.h80;
int rr;
rr = drbd_recv_short(mdev, sock, h, sizeof(*h), 0);
if (rr == sizeof(*h) && h->magic == BE_DRBD_MAGIC)
return be16_to_cpu(h->command);
return 0xffff;
}
/**
* drbd_socket_okay() - Free the socket if its connection is not okay
* @mdev: DRBD device.
* @sock: pointer to the pointer to the socket.
*/
static int drbd_socket_okay(struct drbd_conf *mdev, struct socket **sock)
{
int rr;
char tb[4];
if (!*sock)
return false;
rr = drbd_recv_short(mdev, *sock, tb, 4, MSG_DONTWAIT | MSG_PEEK);
if (rr > 0 || rr == -EAGAIN) {
return true;
} else {
sock_release(*sock);
*sock = NULL;
return false;
}
}
/*
* return values:
* 1 yes, we have a valid connection
* 0 oops, did not work out, please try again
* -1 peer talks different language,
* no point in trying again, please go standalone.
* -2 We do not have a network config...
*/
static int drbd_connect(struct drbd_conf *mdev)
{
struct socket *s, *sock, *msock;
int try, h, ok;
D_ASSERT(!mdev->data.socket);
if (drbd_request_state(mdev, NS(conn, C_WF_CONNECTION)) < SS_SUCCESS)
return -2;
clear_bit(DISCARD_CONCURRENT, &mdev->flags);
sock = NULL;
msock = NULL;
do {
for (try = 0;;) {
/* 3 tries, this should take less than a second! */
s = drbd_try_connect(mdev);
if (s || ++try >= 3)
break;
/* give the other side time to call bind() & listen() */
schedule_timeout_interruptible(HZ / 10);
}
if (s) {
if (!sock) {
drbd_send_fp(mdev, s, P_HAND_SHAKE_S);
sock = s;
s = NULL;
} else if (!msock) {
drbd_send_fp(mdev, s, P_HAND_SHAKE_M);
msock = s;
s = NULL;
} else {
dev_err(DEV, "Logic error in drbd_connect()\n");
goto out_release_sockets;
}
}
if (sock && msock) {
schedule_timeout_interruptible(mdev->net_conf->ping_timeo*HZ/10);
ok = drbd_socket_okay(mdev, &sock);
ok = drbd_socket_okay(mdev, &msock) && ok;
if (ok)
break;
}
retry:
s = drbd_wait_for_connect(mdev);
if (s) {
try = drbd_recv_fp(mdev, s);
drbd_socket_okay(mdev, &sock);
drbd_socket_okay(mdev, &msock);
switch (try) {
case P_HAND_SHAKE_S:
if (sock) {
dev_warn(DEV, "initial packet S crossed\n");
sock_release(sock);
}
sock = s;
break;
case P_HAND_SHAKE_M:
if (msock) {
dev_warn(DEV, "initial packet M crossed\n");
sock_release(msock);
}
msock = s;
set_bit(DISCARD_CONCURRENT, &mdev->flags);
break;
default:
dev_warn(DEV, "Error receiving initial packet\n");
sock_release(s);
if (random32() & 1)
goto retry;
}
}
if (mdev->state.conn <= C_DISCONNECTING)
goto out_release_sockets;
if (signal_pending(current)) {
flush_signals(current);
smp_rmb();
if (get_t_state(&mdev->receiver) == Exiting)
goto out_release_sockets;
}
if (sock && msock) {
ok = drbd_socket_okay(mdev, &sock);
ok = drbd_socket_okay(mdev, &msock) && ok;
if (ok)
break;
}
} while (1);
msock->sk->sk_reuse = 1; /* SO_REUSEADDR */
sock->sk->sk_reuse = 1; /* SO_REUSEADDR */
sock->sk->sk_allocation = GFP_NOIO;
msock->sk->sk_allocation = GFP_NOIO;
sock->sk->sk_priority = TC_PRIO_INTERACTIVE_BULK;
msock->sk->sk_priority = TC_PRIO_INTERACTIVE;
/* NOT YET ...
* sock->sk->sk_sndtimeo = mdev->net_conf->timeout*HZ/10;
* sock->sk->sk_rcvtimeo = MAX_SCHEDULE_TIMEOUT;
* first set it to the P_HAND_SHAKE timeout,
* which we set to 4x the configured ping_timeout. */
sock->sk->sk_sndtimeo =
sock->sk->sk_rcvtimeo = mdev->net_conf->ping_timeo*4*HZ/10;
msock->sk->sk_sndtimeo = mdev->net_conf->timeout*HZ/10;
msock->sk->sk_rcvtimeo = mdev->net_conf->ping_int*HZ;
/* we don't want delays.
* we use TCP_CORK where appropriate, though */
drbd_tcp_nodelay(sock);
drbd_tcp_nodelay(msock);
mdev->data.socket = sock;
mdev->meta.socket = msock;
mdev->last_received = jiffies;
D_ASSERT(mdev->asender.task == NULL);
h = drbd_do_handshake(mdev);
if (h <= 0)
return h;
if (mdev->cram_hmac_tfm) {
/* drbd_request_state(mdev, NS(conn, WFAuth)); */
switch (drbd_do_auth(mdev)) {
case -1:
dev_err(DEV, "Authentication of peer failed\n");
return -1;
case 0:
dev_err(DEV, "Authentication of peer failed, trying again.\n");
return 0;
}
}
if (drbd_request_state(mdev, NS(conn, C_WF_REPORT_PARAMS)) < SS_SUCCESS)
return 0;
sock->sk->sk_sndtimeo = mdev->net_conf->timeout*HZ/10;
sock->sk->sk_rcvtimeo = MAX_SCHEDULE_TIMEOUT;
atomic_set(&mdev->packet_seq, 0);
mdev->peer_seq = 0;
drbd_thread_start(&mdev->asender);
if (drbd_send_protocol(mdev) == -1)
return -1;
drbd_send_sync_param(mdev, &mdev->sync_conf);
drbd_send_sizes(mdev, 0, 0);
drbd_send_uuids(mdev);
drbd_send_state(mdev);
clear_bit(USE_DEGR_WFC_T, &mdev->flags);
clear_bit(RESIZE_PENDING, &mdev->flags);
mod_timer(&mdev->request_timer, jiffies + HZ); /* just start it here. */
return 1;
out_release_sockets:
if (sock)
sock_release(sock);
if (msock)
sock_release(msock);
return -1;
}
static int drbd_recv_header(struct drbd_conf *mdev, enum drbd_packets *cmd, unsigned int *packet_size)
{
union p_header *h = &mdev->data.rbuf.header;
int r;
r = drbd_recv(mdev, h, sizeof(*h));
if (unlikely(r != sizeof(*h))) {
if (!signal_pending(current))
dev_warn(DEV, "short read expecting header on sock: r=%d\n", r);
return false;
}
if (likely(h->h80.magic == BE_DRBD_MAGIC)) {
*cmd = be16_to_cpu(h->h80.command);
*packet_size = be16_to_cpu(h->h80.length);
} else if (h->h95.magic == BE_DRBD_MAGIC_BIG) {
*cmd = be16_to_cpu(h->h95.command);
*packet_size = be32_to_cpu(h->h95.length);
} else {
dev_err(DEV, "magic?? on data m: 0x%08x c: %d l: %d\n",
be32_to_cpu(h->h80.magic),
be16_to_cpu(h->h80.command),
be16_to_cpu(h->h80.length));
return false;
}
mdev->last_received = jiffies;
return true;
}
static void drbd_flush(struct drbd_conf *mdev)
{
int rv;
if (mdev->write_ordering >= WO_bdev_flush && get_ldev(mdev)) {
rv = blkdev_issue_flush(mdev->ldev->backing_bdev, GFP_KERNEL,
NULL);
if (rv) {
dev_err(DEV, "local disk flush failed with status %d\n", rv);
/* would rather check on EOPNOTSUPP, but that is not reliable.
* don't try again for ANY return value != 0
* if (rv == -EOPNOTSUPP) */
drbd_bump_write_ordering(mdev, WO_drain_io);
}
put_ldev(mdev);
}
}
/**
* drbd_may_finish_epoch() - Applies an epoch_event to the epoch's state, eventually finishes it.
* @mdev: DRBD device.
* @epoch: Epoch object.
* @ev: Epoch event.
*/
static enum finish_epoch drbd_may_finish_epoch(struct drbd_conf *mdev,
struct drbd_epoch *epoch,
enum epoch_event ev)
{
int epoch_size;
struct drbd_epoch *next_epoch;
enum finish_epoch rv = FE_STILL_LIVE;
spin_lock(&mdev->epoch_lock);
do {
next_epoch = NULL;
epoch_size = atomic_read(&epoch->epoch_size);
switch (ev & ~EV_CLEANUP) {
case EV_PUT:
atomic_dec(&epoch->active);
break;
case EV_GOT_BARRIER_NR:
set_bit(DE_HAVE_BARRIER_NUMBER, &epoch->flags);
break;
case EV_BECAME_LAST:
/* nothing to do*/
break;
}
if (epoch_size != 0 &&
atomic_read(&epoch->active) == 0 &&
test_bit(DE_HAVE_BARRIER_NUMBER, &epoch->flags)) {
if (!(ev & EV_CLEANUP)) {
spin_unlock(&mdev->epoch_lock);
drbd_send_b_ack(mdev, epoch->barrier_nr, epoch_size);
spin_lock(&mdev->epoch_lock);
}
dec_unacked(mdev);
if (mdev->current_epoch != epoch) {
next_epoch = list_entry(epoch->list.next, struct drbd_epoch, list);
list_del(&epoch->list);
ev = EV_BECAME_LAST | (ev & EV_CLEANUP);
mdev->epochs--;
kfree(epoch);
if (rv == FE_STILL_LIVE)
rv = FE_DESTROYED;
} else {
epoch->flags = 0;
atomic_set(&epoch->epoch_size, 0);
/* atomic_set(&epoch->active, 0); is already zero */
if (rv == FE_STILL_LIVE)
rv = FE_RECYCLED;
wake_up(&mdev->ee_wait);
}
}
if (!next_epoch)
break;
epoch = next_epoch;
} while (1);
spin_unlock(&mdev->epoch_lock);
return rv;
}
/**
* drbd_bump_write_ordering() - Fall back to an other write ordering method
* @mdev: DRBD device.
* @wo: Write ordering method to try.
*/
void drbd_bump_write_ordering(struct drbd_conf *mdev, enum write_ordering_e wo) __must_hold(local)
{
enum write_ordering_e pwo;
static char *write_ordering_str[] = {
[WO_none] = "none",
[WO_drain_io] = "drain",
[WO_bdev_flush] = "flush",
};
pwo = mdev->write_ordering;
wo = min(pwo, wo);
if (wo == WO_bdev_flush && mdev->ldev->dc.no_disk_flush)
wo = WO_drain_io;
if (wo == WO_drain_io && mdev->ldev->dc.no_disk_drain)
wo = WO_none;
mdev->write_ordering = wo;
if (pwo != mdev->write_ordering || wo == WO_bdev_flush)
dev_info(DEV, "Method to ensure write ordering: %s\n", write_ordering_str[mdev->write_ordering]);
}
/**
* drbd_submit_ee()
* @mdev: DRBD device.
* @e: epoch entry
* @rw: flag field, see bio->bi_rw
*
* May spread the pages to multiple bios,
* depending on bio_add_page restrictions.
*
* Returns 0 if all bios have been submitted,
* -ENOMEM if we could not allocate enough bios,
* -ENOSPC (any better suggestion?) if we have not been able to bio_add_page a
* single page to an empty bio (which should never happen and likely indicates
* that the lower level IO stack is in some way broken). This has been observed
* on certain Xen deployments.
*/
/* TODO allocate from our own bio_set. */
int drbd_submit_ee(struct drbd_conf *mdev, struct drbd_epoch_entry *e,
const unsigned rw, const int fault_type)
{
struct bio *bios = NULL;
struct bio *bio;
struct page *page = e->pages;
sector_t sector = e->sector;
unsigned ds = e->size;
unsigned n_bios = 0;
unsigned nr_pages = (ds + PAGE_SIZE -1) >> PAGE_SHIFT;
int err = -ENOMEM;
/* In most cases, we will only need one bio. But in case the lower
* level restrictions happen to be different at this offset on this
* side than those of the sending peer, we may need to submit the
* request in more than one bio. */
next_bio:
bio = bio_alloc(GFP_NOIO, nr_pages);
if (!bio) {
dev_err(DEV, "submit_ee: Allocation of a bio failed\n");
goto fail;
}
/* > e->sector, unless this is the first bio */
bio->bi_sector = sector;
bio->bi_bdev = mdev->ldev->backing_bdev;
bio->bi_rw = rw;
bio->bi_private = e;
bio->bi_end_io = drbd_endio_sec;
bio->bi_next = bios;
bios = bio;
++n_bios;
page_chain_for_each(page) {
unsigned len = min_t(unsigned, ds, PAGE_SIZE);
if (!bio_add_page(bio, page, len, 0)) {
/* A single page must always be possible!
* But in case it fails anyways,
* we deal with it, and complain (below). */
if (bio->bi_vcnt == 0) {
dev_err(DEV,
"bio_add_page failed for len=%u, "
"bi_vcnt=0 (bi_sector=%llu)\n",
len, (unsigned long long)bio->bi_sector);
err = -ENOSPC;
goto fail;
}
goto next_bio;
}
ds -= len;
sector += len >> 9;
--nr_pages;
}
D_ASSERT(page == NULL);
D_ASSERT(ds == 0);
atomic_set(&e->pending_bios, n_bios);
do {
bio = bios;
bios = bios->bi_next;
bio->bi_next = NULL;
drbd_generic_make_request(mdev, fault_type, bio);
} while (bios);
return 0;
fail:
while (bios) {
bio = bios;
bios = bios->bi_next;
bio_put(bio);
}
return err;
}
static int receive_Barrier(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int data_size)
{
int rv;
struct p_barrier *p = &mdev->data.rbuf.barrier;
struct drbd_epoch *epoch;
inc_unacked(mdev);
mdev->current_epoch->barrier_nr = p->barrier;
rv = drbd_may_finish_epoch(mdev, mdev->current_epoch, EV_GOT_BARRIER_NR);
/* P_BARRIER_ACK may imply that the corresponding extent is dropped from
* the activity log, which means it would not be resynced in case the
* R_PRIMARY crashes now.
* Therefore we must send the barrier_ack after the barrier request was
* completed. */
switch (mdev->write_ordering) {
case WO_none:
if (rv == FE_RECYCLED)
return true;
/* receiver context, in the writeout path of the other node.
* avoid potential distributed deadlock */
epoch = kmalloc(sizeof(struct drbd_epoch), GFP_NOIO);
if (epoch)
break;
else
dev_warn(DEV, "Allocation of an epoch failed, slowing down\n");
/* Fall through */
case WO_bdev_flush:
case WO_drain_io:
drbd_wait_ee_list_empty(mdev, &mdev->active_ee);
drbd_flush(mdev);
if (atomic_read(&mdev->current_epoch->epoch_size)) {
epoch = kmalloc(sizeof(struct drbd_epoch), GFP_NOIO);
if (epoch)
break;
}
epoch = mdev->current_epoch;
wait_event(mdev->ee_wait, atomic_read(&epoch->epoch_size) == 0);
D_ASSERT(atomic_read(&epoch->active) == 0);
D_ASSERT(epoch->flags == 0);
return true;
default:
dev_err(DEV, "Strangeness in mdev->write_ordering %d\n", mdev->write_ordering);
return false;
}
epoch->flags = 0;
atomic_set(&epoch->epoch_size, 0);
atomic_set(&epoch->active, 0);
spin_lock(&mdev->epoch_lock);
if (atomic_read(&mdev->current_epoch->epoch_size)) {
list_add(&epoch->list, &mdev->current_epoch->list);
mdev->current_epoch = epoch;
mdev->epochs++;
} else {
/* The current_epoch got recycled while we allocated this one... */
kfree(epoch);
}
spin_unlock(&mdev->epoch_lock);
return true;
}
/* used from receive_RSDataReply (recv_resync_read)
* and from receive_Data */
static struct drbd_epoch_entry *
read_in_block(struct drbd_conf *mdev, u64 id, sector_t sector, int data_size) __must_hold(local)
{
const sector_t capacity = drbd_get_capacity(mdev->this_bdev);
struct drbd_epoch_entry *e;
struct page *page;
int dgs, ds, rr;
void *dig_in = mdev->int_dig_in;
void *dig_vv = mdev->int_dig_vv;
unsigned long *data;
dgs = (mdev->agreed_pro_version >= 87 && mdev->integrity_r_tfm) ?
crypto_hash_digestsize(mdev->integrity_r_tfm) : 0;
if (dgs) {
rr = drbd_recv(mdev, dig_in, dgs);
if (rr != dgs) {
if (!signal_pending(current))
dev_warn(DEV,
"short read receiving data digest: read %d expected %d\n",
rr, dgs);
return NULL;
}
}
data_size -= dgs;
ERR_IF(data_size == 0) return NULL;
ERR_IF(data_size & 0x1ff) return NULL;
ERR_IF(data_size > DRBD_MAX_BIO_SIZE) return NULL;
/* even though we trust out peer,
* we sometimes have to double check. */
if (sector + (data_size>>9) > capacity) {
dev_err(DEV, "request from peer beyond end of local disk: "
"capacity: %llus < sector: %llus + size: %u\n",
(unsigned long long)capacity,
(unsigned long long)sector, data_size);
return NULL;
}
/* GFP_NOIO, because we must not cause arbitrary write-out: in a DRBD
* "criss-cross" setup, that might cause write-out on some other DRBD,
* which in turn might block on the other node at this very place. */
e = drbd_alloc_ee(mdev, id, sector, data_size, GFP_NOIO);
if (!e)
return NULL;
ds = data_size;
page = e->pages;
page_chain_for_each(page) {
unsigned len = min_t(int, ds, PAGE_SIZE);
data = kmap(page);
rr = drbd_recv(mdev, data, len);
if (drbd_insert_fault(mdev, DRBD_FAULT_RECEIVE)) {
dev_err(DEV, "Fault injection: Corrupting data on receive\n");
data[0] = data[0] ^ (unsigned long)-1;
}
kunmap(page);
if (rr != len) {
drbd_free_ee(mdev, e);
if (!signal_pending(current))
dev_warn(DEV, "short read receiving data: read %d expected %d\n",
rr, len);
return NULL;
}
ds -= rr;
}
if (dgs) {
drbd_csum_ee(mdev, mdev->integrity_r_tfm, e, dig_vv);
if (memcmp(dig_in, dig_vv, dgs)) {
dev_err(DEV, "Digest integrity check FAILED: %llus +%u\n",
(unsigned long long)sector, data_size);
drbd_bcast_ee(mdev, "digest failed",
dgs, dig_in, dig_vv, e);
drbd_free_ee(mdev, e);
return NULL;
}
}
mdev->recv_cnt += data_size>>9;
return e;
}
/* drbd_drain_block() just takes a data block
* out of the socket input buffer, and discards it.
*/
static int drbd_drain_block(struct drbd_conf *mdev, int data_size)
{
struct page *page;
int rr, rv = 1;
void *data;
if (!data_size)
return true;
page = drbd_pp_alloc(mdev, 1, 1);
data = kmap(page);
while (data_size) {
rr = drbd_recv(mdev, data, min_t(int, data_size, PAGE_SIZE));
if (rr != min_t(int, data_size, PAGE_SIZE)) {
rv = 0;
if (!signal_pending(current))
dev_warn(DEV,
"short read receiving data: read %d expected %d\n",
rr, min_t(int, data_size, PAGE_SIZE));
break;
}
data_size -= rr;
}
kunmap(page);
drbd_pp_free(mdev, page, 0);
return rv;
}
static int recv_dless_read(struct drbd_conf *mdev, struct drbd_request *req,
sector_t sector, int data_size)
{
struct bio_vec *bvec;
struct bio *bio;
int dgs, rr, i, expect;
void *dig_in = mdev->int_dig_in;
void *dig_vv = mdev->int_dig_vv;
dgs = (mdev->agreed_pro_version >= 87 && mdev->integrity_r_tfm) ?
crypto_hash_digestsize(mdev->integrity_r_tfm) : 0;
if (dgs) {
rr = drbd_recv(mdev, dig_in, dgs);
if (rr != dgs) {
if (!signal_pending(current))
dev_warn(DEV,
"short read receiving data reply digest: read %d expected %d\n",
rr, dgs);
return 0;
}
}
data_size -= dgs;
/* optimistically update recv_cnt. if receiving fails below,
* we disconnect anyways, and counters will be reset. */
mdev->recv_cnt += data_size>>9;
bio = req->master_bio;
D_ASSERT(sector == bio->bi_sector);
bio_for_each_segment(bvec, bio, i) {
expect = min_t(int, data_size, bvec->bv_len);
rr = drbd_recv(mdev,
kmap(bvec->bv_page)+bvec->bv_offset,
expect);
kunmap(bvec->bv_page);
if (rr != expect) {
if (!signal_pending(current))
dev_warn(DEV, "short read receiving data reply: "
"read %d expected %d\n",
rr, expect);
return 0;
}
data_size -= rr;
}
if (dgs) {
drbd_csum_bio(mdev, mdev->integrity_r_tfm, bio, dig_vv);
if (memcmp(dig_in, dig_vv, dgs)) {
dev_err(DEV, "Digest integrity check FAILED. Broken NICs?\n");
return 0;
}
}
D_ASSERT(data_size == 0);
return 1;
}
/* e_end_resync_block() is called via
* drbd_process_done_ee() by asender only */
static int e_end_resync_block(struct drbd_conf *mdev, struct drbd_work *w, int unused)
{
struct drbd_epoch_entry *e = (struct drbd_epoch_entry *)w;
sector_t sector = e->sector;
int ok;
D_ASSERT(hlist_unhashed(&e->collision));
if (likely((e->flags & EE_WAS_ERROR) == 0)) {
drbd_set_in_sync(mdev, sector, e->size);
ok = drbd_send_ack(mdev, P_RS_WRITE_ACK, e);
} else {
/* Record failure to sync */
drbd_rs_failed_io(mdev, sector, e->size);
ok = drbd_send_ack(mdev, P_NEG_ACK, e);
}
dec_unacked(mdev);
return ok;
}
static int recv_resync_read(struct drbd_conf *mdev, sector_t sector, int data_size) __releases(local)
{
struct drbd_epoch_entry *e;
e = read_in_block(mdev, ID_SYNCER, sector, data_size);
if (!e)
goto fail;
dec_rs_pending(mdev);
inc_unacked(mdev);
/* corresponding dec_unacked() in e_end_resync_block()
* respective _drbd_clear_done_ee */
e->w.cb = e_end_resync_block;
spin_lock_irq(&mdev->req_lock);
list_add(&e->w.list, &mdev->sync_ee);
spin_unlock_irq(&mdev->req_lock);
atomic_add(data_size >> 9, &mdev->rs_sect_ev);
if (drbd_submit_ee(mdev, e, WRITE, DRBD_FAULT_RS_WR) == 0)
return true;
/* don't care for the reason here */
dev_err(DEV, "submit failed, triggering re-connect\n");
spin_lock_irq(&mdev->req_lock);
list_del(&e->w.list);
spin_unlock_irq(&mdev->req_lock);
drbd_free_ee(mdev, e);
fail:
put_ldev(mdev);
return false;
}
static int receive_DataReply(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int data_size)
{
struct drbd_request *req;
sector_t sector;
int ok;
struct p_data *p = &mdev->data.rbuf.data;
sector = be64_to_cpu(p->sector);
spin_lock_irq(&mdev->req_lock);
req = _ar_id_to_req(mdev, p->block_id, sector);
spin_unlock_irq(&mdev->req_lock);
if (unlikely(!req)) {
dev_err(DEV, "Got a corrupt block_id/sector pair(1).\n");
return false;
}
/* hlist_del(&req->collision) is done in _req_may_be_done, to avoid
* special casing it there for the various failure cases.
* still no race with drbd_fail_pending_reads */
ok = recv_dless_read(mdev, req, sector, data_size);
if (ok)
req_mod(req, data_received);
/* else: nothing. handled from drbd_disconnect...
* I don't think we may complete this just yet
* in case we are "on-disconnect: freeze" */
return ok;
}
static int receive_RSDataReply(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int data_size)
{
sector_t sector;
int ok;
struct p_data *p = &mdev->data.rbuf.data;
sector = be64_to_cpu(p->sector);
D_ASSERT(p->block_id == ID_SYNCER);
if (get_ldev(mdev)) {
/* data is submitted to disk within recv_resync_read.
* corresponding put_ldev done below on error,
* or in drbd_endio_write_sec. */
ok = recv_resync_read(mdev, sector, data_size);
} else {
if (__ratelimit(&drbd_ratelimit_state))
dev_err(DEV, "Can not write resync data to local disk.\n");
ok = drbd_drain_block(mdev, data_size);
drbd_send_ack_dp(mdev, P_NEG_ACK, p, data_size);
}
atomic_add(data_size >> 9, &mdev->rs_sect_in);
return ok;
}
/* e_end_block() is called via drbd_process_done_ee().
* this means this function only runs in the asender thread
*/
static int e_end_block(struct drbd_conf *mdev, struct drbd_work *w, int cancel)
{
struct drbd_epoch_entry *e = (struct drbd_epoch_entry *)w;
sector_t sector = e->sector;
int ok = 1, pcmd;
if (mdev->net_conf->wire_protocol == DRBD_PROT_C) {
if (likely((e->flags & EE_WAS_ERROR) == 0)) {
pcmd = (mdev->state.conn >= C_SYNC_SOURCE &&
mdev->state.conn <= C_PAUSED_SYNC_T &&
e->flags & EE_MAY_SET_IN_SYNC) ?
P_RS_WRITE_ACK : P_WRITE_ACK;
ok &= drbd_send_ack(mdev, pcmd, e);
if (pcmd == P_RS_WRITE_ACK)
drbd_set_in_sync(mdev, sector, e->size);
} else {
ok = drbd_send_ack(mdev, P_NEG_ACK, e);
/* we expect it to be marked out of sync anyways...
* maybe assert this? */
}
dec_unacked(mdev);
}
/* we delete from the conflict detection hash _after_ we sent out the
* P_WRITE_ACK / P_NEG_ACK, to get the sequence number right. */
if (mdev->net_conf->two_primaries) {
spin_lock_irq(&mdev->req_lock);
D_ASSERT(!hlist_unhashed(&e->collision));
hlist_del_init(&e->collision);
spin_unlock_irq(&mdev->req_lock);
} else {
D_ASSERT(hlist_unhashed(&e->collision));
}
drbd_may_finish_epoch(mdev, e->epoch, EV_PUT + (cancel ? EV_CLEANUP : 0));
return ok;
}
static int e_send_discard_ack(struct drbd_conf *mdev, struct drbd_work *w, int unused)
{
struct drbd_epoch_entry *e = (struct drbd_epoch_entry *)w;
int ok = 1;
D_ASSERT(mdev->net_conf->wire_protocol == DRBD_PROT_C);
ok = drbd_send_ack(mdev, P_DISCARD_ACK, e);
spin_lock_irq(&mdev->req_lock);
D_ASSERT(!hlist_unhashed(&e->collision));
hlist_del_init(&e->collision);
spin_unlock_irq(&mdev->req_lock);
dec_unacked(mdev);
return ok;
}
/* Called from receive_Data.
* Synchronize packets on sock with packets on msock.
*
* This is here so even when a P_DATA packet traveling via sock overtook an Ack
* packet traveling on msock, they are still processed in the order they have
* been sent.
*
* Note: we don't care for Ack packets overtaking P_DATA packets.
*
* In case packet_seq is larger than mdev->peer_seq number, there are
* outstanding packets on the msock. We wait for them to arrive.
* In case we are the logically next packet, we update mdev->peer_seq
* ourselves. Correctly handles 32bit wrap around.
*
* Assume we have a 10 GBit connection, that is about 1<<30 byte per second,
* about 1<<21 sectors per second. So "worst" case, we have 1<<3 == 8 seconds
* for the 24bit wrap (historical atomic_t guarantee on some archs), and we have
* 1<<9 == 512 seconds aka ages for the 32bit wrap around...
*
* returns 0 if we may process the packet,
* -ERESTARTSYS if we were interrupted (by disconnect signal). */
static int drbd_wait_peer_seq(struct drbd_conf *mdev, const u32 packet_seq)
{
DEFINE_WAIT(wait);
unsigned int p_seq;
long timeout;
int ret = 0;
spin_lock(&mdev->peer_seq_lock);
for (;;) {
prepare_to_wait(&mdev->seq_wait, &wait, TASK_INTERRUPTIBLE);
if (seq_le(packet_seq, mdev->peer_seq+1))
break;
if (signal_pending(current)) {
ret = -ERESTARTSYS;
break;
}
p_seq = mdev->peer_seq;
spin_unlock(&mdev->peer_seq_lock);
timeout = schedule_timeout(30*HZ);
spin_lock(&mdev->peer_seq_lock);
if (timeout == 0 && p_seq == mdev->peer_seq) {
ret = -ETIMEDOUT;
dev_err(DEV, "ASSERT FAILED waited 30 seconds for sequence update, forcing reconnect\n");
break;
}
}
finish_wait(&mdev->seq_wait, &wait);
if (mdev->peer_seq+1 == packet_seq)
mdev->peer_seq++;
spin_unlock(&mdev->peer_seq_lock);
return ret;
}
/* see also bio_flags_to_wire()
* DRBD_REQ_*, because we need to semantically map the flags to data packet
* flags and back. We may replicate to other kernel versions. */
static unsigned long wire_flags_to_bio(struct drbd_conf *mdev, u32 dpf)
{
return (dpf & DP_RW_SYNC ? REQ_SYNC : 0) |
(dpf & DP_FUA ? REQ_FUA : 0) |
(dpf & DP_FLUSH ? REQ_FLUSH : 0) |
(dpf & DP_DISCARD ? REQ_DISCARD : 0);
}
/* mirrored write */
static int receive_Data(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int data_size)
{
sector_t sector;
struct drbd_epoch_entry *e;
struct p_data *p = &mdev->data.rbuf.data;
int rw = WRITE;
u32 dp_flags;
if (!get_ldev(mdev)) {
spin_lock(&mdev->peer_seq_lock);
if (mdev->peer_seq+1 == be32_to_cpu(p->seq_num))
mdev->peer_seq++;
spin_unlock(&mdev->peer_seq_lock);
drbd_send_ack_dp(mdev, P_NEG_ACK, p, data_size);
atomic_inc(&mdev->current_epoch->epoch_size);
return drbd_drain_block(mdev, data_size);
}
/* get_ldev(mdev) successful.
* Corresponding put_ldev done either below (on various errors),
* or in drbd_endio_write_sec, if we successfully submit the data at
* the end of this function. */
sector = be64_to_cpu(p->sector);
e = read_in_block(mdev, p->block_id, sector, data_size);
if (!e) {
put_ldev(mdev);
return false;
}
e->w.cb = e_end_block;
dp_flags = be32_to_cpu(p->dp_flags);
rw |= wire_flags_to_bio(mdev, dp_flags);
if (dp_flags & DP_MAY_SET_IN_SYNC)
e->flags |= EE_MAY_SET_IN_SYNC;
spin_lock(&mdev->epoch_lock);
e->epoch = mdev->current_epoch;
atomic_inc(&e->epoch->epoch_size);
atomic_inc(&e->epoch->active);
spin_unlock(&mdev->epoch_lock);
/* I'm the receiver, I do hold a net_cnt reference. */
if (!mdev->net_conf->two_primaries) {
spin_lock_irq(&mdev->req_lock);
} else {
/* don't get the req_lock yet,
* we may sleep in drbd_wait_peer_seq */
const int size = e->size;
const int discard = test_bit(DISCARD_CONCURRENT, &mdev->flags);
DEFINE_WAIT(wait);
struct drbd_request *i;
struct hlist_node *n;
struct hlist_head *slot;
int first;
D_ASSERT(mdev->net_conf->wire_protocol == DRBD_PROT_C);
BUG_ON(mdev->ee_hash == NULL);
BUG_ON(mdev->tl_hash == NULL);
/* conflict detection and handling:
* 1. wait on the sequence number,
* in case this data packet overtook ACK packets.
* 2. check our hash tables for conflicting requests.
* we only need to walk the tl_hash, since an ee can not
* have a conflict with an other ee: on the submitting
* node, the corresponding req had already been conflicting,
* and a conflicting req is never sent.
*
* Note: for two_primaries, we are protocol C,
* so there cannot be any request that is DONE
* but still on the transfer log.
*
* unconditionally add to the ee_hash.
*
* if no conflicting request is found:
* submit.
*
* if any conflicting request is found
* that has not yet been acked,
* AND I have the "discard concurrent writes" flag:
* queue (via done_ee) the P_DISCARD_ACK; OUT.
*
* if any conflicting request is found:
* block the receiver, waiting on misc_wait
* until no more conflicting requests are there,
* or we get interrupted (disconnect).
*
* we do not just write after local io completion of those
* requests, but only after req is done completely, i.e.
* we wait for the P_DISCARD_ACK to arrive!
*
* then proceed normally, i.e. submit.
*/
if (drbd_wait_peer_seq(mdev, be32_to_cpu(p->seq_num)))
goto out_interrupted;
spin_lock_irq(&mdev->req_lock);
hlist_add_head(&e->collision, ee_hash_slot(mdev, sector));
#define OVERLAPS overlaps(i->sector, i->size, sector, size)
slot = tl_hash_slot(mdev, sector);
first = 1;
for (;;) {
int have_unacked = 0;
int have_conflict = 0;
prepare_to_wait(&mdev->misc_wait, &wait,
TASK_INTERRUPTIBLE);
hlist_for_each_entry(i, n, slot, collision) {
if (OVERLAPS) {
/* only ALERT on first iteration,
* we may be woken up early... */
if (first)
dev_alert(DEV, "%s[%u] Concurrent local write detected!"
" new: %llus +%u; pending: %llus +%u\n",
current->comm, current->pid,
(unsigned long long)sector, size,
(unsigned long long)i->sector, i->size);
if (i->rq_state & RQ_NET_PENDING)
++have_unacked;
++have_conflict;
}
}
#undef OVERLAPS
if (!have_conflict)
break;
/* Discard Ack only for the _first_ iteration */
if (first && discard && have_unacked) {
dev_alert(DEV, "Concurrent write! [DISCARD BY FLAG] sec=%llus\n",
(unsigned long long)sector);
inc_unacked(mdev);
e->w.cb = e_send_discard_ack;
list_add_tail(&e->w.list, &mdev->done_ee);
spin_unlock_irq(&mdev->req_lock);
/* we could probably send that P_DISCARD_ACK ourselves,
* but I don't like the receiver using the msock */
put_ldev(mdev);
wake_asender(mdev);
finish_wait(&mdev->misc_wait, &wait);
return true;
}
if (signal_pending(current)) {
hlist_del_init(&e->collision);
spin_unlock_irq(&mdev->req_lock);
finish_wait(&mdev->misc_wait, &wait);
goto out_interrupted;
}
spin_unlock_irq(&mdev->req_lock);
if (first) {
first = 0;
dev_alert(DEV, "Concurrent write! [W AFTERWARDS] "
"sec=%llus\n", (unsigned long long)sector);
} else if (discard) {
/* we had none on the first iteration.
* there must be none now. */
D_ASSERT(have_unacked == 0);
}
schedule();
spin_lock_irq(&mdev->req_lock);
}
finish_wait(&mdev->misc_wait, &wait);
}
list_add(&e->w.list, &mdev->active_ee);
spin_unlock_irq(&mdev->req_lock);
switch (mdev->net_conf->wire_protocol) {
case DRBD_PROT_C:
inc_unacked(mdev);
/* corresponding dec_unacked() in e_end_block()
* respective _drbd_clear_done_ee */
break;
case DRBD_PROT_B:
/* I really don't like it that the receiver thread
* sends on the msock, but anyways */
drbd_send_ack(mdev, P_RECV_ACK, e);
break;
case DRBD_PROT_A:
/* nothing to do */
break;
}
if (mdev->state.pdsk < D_INCONSISTENT) {
/* In case we have the only disk of the cluster, */
drbd_set_out_of_sync(mdev, e->sector, e->size);
e->flags |= EE_CALL_AL_COMPLETE_IO;
e->flags &= ~EE_MAY_SET_IN_SYNC;
drbd_al_begin_io(mdev, e->sector);
}
if (drbd_submit_ee(mdev, e, rw, DRBD_FAULT_DT_WR) == 0)
return true;
/* don't care for the reason here */
dev_err(DEV, "submit failed, triggering re-connect\n");
spin_lock_irq(&mdev->req_lock);
list_del(&e->w.list);
hlist_del_init(&e->collision);
spin_unlock_irq(&mdev->req_lock);
if (e->flags & EE_CALL_AL_COMPLETE_IO)
drbd_al_complete_io(mdev, e->sector);
out_interrupted:
drbd_may_finish_epoch(mdev, e->epoch, EV_PUT + EV_CLEANUP);
put_ldev(mdev);
drbd_free_ee(mdev, e);
return false;
}
/* We may throttle resync, if the lower device seems to be busy,
* and current sync rate is above c_min_rate.
*
* To decide whether or not the lower device is busy, we use a scheme similar
* to MD RAID is_mddev_idle(): if the partition stats reveal "significant"
* (more than 64 sectors) of activity we cannot account for with our own resync
* activity, it obviously is "busy".
*
* The current sync rate used here uses only the most recent two step marks,
* to have a short time average so we can react faster.
*/
int drbd_rs_should_slow_down(struct drbd_conf *mdev, sector_t sector)
{
struct gendisk *disk = mdev->ldev->backing_bdev->bd_contains->bd_disk;
unsigned long db, dt, dbdt;
struct lc_element *tmp;
int curr_events;
int throttle = 0;
/* feature disabled? */
if (mdev->sync_conf.c_min_rate == 0)
return 0;
spin_lock_irq(&mdev->al_lock);
tmp = lc_find(mdev->resync, BM_SECT_TO_EXT(sector));
if (tmp) {
struct bm_extent *bm_ext = lc_entry(tmp, struct bm_extent, lce);
if (test_bit(BME_PRIORITY, &bm_ext->flags)) {
spin_unlock_irq(&mdev->al_lock);
return 0;
}
/* Do not slow down if app IO is already waiting for this extent */
}
spin_unlock_irq(&mdev->al_lock);
curr_events = (int)part_stat_read(&disk->part0, sectors[0]) +
(int)part_stat_read(&disk->part0, sectors[1]) -
atomic_read(&mdev->rs_sect_ev);
if (!mdev->rs_last_events || curr_events - mdev->rs_last_events > 64) {
unsigned long rs_left;
int i;
mdev->rs_last_events = curr_events;
/* sync speed average over the last 2*DRBD_SYNC_MARK_STEP,
* approx. */
i = (mdev->rs_last_mark + DRBD_SYNC_MARKS-1) % DRBD_SYNC_MARKS;
if (mdev->state.conn == C_VERIFY_S || mdev->state.conn == C_VERIFY_T)
rs_left = mdev->ov_left;
else
rs_left = drbd_bm_total_weight(mdev) - mdev->rs_failed;
dt = ((long)jiffies - (long)mdev->rs_mark_time[i]) / HZ;
if (!dt)
dt++;
db = mdev->rs_mark_left[i] - rs_left;
dbdt = Bit2KB(db/dt);
if (dbdt > mdev->sync_conf.c_min_rate)
throttle = 1;
}
return throttle;
}
static int receive_DataRequest(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int digest_size)
{
sector_t sector;
const sector_t capacity = drbd_get_capacity(mdev->this_bdev);
struct drbd_epoch_entry *e;
struct digest_info *di = NULL;
int size, verb;
unsigned int fault_type;
struct p_block_req *p = &mdev->data.rbuf.block_req;
sector = be64_to_cpu(p->sector);
size = be32_to_cpu(p->blksize);
if (size <= 0 || (size & 0x1ff) != 0 || size > DRBD_MAX_BIO_SIZE) {
dev_err(DEV, "%s:%d: sector: %llus, size: %u\n", __FILE__, __LINE__,
(unsigned long long)sector, size);
return false;
}
if (sector + (size>>9) > capacity) {
dev_err(DEV, "%s:%d: sector: %llus, size: %u\n", __FILE__, __LINE__,
(unsigned long long)sector, size);
return false;
}
if (!get_ldev_if_state(mdev, D_UP_TO_DATE)) {
verb = 1;
switch (cmd) {
case P_DATA_REQUEST:
drbd_send_ack_rp(mdev, P_NEG_DREPLY, p);
break;
case P_RS_DATA_REQUEST:
case P_CSUM_RS_REQUEST:
case P_OV_REQUEST:
drbd_send_ack_rp(mdev, P_NEG_RS_DREPLY , p);
break;
case P_OV_REPLY:
verb = 0;
dec_rs_pending(mdev);
drbd_send_ack_ex(mdev, P_OV_RESULT, sector, size, ID_IN_SYNC);
break;
default:
dev_err(DEV, "unexpected command (%s) in receive_DataRequest\n",
cmdname(cmd));
}
if (verb && __ratelimit(&drbd_ratelimit_state))
dev_err(DEV, "Can not satisfy peer's read request, "
"no local data.\n");
/* drain possibly payload */
return drbd_drain_block(mdev, digest_size);
}
/* GFP_NOIO, because we must not cause arbitrary write-out: in a DRBD
* "criss-cross" setup, that might cause write-out on some other DRBD,
* which in turn might block on the other node at this very place. */
e = drbd_alloc_ee(mdev, p->block_id, sector, size, GFP_NOIO);
if (!e) {
put_ldev(mdev);
return false;
}
switch (cmd) {
case P_DATA_REQUEST:
e->w.cb = w_e_end_data_req;
fault_type = DRBD_FAULT_DT_RD;
/* application IO, don't drbd_rs_begin_io */
goto submit;
case P_RS_DATA_REQUEST:
e->w.cb = w_e_end_rsdata_req;
fault_type = DRBD_FAULT_RS_RD;
/* used in the sector offset progress display */
mdev->bm_resync_fo = BM_SECT_TO_BIT(sector);
break;
case P_OV_REPLY:
case P_CSUM_RS_REQUEST:
fault_type = DRBD_FAULT_RS_RD;
di = kmalloc(sizeof(*di) + digest_size, GFP_NOIO);
if (!di)
goto out_free_e;
di->digest_size = digest_size;
di->digest = (((char *)di)+sizeof(struct digest_info));
e->digest = di;
e->flags |= EE_HAS_DIGEST;
if (drbd_recv(mdev, di->digest, digest_size) != digest_size)
goto out_free_e;
if (cmd == P_CSUM_RS_REQUEST) {
D_ASSERT(mdev->agreed_pro_version >= 89);
e->w.cb = w_e_end_csum_rs_req;
/* used in the sector offset progress display */
mdev->bm_resync_fo = BM_SECT_TO_BIT(sector);
} else if (cmd == P_OV_REPLY) {
/* track progress, we may need to throttle */
atomic_add(size >> 9, &mdev->rs_sect_in);
e->w.cb = w_e_end_ov_reply;
dec_rs_pending(mdev);
/* drbd_rs_begin_io done when we sent this request,
* but accounting still needs to be done. */
goto submit_for_resync;
}
break;
case P_OV_REQUEST:
if (mdev->ov_start_sector == ~(sector_t)0 &&
mdev->agreed_pro_version >= 90) {
unsigned long now = jiffies;
int i;
mdev->ov_start_sector = sector;
mdev->ov_position = sector;
mdev->ov_left = drbd_bm_bits(mdev) - BM_SECT_TO_BIT(sector);
mdev->rs_total = mdev->ov_left;
for (i = 0; i < DRBD_SYNC_MARKS; i++) {
mdev->rs_mark_left[i] = mdev->ov_left;
mdev->rs_mark_time[i] = now;
}
dev_info(DEV, "Online Verify start sector: %llu\n",
(unsigned long long)sector);
}
e->w.cb = w_e_end_ov_req;
fault_type = DRBD_FAULT_RS_RD;
break;
default:
dev_err(DEV, "unexpected command (%s) in receive_DataRequest\n",
cmdname(cmd));
fault_type = DRBD_FAULT_MAX;
goto out_free_e;
}
/* Throttle, drbd_rs_begin_io and submit should become asynchronous
* wrt the receiver, but it is not as straightforward as it may seem.
* Various places in the resync start and stop logic assume resync
* requests are processed in order, requeuing this on the worker thread
* introduces a bunch of new code for synchronization between threads.
*
* Unlimited throttling before drbd_rs_begin_io may stall the resync
* "forever", throttling after drbd_rs_begin_io will lock that extent
* for application writes for the same time. For now, just throttle
* here, where the rest of the code expects the receiver to sleep for
* a while, anyways.
*/
/* Throttle before drbd_rs_begin_io, as that locks out application IO;
* this defers syncer requests for some time, before letting at least
* on request through. The resync controller on the receiving side
* will adapt to the incoming rate accordingly.
*
* We cannot throttle here if remote is Primary/SyncTarget:
* we would also throttle its application reads.
* In that case, throttling is done on the SyncTarget only.
*/
if (mdev->state.peer != R_PRIMARY && drbd_rs_should_slow_down(mdev, sector))
schedule_timeout_uninterruptible(HZ/10);
if (drbd_rs_begin_io(mdev, sector))
goto out_free_e;
submit_for_resync:
atomic_add(size >> 9, &mdev->rs_sect_ev);
submit:
inc_unacked(mdev);
spin_lock_irq(&mdev->req_lock);
list_add_tail(&e->w.list, &mdev->read_ee);
spin_unlock_irq(&mdev->req_lock);
if (drbd_submit_ee(mdev, e, READ, fault_type) == 0)
return true;
/* don't care for the reason here */
dev_err(DEV, "submit failed, triggering re-connect\n");
spin_lock_irq(&mdev->req_lock);
list_del(&e->w.list);
spin_unlock_irq(&mdev->req_lock);
/* no drbd_rs_complete_io(), we are dropping the connection anyways */
out_free_e:
put_ldev(mdev);
drbd_free_ee(mdev, e);
return false;
}
static int drbd_asb_recover_0p(struct drbd_conf *mdev) __must_hold(local)
{
int self, peer, rv = -100;
unsigned long ch_self, ch_peer;
self = mdev->ldev->md.uuid[UI_BITMAP] & 1;
peer = mdev->p_uuid[UI_BITMAP] & 1;
ch_peer = mdev->p_uuid[UI_SIZE];
ch_self = mdev->comm_bm_set;
switch (mdev->net_conf->after_sb_0p) {
case ASB_CONSENSUS:
case ASB_DISCARD_SECONDARY:
case ASB_CALL_HELPER:
dev_err(DEV, "Configuration error.\n");
break;
case ASB_DISCONNECT:
break;
case ASB_DISCARD_YOUNGER_PRI:
if (self == 0 && peer == 1) {
rv = -1;
break;
}
if (self == 1 && peer == 0) {
rv = 1;
break;
}
/* Else fall through to one of the other strategies... */
case ASB_DISCARD_OLDER_PRI:
if (self == 0 && peer == 1) {
rv = 1;
break;
}
if (self == 1 && peer == 0) {
rv = -1;
break;
}
/* Else fall through to one of the other strategies... */
dev_warn(DEV, "Discard younger/older primary did not find a decision\n"
"Using discard-least-changes instead\n");
case ASB_DISCARD_ZERO_CHG:
if (ch_peer == 0 && ch_self == 0) {
rv = test_bit(DISCARD_CONCURRENT, &mdev->flags)
? -1 : 1;
break;
} else {
if (ch_peer == 0) { rv = 1; break; }
if (ch_self == 0) { rv = -1; break; }
}
if (mdev->net_conf->after_sb_0p == ASB_DISCARD_ZERO_CHG)
break;
case ASB_DISCARD_LEAST_CHG:
if (ch_self < ch_peer)
rv = -1;
else if (ch_self > ch_peer)
rv = 1;
else /* ( ch_self == ch_peer ) */
/* Well, then use something else. */
rv = test_bit(DISCARD_CONCURRENT, &mdev->flags)
? -1 : 1;
break;
case ASB_DISCARD_LOCAL:
rv = -1;
break;
case ASB_DISCARD_REMOTE:
rv = 1;
}
return rv;
}
static int drbd_asb_recover_1p(struct drbd_conf *mdev) __must_hold(local)
{
int hg, rv = -100;
switch (mdev->net_conf->after_sb_1p) {
case ASB_DISCARD_YOUNGER_PRI:
case ASB_DISCARD_OLDER_PRI:
case ASB_DISCARD_LEAST_CHG:
case ASB_DISCARD_LOCAL:
case ASB_DISCARD_REMOTE:
dev_err(DEV, "Configuration error.\n");
break;
case ASB_DISCONNECT:
break;
case ASB_CONSENSUS:
hg = drbd_asb_recover_0p(mdev);
if (hg == -1 && mdev->state.role == R_SECONDARY)
rv = hg;
if (hg == 1 && mdev->state.role == R_PRIMARY)
rv = hg;
break;
case ASB_VIOLENTLY:
rv = drbd_asb_recover_0p(mdev);
break;
case ASB_DISCARD_SECONDARY:
return mdev->state.role == R_PRIMARY ? 1 : -1;
case ASB_CALL_HELPER:
hg = drbd_asb_recover_0p(mdev);
if (hg == -1 && mdev->state.role == R_PRIMARY) {
enum drbd_state_rv rv2;
drbd_set_role(mdev, R_SECONDARY, 0);
/* drbd_change_state() does not sleep while in SS_IN_TRANSIENT_STATE,
* we might be here in C_WF_REPORT_PARAMS which is transient.
* we do not need to wait for the after state change work either. */
rv2 = drbd_change_state(mdev, CS_VERBOSE, NS(role, R_SECONDARY));
if (rv2 != SS_SUCCESS) {
drbd_khelper(mdev, "pri-lost-after-sb");
} else {
dev_warn(DEV, "Successfully gave up primary role.\n");
rv = hg;
}
} else
rv = hg;
}
return rv;
}
static int drbd_asb_recover_2p(struct drbd_conf *mdev) __must_hold(local)
{
int hg, rv = -100;
switch (mdev->net_conf->after_sb_2p) {
case ASB_DISCARD_YOUNGER_PRI:
case ASB_DISCARD_OLDER_PRI:
case ASB_DISCARD_LEAST_CHG:
case ASB_DISCARD_LOCAL:
case ASB_DISCARD_REMOTE:
case ASB_CONSENSUS:
case ASB_DISCARD_SECONDARY:
dev_err(DEV, "Configuration error.\n");
break;
case ASB_VIOLENTLY:
rv = drbd_asb_recover_0p(mdev);
break;
case ASB_DISCONNECT:
break;
case ASB_CALL_HELPER:
hg = drbd_asb_recover_0p(mdev);
if (hg == -1) {
enum drbd_state_rv rv2;
/* drbd_change_state() does not sleep while in SS_IN_TRANSIENT_STATE,
* we might be here in C_WF_REPORT_PARAMS which is transient.
* we do not need to wait for the after state change work either. */
rv2 = drbd_change_state(mdev, CS_VERBOSE, NS(role, R_SECONDARY));
if (rv2 != SS_SUCCESS) {
drbd_khelper(mdev, "pri-lost-after-sb");
} else {
dev_warn(DEV, "Successfully gave up primary role.\n");
rv = hg;
}
} else
rv = hg;
}
return rv;
}
static void drbd_uuid_dump(struct drbd_conf *mdev, char *text, u64 *uuid,
u64 bits, u64 flags)
{
if (!uuid) {
dev_info(DEV, "%s uuid info vanished while I was looking!\n", text);
return;
}
dev_info(DEV, "%s %016llX:%016llX:%016llX:%016llX bits:%llu flags:%llX\n",
text,
(unsigned long long)uuid[UI_CURRENT],
(unsigned long long)uuid[UI_BITMAP],
(unsigned long long)uuid[UI_HISTORY_START],
(unsigned long long)uuid[UI_HISTORY_END],
(unsigned long long)bits,
(unsigned long long)flags);
}
/*
100 after split brain try auto recover
2 C_SYNC_SOURCE set BitMap
1 C_SYNC_SOURCE use BitMap
0 no Sync
-1 C_SYNC_TARGET use BitMap
-2 C_SYNC_TARGET set BitMap
-100 after split brain, disconnect
-1000 unrelated data
-1091 requires proto 91
-1096 requires proto 96
*/
static int drbd_uuid_compare(struct drbd_conf *mdev, int *rule_nr) __must_hold(local)
{
u64 self, peer;
int i, j;
self = mdev->ldev->md.uuid[UI_CURRENT] & ~((u64)1);
peer = mdev->p_uuid[UI_CURRENT] & ~((u64)1);
*rule_nr = 10;
if (self == UUID_JUST_CREATED && peer == UUID_JUST_CREATED)
return 0;
*rule_nr = 20;
if ((self == UUID_JUST_CREATED || self == (u64)0) &&
peer != UUID_JUST_CREATED)
return -2;
*rule_nr = 30;
if (self != UUID_JUST_CREATED &&
(peer == UUID_JUST_CREATED || peer == (u64)0))
return 2;
if (self == peer) {
int rct, dc; /* roles at crash time */
if (mdev->p_uuid[UI_BITMAP] == (u64)0 && mdev->ldev->md.uuid[UI_BITMAP] != (u64)0) {
if (mdev->agreed_pro_version < 91)
return -1091;
if ((mdev->ldev->md.uuid[UI_BITMAP] & ~((u64)1)) == (mdev->p_uuid[UI_HISTORY_START] & ~((u64)1)) &&
(mdev->ldev->md.uuid[UI_HISTORY_START] & ~((u64)1)) == (mdev->p_uuid[UI_HISTORY_START + 1] & ~((u64)1))) {
dev_info(DEV, "was SyncSource, missed the resync finished event, corrected myself:\n");
drbd_uuid_set_bm(mdev, 0UL);
drbd_uuid_dump(mdev, "self", mdev->ldev->md.uuid,
mdev->state.disk >= D_NEGOTIATING ? drbd_bm_total_weight(mdev) : 0, 0);
*rule_nr = 34;
} else {
dev_info(DEV, "was SyncSource (peer failed to write sync_uuid)\n");
*rule_nr = 36;
}
return 1;
}
if (mdev->ldev->md.uuid[UI_BITMAP] == (u64)0 && mdev->p_uuid[UI_BITMAP] != (u64)0) {
if (mdev->agreed_pro_version < 91)
return -1091;
if ((mdev->ldev->md.uuid[UI_HISTORY_START] & ~((u64)1)) == (mdev->p_uuid[UI_BITMAP] & ~((u64)1)) &&
(mdev->ldev->md.uuid[UI_HISTORY_START + 1] & ~((u64)1)) == (mdev->p_uuid[UI_HISTORY_START] & ~((u64)1))) {
dev_info(DEV, "was SyncTarget, peer missed the resync finished event, corrected peer:\n");
mdev->p_uuid[UI_HISTORY_START + 1] = mdev->p_uuid[UI_HISTORY_START];
mdev->p_uuid[UI_HISTORY_START] = mdev->p_uuid[UI_BITMAP];
mdev->p_uuid[UI_BITMAP] = 0UL;
drbd_uuid_dump(mdev, "peer", mdev->p_uuid, mdev->p_uuid[UI_SIZE], mdev->p_uuid[UI_FLAGS]);
*rule_nr = 35;
} else {
dev_info(DEV, "was SyncTarget (failed to write sync_uuid)\n");
*rule_nr = 37;
}
return -1;
}
/* Common power [off|failure] */
rct = (test_bit(CRASHED_PRIMARY, &mdev->flags) ? 1 : 0) +
(mdev->p_uuid[UI_FLAGS] & 2);
/* lowest bit is set when we were primary,
* next bit (weight 2) is set when peer was primary */
*rule_nr = 40;
switch (rct) {
case 0: /* !self_pri && !peer_pri */ return 0;
case 1: /* self_pri && !peer_pri */ return 1;
case 2: /* !self_pri && peer_pri */ return -1;
case 3: /* self_pri && peer_pri */
dc = test_bit(DISCARD_CONCURRENT, &mdev->flags);
return dc ? -1 : 1;
}
}
*rule_nr = 50;
peer = mdev->p_uuid[UI_BITMAP] & ~((u64)1);
if (self == peer)
return -1;
*rule_nr = 51;
peer = mdev->p_uuid[UI_HISTORY_START] & ~((u64)1);
if (self == peer) {
if (mdev->agreed_pro_version < 96 ?
(mdev->ldev->md.uuid[UI_HISTORY_START] & ~((u64)1)) ==
(mdev->p_uuid[UI_HISTORY_START + 1] & ~((u64)1)) :
peer + UUID_NEW_BM_OFFSET == (mdev->p_uuid[UI_BITMAP] & ~((u64)1))) {
/* The last P_SYNC_UUID did not get though. Undo the last start of
resync as sync source modifications of the peer's UUIDs. */
if (mdev->agreed_pro_version < 91)
return -1091;
mdev->p_uuid[UI_BITMAP] = mdev->p_uuid[UI_HISTORY_START];
mdev->p_uuid[UI_HISTORY_START] = mdev->p_uuid[UI_HISTORY_START + 1];
dev_info(DEV, "Did not got last syncUUID packet, corrected:\n");
drbd_uuid_dump(mdev, "peer", mdev->p_uuid, mdev->p_uuid[UI_SIZE], mdev->p_uuid[UI_FLAGS]);
return -1;
}
}
*rule_nr = 60;
self = mdev->ldev->md.uuid[UI_CURRENT] & ~((u64)1);
for (i = UI_HISTORY_START; i <= UI_HISTORY_END; i++) {
peer = mdev->p_uuid[i] & ~((u64)1);
if (self == peer)
return -2;
}
*rule_nr = 70;
self = mdev->ldev->md.uuid[UI_BITMAP] & ~((u64)1);
peer = mdev->p_uuid[UI_CURRENT] & ~((u64)1);
if (self == peer)
return 1;
*rule_nr = 71;
self = mdev->ldev->md.uuid[UI_HISTORY_START] & ~((u64)1);
if (self == peer) {
if (mdev->agreed_pro_version < 96 ?
(mdev->ldev->md.uuid[UI_HISTORY_START + 1] & ~((u64)1)) ==
(mdev->p_uuid[UI_HISTORY_START] & ~((u64)1)) :
self + UUID_NEW_BM_OFFSET == (mdev->ldev->md.uuid[UI_BITMAP] & ~((u64)1))) {
/* The last P_SYNC_UUID did not get though. Undo the last start of
resync as sync source modifications of our UUIDs. */
if (mdev->agreed_pro_version < 91)
return -1091;
_drbd_uuid_set(mdev, UI_BITMAP, mdev->ldev->md.uuid[UI_HISTORY_START]);
_drbd_uuid_set(mdev, UI_HISTORY_START, mdev->ldev->md.uuid[UI_HISTORY_START + 1]);
dev_info(DEV, "Last syncUUID did not get through, corrected:\n");
drbd_uuid_dump(mdev, "self", mdev->ldev->md.uuid,
mdev->state.disk >= D_NEGOTIATING ? drbd_bm_total_weight(mdev) : 0, 0);
return 1;
}
}
*rule_nr = 80;
peer = mdev->p_uuid[UI_CURRENT] & ~((u64)1);
for (i = UI_HISTORY_START; i <= UI_HISTORY_END; i++) {
self = mdev->ldev->md.uuid[i] & ~((u64)1);
if (self == peer)
return 2;
}
*rule_nr = 90;
self = mdev->ldev->md.uuid[UI_BITMAP] & ~((u64)1);
peer = mdev->p_uuid[UI_BITMAP] & ~((u64)1);
if (self == peer && self != ((u64)0))
return 100;
*rule_nr = 100;
for (i = UI_HISTORY_START; i <= UI_HISTORY_END; i++) {
self = mdev->ldev->md.uuid[i] & ~((u64)1);
for (j = UI_HISTORY_START; j <= UI_HISTORY_END; j++) {
peer = mdev->p_uuid[j] & ~((u64)1);
if (self == peer)
return -100;
}
}
return -1000;
}
/* drbd_sync_handshake() returns the new conn state on success, or
CONN_MASK (-1) on failure.
*/
static enum drbd_conns drbd_sync_handshake(struct drbd_conf *mdev, enum drbd_role peer_role,
enum drbd_disk_state peer_disk) __must_hold(local)
{
int hg, rule_nr;
enum drbd_conns rv = C_MASK;
enum drbd_disk_state mydisk;
mydisk = mdev->state.disk;
if (mydisk == D_NEGOTIATING)
mydisk = mdev->new_state_tmp.disk;
dev_info(DEV, "drbd_sync_handshake:\n");
drbd_uuid_dump(mdev, "self", mdev->ldev->md.uuid, mdev->comm_bm_set, 0);
drbd_uuid_dump(mdev, "peer", mdev->p_uuid,
mdev->p_uuid[UI_SIZE], mdev->p_uuid[UI_FLAGS]);
hg = drbd_uuid_compare(mdev, &rule_nr);
dev_info(DEV, "uuid_compare()=%d by rule %d\n", hg, rule_nr);
if (hg == -1000) {
dev_alert(DEV, "Unrelated data, aborting!\n");
return C_MASK;
}
if (hg < -1000) {
dev_alert(DEV, "To resolve this both sides have to support at least protocol %d\n", -hg - 1000);
return C_MASK;
}
if ((mydisk == D_INCONSISTENT && peer_disk > D_INCONSISTENT) ||
(peer_disk == D_INCONSISTENT && mydisk > D_INCONSISTENT)) {
int f = (hg == -100) || abs(hg) == 2;
hg = mydisk > D_INCONSISTENT ? 1 : -1;
if (f)
hg = hg*2;
dev_info(DEV, "Becoming sync %s due to disk states.\n",
hg > 0 ? "source" : "target");
}
if (abs(hg) == 100)
drbd_khelper(mdev, "initial-split-brain");
if (hg == 100 || (hg == -100 && mdev->net_conf->always_asbp)) {
int pcount = (mdev->state.role == R_PRIMARY)
+ (peer_role == R_PRIMARY);
int forced = (hg == -100);
switch (pcount) {
case 0:
hg = drbd_asb_recover_0p(mdev);
break;
case 1:
hg = drbd_asb_recover_1p(mdev);
break;
case 2:
hg = drbd_asb_recover_2p(mdev);
break;
}
if (abs(hg) < 100) {
dev_warn(DEV, "Split-Brain detected, %d primaries, "
"automatically solved. Sync from %s node\n",
pcount, (hg < 0) ? "peer" : "this");
if (forced) {
dev_warn(DEV, "Doing a full sync, since"
" UUIDs where ambiguous.\n");
hg = hg*2;
}
}
}
if (hg == -100) {
if (mdev->net_conf->want_lose && !(mdev->p_uuid[UI_FLAGS]&1))
hg = -1;
if (!mdev->net_conf->want_lose && (mdev->p_uuid[UI_FLAGS]&1))
hg = 1;
if (abs(hg) < 100)
dev_warn(DEV, "Split-Brain detected, manually solved. "
"Sync from %s node\n",
(hg < 0) ? "peer" : "this");
}
if (hg == -100) {
/* FIXME this log message is not correct if we end up here
* after an attempted attach on a diskless node.
* We just refuse to attach -- well, we drop the "connection"
* to that disk, in a way... */
dev_alert(DEV, "Split-Brain detected but unresolved, dropping connection!\n");
drbd_khelper(mdev, "split-brain");
return C_MASK;
}
if (hg > 0 && mydisk <= D_INCONSISTENT) {
dev_err(DEV, "I shall become SyncSource, but I am inconsistent!\n");
return C_MASK;
}
if (hg < 0 && /* by intention we do not use mydisk here. */
mdev->state.role == R_PRIMARY && mdev->state.disk >= D_CONSISTENT) {
switch (mdev->net_conf->rr_conflict) {
case ASB_CALL_HELPER:
drbd_khelper(mdev, "pri-lost");
/* fall through */
case ASB_DISCONNECT:
dev_err(DEV, "I shall become SyncTarget, but I am primary!\n");
return C_MASK;
case ASB_VIOLENTLY:
dev_warn(DEV, "Becoming SyncTarget, violating the stable-data"
"assumption\n");
}
}
if (mdev->net_conf->dry_run || test_bit(CONN_DRY_RUN, &mdev->flags)) {
if (hg == 0)
dev_info(DEV, "dry-run connect: No resync, would become Connected immediately.\n");
else
dev_info(DEV, "dry-run connect: Would become %s, doing a %s resync.",
drbd_conn_str(hg > 0 ? C_SYNC_SOURCE : C_SYNC_TARGET),
abs(hg) >= 2 ? "full" : "bit-map based");
return C_MASK;
}
if (abs(hg) >= 2) {
dev_info(DEV, "Writing the whole bitmap, full sync required after drbd_sync_handshake.\n");
if (drbd_bitmap_io(mdev, &drbd_bmio_set_n_write, "set_n_write from sync_handshake",
BM_LOCKED_SET_ALLOWED))
return C_MASK;
}
if (hg > 0) { /* become sync source. */
rv = C_WF_BITMAP_S;
} else if (hg < 0) { /* become sync target */
rv = C_WF_BITMAP_T;
} else {
rv = C_CONNECTED;
if (drbd_bm_total_weight(mdev)) {
dev_info(DEV, "No resync, but %lu bits in bitmap!\n",
drbd_bm_total_weight(mdev));
}
}
return rv;
}
/* returns 1 if invalid */
static int cmp_after_sb(enum drbd_after_sb_p peer, enum drbd_after_sb_p self)
{
/* ASB_DISCARD_REMOTE - ASB_DISCARD_LOCAL is valid */
if ((peer == ASB_DISCARD_REMOTE && self == ASB_DISCARD_LOCAL) ||
(self == ASB_DISCARD_REMOTE && peer == ASB_DISCARD_LOCAL))
return 0;
/* any other things with ASB_DISCARD_REMOTE or ASB_DISCARD_LOCAL are invalid */
if (peer == ASB_DISCARD_REMOTE || peer == ASB_DISCARD_LOCAL ||
self == ASB_DISCARD_REMOTE || self == ASB_DISCARD_LOCAL)
return 1;
/* everything else is valid if they are equal on both sides. */
if (peer == self)
return 0;
/* everything es is invalid. */
return 1;
}
static int receive_protocol(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int data_size)
{
struct p_protocol *p = &mdev->data.rbuf.protocol;
int p_proto, p_after_sb_0p, p_after_sb_1p, p_after_sb_2p;
int p_want_lose, p_two_primaries, cf;
char p_integrity_alg[SHARED_SECRET_MAX] = "";
p_proto = be32_to_cpu(p->protocol);
p_after_sb_0p = be32_to_cpu(p->after_sb_0p);
p_after_sb_1p = be32_to_cpu(p->after_sb_1p);
p_after_sb_2p = be32_to_cpu(p->after_sb_2p);
p_two_primaries = be32_to_cpu(p->two_primaries);
cf = be32_to_cpu(p->conn_flags);
p_want_lose = cf & CF_WANT_LOSE;
clear_bit(CONN_DRY_RUN, &mdev->flags);
if (cf & CF_DRY_RUN)
set_bit(CONN_DRY_RUN, &mdev->flags);
if (p_proto != mdev->net_conf->wire_protocol) {
dev_err(DEV, "incompatible communication protocols\n");
goto disconnect;
}
if (cmp_after_sb(p_after_sb_0p, mdev->net_conf->after_sb_0p)) {
dev_err(DEV, "incompatible after-sb-0pri settings\n");
goto disconnect;
}
if (cmp_after_sb(p_after_sb_1p, mdev->net_conf->after_sb_1p)) {
dev_err(DEV, "incompatible after-sb-1pri settings\n");
goto disconnect;
}
if (cmp_after_sb(p_after_sb_2p, mdev->net_conf->after_sb_2p)) {
dev_err(DEV, "incompatible after-sb-2pri settings\n");
goto disconnect;
}
if (p_want_lose && mdev->net_conf->want_lose) {
dev_err(DEV, "both sides have the 'want_lose' flag set\n");
goto disconnect;
}
if (p_two_primaries != mdev->net_conf->two_primaries) {
dev_err(DEV, "incompatible setting of the two-primaries options\n");
goto disconnect;
}
if (mdev->agreed_pro_version >= 87) {
unsigned char *my_alg = mdev->net_conf->integrity_alg;
if (drbd_recv(mdev, p_integrity_alg, data_size) != data_size)
return false;
p_integrity_alg[SHARED_SECRET_MAX-1] = 0;
if (strcmp(p_integrity_alg, my_alg)) {
dev_err(DEV, "incompatible setting of the data-integrity-alg\n");
goto disconnect;
}
dev_info(DEV, "data-integrity-alg: %s\n",
my_alg[0] ? my_alg : (unsigned char *)"<not-used>");
}
return true;
disconnect:
drbd_force_state(mdev, NS(conn, C_DISCONNECTING));
return false;
}
/* helper function
* input: alg name, feature name
* return: NULL (alg name was "")
* ERR_PTR(error) if something goes wrong
* or the crypto hash ptr, if it worked out ok. */
struct crypto_hash *drbd_crypto_alloc_digest_safe(const struct drbd_conf *mdev,
const char *alg, const char *name)
{
struct crypto_hash *tfm;
if (!alg[0])
return NULL;
tfm = crypto_alloc_hash(alg, 0, CRYPTO_ALG_ASYNC);
if (IS_ERR(tfm)) {
dev_err(DEV, "Can not allocate \"%s\" as %s (reason: %ld)\n",
alg, name, PTR_ERR(tfm));
return tfm;
}
if (!drbd_crypto_is_hash(crypto_hash_tfm(tfm))) {
crypto_free_hash(tfm);
dev_err(DEV, "\"%s\" is not a digest (%s)\n", alg, name);
return ERR_PTR(-EINVAL);
}
return tfm;
}
static int receive_SyncParam(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int packet_size)
{
int ok = true;
struct p_rs_param_95 *p = &mdev->data.rbuf.rs_param_95;
unsigned int header_size, data_size, exp_max_sz;
struct crypto_hash *verify_tfm = NULL;
struct crypto_hash *csums_tfm = NULL;
const int apv = mdev->agreed_pro_version;
int *rs_plan_s = NULL;
int fifo_size = 0;
exp_max_sz = apv <= 87 ? sizeof(struct p_rs_param)
: apv == 88 ? sizeof(struct p_rs_param)
+ SHARED_SECRET_MAX
: apv <= 94 ? sizeof(struct p_rs_param_89)
: /* apv >= 95 */ sizeof(struct p_rs_param_95);
if (packet_size > exp_max_sz) {
dev_err(DEV, "SyncParam packet too long: received %u, expected <= %u bytes\n",
packet_size, exp_max_sz);
return false;
}
if (apv <= 88) {
header_size = sizeof(struct p_rs_param) - sizeof(struct p_header80);
data_size = packet_size - header_size;
} else if (apv <= 94) {
header_size = sizeof(struct p_rs_param_89) - sizeof(struct p_header80);
data_size = packet_size - header_size;
D_ASSERT(data_size == 0);
} else {
header_size = sizeof(struct p_rs_param_95) - sizeof(struct p_header80);
data_size = packet_size - header_size;
D_ASSERT(data_size == 0);
}
/* initialize verify_alg and csums_alg */
memset(p->verify_alg, 0, 2 * SHARED_SECRET_MAX);
if (drbd_recv(mdev, &p->head.payload, header_size) != header_size)
return false;
mdev->sync_conf.rate = be32_to_cpu(p->rate);
if (apv >= 88) {
if (apv == 88) {
if (data_size > SHARED_SECRET_MAX) {
dev_err(DEV, "verify-alg too long, "
"peer wants %u, accepting only %u byte\n",
data_size, SHARED_SECRET_MAX);
return false;
}
if (drbd_recv(mdev, p->verify_alg, data_size) != data_size)
return false;
/* we expect NUL terminated string */
/* but just in case someone tries to be evil */
D_ASSERT(p->verify_alg[data_size-1] == 0);
p->verify_alg[data_size-1] = 0;
} else /* apv >= 89 */ {
/* we still expect NUL terminated strings */
/* but just in case someone tries to be evil */
D_ASSERT(p->verify_alg[SHARED_SECRET_MAX-1] == 0);
D_ASSERT(p->csums_alg[SHARED_SECRET_MAX-1] == 0);
p->verify_alg[SHARED_SECRET_MAX-1] = 0;
p->csums_alg[SHARED_SECRET_MAX-1] = 0;
}
if (strcmp(mdev->sync_conf.verify_alg, p->verify_alg)) {
if (mdev->state.conn == C_WF_REPORT_PARAMS) {
dev_err(DEV, "Different verify-alg settings. me=\"%s\" peer=\"%s\"\n",
mdev->sync_conf.verify_alg, p->verify_alg);
goto disconnect;
}
verify_tfm = drbd_crypto_alloc_digest_safe(mdev,
p->verify_alg, "verify-alg");
if (IS_ERR(verify_tfm)) {
verify_tfm = NULL;
goto disconnect;
}
}
if (apv >= 89 && strcmp(mdev->sync_conf.csums_alg, p->csums_alg)) {
if (mdev->state.conn == C_WF_REPORT_PARAMS) {
dev_err(DEV, "Different csums-alg settings. me=\"%s\" peer=\"%s\"\n",
mdev->sync_conf.csums_alg, p->csums_alg);
goto disconnect;
}
csums_tfm = drbd_crypto_alloc_digest_safe(mdev,
p->csums_alg, "csums-alg");
if (IS_ERR(csums_tfm)) {
csums_tfm = NULL;
goto disconnect;
}
}
if (apv > 94) {
mdev->sync_conf.rate = be32_to_cpu(p->rate);
mdev->sync_conf.c_plan_ahead = be32_to_cpu(p->c_plan_ahead);
mdev->sync_conf.c_delay_target = be32_to_cpu(p->c_delay_target);
mdev->sync_conf.c_fill_target = be32_to_cpu(p->c_fill_target);
mdev->sync_conf.c_max_rate = be32_to_cpu(p->c_max_rate);
fifo_size = (mdev->sync_conf.c_plan_ahead * 10 * SLEEP_TIME) / HZ;
if (fifo_size != mdev->rs_plan_s.size && fifo_size > 0) {
rs_plan_s = kzalloc(sizeof(int) * fifo_size, GFP_KERNEL);
if (!rs_plan_s) {
dev_err(DEV, "kmalloc of fifo_buffer failed");
goto disconnect;
}
}
}
spin_lock(&mdev->peer_seq_lock);
/* lock against drbd_nl_syncer_conf() */
if (verify_tfm) {
strcpy(mdev->sync_conf.verify_alg, p->verify_alg);
mdev->sync_conf.verify_alg_len = strlen(p->verify_alg) + 1;
crypto_free_hash(mdev->verify_tfm);
mdev->verify_tfm = verify_tfm;
dev_info(DEV, "using verify-alg: \"%s\"\n", p->verify_alg);
}
if (csums_tfm) {
strcpy(mdev->sync_conf.csums_alg, p->csums_alg);
mdev->sync_conf.csums_alg_len = strlen(p->csums_alg) + 1;
crypto_free_hash(mdev->csums_tfm);
mdev->csums_tfm = csums_tfm;
dev_info(DEV, "using csums-alg: \"%s\"\n", p->csums_alg);
}
if (fifo_size != mdev->rs_plan_s.size) {
kfree(mdev->rs_plan_s.values);
mdev->rs_plan_s.values = rs_plan_s;
mdev->rs_plan_s.size = fifo_size;
mdev->rs_planed = 0;
}
spin_unlock(&mdev->peer_seq_lock);
}
return ok;
disconnect:
/* just for completeness: actually not needed,
* as this is not reached if csums_tfm was ok. */
crypto_free_hash(csums_tfm);
/* but free the verify_tfm again, if csums_tfm did not work out */
crypto_free_hash(verify_tfm);
drbd_force_state(mdev, NS(conn, C_DISCONNECTING));
return false;
}
/* warn if the arguments differ by more than 12.5% */
static void warn_if_differ_considerably(struct drbd_conf *mdev,
const char *s, sector_t a, sector_t b)
{
sector_t d;
if (a == 0 || b == 0)
return;
d = (a > b) ? (a - b) : (b - a);
if (d > (a>>3) || d > (b>>3))
dev_warn(DEV, "Considerable difference in %s: %llus vs. %llus\n", s,
(unsigned long long)a, (unsigned long long)b);
}
static int receive_sizes(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int data_size)
{
struct p_sizes *p = &mdev->data.rbuf.sizes;
enum determine_dev_size dd = unchanged;
sector_t p_size, p_usize, my_usize;
int ldsc = 0; /* local disk size changed */
enum dds_flags ddsf;
p_size = be64_to_cpu(p->d_size);
p_usize = be64_to_cpu(p->u_size);
if (p_size == 0 && mdev->state.disk == D_DISKLESS) {
dev_err(DEV, "some backing storage is needed\n");
drbd_force_state(mdev, NS(conn, C_DISCONNECTING));
return false;
}
/* just store the peer's disk size for now.
* we still need to figure out whether we accept that. */
mdev->p_size = p_size;
if (get_ldev(mdev)) {
warn_if_differ_considerably(mdev, "lower level device sizes",
p_size, drbd_get_max_capacity(mdev->ldev));
warn_if_differ_considerably(mdev, "user requested size",
p_usize, mdev->ldev->dc.disk_size);
/* if this is the first connect, or an otherwise expected
* param exchange, choose the minimum */
if (mdev->state.conn == C_WF_REPORT_PARAMS)
p_usize = min_not_zero((sector_t)mdev->ldev->dc.disk_size,
p_usize);
my_usize = mdev->ldev->dc.disk_size;
if (mdev->ldev->dc.disk_size != p_usize) {
mdev->ldev->dc.disk_size = p_usize;
dev_info(DEV, "Peer sets u_size to %lu sectors\n",
(unsigned long)mdev->ldev->dc.disk_size);
}
/* Never shrink a device with usable data during connect.
But allow online shrinking if we are connected. */
if (drbd_new_dev_size(mdev, mdev->ldev, 0) <
drbd_get_capacity(mdev->this_bdev) &&
mdev->state.disk >= D_OUTDATED &&
mdev->state.conn < C_CONNECTED) {
dev_err(DEV, "The peer's disk size is too small!\n");
drbd_force_state(mdev, NS(conn, C_DISCONNECTING));
mdev->ldev->dc.disk_size = my_usize;
put_ldev(mdev);
return false;
}
put_ldev(mdev);
}
ddsf = be16_to_cpu(p->dds_flags);
if (get_ldev(mdev)) {
dd = drbd_determine_dev_size(mdev, ddsf);
put_ldev(mdev);
if (dd == dev_size_error)
return false;
drbd_md_sync(mdev);
} else {
/* I am diskless, need to accept the peer's size. */
drbd_set_my_capacity(mdev, p_size);
}
mdev->peer_max_bio_size = be32_to_cpu(p->max_bio_size);
drbd_reconsider_max_bio_size(mdev);
if (get_ldev(mdev)) {
if (mdev->ldev->known_size != drbd_get_capacity(mdev->ldev->backing_bdev)) {
mdev->ldev->known_size = drbd_get_capacity(mdev->ldev->backing_bdev);
ldsc = 1;
}
put_ldev(mdev);
}
if (mdev->state.conn > C_WF_REPORT_PARAMS) {
if (be64_to_cpu(p->c_size) !=
drbd_get_capacity(mdev->this_bdev) || ldsc) {
/* we have different sizes, probably peer
* needs to know my new size... */
drbd_send_sizes(mdev, 0, ddsf);
}
if (test_and_clear_bit(RESIZE_PENDING, &mdev->flags) ||
(dd == grew && mdev->state.conn == C_CONNECTED)) {
if (mdev->state.pdsk >= D_INCONSISTENT &&
mdev->state.disk >= D_INCONSISTENT) {
if (ddsf & DDSF_NO_RESYNC)
dev_info(DEV, "Resync of new storage suppressed with --assume-clean\n");
else
resync_after_online_grow(mdev);
} else
set_bit(RESYNC_AFTER_NEG, &mdev->flags);
}
}
return true;
}
static int receive_uuids(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int data_size)
{
struct p_uuids *p = &mdev->data.rbuf.uuids;
u64 *p_uuid;
int i, updated_uuids = 0;
p_uuid = kmalloc(sizeof(u64)*UI_EXTENDED_SIZE, GFP_NOIO);
for (i = UI_CURRENT; i < UI_EXTENDED_SIZE; i++)
p_uuid[i] = be64_to_cpu(p->uuid[i]);
kfree(mdev->p_uuid);
mdev->p_uuid = p_uuid;
if (mdev->state.conn < C_CONNECTED &&
mdev->state.disk < D_INCONSISTENT &&
mdev->state.role == R_PRIMARY &&
(mdev->ed_uuid & ~((u64)1)) != (p_uuid[UI_CURRENT] & ~((u64)1))) {
dev_err(DEV, "Can only connect to data with current UUID=%016llX\n",
(unsigned long long)mdev->ed_uuid);
drbd_force_state(mdev, NS(conn, C_DISCONNECTING));
return false;
}
if (get_ldev(mdev)) {
int skip_initial_sync =
mdev->state.conn == C_CONNECTED &&
mdev->agreed_pro_version >= 90 &&
mdev->ldev->md.uuid[UI_CURRENT] == UUID_JUST_CREATED &&
(p_uuid[UI_FLAGS] & 8);
if (skip_initial_sync) {
dev_info(DEV, "Accepted new current UUID, preparing to skip initial sync\n");
drbd_bitmap_io(mdev, &drbd_bmio_clear_n_write,
"clear_n_write from receive_uuids",
BM_LOCKED_TEST_ALLOWED);
_drbd_uuid_set(mdev, UI_CURRENT, p_uuid[UI_CURRENT]);
_drbd_uuid_set(mdev, UI_BITMAP, 0);
_drbd_set_state(_NS2(mdev, disk, D_UP_TO_DATE, pdsk, D_UP_TO_DATE),
CS_VERBOSE, NULL);
drbd_md_sync(mdev);
updated_uuids = 1;
}
put_ldev(mdev);
} else if (mdev->state.disk < D_INCONSISTENT &&
mdev->state.role == R_PRIMARY) {
/* I am a diskless primary, the peer just created a new current UUID
for me. */
updated_uuids = drbd_set_ed_uuid(mdev, p_uuid[UI_CURRENT]);
}
/* Before we test for the disk state, we should wait until an eventually
ongoing cluster wide state change is finished. That is important if
we are primary and are detaching from our disk. We need to see the
new disk state... */
wait_event(mdev->misc_wait, !test_bit(CLUSTER_ST_CHANGE, &mdev->flags));
if (mdev->state.conn >= C_CONNECTED && mdev->state.disk < D_INCONSISTENT)
updated_uuids |= drbd_set_ed_uuid(mdev, p_uuid[UI_CURRENT]);
if (updated_uuids)
drbd_print_uuids(mdev, "receiver updated UUIDs to");
return true;
}
/**
* convert_state() - Converts the peer's view of the cluster state to our point of view
* @ps: The state as seen by the peer.
*/
static union drbd_state convert_state(union drbd_state ps)
{
union drbd_state ms;
static enum drbd_conns c_tab[] = {
[C_CONNECTED] = C_CONNECTED,
[C_STARTING_SYNC_S] = C_STARTING_SYNC_T,
[C_STARTING_SYNC_T] = C_STARTING_SYNC_S,
[C_DISCONNECTING] = C_TEAR_DOWN, /* C_NETWORK_FAILURE, */
[C_VERIFY_S] = C_VERIFY_T,
[C_MASK] = C_MASK,
};
ms.i = ps.i;
ms.conn = c_tab[ps.conn];
ms.peer = ps.role;
ms.role = ps.peer;
ms.pdsk = ps.disk;
ms.disk = ps.pdsk;
ms.peer_isp = (ps.aftr_isp | ps.user_isp);
return ms;
}
static int receive_req_state(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int data_size)
{
struct p_req_state *p = &mdev->data.rbuf.req_state;
union drbd_state mask, val;
enum drbd_state_rv rv;
mask.i = be32_to_cpu(p->mask);
val.i = be32_to_cpu(p->val);
if (test_bit(DISCARD_CONCURRENT, &mdev->flags) &&
test_bit(CLUSTER_ST_CHANGE, &mdev->flags)) {
drbd_send_sr_reply(mdev, SS_CONCURRENT_ST_CHG);
return true;
}
mask = convert_state(mask);
val = convert_state(val);
rv = drbd_change_state(mdev, CS_VERBOSE, mask, val);
drbd_send_sr_reply(mdev, rv);
drbd_md_sync(mdev);
return true;
}
static int receive_state(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int data_size)
{
struct p_state *p = &mdev->data.rbuf.state;
union drbd_state os, ns, peer_state;
enum drbd_disk_state real_peer_disk;
enum chg_state_flags cs_flags;
int rv;
peer_state.i = be32_to_cpu(p->state);
real_peer_disk = peer_state.disk;
if (peer_state.disk == D_NEGOTIATING) {
real_peer_disk = mdev->p_uuid[UI_FLAGS] & 4 ? D_INCONSISTENT : D_CONSISTENT;
dev_info(DEV, "real peer disk state = %s\n", drbd_disk_str(real_peer_disk));
}
spin_lock_irq(&mdev->req_lock);
retry:
os = ns = mdev->state;
spin_unlock_irq(&mdev->req_lock);
/* peer says his disk is uptodate, while we think it is inconsistent,
* and this happens while we think we have a sync going on. */
if (os.pdsk == D_INCONSISTENT && real_peer_disk == D_UP_TO_DATE &&
os.conn > C_CONNECTED && os.disk == D_UP_TO_DATE) {
/* If we are (becoming) SyncSource, but peer is still in sync
* preparation, ignore its uptodate-ness to avoid flapping, it
* will change to inconsistent once the peer reaches active
* syncing states.
* It may have changed syncer-paused flags, however, so we
* cannot ignore this completely. */
if (peer_state.conn > C_CONNECTED &&
peer_state.conn < C_SYNC_SOURCE)
real_peer_disk = D_INCONSISTENT;
/* if peer_state changes to connected at the same time,
* it explicitly notifies us that it finished resync.
* Maybe we should finish it up, too? */
else if (os.conn >= C_SYNC_SOURCE &&
peer_state.conn == C_CONNECTED) {
if (drbd_bm_total_weight(mdev) <= mdev->rs_failed)
drbd_resync_finished(mdev);
return true;
}
}
/* peer says his disk is inconsistent, while we think it is uptodate,
* and this happens while the peer still thinks we have a sync going on,
* but we think we are already done with the sync.
* We ignore this to avoid flapping pdsk.
* This should not happen, if the peer is a recent version of drbd. */
if (os.pdsk == D_UP_TO_DATE && real_peer_disk == D_INCONSISTENT &&
os.conn == C_CONNECTED && peer_state.conn > C_SYNC_SOURCE)
real_peer_disk = D_UP_TO_DATE;
if (ns.conn == C_WF_REPORT_PARAMS)
ns.conn = C_CONNECTED;
if (peer_state.conn == C_AHEAD)
ns.conn = C_BEHIND;
if (mdev->p_uuid && peer_state.disk >= D_NEGOTIATING &&
get_ldev_if_state(mdev, D_NEGOTIATING)) {
int cr; /* consider resync */
/* if we established a new connection */
cr = (os.conn < C_CONNECTED);
/* if we had an established connection
* and one of the nodes newly attaches a disk */
cr |= (os.conn == C_CONNECTED &&
(peer_state.disk == D_NEGOTIATING ||
os.disk == D_NEGOTIATING));
/* if we have both been inconsistent, and the peer has been
* forced to be UpToDate with --overwrite-data */
cr |= test_bit(CONSIDER_RESYNC, &mdev->flags);
/* if we had been plain connected, and the admin requested to
* start a sync by "invalidate" or "invalidate-remote" */
cr |= (os.conn == C_CONNECTED &&
(peer_state.conn >= C_STARTING_SYNC_S &&
peer_state.conn <= C_WF_BITMAP_T));
if (cr)
ns.conn = drbd_sync_handshake(mdev, peer_state.role, real_peer_disk);
put_ldev(mdev);
if (ns.conn == C_MASK) {
ns.conn = C_CONNECTED;
if (mdev->state.disk == D_NEGOTIATING) {
drbd_force_state(mdev, NS(disk, D_FAILED));
} else if (peer_state.disk == D_NEGOTIATING) {
dev_err(DEV, "Disk attach process on the peer node was aborted.\n");
peer_state.disk = D_DISKLESS;
real_peer_disk = D_DISKLESS;
} else {
if (test_and_clear_bit(CONN_DRY_RUN, &mdev->flags))
return false;
D_ASSERT(os.conn == C_WF_REPORT_PARAMS);
drbd_force_state(mdev, NS(conn, C_DISCONNECTING));
return false;
}
}
}
spin_lock_irq(&mdev->req_lock);
if (mdev->state.i != os.i)
goto retry;
clear_bit(CONSIDER_RESYNC, &mdev->flags);
ns.peer = peer_state.role;
ns.pdsk = real_peer_disk;
ns.peer_isp = (peer_state.aftr_isp | peer_state.user_isp);
if ((ns.conn == C_CONNECTED || ns.conn == C_WF_BITMAP_S) && ns.disk == D_NEGOTIATING)
ns.disk = mdev->new_state_tmp.disk;
cs_flags = CS_VERBOSE + (os.conn < C_CONNECTED && ns.conn >= C_CONNECTED ? 0 : CS_HARD);
if (ns.pdsk == D_CONSISTENT && is_susp(ns) && ns.conn == C_CONNECTED && os.conn < C_CONNECTED &&
test_bit(NEW_CUR_UUID, &mdev->flags)) {
/* Do not allow tl_restart(resend) for a rebooted peer. We can only allow this
for temporal network outages! */
spin_unlock_irq(&mdev->req_lock);
dev_err(DEV, "Aborting Connect, can not thaw IO with an only Consistent peer\n");
tl_clear(mdev);
drbd_uuid_new_current(mdev);
clear_bit(NEW_CUR_UUID, &mdev->flags);
drbd_force_state(mdev, NS2(conn, C_PROTOCOL_ERROR, susp, 0));
return false;
}
rv = _drbd_set_state(mdev, ns, cs_flags, NULL);
ns = mdev->state;
spin_unlock_irq(&mdev->req_lock);
if (rv < SS_SUCCESS) {
drbd_force_state(mdev, NS(conn, C_DISCONNECTING));
return false;
}
if (os.conn > C_WF_REPORT_PARAMS) {
if (ns.conn > C_CONNECTED && peer_state.conn <= C_CONNECTED &&
peer_state.disk != D_NEGOTIATING ) {
/* we want resync, peer has not yet decided to sync... */
/* Nowadays only used when forcing a node into primary role and
setting its disk to UpToDate with that */
drbd_send_uuids(mdev);
drbd_send_state(mdev);
}
}
mdev->net_conf->want_lose = 0;
drbd_md_sync(mdev); /* update connected indicator, la_size, ... */
return true;
}
static int receive_sync_uuid(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int data_size)
{
struct p_rs_uuid *p = &mdev->data.rbuf.rs_uuid;
wait_event(mdev->misc_wait,
mdev->state.conn == C_WF_SYNC_UUID ||
mdev->state.conn == C_BEHIND ||
mdev->state.conn < C_CONNECTED ||
mdev->state.disk < D_NEGOTIATING);
/* D_ASSERT( mdev->state.conn == C_WF_SYNC_UUID ); */
/* Here the _drbd_uuid_ functions are right, current should
_not_ be rotated into the history */
if (get_ldev_if_state(mdev, D_NEGOTIATING)) {
_drbd_uuid_set(mdev, UI_CURRENT, be64_to_cpu(p->uuid));
_drbd_uuid_set(mdev, UI_BITMAP, 0UL);
drbd_print_uuids(mdev, "updated sync uuid");
drbd_start_resync(mdev, C_SYNC_TARGET);
put_ldev(mdev);
} else
dev_err(DEV, "Ignoring SyncUUID packet!\n");
return true;
}
/**
* receive_bitmap_plain
*
* Return 0 when done, 1 when another iteration is needed, and a negative error
* code upon failure.
*/
static int
receive_bitmap_plain(struct drbd_conf *mdev, unsigned int data_size,
unsigned long *buffer, struct bm_xfer_ctx *c)
{
unsigned num_words = min_t(size_t, BM_PACKET_WORDS, c->bm_words - c->word_offset);
unsigned want = num_words * sizeof(long);
int err;
if (want != data_size) {
dev_err(DEV, "%s:want (%u) != data_size (%u)\n", __func__, want, data_size);
return -EIO;
}
if (want == 0)
return 0;
err = drbd_recv(mdev, buffer, want);
if (err != want) {
if (err >= 0)
err = -EIO;
return err;
}
drbd_bm_merge_lel(mdev, c->word_offset, num_words, buffer);
c->word_offset += num_words;
c->bit_offset = c->word_offset * BITS_PER_LONG;
if (c->bit_offset > c->bm_bits)
c->bit_offset = c->bm_bits;
return 1;
}
/**
* recv_bm_rle_bits
*
* Return 0 when done, 1 when another iteration is needed, and a negative error
* code upon failure.
*/
static int
recv_bm_rle_bits(struct drbd_conf *mdev,
struct p_compressed_bm *p,
struct bm_xfer_ctx *c)
{
struct bitstream bs;
u64 look_ahead;
u64 rl;
u64 tmp;
unsigned long s = c->bit_offset;
unsigned long e;
int len = be16_to_cpu(p->head.length) - (sizeof(*p) - sizeof(p->head));
int toggle = DCBP_get_start(p);
int have;
int bits;
bitstream_init(&bs, p->code, len, DCBP_get_pad_bits(p));
bits = bitstream_get_bits(&bs, &look_ahead, 64);
if (bits < 0)
return -EIO;
for (have = bits; have > 0; s += rl, toggle = !toggle) {
bits = vli_decode_bits(&rl, look_ahead);
if (bits <= 0)
return -EIO;
if (toggle) {
e = s + rl -1;
if (e >= c->bm_bits) {
dev_err(DEV, "bitmap overflow (e:%lu) while decoding bm RLE packet\n", e);
return -EIO;
}
_drbd_bm_set_bits(mdev, s, e);
}
if (have < bits) {
dev_err(DEV, "bitmap decoding error: h:%d b:%d la:0x%08llx l:%u/%u\n",
have, bits, look_ahead,
(unsigned int)(bs.cur.b - p->code),
(unsigned int)bs.buf_len);
return -EIO;
}
look_ahead >>= bits;
have -= bits;
bits = bitstream_get_bits(&bs, &tmp, 64 - have);
if (bits < 0)
return -EIO;
look_ahead |= tmp << have;
have += bits;
}
c->bit_offset = s;
bm_xfer_ctx_bit_to_word_offset(c);
return (s != c->bm_bits);
}
/**
* decode_bitmap_c
*
* Return 0 when done, 1 when another iteration is needed, and a negative error
* code upon failure.
*/
static int
decode_bitmap_c(struct drbd_conf *mdev,
struct p_compressed_bm *p,
struct bm_xfer_ctx *c)
{
if (DCBP_get_code(p) == RLE_VLI_Bits)
return recv_bm_rle_bits(mdev, p, c);
/* other variants had been implemented for evaluation,
* but have been dropped as this one turned out to be "best"
* during all our tests. */
dev_err(DEV, "receive_bitmap_c: unknown encoding %u\n", p->encoding);
drbd_force_state(mdev, NS(conn, C_PROTOCOL_ERROR));
return -EIO;
}
void INFO_bm_xfer_stats(struct drbd_conf *mdev,
const char *direction, struct bm_xfer_ctx *c)
{
/* what would it take to transfer it "plaintext" */
unsigned plain = sizeof(struct p_header80) *
((c->bm_words+BM_PACKET_WORDS-1)/BM_PACKET_WORDS+1)
+ c->bm_words * sizeof(long);
unsigned total = c->bytes[0] + c->bytes[1];
unsigned r;
/* total can not be zero. but just in case: */
if (total == 0)
return;
/* don't report if not compressed */
if (total >= plain)
return;
/* total < plain. check for overflow, still */
r = (total > UINT_MAX/1000) ? (total / (plain/1000))
: (1000 * total / plain);
if (r > 1000)
r = 1000;
r = 1000 - r;
dev_info(DEV, "%s bitmap stats [Bytes(packets)]: plain %u(%u), RLE %u(%u), "
"total %u; compression: %u.%u%%\n",
direction,
c->bytes[1], c->packets[1],
c->bytes[0], c->packets[0],
total, r/10, r % 10);
}
/* Since we are processing the bitfield from lower addresses to higher,
it does not matter if the process it in 32 bit chunks or 64 bit
chunks as long as it is little endian. (Understand it as byte stream,
beginning with the lowest byte...) If we would use big endian
we would need to process it from the highest address to the lowest,
in order to be agnostic to the 32 vs 64 bits issue.
returns 0 on failure, 1 if we successfully received it. */
static int receive_bitmap(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int data_size)
{
struct bm_xfer_ctx c;
void *buffer;
int err;
int ok = false;
struct p_header80 *h = &mdev->data.rbuf.header.h80;
drbd_bm_lock(mdev, "receive bitmap", BM_LOCKED_SET_ALLOWED);
/* you are supposed to send additional out-of-sync information
* if you actually set bits during this phase */
/* maybe we should use some per thread scratch page,
* and allocate that during initial device creation? */
buffer = (unsigned long *) __get_free_page(GFP_NOIO);
if (!buffer) {
dev_err(DEV, "failed to allocate one page buffer in %s\n", __func__);
goto out;
}
c = (struct bm_xfer_ctx) {
.bm_bits = drbd_bm_bits(mdev),
.bm_words = drbd_bm_words(mdev),
};
for(;;) {
if (cmd == P_BITMAP) {
err = receive_bitmap_plain(mdev, data_size, buffer, &c);
} else if (cmd == P_COMPRESSED_BITMAP) {
/* MAYBE: sanity check that we speak proto >= 90,
* and the feature is enabled! */
struct p_compressed_bm *p;
if (data_size > BM_PACKET_PAYLOAD_BYTES) {
dev_err(DEV, "ReportCBitmap packet too large\n");
goto out;
}
/* use the page buff */
p = buffer;
memcpy(p, h, sizeof(*h));
if (drbd_recv(mdev, p->head.payload, data_size) != data_size)
goto out;
if (data_size <= (sizeof(*p) - sizeof(p->head))) {
dev_err(DEV, "ReportCBitmap packet too small (l:%u)\n", data_size);
goto out;
}
err = decode_bitmap_c(mdev, p, &c);
} else {
dev_warn(DEV, "receive_bitmap: cmd neither ReportBitMap nor ReportCBitMap (is 0x%x)", cmd);
goto out;
}
c.packets[cmd == P_BITMAP]++;
c.bytes[cmd == P_BITMAP] += sizeof(struct p_header80) + data_size;
if (err <= 0) {
if (err < 0)
goto out;
break;
}
if (!drbd_recv_header(mdev, &cmd, &data_size))
goto out;
}
INFO_bm_xfer_stats(mdev, "receive", &c);
if (mdev->state.conn == C_WF_BITMAP_T) {
enum drbd_state_rv rv;
ok = !drbd_send_bitmap(mdev);
if (!ok)
goto out;
/* Omit CS_ORDERED with this state transition to avoid deadlocks. */
rv = _drbd_request_state(mdev, NS(conn, C_WF_SYNC_UUID), CS_VERBOSE);
D_ASSERT(rv == SS_SUCCESS);
} else if (mdev->state.conn != C_WF_BITMAP_S) {
/* admin may have requested C_DISCONNECTING,
* other threads may have noticed network errors */
dev_info(DEV, "unexpected cstate (%s) in receive_bitmap\n",
drbd_conn_str(mdev->state.conn));
}
ok = true;
out:
drbd_bm_unlock(mdev);
if (ok && mdev->state.conn == C_WF_BITMAP_S)
drbd_start_resync(mdev, C_SYNC_SOURCE);
free_page((unsigned long) buffer);
return ok;
}
static int receive_skip(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int data_size)
{
/* TODO zero copy sink :) */
static char sink[128];
int size, want, r;
dev_warn(DEV, "skipping unknown optional packet type %d, l: %d!\n",
cmd, data_size);
size = data_size;
while (size > 0) {
want = min_t(int, size, sizeof(sink));
r = drbd_recv(mdev, sink, want);
ERR_IF(r <= 0) break;
size -= r;
}
return size == 0;
}
static int receive_UnplugRemote(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int data_size)
{
/* Make sure we've acked all the TCP data associated
* with the data requests being unplugged */
drbd_tcp_quickack(mdev->data.socket);
return true;
}
static int receive_out_of_sync(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int data_size)
{
struct p_block_desc *p = &mdev->data.rbuf.block_desc;
switch (mdev->state.conn) {
case C_WF_SYNC_UUID:
case C_WF_BITMAP_T:
case C_BEHIND:
break;
default:
dev_err(DEV, "ASSERT FAILED cstate = %s, expected: WFSyncUUID|WFBitMapT|Behind\n",
drbd_conn_str(mdev->state.conn));
}
drbd_set_out_of_sync(mdev, be64_to_cpu(p->sector), be32_to_cpu(p->blksize));
return true;
}
typedef int (*drbd_cmd_handler_f)(struct drbd_conf *, enum drbd_packets cmd, unsigned int to_receive);
struct data_cmd {
int expect_payload;
size_t pkt_size;
drbd_cmd_handler_f function;
};
static struct data_cmd drbd_cmd_handler[] = {
[P_DATA] = { 1, sizeof(struct p_data), receive_Data },
[P_DATA_REPLY] = { 1, sizeof(struct p_data), receive_DataReply },
[P_RS_DATA_REPLY] = { 1, sizeof(struct p_data), receive_RSDataReply } ,
[P_BARRIER] = { 0, sizeof(struct p_barrier), receive_Barrier } ,
[P_BITMAP] = { 1, sizeof(struct p_header80), receive_bitmap } ,
[P_COMPRESSED_BITMAP] = { 1, sizeof(struct p_header80), receive_bitmap } ,
[P_UNPLUG_REMOTE] = { 0, sizeof(struct p_header80), receive_UnplugRemote },
[P_DATA_REQUEST] = { 0, sizeof(struct p_block_req), receive_DataRequest },
[P_RS_DATA_REQUEST] = { 0, sizeof(struct p_block_req), receive_DataRequest },
[P_SYNC_PARAM] = { 1, sizeof(struct p_header80), receive_SyncParam },
[P_SYNC_PARAM89] = { 1, sizeof(struct p_header80), receive_SyncParam },
[P_PROTOCOL] = { 1, sizeof(struct p_protocol), receive_protocol },
[P_UUIDS] = { 0, sizeof(struct p_uuids), receive_uuids },
[P_SIZES] = { 0, sizeof(struct p_sizes), receive_sizes },
[P_STATE] = { 0, sizeof(struct p_state), receive_state },
[P_STATE_CHG_REQ] = { 0, sizeof(struct p_req_state), receive_req_state },
[P_SYNC_UUID] = { 0, sizeof(struct p_rs_uuid), receive_sync_uuid },
[P_OV_REQUEST] = { 0, sizeof(struct p_block_req), receive_DataRequest },
[P_OV_REPLY] = { 1, sizeof(struct p_block_req), receive_DataRequest },
[P_CSUM_RS_REQUEST] = { 1, sizeof(struct p_block_req), receive_DataRequest },
[P_DELAY_PROBE] = { 0, sizeof(struct p_delay_probe93), receive_skip },
[P_OUT_OF_SYNC] = { 0, sizeof(struct p_block_desc), receive_out_of_sync },
/* anything missing from this table is in
* the asender_tbl, see get_asender_cmd */
[P_MAX_CMD] = { 0, 0, NULL },
};
/* All handler functions that expect a sub-header get that sub-heder in
mdev->data.rbuf.header.head.payload.
Usually in mdev->data.rbuf.header.head the callback can find the usual
p_header, but they may not rely on that. Since there is also p_header95 !
*/
static void drbdd(struct drbd_conf *mdev)
{
union p_header *header = &mdev->data.rbuf.header;
unsigned int packet_size;
enum drbd_packets cmd;
size_t shs; /* sub header size */
int rv;
while (get_t_state(&mdev->receiver) == Running) {
drbd_thread_current_set_cpu(mdev);
if (!drbd_recv_header(mdev, &cmd, &packet_size))
goto err_out;
if (unlikely(cmd >= P_MAX_CMD || !drbd_cmd_handler[cmd].function)) {
dev_err(DEV, "unknown packet type %d, l: %d!\n", cmd, packet_size);
goto err_out;
}
shs = drbd_cmd_handler[cmd].pkt_size - sizeof(union p_header);
if (packet_size - shs > 0 && !drbd_cmd_handler[cmd].expect_payload) {
dev_err(DEV, "No payload expected %s l:%d\n", cmdname(cmd), packet_size);
goto err_out;
}
if (shs) {
rv = drbd_recv(mdev, &header->h80.payload, shs);
if (unlikely(rv != shs)) {
if (!signal_pending(current))
dev_warn(DEV, "short read while reading sub header: rv=%d\n", rv);
goto err_out;
}
}
rv = drbd_cmd_handler[cmd].function(mdev, cmd, packet_size - shs);
if (unlikely(!rv)) {
dev_err(DEV, "error receiving %s, l: %d!\n",
cmdname(cmd), packet_size);
goto err_out;
}
}
if (0) {
err_out:
drbd_force_state(mdev, NS(conn, C_PROTOCOL_ERROR));
}
/* If we leave here, we probably want to update at least the
* "Connected" indicator on stable storage. Do so explicitly here. */
drbd_md_sync(mdev);
}
void drbd_flush_workqueue(struct drbd_conf *mdev)
{
struct drbd_wq_barrier barr;
barr.w.cb = w_prev_work_done;
init_completion(&barr.done);
drbd_queue_work(&mdev->data.work, &barr.w);
wait_for_completion(&barr.done);
}
void drbd_free_tl_hash(struct drbd_conf *mdev)
{
struct hlist_head *h;
spin_lock_irq(&mdev->req_lock);
if (!mdev->tl_hash || mdev->state.conn != C_STANDALONE) {
spin_unlock_irq(&mdev->req_lock);
return;
}
/* paranoia code */
for (h = mdev->ee_hash; h < mdev->ee_hash + mdev->ee_hash_s; h++)
if (h->first)
dev_err(DEV, "ASSERT FAILED ee_hash[%u].first == %p, expected NULL\n",
(int)(h - mdev->ee_hash), h->first);
kfree(mdev->ee_hash);
mdev->ee_hash = NULL;
mdev->ee_hash_s = 0;
/* paranoia code */
for (h = mdev->tl_hash; h < mdev->tl_hash + mdev->tl_hash_s; h++)
if (h->first)
dev_err(DEV, "ASSERT FAILED tl_hash[%u] == %p, expected NULL\n",
(int)(h - mdev->tl_hash), h->first);
kfree(mdev->tl_hash);
mdev->tl_hash = NULL;
mdev->tl_hash_s = 0;
spin_unlock_irq(&mdev->req_lock);
}
static void drbd_disconnect(struct drbd_conf *mdev)
{
enum drbd_fencing_p fp;
union drbd_state os, ns;
int rv = SS_UNKNOWN_ERROR;
unsigned int i;
if (mdev->state.conn == C_STANDALONE)
return;
/* asender does not clean up anything. it must not interfere, either */
drbd_thread_stop(&mdev->asender);
drbd_free_sock(mdev);
/* wait for current activity to cease. */
spin_lock_irq(&mdev->req_lock);
_drbd_wait_ee_list_empty(mdev, &mdev->active_ee);
_drbd_wait_ee_list_empty(mdev, &mdev->sync_ee);
_drbd_wait_ee_list_empty(mdev, &mdev->read_ee);
spin_unlock_irq(&mdev->req_lock);
/* We do not have data structures that would allow us to
* get the rs_pending_cnt down to 0 again.
* * On C_SYNC_TARGET we do not have any data structures describing
* the pending RSDataRequest's we have sent.
* * On C_SYNC_SOURCE there is no data structure that tracks
* the P_RS_DATA_REPLY blocks that we sent to the SyncTarget.
* And no, it is not the sum of the reference counts in the
* resync_LRU. The resync_LRU tracks the whole operation including
* the disk-IO, while the rs_pending_cnt only tracks the blocks
* on the fly. */
drbd_rs_cancel_all(mdev);
mdev->rs_total = 0;
mdev->rs_failed = 0;
atomic_set(&mdev->rs_pending_cnt, 0);
wake_up(&mdev->misc_wait);
del_timer(&mdev->request_timer);
/* make sure syncer is stopped and w_resume_next_sg queued */
del_timer_sync(&mdev->resync_timer);
resync_timer_fn((unsigned long)mdev);
/* wait for all w_e_end_data_req, w_e_end_rsdata_req, w_send_barrier,
* w_make_resync_request etc. which may still be on the worker queue
* to be "canceled" */
drbd_flush_workqueue(mdev);
/* This also does reclaim_net_ee(). If we do this too early, we might
* miss some resync ee and pages.*/
drbd_process_done_ee(mdev);
kfree(mdev->p_uuid);
mdev->p_uuid = NULL;
if (!is_susp(mdev->state))
tl_clear(mdev);
dev_info(DEV, "Connection closed\n");
drbd_md_sync(mdev);
fp = FP_DONT_CARE;
if (get_ldev(mdev)) {
fp = mdev->ldev->dc.fencing;
put_ldev(mdev);
}
if (mdev->state.role == R_PRIMARY && fp >= FP_RESOURCE && mdev->state.pdsk >= D_UNKNOWN)
drbd_try_outdate_peer_async(mdev);
spin_lock_irq(&mdev->req_lock);
os = mdev->state;
if (os.conn >= C_UNCONNECTED) {
/* Do not restart in case we are C_DISCONNECTING */
ns = os;
ns.conn = C_UNCONNECTED;
rv = _drbd_set_state(mdev, ns, CS_VERBOSE, NULL);
}
spin_unlock_irq(&mdev->req_lock);
if (os.conn == C_DISCONNECTING) {
wait_event(mdev->net_cnt_wait, atomic_read(&mdev->net_cnt) == 0);
crypto_free_hash(mdev->cram_hmac_tfm);
mdev->cram_hmac_tfm = NULL;
kfree(mdev->net_conf);
mdev->net_conf = NULL;
drbd_request_state(mdev, NS(conn, C_STANDALONE));
}
/* serialize with bitmap writeout triggered by the state change,
* if any. */
wait_event(mdev->misc_wait, !test_bit(BITMAP_IO, &mdev->flags));
/* tcp_close and release of sendpage pages can be deferred. I don't
* want to use SO_LINGER, because apparently it can be deferred for
* more than 20 seconds (longest time I checked).
*
* Actually we don't care for exactly when the network stack does its
* put_page(), but release our reference on these pages right here.
*/
i = drbd_release_ee(mdev, &mdev->net_ee);
if (i)
dev_info(DEV, "net_ee not empty, killed %u entries\n", i);
i = atomic_read(&mdev->pp_in_use_by_net);
if (i)
dev_info(DEV, "pp_in_use_by_net = %d, expected 0\n", i);
i = atomic_read(&mdev->pp_in_use);
if (i)
dev_info(DEV, "pp_in_use = %d, expected 0\n", i);
D_ASSERT(list_empty(&mdev->read_ee));
D_ASSERT(list_empty(&mdev->active_ee));
D_ASSERT(list_empty(&mdev->sync_ee));
D_ASSERT(list_empty(&mdev->done_ee));
/* ok, no more ee's on the fly, it is safe to reset the epoch_size */
atomic_set(&mdev->current_epoch->epoch_size, 0);
D_ASSERT(list_empty(&mdev->current_epoch->list));
}
/*
* We support PRO_VERSION_MIN to PRO_VERSION_MAX. The protocol version
* we can agree on is stored in agreed_pro_version.
*
* feature flags and the reserved array should be enough room for future
* enhancements of the handshake protocol, and possible plugins...
*
* for now, they are expected to be zero, but ignored.
*/
static int drbd_send_handshake(struct drbd_conf *mdev)
{
/* ASSERT current == mdev->receiver ... */
struct p_handshake *p = &mdev->data.sbuf.handshake;
int ok;
if (mutex_lock_interruptible(&mdev->data.mutex)) {
dev_err(DEV, "interrupted during initial handshake\n");
return 0; /* interrupted. not ok. */
}
if (mdev->data.socket == NULL) {
mutex_unlock(&mdev->data.mutex);
return 0;
}
memset(p, 0, sizeof(*p));
p->protocol_min = cpu_to_be32(PRO_VERSION_MIN);
p->protocol_max = cpu_to_be32(PRO_VERSION_MAX);
ok = _drbd_send_cmd( mdev, mdev->data.socket, P_HAND_SHAKE,
(struct p_header80 *)p, sizeof(*p), 0 );
mutex_unlock(&mdev->data.mutex);
return ok;
}
/*
* return values:
* 1 yes, we have a valid connection
* 0 oops, did not work out, please try again
* -1 peer talks different language,
* no point in trying again, please go standalone.
*/
static int drbd_do_handshake(struct drbd_conf *mdev)
{
/* ASSERT current == mdev->receiver ... */
struct p_handshake *p = &mdev->data.rbuf.handshake;
const int expect = sizeof(struct p_handshake) - sizeof(struct p_header80);
unsigned int length;
enum drbd_packets cmd;
int rv;
rv = drbd_send_handshake(mdev);
if (!rv)
return 0;
rv = drbd_recv_header(mdev, &cmd, &length);
if (!rv)
return 0;
if (cmd != P_HAND_SHAKE) {
dev_err(DEV, "expected HandShake packet, received: %s (0x%04x)\n",
cmdname(cmd), cmd);
return -1;
}
if (length != expect) {
dev_err(DEV, "expected HandShake length: %u, received: %u\n",
expect, length);
return -1;
}
rv = drbd_recv(mdev, &p->head.payload, expect);
if (rv != expect) {
if (!signal_pending(current))
dev_warn(DEV, "short read receiving handshake packet: l=%u\n", rv);
return 0;
}
p->protocol_min = be32_to_cpu(p->protocol_min);
p->protocol_max = be32_to_cpu(p->protocol_max);
if (p->protocol_max == 0)
p->protocol_max = p->protocol_min;
if (PRO_VERSION_MAX < p->protocol_min ||
PRO_VERSION_MIN > p->protocol_max)
goto incompat;
mdev->agreed_pro_version = min_t(int, PRO_VERSION_MAX, p->protocol_max);
dev_info(DEV, "Handshake successful: "
"Agreed network protocol version %d\n", mdev->agreed_pro_version);
return 1;
incompat:
dev_err(DEV, "incompatible DRBD dialects: "
"I support %d-%d, peer supports %d-%d\n",
PRO_VERSION_MIN, PRO_VERSION_MAX,
p->protocol_min, p->protocol_max);
return -1;
}
#if !defined(CONFIG_CRYPTO_HMAC) && !defined(CONFIG_CRYPTO_HMAC_MODULE)
static int drbd_do_auth(struct drbd_conf *mdev)
{
dev_err(DEV, "This kernel was build without CONFIG_CRYPTO_HMAC.\n");
dev_err(DEV, "You need to disable 'cram-hmac-alg' in drbd.conf.\n");
return -1;
}
#else
#define CHALLENGE_LEN 64
/* Return value:
1 - auth succeeded,
0 - failed, try again (network error),
-1 - auth failed, don't try again.
*/
static int drbd_do_auth(struct drbd_conf *mdev)
{
char my_challenge[CHALLENGE_LEN]; /* 64 Bytes... */
struct scatterlist sg;
char *response = NULL;
char *right_response = NULL;
char *peers_ch = NULL;
unsigned int key_len = strlen(mdev->net_conf->shared_secret);
unsigned int resp_size;
struct hash_desc desc;
enum drbd_packets cmd;
unsigned int length;
int rv;
desc.tfm = mdev->cram_hmac_tfm;
desc.flags = 0;
rv = crypto_hash_setkey(mdev->cram_hmac_tfm,
(u8 *)mdev->net_conf->shared_secret, key_len);
if (rv) {
dev_err(DEV, "crypto_hash_setkey() failed with %d\n", rv);
rv = -1;
goto fail;
}
get_random_bytes(my_challenge, CHALLENGE_LEN);
rv = drbd_send_cmd2(mdev, P_AUTH_CHALLENGE, my_challenge, CHALLENGE_LEN);
if (!rv)
goto fail;
rv = drbd_recv_header(mdev, &cmd, &length);
if (!rv)
goto fail;
if (cmd != P_AUTH_CHALLENGE) {
dev_err(DEV, "expected AuthChallenge packet, received: %s (0x%04x)\n",
cmdname(cmd), cmd);
rv = 0;
goto fail;
}
if (length > CHALLENGE_LEN * 2) {
dev_err(DEV, "expected AuthChallenge payload too big.\n");
rv = -1;
goto fail;
}
peers_ch = kmalloc(length, GFP_NOIO);
if (peers_ch == NULL) {
dev_err(DEV, "kmalloc of peers_ch failed\n");
rv = -1;
goto fail;
}
rv = drbd_recv(mdev, peers_ch, length);
if (rv != length) {
if (!signal_pending(current))
dev_warn(DEV, "short read AuthChallenge: l=%u\n", rv);
rv = 0;
goto fail;
}
resp_size = crypto_hash_digestsize(mdev->cram_hmac_tfm);
response = kmalloc(resp_size, GFP_NOIO);
if (response == NULL) {
dev_err(DEV, "kmalloc of response failed\n");
rv = -1;
goto fail;
}
sg_init_table(&sg, 1);
sg_set_buf(&sg, peers_ch, length);
rv = crypto_hash_digest(&desc, &sg, sg.length, response);
if (rv) {
dev_err(DEV, "crypto_hash_digest() failed with %d\n", rv);
rv = -1;
goto fail;
}
rv = drbd_send_cmd2(mdev, P_AUTH_RESPONSE, response, resp_size);
if (!rv)
goto fail;
rv = drbd_recv_header(mdev, &cmd, &length);
if (!rv)
goto fail;
if (cmd != P_AUTH_RESPONSE) {
dev_err(DEV, "expected AuthResponse packet, received: %s (0x%04x)\n",
cmdname(cmd), cmd);
rv = 0;
goto fail;
}
if (length != resp_size) {
dev_err(DEV, "expected AuthResponse payload of wrong size\n");
rv = 0;
goto fail;
}
rv = drbd_recv(mdev, response , resp_size);
if (rv != resp_size) {
if (!signal_pending(current))
dev_warn(DEV, "short read receiving AuthResponse: l=%u\n", rv);
rv = 0;
goto fail;
}
right_response = kmalloc(resp_size, GFP_NOIO);
if (right_response == NULL) {
dev_err(DEV, "kmalloc of right_response failed\n");
rv = -1;
goto fail;
}
sg_set_buf(&sg, my_challenge, CHALLENGE_LEN);
rv = crypto_hash_digest(&desc, &sg, sg.length, right_response);
if (rv) {
dev_err(DEV, "crypto_hash_digest() failed with %d\n", rv);
rv = -1;
goto fail;
}
rv = !memcmp(response, right_response, resp_size);
if (rv)
dev_info(DEV, "Peer authenticated using %d bytes of '%s' HMAC\n",
resp_size, mdev->net_conf->cram_hmac_alg);
else
rv = -1;
fail:
kfree(peers_ch);
kfree(response);
kfree(right_response);
return rv;
}
#endif
int drbdd_init(struct drbd_thread *thi)
{
struct drbd_conf *mdev = thi->mdev;
unsigned int minor = mdev_to_minor(mdev);
int h;
sprintf(current->comm, "drbd%d_receiver", minor);
dev_info(DEV, "receiver (re)started\n");
do {
h = drbd_connect(mdev);
if (h == 0) {
drbd_disconnect(mdev);
schedule_timeout_interruptible(HZ);
}
if (h == -1) {
dev_warn(DEV, "Discarding network configuration.\n");
drbd_force_state(mdev, NS(conn, C_DISCONNECTING));
}
} while (h == 0);
if (h > 0) {
if (get_net_conf(mdev)) {
drbdd(mdev);
put_net_conf(mdev);
}
}
drbd_disconnect(mdev);
dev_info(DEV, "receiver terminated\n");
return 0;
}
/* ********* acknowledge sender ******** */
static int got_RqSReply(struct drbd_conf *mdev, struct p_header80 *h)
{
struct p_req_state_reply *p = (struct p_req_state_reply *)h;
int retcode = be32_to_cpu(p->retcode);
if (retcode >= SS_SUCCESS) {
set_bit(CL_ST_CHG_SUCCESS, &mdev->flags);
} else {
set_bit(CL_ST_CHG_FAIL, &mdev->flags);
dev_err(DEV, "Requested state change failed by peer: %s (%d)\n",
drbd_set_st_err_str(retcode), retcode);
}
wake_up(&mdev->state_wait);
return true;
}
static int got_Ping(struct drbd_conf *mdev, struct p_header80 *h)
{
return drbd_send_ping_ack(mdev);
}
static int got_PingAck(struct drbd_conf *mdev, struct p_header80 *h)
{
/* restore idle timeout */
mdev->meta.socket->sk->sk_rcvtimeo = mdev->net_conf->ping_int*HZ;
if (!test_and_set_bit(GOT_PING_ACK, &mdev->flags))
wake_up(&mdev->misc_wait);
return true;
}
static int got_IsInSync(struct drbd_conf *mdev, struct p_header80 *h)
{
struct p_block_ack *p = (struct p_block_ack *)h;
sector_t sector = be64_to_cpu(p->sector);
int blksize = be32_to_cpu(p->blksize);
D_ASSERT(mdev->agreed_pro_version >= 89);
update_peer_seq(mdev, be32_to_cpu(p->seq_num));
if (get_ldev(mdev)) {
drbd_rs_complete_io(mdev, sector);
drbd_set_in_sync(mdev, sector, blksize);
/* rs_same_csums is supposed to count in units of BM_BLOCK_SIZE */
mdev->rs_same_csum += (blksize >> BM_BLOCK_SHIFT);
put_ldev(mdev);
}
dec_rs_pending(mdev);
atomic_add(blksize >> 9, &mdev->rs_sect_in);
return true;
}
/* when we receive the ACK for a write request,
* verify that we actually know about it */
static struct drbd_request *_ack_id_to_req(struct drbd_conf *mdev,
u64 id, sector_t sector)
{
struct hlist_head *slot = tl_hash_slot(mdev, sector);
struct hlist_node *n;
struct drbd_request *req;
hlist_for_each_entry(req, n, slot, collision) {
if ((unsigned long)req == (unsigned long)id) {
if (req->sector != sector) {
dev_err(DEV, "_ack_id_to_req: found req %p but it has "
"wrong sector (%llus versus %llus)\n", req,
(unsigned long long)req->sector,
(unsigned long long)sector);
break;
}
return req;
}
}
return NULL;
}
typedef struct drbd_request *(req_validator_fn)
(struct drbd_conf *mdev, u64 id, sector_t sector);
static int validate_req_change_req_state(struct drbd_conf *mdev,
u64 id, sector_t sector, req_validator_fn validator,
const char *func, enum drbd_req_event what)
{
struct drbd_request *req;
struct bio_and_error m;
spin_lock_irq(&mdev->req_lock);
req = validator(mdev, id, sector);
if (unlikely(!req)) {
spin_unlock_irq(&mdev->req_lock);
dev_err(DEV, "%s: failed to find req %p, sector %llus\n", func,
(void *)(unsigned long)id, (unsigned long long)sector);
return false;
}
__req_mod(req, what, &m);
spin_unlock_irq(&mdev->req_lock);
if (m.bio)
complete_master_bio(mdev, &m);
return true;
}
static int got_BlockAck(struct drbd_conf *mdev, struct p_header80 *h)
{
struct p_block_ack *p = (struct p_block_ack *)h;
sector_t sector = be64_to_cpu(p->sector);
int blksize = be32_to_cpu(p->blksize);
enum drbd_req_event what;
update_peer_seq(mdev, be32_to_cpu(p->seq_num));
if (is_syncer_block_id(p->block_id)) {
drbd_set_in_sync(mdev, sector, blksize);
dec_rs_pending(mdev);
return true;
}
switch (be16_to_cpu(h->command)) {
case P_RS_WRITE_ACK:
D_ASSERT(mdev->net_conf->wire_protocol == DRBD_PROT_C);
what = write_acked_by_peer_and_sis;
break;
case P_WRITE_ACK:
D_ASSERT(mdev->net_conf->wire_protocol == DRBD_PROT_C);
what = write_acked_by_peer;
break;
case P_RECV_ACK:
D_ASSERT(mdev->net_conf->wire_protocol == DRBD_PROT_B);
what = recv_acked_by_peer;
break;
case P_DISCARD_ACK:
D_ASSERT(mdev->net_conf->wire_protocol == DRBD_PROT_C);
what = conflict_discarded_by_peer;
break;
default:
D_ASSERT(0);
return false;
}
return validate_req_change_req_state(mdev, p->block_id, sector,
_ack_id_to_req, __func__ , what);
}
static int got_NegAck(struct drbd_conf *mdev, struct p_header80 *h)
{
struct p_block_ack *p = (struct p_block_ack *)h;
sector_t sector = be64_to_cpu(p->sector);
int size = be32_to_cpu(p->blksize);
struct drbd_request *req;
struct bio_and_error m;
update_peer_seq(mdev, be32_to_cpu(p->seq_num));
if (is_syncer_block_id(p->block_id)) {
dec_rs_pending(mdev);
drbd_rs_failed_io(mdev, sector, size);
return true;
}
spin_lock_irq(&mdev->req_lock);
req = _ack_id_to_req(mdev, p->block_id, sector);
if (!req) {
spin_unlock_irq(&mdev->req_lock);
if (mdev->net_conf->wire_protocol == DRBD_PROT_A ||
mdev->net_conf->wire_protocol == DRBD_PROT_B) {
/* Protocol A has no P_WRITE_ACKs, but has P_NEG_ACKs.
The master bio might already be completed, therefore the
request is no longer in the collision hash.
=> Do not try to validate block_id as request. */
/* In Protocol B we might already have got a P_RECV_ACK
but then get a P_NEG_ACK after wards. */
drbd_set_out_of_sync(mdev, sector, size);
return true;
} else {
dev_err(DEV, "%s: failed to find req %p, sector %llus\n", __func__,
(void *)(unsigned long)p->block_id, (unsigned long long)sector);
return false;
}
}
__req_mod(req, neg_acked, &m);
spin_unlock_irq(&mdev->req_lock);
if (m.bio)
complete_master_bio(mdev, &m);
return true;
}
static int got_NegDReply(struct drbd_conf *mdev, struct p_header80 *h)
{
struct p_block_ack *p = (struct p_block_ack *)h;
sector_t sector = be64_to_cpu(p->sector);
update_peer_seq(mdev, be32_to_cpu(p->seq_num));
dev_err(DEV, "Got NegDReply; Sector %llus, len %u; Fail original request.\n",
(unsigned long long)sector, be32_to_cpu(p->blksize));
return validate_req_change_req_state(mdev, p->block_id, sector,
_ar_id_to_req, __func__ , neg_acked);
}
static int got_NegRSDReply(struct drbd_conf *mdev, struct p_header80 *h)
{
sector_t sector;
int size;
struct p_block_ack *p = (struct p_block_ack *)h;
sector = be64_to_cpu(p->sector);
size = be32_to_cpu(p->blksize);
update_peer_seq(mdev, be32_to_cpu(p->seq_num));
dec_rs_pending(mdev);
if (get_ldev_if_state(mdev, D_FAILED)) {
drbd_rs_complete_io(mdev, sector);
switch (be16_to_cpu(h->command)) {
case P_NEG_RS_DREPLY:
drbd_rs_failed_io(mdev, sector, size);
case P_RS_CANCEL:
break;
default:
D_ASSERT(0);
put_ldev(mdev);
return false;
}
put_ldev(mdev);
}
return true;
}
static int got_BarrierAck(struct drbd_conf *mdev, struct p_header80 *h)
{
struct p_barrier_ack *p = (struct p_barrier_ack *)h;
tl_release(mdev, p->barrier, be32_to_cpu(p->set_size));
if (mdev->state.conn == C_AHEAD &&
atomic_read(&mdev->ap_in_flight) == 0 &&
!test_and_set_bit(AHEAD_TO_SYNC_SOURCE, &mdev->current_epoch->flags)) {
mdev->start_resync_timer.expires = jiffies + HZ;
add_timer(&mdev->start_resync_timer);
}
return true;
}
static int got_OVResult(struct drbd_conf *mdev, struct p_header80 *h)
{
struct p_block_ack *p = (struct p_block_ack *)h;
struct drbd_work *w;
sector_t sector;
int size;
sector = be64_to_cpu(p->sector);
size = be32_to_cpu(p->blksize);
update_peer_seq(mdev, be32_to_cpu(p->seq_num));
if (be64_to_cpu(p->block_id) == ID_OUT_OF_SYNC)
drbd_ov_oos_found(mdev, sector, size);
else
ov_oos_print(mdev);
if (!get_ldev(mdev))
return true;
drbd_rs_complete_io(mdev, sector);
dec_rs_pending(mdev);
--mdev->ov_left;
/* let's advance progress step marks only for every other megabyte */
if ((mdev->ov_left & 0x200) == 0x200)
drbd_advance_rs_marks(mdev, mdev->ov_left);
if (mdev->ov_left == 0) {
w = kmalloc(sizeof(*w), GFP_NOIO);
if (w) {
w->cb = w_ov_finished;
drbd_queue_work_front(&mdev->data.work, w);
} else {
dev_err(DEV, "kmalloc(w) failed.");
ov_oos_print(mdev);
drbd_resync_finished(mdev);
}
}
put_ldev(mdev);
return true;
}
static int got_skip(struct drbd_conf *mdev, struct p_header80 *h)
{
return true;
}
struct asender_cmd {
size_t pkt_size;
int (*process)(struct drbd_conf *mdev, struct p_header80 *h);
};
static struct asender_cmd *get_asender_cmd(int cmd)
{
static struct asender_cmd asender_tbl[] = {
/* anything missing from this table is in
* the drbd_cmd_handler (drbd_default_handler) table,
* see the beginning of drbdd() */
[P_PING] = { sizeof(struct p_header80), got_Ping },
[P_PING_ACK] = { sizeof(struct p_header80), got_PingAck },
[P_RECV_ACK] = { sizeof(struct p_block_ack), got_BlockAck },
[P_WRITE_ACK] = { sizeof(struct p_block_ack), got_BlockAck },
[P_RS_WRITE_ACK] = { sizeof(struct p_block_ack), got_BlockAck },
[P_DISCARD_ACK] = { sizeof(struct p_block_ack), got_BlockAck },
[P_NEG_ACK] = { sizeof(struct p_block_ack), got_NegAck },
[P_NEG_DREPLY] = { sizeof(struct p_block_ack), got_NegDReply },
[P_NEG_RS_DREPLY] = { sizeof(struct p_block_ack), got_NegRSDReply},
[P_OV_RESULT] = { sizeof(struct p_block_ack), got_OVResult },
[P_BARRIER_ACK] = { sizeof(struct p_barrier_ack), got_BarrierAck },
[P_STATE_CHG_REPLY] = { sizeof(struct p_req_state_reply), got_RqSReply },
[P_RS_IS_IN_SYNC] = { sizeof(struct p_block_ack), got_IsInSync },
[P_DELAY_PROBE] = { sizeof(struct p_delay_probe93), got_skip },
[P_RS_CANCEL] = { sizeof(struct p_block_ack), got_NegRSDReply},
[P_MAX_CMD] = { 0, NULL },
};
if (cmd > P_MAX_CMD || asender_tbl[cmd].process == NULL)
return NULL;
return &asender_tbl[cmd];
}
int drbd_asender(struct drbd_thread *thi)
{
struct drbd_conf *mdev = thi->mdev;
struct p_header80 *h = &mdev->meta.rbuf.header.h80;
struct asender_cmd *cmd = NULL;
int rv, len;
void *buf = h;
int received = 0;
int expect = sizeof(struct p_header80);
int empty;
int ping_timeout_active = 0;
sprintf(current->comm, "drbd%d_asender", mdev_to_minor(mdev));
current->policy = SCHED_RR; /* Make this a realtime task! */
current->rt_priority = 2; /* more important than all other tasks */
while (get_t_state(thi) == Running) {
drbd_thread_current_set_cpu(mdev);
if (test_and_clear_bit(SEND_PING, &mdev->flags)) {
ERR_IF(!drbd_send_ping(mdev)) goto reconnect;
mdev->meta.socket->sk->sk_rcvtimeo =
mdev->net_conf->ping_timeo*HZ/10;
ping_timeout_active = 1;
}
/* conditionally cork;
* it may hurt latency if we cork without much to send */
if (!mdev->net_conf->no_cork &&
3 < atomic_read(&mdev->unacked_cnt))
drbd_tcp_cork(mdev->meta.socket);
while (1) {
clear_bit(SIGNAL_ASENDER, &mdev->flags);
flush_signals(current);
if (!drbd_process_done_ee(mdev))
goto reconnect;
/* to avoid race with newly queued ACKs */
set_bit(SIGNAL_ASENDER, &mdev->flags);
spin_lock_irq(&mdev->req_lock);
empty = list_empty(&mdev->done_ee);
spin_unlock_irq(&mdev->req_lock);
/* new ack may have been queued right here,
* but then there is also a signal pending,
* and we start over... */
if (empty)
break;
}
/* but unconditionally uncork unless disabled */
if (!mdev->net_conf->no_cork)
drbd_tcp_uncork(mdev->meta.socket);
/* short circuit, recv_msg would return EINTR anyways. */
if (signal_pending(current))
continue;
rv = drbd_recv_short(mdev, mdev->meta.socket,
buf, expect-received, 0);
clear_bit(SIGNAL_ASENDER, &mdev->flags);
flush_signals(current);
/* Note:
* -EINTR (on meta) we got a signal
* -EAGAIN (on meta) rcvtimeo expired
* -ECONNRESET other side closed the connection
* -ERESTARTSYS (on data) we got a signal
* rv < 0 other than above: unexpected error!
* rv == expected: full header or command
* rv < expected: "woken" by signal during receive
* rv == 0 : "connection shut down by peer"
*/
if (likely(rv > 0)) {
received += rv;
buf += rv;
} else if (rv == 0) {
dev_err(DEV, "meta connection shut down by peer.\n");
goto reconnect;
} else if (rv == -EAGAIN) {
/* If the data socket received something meanwhile,
* that is good enough: peer is still alive. */
if (time_after(mdev->last_received,
jiffies - mdev->meta.socket->sk->sk_rcvtimeo))
continue;
if (ping_timeout_active) {
dev_err(DEV, "PingAck did not arrive in time.\n");
goto reconnect;
}
set_bit(SEND_PING, &mdev->flags);
continue;
} else if (rv == -EINTR) {
continue;
} else {
dev_err(DEV, "sock_recvmsg returned %d\n", rv);
goto reconnect;
}
if (received == expect && cmd == NULL) {
if (unlikely(h->magic != BE_DRBD_MAGIC)) {
dev_err(DEV, "magic?? on meta m: 0x%08x c: %d l: %d\n",
be32_to_cpu(h->magic),
be16_to_cpu(h->command),
be16_to_cpu(h->length));
goto reconnect;
}
cmd = get_asender_cmd(be16_to_cpu(h->command));
len = be16_to_cpu(h->length);
if (unlikely(cmd == NULL)) {
dev_err(DEV, "unknown command?? on meta m: 0x%08x c: %d l: %d\n",
be32_to_cpu(h->magic),
be16_to_cpu(h->command),
be16_to_cpu(h->length));
goto disconnect;
}
expect = cmd->pkt_size;
ERR_IF(len != expect-sizeof(struct p_header80))
goto reconnect;
}
if (received == expect) {
mdev->last_received = jiffies;
D_ASSERT(cmd != NULL);
if (!cmd->process(mdev, h))
goto reconnect;
/* the idle_timeout (ping-int)
* has been restored in got_PingAck() */
if (cmd == get_asender_cmd(P_PING_ACK))
ping_timeout_active = 0;
buf = h;
received = 0;
expect = sizeof(struct p_header80);
cmd = NULL;
}
}
if (0) {
reconnect:
drbd_force_state(mdev, NS(conn, C_NETWORK_FAILURE));
drbd_md_sync(mdev);
}
if (0) {
disconnect:
drbd_force_state(mdev, NS(conn, C_DISCONNECTING));
drbd_md_sync(mdev);
}
clear_bit(SIGNAL_ASENDER, &mdev->flags);
D_ASSERT(mdev->state.conn < C_CONNECTED);
dev_info(DEV, "asender terminated\n");
return 0;
}
| gpl-2.0 |
1DeMaCr/android_kernel_samsung_codina | arch/mips/jz4740/reset.c | 7775 | 1852 | /*
* Copyright (C) 2010, Lars-Peter Clausen <lars@metafoo.de>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* 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/io.h>
#include <linux/kernel.h>
#include <linux/pm.h>
#include <asm/reboot.h>
#include <asm/mach-jz4740/base.h>
#include <asm/mach-jz4740/timer.h>
static void jz4740_halt(void)
{
while (1) {
__asm__(".set push;\n"
".set mips3;\n"
"wait;\n"
".set pop;\n"
);
}
}
#define JZ_REG_WDT_DATA 0x00
#define JZ_REG_WDT_COUNTER_ENABLE 0x04
#define JZ_REG_WDT_COUNTER 0x08
#define JZ_REG_WDT_CTRL 0x0c
static void jz4740_restart(char *command)
{
void __iomem *wdt_base = ioremap(JZ4740_WDT_BASE_ADDR, 0x0f);
jz4740_timer_enable_watchdog();
writeb(0, wdt_base + JZ_REG_WDT_COUNTER_ENABLE);
writew(0, wdt_base + JZ_REG_WDT_COUNTER);
writew(0, wdt_base + JZ_REG_WDT_DATA);
writew(BIT(2), wdt_base + JZ_REG_WDT_CTRL);
writeb(1, wdt_base + JZ_REG_WDT_COUNTER_ENABLE);
jz4740_halt();
}
#define JZ_REG_RTC_CTRL 0x00
#define JZ_REG_RTC_HIBERNATE 0x20
#define JZ_RTC_CTRL_WRDY BIT(7)
static void jz4740_power_off(void)
{
void __iomem *rtc_base = ioremap(JZ4740_RTC_BASE_ADDR, 0x24);
uint32_t ctrl;
do {
ctrl = readl(rtc_base + JZ_REG_RTC_CTRL);
} while (!(ctrl & JZ_RTC_CTRL_WRDY));
writel(1, rtc_base + JZ_REG_RTC_HIBERNATE);
jz4740_halt();
}
void jz4740_reset_init(void)
{
_machine_restart = jz4740_restart;
_machine_halt = jz4740_halt;
pm_power_off = jz4740_power_off;
}
| gpl-2.0 |
xenius9/d838_kernel | crypto/twofish_generic.c | 8031 | 6450 | /*
* Twofish for CryptoAPI
*
* Originally Twofish for GPG
* By Matthew Skala <mskala@ansuz.sooke.bc.ca>, July 26, 1998
* 256-bit key length added March 20, 1999
* Some modifications to reduce the text size by Werner Koch, April, 1998
* Ported to the kerneli patch by Marc Mutz <Marc@Mutz.com>
* Ported to CryptoAPI by Colin Slater <hoho@tacomeat.net>
*
* The original author has disclaimed all copyright interest in this
* code and thus put it in the public domain. The subsequent authors
* have put this under the GNU General Public License.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* This code is a "clean room" implementation, written from the paper
* _Twofish: A 128-Bit Block Cipher_ by Bruce Schneier, John Kelsey,
* Doug Whiting, David Wagner, Chris Hall, and Niels Ferguson, available
* through http://www.counterpane.com/twofish.html
*
* For background information on multiplication in finite fields, used for
* the matrix operations in the key schedule, see the book _Contemporary
* Abstract Algebra_ by Joseph A. Gallian, especially chapter 22 in the
* Third Edition.
*/
#include <asm/byteorder.h>
#include <crypto/twofish.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/crypto.h>
#include <linux/bitops.h>
/* Macros to compute the g() function in the encryption and decryption
* rounds. G1 is the straight g() function; G2 includes the 8-bit
* rotation for the high 32-bit word. */
#define G1(a) \
(ctx->s[0][(a) & 0xFF]) ^ (ctx->s[1][((a) >> 8) & 0xFF]) \
^ (ctx->s[2][((a) >> 16) & 0xFF]) ^ (ctx->s[3][(a) >> 24])
#define G2(b) \
(ctx->s[1][(b) & 0xFF]) ^ (ctx->s[2][((b) >> 8) & 0xFF]) \
^ (ctx->s[3][((b) >> 16) & 0xFF]) ^ (ctx->s[0][(b) >> 24])
/* Encryption and decryption Feistel rounds. Each one calls the two g()
* macros, does the PHT, and performs the XOR and the appropriate bit
* rotations. The parameters are the round number (used to select subkeys),
* and the four 32-bit chunks of the text. */
#define ENCROUND(n, a, b, c, d) \
x = G1 (a); y = G2 (b); \
x += y; y += x + ctx->k[2 * (n) + 1]; \
(c) ^= x + ctx->k[2 * (n)]; \
(c) = ror32((c), 1); \
(d) = rol32((d), 1) ^ y
#define DECROUND(n, a, b, c, d) \
x = G1 (a); y = G2 (b); \
x += y; y += x; \
(d) ^= y + ctx->k[2 * (n) + 1]; \
(d) = ror32((d), 1); \
(c) = rol32((c), 1); \
(c) ^= (x + ctx->k[2 * (n)])
/* Encryption and decryption cycles; each one is simply two Feistel rounds
* with the 32-bit chunks re-ordered to simulate the "swap" */
#define ENCCYCLE(n) \
ENCROUND (2 * (n), a, b, c, d); \
ENCROUND (2 * (n) + 1, c, d, a, b)
#define DECCYCLE(n) \
DECROUND (2 * (n) + 1, c, d, a, b); \
DECROUND (2 * (n), a, b, c, d)
/* Macros to convert the input and output bytes into 32-bit words,
* and simultaneously perform the whitening step. INPACK packs word
* number n into the variable named by x, using whitening subkey number m.
* OUTUNPACK unpacks word number n from the variable named by x, using
* whitening subkey number m. */
#define INPACK(n, x, m) \
x = le32_to_cpu(src[n]) ^ ctx->w[m]
#define OUTUNPACK(n, x, m) \
x ^= ctx->w[m]; \
dst[n] = cpu_to_le32(x)
/* Encrypt one block. in and out may be the same. */
static void twofish_encrypt(struct crypto_tfm *tfm, u8 *out, const u8 *in)
{
struct twofish_ctx *ctx = crypto_tfm_ctx(tfm);
const __le32 *src = (const __le32 *)in;
__le32 *dst = (__le32 *)out;
/* The four 32-bit chunks of the text. */
u32 a, b, c, d;
/* Temporaries used by the round function. */
u32 x, y;
/* Input whitening and packing. */
INPACK (0, a, 0);
INPACK (1, b, 1);
INPACK (2, c, 2);
INPACK (3, d, 3);
/* Encryption Feistel cycles. */
ENCCYCLE (0);
ENCCYCLE (1);
ENCCYCLE (2);
ENCCYCLE (3);
ENCCYCLE (4);
ENCCYCLE (5);
ENCCYCLE (6);
ENCCYCLE (7);
/* Output whitening and unpacking. */
OUTUNPACK (0, c, 4);
OUTUNPACK (1, d, 5);
OUTUNPACK (2, a, 6);
OUTUNPACK (3, b, 7);
}
/* Decrypt one block. in and out may be the same. */
static void twofish_decrypt(struct crypto_tfm *tfm, u8 *out, const u8 *in)
{
struct twofish_ctx *ctx = crypto_tfm_ctx(tfm);
const __le32 *src = (const __le32 *)in;
__le32 *dst = (__le32 *)out;
/* The four 32-bit chunks of the text. */
u32 a, b, c, d;
/* Temporaries used by the round function. */
u32 x, y;
/* Input whitening and packing. */
INPACK (0, c, 4);
INPACK (1, d, 5);
INPACK (2, a, 6);
INPACK (3, b, 7);
/* Encryption Feistel cycles. */
DECCYCLE (7);
DECCYCLE (6);
DECCYCLE (5);
DECCYCLE (4);
DECCYCLE (3);
DECCYCLE (2);
DECCYCLE (1);
DECCYCLE (0);
/* Output whitening and unpacking. */
OUTUNPACK (0, a, 0);
OUTUNPACK (1, b, 1);
OUTUNPACK (2, c, 2);
OUTUNPACK (3, d, 3);
}
static struct crypto_alg alg = {
.cra_name = "twofish",
.cra_driver_name = "twofish-generic",
.cra_priority = 100,
.cra_flags = CRYPTO_ALG_TYPE_CIPHER,
.cra_blocksize = TF_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct twofish_ctx),
.cra_alignmask = 3,
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(alg.cra_list),
.cra_u = { .cipher = {
.cia_min_keysize = TF_MIN_KEY_SIZE,
.cia_max_keysize = TF_MAX_KEY_SIZE,
.cia_setkey = twofish_setkey,
.cia_encrypt = twofish_encrypt,
.cia_decrypt = twofish_decrypt } }
};
static int __init twofish_mod_init(void)
{
return crypto_register_alg(&alg);
}
static void __exit twofish_mod_fini(void)
{
crypto_unregister_alg(&alg);
}
module_init(twofish_mod_init);
module_exit(twofish_mod_fini);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION ("Twofish Cipher Algorithm");
MODULE_ALIAS("twofish");
| gpl-2.0 |
DirtyUnicorns/android_kernel_samsung_manta | arch/c6x/kernel/module.c | 9311 | 3257 | /*
* Port on Texas Instruments TMS320C6x architecture
*
* Copyright (C) 2005, 2009, 2010, 2011 Texas Instruments Incorporated
* Author: Thomas Charleux (thomas.charleux@jaluna.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/moduleloader.h>
#include <linux/elf.h>
#include <linux/vmalloc.h>
#include <linux/kernel.h>
static inline int fixup_pcr(u32 *ip, Elf32_Addr dest, u32 maskbits, int shift)
{
u32 opcode;
long ep = (long)ip & ~31;
long delta = ((long)dest - ep) >> 2;
long mask = (1 << maskbits) - 1;
if ((delta >> (maskbits - 1)) == 0 ||
(delta >> (maskbits - 1)) == -1) {
opcode = *ip;
opcode &= ~(mask << shift);
opcode |= ((delta & mask) << shift);
*ip = opcode;
pr_debug("REL PCR_S%d[%p] dest[%p] opcode[%08x]\n",
maskbits, ip, (void *)dest, opcode);
return 0;
}
pr_err("PCR_S%d reloc %p -> %p out of range!\n",
maskbits, ip, (void *)dest);
return -1;
}
/*
* apply a RELA relocation
*/
int apply_relocate_add(Elf32_Shdr *sechdrs,
const char *strtab,
unsigned int symindex,
unsigned int relsec,
struct module *me)
{
Elf32_Rela *rel = (void *) sechdrs[relsec].sh_addr;
Elf_Sym *sym;
u32 *location, opcode;
unsigned int i;
Elf32_Addr v;
Elf_Addr offset = 0;
pr_debug("Applying relocate section %u to %u with offset 0x%x\n",
relsec, sechdrs[relsec].sh_info, offset);
for (i = 0; i < sechdrs[relsec].sh_size / sizeof(*rel); i++) {
/* This is where to make the change */
location = (void *)sechdrs[sechdrs[relsec].sh_info].sh_addr
+ rel[i].r_offset - offset;
/* This is the symbol it is referring to. Note that all
undefined symbols have been resolved. */
sym = (Elf_Sym *)sechdrs[symindex].sh_addr
+ ELF32_R_SYM(rel[i].r_info);
/* this is the adjustment to be made */
v = sym->st_value + rel[i].r_addend;
switch (ELF32_R_TYPE(rel[i].r_info)) {
case R_C6000_ABS32:
pr_debug("RELA ABS32: [%p] = 0x%x\n", location, v);
*location = v;
break;
case R_C6000_ABS16:
pr_debug("RELA ABS16: [%p] = 0x%x\n", location, v);
*(u16 *)location = v;
break;
case R_C6000_ABS8:
pr_debug("RELA ABS8: [%p] = 0x%x\n", location, v);
*(u8 *)location = v;
break;
case R_C6000_ABS_L16:
opcode = *location;
opcode &= ~0x7fff80;
opcode |= ((v & 0xffff) << 7);
pr_debug("RELA ABS_L16[%p] v[0x%x] opcode[0x%x]\n",
location, v, opcode);
*location = opcode;
break;
case R_C6000_ABS_H16:
opcode = *location;
opcode &= ~0x7fff80;
opcode |= ((v >> 9) & 0x7fff80);
pr_debug("RELA ABS_H16[%p] v[0x%x] opcode[0x%x]\n",
location, v, opcode);
*location = opcode;
break;
case R_C6000_PCR_S21:
if (fixup_pcr(location, v, 21, 7))
return -ENOEXEC;
break;
case R_C6000_PCR_S12:
if (fixup_pcr(location, v, 12, 16))
return -ENOEXEC;
break;
case R_C6000_PCR_S10:
if (fixup_pcr(location, v, 10, 13))
return -ENOEXEC;
break;
default:
pr_err("module %s: Unknown RELA relocation: %u\n",
me->name, ELF32_R_TYPE(rel[i].r_info));
return -ENOEXEC;
}
}
return 0;
}
| gpl-2.0 |
Dee-UK/RK3288_Lollipop_Kernel | arch/c6x/platforms/emif.c | 9311 | 2004 | /*
* External Memory Interface
*
* Copyright (C) 2011 Texas Instruments Incorporated
* Author: Mark Salter <msalter@redhat.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/of.h>
#include <linux/of_address.h>
#include <linux/io.h>
#include <asm/soc.h>
#include <asm/dscr.h>
#define NUM_EMIFA_CHIP_ENABLES 4
struct emifa_regs {
u32 midr;
u32 stat;
u32 reserved1[6];
u32 bprio;
u32 reserved2[23];
u32 cecfg[NUM_EMIFA_CHIP_ENABLES];
u32 reserved3[4];
u32 awcc;
u32 reserved4[7];
u32 intraw;
u32 intmsk;
u32 intmskset;
u32 intmskclr;
};
static struct of_device_id emifa_match[] __initdata = {
{ .compatible = "ti,c64x+emifa" },
{}
};
/*
* Parse device tree for existence of an EMIF (External Memory Interface)
* and initialize it if found.
*/
static int __init c6x_emifa_init(void)
{
struct emifa_regs __iomem *regs;
struct device_node *node;
const __be32 *p;
u32 val;
int i, len, err;
node = of_find_matching_node(NULL, emifa_match);
if (!node)
return 0;
regs = of_iomap(node, 0);
if (!regs)
return 0;
/* look for a dscr-based enable for emifa pin buffers */
err = of_property_read_u32_array(node, "ti,dscr-dev-enable", &val, 1);
if (!err)
dscr_set_devstate(val, DSCR_DEVSTATE_ENABLED);
/* set up the chip enables */
p = of_get_property(node, "ti,emifa-ce-config", &len);
if (p) {
len /= sizeof(u32);
if (len > NUM_EMIFA_CHIP_ENABLES)
len = NUM_EMIFA_CHIP_ENABLES;
for (i = 0; i <= len; i++)
soc_writel(be32_to_cpup(&p[i]), ®s->cecfg[i]);
}
err = of_property_read_u32_array(node, "ti,emifa-burst-priority", &val, 1);
if (!err)
soc_writel(val, ®s->bprio);
err = of_property_read_u32_array(node, "ti,emifa-async-wait-control", &val, 1);
if (!err)
soc_writel(val, ®s->awcc);
iounmap(regs);
of_node_put(node);
return 0;
}
pure_initcall(c6x_emifa_init);
| gpl-2.0 |
akw28888/n909 | drivers/pcmcia/pxa2xx_cm_x2xx.c | 10079 | 1149 | /*
* linux/drivers/pcmcia/pxa/pxa_cm_x2xx.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.
*
* Compulab Ltd., 2003, 2007, 2008
* Mike Rapoport <mike@compulab.co.il>
*
*/
#include <linux/module.h>
#include <asm/mach-types.h>
#include <mach/hardware.h>
int cmx255_pcmcia_init(void);
int cmx270_pcmcia_init(void);
void cmx255_pcmcia_exit(void);
void cmx270_pcmcia_exit(void);
static int __init cmx2xx_pcmcia_init(void)
{
int ret = -ENODEV;
if (machine_is_armcore() && cpu_is_pxa25x())
ret = cmx255_pcmcia_init();
else if (machine_is_armcore() && cpu_is_pxa27x())
ret = cmx270_pcmcia_init();
return ret;
}
static void __exit cmx2xx_pcmcia_exit(void)
{
if (machine_is_armcore() && cpu_is_pxa25x())
cmx255_pcmcia_exit();
else if (machine_is_armcore() && cpu_is_pxa27x())
cmx270_pcmcia_exit();
}
module_init(cmx2xx_pcmcia_init);
module_exit(cmx2xx_pcmcia_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mike Rapoport <mike@compulab.co.il>");
MODULE_DESCRIPTION("CM-x2xx PCMCIA driver");
| gpl-2.0 |
GerrieWell/AK-OnePone | drivers/infiniband/hw/mthca/mthca_allocator.c | 13919 | 7640 | /*
* Copyright (c) 2004 Topspin Communications. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/bitmap.h>
#include "mthca_dev.h"
/* Trivial bitmap-based allocator */
u32 mthca_alloc(struct mthca_alloc *alloc)
{
unsigned long flags;
u32 obj;
spin_lock_irqsave(&alloc->lock, flags);
obj = find_next_zero_bit(alloc->table, alloc->max, alloc->last);
if (obj >= alloc->max) {
alloc->top = (alloc->top + alloc->max) & alloc->mask;
obj = find_first_zero_bit(alloc->table, alloc->max);
}
if (obj < alloc->max) {
set_bit(obj, alloc->table);
obj |= alloc->top;
} else
obj = -1;
spin_unlock_irqrestore(&alloc->lock, flags);
return obj;
}
void mthca_free(struct mthca_alloc *alloc, u32 obj)
{
unsigned long flags;
obj &= alloc->max - 1;
spin_lock_irqsave(&alloc->lock, flags);
clear_bit(obj, alloc->table);
alloc->last = min(alloc->last, obj);
alloc->top = (alloc->top + alloc->max) & alloc->mask;
spin_unlock_irqrestore(&alloc->lock, flags);
}
int mthca_alloc_init(struct mthca_alloc *alloc, u32 num, u32 mask,
u32 reserved)
{
int i;
/* num must be a power of 2 */
if (num != 1 << (ffs(num) - 1))
return -EINVAL;
alloc->last = 0;
alloc->top = 0;
alloc->max = num;
alloc->mask = mask;
spin_lock_init(&alloc->lock);
alloc->table = kmalloc(BITS_TO_LONGS(num) * sizeof (long),
GFP_KERNEL);
if (!alloc->table)
return -ENOMEM;
bitmap_zero(alloc->table, num);
for (i = 0; i < reserved; ++i)
set_bit(i, alloc->table);
return 0;
}
void mthca_alloc_cleanup(struct mthca_alloc *alloc)
{
kfree(alloc->table);
}
/*
* Array of pointers with lazy allocation of leaf pages. Callers of
* _get, _set and _clear methods must use a lock or otherwise
* serialize access to the array.
*/
#define MTHCA_ARRAY_MASK (PAGE_SIZE / sizeof (void *) - 1)
void *mthca_array_get(struct mthca_array *array, int index)
{
int p = (index * sizeof (void *)) >> PAGE_SHIFT;
if (array->page_list[p].page)
return array->page_list[p].page[index & MTHCA_ARRAY_MASK];
else
return NULL;
}
int mthca_array_set(struct mthca_array *array, int index, void *value)
{
int p = (index * sizeof (void *)) >> PAGE_SHIFT;
/* Allocate with GFP_ATOMIC because we'll be called with locks held. */
if (!array->page_list[p].page)
array->page_list[p].page = (void **) get_zeroed_page(GFP_ATOMIC);
if (!array->page_list[p].page)
return -ENOMEM;
array->page_list[p].page[index & MTHCA_ARRAY_MASK] = value;
++array->page_list[p].used;
return 0;
}
void mthca_array_clear(struct mthca_array *array, int index)
{
int p = (index * sizeof (void *)) >> PAGE_SHIFT;
if (--array->page_list[p].used == 0) {
free_page((unsigned long) array->page_list[p].page);
array->page_list[p].page = NULL;
} else
array->page_list[p].page[index & MTHCA_ARRAY_MASK] = NULL;
if (array->page_list[p].used < 0)
pr_debug("Array %p index %d page %d with ref count %d < 0\n",
array, index, p, array->page_list[p].used);
}
int mthca_array_init(struct mthca_array *array, int nent)
{
int npage = (nent * sizeof (void *) + PAGE_SIZE - 1) / PAGE_SIZE;
int i;
array->page_list = kmalloc(npage * sizeof *array->page_list, GFP_KERNEL);
if (!array->page_list)
return -ENOMEM;
for (i = 0; i < npage; ++i) {
array->page_list[i].page = NULL;
array->page_list[i].used = 0;
}
return 0;
}
void mthca_array_cleanup(struct mthca_array *array, int nent)
{
int i;
for (i = 0; i < (nent * sizeof (void *) + PAGE_SIZE - 1) / PAGE_SIZE; ++i)
free_page((unsigned long) array->page_list[i].page);
kfree(array->page_list);
}
/*
* Handling for queue buffers -- we allocate a bunch of memory and
* register it in a memory region at HCA virtual address 0. If the
* requested size is > max_direct, we split the allocation into
* multiple pages, so we don't require too much contiguous memory.
*/
int mthca_buf_alloc(struct mthca_dev *dev, int size, int max_direct,
union mthca_buf *buf, int *is_direct, struct mthca_pd *pd,
int hca_write, struct mthca_mr *mr)
{
int err = -ENOMEM;
int npages, shift;
u64 *dma_list = NULL;
dma_addr_t t;
int i;
if (size <= max_direct) {
*is_direct = 1;
npages = 1;
shift = get_order(size) + PAGE_SHIFT;
buf->direct.buf = dma_alloc_coherent(&dev->pdev->dev,
size, &t, GFP_KERNEL);
if (!buf->direct.buf)
return -ENOMEM;
dma_unmap_addr_set(&buf->direct, mapping, t);
memset(buf->direct.buf, 0, size);
while (t & ((1 << shift) - 1)) {
--shift;
npages *= 2;
}
dma_list = kmalloc(npages * sizeof *dma_list, GFP_KERNEL);
if (!dma_list)
goto err_free;
for (i = 0; i < npages; ++i)
dma_list[i] = t + i * (1 << shift);
} else {
*is_direct = 0;
npages = (size + PAGE_SIZE - 1) / PAGE_SIZE;
shift = PAGE_SHIFT;
dma_list = kmalloc(npages * sizeof *dma_list, GFP_KERNEL);
if (!dma_list)
return -ENOMEM;
buf->page_list = kmalloc(npages * sizeof *buf->page_list,
GFP_KERNEL);
if (!buf->page_list)
goto err_out;
for (i = 0; i < npages; ++i)
buf->page_list[i].buf = NULL;
for (i = 0; i < npages; ++i) {
buf->page_list[i].buf =
dma_alloc_coherent(&dev->pdev->dev, PAGE_SIZE,
&t, GFP_KERNEL);
if (!buf->page_list[i].buf)
goto err_free;
dma_list[i] = t;
dma_unmap_addr_set(&buf->page_list[i], mapping, t);
clear_page(buf->page_list[i].buf);
}
}
err = mthca_mr_alloc_phys(dev, pd->pd_num,
dma_list, shift, npages,
0, size,
MTHCA_MPT_FLAG_LOCAL_READ |
(hca_write ? MTHCA_MPT_FLAG_LOCAL_WRITE : 0),
mr);
if (err)
goto err_free;
kfree(dma_list);
return 0;
err_free:
mthca_buf_free(dev, size, buf, *is_direct, NULL);
err_out:
kfree(dma_list);
return err;
}
void mthca_buf_free(struct mthca_dev *dev, int size, union mthca_buf *buf,
int is_direct, struct mthca_mr *mr)
{
int i;
if (mr)
mthca_free_mr(dev, mr);
if (is_direct)
dma_free_coherent(&dev->pdev->dev, size, buf->direct.buf,
dma_unmap_addr(&buf->direct, mapping));
else {
for (i = 0; i < (size + PAGE_SIZE - 1) / PAGE_SIZE; ++i)
dma_free_coherent(&dev->pdev->dev, PAGE_SIZE,
buf->page_list[i].buf,
dma_unmap_addr(&buf->page_list[i],
mapping));
kfree(buf->page_list);
}
}
| gpl-2.0 |
waynedkim/sgs3-kernel | drivers/media/video/ivtv/ivtv-routing.c | 14175 | 3640 | /*
Audio/video-routing-related ivtv functions.
Copyright (C) 2003-2004 Kevin Thayer <nufan_wfk at yahoo.com>
Copyright (C) 2005-2007 Hans Verkuil <hverkuil@xs4all.nl>
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 "ivtv-driver.h"
#include "ivtv-i2c.h"
#include "ivtv-cards.h"
#include "ivtv-gpio.h"
#include "ivtv-routing.h"
#include <media/msp3400.h>
#include <media/m52790.h>
#include <media/upd64031a.h>
#include <media/upd64083.h>
/* Selects the audio input and output according to the current
settings. */
void ivtv_audio_set_io(struct ivtv *itv)
{
const struct ivtv_card_audio_input *in;
u32 input, output = 0;
/* Determine which input to use */
if (test_bit(IVTV_F_I_RADIO_USER, &itv->i_flags))
in = &itv->card->radio_input;
else
in = &itv->card->audio_inputs[itv->audio_input];
/* handle muxer chips */
input = in->muxer_input;
if (itv->card->hw_muxer & IVTV_HW_M52790)
output = M52790_OUT_STEREO;
v4l2_subdev_call(itv->sd_muxer, audio, s_routing,
input, output, 0);
input = in->audio_input;
output = 0;
if (itv->card->hw_audio & IVTV_HW_MSP34XX)
output = MSP_OUTPUT(MSP_SC_IN_DSP_SCART1);
ivtv_call_hw(itv, itv->card->hw_audio, audio, s_routing,
input, output, 0);
}
/* Selects the video input and output according to the current
settings. */
void ivtv_video_set_io(struct ivtv *itv)
{
int inp = itv->active_input;
u32 input;
u32 type;
v4l2_subdev_call(itv->sd_video, video, s_routing,
itv->card->video_inputs[inp].video_input, 0, 0);
type = itv->card->video_inputs[inp].video_type;
if (type == IVTV_CARD_INPUT_VID_TUNER) {
input = 0; /* Tuner */
} else if (type < IVTV_CARD_INPUT_COMPOSITE1) {
input = 2; /* S-Video */
} else {
input = 1; /* Composite */
}
if (itv->card->hw_video & IVTV_HW_GPIO)
ivtv_call_hw(itv, IVTV_HW_GPIO, video, s_routing,
input, 0, 0);
if (itv->card->hw_video & IVTV_HW_UPD64031A) {
if (type == IVTV_CARD_INPUT_VID_TUNER ||
type >= IVTV_CARD_INPUT_COMPOSITE1) {
/* Composite: GR on, connect to 3DYCS */
input = UPD64031A_GR_ON | UPD64031A_3DYCS_COMPOSITE;
} else {
/* S-Video: GR bypassed, turn it off */
input = UPD64031A_GR_OFF | UPD64031A_3DYCS_DISABLE;
}
input |= itv->card->gr_config;
ivtv_call_hw(itv, IVTV_HW_UPD64031A, video, s_routing,
input, 0, 0);
}
if (itv->card->hw_video & IVTV_HW_UPD6408X) {
input = UPD64083_YCS_MODE;
if (type > IVTV_CARD_INPUT_VID_TUNER &&
type < IVTV_CARD_INPUT_COMPOSITE1) {
/* S-Video uses YCNR mode and internal Y-ADC, the
upd64031a is not used. */
input |= UPD64083_YCNR_MODE;
}
else if (itv->card->hw_video & IVTV_HW_UPD64031A) {
/* Use upd64031a output for tuner and
composite(CX23416GYC only) inputs */
if (type == IVTV_CARD_INPUT_VID_TUNER ||
itv->card->type == IVTV_CARD_CX23416GYC) {
input |= UPD64083_EXT_Y_ADC;
}
}
ivtv_call_hw(itv, IVTV_HW_UPD6408X, video, s_routing,
input, 0, 0);
}
}
| gpl-2.0 |
thederekjay/SGH-T989_GB_Kernel | drivers/rtc/rtc-pm8xxx.c | 96 | 14172 | /* Copyright (c) 2010-2011, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/rtc.h>
#include <linux/pm.h>
#include <linux/slab.h>
#include<linux/spinlock.h>
#include <linux/mfd/pm8xxx/core.h>
#include <linux/mfd/pm8xxx/rtc.h>
/* RTC Register offsets from RTC CTRL REG */
#define PM8XXX_ALARM_CTRL_OFFSET 0x01
#define PM8XXX_RTC_WRITE_OFFSET 0x02
#define PM8XXX_RTC_READ_OFFSET 0x06
#define PM8XXX_ALARM_RW_OFFSET 0x0A
/* RTC_CTRL register bit fields */
#define PM8xxx_RTC_ENABLE BIT(7)
#define PM8xxx_RTC_ALARM_ENABLE BIT(1)
#define PM8xxx_RTC_ALARM_CLEAR BIT(0)
#define NUM_8_BIT_RTC_REGS 0x4
/**
* struct pm8xxx_rtc - rtc driver internal structure
* @rtc: rtc device for this driver
* @rtc_alarm_irq: rtc alarm irq number
*/
struct pm8xxx_rtc {
struct rtc_device *rtc;
int rtc_alarm_irq;
int rtc_base;
int rtc_read_base;
int rtc_write_base;
int alarm_rw_base;
u8 ctrl_reg;
struct device *rtc_dev;
spinlock_t ctrl_reg_lock;
};
/*
* The RTC registers need to be read/written one byte at a time. This is a
* hardware limitation.
*/
static int pm8xxx_read_wrapper(struct pm8xxx_rtc *rtc_dd, u8 *rtc_val,
int base, int count)
{
int i, rc;
struct device *parent = rtc_dd->rtc_dev->parent;
for (i = 0; i < count; i++) {
rc = pm8xxx_readb(parent, base + i, &rtc_val[i]);
if (rc < 0) {
dev_err(rtc_dd->rtc_dev, "PM8xxx read failed\n");
return rc;
}
}
return 0;
}
static int pm8xxx_write_wrapper(struct pm8xxx_rtc *rtc_dd, u8 *rtc_val,
int base, int count)
{
int i, rc;
struct device *parent = rtc_dd->rtc_dev->parent;
for (i = 0; i < count; i++) {
rc = pm8xxx_writeb(parent, base + i, rtc_val[i]);
if (rc < 0) {
dev_err(rtc_dd->rtc_dev, "PM8xxx write failed\n");
return rc;
}
}
return 0;
}
/*
* Steps to write the RTC registers.
* 1. Disable alarm if enabled.
* 2. Write 0x00 to LSB.
* 3. Write Byte[1], Byte[2], Byte[3] then Byte[0].
* 4. Enable alarm if disabled in step 1.
*/
static int
pm8xxx_rtc_set_time(struct device *dev, struct rtc_time *tm)
{
int rc;
unsigned long secs, irq_flags;
u8 value[4], reg = 0, alarm_enabled = 0, ctrl_reg;
struct pm8xxx_rtc *rtc_dd = dev_get_drvdata(dev);
rtc_tm_to_time(tm, &secs);
value[0] = secs & 0xFF;
value[1] = (secs >> 8) & 0xFF;
value[2] = (secs >> 16) & 0xFF;
value[3] = (secs >> 24) & 0xFF;
dev_dbg(dev, "Seconds value to be written to RTC = %lu\n", secs);
spin_lock_irqsave(&rtc_dd->ctrl_reg_lock, irq_flags);
ctrl_reg = rtc_dd->ctrl_reg;
if (ctrl_reg & PM8xxx_RTC_ALARM_ENABLE) {
alarm_enabled = 1;
ctrl_reg &= ~PM8xxx_RTC_ALARM_ENABLE;
rc = pm8xxx_write_wrapper(rtc_dd, &ctrl_reg, rtc_dd->rtc_base,
1);
if (rc < 0) {
dev_err(dev, "PM8xxx write failed\n");
goto rtc_rw_fail;
}
} else
spin_unlock_irqrestore(&rtc_dd->ctrl_reg_lock, irq_flags);
/* Write Byte[1], Byte[2], Byte[3], Byte[0] */
/* Write 0 to Byte[0] */
reg = 0;
rc = pm8xxx_write_wrapper(rtc_dd, ®, rtc_dd->rtc_write_base, 1);
if (rc < 0) {
dev_err(dev, "PM8xxx write failed\n");
goto rtc_rw_fail;
}
/* Write Byte[1], Byte[2], Byte[3] */
rc = pm8xxx_write_wrapper(rtc_dd, value + 1,
rtc_dd->rtc_write_base + 1, 3);
if (rc < 0) {
dev_err(dev, "Write to RTC registers failed\n");
goto rtc_rw_fail;
}
/* Write Byte[0] */
rc = pm8xxx_write_wrapper(rtc_dd, value, rtc_dd->rtc_write_base, 1);
if (rc < 0) {
dev_err(dev, "Write to RTC register failed\n");
goto rtc_rw_fail;
}
if (alarm_enabled) {
ctrl_reg |= PM8xxx_RTC_ALARM_ENABLE;
rc = pm8xxx_write_wrapper(rtc_dd, &ctrl_reg, rtc_dd->rtc_base,
1);
if (rc < 0) {
dev_err(dev, "PM8xxx write failed\n");
goto rtc_rw_fail;
}
}
rtc_dd->ctrl_reg = ctrl_reg;
rtc_rw_fail:
if (alarm_enabled)
spin_unlock_irqrestore(&rtc_dd->ctrl_reg_lock, irq_flags);
return rc;
}
static int
pm8xxx_rtc_read_time(struct device *dev, struct rtc_time *tm)
{
int rc;
u8 value[4], reg;
unsigned long secs;
struct pm8xxx_rtc *rtc_dd = dev_get_drvdata(dev);
rc = pm8xxx_read_wrapper(rtc_dd, value, rtc_dd->rtc_read_base,
NUM_8_BIT_RTC_REGS);
if (rc < 0) {
dev_err(dev, "RTC time read failed\n");
return rc;
}
/*
* Read the LSB again and check if there has been a carry over.
* If there is, redo the read operation.
*/
rc = pm8xxx_read_wrapper(rtc_dd, ®, rtc_dd->rtc_read_base, 1);
if (rc < 0) {
dev_err(dev, "PM8xxx read failed\n");
return rc;
}
if (unlikely(reg < value[0])) {
rc = pm8xxx_read_wrapper(rtc_dd, value,
rtc_dd->rtc_read_base, NUM_8_BIT_RTC_REGS);
if (rc < 0) {
dev_err(dev, "RTC time read failed\n");
return rc;
}
}
secs = value[0] | (value[1] << 8) | (value[2] << 16) \
| (value[3] << 24);
rtc_time_to_tm(secs, tm);
rc = rtc_valid_tm(tm);
if (rc < 0) {
dev_err(dev, "Invalid time read from PM8xxx\n");
return rc;
}
dev_dbg(dev, "secs = %lu, h:m:s == %d:%d:%d, d/m/y = %d/%d/%d\n",
secs, tm->tm_hour, tm->tm_min, tm->tm_sec,
tm->tm_mday, tm->tm_mon, tm->tm_year);
return 0;
}
static int
pm8xxx_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alarm)
{
int rc;
u8 value[4], ctrl_reg;
unsigned long secs, secs_rtc, irq_flags;
struct pm8xxx_rtc *rtc_dd = dev_get_drvdata(dev);
struct rtc_time rtc_tm;
rtc_tm_to_time(&alarm->time, &secs);
/*
* Read the current RTC time and verify if the alarm time is in the
* past. If yes, return invalid.
*/
rc = pm8xxx_rtc_read_time(dev, &rtc_tm);
if (rc < 0) {
dev_err(dev, "Unamble to read RTC time\n");
return -EINVAL;
}
rtc_tm_to_time(&rtc_tm, &secs_rtc);
if (secs < secs_rtc) {
dev_err(dev, "Trying to set alarm in the past\n");
return -EINVAL;
}
value[0] = secs & 0xFF;
value[1] = (secs >> 8) & 0xFF;
value[2] = (secs >> 16) & 0xFF;
value[3] = (secs >> 24) & 0xFF;
spin_lock_irqsave(&rtc_dd->ctrl_reg_lock, irq_flags);
rc = pm8xxx_write_wrapper(rtc_dd, value, rtc_dd->alarm_rw_base,
NUM_8_BIT_RTC_REGS);
if (rc < 0) {
dev_err(dev, "Write to RTC ALARM registers failed\n");
goto rtc_rw_fail;
}
ctrl_reg = rtc_dd->ctrl_reg;
ctrl_reg = (alarm->enabled) ? (ctrl_reg | PM8xxx_RTC_ALARM_ENABLE) :
(ctrl_reg & ~PM8xxx_RTC_ALARM_ENABLE);
rc = pm8xxx_write_wrapper(rtc_dd, &ctrl_reg, rtc_dd->rtc_base, 1);
if (rc < 0) {
dev_err(dev, "PM8xxx write failed\n");
goto rtc_rw_fail;
}
rtc_dd->ctrl_reg = ctrl_reg;
dev_dbg(dev, "Alarm Set for h:r:s=%d:%d:%d, d/m/y=%d/%d/%d\n",
alarm->time.tm_hour, alarm->time.tm_min,
alarm->time.tm_sec, alarm->time.tm_mday,
alarm->time.tm_mon, alarm->time.tm_year);
rtc_rw_fail:
spin_unlock_irqrestore(&rtc_dd->ctrl_reg_lock, irq_flags);
return rc;
}
static int
pm8xxx_rtc_read_alarm(struct device *dev, struct rtc_wkalrm *alarm)
{
int rc;
u8 value[4];
unsigned long secs;
struct pm8xxx_rtc *rtc_dd = dev_get_drvdata(dev);
rc = pm8xxx_read_wrapper(rtc_dd, value, rtc_dd->alarm_rw_base,
NUM_8_BIT_RTC_REGS);
if (rc < 0) {
dev_err(dev, "RTC alarm time read failed\n");
return rc;
}
secs = value[0] | (value[1] << 8) | (value[2] << 16) | \
(value[3] << 24);
rtc_time_to_tm(secs, &alarm->time);
rc = rtc_valid_tm(&alarm->time);
if (rc < 0) {
dev_err(dev, "Invalid time read from PM8xxx\n");
return rc;
}
dev_dbg(dev, "Alarm set for - h:r:s=%d:%d:%d, d/m/y=%d/%d/%d\n",
alarm->time.tm_hour, alarm->time.tm_min,
alarm->time.tm_sec, alarm->time.tm_mday,
alarm->time.tm_mon, alarm->time.tm_year);
return 0;
}
static int
pm8xxx_rtc_alarm_irq_enable(struct device *dev, unsigned int enabled)
{
int rc;
unsigned long irq_flags;
struct pm8xxx_rtc *rtc_dd = dev_get_drvdata(dev);
u8 ctrl_reg;
spin_lock_irqsave(&rtc_dd->ctrl_reg_lock, irq_flags);
ctrl_reg = rtc_dd->ctrl_reg;
ctrl_reg = (enabled) ? (ctrl_reg | PM8xxx_RTC_ALARM_ENABLE) :
(ctrl_reg & ~PM8xxx_RTC_ALARM_ENABLE);
rc = pm8xxx_write_wrapper(rtc_dd, &ctrl_reg, rtc_dd->rtc_base, 1);
if (rc < 0) {
dev_err(dev, "PM8xxx write failed\n");
goto rtc_rw_fail;
}
rtc_dd->ctrl_reg = ctrl_reg;
rtc_rw_fail:
spin_unlock_irqrestore(&rtc_dd->ctrl_reg_lock, irq_flags);
return rc;
}
static struct rtc_class_ops pm8xxx_rtc_ops = {
.read_time = pm8xxx_rtc_read_time,
.set_alarm = pm8xxx_rtc_set_alarm,
.read_alarm = pm8xxx_rtc_read_alarm,
.alarm_irq_enable = pm8xxx_rtc_alarm_irq_enable,
};
static irqreturn_t pm8xxx_alarm_trigger(int irq, void *dev_id)
{
struct pm8xxx_rtc *rtc_dd = dev_id;
u8 ctrl_reg;
int rc;
unsigned long irq_flags;
rtc_update_irq(rtc_dd->rtc, 1, RTC_IRQF | RTC_AF);
spin_lock_irqsave(&rtc_dd->ctrl_reg_lock, irq_flags);
/* Clear the alarm enable bit */
ctrl_reg = rtc_dd->ctrl_reg;
ctrl_reg &= ~PM8xxx_RTC_ALARM_ENABLE;
rc = pm8xxx_write_wrapper(rtc_dd, &ctrl_reg, rtc_dd->rtc_base, 1);
if (rc < 0) {
spin_unlock_irqrestore(&rtc_dd->ctrl_reg_lock, irq_flags);
dev_err(rtc_dd->rtc_dev, "PM8xxx write failed!\n");
goto rtc_alarm_handled;
}
rtc_dd->ctrl_reg = ctrl_reg;
spin_unlock_irqrestore(&rtc_dd->ctrl_reg_lock, irq_flags);
/* Clear RTC alarm register */
rc = pm8xxx_read_wrapper(rtc_dd, &ctrl_reg, rtc_dd->rtc_base +
PM8XXX_ALARM_CTRL_OFFSET, 1);
if (rc < 0) {
dev_err(rtc_dd->rtc_dev, "PM8xxx write failed!\n");
goto rtc_alarm_handled;
}
ctrl_reg &= ~PM8xxx_RTC_ALARM_CLEAR;
rc = pm8xxx_write_wrapper(rtc_dd, &ctrl_reg, rtc_dd->rtc_base +
PM8XXX_ALARM_CTRL_OFFSET, 1);
if (rc < 0)
dev_err(rtc_dd->rtc_dev, "PM8xxx write failed!\n");
rtc_alarm_handled:
return IRQ_HANDLED;
}
static int __devinit pm8xxx_rtc_probe(struct platform_device *pdev)
{
int rc;
u8 ctrl_reg;
bool rtc_write_enable = false;
struct pm8xxx_rtc *rtc_dd;
struct resource *rtc_resource;
const struct pm8xxx_rtc_platform_data *pdata =
pdev->dev.platform_data;
if (pdata != NULL)
rtc_write_enable = pdata->rtc_write_enable;
rtc_dd = kzalloc(sizeof(*rtc_dd), GFP_KERNEL);
if (rtc_dd == NULL) {
dev_err(&pdev->dev, "Unable to allocate memory!\n");
return -ENOMEM;
}
/* Initialise spinlock to protect RTC cntrol register */
spin_lock_init(&rtc_dd->ctrl_reg_lock);
rtc_dd->rtc_alarm_irq = platform_get_irq(pdev, 0);
if (rtc_dd->rtc_alarm_irq < 0) {
dev_err(&pdev->dev, "Alarm IRQ resource absent!\n");
rc = -ENXIO;
goto fail_rtc_enable;
}
rtc_resource = platform_get_resource_byname(pdev, IORESOURCE_IO,
"pmic_rtc_base");
if (!(rtc_resource && rtc_resource->start)) {
dev_err(&pdev->dev, "RTC IO resource absent!\n");
rc = -ENXIO;
goto fail_rtc_enable;
}
rtc_dd->rtc_base = rtc_resource->start;
/* Setup RTC register addresses */
rtc_dd->rtc_write_base = rtc_dd->rtc_base + PM8XXX_RTC_WRITE_OFFSET;
rtc_dd->rtc_read_base = rtc_dd->rtc_base + PM8XXX_RTC_READ_OFFSET;
rtc_dd->alarm_rw_base = rtc_dd->rtc_base + PM8XXX_ALARM_RW_OFFSET;
rtc_dd->rtc_dev = &(pdev->dev);
/* Check if the RTC is on, else turn it on */
rc = pm8xxx_read_wrapper(rtc_dd, &ctrl_reg, rtc_dd->rtc_base, 1);
if (rc < 0) {
dev_err(&pdev->dev, "PM8xxx read failed!\n");
goto fail_rtc_enable;
}
if (!(ctrl_reg & PM8xxx_RTC_ENABLE)) {
ctrl_reg |= PM8xxx_RTC_ENABLE;
rc = pm8xxx_write_wrapper(rtc_dd, &ctrl_reg, rtc_dd->rtc_base,
1);
if (rc < 0) {
dev_err(&pdev->dev, "PM8xxx write failed!\n");
goto fail_rtc_enable;
}
}
rtc_dd->ctrl_reg = ctrl_reg;
if (rtc_write_enable == true)
pm8xxx_rtc_ops.set_time = pm8xxx_rtc_set_time;
platform_set_drvdata(pdev, rtc_dd);
/* Register the RTC device */
rtc_dd->rtc = rtc_device_register("pm8xxx_rtc", &pdev->dev,
&pm8xxx_rtc_ops, THIS_MODULE);
if (IS_ERR(rtc_dd->rtc)) {
dev_err(&pdev->dev, "%s: RTC registration failed (%ld)\n",
__func__, PTR_ERR(rtc_dd->rtc));
rc = PTR_ERR(rtc_dd->rtc);
goto fail_rtc_enable;
}
/* Request the alarm IRQ */
rc = request_any_context_irq(rtc_dd->rtc_alarm_irq,
pm8xxx_alarm_trigger, IRQF_TRIGGER_RISING,
"pm8xxx_rtc_alarm", rtc_dd);
if (rc < 0) {
dev_err(&pdev->dev, "Request IRQ failed (%d)\n", rc);
goto fail_req_irq;
}
device_init_wakeup(&pdev->dev, 1);
dev_dbg(&pdev->dev, "Probe success !!\n");
return 0;
fail_req_irq:
rtc_device_unregister(rtc_dd->rtc);
fail_rtc_enable:
platform_set_drvdata(pdev, NULL);
kfree(rtc_dd);
return rc;
}
#ifdef CONFIG_PM
static int pm8xxx_rtc_resume(struct device *dev)
{
struct pm8xxx_rtc *rtc_dd = dev_get_drvdata(dev);
if (device_may_wakeup(dev))
disable_irq_wake(rtc_dd->rtc_alarm_irq);
return 0;
}
static int pm8xxx_rtc_suspend(struct device *dev)
{
struct pm8xxx_rtc *rtc_dd = dev_get_drvdata(dev);
if (device_may_wakeup(dev))
enable_irq_wake(rtc_dd->rtc_alarm_irq);
return 0;
}
static const struct dev_pm_ops pm8xxx_rtc_pm_ops = {
.suspend = pm8xxx_rtc_suspend,
.resume = pm8xxx_rtc_resume,
};
#endif
static int __devexit pm8xxx_rtc_remove(struct platform_device *pdev)
{
struct pm8xxx_rtc *rtc_dd = platform_get_drvdata(pdev);
device_init_wakeup(&pdev->dev, 0);
free_irq(rtc_dd->rtc_alarm_irq, rtc_dd);
rtc_device_unregister(rtc_dd->rtc);
platform_set_drvdata(pdev, NULL);
kfree(rtc_dd);
return 0;
}
static struct platform_driver pm8xxx_rtc_driver = {
.probe = pm8xxx_rtc_probe,
.remove = __devexit_p(pm8xxx_rtc_remove),
.driver = {
.name = PM8XXX_RTC_DEV_NAME,
.owner = THIS_MODULE,
#ifdef CONFIG_PM
.pm = &pm8xxx_rtc_pm_ops,
#endif
},
};
static int __init pm8xxx_rtc_init(void)
{
return platform_driver_register(&pm8xxx_rtc_driver);
}
module_init(pm8xxx_rtc_init);
static void __exit pm8xxx_rtc_exit(void)
{
platform_driver_unregister(&pm8xxx_rtc_driver);
}
module_exit(pm8xxx_rtc_exit);
MODULE_ALIAS("platform:rtc-pm8xxx");
MODULE_DESCRIPTION("PMIC8xxx RTC driver");
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("Anirudh Ghayal <aghayal@codeaurora.org>");
| gpl-2.0 |
virtuoso/linux-perf | drivers/char/ipmi/ipmi_msghandler.c | 96 | 120753 | /*
* ipmi_msghandler.c
*
* Incoming and outgoing message routing for an IPMI interface.
*
* Author: MontaVista Software, Inc.
* Corey Minyard <minyard@mvista.com>
* source@mvista.com
*
* Copyright 2002 MontaVista Software 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 SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/poll.h>
#include <linux/sched.h>
#include <linux/seq_file.h>
#include <linux/spinlock.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <linux/ipmi.h>
#include <linux/ipmi_smi.h>
#include <linux/notifier.h>
#include <linux/init.h>
#include <linux/proc_fs.h>
#include <linux/rcupdate.h>
#include <linux/interrupt.h>
#define PFX "IPMI message handler: "
#define IPMI_DRIVER_VERSION "39.2"
static struct ipmi_recv_msg *ipmi_alloc_recv_msg(void);
static int ipmi_init_msghandler(void);
static void smi_recv_tasklet(unsigned long);
static void handle_new_recv_msgs(ipmi_smi_t intf);
static void need_waiter(ipmi_smi_t intf);
static int handle_one_recv_msg(ipmi_smi_t intf,
struct ipmi_smi_msg *msg);
static int initialized;
#ifdef CONFIG_PROC_FS
static struct proc_dir_entry *proc_ipmi_root;
#endif /* CONFIG_PROC_FS */
/* Remain in auto-maintenance mode for this amount of time (in ms). */
#define IPMI_MAINTENANCE_MODE_TIMEOUT 30000
#define MAX_EVENTS_IN_QUEUE 25
/*
* Don't let a message sit in a queue forever, always time it with at lest
* the max message timer. This is in milliseconds.
*/
#define MAX_MSG_TIMEOUT 60000
/* Call every ~1000 ms. */
#define IPMI_TIMEOUT_TIME 1000
/* How many jiffies does it take to get to the timeout time. */
#define IPMI_TIMEOUT_JIFFIES ((IPMI_TIMEOUT_TIME * HZ) / 1000)
/*
* Request events from the queue every second (this is the number of
* IPMI_TIMEOUT_TIMES between event requests). Hopefully, in the
* future, IPMI will add a way to know immediately if an event is in
* the queue and this silliness can go away.
*/
#define IPMI_REQUEST_EV_TIME (1000 / (IPMI_TIMEOUT_TIME))
/*
* The main "user" data structure.
*/
struct ipmi_user {
struct list_head link;
/* Set to false when the user is destroyed. */
bool valid;
struct kref refcount;
/* The upper layer that handles receive messages. */
struct ipmi_user_hndl *handler;
void *handler_data;
/* The interface this user is bound to. */
ipmi_smi_t intf;
/* Does this interface receive IPMI events? */
bool gets_events;
};
struct cmd_rcvr {
struct list_head link;
ipmi_user_t user;
unsigned char netfn;
unsigned char cmd;
unsigned int chans;
/*
* This is used to form a linked lised during mass deletion.
* Since this is in an RCU list, we cannot use the link above
* or change any data until the RCU period completes. So we
* use this next variable during mass deletion so we can have
* a list and don't have to wait and restart the search on
* every individual deletion of a command.
*/
struct cmd_rcvr *next;
};
struct seq_table {
unsigned int inuse : 1;
unsigned int broadcast : 1;
unsigned long timeout;
unsigned long orig_timeout;
unsigned int retries_left;
/*
* To verify on an incoming send message response that this is
* the message that the response is for, we keep a sequence id
* and increment it every time we send a message.
*/
long seqid;
/*
* This is held so we can properly respond to the message on a
* timeout, and it is used to hold the temporary data for
* retransmission, too.
*/
struct ipmi_recv_msg *recv_msg;
};
/*
* Store the information in a msgid (long) to allow us to find a
* sequence table entry from the msgid.
*/
#define STORE_SEQ_IN_MSGID(seq, seqid) (((seq&0xff)<<26) | (seqid&0x3ffffff))
#define GET_SEQ_FROM_MSGID(msgid, seq, seqid) \
do { \
seq = ((msgid >> 26) & 0x3f); \
seqid = (msgid & 0x3fffff); \
} while (0)
#define NEXT_SEQID(seqid) (((seqid) + 1) & 0x3fffff)
struct ipmi_channel {
unsigned char medium;
unsigned char protocol;
/*
* My slave address. This is initialized to IPMI_BMC_SLAVE_ADDR,
* but may be changed by the user.
*/
unsigned char address;
/*
* My LUN. This should generally stay the SMS LUN, but just in
* case...
*/
unsigned char lun;
};
#ifdef CONFIG_PROC_FS
struct ipmi_proc_entry {
char *name;
struct ipmi_proc_entry *next;
};
#endif
struct bmc_device {
struct platform_device pdev;
struct ipmi_device_id id;
unsigned char guid[16];
int guid_set;
char name[16];
struct kref usecount;
};
#define to_bmc_device(x) container_of((x), struct bmc_device, pdev.dev)
/*
* Various statistics for IPMI, these index stats[] in the ipmi_smi
* structure.
*/
enum ipmi_stat_indexes {
/* Commands we got from the user that were invalid. */
IPMI_STAT_sent_invalid_commands = 0,
/* Commands we sent to the MC. */
IPMI_STAT_sent_local_commands,
/* Responses from the MC that were delivered to a user. */
IPMI_STAT_handled_local_responses,
/* Responses from the MC that were not delivered to a user. */
IPMI_STAT_unhandled_local_responses,
/* Commands we sent out to the IPMB bus. */
IPMI_STAT_sent_ipmb_commands,
/* Commands sent on the IPMB that had errors on the SEND CMD */
IPMI_STAT_sent_ipmb_command_errs,
/* Each retransmit increments this count. */
IPMI_STAT_retransmitted_ipmb_commands,
/*
* When a message times out (runs out of retransmits) this is
* incremented.
*/
IPMI_STAT_timed_out_ipmb_commands,
/*
* This is like above, but for broadcasts. Broadcasts are
* *not* included in the above count (they are expected to
* time out).
*/
IPMI_STAT_timed_out_ipmb_broadcasts,
/* Responses I have sent to the IPMB bus. */
IPMI_STAT_sent_ipmb_responses,
/* The response was delivered to the user. */
IPMI_STAT_handled_ipmb_responses,
/* The response had invalid data in it. */
IPMI_STAT_invalid_ipmb_responses,
/* The response didn't have anyone waiting for it. */
IPMI_STAT_unhandled_ipmb_responses,
/* Commands we sent out to the IPMB bus. */
IPMI_STAT_sent_lan_commands,
/* Commands sent on the IPMB that had errors on the SEND CMD */
IPMI_STAT_sent_lan_command_errs,
/* Each retransmit increments this count. */
IPMI_STAT_retransmitted_lan_commands,
/*
* When a message times out (runs out of retransmits) this is
* incremented.
*/
IPMI_STAT_timed_out_lan_commands,
/* Responses I have sent to the IPMB bus. */
IPMI_STAT_sent_lan_responses,
/* The response was delivered to the user. */
IPMI_STAT_handled_lan_responses,
/* The response had invalid data in it. */
IPMI_STAT_invalid_lan_responses,
/* The response didn't have anyone waiting for it. */
IPMI_STAT_unhandled_lan_responses,
/* The command was delivered to the user. */
IPMI_STAT_handled_commands,
/* The command had invalid data in it. */
IPMI_STAT_invalid_commands,
/* The command didn't have anyone waiting for it. */
IPMI_STAT_unhandled_commands,
/* Invalid data in an event. */
IPMI_STAT_invalid_events,
/* Events that were received with the proper format. */
IPMI_STAT_events,
/* Retransmissions on IPMB that failed. */
IPMI_STAT_dropped_rexmit_ipmb_commands,
/* Retransmissions on LAN that failed. */
IPMI_STAT_dropped_rexmit_lan_commands,
/* This *must* remain last, add new values above this. */
IPMI_NUM_STATS
};
#define IPMI_IPMB_NUM_SEQ 64
#define IPMI_MAX_CHANNELS 16
struct ipmi_smi {
/* What interface number are we? */
int intf_num;
struct kref refcount;
/* Set when the interface is being unregistered. */
bool in_shutdown;
/* Used for a list of interfaces. */
struct list_head link;
/*
* The list of upper layers that are using me. seq_lock
* protects this.
*/
struct list_head users;
/* Information to supply to users. */
unsigned char ipmi_version_major;
unsigned char ipmi_version_minor;
/* Used for wake ups at startup. */
wait_queue_head_t waitq;
struct bmc_device *bmc;
char *my_dev_name;
/*
* This is the lower-layer's sender routine. Note that you
* must either be holding the ipmi_interfaces_mutex or be in
* an umpreemptible region to use this. You must fetch the
* value into a local variable and make sure it is not NULL.
*/
const struct ipmi_smi_handlers *handlers;
void *send_info;
#ifdef CONFIG_PROC_FS
/* A list of proc entries for this interface. */
struct mutex proc_entry_lock;
struct ipmi_proc_entry *proc_entries;
#endif
/* Driver-model device for the system interface. */
struct device *si_dev;
/*
* A table of sequence numbers for this interface. We use the
* sequence numbers for IPMB messages that go out of the
* interface to match them up with their responses. A routine
* is called periodically to time the items in this list.
*/
spinlock_t seq_lock;
struct seq_table seq_table[IPMI_IPMB_NUM_SEQ];
int curr_seq;
/*
* Messages queued for delivery. If delivery fails (out of memory
* for instance), They will stay in here to be processed later in a
* periodic timer interrupt. The tasklet is for handling received
* messages directly from the handler.
*/
spinlock_t waiting_rcv_msgs_lock;
struct list_head waiting_rcv_msgs;
atomic_t watchdog_pretimeouts_to_deliver;
struct tasklet_struct recv_tasklet;
spinlock_t xmit_msgs_lock;
struct list_head xmit_msgs;
struct ipmi_smi_msg *curr_msg;
struct list_head hp_xmit_msgs;
/*
* The list of command receivers that are registered for commands
* on this interface.
*/
struct mutex cmd_rcvrs_mutex;
struct list_head cmd_rcvrs;
/*
* Events that were queues because no one was there to receive
* them.
*/
spinlock_t events_lock; /* For dealing with event stuff. */
struct list_head waiting_events;
unsigned int waiting_events_count; /* How many events in queue? */
char delivering_events;
char event_msg_printed;
atomic_t event_waiters;
unsigned int ticks_to_req_ev;
int last_needs_timer;
/*
* The event receiver for my BMC, only really used at panic
* shutdown as a place to store this.
*/
unsigned char event_receiver;
unsigned char event_receiver_lun;
unsigned char local_sel_device;
unsigned char local_event_generator;
/* For handling of maintenance mode. */
int maintenance_mode;
bool maintenance_mode_enable;
int auto_maintenance_timeout;
spinlock_t maintenance_mode_lock; /* Used in a timer... */
/*
* A cheap hack, if this is non-null and a message to an
* interface comes in with a NULL user, call this routine with
* it. Note that the message will still be freed by the
* caller. This only works on the system interface.
*/
void (*null_user_handler)(ipmi_smi_t intf, struct ipmi_recv_msg *msg);
/*
* When we are scanning the channels for an SMI, this will
* tell which channel we are scanning.
*/
int curr_channel;
/* Channel information */
struct ipmi_channel channels[IPMI_MAX_CHANNELS];
/* Proc FS stuff. */
struct proc_dir_entry *proc_dir;
char proc_dir_name[10];
atomic_t stats[IPMI_NUM_STATS];
/*
* run_to_completion duplicate of smb_info, smi_info
* and ipmi_serial_info structures. Used to decrease numbers of
* parameters passed by "low" level IPMI code.
*/
int run_to_completion;
};
#define to_si_intf_from_dev(device) container_of(device, struct ipmi_smi, dev)
/**
* The driver model view of the IPMI messaging driver.
*/
static struct platform_driver ipmidriver = {
.driver = {
.name = "ipmi",
.bus = &platform_bus_type
}
};
static DEFINE_MUTEX(ipmidriver_mutex);
static LIST_HEAD(ipmi_interfaces);
static DEFINE_MUTEX(ipmi_interfaces_mutex);
/*
* List of watchers that want to know when smi's are added and deleted.
*/
static LIST_HEAD(smi_watchers);
static DEFINE_MUTEX(smi_watchers_mutex);
#define ipmi_inc_stat(intf, stat) \
atomic_inc(&(intf)->stats[IPMI_STAT_ ## stat])
#define ipmi_get_stat(intf, stat) \
((unsigned int) atomic_read(&(intf)->stats[IPMI_STAT_ ## stat]))
static const char * const addr_src_to_str[] = {
"invalid", "hotmod", "hardcoded", "SPMI", "ACPI", "SMBIOS", "PCI",
"device-tree", "default"
};
const char *ipmi_addr_src_to_str(enum ipmi_addr_src src)
{
if (src > SI_DEFAULT)
src = 0; /* Invalid */
return addr_src_to_str[src];
}
EXPORT_SYMBOL(ipmi_addr_src_to_str);
static int is_lan_addr(struct ipmi_addr *addr)
{
return addr->addr_type == IPMI_LAN_ADDR_TYPE;
}
static int is_ipmb_addr(struct ipmi_addr *addr)
{
return addr->addr_type == IPMI_IPMB_ADDR_TYPE;
}
static int is_ipmb_bcast_addr(struct ipmi_addr *addr)
{
return addr->addr_type == IPMI_IPMB_BROADCAST_ADDR_TYPE;
}
static void free_recv_msg_list(struct list_head *q)
{
struct ipmi_recv_msg *msg, *msg2;
list_for_each_entry_safe(msg, msg2, q, link) {
list_del(&msg->link);
ipmi_free_recv_msg(msg);
}
}
static void free_smi_msg_list(struct list_head *q)
{
struct ipmi_smi_msg *msg, *msg2;
list_for_each_entry_safe(msg, msg2, q, link) {
list_del(&msg->link);
ipmi_free_smi_msg(msg);
}
}
static void clean_up_interface_data(ipmi_smi_t intf)
{
int i;
struct cmd_rcvr *rcvr, *rcvr2;
struct list_head list;
tasklet_kill(&intf->recv_tasklet);
free_smi_msg_list(&intf->waiting_rcv_msgs);
free_recv_msg_list(&intf->waiting_events);
/*
* Wholesale remove all the entries from the list in the
* interface and wait for RCU to know that none are in use.
*/
mutex_lock(&intf->cmd_rcvrs_mutex);
INIT_LIST_HEAD(&list);
list_splice_init_rcu(&intf->cmd_rcvrs, &list, synchronize_rcu);
mutex_unlock(&intf->cmd_rcvrs_mutex);
list_for_each_entry_safe(rcvr, rcvr2, &list, link)
kfree(rcvr);
for (i = 0; i < IPMI_IPMB_NUM_SEQ; i++) {
if ((intf->seq_table[i].inuse)
&& (intf->seq_table[i].recv_msg))
ipmi_free_recv_msg(intf->seq_table[i].recv_msg);
}
}
static void intf_free(struct kref *ref)
{
ipmi_smi_t intf = container_of(ref, struct ipmi_smi, refcount);
clean_up_interface_data(intf);
kfree(intf);
}
struct watcher_entry {
int intf_num;
ipmi_smi_t intf;
struct list_head link;
};
int ipmi_smi_watcher_register(struct ipmi_smi_watcher *watcher)
{
ipmi_smi_t intf;
LIST_HEAD(to_deliver);
struct watcher_entry *e, *e2;
mutex_lock(&smi_watchers_mutex);
mutex_lock(&ipmi_interfaces_mutex);
/* Build a list of things to deliver. */
list_for_each_entry(intf, &ipmi_interfaces, link) {
if (intf->intf_num == -1)
continue;
e = kmalloc(sizeof(*e), GFP_KERNEL);
if (!e)
goto out_err;
kref_get(&intf->refcount);
e->intf = intf;
e->intf_num = intf->intf_num;
list_add_tail(&e->link, &to_deliver);
}
/* We will succeed, so add it to the list. */
list_add(&watcher->link, &smi_watchers);
mutex_unlock(&ipmi_interfaces_mutex);
list_for_each_entry_safe(e, e2, &to_deliver, link) {
list_del(&e->link);
watcher->new_smi(e->intf_num, e->intf->si_dev);
kref_put(&e->intf->refcount, intf_free);
kfree(e);
}
mutex_unlock(&smi_watchers_mutex);
return 0;
out_err:
mutex_unlock(&ipmi_interfaces_mutex);
mutex_unlock(&smi_watchers_mutex);
list_for_each_entry_safe(e, e2, &to_deliver, link) {
list_del(&e->link);
kref_put(&e->intf->refcount, intf_free);
kfree(e);
}
return -ENOMEM;
}
EXPORT_SYMBOL(ipmi_smi_watcher_register);
int ipmi_smi_watcher_unregister(struct ipmi_smi_watcher *watcher)
{
mutex_lock(&smi_watchers_mutex);
list_del(&(watcher->link));
mutex_unlock(&smi_watchers_mutex);
return 0;
}
EXPORT_SYMBOL(ipmi_smi_watcher_unregister);
/*
* Must be called with smi_watchers_mutex held.
*/
static void
call_smi_watchers(int i, struct device *dev)
{
struct ipmi_smi_watcher *w;
list_for_each_entry(w, &smi_watchers, link) {
if (try_module_get(w->owner)) {
w->new_smi(i, dev);
module_put(w->owner);
}
}
}
static int
ipmi_addr_equal(struct ipmi_addr *addr1, struct ipmi_addr *addr2)
{
if (addr1->addr_type != addr2->addr_type)
return 0;
if (addr1->channel != addr2->channel)
return 0;
if (addr1->addr_type == IPMI_SYSTEM_INTERFACE_ADDR_TYPE) {
struct ipmi_system_interface_addr *smi_addr1
= (struct ipmi_system_interface_addr *) addr1;
struct ipmi_system_interface_addr *smi_addr2
= (struct ipmi_system_interface_addr *) addr2;
return (smi_addr1->lun == smi_addr2->lun);
}
if (is_ipmb_addr(addr1) || is_ipmb_bcast_addr(addr1)) {
struct ipmi_ipmb_addr *ipmb_addr1
= (struct ipmi_ipmb_addr *) addr1;
struct ipmi_ipmb_addr *ipmb_addr2
= (struct ipmi_ipmb_addr *) addr2;
return ((ipmb_addr1->slave_addr == ipmb_addr2->slave_addr)
&& (ipmb_addr1->lun == ipmb_addr2->lun));
}
if (is_lan_addr(addr1)) {
struct ipmi_lan_addr *lan_addr1
= (struct ipmi_lan_addr *) addr1;
struct ipmi_lan_addr *lan_addr2
= (struct ipmi_lan_addr *) addr2;
return ((lan_addr1->remote_SWID == lan_addr2->remote_SWID)
&& (lan_addr1->local_SWID == lan_addr2->local_SWID)
&& (lan_addr1->session_handle
== lan_addr2->session_handle)
&& (lan_addr1->lun == lan_addr2->lun));
}
return 1;
}
int ipmi_validate_addr(struct ipmi_addr *addr, int len)
{
if (len < sizeof(struct ipmi_system_interface_addr))
return -EINVAL;
if (addr->addr_type == IPMI_SYSTEM_INTERFACE_ADDR_TYPE) {
if (addr->channel != IPMI_BMC_CHANNEL)
return -EINVAL;
return 0;
}
if ((addr->channel == IPMI_BMC_CHANNEL)
|| (addr->channel >= IPMI_MAX_CHANNELS)
|| (addr->channel < 0))
return -EINVAL;
if (is_ipmb_addr(addr) || is_ipmb_bcast_addr(addr)) {
if (len < sizeof(struct ipmi_ipmb_addr))
return -EINVAL;
return 0;
}
if (is_lan_addr(addr)) {
if (len < sizeof(struct ipmi_lan_addr))
return -EINVAL;
return 0;
}
return -EINVAL;
}
EXPORT_SYMBOL(ipmi_validate_addr);
unsigned int ipmi_addr_length(int addr_type)
{
if (addr_type == IPMI_SYSTEM_INTERFACE_ADDR_TYPE)
return sizeof(struct ipmi_system_interface_addr);
if ((addr_type == IPMI_IPMB_ADDR_TYPE)
|| (addr_type == IPMI_IPMB_BROADCAST_ADDR_TYPE))
return sizeof(struct ipmi_ipmb_addr);
if (addr_type == IPMI_LAN_ADDR_TYPE)
return sizeof(struct ipmi_lan_addr);
return 0;
}
EXPORT_SYMBOL(ipmi_addr_length);
static void deliver_response(struct ipmi_recv_msg *msg)
{
if (!msg->user) {
ipmi_smi_t intf = msg->user_msg_data;
/* Special handling for NULL users. */
if (intf->null_user_handler) {
intf->null_user_handler(intf, msg);
ipmi_inc_stat(intf, handled_local_responses);
} else {
/* No handler, so give up. */
ipmi_inc_stat(intf, unhandled_local_responses);
}
ipmi_free_recv_msg(msg);
} else if (!oops_in_progress) {
/*
* If we are running in the panic context, calling the
* receive handler doesn't much meaning and has a deadlock
* risk. At this moment, simply skip it in that case.
*/
ipmi_user_t user = msg->user;
user->handler->ipmi_recv_hndl(msg, user->handler_data);
}
}
static void
deliver_err_response(struct ipmi_recv_msg *msg, int err)
{
msg->recv_type = IPMI_RESPONSE_RECV_TYPE;
msg->msg_data[0] = err;
msg->msg.netfn |= 1; /* Convert to a response. */
msg->msg.data_len = 1;
msg->msg.data = msg->msg_data;
deliver_response(msg);
}
/*
* Find the next sequence number not being used and add the given
* message with the given timeout to the sequence table. This must be
* called with the interface's seq_lock held.
*/
static int intf_next_seq(ipmi_smi_t intf,
struct ipmi_recv_msg *recv_msg,
unsigned long timeout,
int retries,
int broadcast,
unsigned char *seq,
long *seqid)
{
int rv = 0;
unsigned int i;
for (i = intf->curr_seq; (i+1)%IPMI_IPMB_NUM_SEQ != intf->curr_seq;
i = (i+1)%IPMI_IPMB_NUM_SEQ) {
if (!intf->seq_table[i].inuse)
break;
}
if (!intf->seq_table[i].inuse) {
intf->seq_table[i].recv_msg = recv_msg;
/*
* Start with the maximum timeout, when the send response
* comes in we will start the real timer.
*/
intf->seq_table[i].timeout = MAX_MSG_TIMEOUT;
intf->seq_table[i].orig_timeout = timeout;
intf->seq_table[i].retries_left = retries;
intf->seq_table[i].broadcast = broadcast;
intf->seq_table[i].inuse = 1;
intf->seq_table[i].seqid = NEXT_SEQID(intf->seq_table[i].seqid);
*seq = i;
*seqid = intf->seq_table[i].seqid;
intf->curr_seq = (i+1)%IPMI_IPMB_NUM_SEQ;
need_waiter(intf);
} else {
rv = -EAGAIN;
}
return rv;
}
/*
* Return the receive message for the given sequence number and
* release the sequence number so it can be reused. Some other data
* is passed in to be sure the message matches up correctly (to help
* guard against message coming in after their timeout and the
* sequence number being reused).
*/
static int intf_find_seq(ipmi_smi_t intf,
unsigned char seq,
short channel,
unsigned char cmd,
unsigned char netfn,
struct ipmi_addr *addr,
struct ipmi_recv_msg **recv_msg)
{
int rv = -ENODEV;
unsigned long flags;
if (seq >= IPMI_IPMB_NUM_SEQ)
return -EINVAL;
spin_lock_irqsave(&(intf->seq_lock), flags);
if (intf->seq_table[seq].inuse) {
struct ipmi_recv_msg *msg = intf->seq_table[seq].recv_msg;
if ((msg->addr.channel == channel) && (msg->msg.cmd == cmd)
&& (msg->msg.netfn == netfn)
&& (ipmi_addr_equal(addr, &(msg->addr)))) {
*recv_msg = msg;
intf->seq_table[seq].inuse = 0;
rv = 0;
}
}
spin_unlock_irqrestore(&(intf->seq_lock), flags);
return rv;
}
/* Start the timer for a specific sequence table entry. */
static int intf_start_seq_timer(ipmi_smi_t intf,
long msgid)
{
int rv = -ENODEV;
unsigned long flags;
unsigned char seq;
unsigned long seqid;
GET_SEQ_FROM_MSGID(msgid, seq, seqid);
spin_lock_irqsave(&(intf->seq_lock), flags);
/*
* We do this verification because the user can be deleted
* while a message is outstanding.
*/
if ((intf->seq_table[seq].inuse)
&& (intf->seq_table[seq].seqid == seqid)) {
struct seq_table *ent = &(intf->seq_table[seq]);
ent->timeout = ent->orig_timeout;
rv = 0;
}
spin_unlock_irqrestore(&(intf->seq_lock), flags);
return rv;
}
/* Got an error for the send message for a specific sequence number. */
static int intf_err_seq(ipmi_smi_t intf,
long msgid,
unsigned int err)
{
int rv = -ENODEV;
unsigned long flags;
unsigned char seq;
unsigned long seqid;
struct ipmi_recv_msg *msg = NULL;
GET_SEQ_FROM_MSGID(msgid, seq, seqid);
spin_lock_irqsave(&(intf->seq_lock), flags);
/*
* We do this verification because the user can be deleted
* while a message is outstanding.
*/
if ((intf->seq_table[seq].inuse)
&& (intf->seq_table[seq].seqid == seqid)) {
struct seq_table *ent = &(intf->seq_table[seq]);
ent->inuse = 0;
msg = ent->recv_msg;
rv = 0;
}
spin_unlock_irqrestore(&(intf->seq_lock), flags);
if (msg)
deliver_err_response(msg, err);
return rv;
}
int ipmi_create_user(unsigned int if_num,
struct ipmi_user_hndl *handler,
void *handler_data,
ipmi_user_t *user)
{
unsigned long flags;
ipmi_user_t new_user;
int rv = 0;
ipmi_smi_t intf;
/*
* There is no module usecount here, because it's not
* required. Since this can only be used by and called from
* other modules, they will implicitly use this module, and
* thus this can't be removed unless the other modules are
* removed.
*/
if (handler == NULL)
return -EINVAL;
/*
* Make sure the driver is actually initialized, this handles
* problems with initialization order.
*/
if (!initialized) {
rv = ipmi_init_msghandler();
if (rv)
return rv;
/*
* The init code doesn't return an error if it was turned
* off, but it won't initialize. Check that.
*/
if (!initialized)
return -ENODEV;
}
new_user = kmalloc(sizeof(*new_user), GFP_KERNEL);
if (!new_user)
return -ENOMEM;
mutex_lock(&ipmi_interfaces_mutex);
list_for_each_entry_rcu(intf, &ipmi_interfaces, link) {
if (intf->intf_num == if_num)
goto found;
}
/* Not found, return an error */
rv = -EINVAL;
goto out_kfree;
found:
/* Note that each existing user holds a refcount to the interface. */
kref_get(&intf->refcount);
kref_init(&new_user->refcount);
new_user->handler = handler;
new_user->handler_data = handler_data;
new_user->intf = intf;
new_user->gets_events = false;
if (!try_module_get(intf->handlers->owner)) {
rv = -ENODEV;
goto out_kref;
}
if (intf->handlers->inc_usecount) {
rv = intf->handlers->inc_usecount(intf->send_info);
if (rv) {
module_put(intf->handlers->owner);
goto out_kref;
}
}
/*
* Hold the lock so intf->handlers is guaranteed to be good
* until now
*/
mutex_unlock(&ipmi_interfaces_mutex);
new_user->valid = true;
spin_lock_irqsave(&intf->seq_lock, flags);
list_add_rcu(&new_user->link, &intf->users);
spin_unlock_irqrestore(&intf->seq_lock, flags);
if (handler->ipmi_watchdog_pretimeout) {
/* User wants pretimeouts, so make sure to watch for them. */
if (atomic_inc_return(&intf->event_waiters) == 1)
need_waiter(intf);
}
*user = new_user;
return 0;
out_kref:
kref_put(&intf->refcount, intf_free);
out_kfree:
mutex_unlock(&ipmi_interfaces_mutex);
kfree(new_user);
return rv;
}
EXPORT_SYMBOL(ipmi_create_user);
int ipmi_get_smi_info(int if_num, struct ipmi_smi_info *data)
{
int rv = 0;
ipmi_smi_t intf;
const struct ipmi_smi_handlers *handlers;
mutex_lock(&ipmi_interfaces_mutex);
list_for_each_entry_rcu(intf, &ipmi_interfaces, link) {
if (intf->intf_num == if_num)
goto found;
}
/* Not found, return an error */
rv = -EINVAL;
mutex_unlock(&ipmi_interfaces_mutex);
return rv;
found:
handlers = intf->handlers;
rv = -ENOSYS;
if (handlers->get_smi_info)
rv = handlers->get_smi_info(intf->send_info, data);
mutex_unlock(&ipmi_interfaces_mutex);
return rv;
}
EXPORT_SYMBOL(ipmi_get_smi_info);
static void free_user(struct kref *ref)
{
ipmi_user_t user = container_of(ref, struct ipmi_user, refcount);
kfree(user);
}
int ipmi_destroy_user(ipmi_user_t user)
{
ipmi_smi_t intf = user->intf;
int i;
unsigned long flags;
struct cmd_rcvr *rcvr;
struct cmd_rcvr *rcvrs = NULL;
user->valid = false;
if (user->handler->ipmi_watchdog_pretimeout)
atomic_dec(&intf->event_waiters);
if (user->gets_events)
atomic_dec(&intf->event_waiters);
/* Remove the user from the interface's sequence table. */
spin_lock_irqsave(&intf->seq_lock, flags);
list_del_rcu(&user->link);
for (i = 0; i < IPMI_IPMB_NUM_SEQ; i++) {
if (intf->seq_table[i].inuse
&& (intf->seq_table[i].recv_msg->user == user)) {
intf->seq_table[i].inuse = 0;
ipmi_free_recv_msg(intf->seq_table[i].recv_msg);
}
}
spin_unlock_irqrestore(&intf->seq_lock, flags);
/*
* Remove the user from the command receiver's table. First
* we build a list of everything (not using the standard link,
* since other things may be using it till we do
* synchronize_rcu()) then free everything in that list.
*/
mutex_lock(&intf->cmd_rcvrs_mutex);
list_for_each_entry_rcu(rcvr, &intf->cmd_rcvrs, link) {
if (rcvr->user == user) {
list_del_rcu(&rcvr->link);
rcvr->next = rcvrs;
rcvrs = rcvr;
}
}
mutex_unlock(&intf->cmd_rcvrs_mutex);
synchronize_rcu();
while (rcvrs) {
rcvr = rcvrs;
rcvrs = rcvr->next;
kfree(rcvr);
}
mutex_lock(&ipmi_interfaces_mutex);
if (intf->handlers) {
module_put(intf->handlers->owner);
if (intf->handlers->dec_usecount)
intf->handlers->dec_usecount(intf->send_info);
}
mutex_unlock(&ipmi_interfaces_mutex);
kref_put(&intf->refcount, intf_free);
kref_put(&user->refcount, free_user);
return 0;
}
EXPORT_SYMBOL(ipmi_destroy_user);
void ipmi_get_version(ipmi_user_t user,
unsigned char *major,
unsigned char *minor)
{
*major = user->intf->ipmi_version_major;
*minor = user->intf->ipmi_version_minor;
}
EXPORT_SYMBOL(ipmi_get_version);
int ipmi_set_my_address(ipmi_user_t user,
unsigned int channel,
unsigned char address)
{
if (channel >= IPMI_MAX_CHANNELS)
return -EINVAL;
user->intf->channels[channel].address = address;
return 0;
}
EXPORT_SYMBOL(ipmi_set_my_address);
int ipmi_get_my_address(ipmi_user_t user,
unsigned int channel,
unsigned char *address)
{
if (channel >= IPMI_MAX_CHANNELS)
return -EINVAL;
*address = user->intf->channels[channel].address;
return 0;
}
EXPORT_SYMBOL(ipmi_get_my_address);
int ipmi_set_my_LUN(ipmi_user_t user,
unsigned int channel,
unsigned char LUN)
{
if (channel >= IPMI_MAX_CHANNELS)
return -EINVAL;
user->intf->channels[channel].lun = LUN & 0x3;
return 0;
}
EXPORT_SYMBOL(ipmi_set_my_LUN);
int ipmi_get_my_LUN(ipmi_user_t user,
unsigned int channel,
unsigned char *address)
{
if (channel >= IPMI_MAX_CHANNELS)
return -EINVAL;
*address = user->intf->channels[channel].lun;
return 0;
}
EXPORT_SYMBOL(ipmi_get_my_LUN);
int ipmi_get_maintenance_mode(ipmi_user_t user)
{
int mode;
unsigned long flags;
spin_lock_irqsave(&user->intf->maintenance_mode_lock, flags);
mode = user->intf->maintenance_mode;
spin_unlock_irqrestore(&user->intf->maintenance_mode_lock, flags);
return mode;
}
EXPORT_SYMBOL(ipmi_get_maintenance_mode);
static void maintenance_mode_update(ipmi_smi_t intf)
{
if (intf->handlers->set_maintenance_mode)
intf->handlers->set_maintenance_mode(
intf->send_info, intf->maintenance_mode_enable);
}
int ipmi_set_maintenance_mode(ipmi_user_t user, int mode)
{
int rv = 0;
unsigned long flags;
ipmi_smi_t intf = user->intf;
spin_lock_irqsave(&intf->maintenance_mode_lock, flags);
if (intf->maintenance_mode != mode) {
switch (mode) {
case IPMI_MAINTENANCE_MODE_AUTO:
intf->maintenance_mode_enable
= (intf->auto_maintenance_timeout > 0);
break;
case IPMI_MAINTENANCE_MODE_OFF:
intf->maintenance_mode_enable = false;
break;
case IPMI_MAINTENANCE_MODE_ON:
intf->maintenance_mode_enable = true;
break;
default:
rv = -EINVAL;
goto out_unlock;
}
intf->maintenance_mode = mode;
maintenance_mode_update(intf);
}
out_unlock:
spin_unlock_irqrestore(&intf->maintenance_mode_lock, flags);
return rv;
}
EXPORT_SYMBOL(ipmi_set_maintenance_mode);
int ipmi_set_gets_events(ipmi_user_t user, bool val)
{
unsigned long flags;
ipmi_smi_t intf = user->intf;
struct ipmi_recv_msg *msg, *msg2;
struct list_head msgs;
INIT_LIST_HEAD(&msgs);
spin_lock_irqsave(&intf->events_lock, flags);
if (user->gets_events == val)
goto out;
user->gets_events = val;
if (val) {
if (atomic_inc_return(&intf->event_waiters) == 1)
need_waiter(intf);
} else {
atomic_dec(&intf->event_waiters);
}
if (intf->delivering_events)
/*
* Another thread is delivering events for this, so
* let it handle any new events.
*/
goto out;
/* Deliver any queued events. */
while (user->gets_events && !list_empty(&intf->waiting_events)) {
list_for_each_entry_safe(msg, msg2, &intf->waiting_events, link)
list_move_tail(&msg->link, &msgs);
intf->waiting_events_count = 0;
if (intf->event_msg_printed) {
printk(KERN_WARNING PFX "Event queue no longer"
" full\n");
intf->event_msg_printed = 0;
}
intf->delivering_events = 1;
spin_unlock_irqrestore(&intf->events_lock, flags);
list_for_each_entry_safe(msg, msg2, &msgs, link) {
msg->user = user;
kref_get(&user->refcount);
deliver_response(msg);
}
spin_lock_irqsave(&intf->events_lock, flags);
intf->delivering_events = 0;
}
out:
spin_unlock_irqrestore(&intf->events_lock, flags);
return 0;
}
EXPORT_SYMBOL(ipmi_set_gets_events);
static struct cmd_rcvr *find_cmd_rcvr(ipmi_smi_t intf,
unsigned char netfn,
unsigned char cmd,
unsigned char chan)
{
struct cmd_rcvr *rcvr;
list_for_each_entry_rcu(rcvr, &intf->cmd_rcvrs, link) {
if ((rcvr->netfn == netfn) && (rcvr->cmd == cmd)
&& (rcvr->chans & (1 << chan)))
return rcvr;
}
return NULL;
}
static int is_cmd_rcvr_exclusive(ipmi_smi_t intf,
unsigned char netfn,
unsigned char cmd,
unsigned int chans)
{
struct cmd_rcvr *rcvr;
list_for_each_entry_rcu(rcvr, &intf->cmd_rcvrs, link) {
if ((rcvr->netfn == netfn) && (rcvr->cmd == cmd)
&& (rcvr->chans & chans))
return 0;
}
return 1;
}
int ipmi_register_for_cmd(ipmi_user_t user,
unsigned char netfn,
unsigned char cmd,
unsigned int chans)
{
ipmi_smi_t intf = user->intf;
struct cmd_rcvr *rcvr;
int rv = 0;
rcvr = kmalloc(sizeof(*rcvr), GFP_KERNEL);
if (!rcvr)
return -ENOMEM;
rcvr->cmd = cmd;
rcvr->netfn = netfn;
rcvr->chans = chans;
rcvr->user = user;
mutex_lock(&intf->cmd_rcvrs_mutex);
/* Make sure the command/netfn is not already registered. */
if (!is_cmd_rcvr_exclusive(intf, netfn, cmd, chans)) {
rv = -EBUSY;
goto out_unlock;
}
if (atomic_inc_return(&intf->event_waiters) == 1)
need_waiter(intf);
list_add_rcu(&rcvr->link, &intf->cmd_rcvrs);
out_unlock:
mutex_unlock(&intf->cmd_rcvrs_mutex);
if (rv)
kfree(rcvr);
return rv;
}
EXPORT_SYMBOL(ipmi_register_for_cmd);
int ipmi_unregister_for_cmd(ipmi_user_t user,
unsigned char netfn,
unsigned char cmd,
unsigned int chans)
{
ipmi_smi_t intf = user->intf;
struct cmd_rcvr *rcvr;
struct cmd_rcvr *rcvrs = NULL;
int i, rv = -ENOENT;
mutex_lock(&intf->cmd_rcvrs_mutex);
for (i = 0; i < IPMI_NUM_CHANNELS; i++) {
if (((1 << i) & chans) == 0)
continue;
rcvr = find_cmd_rcvr(intf, netfn, cmd, i);
if (rcvr == NULL)
continue;
if (rcvr->user == user) {
rv = 0;
rcvr->chans &= ~chans;
if (rcvr->chans == 0) {
list_del_rcu(&rcvr->link);
rcvr->next = rcvrs;
rcvrs = rcvr;
}
}
}
mutex_unlock(&intf->cmd_rcvrs_mutex);
synchronize_rcu();
while (rcvrs) {
atomic_dec(&intf->event_waiters);
rcvr = rcvrs;
rcvrs = rcvr->next;
kfree(rcvr);
}
return rv;
}
EXPORT_SYMBOL(ipmi_unregister_for_cmd);
static unsigned char
ipmb_checksum(unsigned char *data, int size)
{
unsigned char csum = 0;
for (; size > 0; size--, data++)
csum += *data;
return -csum;
}
static inline void format_ipmb_msg(struct ipmi_smi_msg *smi_msg,
struct kernel_ipmi_msg *msg,
struct ipmi_ipmb_addr *ipmb_addr,
long msgid,
unsigned char ipmb_seq,
int broadcast,
unsigned char source_address,
unsigned char source_lun)
{
int i = broadcast;
/* Format the IPMB header data. */
smi_msg->data[0] = (IPMI_NETFN_APP_REQUEST << 2);
smi_msg->data[1] = IPMI_SEND_MSG_CMD;
smi_msg->data[2] = ipmb_addr->channel;
if (broadcast)
smi_msg->data[3] = 0;
smi_msg->data[i+3] = ipmb_addr->slave_addr;
smi_msg->data[i+4] = (msg->netfn << 2) | (ipmb_addr->lun & 0x3);
smi_msg->data[i+5] = ipmb_checksum(&(smi_msg->data[i+3]), 2);
smi_msg->data[i+6] = source_address;
smi_msg->data[i+7] = (ipmb_seq << 2) | source_lun;
smi_msg->data[i+8] = msg->cmd;
/* Now tack on the data to the message. */
if (msg->data_len > 0)
memcpy(&(smi_msg->data[i+9]), msg->data,
msg->data_len);
smi_msg->data_size = msg->data_len + 9;
/* Now calculate the checksum and tack it on. */
smi_msg->data[i+smi_msg->data_size]
= ipmb_checksum(&(smi_msg->data[i+6]),
smi_msg->data_size-6);
/*
* Add on the checksum size and the offset from the
* broadcast.
*/
smi_msg->data_size += 1 + i;
smi_msg->msgid = msgid;
}
static inline void format_lan_msg(struct ipmi_smi_msg *smi_msg,
struct kernel_ipmi_msg *msg,
struct ipmi_lan_addr *lan_addr,
long msgid,
unsigned char ipmb_seq,
unsigned char source_lun)
{
/* Format the IPMB header data. */
smi_msg->data[0] = (IPMI_NETFN_APP_REQUEST << 2);
smi_msg->data[1] = IPMI_SEND_MSG_CMD;
smi_msg->data[2] = lan_addr->channel;
smi_msg->data[3] = lan_addr->session_handle;
smi_msg->data[4] = lan_addr->remote_SWID;
smi_msg->data[5] = (msg->netfn << 2) | (lan_addr->lun & 0x3);
smi_msg->data[6] = ipmb_checksum(&(smi_msg->data[4]), 2);
smi_msg->data[7] = lan_addr->local_SWID;
smi_msg->data[8] = (ipmb_seq << 2) | source_lun;
smi_msg->data[9] = msg->cmd;
/* Now tack on the data to the message. */
if (msg->data_len > 0)
memcpy(&(smi_msg->data[10]), msg->data,
msg->data_len);
smi_msg->data_size = msg->data_len + 10;
/* Now calculate the checksum and tack it on. */
smi_msg->data[smi_msg->data_size]
= ipmb_checksum(&(smi_msg->data[7]),
smi_msg->data_size-7);
/*
* Add on the checksum size and the offset from the
* broadcast.
*/
smi_msg->data_size += 1;
smi_msg->msgid = msgid;
}
static struct ipmi_smi_msg *smi_add_send_msg(ipmi_smi_t intf,
struct ipmi_smi_msg *smi_msg,
int priority)
{
if (intf->curr_msg) {
if (priority > 0)
list_add_tail(&smi_msg->link, &intf->hp_xmit_msgs);
else
list_add_tail(&smi_msg->link, &intf->xmit_msgs);
smi_msg = NULL;
} else {
intf->curr_msg = smi_msg;
}
return smi_msg;
}
static void smi_send(ipmi_smi_t intf, const struct ipmi_smi_handlers *handlers,
struct ipmi_smi_msg *smi_msg, int priority)
{
int run_to_completion = intf->run_to_completion;
if (run_to_completion) {
smi_msg = smi_add_send_msg(intf, smi_msg, priority);
} else {
unsigned long flags;
spin_lock_irqsave(&intf->xmit_msgs_lock, flags);
smi_msg = smi_add_send_msg(intf, smi_msg, priority);
spin_unlock_irqrestore(&intf->xmit_msgs_lock, flags);
}
if (smi_msg)
handlers->sender(intf->send_info, smi_msg);
}
/*
* Separate from ipmi_request so that the user does not have to be
* supplied in certain circumstances (mainly at panic time). If
* messages are supplied, they will be freed, even if an error
* occurs.
*/
static int i_ipmi_request(ipmi_user_t user,
ipmi_smi_t intf,
struct ipmi_addr *addr,
long msgid,
struct kernel_ipmi_msg *msg,
void *user_msg_data,
void *supplied_smi,
struct ipmi_recv_msg *supplied_recv,
int priority,
unsigned char source_address,
unsigned char source_lun,
int retries,
unsigned int retry_time_ms)
{
int rv = 0;
struct ipmi_smi_msg *smi_msg;
struct ipmi_recv_msg *recv_msg;
unsigned long flags;
if (supplied_recv)
recv_msg = supplied_recv;
else {
recv_msg = ipmi_alloc_recv_msg();
if (recv_msg == NULL)
return -ENOMEM;
}
recv_msg->user_msg_data = user_msg_data;
if (supplied_smi)
smi_msg = (struct ipmi_smi_msg *) supplied_smi;
else {
smi_msg = ipmi_alloc_smi_msg();
if (smi_msg == NULL) {
ipmi_free_recv_msg(recv_msg);
return -ENOMEM;
}
}
rcu_read_lock();
if (intf->in_shutdown) {
rv = -ENODEV;
goto out_err;
}
recv_msg->user = user;
if (user)
kref_get(&user->refcount);
recv_msg->msgid = msgid;
/*
* Store the message to send in the receive message so timeout
* responses can get the proper response data.
*/
recv_msg->msg = *msg;
if (addr->addr_type == IPMI_SYSTEM_INTERFACE_ADDR_TYPE) {
struct ipmi_system_interface_addr *smi_addr;
if (msg->netfn & 1) {
/* Responses are not allowed to the SMI. */
rv = -EINVAL;
goto out_err;
}
smi_addr = (struct ipmi_system_interface_addr *) addr;
if (smi_addr->lun > 3) {
ipmi_inc_stat(intf, sent_invalid_commands);
rv = -EINVAL;
goto out_err;
}
memcpy(&recv_msg->addr, smi_addr, sizeof(*smi_addr));
if ((msg->netfn == IPMI_NETFN_APP_REQUEST)
&& ((msg->cmd == IPMI_SEND_MSG_CMD)
|| (msg->cmd == IPMI_GET_MSG_CMD)
|| (msg->cmd == IPMI_READ_EVENT_MSG_BUFFER_CMD))) {
/*
* We don't let the user do these, since we manage
* the sequence numbers.
*/
ipmi_inc_stat(intf, sent_invalid_commands);
rv = -EINVAL;
goto out_err;
}
if (((msg->netfn == IPMI_NETFN_APP_REQUEST)
&& ((msg->cmd == IPMI_COLD_RESET_CMD)
|| (msg->cmd == IPMI_WARM_RESET_CMD)))
|| (msg->netfn == IPMI_NETFN_FIRMWARE_REQUEST)) {
spin_lock_irqsave(&intf->maintenance_mode_lock, flags);
intf->auto_maintenance_timeout
= IPMI_MAINTENANCE_MODE_TIMEOUT;
if (!intf->maintenance_mode
&& !intf->maintenance_mode_enable) {
intf->maintenance_mode_enable = true;
maintenance_mode_update(intf);
}
spin_unlock_irqrestore(&intf->maintenance_mode_lock,
flags);
}
if ((msg->data_len + 2) > IPMI_MAX_MSG_LENGTH) {
ipmi_inc_stat(intf, sent_invalid_commands);
rv = -EMSGSIZE;
goto out_err;
}
smi_msg->data[0] = (msg->netfn << 2) | (smi_addr->lun & 0x3);
smi_msg->data[1] = msg->cmd;
smi_msg->msgid = msgid;
smi_msg->user_data = recv_msg;
if (msg->data_len > 0)
memcpy(&(smi_msg->data[2]), msg->data, msg->data_len);
smi_msg->data_size = msg->data_len + 2;
ipmi_inc_stat(intf, sent_local_commands);
} else if (is_ipmb_addr(addr) || is_ipmb_bcast_addr(addr)) {
struct ipmi_ipmb_addr *ipmb_addr;
unsigned char ipmb_seq;
long seqid;
int broadcast = 0;
if (addr->channel >= IPMI_MAX_CHANNELS) {
ipmi_inc_stat(intf, sent_invalid_commands);
rv = -EINVAL;
goto out_err;
}
if (intf->channels[addr->channel].medium
!= IPMI_CHANNEL_MEDIUM_IPMB) {
ipmi_inc_stat(intf, sent_invalid_commands);
rv = -EINVAL;
goto out_err;
}
if (retries < 0) {
if (addr->addr_type == IPMI_IPMB_BROADCAST_ADDR_TYPE)
retries = 0; /* Don't retry broadcasts. */
else
retries = 4;
}
if (addr->addr_type == IPMI_IPMB_BROADCAST_ADDR_TYPE) {
/*
* Broadcasts add a zero at the beginning of the
* message, but otherwise is the same as an IPMB
* address.
*/
addr->addr_type = IPMI_IPMB_ADDR_TYPE;
broadcast = 1;
}
/* Default to 1 second retries. */
if (retry_time_ms == 0)
retry_time_ms = 1000;
/*
* 9 for the header and 1 for the checksum, plus
* possibly one for the broadcast.
*/
if ((msg->data_len + 10 + broadcast) > IPMI_MAX_MSG_LENGTH) {
ipmi_inc_stat(intf, sent_invalid_commands);
rv = -EMSGSIZE;
goto out_err;
}
ipmb_addr = (struct ipmi_ipmb_addr *) addr;
if (ipmb_addr->lun > 3) {
ipmi_inc_stat(intf, sent_invalid_commands);
rv = -EINVAL;
goto out_err;
}
memcpy(&recv_msg->addr, ipmb_addr, sizeof(*ipmb_addr));
if (recv_msg->msg.netfn & 0x1) {
/*
* It's a response, so use the user's sequence
* from msgid.
*/
ipmi_inc_stat(intf, sent_ipmb_responses);
format_ipmb_msg(smi_msg, msg, ipmb_addr, msgid,
msgid, broadcast,
source_address, source_lun);
/*
* Save the receive message so we can use it
* to deliver the response.
*/
smi_msg->user_data = recv_msg;
} else {
/* It's a command, so get a sequence for it. */
spin_lock_irqsave(&(intf->seq_lock), flags);
/*
* Create a sequence number with a 1 second
* timeout and 4 retries.
*/
rv = intf_next_seq(intf,
recv_msg,
retry_time_ms,
retries,
broadcast,
&ipmb_seq,
&seqid);
if (rv) {
/*
* We have used up all the sequence numbers,
* probably, so abort.
*/
spin_unlock_irqrestore(&(intf->seq_lock),
flags);
goto out_err;
}
ipmi_inc_stat(intf, sent_ipmb_commands);
/*
* Store the sequence number in the message,
* so that when the send message response
* comes back we can start the timer.
*/
format_ipmb_msg(smi_msg, msg, ipmb_addr,
STORE_SEQ_IN_MSGID(ipmb_seq, seqid),
ipmb_seq, broadcast,
source_address, source_lun);
/*
* Copy the message into the recv message data, so we
* can retransmit it later if necessary.
*/
memcpy(recv_msg->msg_data, smi_msg->data,
smi_msg->data_size);
recv_msg->msg.data = recv_msg->msg_data;
recv_msg->msg.data_len = smi_msg->data_size;
/*
* We don't unlock until here, because we need
* to copy the completed message into the
* recv_msg before we release the lock.
* Otherwise, race conditions may bite us. I
* know that's pretty paranoid, but I prefer
* to be correct.
*/
spin_unlock_irqrestore(&(intf->seq_lock), flags);
}
} else if (is_lan_addr(addr)) {
struct ipmi_lan_addr *lan_addr;
unsigned char ipmb_seq;
long seqid;
if (addr->channel >= IPMI_MAX_CHANNELS) {
ipmi_inc_stat(intf, sent_invalid_commands);
rv = -EINVAL;
goto out_err;
}
if ((intf->channels[addr->channel].medium
!= IPMI_CHANNEL_MEDIUM_8023LAN)
&& (intf->channels[addr->channel].medium
!= IPMI_CHANNEL_MEDIUM_ASYNC)) {
ipmi_inc_stat(intf, sent_invalid_commands);
rv = -EINVAL;
goto out_err;
}
retries = 4;
/* Default to 1 second retries. */
if (retry_time_ms == 0)
retry_time_ms = 1000;
/* 11 for the header and 1 for the checksum. */
if ((msg->data_len + 12) > IPMI_MAX_MSG_LENGTH) {
ipmi_inc_stat(intf, sent_invalid_commands);
rv = -EMSGSIZE;
goto out_err;
}
lan_addr = (struct ipmi_lan_addr *) addr;
if (lan_addr->lun > 3) {
ipmi_inc_stat(intf, sent_invalid_commands);
rv = -EINVAL;
goto out_err;
}
memcpy(&recv_msg->addr, lan_addr, sizeof(*lan_addr));
if (recv_msg->msg.netfn & 0x1) {
/*
* It's a response, so use the user's sequence
* from msgid.
*/
ipmi_inc_stat(intf, sent_lan_responses);
format_lan_msg(smi_msg, msg, lan_addr, msgid,
msgid, source_lun);
/*
* Save the receive message so we can use it
* to deliver the response.
*/
smi_msg->user_data = recv_msg;
} else {
/* It's a command, so get a sequence for it. */
spin_lock_irqsave(&(intf->seq_lock), flags);
/*
* Create a sequence number with a 1 second
* timeout and 4 retries.
*/
rv = intf_next_seq(intf,
recv_msg,
retry_time_ms,
retries,
0,
&ipmb_seq,
&seqid);
if (rv) {
/*
* We have used up all the sequence numbers,
* probably, so abort.
*/
spin_unlock_irqrestore(&(intf->seq_lock),
flags);
goto out_err;
}
ipmi_inc_stat(intf, sent_lan_commands);
/*
* Store the sequence number in the message,
* so that when the send message response
* comes back we can start the timer.
*/
format_lan_msg(smi_msg, msg, lan_addr,
STORE_SEQ_IN_MSGID(ipmb_seq, seqid),
ipmb_seq, source_lun);
/*
* Copy the message into the recv message data, so we
* can retransmit it later if necessary.
*/
memcpy(recv_msg->msg_data, smi_msg->data,
smi_msg->data_size);
recv_msg->msg.data = recv_msg->msg_data;
recv_msg->msg.data_len = smi_msg->data_size;
/*
* We don't unlock until here, because we need
* to copy the completed message into the
* recv_msg before we release the lock.
* Otherwise, race conditions may bite us. I
* know that's pretty paranoid, but I prefer
* to be correct.
*/
spin_unlock_irqrestore(&(intf->seq_lock), flags);
}
} else {
/* Unknown address type. */
ipmi_inc_stat(intf, sent_invalid_commands);
rv = -EINVAL;
goto out_err;
}
#ifdef DEBUG_MSGING
{
int m;
for (m = 0; m < smi_msg->data_size; m++)
printk(" %2.2x", smi_msg->data[m]);
printk("\n");
}
#endif
smi_send(intf, intf->handlers, smi_msg, priority);
rcu_read_unlock();
return 0;
out_err:
rcu_read_unlock();
ipmi_free_smi_msg(smi_msg);
ipmi_free_recv_msg(recv_msg);
return rv;
}
static int check_addr(ipmi_smi_t intf,
struct ipmi_addr *addr,
unsigned char *saddr,
unsigned char *lun)
{
if (addr->channel >= IPMI_MAX_CHANNELS)
return -EINVAL;
*lun = intf->channels[addr->channel].lun;
*saddr = intf->channels[addr->channel].address;
return 0;
}
int ipmi_request_settime(ipmi_user_t user,
struct ipmi_addr *addr,
long msgid,
struct kernel_ipmi_msg *msg,
void *user_msg_data,
int priority,
int retries,
unsigned int retry_time_ms)
{
unsigned char saddr = 0, lun = 0;
int rv;
if (!user)
return -EINVAL;
rv = check_addr(user->intf, addr, &saddr, &lun);
if (rv)
return rv;
return i_ipmi_request(user,
user->intf,
addr,
msgid,
msg,
user_msg_data,
NULL, NULL,
priority,
saddr,
lun,
retries,
retry_time_ms);
}
EXPORT_SYMBOL(ipmi_request_settime);
int ipmi_request_supply_msgs(ipmi_user_t user,
struct ipmi_addr *addr,
long msgid,
struct kernel_ipmi_msg *msg,
void *user_msg_data,
void *supplied_smi,
struct ipmi_recv_msg *supplied_recv,
int priority)
{
unsigned char saddr = 0, lun = 0;
int rv;
if (!user)
return -EINVAL;
rv = check_addr(user->intf, addr, &saddr, &lun);
if (rv)
return rv;
return i_ipmi_request(user,
user->intf,
addr,
msgid,
msg,
user_msg_data,
supplied_smi,
supplied_recv,
priority,
saddr,
lun,
-1, 0);
}
EXPORT_SYMBOL(ipmi_request_supply_msgs);
#ifdef CONFIG_PROC_FS
static int smi_ipmb_proc_show(struct seq_file *m, void *v)
{
ipmi_smi_t intf = m->private;
int i;
seq_printf(m, "%x", intf->channels[0].address);
for (i = 1; i < IPMI_MAX_CHANNELS; i++)
seq_printf(m, " %x", intf->channels[i].address);
seq_putc(m, '\n');
return 0;
}
static int smi_ipmb_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, smi_ipmb_proc_show, PDE_DATA(inode));
}
static const struct file_operations smi_ipmb_proc_ops = {
.open = smi_ipmb_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int smi_version_proc_show(struct seq_file *m, void *v)
{
ipmi_smi_t intf = m->private;
seq_printf(m, "%u.%u\n",
ipmi_version_major(&intf->bmc->id),
ipmi_version_minor(&intf->bmc->id));
return 0;
}
static int smi_version_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, smi_version_proc_show, PDE_DATA(inode));
}
static const struct file_operations smi_version_proc_ops = {
.open = smi_version_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int smi_stats_proc_show(struct seq_file *m, void *v)
{
ipmi_smi_t intf = m->private;
seq_printf(m, "sent_invalid_commands: %u\n",
ipmi_get_stat(intf, sent_invalid_commands));
seq_printf(m, "sent_local_commands: %u\n",
ipmi_get_stat(intf, sent_local_commands));
seq_printf(m, "handled_local_responses: %u\n",
ipmi_get_stat(intf, handled_local_responses));
seq_printf(m, "unhandled_local_responses: %u\n",
ipmi_get_stat(intf, unhandled_local_responses));
seq_printf(m, "sent_ipmb_commands: %u\n",
ipmi_get_stat(intf, sent_ipmb_commands));
seq_printf(m, "sent_ipmb_command_errs: %u\n",
ipmi_get_stat(intf, sent_ipmb_command_errs));
seq_printf(m, "retransmitted_ipmb_commands: %u\n",
ipmi_get_stat(intf, retransmitted_ipmb_commands));
seq_printf(m, "timed_out_ipmb_commands: %u\n",
ipmi_get_stat(intf, timed_out_ipmb_commands));
seq_printf(m, "timed_out_ipmb_broadcasts: %u\n",
ipmi_get_stat(intf, timed_out_ipmb_broadcasts));
seq_printf(m, "sent_ipmb_responses: %u\n",
ipmi_get_stat(intf, sent_ipmb_responses));
seq_printf(m, "handled_ipmb_responses: %u\n",
ipmi_get_stat(intf, handled_ipmb_responses));
seq_printf(m, "invalid_ipmb_responses: %u\n",
ipmi_get_stat(intf, invalid_ipmb_responses));
seq_printf(m, "unhandled_ipmb_responses: %u\n",
ipmi_get_stat(intf, unhandled_ipmb_responses));
seq_printf(m, "sent_lan_commands: %u\n",
ipmi_get_stat(intf, sent_lan_commands));
seq_printf(m, "sent_lan_command_errs: %u\n",
ipmi_get_stat(intf, sent_lan_command_errs));
seq_printf(m, "retransmitted_lan_commands: %u\n",
ipmi_get_stat(intf, retransmitted_lan_commands));
seq_printf(m, "timed_out_lan_commands: %u\n",
ipmi_get_stat(intf, timed_out_lan_commands));
seq_printf(m, "sent_lan_responses: %u\n",
ipmi_get_stat(intf, sent_lan_responses));
seq_printf(m, "handled_lan_responses: %u\n",
ipmi_get_stat(intf, handled_lan_responses));
seq_printf(m, "invalid_lan_responses: %u\n",
ipmi_get_stat(intf, invalid_lan_responses));
seq_printf(m, "unhandled_lan_responses: %u\n",
ipmi_get_stat(intf, unhandled_lan_responses));
seq_printf(m, "handled_commands: %u\n",
ipmi_get_stat(intf, handled_commands));
seq_printf(m, "invalid_commands: %u\n",
ipmi_get_stat(intf, invalid_commands));
seq_printf(m, "unhandled_commands: %u\n",
ipmi_get_stat(intf, unhandled_commands));
seq_printf(m, "invalid_events: %u\n",
ipmi_get_stat(intf, invalid_events));
seq_printf(m, "events: %u\n",
ipmi_get_stat(intf, events));
seq_printf(m, "failed rexmit LAN msgs: %u\n",
ipmi_get_stat(intf, dropped_rexmit_lan_commands));
seq_printf(m, "failed rexmit IPMB msgs: %u\n",
ipmi_get_stat(intf, dropped_rexmit_ipmb_commands));
return 0;
}
static int smi_stats_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, smi_stats_proc_show, PDE_DATA(inode));
}
static const struct file_operations smi_stats_proc_ops = {
.open = smi_stats_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
#endif /* CONFIG_PROC_FS */
int ipmi_smi_add_proc_entry(ipmi_smi_t smi, char *name,
const struct file_operations *proc_ops,
void *data)
{
int rv = 0;
#ifdef CONFIG_PROC_FS
struct proc_dir_entry *file;
struct ipmi_proc_entry *entry;
/* Create a list element. */
entry = kmalloc(sizeof(*entry), GFP_KERNEL);
if (!entry)
return -ENOMEM;
entry->name = kstrdup(name, GFP_KERNEL);
if (!entry->name) {
kfree(entry);
return -ENOMEM;
}
file = proc_create_data(name, 0, smi->proc_dir, proc_ops, data);
if (!file) {
kfree(entry->name);
kfree(entry);
rv = -ENOMEM;
} else {
mutex_lock(&smi->proc_entry_lock);
/* Stick it on the list. */
entry->next = smi->proc_entries;
smi->proc_entries = entry;
mutex_unlock(&smi->proc_entry_lock);
}
#endif /* CONFIG_PROC_FS */
return rv;
}
EXPORT_SYMBOL(ipmi_smi_add_proc_entry);
static int add_proc_entries(ipmi_smi_t smi, int num)
{
int rv = 0;
#ifdef CONFIG_PROC_FS
sprintf(smi->proc_dir_name, "%d", num);
smi->proc_dir = proc_mkdir(smi->proc_dir_name, proc_ipmi_root);
if (!smi->proc_dir)
rv = -ENOMEM;
if (rv == 0)
rv = ipmi_smi_add_proc_entry(smi, "stats",
&smi_stats_proc_ops,
smi);
if (rv == 0)
rv = ipmi_smi_add_proc_entry(smi, "ipmb",
&smi_ipmb_proc_ops,
smi);
if (rv == 0)
rv = ipmi_smi_add_proc_entry(smi, "version",
&smi_version_proc_ops,
smi);
#endif /* CONFIG_PROC_FS */
return rv;
}
static void remove_proc_entries(ipmi_smi_t smi)
{
#ifdef CONFIG_PROC_FS
struct ipmi_proc_entry *entry;
mutex_lock(&smi->proc_entry_lock);
while (smi->proc_entries) {
entry = smi->proc_entries;
smi->proc_entries = entry->next;
remove_proc_entry(entry->name, smi->proc_dir);
kfree(entry->name);
kfree(entry);
}
mutex_unlock(&smi->proc_entry_lock);
remove_proc_entry(smi->proc_dir_name, proc_ipmi_root);
#endif /* CONFIG_PROC_FS */
}
static int __find_bmc_guid(struct device *dev, void *data)
{
unsigned char *id = data;
struct bmc_device *bmc = to_bmc_device(dev);
return memcmp(bmc->guid, id, 16) == 0;
}
static struct bmc_device *ipmi_find_bmc_guid(struct device_driver *drv,
unsigned char *guid)
{
struct device *dev;
dev = driver_find_device(drv, NULL, guid, __find_bmc_guid);
if (dev)
return to_bmc_device(dev);
else
return NULL;
}
struct prod_dev_id {
unsigned int product_id;
unsigned char device_id;
};
static int __find_bmc_prod_dev_id(struct device *dev, void *data)
{
struct prod_dev_id *id = data;
struct bmc_device *bmc = to_bmc_device(dev);
return (bmc->id.product_id == id->product_id
&& bmc->id.device_id == id->device_id);
}
static struct bmc_device *ipmi_find_bmc_prod_dev_id(
struct device_driver *drv,
unsigned int product_id, unsigned char device_id)
{
struct prod_dev_id id = {
.product_id = product_id,
.device_id = device_id,
};
struct device *dev;
dev = driver_find_device(drv, NULL, &id, __find_bmc_prod_dev_id);
if (dev)
return to_bmc_device(dev);
else
return NULL;
}
static ssize_t device_id_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct bmc_device *bmc = to_bmc_device(dev);
return snprintf(buf, 10, "%u\n", bmc->id.device_id);
}
static DEVICE_ATTR(device_id, S_IRUGO, device_id_show, NULL);
static ssize_t provides_device_sdrs_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct bmc_device *bmc = to_bmc_device(dev);
return snprintf(buf, 10, "%u\n",
(bmc->id.device_revision & 0x80) >> 7);
}
static DEVICE_ATTR(provides_device_sdrs, S_IRUGO, provides_device_sdrs_show,
NULL);
static ssize_t revision_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct bmc_device *bmc = to_bmc_device(dev);
return snprintf(buf, 20, "%u\n",
bmc->id.device_revision & 0x0F);
}
static DEVICE_ATTR(revision, S_IRUGO, revision_show, NULL);
static ssize_t firmware_revision_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct bmc_device *bmc = to_bmc_device(dev);
return snprintf(buf, 20, "%u.%x\n", bmc->id.firmware_revision_1,
bmc->id.firmware_revision_2);
}
static DEVICE_ATTR(firmware_revision, S_IRUGO, firmware_revision_show, NULL);
static ssize_t ipmi_version_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct bmc_device *bmc = to_bmc_device(dev);
return snprintf(buf, 20, "%u.%u\n",
ipmi_version_major(&bmc->id),
ipmi_version_minor(&bmc->id));
}
static DEVICE_ATTR(ipmi_version, S_IRUGO, ipmi_version_show, NULL);
static ssize_t add_dev_support_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct bmc_device *bmc = to_bmc_device(dev);
return snprintf(buf, 10, "0x%02x\n",
bmc->id.additional_device_support);
}
static DEVICE_ATTR(additional_device_support, S_IRUGO, add_dev_support_show,
NULL);
static ssize_t manufacturer_id_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct bmc_device *bmc = to_bmc_device(dev);
return snprintf(buf, 20, "0x%6.6x\n", bmc->id.manufacturer_id);
}
static DEVICE_ATTR(manufacturer_id, S_IRUGO, manufacturer_id_show, NULL);
static ssize_t product_id_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct bmc_device *bmc = to_bmc_device(dev);
return snprintf(buf, 10, "0x%4.4x\n", bmc->id.product_id);
}
static DEVICE_ATTR(product_id, S_IRUGO, product_id_show, NULL);
static ssize_t aux_firmware_rev_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct bmc_device *bmc = to_bmc_device(dev);
return snprintf(buf, 21, "0x%02x 0x%02x 0x%02x 0x%02x\n",
bmc->id.aux_firmware_revision[3],
bmc->id.aux_firmware_revision[2],
bmc->id.aux_firmware_revision[1],
bmc->id.aux_firmware_revision[0]);
}
static DEVICE_ATTR(aux_firmware_revision, S_IRUGO, aux_firmware_rev_show, NULL);
static ssize_t guid_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct bmc_device *bmc = to_bmc_device(dev);
return snprintf(buf, 100, "%Lx%Lx\n",
(long long) bmc->guid[0],
(long long) bmc->guid[8]);
}
static DEVICE_ATTR(guid, S_IRUGO, guid_show, NULL);
static struct attribute *bmc_dev_attrs[] = {
&dev_attr_device_id.attr,
&dev_attr_provides_device_sdrs.attr,
&dev_attr_revision.attr,
&dev_attr_firmware_revision.attr,
&dev_attr_ipmi_version.attr,
&dev_attr_additional_device_support.attr,
&dev_attr_manufacturer_id.attr,
&dev_attr_product_id.attr,
&dev_attr_aux_firmware_revision.attr,
&dev_attr_guid.attr,
NULL
};
static umode_t bmc_dev_attr_is_visible(struct kobject *kobj,
struct attribute *attr, int idx)
{
struct device *dev = kobj_to_dev(kobj);
struct bmc_device *bmc = to_bmc_device(dev);
umode_t mode = attr->mode;
if (attr == &dev_attr_aux_firmware_revision.attr)
return bmc->id.aux_firmware_revision_set ? mode : 0;
if (attr == &dev_attr_guid.attr)
return bmc->guid_set ? mode : 0;
return mode;
}
static struct attribute_group bmc_dev_attr_group = {
.attrs = bmc_dev_attrs,
.is_visible = bmc_dev_attr_is_visible,
};
static const struct attribute_group *bmc_dev_attr_groups[] = {
&bmc_dev_attr_group,
NULL
};
static struct device_type bmc_device_type = {
.groups = bmc_dev_attr_groups,
};
static void
release_bmc_device(struct device *dev)
{
kfree(to_bmc_device(dev));
}
static void
cleanup_bmc_device(struct kref *ref)
{
struct bmc_device *bmc = container_of(ref, struct bmc_device, usecount);
platform_device_unregister(&bmc->pdev);
}
static void ipmi_bmc_unregister(ipmi_smi_t intf)
{
struct bmc_device *bmc = intf->bmc;
sysfs_remove_link(&intf->si_dev->kobj, "bmc");
if (intf->my_dev_name) {
sysfs_remove_link(&bmc->pdev.dev.kobj, intf->my_dev_name);
kfree(intf->my_dev_name);
intf->my_dev_name = NULL;
}
mutex_lock(&ipmidriver_mutex);
kref_put(&bmc->usecount, cleanup_bmc_device);
intf->bmc = NULL;
mutex_unlock(&ipmidriver_mutex);
}
static int ipmi_bmc_register(ipmi_smi_t intf, int ifnum)
{
int rv;
struct bmc_device *bmc = intf->bmc;
struct bmc_device *old_bmc;
mutex_lock(&ipmidriver_mutex);
/*
* Try to find if there is an bmc_device struct
* representing the interfaced BMC already
*/
if (bmc->guid_set)
old_bmc = ipmi_find_bmc_guid(&ipmidriver.driver, bmc->guid);
else
old_bmc = ipmi_find_bmc_prod_dev_id(&ipmidriver.driver,
bmc->id.product_id,
bmc->id.device_id);
/*
* If there is already an bmc_device, free the new one,
* otherwise register the new BMC device
*/
if (old_bmc) {
kfree(bmc);
intf->bmc = old_bmc;
bmc = old_bmc;
kref_get(&bmc->usecount);
mutex_unlock(&ipmidriver_mutex);
printk(KERN_INFO
"ipmi: interfacing existing BMC (man_id: 0x%6.6x,"
" prod_id: 0x%4.4x, dev_id: 0x%2.2x)\n",
bmc->id.manufacturer_id,
bmc->id.product_id,
bmc->id.device_id);
} else {
unsigned char orig_dev_id = bmc->id.device_id;
int warn_printed = 0;
snprintf(bmc->name, sizeof(bmc->name),
"ipmi_bmc.%4.4x", bmc->id.product_id);
bmc->pdev.name = bmc->name;
while (ipmi_find_bmc_prod_dev_id(&ipmidriver.driver,
bmc->id.product_id,
bmc->id.device_id)) {
if (!warn_printed) {
printk(KERN_WARNING PFX
"This machine has two different BMCs"
" with the same product id and device"
" id. This is an error in the"
" firmware, but incrementing the"
" device id to work around the problem."
" Prod ID = 0x%x, Dev ID = 0x%x\n",
bmc->id.product_id, bmc->id.device_id);
warn_printed = 1;
}
bmc->id.device_id++; /* Wraps at 255 */
if (bmc->id.device_id == orig_dev_id) {
printk(KERN_ERR PFX
"Out of device ids!\n");
break;
}
}
bmc->pdev.dev.driver = &ipmidriver.driver;
bmc->pdev.id = bmc->id.device_id;
bmc->pdev.dev.release = release_bmc_device;
bmc->pdev.dev.type = &bmc_device_type;
kref_init(&bmc->usecount);
rv = platform_device_register(&bmc->pdev);
mutex_unlock(&ipmidriver_mutex);
if (rv) {
put_device(&bmc->pdev.dev);
printk(KERN_ERR
"ipmi_msghandler:"
" Unable to register bmc device: %d\n",
rv);
/*
* Don't go to out_err, you can only do that if
* the device is registered already.
*/
return rv;
}
dev_info(intf->si_dev, "Found new BMC (man_id: 0x%6.6x, "
"prod_id: 0x%4.4x, dev_id: 0x%2.2x)\n",
bmc->id.manufacturer_id,
bmc->id.product_id,
bmc->id.device_id);
}
/*
* create symlink from system interface device to bmc device
* and back.
*/
rv = sysfs_create_link(&intf->si_dev->kobj, &bmc->pdev.dev.kobj, "bmc");
if (rv) {
printk(KERN_ERR
"ipmi_msghandler: Unable to create bmc symlink: %d\n",
rv);
goto out_err;
}
intf->my_dev_name = kasprintf(GFP_KERNEL, "ipmi%d", ifnum);
if (!intf->my_dev_name) {
rv = -ENOMEM;
printk(KERN_ERR
"ipmi_msghandler: allocate link from BMC: %d\n",
rv);
goto out_err;
}
rv = sysfs_create_link(&bmc->pdev.dev.kobj, &intf->si_dev->kobj,
intf->my_dev_name);
if (rv) {
kfree(intf->my_dev_name);
intf->my_dev_name = NULL;
printk(KERN_ERR
"ipmi_msghandler:"
" Unable to create symlink to bmc: %d\n",
rv);
goto out_err;
}
return 0;
out_err:
ipmi_bmc_unregister(intf);
return rv;
}
static int
send_guid_cmd(ipmi_smi_t intf, int chan)
{
struct kernel_ipmi_msg msg;
struct ipmi_system_interface_addr si;
si.addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
si.channel = IPMI_BMC_CHANNEL;
si.lun = 0;
msg.netfn = IPMI_NETFN_APP_REQUEST;
msg.cmd = IPMI_GET_DEVICE_GUID_CMD;
msg.data = NULL;
msg.data_len = 0;
return i_ipmi_request(NULL,
intf,
(struct ipmi_addr *) &si,
0,
&msg,
intf,
NULL,
NULL,
0,
intf->channels[0].address,
intf->channels[0].lun,
-1, 0);
}
static void
guid_handler(ipmi_smi_t intf, struct ipmi_recv_msg *msg)
{
if ((msg->addr.addr_type != IPMI_SYSTEM_INTERFACE_ADDR_TYPE)
|| (msg->msg.netfn != IPMI_NETFN_APP_RESPONSE)
|| (msg->msg.cmd != IPMI_GET_DEVICE_GUID_CMD))
/* Not for me */
return;
if (msg->msg.data[0] != 0) {
/* Error from getting the GUID, the BMC doesn't have one. */
intf->bmc->guid_set = 0;
goto out;
}
if (msg->msg.data_len < 17) {
intf->bmc->guid_set = 0;
printk(KERN_WARNING PFX
"guid_handler: The GUID response from the BMC was too"
" short, it was %d but should have been 17. Assuming"
" GUID is not available.\n",
msg->msg.data_len);
goto out;
}
memcpy(intf->bmc->guid, msg->msg.data, 16);
intf->bmc->guid_set = 1;
out:
wake_up(&intf->waitq);
}
static void
get_guid(ipmi_smi_t intf)
{
int rv;
intf->bmc->guid_set = 0x2;
intf->null_user_handler = guid_handler;
rv = send_guid_cmd(intf, 0);
if (rv)
/* Send failed, no GUID available. */
intf->bmc->guid_set = 0;
wait_event(intf->waitq, intf->bmc->guid_set != 2);
intf->null_user_handler = NULL;
}
static int
send_channel_info_cmd(ipmi_smi_t intf, int chan)
{
struct kernel_ipmi_msg msg;
unsigned char data[1];
struct ipmi_system_interface_addr si;
si.addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
si.channel = IPMI_BMC_CHANNEL;
si.lun = 0;
msg.netfn = IPMI_NETFN_APP_REQUEST;
msg.cmd = IPMI_GET_CHANNEL_INFO_CMD;
msg.data = data;
msg.data_len = 1;
data[0] = chan;
return i_ipmi_request(NULL,
intf,
(struct ipmi_addr *) &si,
0,
&msg,
intf,
NULL,
NULL,
0,
intf->channels[0].address,
intf->channels[0].lun,
-1, 0);
}
static void
channel_handler(ipmi_smi_t intf, struct ipmi_recv_msg *msg)
{
int rv = 0;
int chan;
if ((msg->addr.addr_type == IPMI_SYSTEM_INTERFACE_ADDR_TYPE)
&& (msg->msg.netfn == IPMI_NETFN_APP_RESPONSE)
&& (msg->msg.cmd == IPMI_GET_CHANNEL_INFO_CMD)) {
/* It's the one we want */
if (msg->msg.data[0] != 0) {
/* Got an error from the channel, just go on. */
if (msg->msg.data[0] == IPMI_INVALID_COMMAND_ERR) {
/*
* If the MC does not support this
* command, that is legal. We just
* assume it has one IPMB at channel
* zero.
*/
intf->channels[0].medium
= IPMI_CHANNEL_MEDIUM_IPMB;
intf->channels[0].protocol
= IPMI_CHANNEL_PROTOCOL_IPMB;
intf->curr_channel = IPMI_MAX_CHANNELS;
wake_up(&intf->waitq);
goto out;
}
goto next_channel;
}
if (msg->msg.data_len < 4) {
/* Message not big enough, just go on. */
goto next_channel;
}
chan = intf->curr_channel;
intf->channels[chan].medium = msg->msg.data[2] & 0x7f;
intf->channels[chan].protocol = msg->msg.data[3] & 0x1f;
next_channel:
intf->curr_channel++;
if (intf->curr_channel >= IPMI_MAX_CHANNELS)
wake_up(&intf->waitq);
else
rv = send_channel_info_cmd(intf, intf->curr_channel);
if (rv) {
/* Got an error somehow, just give up. */
printk(KERN_WARNING PFX
"Error sending channel information for channel"
" %d: %d\n", intf->curr_channel, rv);
intf->curr_channel = IPMI_MAX_CHANNELS;
wake_up(&intf->waitq);
}
}
out:
return;
}
static void ipmi_poll(ipmi_smi_t intf)
{
if (intf->handlers->poll)
intf->handlers->poll(intf->send_info);
/* In case something came in */
handle_new_recv_msgs(intf);
}
void ipmi_poll_interface(ipmi_user_t user)
{
ipmi_poll(user->intf);
}
EXPORT_SYMBOL(ipmi_poll_interface);
int ipmi_register_smi(const struct ipmi_smi_handlers *handlers,
void *send_info,
struct ipmi_device_id *device_id,
struct device *si_dev,
unsigned char slave_addr)
{
int i, j;
int rv;
ipmi_smi_t intf;
ipmi_smi_t tintf;
struct list_head *link;
/*
* Make sure the driver is actually initialized, this handles
* problems with initialization order.
*/
if (!initialized) {
rv = ipmi_init_msghandler();
if (rv)
return rv;
/*
* The init code doesn't return an error if it was turned
* off, but it won't initialize. Check that.
*/
if (!initialized)
return -ENODEV;
}
intf = kzalloc(sizeof(*intf), GFP_KERNEL);
if (!intf)
return -ENOMEM;
intf->ipmi_version_major = ipmi_version_major(device_id);
intf->ipmi_version_minor = ipmi_version_minor(device_id);
intf->bmc = kzalloc(sizeof(*intf->bmc), GFP_KERNEL);
if (!intf->bmc) {
kfree(intf);
return -ENOMEM;
}
intf->intf_num = -1; /* Mark it invalid for now. */
kref_init(&intf->refcount);
intf->bmc->id = *device_id;
intf->si_dev = si_dev;
for (j = 0; j < IPMI_MAX_CHANNELS; j++) {
intf->channels[j].address = IPMI_BMC_SLAVE_ADDR;
intf->channels[j].lun = 2;
}
if (slave_addr != 0)
intf->channels[0].address = slave_addr;
INIT_LIST_HEAD(&intf->users);
intf->handlers = handlers;
intf->send_info = send_info;
spin_lock_init(&intf->seq_lock);
for (j = 0; j < IPMI_IPMB_NUM_SEQ; j++) {
intf->seq_table[j].inuse = 0;
intf->seq_table[j].seqid = 0;
}
intf->curr_seq = 0;
#ifdef CONFIG_PROC_FS
mutex_init(&intf->proc_entry_lock);
#endif
spin_lock_init(&intf->waiting_rcv_msgs_lock);
INIT_LIST_HEAD(&intf->waiting_rcv_msgs);
tasklet_init(&intf->recv_tasklet,
smi_recv_tasklet,
(unsigned long) intf);
atomic_set(&intf->watchdog_pretimeouts_to_deliver, 0);
spin_lock_init(&intf->xmit_msgs_lock);
INIT_LIST_HEAD(&intf->xmit_msgs);
INIT_LIST_HEAD(&intf->hp_xmit_msgs);
spin_lock_init(&intf->events_lock);
atomic_set(&intf->event_waiters, 0);
intf->ticks_to_req_ev = IPMI_REQUEST_EV_TIME;
INIT_LIST_HEAD(&intf->waiting_events);
intf->waiting_events_count = 0;
mutex_init(&intf->cmd_rcvrs_mutex);
spin_lock_init(&intf->maintenance_mode_lock);
INIT_LIST_HEAD(&intf->cmd_rcvrs);
init_waitqueue_head(&intf->waitq);
for (i = 0; i < IPMI_NUM_STATS; i++)
atomic_set(&intf->stats[i], 0);
intf->proc_dir = NULL;
mutex_lock(&smi_watchers_mutex);
mutex_lock(&ipmi_interfaces_mutex);
/* Look for a hole in the numbers. */
i = 0;
link = &ipmi_interfaces;
list_for_each_entry_rcu(tintf, &ipmi_interfaces, link) {
if (tintf->intf_num != i) {
link = &tintf->link;
break;
}
i++;
}
/* Add the new interface in numeric order. */
if (i == 0)
list_add_rcu(&intf->link, &ipmi_interfaces);
else
list_add_tail_rcu(&intf->link, link);
rv = handlers->start_processing(send_info, intf);
if (rv)
goto out;
get_guid(intf);
if ((intf->ipmi_version_major > 1)
|| ((intf->ipmi_version_major == 1)
&& (intf->ipmi_version_minor >= 5))) {
/*
* Start scanning the channels to see what is
* available.
*/
intf->null_user_handler = channel_handler;
intf->curr_channel = 0;
rv = send_channel_info_cmd(intf, 0);
if (rv) {
printk(KERN_WARNING PFX
"Error sending channel information for channel"
" 0, %d\n", rv);
goto out;
}
/* Wait for the channel info to be read. */
wait_event(intf->waitq,
intf->curr_channel >= IPMI_MAX_CHANNELS);
intf->null_user_handler = NULL;
} else {
/* Assume a single IPMB channel at zero. */
intf->channels[0].medium = IPMI_CHANNEL_MEDIUM_IPMB;
intf->channels[0].protocol = IPMI_CHANNEL_PROTOCOL_IPMB;
intf->curr_channel = IPMI_MAX_CHANNELS;
}
if (rv == 0)
rv = add_proc_entries(intf, i);
rv = ipmi_bmc_register(intf, i);
out:
if (rv) {
if (intf->proc_dir)
remove_proc_entries(intf);
intf->handlers = NULL;
list_del_rcu(&intf->link);
mutex_unlock(&ipmi_interfaces_mutex);
mutex_unlock(&smi_watchers_mutex);
synchronize_rcu();
kref_put(&intf->refcount, intf_free);
} else {
/*
* Keep memory order straight for RCU readers. Make
* sure everything else is committed to memory before
* setting intf_num to mark the interface valid.
*/
smp_wmb();
intf->intf_num = i;
mutex_unlock(&ipmi_interfaces_mutex);
/* After this point the interface is legal to use. */
call_smi_watchers(i, intf->si_dev);
mutex_unlock(&smi_watchers_mutex);
}
return rv;
}
EXPORT_SYMBOL(ipmi_register_smi);
static void deliver_smi_err_response(ipmi_smi_t intf,
struct ipmi_smi_msg *msg,
unsigned char err)
{
msg->rsp[0] = msg->data[0] | 4;
msg->rsp[1] = msg->data[1];
msg->rsp[2] = err;
msg->rsp_size = 3;
/* It's an error, so it will never requeue, no need to check return. */
handle_one_recv_msg(intf, msg);
}
static void cleanup_smi_msgs(ipmi_smi_t intf)
{
int i;
struct seq_table *ent;
struct ipmi_smi_msg *msg;
struct list_head *entry;
struct list_head tmplist;
/* Clear out our transmit queues and hold the messages. */
INIT_LIST_HEAD(&tmplist);
list_splice_tail(&intf->hp_xmit_msgs, &tmplist);
list_splice_tail(&intf->xmit_msgs, &tmplist);
/* Current message first, to preserve order */
while (intf->curr_msg && !list_empty(&intf->waiting_rcv_msgs)) {
/* Wait for the message to clear out. */
schedule_timeout(1);
}
/* No need for locks, the interface is down. */
/*
* Return errors for all pending messages in queue and in the
* tables waiting for remote responses.
*/
while (!list_empty(&tmplist)) {
entry = tmplist.next;
list_del(entry);
msg = list_entry(entry, struct ipmi_smi_msg, link);
deliver_smi_err_response(intf, msg, IPMI_ERR_UNSPECIFIED);
}
for (i = 0; i < IPMI_IPMB_NUM_SEQ; i++) {
ent = &(intf->seq_table[i]);
if (!ent->inuse)
continue;
deliver_err_response(ent->recv_msg, IPMI_ERR_UNSPECIFIED);
}
}
int ipmi_unregister_smi(ipmi_smi_t intf)
{
struct ipmi_smi_watcher *w;
int intf_num = intf->intf_num;
ipmi_user_t user;
ipmi_bmc_unregister(intf);
mutex_lock(&smi_watchers_mutex);
mutex_lock(&ipmi_interfaces_mutex);
intf->intf_num = -1;
intf->in_shutdown = true;
list_del_rcu(&intf->link);
mutex_unlock(&ipmi_interfaces_mutex);
synchronize_rcu();
cleanup_smi_msgs(intf);
/* Clean up the effects of users on the lower-level software. */
mutex_lock(&ipmi_interfaces_mutex);
rcu_read_lock();
list_for_each_entry_rcu(user, &intf->users, link) {
module_put(intf->handlers->owner);
if (intf->handlers->dec_usecount)
intf->handlers->dec_usecount(intf->send_info);
}
rcu_read_unlock();
intf->handlers = NULL;
mutex_unlock(&ipmi_interfaces_mutex);
remove_proc_entries(intf);
/*
* Call all the watcher interfaces to tell them that
* an interface is gone.
*/
list_for_each_entry(w, &smi_watchers, link)
w->smi_gone(intf_num);
mutex_unlock(&smi_watchers_mutex);
kref_put(&intf->refcount, intf_free);
return 0;
}
EXPORT_SYMBOL(ipmi_unregister_smi);
static int handle_ipmb_get_msg_rsp(ipmi_smi_t intf,
struct ipmi_smi_msg *msg)
{
struct ipmi_ipmb_addr ipmb_addr;
struct ipmi_recv_msg *recv_msg;
/*
* This is 11, not 10, because the response must contain a
* completion code.
*/
if (msg->rsp_size < 11) {
/* Message not big enough, just ignore it. */
ipmi_inc_stat(intf, invalid_ipmb_responses);
return 0;
}
if (msg->rsp[2] != 0) {
/* An error getting the response, just ignore it. */
return 0;
}
ipmb_addr.addr_type = IPMI_IPMB_ADDR_TYPE;
ipmb_addr.slave_addr = msg->rsp[6];
ipmb_addr.channel = msg->rsp[3] & 0x0f;
ipmb_addr.lun = msg->rsp[7] & 3;
/*
* It's a response from a remote entity. Look up the sequence
* number and handle the response.
*/
if (intf_find_seq(intf,
msg->rsp[7] >> 2,
msg->rsp[3] & 0x0f,
msg->rsp[8],
(msg->rsp[4] >> 2) & (~1),
(struct ipmi_addr *) &(ipmb_addr),
&recv_msg)) {
/*
* We were unable to find the sequence number,
* so just nuke the message.
*/
ipmi_inc_stat(intf, unhandled_ipmb_responses);
return 0;
}
memcpy(recv_msg->msg_data,
&(msg->rsp[9]),
msg->rsp_size - 9);
/*
* The other fields matched, so no need to set them, except
* for netfn, which needs to be the response that was
* returned, not the request value.
*/
recv_msg->msg.netfn = msg->rsp[4] >> 2;
recv_msg->msg.data = recv_msg->msg_data;
recv_msg->msg.data_len = msg->rsp_size - 10;
recv_msg->recv_type = IPMI_RESPONSE_RECV_TYPE;
ipmi_inc_stat(intf, handled_ipmb_responses);
deliver_response(recv_msg);
return 0;
}
static int handle_ipmb_get_msg_cmd(ipmi_smi_t intf,
struct ipmi_smi_msg *msg)
{
struct cmd_rcvr *rcvr;
int rv = 0;
unsigned char netfn;
unsigned char cmd;
unsigned char chan;
ipmi_user_t user = NULL;
struct ipmi_ipmb_addr *ipmb_addr;
struct ipmi_recv_msg *recv_msg;
if (msg->rsp_size < 10) {
/* Message not big enough, just ignore it. */
ipmi_inc_stat(intf, invalid_commands);
return 0;
}
if (msg->rsp[2] != 0) {
/* An error getting the response, just ignore it. */
return 0;
}
netfn = msg->rsp[4] >> 2;
cmd = msg->rsp[8];
chan = msg->rsp[3] & 0xf;
rcu_read_lock();
rcvr = find_cmd_rcvr(intf, netfn, cmd, chan);
if (rcvr) {
user = rcvr->user;
kref_get(&user->refcount);
} else
user = NULL;
rcu_read_unlock();
if (user == NULL) {
/* We didn't find a user, deliver an error response. */
ipmi_inc_stat(intf, unhandled_commands);
msg->data[0] = (IPMI_NETFN_APP_REQUEST << 2);
msg->data[1] = IPMI_SEND_MSG_CMD;
msg->data[2] = msg->rsp[3];
msg->data[3] = msg->rsp[6];
msg->data[4] = ((netfn + 1) << 2) | (msg->rsp[7] & 0x3);
msg->data[5] = ipmb_checksum(&(msg->data[3]), 2);
msg->data[6] = intf->channels[msg->rsp[3] & 0xf].address;
/* rqseq/lun */
msg->data[7] = (msg->rsp[7] & 0xfc) | (msg->rsp[4] & 0x3);
msg->data[8] = msg->rsp[8]; /* cmd */
msg->data[9] = IPMI_INVALID_CMD_COMPLETION_CODE;
msg->data[10] = ipmb_checksum(&(msg->data[6]), 4);
msg->data_size = 11;
#ifdef DEBUG_MSGING
{
int m;
printk("Invalid command:");
for (m = 0; m < msg->data_size; m++)
printk(" %2.2x", msg->data[m]);
printk("\n");
}
#endif
rcu_read_lock();
if (!intf->in_shutdown) {
smi_send(intf, intf->handlers, msg, 0);
/*
* We used the message, so return the value
* that causes it to not be freed or
* queued.
*/
rv = -1;
}
rcu_read_unlock();
} else {
/* Deliver the message to the user. */
ipmi_inc_stat(intf, handled_commands);
recv_msg = ipmi_alloc_recv_msg();
if (!recv_msg) {
/*
* We couldn't allocate memory for the
* message, so requeue it for handling
* later.
*/
rv = 1;
kref_put(&user->refcount, free_user);
} else {
/* Extract the source address from the data. */
ipmb_addr = (struct ipmi_ipmb_addr *) &recv_msg->addr;
ipmb_addr->addr_type = IPMI_IPMB_ADDR_TYPE;
ipmb_addr->slave_addr = msg->rsp[6];
ipmb_addr->lun = msg->rsp[7] & 3;
ipmb_addr->channel = msg->rsp[3] & 0xf;
/*
* Extract the rest of the message information
* from the IPMB header.
*/
recv_msg->user = user;
recv_msg->recv_type = IPMI_CMD_RECV_TYPE;
recv_msg->msgid = msg->rsp[7] >> 2;
recv_msg->msg.netfn = msg->rsp[4] >> 2;
recv_msg->msg.cmd = msg->rsp[8];
recv_msg->msg.data = recv_msg->msg_data;
/*
* We chop off 10, not 9 bytes because the checksum
* at the end also needs to be removed.
*/
recv_msg->msg.data_len = msg->rsp_size - 10;
memcpy(recv_msg->msg_data,
&(msg->rsp[9]),
msg->rsp_size - 10);
deliver_response(recv_msg);
}
}
return rv;
}
static int handle_lan_get_msg_rsp(ipmi_smi_t intf,
struct ipmi_smi_msg *msg)
{
struct ipmi_lan_addr lan_addr;
struct ipmi_recv_msg *recv_msg;
/*
* This is 13, not 12, because the response must contain a
* completion code.
*/
if (msg->rsp_size < 13) {
/* Message not big enough, just ignore it. */
ipmi_inc_stat(intf, invalid_lan_responses);
return 0;
}
if (msg->rsp[2] != 0) {
/* An error getting the response, just ignore it. */
return 0;
}
lan_addr.addr_type = IPMI_LAN_ADDR_TYPE;
lan_addr.session_handle = msg->rsp[4];
lan_addr.remote_SWID = msg->rsp[8];
lan_addr.local_SWID = msg->rsp[5];
lan_addr.channel = msg->rsp[3] & 0x0f;
lan_addr.privilege = msg->rsp[3] >> 4;
lan_addr.lun = msg->rsp[9] & 3;
/*
* It's a response from a remote entity. Look up the sequence
* number and handle the response.
*/
if (intf_find_seq(intf,
msg->rsp[9] >> 2,
msg->rsp[3] & 0x0f,
msg->rsp[10],
(msg->rsp[6] >> 2) & (~1),
(struct ipmi_addr *) &(lan_addr),
&recv_msg)) {
/*
* We were unable to find the sequence number,
* so just nuke the message.
*/
ipmi_inc_stat(intf, unhandled_lan_responses);
return 0;
}
memcpy(recv_msg->msg_data,
&(msg->rsp[11]),
msg->rsp_size - 11);
/*
* The other fields matched, so no need to set them, except
* for netfn, which needs to be the response that was
* returned, not the request value.
*/
recv_msg->msg.netfn = msg->rsp[6] >> 2;
recv_msg->msg.data = recv_msg->msg_data;
recv_msg->msg.data_len = msg->rsp_size - 12;
recv_msg->recv_type = IPMI_RESPONSE_RECV_TYPE;
ipmi_inc_stat(intf, handled_lan_responses);
deliver_response(recv_msg);
return 0;
}
static int handle_lan_get_msg_cmd(ipmi_smi_t intf,
struct ipmi_smi_msg *msg)
{
struct cmd_rcvr *rcvr;
int rv = 0;
unsigned char netfn;
unsigned char cmd;
unsigned char chan;
ipmi_user_t user = NULL;
struct ipmi_lan_addr *lan_addr;
struct ipmi_recv_msg *recv_msg;
if (msg->rsp_size < 12) {
/* Message not big enough, just ignore it. */
ipmi_inc_stat(intf, invalid_commands);
return 0;
}
if (msg->rsp[2] != 0) {
/* An error getting the response, just ignore it. */
return 0;
}
netfn = msg->rsp[6] >> 2;
cmd = msg->rsp[10];
chan = msg->rsp[3] & 0xf;
rcu_read_lock();
rcvr = find_cmd_rcvr(intf, netfn, cmd, chan);
if (rcvr) {
user = rcvr->user;
kref_get(&user->refcount);
} else
user = NULL;
rcu_read_unlock();
if (user == NULL) {
/* We didn't find a user, just give up. */
ipmi_inc_stat(intf, unhandled_commands);
/*
* Don't do anything with these messages, just allow
* them to be freed.
*/
rv = 0;
} else {
/* Deliver the message to the user. */
ipmi_inc_stat(intf, handled_commands);
recv_msg = ipmi_alloc_recv_msg();
if (!recv_msg) {
/*
* We couldn't allocate memory for the
* message, so requeue it for handling later.
*/
rv = 1;
kref_put(&user->refcount, free_user);
} else {
/* Extract the source address from the data. */
lan_addr = (struct ipmi_lan_addr *) &recv_msg->addr;
lan_addr->addr_type = IPMI_LAN_ADDR_TYPE;
lan_addr->session_handle = msg->rsp[4];
lan_addr->remote_SWID = msg->rsp[8];
lan_addr->local_SWID = msg->rsp[5];
lan_addr->lun = msg->rsp[9] & 3;
lan_addr->channel = msg->rsp[3] & 0xf;
lan_addr->privilege = msg->rsp[3] >> 4;
/*
* Extract the rest of the message information
* from the IPMB header.
*/
recv_msg->user = user;
recv_msg->recv_type = IPMI_CMD_RECV_TYPE;
recv_msg->msgid = msg->rsp[9] >> 2;
recv_msg->msg.netfn = msg->rsp[6] >> 2;
recv_msg->msg.cmd = msg->rsp[10];
recv_msg->msg.data = recv_msg->msg_data;
/*
* We chop off 12, not 11 bytes because the checksum
* at the end also needs to be removed.
*/
recv_msg->msg.data_len = msg->rsp_size - 12;
memcpy(recv_msg->msg_data,
&(msg->rsp[11]),
msg->rsp_size - 12);
deliver_response(recv_msg);
}
}
return rv;
}
/*
* This routine will handle "Get Message" command responses with
* channels that use an OEM Medium. The message format belongs to
* the OEM. See IPMI 2.0 specification, Chapter 6 and
* Chapter 22, sections 22.6 and 22.24 for more details.
*/
static int handle_oem_get_msg_cmd(ipmi_smi_t intf,
struct ipmi_smi_msg *msg)
{
struct cmd_rcvr *rcvr;
int rv = 0;
unsigned char netfn;
unsigned char cmd;
unsigned char chan;
ipmi_user_t user = NULL;
struct ipmi_system_interface_addr *smi_addr;
struct ipmi_recv_msg *recv_msg;
/*
* We expect the OEM SW to perform error checking
* so we just do some basic sanity checks
*/
if (msg->rsp_size < 4) {
/* Message not big enough, just ignore it. */
ipmi_inc_stat(intf, invalid_commands);
return 0;
}
if (msg->rsp[2] != 0) {
/* An error getting the response, just ignore it. */
return 0;
}
/*
* This is an OEM Message so the OEM needs to know how
* handle the message. We do no interpretation.
*/
netfn = msg->rsp[0] >> 2;
cmd = msg->rsp[1];
chan = msg->rsp[3] & 0xf;
rcu_read_lock();
rcvr = find_cmd_rcvr(intf, netfn, cmd, chan);
if (rcvr) {
user = rcvr->user;
kref_get(&user->refcount);
} else
user = NULL;
rcu_read_unlock();
if (user == NULL) {
/* We didn't find a user, just give up. */
ipmi_inc_stat(intf, unhandled_commands);
/*
* Don't do anything with these messages, just allow
* them to be freed.
*/
rv = 0;
} else {
/* Deliver the message to the user. */
ipmi_inc_stat(intf, handled_commands);
recv_msg = ipmi_alloc_recv_msg();
if (!recv_msg) {
/*
* We couldn't allocate memory for the
* message, so requeue it for handling
* later.
*/
rv = 1;
kref_put(&user->refcount, free_user);
} else {
/*
* OEM Messages are expected to be delivered via
* the system interface to SMS software. We might
* need to visit this again depending on OEM
* requirements
*/
smi_addr = ((struct ipmi_system_interface_addr *)
&(recv_msg->addr));
smi_addr->addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
smi_addr->channel = IPMI_BMC_CHANNEL;
smi_addr->lun = msg->rsp[0] & 3;
recv_msg->user = user;
recv_msg->user_msg_data = NULL;
recv_msg->recv_type = IPMI_OEM_RECV_TYPE;
recv_msg->msg.netfn = msg->rsp[0] >> 2;
recv_msg->msg.cmd = msg->rsp[1];
recv_msg->msg.data = recv_msg->msg_data;
/*
* The message starts at byte 4 which follows the
* the Channel Byte in the "GET MESSAGE" command
*/
recv_msg->msg.data_len = msg->rsp_size - 4;
memcpy(recv_msg->msg_data,
&(msg->rsp[4]),
msg->rsp_size - 4);
deliver_response(recv_msg);
}
}
return rv;
}
static void copy_event_into_recv_msg(struct ipmi_recv_msg *recv_msg,
struct ipmi_smi_msg *msg)
{
struct ipmi_system_interface_addr *smi_addr;
recv_msg->msgid = 0;
smi_addr = (struct ipmi_system_interface_addr *) &(recv_msg->addr);
smi_addr->addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
smi_addr->channel = IPMI_BMC_CHANNEL;
smi_addr->lun = msg->rsp[0] & 3;
recv_msg->recv_type = IPMI_ASYNC_EVENT_RECV_TYPE;
recv_msg->msg.netfn = msg->rsp[0] >> 2;
recv_msg->msg.cmd = msg->rsp[1];
memcpy(recv_msg->msg_data, &(msg->rsp[3]), msg->rsp_size - 3);
recv_msg->msg.data = recv_msg->msg_data;
recv_msg->msg.data_len = msg->rsp_size - 3;
}
static int handle_read_event_rsp(ipmi_smi_t intf,
struct ipmi_smi_msg *msg)
{
struct ipmi_recv_msg *recv_msg, *recv_msg2;
struct list_head msgs;
ipmi_user_t user;
int rv = 0;
int deliver_count = 0;
unsigned long flags;
if (msg->rsp_size < 19) {
/* Message is too small to be an IPMB event. */
ipmi_inc_stat(intf, invalid_events);
return 0;
}
if (msg->rsp[2] != 0) {
/* An error getting the event, just ignore it. */
return 0;
}
INIT_LIST_HEAD(&msgs);
spin_lock_irqsave(&intf->events_lock, flags);
ipmi_inc_stat(intf, events);
/*
* Allocate and fill in one message for every user that is
* getting events.
*/
rcu_read_lock();
list_for_each_entry_rcu(user, &intf->users, link) {
if (!user->gets_events)
continue;
recv_msg = ipmi_alloc_recv_msg();
if (!recv_msg) {
rcu_read_unlock();
list_for_each_entry_safe(recv_msg, recv_msg2, &msgs,
link) {
list_del(&recv_msg->link);
ipmi_free_recv_msg(recv_msg);
}
/*
* We couldn't allocate memory for the
* message, so requeue it for handling
* later.
*/
rv = 1;
goto out;
}
deliver_count++;
copy_event_into_recv_msg(recv_msg, msg);
recv_msg->user = user;
kref_get(&user->refcount);
list_add_tail(&(recv_msg->link), &msgs);
}
rcu_read_unlock();
if (deliver_count) {
/* Now deliver all the messages. */
list_for_each_entry_safe(recv_msg, recv_msg2, &msgs, link) {
list_del(&recv_msg->link);
deliver_response(recv_msg);
}
} else if (intf->waiting_events_count < MAX_EVENTS_IN_QUEUE) {
/*
* No one to receive the message, put it in queue if there's
* not already too many things in the queue.
*/
recv_msg = ipmi_alloc_recv_msg();
if (!recv_msg) {
/*
* We couldn't allocate memory for the
* message, so requeue it for handling
* later.
*/
rv = 1;
goto out;
}
copy_event_into_recv_msg(recv_msg, msg);
list_add_tail(&(recv_msg->link), &(intf->waiting_events));
intf->waiting_events_count++;
} else if (!intf->event_msg_printed) {
/*
* There's too many things in the queue, discard this
* message.
*/
printk(KERN_WARNING PFX "Event queue full, discarding"
" incoming events\n");
intf->event_msg_printed = 1;
}
out:
spin_unlock_irqrestore(&(intf->events_lock), flags);
return rv;
}
static int handle_bmc_rsp(ipmi_smi_t intf,
struct ipmi_smi_msg *msg)
{
struct ipmi_recv_msg *recv_msg;
struct ipmi_user *user;
recv_msg = (struct ipmi_recv_msg *) msg->user_data;
if (recv_msg == NULL) {
printk(KERN_WARNING
"IPMI message received with no owner. This\n"
"could be because of a malformed message, or\n"
"because of a hardware error. Contact your\n"
"hardware vender for assistance\n");
return 0;
}
user = recv_msg->user;
/* Make sure the user still exists. */
if (user && !user->valid) {
/* The user for the message went away, so give up. */
ipmi_inc_stat(intf, unhandled_local_responses);
ipmi_free_recv_msg(recv_msg);
} else {
struct ipmi_system_interface_addr *smi_addr;
ipmi_inc_stat(intf, handled_local_responses);
recv_msg->recv_type = IPMI_RESPONSE_RECV_TYPE;
recv_msg->msgid = msg->msgid;
smi_addr = ((struct ipmi_system_interface_addr *)
&(recv_msg->addr));
smi_addr->addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
smi_addr->channel = IPMI_BMC_CHANNEL;
smi_addr->lun = msg->rsp[0] & 3;
recv_msg->msg.netfn = msg->rsp[0] >> 2;
recv_msg->msg.cmd = msg->rsp[1];
memcpy(recv_msg->msg_data,
&(msg->rsp[2]),
msg->rsp_size - 2);
recv_msg->msg.data = recv_msg->msg_data;
recv_msg->msg.data_len = msg->rsp_size - 2;
deliver_response(recv_msg);
}
return 0;
}
/*
* Handle a received message. Return 1 if the message should be requeued,
* 0 if the message should be freed, or -1 if the message should not
* be freed or requeued.
*/
static int handle_one_recv_msg(ipmi_smi_t intf,
struct ipmi_smi_msg *msg)
{
int requeue;
int chan;
#ifdef DEBUG_MSGING
int m;
printk("Recv:");
for (m = 0; m < msg->rsp_size; m++)
printk(" %2.2x", msg->rsp[m]);
printk("\n");
#endif
if (msg->rsp_size < 2) {
/* Message is too small to be correct. */
printk(KERN_WARNING PFX "BMC returned to small a message"
" for netfn %x cmd %x, got %d bytes\n",
(msg->data[0] >> 2) | 1, msg->data[1], msg->rsp_size);
/* Generate an error response for the message. */
msg->rsp[0] = msg->data[0] | (1 << 2);
msg->rsp[1] = msg->data[1];
msg->rsp[2] = IPMI_ERR_UNSPECIFIED;
msg->rsp_size = 3;
} else if (((msg->rsp[0] >> 2) != ((msg->data[0] >> 2) | 1))
|| (msg->rsp[1] != msg->data[1])) {
/*
* The NetFN and Command in the response is not even
* marginally correct.
*/
printk(KERN_WARNING PFX "BMC returned incorrect response,"
" expected netfn %x cmd %x, got netfn %x cmd %x\n",
(msg->data[0] >> 2) | 1, msg->data[1],
msg->rsp[0] >> 2, msg->rsp[1]);
/* Generate an error response for the message. */
msg->rsp[0] = msg->data[0] | (1 << 2);
msg->rsp[1] = msg->data[1];
msg->rsp[2] = IPMI_ERR_UNSPECIFIED;
msg->rsp_size = 3;
}
if ((msg->rsp[0] == ((IPMI_NETFN_APP_REQUEST|1) << 2))
&& (msg->rsp[1] == IPMI_SEND_MSG_CMD)
&& (msg->user_data != NULL)) {
/*
* It's a response to a response we sent. For this we
* deliver a send message response to the user.
*/
struct ipmi_recv_msg *recv_msg = msg->user_data;
requeue = 0;
if (msg->rsp_size < 2)
/* Message is too small to be correct. */
goto out;
chan = msg->data[2] & 0x0f;
if (chan >= IPMI_MAX_CHANNELS)
/* Invalid channel number */
goto out;
if (!recv_msg)
goto out;
/* Make sure the user still exists. */
if (!recv_msg->user || !recv_msg->user->valid)
goto out;
recv_msg->recv_type = IPMI_RESPONSE_RESPONSE_TYPE;
recv_msg->msg.data = recv_msg->msg_data;
recv_msg->msg.data_len = 1;
recv_msg->msg_data[0] = msg->rsp[2];
deliver_response(recv_msg);
} else if ((msg->rsp[0] == ((IPMI_NETFN_APP_REQUEST|1) << 2))
&& (msg->rsp[1] == IPMI_GET_MSG_CMD)) {
/* It's from the receive queue. */
chan = msg->rsp[3] & 0xf;
if (chan >= IPMI_MAX_CHANNELS) {
/* Invalid channel number */
requeue = 0;
goto out;
}
/*
* We need to make sure the channels have been initialized.
* The channel_handler routine will set the "curr_channel"
* equal to or greater than IPMI_MAX_CHANNELS when all the
* channels for this interface have been initialized.
*/
if (intf->curr_channel < IPMI_MAX_CHANNELS) {
requeue = 0; /* Throw the message away */
goto out;
}
switch (intf->channels[chan].medium) {
case IPMI_CHANNEL_MEDIUM_IPMB:
if (msg->rsp[4] & 0x04) {
/*
* It's a response, so find the
* requesting message and send it up.
*/
requeue = handle_ipmb_get_msg_rsp(intf, msg);
} else {
/*
* It's a command to the SMS from some other
* entity. Handle that.
*/
requeue = handle_ipmb_get_msg_cmd(intf, msg);
}
break;
case IPMI_CHANNEL_MEDIUM_8023LAN:
case IPMI_CHANNEL_MEDIUM_ASYNC:
if (msg->rsp[6] & 0x04) {
/*
* It's a response, so find the
* requesting message and send it up.
*/
requeue = handle_lan_get_msg_rsp(intf, msg);
} else {
/*
* It's a command to the SMS from some other
* entity. Handle that.
*/
requeue = handle_lan_get_msg_cmd(intf, msg);
}
break;
default:
/* Check for OEM Channels. Clients had better
register for these commands. */
if ((intf->channels[chan].medium
>= IPMI_CHANNEL_MEDIUM_OEM_MIN)
&& (intf->channels[chan].medium
<= IPMI_CHANNEL_MEDIUM_OEM_MAX)) {
requeue = handle_oem_get_msg_cmd(intf, msg);
} else {
/*
* We don't handle the channel type, so just
* free the message.
*/
requeue = 0;
}
}
} else if ((msg->rsp[0] == ((IPMI_NETFN_APP_REQUEST|1) << 2))
&& (msg->rsp[1] == IPMI_READ_EVENT_MSG_BUFFER_CMD)) {
/* It's an asynchronous event. */
requeue = handle_read_event_rsp(intf, msg);
} else {
/* It's a response from the local BMC. */
requeue = handle_bmc_rsp(intf, msg);
}
out:
return requeue;
}
/*
* If there are messages in the queue or pretimeouts, handle them.
*/
static void handle_new_recv_msgs(ipmi_smi_t intf)
{
struct ipmi_smi_msg *smi_msg;
unsigned long flags = 0;
int rv;
int run_to_completion = intf->run_to_completion;
/* See if any waiting messages need to be processed. */
if (!run_to_completion)
spin_lock_irqsave(&intf->waiting_rcv_msgs_lock, flags);
while (!list_empty(&intf->waiting_rcv_msgs)) {
smi_msg = list_entry(intf->waiting_rcv_msgs.next,
struct ipmi_smi_msg, link);
if (!run_to_completion)
spin_unlock_irqrestore(&intf->waiting_rcv_msgs_lock,
flags);
rv = handle_one_recv_msg(intf, smi_msg);
if (!run_to_completion)
spin_lock_irqsave(&intf->waiting_rcv_msgs_lock, flags);
if (rv > 0) {
/*
* To preserve message order, quit if we
* can't handle a message.
*/
break;
} else {
list_del(&smi_msg->link);
if (rv == 0)
/* Message handled */
ipmi_free_smi_msg(smi_msg);
/* If rv < 0, fatal error, del but don't free. */
}
}
if (!run_to_completion)
spin_unlock_irqrestore(&intf->waiting_rcv_msgs_lock, flags);
/*
* If the pretimout count is non-zero, decrement one from it and
* deliver pretimeouts to all the users.
*/
if (atomic_add_unless(&intf->watchdog_pretimeouts_to_deliver, -1, 0)) {
ipmi_user_t user;
rcu_read_lock();
list_for_each_entry_rcu(user, &intf->users, link) {
if (user->handler->ipmi_watchdog_pretimeout)
user->handler->ipmi_watchdog_pretimeout(
user->handler_data);
}
rcu_read_unlock();
}
}
static void smi_recv_tasklet(unsigned long val)
{
unsigned long flags = 0; /* keep us warning-free. */
ipmi_smi_t intf = (ipmi_smi_t) val;
int run_to_completion = intf->run_to_completion;
struct ipmi_smi_msg *newmsg = NULL;
/*
* Start the next message if available.
*
* Do this here, not in the actual receiver, because we may deadlock
* because the lower layer is allowed to hold locks while calling
* message delivery.
*/
if (!run_to_completion)
spin_lock_irqsave(&intf->xmit_msgs_lock, flags);
if (intf->curr_msg == NULL && !intf->in_shutdown) {
struct list_head *entry = NULL;
/* Pick the high priority queue first. */
if (!list_empty(&intf->hp_xmit_msgs))
entry = intf->hp_xmit_msgs.next;
else if (!list_empty(&intf->xmit_msgs))
entry = intf->xmit_msgs.next;
if (entry) {
list_del(entry);
newmsg = list_entry(entry, struct ipmi_smi_msg, link);
intf->curr_msg = newmsg;
}
}
if (!run_to_completion)
spin_unlock_irqrestore(&intf->xmit_msgs_lock, flags);
if (newmsg)
intf->handlers->sender(intf->send_info, newmsg);
handle_new_recv_msgs(intf);
}
/* Handle a new message from the lower layer. */
void ipmi_smi_msg_received(ipmi_smi_t intf,
struct ipmi_smi_msg *msg)
{
unsigned long flags = 0; /* keep us warning-free. */
int run_to_completion = intf->run_to_completion;
if ((msg->data_size >= 2)
&& (msg->data[0] == (IPMI_NETFN_APP_REQUEST << 2))
&& (msg->data[1] == IPMI_SEND_MSG_CMD)
&& (msg->user_data == NULL)) {
if (intf->in_shutdown)
goto free_msg;
/*
* This is the local response to a command send, start
* the timer for these. The user_data will not be
* NULL if this is a response send, and we will let
* response sends just go through.
*/
/*
* Check for errors, if we get certain errors (ones
* that mean basically we can try again later), we
* ignore them and start the timer. Otherwise we
* report the error immediately.
*/
if ((msg->rsp_size >= 3) && (msg->rsp[2] != 0)
&& (msg->rsp[2] != IPMI_NODE_BUSY_ERR)
&& (msg->rsp[2] != IPMI_LOST_ARBITRATION_ERR)
&& (msg->rsp[2] != IPMI_BUS_ERR)
&& (msg->rsp[2] != IPMI_NAK_ON_WRITE_ERR)) {
int chan = msg->rsp[3] & 0xf;
/* Got an error sending the message, handle it. */
if (chan >= IPMI_MAX_CHANNELS)
; /* This shouldn't happen */
else if ((intf->channels[chan].medium
== IPMI_CHANNEL_MEDIUM_8023LAN)
|| (intf->channels[chan].medium
== IPMI_CHANNEL_MEDIUM_ASYNC))
ipmi_inc_stat(intf, sent_lan_command_errs);
else
ipmi_inc_stat(intf, sent_ipmb_command_errs);
intf_err_seq(intf, msg->msgid, msg->rsp[2]);
} else
/* The message was sent, start the timer. */
intf_start_seq_timer(intf, msg->msgid);
free_msg:
ipmi_free_smi_msg(msg);
} else {
/*
* To preserve message order, we keep a queue and deliver from
* a tasklet.
*/
if (!run_to_completion)
spin_lock_irqsave(&intf->waiting_rcv_msgs_lock, flags);
list_add_tail(&msg->link, &intf->waiting_rcv_msgs);
if (!run_to_completion)
spin_unlock_irqrestore(&intf->waiting_rcv_msgs_lock,
flags);
}
if (!run_to_completion)
spin_lock_irqsave(&intf->xmit_msgs_lock, flags);
/*
* We can get an asynchronous event or receive message in addition
* to commands we send.
*/
if (msg == intf->curr_msg)
intf->curr_msg = NULL;
if (!run_to_completion)
spin_unlock_irqrestore(&intf->xmit_msgs_lock, flags);
if (run_to_completion)
smi_recv_tasklet((unsigned long) intf);
else
tasklet_schedule(&intf->recv_tasklet);
}
EXPORT_SYMBOL(ipmi_smi_msg_received);
void ipmi_smi_watchdog_pretimeout(ipmi_smi_t intf)
{
if (intf->in_shutdown)
return;
atomic_set(&intf->watchdog_pretimeouts_to_deliver, 1);
tasklet_schedule(&intf->recv_tasklet);
}
EXPORT_SYMBOL(ipmi_smi_watchdog_pretimeout);
static struct ipmi_smi_msg *
smi_from_recv_msg(ipmi_smi_t intf, struct ipmi_recv_msg *recv_msg,
unsigned char seq, long seqid)
{
struct ipmi_smi_msg *smi_msg = ipmi_alloc_smi_msg();
if (!smi_msg)
/*
* If we can't allocate the message, then just return, we
* get 4 retries, so this should be ok.
*/
return NULL;
memcpy(smi_msg->data, recv_msg->msg.data, recv_msg->msg.data_len);
smi_msg->data_size = recv_msg->msg.data_len;
smi_msg->msgid = STORE_SEQ_IN_MSGID(seq, seqid);
#ifdef DEBUG_MSGING
{
int m;
printk("Resend: ");
for (m = 0; m < smi_msg->data_size; m++)
printk(" %2.2x", smi_msg->data[m]);
printk("\n");
}
#endif
return smi_msg;
}
static void check_msg_timeout(ipmi_smi_t intf, struct seq_table *ent,
struct list_head *timeouts, long timeout_period,
int slot, unsigned long *flags,
unsigned int *waiting_msgs)
{
struct ipmi_recv_msg *msg;
const struct ipmi_smi_handlers *handlers;
if (intf->in_shutdown)
return;
if (!ent->inuse)
return;
ent->timeout -= timeout_period;
if (ent->timeout > 0) {
(*waiting_msgs)++;
return;
}
if (ent->retries_left == 0) {
/* The message has used all its retries. */
ent->inuse = 0;
msg = ent->recv_msg;
list_add_tail(&msg->link, timeouts);
if (ent->broadcast)
ipmi_inc_stat(intf, timed_out_ipmb_broadcasts);
else if (is_lan_addr(&ent->recv_msg->addr))
ipmi_inc_stat(intf, timed_out_lan_commands);
else
ipmi_inc_stat(intf, timed_out_ipmb_commands);
} else {
struct ipmi_smi_msg *smi_msg;
/* More retries, send again. */
(*waiting_msgs)++;
/*
* Start with the max timer, set to normal timer after
* the message is sent.
*/
ent->timeout = MAX_MSG_TIMEOUT;
ent->retries_left--;
smi_msg = smi_from_recv_msg(intf, ent->recv_msg, slot,
ent->seqid);
if (!smi_msg) {
if (is_lan_addr(&ent->recv_msg->addr))
ipmi_inc_stat(intf,
dropped_rexmit_lan_commands);
else
ipmi_inc_stat(intf,
dropped_rexmit_ipmb_commands);
return;
}
spin_unlock_irqrestore(&intf->seq_lock, *flags);
/*
* Send the new message. We send with a zero
* priority. It timed out, I doubt time is that
* critical now, and high priority messages are really
* only for messages to the local MC, which don't get
* resent.
*/
handlers = intf->handlers;
if (handlers) {
if (is_lan_addr(&ent->recv_msg->addr))
ipmi_inc_stat(intf,
retransmitted_lan_commands);
else
ipmi_inc_stat(intf,
retransmitted_ipmb_commands);
smi_send(intf, handlers, smi_msg, 0);
} else
ipmi_free_smi_msg(smi_msg);
spin_lock_irqsave(&intf->seq_lock, *flags);
}
}
static unsigned int ipmi_timeout_handler(ipmi_smi_t intf, long timeout_period)
{
struct list_head timeouts;
struct ipmi_recv_msg *msg, *msg2;
unsigned long flags;
int i;
unsigned int waiting_msgs = 0;
/*
* Go through the seq table and find any messages that
* have timed out, putting them in the timeouts
* list.
*/
INIT_LIST_HEAD(&timeouts);
spin_lock_irqsave(&intf->seq_lock, flags);
for (i = 0; i < IPMI_IPMB_NUM_SEQ; i++)
check_msg_timeout(intf, &(intf->seq_table[i]),
&timeouts, timeout_period, i,
&flags, &waiting_msgs);
spin_unlock_irqrestore(&intf->seq_lock, flags);
list_for_each_entry_safe(msg, msg2, &timeouts, link)
deliver_err_response(msg, IPMI_TIMEOUT_COMPLETION_CODE);
/*
* Maintenance mode handling. Check the timeout
* optimistically before we claim the lock. It may
* mean a timeout gets missed occasionally, but that
* only means the timeout gets extended by one period
* in that case. No big deal, and it avoids the lock
* most of the time.
*/
if (intf->auto_maintenance_timeout > 0) {
spin_lock_irqsave(&intf->maintenance_mode_lock, flags);
if (intf->auto_maintenance_timeout > 0) {
intf->auto_maintenance_timeout
-= timeout_period;
if (!intf->maintenance_mode
&& (intf->auto_maintenance_timeout <= 0)) {
intf->maintenance_mode_enable = false;
maintenance_mode_update(intf);
}
}
spin_unlock_irqrestore(&intf->maintenance_mode_lock,
flags);
}
tasklet_schedule(&intf->recv_tasklet);
return waiting_msgs;
}
static void ipmi_request_event(ipmi_smi_t intf)
{
/* No event requests when in maintenance mode. */
if (intf->maintenance_mode_enable)
return;
if (!intf->in_shutdown)
intf->handlers->request_events(intf->send_info);
}
static struct timer_list ipmi_timer;
static atomic_t stop_operation;
static void ipmi_timeout(unsigned long data)
{
ipmi_smi_t intf;
int nt = 0;
if (atomic_read(&stop_operation))
return;
rcu_read_lock();
list_for_each_entry_rcu(intf, &ipmi_interfaces, link) {
int lnt = 0;
if (atomic_read(&intf->event_waiters)) {
intf->ticks_to_req_ev--;
if (intf->ticks_to_req_ev == 0) {
ipmi_request_event(intf);
intf->ticks_to_req_ev = IPMI_REQUEST_EV_TIME;
}
lnt++;
}
lnt += ipmi_timeout_handler(intf, IPMI_TIMEOUT_TIME);
lnt = !!lnt;
if (lnt != intf->last_needs_timer &&
intf->handlers->set_need_watch)
intf->handlers->set_need_watch(intf->send_info, lnt);
intf->last_needs_timer = lnt;
nt += lnt;
}
rcu_read_unlock();
if (nt)
mod_timer(&ipmi_timer, jiffies + IPMI_TIMEOUT_JIFFIES);
}
static void need_waiter(ipmi_smi_t intf)
{
/* Racy, but worst case we start the timer twice. */
if (!timer_pending(&ipmi_timer))
mod_timer(&ipmi_timer, jiffies + IPMI_TIMEOUT_JIFFIES);
}
static atomic_t smi_msg_inuse_count = ATOMIC_INIT(0);
static atomic_t recv_msg_inuse_count = ATOMIC_INIT(0);
static void free_smi_msg(struct ipmi_smi_msg *msg)
{
atomic_dec(&smi_msg_inuse_count);
kfree(msg);
}
struct ipmi_smi_msg *ipmi_alloc_smi_msg(void)
{
struct ipmi_smi_msg *rv;
rv = kmalloc(sizeof(struct ipmi_smi_msg), GFP_ATOMIC);
if (rv) {
rv->done = free_smi_msg;
rv->user_data = NULL;
atomic_inc(&smi_msg_inuse_count);
}
return rv;
}
EXPORT_SYMBOL(ipmi_alloc_smi_msg);
static void free_recv_msg(struct ipmi_recv_msg *msg)
{
atomic_dec(&recv_msg_inuse_count);
kfree(msg);
}
static struct ipmi_recv_msg *ipmi_alloc_recv_msg(void)
{
struct ipmi_recv_msg *rv;
rv = kmalloc(sizeof(struct ipmi_recv_msg), GFP_ATOMIC);
if (rv) {
rv->user = NULL;
rv->done = free_recv_msg;
atomic_inc(&recv_msg_inuse_count);
}
return rv;
}
void ipmi_free_recv_msg(struct ipmi_recv_msg *msg)
{
if (msg->user)
kref_put(&msg->user->refcount, free_user);
msg->done(msg);
}
EXPORT_SYMBOL(ipmi_free_recv_msg);
#ifdef CONFIG_IPMI_PANIC_EVENT
static atomic_t panic_done_count = ATOMIC_INIT(0);
static void dummy_smi_done_handler(struct ipmi_smi_msg *msg)
{
atomic_dec(&panic_done_count);
}
static void dummy_recv_done_handler(struct ipmi_recv_msg *msg)
{
atomic_dec(&panic_done_count);
}
/*
* Inside a panic, send a message and wait for a response.
*/
static void ipmi_panic_request_and_wait(ipmi_smi_t intf,
struct ipmi_addr *addr,
struct kernel_ipmi_msg *msg)
{
struct ipmi_smi_msg smi_msg;
struct ipmi_recv_msg recv_msg;
int rv;
smi_msg.done = dummy_smi_done_handler;
recv_msg.done = dummy_recv_done_handler;
atomic_add(2, &panic_done_count);
rv = i_ipmi_request(NULL,
intf,
addr,
0,
msg,
intf,
&smi_msg,
&recv_msg,
0,
intf->channels[0].address,
intf->channels[0].lun,
0, 1); /* Don't retry, and don't wait. */
if (rv)
atomic_sub(2, &panic_done_count);
else if (intf->handlers->flush_messages)
intf->handlers->flush_messages(intf->send_info);
while (atomic_read(&panic_done_count) != 0)
ipmi_poll(intf);
}
#ifdef CONFIG_IPMI_PANIC_STRING
static void event_receiver_fetcher(ipmi_smi_t intf, struct ipmi_recv_msg *msg)
{
if ((msg->addr.addr_type == IPMI_SYSTEM_INTERFACE_ADDR_TYPE)
&& (msg->msg.netfn == IPMI_NETFN_SENSOR_EVENT_RESPONSE)
&& (msg->msg.cmd == IPMI_GET_EVENT_RECEIVER_CMD)
&& (msg->msg.data[0] == IPMI_CC_NO_ERROR)) {
/* A get event receiver command, save it. */
intf->event_receiver = msg->msg.data[1];
intf->event_receiver_lun = msg->msg.data[2] & 0x3;
}
}
static void device_id_fetcher(ipmi_smi_t intf, struct ipmi_recv_msg *msg)
{
if ((msg->addr.addr_type == IPMI_SYSTEM_INTERFACE_ADDR_TYPE)
&& (msg->msg.netfn == IPMI_NETFN_APP_RESPONSE)
&& (msg->msg.cmd == IPMI_GET_DEVICE_ID_CMD)
&& (msg->msg.data[0] == IPMI_CC_NO_ERROR)) {
/*
* A get device id command, save if we are an event
* receiver or generator.
*/
intf->local_sel_device = (msg->msg.data[6] >> 2) & 1;
intf->local_event_generator = (msg->msg.data[6] >> 5) & 1;
}
}
#endif
static void send_panic_events(char *str)
{
struct kernel_ipmi_msg msg;
ipmi_smi_t intf;
unsigned char data[16];
struct ipmi_system_interface_addr *si;
struct ipmi_addr addr;
si = (struct ipmi_system_interface_addr *) &addr;
si->addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
si->channel = IPMI_BMC_CHANNEL;
si->lun = 0;
/* Fill in an event telling that we have failed. */
msg.netfn = 0x04; /* Sensor or Event. */
msg.cmd = 2; /* Platform event command. */
msg.data = data;
msg.data_len = 8;
data[0] = 0x41; /* Kernel generator ID, IPMI table 5-4 */
data[1] = 0x03; /* This is for IPMI 1.0. */
data[2] = 0x20; /* OS Critical Stop, IPMI table 36-3 */
data[4] = 0x6f; /* Sensor specific, IPMI table 36-1 */
data[5] = 0xa1; /* Runtime stop OEM bytes 2 & 3. */
/*
* Put a few breadcrumbs in. Hopefully later we can add more things
* to make the panic events more useful.
*/
if (str) {
data[3] = str[0];
data[6] = str[1];
data[7] = str[2];
}
/* For every registered interface, send the event. */
list_for_each_entry_rcu(intf, &ipmi_interfaces, link) {
if (!intf->handlers)
/* Interface is not ready. */
continue;
/* Send the event announcing the panic. */
ipmi_panic_request_and_wait(intf, &addr, &msg);
}
#ifdef CONFIG_IPMI_PANIC_STRING
/*
* On every interface, dump a bunch of OEM event holding the
* string.
*/
if (!str)
return;
/* For every registered interface, send the event. */
list_for_each_entry_rcu(intf, &ipmi_interfaces, link) {
char *p = str;
struct ipmi_ipmb_addr *ipmb;
int j;
if (intf->intf_num == -1)
/* Interface was not ready yet. */
continue;
/*
* intf_num is used as an marker to tell if the
* interface is valid. Thus we need a read barrier to
* make sure data fetched before checking intf_num
* won't be used.
*/
smp_rmb();
/*
* First job here is to figure out where to send the
* OEM events. There's no way in IPMI to send OEM
* events using an event send command, so we have to
* find the SEL to put them in and stick them in
* there.
*/
/* Get capabilities from the get device id. */
intf->local_sel_device = 0;
intf->local_event_generator = 0;
intf->event_receiver = 0;
/* Request the device info from the local MC. */
msg.netfn = IPMI_NETFN_APP_REQUEST;
msg.cmd = IPMI_GET_DEVICE_ID_CMD;
msg.data = NULL;
msg.data_len = 0;
intf->null_user_handler = device_id_fetcher;
ipmi_panic_request_and_wait(intf, &addr, &msg);
if (intf->local_event_generator) {
/* Request the event receiver from the local MC. */
msg.netfn = IPMI_NETFN_SENSOR_EVENT_REQUEST;
msg.cmd = IPMI_GET_EVENT_RECEIVER_CMD;
msg.data = NULL;
msg.data_len = 0;
intf->null_user_handler = event_receiver_fetcher;
ipmi_panic_request_and_wait(intf, &addr, &msg);
}
intf->null_user_handler = NULL;
/*
* Validate the event receiver. The low bit must not
* be 1 (it must be a valid IPMB address), it cannot
* be zero, and it must not be my address.
*/
if (((intf->event_receiver & 1) == 0)
&& (intf->event_receiver != 0)
&& (intf->event_receiver != intf->channels[0].address)) {
/*
* The event receiver is valid, send an IPMB
* message.
*/
ipmb = (struct ipmi_ipmb_addr *) &addr;
ipmb->addr_type = IPMI_IPMB_ADDR_TYPE;
ipmb->channel = 0; /* FIXME - is this right? */
ipmb->lun = intf->event_receiver_lun;
ipmb->slave_addr = intf->event_receiver;
} else if (intf->local_sel_device) {
/*
* The event receiver was not valid (or was
* me), but I am an SEL device, just dump it
* in my SEL.
*/
si = (struct ipmi_system_interface_addr *) &addr;
si->addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
si->channel = IPMI_BMC_CHANNEL;
si->lun = 0;
} else
continue; /* No where to send the event. */
msg.netfn = IPMI_NETFN_STORAGE_REQUEST; /* Storage. */
msg.cmd = IPMI_ADD_SEL_ENTRY_CMD;
msg.data = data;
msg.data_len = 16;
j = 0;
while (*p) {
int size = strlen(p);
if (size > 11)
size = 11;
data[0] = 0;
data[1] = 0;
data[2] = 0xf0; /* OEM event without timestamp. */
data[3] = intf->channels[0].address;
data[4] = j++; /* sequence # */
/*
* Always give 11 bytes, so strncpy will fill
* it with zeroes for me.
*/
strncpy(data+5, p, 11);
p += size;
ipmi_panic_request_and_wait(intf, &addr, &msg);
}
}
#endif /* CONFIG_IPMI_PANIC_STRING */
}
#endif /* CONFIG_IPMI_PANIC_EVENT */
static int has_panicked;
static int panic_event(struct notifier_block *this,
unsigned long event,
void *ptr)
{
ipmi_smi_t intf;
if (has_panicked)
return NOTIFY_DONE;
has_panicked = 1;
/* For every registered interface, set it to run to completion. */
list_for_each_entry_rcu(intf, &ipmi_interfaces, link) {
if (!intf->handlers)
/* Interface is not ready. */
continue;
/*
* If we were interrupted while locking xmit_msgs_lock or
* waiting_rcv_msgs_lock, the corresponding list may be
* corrupted. In this case, drop items on the list for
* the safety.
*/
if (!spin_trylock(&intf->xmit_msgs_lock)) {
INIT_LIST_HEAD(&intf->xmit_msgs);
INIT_LIST_HEAD(&intf->hp_xmit_msgs);
} else
spin_unlock(&intf->xmit_msgs_lock);
if (!spin_trylock(&intf->waiting_rcv_msgs_lock))
INIT_LIST_HEAD(&intf->waiting_rcv_msgs);
else
spin_unlock(&intf->waiting_rcv_msgs_lock);
intf->run_to_completion = 1;
intf->handlers->set_run_to_completion(intf->send_info, 1);
}
#ifdef CONFIG_IPMI_PANIC_EVENT
send_panic_events(ptr);
#endif
return NOTIFY_DONE;
}
static struct notifier_block panic_block = {
.notifier_call = panic_event,
.next = NULL,
.priority = 200 /* priority: INT_MAX >= x >= 0 */
};
static int ipmi_init_msghandler(void)
{
int rv;
if (initialized)
return 0;
rv = driver_register(&ipmidriver.driver);
if (rv) {
printk(KERN_ERR PFX "Could not register IPMI driver\n");
return rv;
}
printk(KERN_INFO "ipmi message handler version "
IPMI_DRIVER_VERSION "\n");
#ifdef CONFIG_PROC_FS
proc_ipmi_root = proc_mkdir("ipmi", NULL);
if (!proc_ipmi_root) {
printk(KERN_ERR PFX "Unable to create IPMI proc dir");
driver_unregister(&ipmidriver.driver);
return -ENOMEM;
}
#endif /* CONFIG_PROC_FS */
setup_timer(&ipmi_timer, ipmi_timeout, 0);
mod_timer(&ipmi_timer, jiffies + IPMI_TIMEOUT_JIFFIES);
atomic_notifier_chain_register(&panic_notifier_list, &panic_block);
initialized = 1;
return 0;
}
static int __init ipmi_init_msghandler_mod(void)
{
ipmi_init_msghandler();
return 0;
}
static void __exit cleanup_ipmi(void)
{
int count;
if (!initialized)
return;
atomic_notifier_chain_unregister(&panic_notifier_list, &panic_block);
/*
* This can't be called if any interfaces exist, so no worry
* about shutting down the interfaces.
*/
/*
* Tell the timer to stop, then wait for it to stop. This
* avoids problems with race conditions removing the timer
* here.
*/
atomic_inc(&stop_operation);
del_timer_sync(&ipmi_timer);
#ifdef CONFIG_PROC_FS
proc_remove(proc_ipmi_root);
#endif /* CONFIG_PROC_FS */
driver_unregister(&ipmidriver.driver);
initialized = 0;
/* Check for buffer leaks. */
count = atomic_read(&smi_msg_inuse_count);
if (count != 0)
printk(KERN_WARNING PFX "SMI message count %d at exit\n",
count);
count = atomic_read(&recv_msg_inuse_count);
if (count != 0)
printk(KERN_WARNING PFX "recv message count %d at exit\n",
count);
}
module_exit(cleanup_ipmi);
module_init(ipmi_init_msghandler_mod);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Corey Minyard <minyard@mvista.com>");
MODULE_DESCRIPTION("Incoming and outgoing message routing for an IPMI"
" interface.");
MODULE_VERSION(IPMI_DRIVER_VERSION);
| gpl-2.0 |
longqiany/linux | arch/unicore32/kernel/irq.c | 864 | 8511 | /*
* linux/arch/unicore32/kernel/irq.c
*
* Code specific to PKUnity SoC and UniCore ISA
*
* Copyright (C) 2001-2010 GUAN Xue-tao
*
* 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_stat.h>
#include <linux/module.h>
#include <linux/signal.h>
#include <linux/ioport.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/random.h>
#include <linux/smp.h>
#include <linux/init.h>
#include <linux/seq_file.h>
#include <linux/errno.h>
#include <linux/list.h>
#include <linux/kallsyms.h>
#include <linux/proc_fs.h>
#include <linux/syscore_ops.h>
#include <linux/gpio.h>
#include <mach/hardware.h>
#include "setup.h"
/*
* PKUnity GPIO edge detection for IRQs:
* IRQs are generated on Falling-Edge, Rising-Edge, or both.
* Use this instead of directly setting GRER/GFER.
*/
static int GPIO_IRQ_rising_edge;
static int GPIO_IRQ_falling_edge;
static int GPIO_IRQ_mask = 0;
#define GPIO_MASK(irq) (1 << (irq - IRQ_GPIO0))
static int puv3_gpio_type(struct irq_data *d, unsigned int type)
{
unsigned int mask;
if (d->irq < IRQ_GPIOHIGH)
mask = 1 << d->irq;
else
mask = GPIO_MASK(d->irq);
if (type == IRQ_TYPE_PROBE) {
if ((GPIO_IRQ_rising_edge | GPIO_IRQ_falling_edge) & mask)
return 0;
type = IRQ_TYPE_EDGE_RISING | IRQ_TYPE_EDGE_FALLING;
}
if (type & IRQ_TYPE_EDGE_RISING)
GPIO_IRQ_rising_edge |= mask;
else
GPIO_IRQ_rising_edge &= ~mask;
if (type & IRQ_TYPE_EDGE_FALLING)
GPIO_IRQ_falling_edge |= mask;
else
GPIO_IRQ_falling_edge &= ~mask;
writel(GPIO_IRQ_rising_edge & GPIO_IRQ_mask, GPIO_GRER);
writel(GPIO_IRQ_falling_edge & GPIO_IRQ_mask, GPIO_GFER);
return 0;
}
/*
* GPIO IRQs must be acknowledged. This is for IRQs from 0 to 7.
*/
static void puv3_low_gpio_ack(struct irq_data *d)
{
writel((1 << d->irq), GPIO_GEDR);
}
static void puv3_low_gpio_mask(struct irq_data *d)
{
writel(readl(INTC_ICMR) & ~(1 << d->irq), INTC_ICMR);
}
static void puv3_low_gpio_unmask(struct irq_data *d)
{
writel(readl(INTC_ICMR) | (1 << d->irq), INTC_ICMR);
}
static int puv3_low_gpio_wake(struct irq_data *d, unsigned int on)
{
if (on)
writel(readl(PM_PWER) | (1 << d->irq), PM_PWER);
else
writel(readl(PM_PWER) & ~(1 << d->irq), PM_PWER);
return 0;
}
static struct irq_chip puv3_low_gpio_chip = {
.name = "GPIO-low",
.irq_ack = puv3_low_gpio_ack,
.irq_mask = puv3_low_gpio_mask,
.irq_unmask = puv3_low_gpio_unmask,
.irq_set_type = puv3_gpio_type,
.irq_set_wake = puv3_low_gpio_wake,
};
/*
* IRQ8 (GPIO0 through 27) handler. We enter here with the
* irq_controller_lock held, and IRQs disabled. Decode the IRQ
* and call the handler.
*/
static void puv3_gpio_handler(struct irq_desc *desc)
{
unsigned int mask, irq;
mask = readl(GPIO_GEDR);
do {
/*
* clear down all currently active IRQ sources.
* We will be processing them all.
*/
writel(mask, GPIO_GEDR);
irq = IRQ_GPIO0;
do {
if (mask & 1)
generic_handle_irq(irq);
mask >>= 1;
irq++;
} while (mask);
mask = readl(GPIO_GEDR);
} while (mask);
}
/*
* GPIO0-27 edge IRQs need to be handled specially.
* In addition, the IRQs are all collected up into one bit in the
* interrupt controller registers.
*/
static void puv3_high_gpio_ack(struct irq_data *d)
{
unsigned int mask = GPIO_MASK(d->irq);
writel(mask, GPIO_GEDR);
}
static void puv3_high_gpio_mask(struct irq_data *d)
{
unsigned int mask = GPIO_MASK(d->irq);
GPIO_IRQ_mask &= ~mask;
writel(readl(GPIO_GRER) & ~mask, GPIO_GRER);
writel(readl(GPIO_GFER) & ~mask, GPIO_GFER);
}
static void puv3_high_gpio_unmask(struct irq_data *d)
{
unsigned int mask = GPIO_MASK(d->irq);
GPIO_IRQ_mask |= mask;
writel(GPIO_IRQ_rising_edge & GPIO_IRQ_mask, GPIO_GRER);
writel(GPIO_IRQ_falling_edge & GPIO_IRQ_mask, GPIO_GFER);
}
static int puv3_high_gpio_wake(struct irq_data *d, unsigned int on)
{
if (on)
writel(readl(PM_PWER) | PM_PWER_GPIOHIGH, PM_PWER);
else
writel(readl(PM_PWER) & ~PM_PWER_GPIOHIGH, PM_PWER);
return 0;
}
static struct irq_chip puv3_high_gpio_chip = {
.name = "GPIO-high",
.irq_ack = puv3_high_gpio_ack,
.irq_mask = puv3_high_gpio_mask,
.irq_unmask = puv3_high_gpio_unmask,
.irq_set_type = puv3_gpio_type,
.irq_set_wake = puv3_high_gpio_wake,
};
/*
* We don't need to ACK IRQs on the PKUnity unless they're GPIOs
* this is for internal IRQs i.e. from 8 to 31.
*/
static void puv3_mask_irq(struct irq_data *d)
{
writel(readl(INTC_ICMR) & ~(1 << d->irq), INTC_ICMR);
}
static void puv3_unmask_irq(struct irq_data *d)
{
writel(readl(INTC_ICMR) | (1 << d->irq), INTC_ICMR);
}
/*
* Apart form GPIOs, only the RTC alarm can be a wakeup event.
*/
static int puv3_set_wake(struct irq_data *d, unsigned int on)
{
if (d->irq == IRQ_RTCAlarm) {
if (on)
writel(readl(PM_PWER) | PM_PWER_RTC, PM_PWER);
else
writel(readl(PM_PWER) & ~PM_PWER_RTC, PM_PWER);
return 0;
}
return -EINVAL;
}
static struct irq_chip puv3_normal_chip = {
.name = "PKUnity-v3",
.irq_ack = puv3_mask_irq,
.irq_mask = puv3_mask_irq,
.irq_unmask = puv3_unmask_irq,
.irq_set_wake = puv3_set_wake,
};
static struct resource irq_resource = {
.name = "irqs",
.start = io_v2p(PKUNITY_INTC_BASE),
.end = io_v2p(PKUNITY_INTC_BASE) + 0xFFFFF,
};
static struct puv3_irq_state {
unsigned int saved;
unsigned int icmr;
unsigned int iclr;
unsigned int iccr;
} puv3_irq_state;
static int puv3_irq_suspend(void)
{
struct puv3_irq_state *st = &puv3_irq_state;
st->saved = 1;
st->icmr = readl(INTC_ICMR);
st->iclr = readl(INTC_ICLR);
st->iccr = readl(INTC_ICCR);
/*
* Disable all GPIO-based interrupts.
*/
writel(readl(INTC_ICMR) & ~(0x1ff), INTC_ICMR);
/*
* Set the appropriate edges for wakeup.
*/
writel(readl(PM_PWER) & GPIO_IRQ_rising_edge, GPIO_GRER);
writel(readl(PM_PWER) & GPIO_IRQ_falling_edge, GPIO_GFER);
/*
* Clear any pending GPIO interrupts.
*/
writel(readl(GPIO_GEDR), GPIO_GEDR);
return 0;
}
static void puv3_irq_resume(void)
{
struct puv3_irq_state *st = &puv3_irq_state;
if (st->saved) {
writel(st->iccr, INTC_ICCR);
writel(st->iclr, INTC_ICLR);
writel(GPIO_IRQ_rising_edge & GPIO_IRQ_mask, GPIO_GRER);
writel(GPIO_IRQ_falling_edge & GPIO_IRQ_mask, GPIO_GFER);
writel(st->icmr, INTC_ICMR);
}
}
static struct syscore_ops puv3_irq_syscore_ops = {
.suspend = puv3_irq_suspend,
.resume = puv3_irq_resume,
};
static int __init puv3_irq_init_syscore(void)
{
register_syscore_ops(&puv3_irq_syscore_ops);
return 0;
}
device_initcall(puv3_irq_init_syscore);
void __init init_IRQ(void)
{
unsigned int irq;
request_resource(&iomem_resource, &irq_resource);
/* disable all IRQs */
writel(0, INTC_ICMR);
/* all IRQs are IRQ, not REAL */
writel(0, INTC_ICLR);
/* clear all GPIO edge detects */
writel(FMASK(8, 0) & ~FIELD(1, 1, GPI_SOFF_REQ), GPIO_GPIR);
writel(0, GPIO_GFER);
writel(0, GPIO_GRER);
writel(0x0FFFFFFF, GPIO_GEDR);
writel(1, INTC_ICCR);
for (irq = 0; irq < IRQ_GPIOHIGH; irq++) {
irq_set_chip(irq, &puv3_low_gpio_chip);
irq_set_handler(irq, handle_edge_irq);
irq_modify_status(irq,
IRQ_NOREQUEST | IRQ_NOPROBE | IRQ_NOAUTOEN,
0);
}
for (irq = IRQ_GPIOHIGH + 1; irq < IRQ_GPIO0; irq++) {
irq_set_chip(irq, &puv3_normal_chip);
irq_set_handler(irq, handle_level_irq);
irq_modify_status(irq,
IRQ_NOREQUEST | IRQ_NOAUTOEN,
IRQ_NOPROBE);
}
for (irq = IRQ_GPIO0; irq <= IRQ_GPIO27; irq++) {
irq_set_chip(irq, &puv3_high_gpio_chip);
irq_set_handler(irq, handle_edge_irq);
irq_modify_status(irq,
IRQ_NOREQUEST | IRQ_NOPROBE | IRQ_NOAUTOEN,
0);
}
/*
* Install handler for GPIO 0-27 edge detect interrupts
*/
irq_set_chip(IRQ_GPIOHIGH, &puv3_normal_chip);
irq_set_chained_handler(IRQ_GPIOHIGH, puv3_gpio_handler);
#ifdef CONFIG_PUV3_GPIO
puv3_init_gpio();
#endif
}
/*
* do_IRQ handles all hardware IRQ's. Decoded IRQs should not
* come via this function. Instead, they should provide their
* own 'handler'
*/
asmlinkage void asm_do_IRQ(unsigned int irq, struct pt_regs *regs)
{
struct pt_regs *old_regs = set_irq_regs(regs);
irq_enter();
/*
* Some hardware gives randomly wrong interrupts. Rather
* than crashing, do something sensible.
*/
if (unlikely(irq >= nr_irqs)) {
if (printk_ratelimit())
printk(KERN_WARNING "Bad IRQ%u\n", irq);
ack_bad_irq(irq);
} else {
generic_handle_irq(irq);
}
irq_exit();
set_irq_regs(old_regs);
}
| gpl-2.0 |
ddilber/telegrauq7-linux | drivers/dma/ste_dma40_ll.c | 2144 | 11407 | /*
* Copyright (C) ST-Ericsson SA 2007-2010
* Author: Per Forlin <per.forlin@stericsson.com> for ST-Ericsson
* Author: Jonas Aaberg <jonas.aberg@stericsson.com> for ST-Ericsson
* License terms: GNU General Public License (GPL) version 2
*/
#include <linux/kernel.h>
#include <linux/platform_data/dma-ste-dma40.h>
#include "ste_dma40_ll.h"
/* Sets up proper LCSP1 and LCSP3 register for a logical channel */
void d40_log_cfg(struct stedma40_chan_cfg *cfg,
u32 *lcsp1, u32 *lcsp3)
{
u32 l3 = 0; /* dst */
u32 l1 = 0; /* src */
/* src is mem? -> increase address pos */
if (cfg->dir == STEDMA40_MEM_TO_PERIPH ||
cfg->dir == STEDMA40_MEM_TO_MEM)
l1 |= 1 << D40_MEM_LCSP1_SCFG_INCR_POS;
/* dst is mem? -> increase address pos */
if (cfg->dir == STEDMA40_PERIPH_TO_MEM ||
cfg->dir == STEDMA40_MEM_TO_MEM)
l3 |= 1 << D40_MEM_LCSP3_DCFG_INCR_POS;
/* src is hw? -> master port 1 */
if (cfg->dir == STEDMA40_PERIPH_TO_MEM ||
cfg->dir == STEDMA40_PERIPH_TO_PERIPH)
l1 |= 1 << D40_MEM_LCSP1_SCFG_MST_POS;
/* dst is hw? -> master port 1 */
if (cfg->dir == STEDMA40_MEM_TO_PERIPH ||
cfg->dir == STEDMA40_PERIPH_TO_PERIPH)
l3 |= 1 << D40_MEM_LCSP3_DCFG_MST_POS;
l3 |= 1 << D40_MEM_LCSP3_DCFG_EIM_POS;
l3 |= cfg->dst_info.psize << D40_MEM_LCSP3_DCFG_PSIZE_POS;
l3 |= cfg->dst_info.data_width << D40_MEM_LCSP3_DCFG_ESIZE_POS;
l1 |= 1 << D40_MEM_LCSP1_SCFG_EIM_POS;
l1 |= cfg->src_info.psize << D40_MEM_LCSP1_SCFG_PSIZE_POS;
l1 |= cfg->src_info.data_width << D40_MEM_LCSP1_SCFG_ESIZE_POS;
*lcsp1 = l1;
*lcsp3 = l3;
}
/* Sets up SRC and DST CFG register for both logical and physical channels */
void d40_phy_cfg(struct stedma40_chan_cfg *cfg,
u32 *src_cfg, u32 *dst_cfg, bool is_log)
{
u32 src = 0;
u32 dst = 0;
if (!is_log) {
/* Physical channel */
if ((cfg->dir == STEDMA40_PERIPH_TO_MEM) ||
(cfg->dir == STEDMA40_PERIPH_TO_PERIPH)) {
/* Set master port to 1 */
src |= 1 << D40_SREG_CFG_MST_POS;
src |= D40_TYPE_TO_EVENT(cfg->src_dev_type);
if (cfg->src_info.flow_ctrl == STEDMA40_NO_FLOW_CTRL)
src |= 1 << D40_SREG_CFG_PHY_TM_POS;
else
src |= 3 << D40_SREG_CFG_PHY_TM_POS;
}
if ((cfg->dir == STEDMA40_MEM_TO_PERIPH) ||
(cfg->dir == STEDMA40_PERIPH_TO_PERIPH)) {
/* Set master port to 1 */
dst |= 1 << D40_SREG_CFG_MST_POS;
dst |= D40_TYPE_TO_EVENT(cfg->dst_dev_type);
if (cfg->dst_info.flow_ctrl == STEDMA40_NO_FLOW_CTRL)
dst |= 1 << D40_SREG_CFG_PHY_TM_POS;
else
dst |= 3 << D40_SREG_CFG_PHY_TM_POS;
}
/* Interrupt on end of transfer for destination */
dst |= 1 << D40_SREG_CFG_TIM_POS;
/* Generate interrupt on error */
src |= 1 << D40_SREG_CFG_EIM_POS;
dst |= 1 << D40_SREG_CFG_EIM_POS;
/* PSIZE */
if (cfg->src_info.psize != STEDMA40_PSIZE_PHY_1) {
src |= 1 << D40_SREG_CFG_PHY_PEN_POS;
src |= cfg->src_info.psize << D40_SREG_CFG_PSIZE_POS;
}
if (cfg->dst_info.psize != STEDMA40_PSIZE_PHY_1) {
dst |= 1 << D40_SREG_CFG_PHY_PEN_POS;
dst |= cfg->dst_info.psize << D40_SREG_CFG_PSIZE_POS;
}
/* Element size */
src |= cfg->src_info.data_width << D40_SREG_CFG_ESIZE_POS;
dst |= cfg->dst_info.data_width << D40_SREG_CFG_ESIZE_POS;
/* Set the priority bit to high for the physical channel */
if (cfg->high_priority) {
src |= 1 << D40_SREG_CFG_PRI_POS;
dst |= 1 << D40_SREG_CFG_PRI_POS;
}
} else {
/* Logical channel */
dst |= 1 << D40_SREG_CFG_LOG_GIM_POS;
src |= 1 << D40_SREG_CFG_LOG_GIM_POS;
}
if (cfg->src_info.big_endian)
src |= 1 << D40_SREG_CFG_LBE_POS;
if (cfg->dst_info.big_endian)
dst |= 1 << D40_SREG_CFG_LBE_POS;
*src_cfg = src;
*dst_cfg = dst;
}
static int d40_phy_fill_lli(struct d40_phy_lli *lli,
dma_addr_t data,
u32 data_size,
dma_addr_t next_lli,
u32 reg_cfg,
struct stedma40_half_channel_info *info,
unsigned int flags)
{
bool addr_inc = flags & LLI_ADDR_INC;
bool term_int = flags & LLI_TERM_INT;
unsigned int data_width = info->data_width;
int psize = info->psize;
int num_elems;
if (psize == STEDMA40_PSIZE_PHY_1)
num_elems = 1;
else
num_elems = 2 << psize;
/* Must be aligned */
if (!IS_ALIGNED(data, 0x1 << data_width))
return -EINVAL;
/* Transfer size can't be smaller than (num_elms * elem_size) */
if (data_size < num_elems * (0x1 << data_width))
return -EINVAL;
/* The number of elements. IE now many chunks */
lli->reg_elt = (data_size >> data_width) << D40_SREG_ELEM_PHY_ECNT_POS;
/*
* Distance to next element sized entry.
* Usually the size of the element unless you want gaps.
*/
if (addr_inc)
lli->reg_elt |= (0x1 << data_width) <<
D40_SREG_ELEM_PHY_EIDX_POS;
/* Where the data is */
lli->reg_ptr = data;
lli->reg_cfg = reg_cfg;
/* If this scatter list entry is the last one, no next link */
if (next_lli == 0)
lli->reg_lnk = 0x1 << D40_SREG_LNK_PHY_TCP_POS;
else
lli->reg_lnk = next_lli;
/* Set/clear interrupt generation on this link item.*/
if (term_int)
lli->reg_cfg |= 0x1 << D40_SREG_CFG_TIM_POS;
else
lli->reg_cfg &= ~(0x1 << D40_SREG_CFG_TIM_POS);
/* Post link */
lli->reg_lnk |= 0 << D40_SREG_LNK_PHY_PRE_POS;
return 0;
}
static int d40_seg_size(int size, int data_width1, int data_width2)
{
u32 max_w = max(data_width1, data_width2);
u32 min_w = min(data_width1, data_width2);
u32 seg_max = ALIGN(STEDMA40_MAX_SEG_SIZE << min_w, 1 << max_w);
if (seg_max > STEDMA40_MAX_SEG_SIZE)
seg_max -= (1 << max_w);
if (size <= seg_max)
return size;
if (size <= 2 * seg_max)
return ALIGN(size / 2, 1 << max_w);
return seg_max;
}
static struct d40_phy_lli *
d40_phy_buf_to_lli(struct d40_phy_lli *lli, dma_addr_t addr, u32 size,
dma_addr_t lli_phys, dma_addr_t first_phys, u32 reg_cfg,
struct stedma40_half_channel_info *info,
struct stedma40_half_channel_info *otherinfo,
unsigned long flags)
{
bool lastlink = flags & LLI_LAST_LINK;
bool addr_inc = flags & LLI_ADDR_INC;
bool term_int = flags & LLI_TERM_INT;
bool cyclic = flags & LLI_CYCLIC;
int err;
dma_addr_t next = lli_phys;
int size_rest = size;
int size_seg = 0;
/*
* This piece may be split up based on d40_seg_size(); we only want the
* term int on the last part.
*/
if (term_int)
flags &= ~LLI_TERM_INT;
do {
size_seg = d40_seg_size(size_rest, info->data_width,
otherinfo->data_width);
size_rest -= size_seg;
if (size_rest == 0 && term_int)
flags |= LLI_TERM_INT;
if (size_rest == 0 && lastlink)
next = cyclic ? first_phys : 0;
else
next = ALIGN(next + sizeof(struct d40_phy_lli),
D40_LLI_ALIGN);
err = d40_phy_fill_lli(lli, addr, size_seg, next,
reg_cfg, info, flags);
if (err)
goto err;
lli++;
if (addr_inc)
addr += size_seg;
} while (size_rest);
return lli;
err:
return NULL;
}
int d40_phy_sg_to_lli(struct scatterlist *sg,
int sg_len,
dma_addr_t target,
struct d40_phy_lli *lli_sg,
dma_addr_t lli_phys,
u32 reg_cfg,
struct stedma40_half_channel_info *info,
struct stedma40_half_channel_info *otherinfo,
unsigned long flags)
{
int total_size = 0;
int i;
struct scatterlist *current_sg = sg;
struct d40_phy_lli *lli = lli_sg;
dma_addr_t l_phys = lli_phys;
if (!target)
flags |= LLI_ADDR_INC;
for_each_sg(sg, current_sg, sg_len, i) {
dma_addr_t sg_addr = sg_dma_address(current_sg);
unsigned int len = sg_dma_len(current_sg);
dma_addr_t dst = target ?: sg_addr;
total_size += sg_dma_len(current_sg);
if (i == sg_len - 1)
flags |= LLI_TERM_INT | LLI_LAST_LINK;
l_phys = ALIGN(lli_phys + (lli - lli_sg) *
sizeof(struct d40_phy_lli), D40_LLI_ALIGN);
lli = d40_phy_buf_to_lli(lli, dst, len, l_phys, lli_phys,
reg_cfg, info, otherinfo, flags);
if (lli == NULL)
return -EINVAL;
}
return total_size;
}
/* DMA logical lli operations */
static void d40_log_lli_link(struct d40_log_lli *lli_dst,
struct d40_log_lli *lli_src,
int next, unsigned int flags)
{
bool interrupt = flags & LLI_TERM_INT;
u32 slos = 0;
u32 dlos = 0;
if (next != -EINVAL) {
slos = next * 2;
dlos = next * 2 + 1;
}
if (interrupt) {
lli_dst->lcsp13 |= D40_MEM_LCSP1_SCFG_TIM_MASK;
lli_dst->lcsp13 |= D40_MEM_LCSP3_DTCP_MASK;
}
lli_src->lcsp13 = (lli_src->lcsp13 & ~D40_MEM_LCSP1_SLOS_MASK) |
(slos << D40_MEM_LCSP1_SLOS_POS);
lli_dst->lcsp13 = (lli_dst->lcsp13 & ~D40_MEM_LCSP1_SLOS_MASK) |
(dlos << D40_MEM_LCSP1_SLOS_POS);
}
void d40_log_lli_lcpa_write(struct d40_log_lli_full *lcpa,
struct d40_log_lli *lli_dst,
struct d40_log_lli *lli_src,
int next, unsigned int flags)
{
d40_log_lli_link(lli_dst, lli_src, next, flags);
writel_relaxed(lli_src->lcsp02, &lcpa[0].lcsp0);
writel_relaxed(lli_src->lcsp13, &lcpa[0].lcsp1);
writel_relaxed(lli_dst->lcsp02, &lcpa[0].lcsp2);
writel_relaxed(lli_dst->lcsp13, &lcpa[0].lcsp3);
}
void d40_log_lli_lcla_write(struct d40_log_lli *lcla,
struct d40_log_lli *lli_dst,
struct d40_log_lli *lli_src,
int next, unsigned int flags)
{
d40_log_lli_link(lli_dst, lli_src, next, flags);
writel_relaxed(lli_src->lcsp02, &lcla[0].lcsp02);
writel_relaxed(lli_src->lcsp13, &lcla[0].lcsp13);
writel_relaxed(lli_dst->lcsp02, &lcla[1].lcsp02);
writel_relaxed(lli_dst->lcsp13, &lcla[1].lcsp13);
}
static void d40_log_fill_lli(struct d40_log_lli *lli,
dma_addr_t data, u32 data_size,
u32 reg_cfg,
u32 data_width,
unsigned int flags)
{
bool addr_inc = flags & LLI_ADDR_INC;
lli->lcsp13 = reg_cfg;
/* The number of elements to transfer */
lli->lcsp02 = ((data_size >> data_width) <<
D40_MEM_LCSP0_ECNT_POS) & D40_MEM_LCSP0_ECNT_MASK;
BUG_ON((data_size >> data_width) > STEDMA40_MAX_SEG_SIZE);
/* 16 LSBs address of the current element */
lli->lcsp02 |= data & D40_MEM_LCSP0_SPTR_MASK;
/* 16 MSBs address of the current element */
lli->lcsp13 |= data & D40_MEM_LCSP1_SPTR_MASK;
if (addr_inc)
lli->lcsp13 |= D40_MEM_LCSP1_SCFG_INCR_MASK;
}
static struct d40_log_lli *d40_log_buf_to_lli(struct d40_log_lli *lli_sg,
dma_addr_t addr,
int size,
u32 lcsp13, /* src or dst*/
u32 data_width1,
u32 data_width2,
unsigned int flags)
{
bool addr_inc = flags & LLI_ADDR_INC;
struct d40_log_lli *lli = lli_sg;
int size_rest = size;
int size_seg = 0;
do {
size_seg = d40_seg_size(size_rest, data_width1, data_width2);
size_rest -= size_seg;
d40_log_fill_lli(lli,
addr,
size_seg,
lcsp13, data_width1,
flags);
if (addr_inc)
addr += size_seg;
lli++;
} while (size_rest);
return lli;
}
int d40_log_sg_to_lli(struct scatterlist *sg,
int sg_len,
dma_addr_t dev_addr,
struct d40_log_lli *lli_sg,
u32 lcsp13, /* src or dst*/
u32 data_width1, u32 data_width2)
{
int total_size = 0;
struct scatterlist *current_sg = sg;
int i;
struct d40_log_lli *lli = lli_sg;
unsigned long flags = 0;
if (!dev_addr)
flags |= LLI_ADDR_INC;
for_each_sg(sg, current_sg, sg_len, i) {
dma_addr_t sg_addr = sg_dma_address(current_sg);
unsigned int len = sg_dma_len(current_sg);
dma_addr_t addr = dev_addr ?: sg_addr;
total_size += sg_dma_len(current_sg);
lli = d40_log_buf_to_lli(lli, addr, len,
lcsp13,
data_width1,
data_width2,
flags);
}
return total_size;
}
| gpl-2.0 |
premaca/android_kernel_cyanogen_msm8916 | drivers/staging/rtl8192u/ieee80211/rtl819x_BAProc.c | 2144 | 25769 | /********************************************************************************************************************************
* This file is created to process BA Action Frame. According to 802.11 spec, there are 3 BA action types at all. And as BA is
* related to TS, this part need some structure defined in QOS side code. Also TX RX is going to be resturctured, so how to send
* ADDBAREQ ADDBARSP and DELBA packet is still on consideration. Temporarily use MANAGE QUEUE instead of Normal Queue.
* WB 2008-05-27
* *****************************************************************************************************************************/
#include "ieee80211.h"
#include "rtl819x_BA.h"
/********************************************************************************************************************
*function: Activate BA entry. And if Time is nozero, start timer.
* input: PBA_RECORD pBA //BA entry to be enabled
* u16 Time //indicate time delay.
* output: none
********************************************************************************************************************/
void ActivateBAEntry(struct ieee80211_device* ieee, PBA_RECORD pBA, u16 Time)
{
pBA->bValid = true;
if(Time != 0)
mod_timer(&pBA->Timer, jiffies + MSECS(Time));
}
/********************************************************************************************************************
*function: deactivate BA entry, including its timer.
* input: PBA_RECORD pBA //BA entry to be disabled
* output: none
********************************************************************************************************************/
void DeActivateBAEntry( struct ieee80211_device* ieee, PBA_RECORD pBA)
{
pBA->bValid = false;
del_timer_sync(&pBA->Timer);
}
/********************************************************************************************************************
*function: deactivete BA entry in Tx Ts, and send DELBA.
* input:
* PTX_TS_RECORD pTxTs //Tx Ts which is to deactivate BA entry.
* output: none
* notice: As PTX_TS_RECORD structure will be defined in QOS, so wait to be merged. //FIXME
********************************************************************************************************************/
u8 TxTsDeleteBA( struct ieee80211_device* ieee, PTX_TS_RECORD pTxTs)
{
PBA_RECORD pAdmittedBa = &pTxTs->TxAdmittedBARecord; //These two BA entries must exist in TS structure
PBA_RECORD pPendingBa = &pTxTs->TxPendingBARecord;
u8 bSendDELBA = false;
// Delete pending BA
if(pPendingBa->bValid)
{
DeActivateBAEntry(ieee, pPendingBa);
bSendDELBA = true;
}
// Delete admitted BA
if(pAdmittedBa->bValid)
{
DeActivateBAEntry(ieee, pAdmittedBa);
bSendDELBA = true;
}
return bSendDELBA;
}
/********************************************************************************************************************
*function: deactivete BA entry in Tx Ts, and send DELBA.
* input:
* PRX_TS_RECORD pRxTs //Rx Ts which is to deactivate BA entry.
* output: none
* notice: As PRX_TS_RECORD structure will be defined in QOS, so wait to be merged. //FIXME, same with above
********************************************************************************************************************/
u8 RxTsDeleteBA( struct ieee80211_device* ieee, PRX_TS_RECORD pRxTs)
{
PBA_RECORD pBa = &pRxTs->RxAdmittedBARecord;
u8 bSendDELBA = false;
if(pBa->bValid)
{
DeActivateBAEntry(ieee, pBa);
bSendDELBA = true;
}
return bSendDELBA;
}
/********************************************************************************************************************
*function: reset BA entry
* input:
* PBA_RECORD pBA //entry to be reset
* output: none
********************************************************************************************************************/
void ResetBaEntry( PBA_RECORD pBA)
{
pBA->bValid = false;
pBA->BaParamSet.shortData = 0;
pBA->BaTimeoutValue = 0;
pBA->DialogToken = 0;
pBA->BaStartSeqCtrl.ShortData = 0;
}
//These functions need porting here or not?
/*******************************************************************************************************************************
*function: construct ADDBAREQ and ADDBARSP frame here together.
* input: u8* Dst //ADDBA frame's destination
* PBA_RECORD pBA //BA_RECORD entry which stores the necessary information for BA.
* u16 StatusCode //status code in RSP and I will use it to indicate whether it's RSP or REQ(will I?)
* u8 type //indicate whether it's RSP(ACT_ADDBARSP) ow REQ(ACT_ADDBAREQ)
* output: none
* return: sk_buff* skb //return constructed skb to xmit
*******************************************************************************************************************************/
static struct sk_buff* ieee80211_ADDBA(struct ieee80211_device* ieee, u8* Dst, PBA_RECORD pBA, u16 StatusCode, u8 type)
{
struct sk_buff *skb = NULL;
struct ieee80211_hdr_3addr* BAReq = NULL;
u8* tag = NULL;
u16 tmp = 0;
u16 len = ieee->tx_headroom + 9;
//category(1) + action field(1) + Dialog Token(1) + BA Parameter Set(2) + BA Timeout Value(2) + BA Start SeqCtrl(2)(or StatusCode(2))
IEEE80211_DEBUG(IEEE80211_DL_TRACE | IEEE80211_DL_BA, "========>%s(), frame(%d) sentd to:%pM, ieee->dev:%p\n", __FUNCTION__, type, Dst, ieee->dev);
if (pBA == NULL||ieee == NULL)
{
IEEE80211_DEBUG(IEEE80211_DL_ERR, "pBA(%p) is NULL or ieee(%p) is NULL\n", pBA, ieee);
return NULL;
}
skb = dev_alloc_skb(len + sizeof( struct ieee80211_hdr_3addr)); //need to add something others? FIXME
if (skb == NULL)
{
IEEE80211_DEBUG(IEEE80211_DL_ERR, "can't alloc skb for ADDBA_REQ\n");
return NULL;
}
memset(skb->data, 0, sizeof( struct ieee80211_hdr_3addr)); //I wonder whether it's necessary. Apparently kernel will not do it when alloc a skb.
skb_reserve(skb, ieee->tx_headroom);
BAReq = ( struct ieee80211_hdr_3addr *) skb_put(skb,sizeof( struct ieee80211_hdr_3addr));
memcpy(BAReq->addr1, Dst, ETH_ALEN);
memcpy(BAReq->addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy(BAReq->addr3, ieee->current_network.bssid, ETH_ALEN);
BAReq->frame_ctl = cpu_to_le16(IEEE80211_STYPE_MANAGE_ACT); //action frame
//tag += sizeof( struct ieee80211_hdr_3addr); //move to action field
tag = (u8*)skb_put(skb, 9);
*tag ++= ACT_CAT_BA;
*tag ++= type;
// Dialog Token
*tag ++= pBA->DialogToken;
if (ACT_ADDBARSP == type)
{
// Status Code
printk("=====>to send ADDBARSP\n");
tmp = cpu_to_le16(StatusCode);
memcpy(tag, (u8*)&tmp, 2);
tag += 2;
}
// BA Parameter Set
tmp = cpu_to_le16(pBA->BaParamSet.shortData);
memcpy(tag, (u8*)&tmp, 2);
tag += 2;
// BA Timeout Value
tmp = cpu_to_le16(pBA->BaTimeoutValue);
memcpy(tag, (u8*)&tmp, 2);
tag += 2;
if (ACT_ADDBAREQ == type)
{
// BA Start SeqCtrl
memcpy(tag,(u8*)&(pBA->BaStartSeqCtrl), 2);
tag += 2;
}
IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA|IEEE80211_DL_BA, skb->data, skb->len);
return skb;
//return NULL;
}
/********************************************************************************************************************
*function: construct DELBA frame
* input: u8* dst //DELBA frame's destination
* PBA_RECORD pBA //BA_RECORD entry which stores the necessary information for BA
* TR_SELECT TxRxSelect //TX RX direction
* u16 ReasonCode //status code.
* output: none
* return: sk_buff* skb //return constructed skb to xmit
********************************************************************************************************************/
static struct sk_buff* ieee80211_DELBA(
struct ieee80211_device* ieee,
u8* dst,
PBA_RECORD pBA,
TR_SELECT TxRxSelect,
u16 ReasonCode
)
{
DELBA_PARAM_SET DelbaParamSet;
struct sk_buff *skb = NULL;
struct ieee80211_hdr_3addr* Delba = NULL;
u8* tag = NULL;
u16 tmp = 0;
//len = head len + DELBA Parameter Set(2) + Reason Code(2)
u16 len = 6 + ieee->tx_headroom;
if (net_ratelimit())
IEEE80211_DEBUG(IEEE80211_DL_TRACE | IEEE80211_DL_BA, "========>%s(), ReasonCode(%d) sentd to:%pM\n", __FUNCTION__, ReasonCode, dst);
memset(&DelbaParamSet, 0, 2);
DelbaParamSet.field.Initiator = (TxRxSelect==TX_DIR)?1:0;
DelbaParamSet.field.TID = pBA->BaParamSet.field.TID;
skb = dev_alloc_skb(len + sizeof( struct ieee80211_hdr_3addr)); //need to add something others? FIXME
if (skb == NULL)
{
IEEE80211_DEBUG(IEEE80211_DL_ERR, "can't alloc skb for ADDBA_REQ\n");
return NULL;
}
// memset(skb->data, 0, len+sizeof( struct ieee80211_hdr_3addr));
skb_reserve(skb, ieee->tx_headroom);
Delba = ( struct ieee80211_hdr_3addr *) skb_put(skb,sizeof( struct ieee80211_hdr_3addr));
memcpy(Delba->addr1, dst, ETH_ALEN);
memcpy(Delba->addr2, ieee->dev->dev_addr, ETH_ALEN);
memcpy(Delba->addr3, ieee->current_network.bssid, ETH_ALEN);
Delba->frame_ctl = cpu_to_le16(IEEE80211_STYPE_MANAGE_ACT); //action frame
tag = (u8*)skb_put(skb, 6);
*tag ++= ACT_CAT_BA;
*tag ++= ACT_DELBA;
// DELBA Parameter Set
tmp = cpu_to_le16(DelbaParamSet.shortData);
memcpy(tag, (u8*)&tmp, 2);
tag += 2;
// Reason Code
tmp = cpu_to_le16(ReasonCode);
memcpy(tag, (u8*)&tmp, 2);
tag += 2;
IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA|IEEE80211_DL_BA, skb->data, skb->len);
if (net_ratelimit())
IEEE80211_DEBUG(IEEE80211_DL_TRACE | IEEE80211_DL_BA, "<=====%s()\n", __FUNCTION__);
return skb;
}
/********************************************************************************************************************
*function: send ADDBAReq frame out
* input: u8* dst //ADDBAReq frame's destination
* PBA_RECORD pBA //BA_RECORD entry which stores the necessary information for BA
* output: none
* notice: If any possible, please hide pBA in ieee. And temporarily use Manage Queue as softmac_mgmt_xmit() usually does
********************************************************************************************************************/
void ieee80211_send_ADDBAReq(struct ieee80211_device* ieee, u8* dst, PBA_RECORD pBA)
{
struct sk_buff *skb = NULL;
skb = ieee80211_ADDBA(ieee, dst, pBA, 0, ACT_ADDBAREQ); //construct ACT_ADDBAREQ frames so set statuscode zero.
if (skb)
{
softmac_mgmt_xmit(skb, ieee);
//add statistic needed here.
//and skb will be freed in softmac_mgmt_xmit(), so omit all dev_kfree_skb_any() outside softmac_mgmt_xmit()
//WB
}
else
{
IEEE80211_DEBUG(IEEE80211_DL_ERR, "alloc skb error in function %s()\n", __FUNCTION__);
}
return;
}
/********************************************************************************************************************
*function: send ADDBARSP frame out
* input: u8* dst //DELBA frame's destination
* PBA_RECORD pBA //BA_RECORD entry which stores the necessary information for BA
* u16 StatusCode //RSP StatusCode
* output: none
* notice: If any possible, please hide pBA in ieee. And temporarily use Manage Queue as softmac_mgmt_xmit() usually does
********************************************************************************************************************/
void ieee80211_send_ADDBARsp(struct ieee80211_device* ieee, u8* dst, PBA_RECORD pBA, u16 StatusCode)
{
struct sk_buff *skb = NULL;
skb = ieee80211_ADDBA(ieee, dst, pBA, StatusCode, ACT_ADDBARSP); //construct ACT_ADDBARSP frames
if (skb)
{
softmac_mgmt_xmit(skb, ieee);
//same above
}
else
{
IEEE80211_DEBUG(IEEE80211_DL_ERR, "alloc skb error in function %s()\n", __FUNCTION__);
}
return;
}
/********************************************************************************************************************
*function: send ADDBARSP frame out
* input: u8* dst //DELBA frame's destination
* PBA_RECORD pBA //BA_RECORD entry which stores the necessary information for BA
* TR_SELECT TxRxSelect //TX or RX
* u16 ReasonCode //DEL ReasonCode
* output: none
* notice: If any possible, please hide pBA in ieee. And temporarily use Manage Queue as softmac_mgmt_xmit() usually does
********************************************************************************************************************/
void ieee80211_send_DELBA(struct ieee80211_device* ieee, u8* dst, PBA_RECORD pBA, TR_SELECT TxRxSelect, u16 ReasonCode)
{
struct sk_buff *skb = NULL;
skb = ieee80211_DELBA(ieee, dst, pBA, TxRxSelect, ReasonCode); //construct ACT_ADDBARSP frames
if (skb)
{
softmac_mgmt_xmit(skb, ieee);
//same above
}
else
{
IEEE80211_DEBUG(IEEE80211_DL_ERR, "alloc skb error in function %s()\n", __FUNCTION__);
}
return ;
}
/********************************************************************************************************************
*function: RX ADDBAReq
* input: struct sk_buff * skb //incoming ADDBAReq skb.
* return: 0(pass), other(fail)
* notice: As this function need support of QOS, I comment some code out. And when qos is ready, this code need to be support.
********************************************************************************************************************/
int ieee80211_rx_ADDBAReq( struct ieee80211_device* ieee, struct sk_buff *skb)
{
struct ieee80211_hdr_3addr* req = NULL;
u16 rc = 0;
u8 * dst = NULL, *pDialogToken = NULL, *tag = NULL;
PBA_RECORD pBA = NULL;
PBA_PARAM_SET pBaParamSet = NULL;
u16* pBaTimeoutVal = NULL;
PSEQUENCE_CONTROL pBaStartSeqCtrl = NULL;
PRX_TS_RECORD pTS = NULL;
if (skb->len < sizeof( struct ieee80211_hdr_3addr) + 9)
{
IEEE80211_DEBUG(IEEE80211_DL_ERR, " Invalid skb len in BAREQ(%d / %zu)\n", skb->len, (sizeof( struct ieee80211_hdr_3addr) + 9));
return -1;
}
IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA|IEEE80211_DL_BA, skb->data, skb->len);
req = ( struct ieee80211_hdr_3addr*) skb->data;
tag = (u8*)req;
dst = (u8*)(&req->addr2[0]);
tag += sizeof( struct ieee80211_hdr_3addr);
pDialogToken = tag + 2; //category+action
pBaParamSet = (PBA_PARAM_SET)(tag + 3); //+DialogToken
pBaTimeoutVal = (u16*)(tag + 5);
pBaStartSeqCtrl = (PSEQUENCE_CONTROL)(req + 7);
printk("====================>rx ADDBAREQ from :%pM\n", dst);
//some other capability is not ready now.
if( (ieee->current_network.qos_data.active == 0) ||
(ieee->pHTInfo->bCurrentHTSupport == false)) //||
// (ieee->pStaQos->bEnableRxImmBA == false) )
{
rc = ADDBA_STATUS_REFUSED;
IEEE80211_DEBUG(IEEE80211_DL_ERR, "Failed to reply on ADDBA_REQ as some capability is not ready(%d, %d)\n", ieee->current_network.qos_data.active, ieee->pHTInfo->bCurrentHTSupport);
goto OnADDBAReq_Fail;
}
// Search for related traffic stream.
// If there is no matched TS, reject the ADDBA request.
if( !GetTs(
ieee,
(PTS_COMMON_INFO*)(&pTS),
dst,
(u8)(pBaParamSet->field.TID),
RX_DIR,
true) )
{
rc = ADDBA_STATUS_REFUSED;
IEEE80211_DEBUG(IEEE80211_DL_ERR, "can't get TS in %s()\n", __FUNCTION__);
goto OnADDBAReq_Fail;
}
pBA = &pTS->RxAdmittedBARecord;
// To Determine the ADDBA Req content
// We can do much more check here, including BufferSize, AMSDU_Support, Policy, StartSeqCtrl...
// I want to check StartSeqCtrl to make sure when we start aggregation!!!
//
if(pBaParamSet->field.BAPolicy == BA_POLICY_DELAYED)
{
rc = ADDBA_STATUS_INVALID_PARAM;
IEEE80211_DEBUG(IEEE80211_DL_ERR, "BA Policy is not correct in %s()\n", __FUNCTION__);
goto OnADDBAReq_Fail;
}
// Admit the ADDBA Request
//
DeActivateBAEntry(ieee, pBA);
pBA->DialogToken = *pDialogToken;
pBA->BaParamSet = *pBaParamSet;
pBA->BaTimeoutValue = *pBaTimeoutVal;
pBA->BaStartSeqCtrl = *pBaStartSeqCtrl;
//for half N mode we only aggregate 1 frame
if (ieee->GetHalfNmodeSupportByAPsHandler(ieee->dev))
pBA->BaParamSet.field.BufferSize = 1;
else
pBA->BaParamSet.field.BufferSize = 32;
ActivateBAEntry(ieee, pBA, pBA->BaTimeoutValue);
ieee80211_send_ADDBARsp(ieee, dst, pBA, ADDBA_STATUS_SUCCESS);
// End of procedure.
return 0;
OnADDBAReq_Fail:
{
BA_RECORD BA;
BA.BaParamSet = *pBaParamSet;
BA.BaTimeoutValue = *pBaTimeoutVal;
BA.DialogToken = *pDialogToken;
BA.BaParamSet.field.BAPolicy = BA_POLICY_IMMEDIATE;
ieee80211_send_ADDBARsp(ieee, dst, &BA, rc);
return 0; //we send RSP out.
}
}
/********************************************************************************************************************
*function: RX ADDBARSP
* input: struct sk_buff * skb //incoming ADDBAReq skb.
* return: 0(pass), other(fail)
* notice: As this function need support of QOS, I comment some code out. And when qos is ready, this code need to be support.
********************************************************************************************************************/
int ieee80211_rx_ADDBARsp( struct ieee80211_device* ieee, struct sk_buff *skb)
{
struct ieee80211_hdr_3addr* rsp = NULL;
PBA_RECORD pPendingBA, pAdmittedBA;
PTX_TS_RECORD pTS = NULL;
u8* dst = NULL, *pDialogToken = NULL, *tag = NULL;
u16* pStatusCode = NULL, *pBaTimeoutVal = NULL;
PBA_PARAM_SET pBaParamSet = NULL;
u16 ReasonCode;
if (skb->len < sizeof( struct ieee80211_hdr_3addr) + 9)
{
IEEE80211_DEBUG(IEEE80211_DL_ERR, " Invalid skb len in BARSP(%d / %zu)\n", skb->len, (sizeof( struct ieee80211_hdr_3addr) + 9));
return -1;
}
rsp = ( struct ieee80211_hdr_3addr*)skb->data;
tag = (u8*)rsp;
dst = (u8*)(&rsp->addr2[0]);
tag += sizeof( struct ieee80211_hdr_3addr);
pDialogToken = tag + 2;
pStatusCode = (u16*)(tag + 3);
pBaParamSet = (PBA_PARAM_SET)(tag + 5);
pBaTimeoutVal = (u16*)(tag + 7);
// Check the capability
// Since we can always receive A-MPDU, we just check if it is under HT mode.
if( ieee->current_network.qos_data.active == 0 ||
ieee->pHTInfo->bCurrentHTSupport == false ||
ieee->pHTInfo->bCurrentAMPDUEnable == false )
{
IEEE80211_DEBUG(IEEE80211_DL_ERR, "reject to ADDBA_RSP as some capability is not ready(%d, %d, %d)\n",ieee->current_network.qos_data.active, ieee->pHTInfo->bCurrentHTSupport, ieee->pHTInfo->bCurrentAMPDUEnable);
ReasonCode = DELBA_REASON_UNKNOWN_BA;
goto OnADDBARsp_Reject;
}
//
// Search for related TS.
// If there is no TS found, we wil reject ADDBA Rsp by sending DELBA frame.
//
if (!GetTs(
ieee,
(PTS_COMMON_INFO*)(&pTS),
dst,
(u8)(pBaParamSet->field.TID),
TX_DIR,
false) )
{
IEEE80211_DEBUG(IEEE80211_DL_ERR, "can't get TS in %s()\n", __FUNCTION__);
ReasonCode = DELBA_REASON_UNKNOWN_BA;
goto OnADDBARsp_Reject;
}
pTS->bAddBaReqInProgress = false;
pPendingBA = &pTS->TxPendingBARecord;
pAdmittedBA = &pTS->TxAdmittedBARecord;
//
// Check if related BA is waiting for setup.
// If not, reject by sending DELBA frame.
//
if((pAdmittedBA->bValid==true))
{
// Since BA is already setup, we ignore all other ADDBA Response.
IEEE80211_DEBUG(IEEE80211_DL_BA, "OnADDBARsp(): Recv ADDBA Rsp. Drop because already admit it! \n");
return -1;
}
else if((pPendingBA->bValid == false) ||(*pDialogToken != pPendingBA->DialogToken))
{
IEEE80211_DEBUG(IEEE80211_DL_ERR, "OnADDBARsp(): Recv ADDBA Rsp. BA invalid, DELBA! \n");
ReasonCode = DELBA_REASON_UNKNOWN_BA;
goto OnADDBARsp_Reject;
}
else
{
IEEE80211_DEBUG(IEEE80211_DL_BA, "OnADDBARsp(): Recv ADDBA Rsp. BA is admitted! Status code:%X\n", *pStatusCode);
DeActivateBAEntry(ieee, pPendingBA);
}
if(*pStatusCode == ADDBA_STATUS_SUCCESS)
{
//
// Determine ADDBA Rsp content here.
// We can compare the value of BA parameter set that Peer returned and Self sent.
// If it is OK, then admitted. Or we can send DELBA to cancel BA mechanism.
//
if(pBaParamSet->field.BAPolicy == BA_POLICY_DELAYED)
{
// Since this is a kind of ADDBA failed, we delay next ADDBA process.
pTS->bAddBaReqDelayed = true;
DeActivateBAEntry(ieee, pAdmittedBA);
ReasonCode = DELBA_REASON_END_BA;
goto OnADDBARsp_Reject;
}
//
// Admitted condition
//
pAdmittedBA->DialogToken = *pDialogToken;
pAdmittedBA->BaTimeoutValue = *pBaTimeoutVal;
pAdmittedBA->BaStartSeqCtrl = pPendingBA->BaStartSeqCtrl;
pAdmittedBA->BaParamSet = *pBaParamSet;
DeActivateBAEntry(ieee, pAdmittedBA);
ActivateBAEntry(ieee, pAdmittedBA, *pBaTimeoutVal);
}
else
{
// Delay next ADDBA process.
pTS->bAddBaReqDelayed = true;
}
// End of procedure
return 0;
OnADDBARsp_Reject:
{
BA_RECORD BA;
BA.BaParamSet = *pBaParamSet;
ieee80211_send_DELBA(ieee, dst, &BA, TX_DIR, ReasonCode);
return 0;
}
}
/********************************************************************************************************************
*function: RX DELBA
* input: struct sk_buff * skb //incoming ADDBAReq skb.
* return: 0(pass), other(fail)
* notice: As this function need support of QOS, I comment some code out. And when qos is ready, this code need to be support.
********************************************************************************************************************/
int ieee80211_rx_DELBA(struct ieee80211_device* ieee,struct sk_buff *skb)
{
struct ieee80211_hdr_3addr* delba = NULL;
PDELBA_PARAM_SET pDelBaParamSet = NULL;
u16* pReasonCode = NULL;
u8* dst = NULL;
if (skb->len < sizeof( struct ieee80211_hdr_3addr) + 6)
{
IEEE80211_DEBUG(IEEE80211_DL_ERR, " Invalid skb len in DELBA(%d / %zu)\n", skb->len, (sizeof( struct ieee80211_hdr_3addr) + 6));
return -1;
}
if(ieee->current_network.qos_data.active == 0 ||
ieee->pHTInfo->bCurrentHTSupport == false )
{
IEEE80211_DEBUG(IEEE80211_DL_ERR, "received DELBA while QOS or HT is not supported(%d, %d)\n",ieee->current_network.qos_data.active, ieee->pHTInfo->bCurrentHTSupport);
return -1;
}
IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA|IEEE80211_DL_BA, skb->data, skb->len);
delba = ( struct ieee80211_hdr_3addr*)skb->data;
dst = (u8*)(&delba->addr2[0]);
delba += sizeof( struct ieee80211_hdr_3addr);
pDelBaParamSet = (PDELBA_PARAM_SET)(delba+2);
pReasonCode = (u16*)(delba+4);
if(pDelBaParamSet->field.Initiator == 1)
{
PRX_TS_RECORD pRxTs;
if( !GetTs(
ieee,
(PTS_COMMON_INFO*)&pRxTs,
dst,
(u8)pDelBaParamSet->field.TID,
RX_DIR,
false) )
{
IEEE80211_DEBUG(IEEE80211_DL_ERR, "can't get TS for RXTS in %s()\n", __FUNCTION__);
return -1;
}
RxTsDeleteBA(ieee, pRxTs);
}
else
{
PTX_TS_RECORD pTxTs;
if(!GetTs(
ieee,
(PTS_COMMON_INFO*)&pTxTs,
dst,
(u8)pDelBaParamSet->field.TID,
TX_DIR,
false) )
{
IEEE80211_DEBUG(IEEE80211_DL_ERR, "can't get TS for TXTS in %s()\n", __FUNCTION__);
return -1;
}
pTxTs->bUsingBa = false;
pTxTs->bAddBaReqInProgress = false;
pTxTs->bAddBaReqDelayed = false;
del_timer_sync(&pTxTs->TsAddBaTimer);
//PlatformCancelTimer(Adapter, &pTxTs->TsAddBaTimer);
TxTsDeleteBA(ieee, pTxTs);
}
return 0;
}
//
// ADDBA initiate. This can only be called by TX side.
//
void
TsInitAddBA(
struct ieee80211_device* ieee,
PTX_TS_RECORD pTS,
u8 Policy,
u8 bOverwritePending
)
{
PBA_RECORD pBA = &pTS->TxPendingBARecord;
if(pBA->bValid==true && bOverwritePending==false)
return;
// Set parameters to "Pending" variable set
DeActivateBAEntry(ieee, pBA);
pBA->DialogToken++; // DialogToken: Only keep the latest dialog token
pBA->BaParamSet.field.AMSDU_Support = 0; // Do not support A-MSDU with A-MPDU now!!
pBA->BaParamSet.field.BAPolicy = Policy; // Policy: Delayed or Immediate
pBA->BaParamSet.field.TID = pTS->TsCommonInfo.TSpec.f.TSInfo.field.ucTSID; // TID
// BufferSize: This need to be set according to A-MPDU vector
pBA->BaParamSet.field.BufferSize = 32; // BufferSize: This need to be set according to A-MPDU vector
pBA->BaTimeoutValue = 0; // Timeout value: Set 0 to disable Timer
pBA->BaStartSeqCtrl.field.SeqNum = (pTS->TxCurSeq + 3) % 4096; // Block Ack will start after 3 packets later.
ActivateBAEntry(ieee, pBA, BA_SETUP_TIMEOUT);
ieee80211_send_ADDBAReq(ieee, pTS->TsCommonInfo.Addr, pBA);
}
void
TsInitDelBA( struct ieee80211_device* ieee, PTS_COMMON_INFO pTsCommonInfo, TR_SELECT TxRxSelect)
{
if(TxRxSelect == TX_DIR)
{
PTX_TS_RECORD pTxTs = (PTX_TS_RECORD)pTsCommonInfo;
if(TxTsDeleteBA(ieee, pTxTs))
ieee80211_send_DELBA(
ieee,
pTsCommonInfo->Addr,
(pTxTs->TxAdmittedBARecord.bValid)?(&pTxTs->TxAdmittedBARecord):(&pTxTs->TxPendingBARecord),
TxRxSelect,
DELBA_REASON_END_BA);
}
else if(TxRxSelect == RX_DIR)
{
PRX_TS_RECORD pRxTs = (PRX_TS_RECORD)pTsCommonInfo;
if(RxTsDeleteBA(ieee, pRxTs))
ieee80211_send_DELBA(
ieee,
pTsCommonInfo->Addr,
&pRxTs->RxAdmittedBARecord,
TxRxSelect,
DELBA_REASON_END_BA );
}
}
/********************************************************************************************************************
*function: BA setup timer
* input: unsigned long data //acturally we send TX_TS_RECORD or RX_TS_RECORD to these timer
* return: NULL
* notice:
********************************************************************************************************************/
void BaSetupTimeOut(unsigned long data)
{
PTX_TS_RECORD pTxTs = (PTX_TS_RECORD)data;
pTxTs->bAddBaReqInProgress = false;
pTxTs->bAddBaReqDelayed = true;
pTxTs->TxPendingBARecord.bValid = false;
}
void TxBaInactTimeout(unsigned long data)
{
PTX_TS_RECORD pTxTs = (PTX_TS_RECORD)data;
struct ieee80211_device *ieee = container_of(pTxTs, struct ieee80211_device, TxTsRecord[pTxTs->num]);
TxTsDeleteBA(ieee, pTxTs);
ieee80211_send_DELBA(
ieee,
pTxTs->TsCommonInfo.Addr,
&pTxTs->TxAdmittedBARecord,
TX_DIR,
DELBA_REASON_TIMEOUT);
}
void RxBaInactTimeout(unsigned long data)
{
PRX_TS_RECORD pRxTs = (PRX_TS_RECORD)data;
struct ieee80211_device *ieee = container_of(pRxTs, struct ieee80211_device, RxTsRecord[pRxTs->num]);
RxTsDeleteBA(ieee, pRxTs);
ieee80211_send_DELBA(
ieee,
pRxTs->TsCommonInfo.Addr,
&pRxTs->RxAdmittedBARecord,
RX_DIR,
DELBA_REASON_TIMEOUT);
return ;
}
| gpl-2.0 |
WildfireDEV/s6 | drivers/net/wireless/brcm80211/brcmfmac/p2p.c | 2144 | 71571 | /*
* Copyright (c) 2012 Broadcom Corporation
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <linux/slab.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <net/cfg80211.h>
#include <brcmu_wifi.h>
#include <brcmu_utils.h>
#include <defs.h>
#include <dhd.h>
#include <dhd_dbg.h>
#include "fwil.h"
#include "fwil_types.h"
#include "p2p.h"
#include "wl_cfg80211.h"
/* parameters used for p2p escan */
#define P2PAPI_SCAN_NPROBES 1
#define P2PAPI_SCAN_DWELL_TIME_MS 80
#define P2PAPI_SCAN_SOCIAL_DWELL_TIME_MS 40
#define P2PAPI_SCAN_HOME_TIME_MS 60
#define P2PAPI_SCAN_NPROBS_TIME_MS 30
#define P2PAPI_SCAN_AF_SEARCH_DWELL_TIME_MS 100
#define WL_SCAN_CONNECT_DWELL_TIME_MS 200
#define WL_SCAN_JOIN_PROBE_INTERVAL_MS 20
#define BRCMF_P2P_WILDCARD_SSID "DIRECT-"
#define BRCMF_P2P_WILDCARD_SSID_LEN (sizeof(BRCMF_P2P_WILDCARD_SSID) - 1)
#define SOCIAL_CHAN_1 1
#define SOCIAL_CHAN_2 6
#define SOCIAL_CHAN_3 11
#define IS_P2P_SOCIAL_CHANNEL(channel) ((channel == SOCIAL_CHAN_1) || \
(channel == SOCIAL_CHAN_2) || \
(channel == SOCIAL_CHAN_3))
#define BRCMF_P2P_TEMP_CHAN SOCIAL_CHAN_3
#define SOCIAL_CHAN_CNT 3
#define AF_PEER_SEARCH_CNT 2
#define BRCMF_SCB_TIMEOUT_VALUE 20
#define P2P_VER 9 /* P2P version: 9=WiFi P2P v1.0 */
#define P2P_PUB_AF_CATEGORY 0x04
#define P2P_PUB_AF_ACTION 0x09
#define P2P_AF_CATEGORY 0x7f
#define P2P_OUI "\x50\x6F\x9A" /* P2P OUI */
#define P2P_OUI_LEN 3 /* P2P OUI length */
/* Action Frame Constants */
#define DOT11_ACTION_HDR_LEN 2 /* action frame category + action */
#define DOT11_ACTION_CAT_OFF 0 /* category offset */
#define DOT11_ACTION_ACT_OFF 1 /* action offset */
#define P2P_AF_DWELL_TIME 200
#define P2P_AF_MIN_DWELL_TIME 100
#define P2P_AF_MED_DWELL_TIME 400
#define P2P_AF_LONG_DWELL_TIME 1000
#define P2P_AF_TX_MAX_RETRY 1
#define P2P_AF_MAX_WAIT_TIME 2000
#define P2P_INVALID_CHANNEL -1
#define P2P_CHANNEL_SYNC_RETRY 5
#define P2P_AF_FRM_SCAN_MAX_WAIT 1500
#define P2P_DEFAULT_SLEEP_TIME_VSDB 200
/* WiFi P2P Public Action Frame OUI Subtypes */
#define P2P_PAF_GON_REQ 0 /* Group Owner Negotiation Req */
#define P2P_PAF_GON_RSP 1 /* Group Owner Negotiation Rsp */
#define P2P_PAF_GON_CONF 2 /* Group Owner Negotiation Confirm */
#define P2P_PAF_INVITE_REQ 3 /* P2P Invitation Request */
#define P2P_PAF_INVITE_RSP 4 /* P2P Invitation Response */
#define P2P_PAF_DEVDIS_REQ 5 /* Device Discoverability Request */
#define P2P_PAF_DEVDIS_RSP 6 /* Device Discoverability Response */
#define P2P_PAF_PROVDIS_REQ 7 /* Provision Discovery Request */
#define P2P_PAF_PROVDIS_RSP 8 /* Provision Discovery Response */
#define P2P_PAF_SUBTYPE_INVALID 255 /* Invalid Subtype */
/* WiFi P2P Action Frame OUI Subtypes */
#define P2P_AF_NOTICE_OF_ABSENCE 0 /* Notice of Absence */
#define P2P_AF_PRESENCE_REQ 1 /* P2P Presence Request */
#define P2P_AF_PRESENCE_RSP 2 /* P2P Presence Response */
#define P2P_AF_GO_DISC_REQ 3 /* GO Discoverability Request */
/* P2P Service Discovery related */
#define P2PSD_ACTION_CATEGORY 0x04 /* Public action frame */
#define P2PSD_ACTION_ID_GAS_IREQ 0x0a /* GAS Initial Request AF */
#define P2PSD_ACTION_ID_GAS_IRESP 0x0b /* GAS Initial Response AF */
#define P2PSD_ACTION_ID_GAS_CREQ 0x0c /* GAS Comback Request AF */
#define P2PSD_ACTION_ID_GAS_CRESP 0x0d /* GAS Comback Response AF */
/**
* struct brcmf_p2p_disc_st_le - set discovery state in firmware.
*
* @state: requested discovery state (see enum brcmf_p2p_disc_state).
* @chspec: channel parameter for %WL_P2P_DISC_ST_LISTEN state.
* @dwell: dwell time in ms for %WL_P2P_DISC_ST_LISTEN state.
*/
struct brcmf_p2p_disc_st_le {
u8 state;
__le16 chspec;
__le16 dwell;
};
/**
* enum brcmf_p2p_disc_state - P2P discovery state values
*
* @WL_P2P_DISC_ST_SCAN: P2P discovery with wildcard SSID and P2P IE.
* @WL_P2P_DISC_ST_LISTEN: P2P discovery off-channel for specified time.
* @WL_P2P_DISC_ST_SEARCH: P2P discovery with P2P wildcard SSID and P2P IE.
*/
enum brcmf_p2p_disc_state {
WL_P2P_DISC_ST_SCAN,
WL_P2P_DISC_ST_LISTEN,
WL_P2P_DISC_ST_SEARCH
};
/**
* struct brcmf_p2p_scan_le - P2P specific scan request.
*
* @type: type of scan method requested (values: 'E' or 'S').
* @reserved: reserved (ignored).
* @eparams: parameters used for type 'E'.
* @sparams: parameters used for type 'S'.
*/
struct brcmf_p2p_scan_le {
u8 type;
u8 reserved[3];
union {
struct brcmf_escan_params_le eparams;
struct brcmf_scan_params_le sparams;
};
};
/**
* struct brcmf_p2p_pub_act_frame - WiFi P2P Public Action Frame
*
* @category: P2P_PUB_AF_CATEGORY
* @action: P2P_PUB_AF_ACTION
* @oui[3]: P2P_OUI
* @oui_type: OUI type - P2P_VER
* @subtype: OUI subtype - P2P_TYPE_*
* @dialog_token: nonzero, identifies req/rsp transaction
* @elts[1]: Variable length information elements.
*/
struct brcmf_p2p_pub_act_frame {
u8 category;
u8 action;
u8 oui[3];
u8 oui_type;
u8 subtype;
u8 dialog_token;
u8 elts[1];
};
/**
* struct brcmf_p2p_action_frame - WiFi P2P Action Frame
*
* @category: P2P_AF_CATEGORY
* @OUI[3]: OUI - P2P_OUI
* @type: OUI Type - P2P_VER
* @subtype: OUI Subtype - P2P_AF_*
* @dialog_token: nonzero, identifies req/resp tranaction
* @elts[1]: Variable length information elements.
*/
struct brcmf_p2p_action_frame {
u8 category;
u8 oui[3];
u8 type;
u8 subtype;
u8 dialog_token;
u8 elts[1];
};
/**
* struct brcmf_p2psd_gas_pub_act_frame - Wi-Fi GAS Public Action Frame
*
* @category: 0x04 Public Action Frame
* @action: 0x6c Advertisement Protocol
* @dialog_token: nonzero, identifies req/rsp transaction
* @query_data[1]: Query Data. SD gas ireq SD gas iresp
*/
struct brcmf_p2psd_gas_pub_act_frame {
u8 category;
u8 action;
u8 dialog_token;
u8 query_data[1];
};
/**
* struct brcmf_config_af_params - Action Frame Parameters for tx.
*
* @mpc_onoff: To make sure to send successfully action frame, we have to
* turn off mpc 0: off, 1: on, (-1): do nothing
* @search_channel: 1: search peer's channel to send af
* extra_listen: keep the dwell time to get af response frame.
*/
struct brcmf_config_af_params {
s32 mpc_onoff;
bool search_channel;
bool extra_listen;
};
/**
* brcmf_p2p_is_pub_action() - true if p2p public type frame.
*
* @frame: action frame data.
* @frame_len: length of action frame data.
*
* Determine if action frame is p2p public action type
*/
static bool brcmf_p2p_is_pub_action(void *frame, u32 frame_len)
{
struct brcmf_p2p_pub_act_frame *pact_frm;
if (frame == NULL)
return false;
pact_frm = (struct brcmf_p2p_pub_act_frame *)frame;
if (frame_len < sizeof(struct brcmf_p2p_pub_act_frame) - 1)
return false;
if (pact_frm->category == P2P_PUB_AF_CATEGORY &&
pact_frm->action == P2P_PUB_AF_ACTION &&
pact_frm->oui_type == P2P_VER &&
memcmp(pact_frm->oui, P2P_OUI, P2P_OUI_LEN) == 0)
return true;
return false;
}
/**
* brcmf_p2p_is_p2p_action() - true if p2p action type frame.
*
* @frame: action frame data.
* @frame_len: length of action frame data.
*
* Determine if action frame is p2p action type
*/
static bool brcmf_p2p_is_p2p_action(void *frame, u32 frame_len)
{
struct brcmf_p2p_action_frame *act_frm;
if (frame == NULL)
return false;
act_frm = (struct brcmf_p2p_action_frame *)frame;
if (frame_len < sizeof(struct brcmf_p2p_action_frame) - 1)
return false;
if (act_frm->category == P2P_AF_CATEGORY &&
act_frm->type == P2P_VER &&
memcmp(act_frm->oui, P2P_OUI, P2P_OUI_LEN) == 0)
return true;
return false;
}
/**
* brcmf_p2p_is_gas_action() - true if p2p gas action type frame.
*
* @frame: action frame data.
* @frame_len: length of action frame data.
*
* Determine if action frame is p2p gas action type
*/
static bool brcmf_p2p_is_gas_action(void *frame, u32 frame_len)
{
struct brcmf_p2psd_gas_pub_act_frame *sd_act_frm;
if (frame == NULL)
return false;
sd_act_frm = (struct brcmf_p2psd_gas_pub_act_frame *)frame;
if (frame_len < sizeof(struct brcmf_p2psd_gas_pub_act_frame) - 1)
return false;
if (sd_act_frm->category != P2PSD_ACTION_CATEGORY)
return false;
if (sd_act_frm->action == P2PSD_ACTION_ID_GAS_IREQ ||
sd_act_frm->action == P2PSD_ACTION_ID_GAS_IRESP ||
sd_act_frm->action == P2PSD_ACTION_ID_GAS_CREQ ||
sd_act_frm->action == P2PSD_ACTION_ID_GAS_CRESP)
return true;
return false;
}
/**
* brcmf_p2p_print_actframe() - debug print routine.
*
* @tx: Received or to be transmitted
* @frame: action frame data.
* @frame_len: length of action frame data.
*
* Print information about the p2p action frame
*/
#ifdef DEBUG
static void brcmf_p2p_print_actframe(bool tx, void *frame, u32 frame_len)
{
struct brcmf_p2p_pub_act_frame *pact_frm;
struct brcmf_p2p_action_frame *act_frm;
struct brcmf_p2psd_gas_pub_act_frame *sd_act_frm;
if (!frame || frame_len <= 2)
return;
if (brcmf_p2p_is_pub_action(frame, frame_len)) {
pact_frm = (struct brcmf_p2p_pub_act_frame *)frame;
switch (pact_frm->subtype) {
case P2P_PAF_GON_REQ:
brcmf_dbg(TRACE, "%s P2P Group Owner Negotiation Req Frame\n",
(tx) ? "TX" : "RX");
break;
case P2P_PAF_GON_RSP:
brcmf_dbg(TRACE, "%s P2P Group Owner Negotiation Rsp Frame\n",
(tx) ? "TX" : "RX");
break;
case P2P_PAF_GON_CONF:
brcmf_dbg(TRACE, "%s P2P Group Owner Negotiation Confirm Frame\n",
(tx) ? "TX" : "RX");
break;
case P2P_PAF_INVITE_REQ:
brcmf_dbg(TRACE, "%s P2P Invitation Request Frame\n",
(tx) ? "TX" : "RX");
break;
case P2P_PAF_INVITE_RSP:
brcmf_dbg(TRACE, "%s P2P Invitation Response Frame\n",
(tx) ? "TX" : "RX");
break;
case P2P_PAF_DEVDIS_REQ:
brcmf_dbg(TRACE, "%s P2P Device Discoverability Request Frame\n",
(tx) ? "TX" : "RX");
break;
case P2P_PAF_DEVDIS_RSP:
brcmf_dbg(TRACE, "%s P2P Device Discoverability Response Frame\n",
(tx) ? "TX" : "RX");
break;
case P2P_PAF_PROVDIS_REQ:
brcmf_dbg(TRACE, "%s P2P Provision Discovery Request Frame\n",
(tx) ? "TX" : "RX");
break;
case P2P_PAF_PROVDIS_RSP:
brcmf_dbg(TRACE, "%s P2P Provision Discovery Response Frame\n",
(tx) ? "TX" : "RX");
break;
default:
brcmf_dbg(TRACE, "%s Unknown P2P Public Action Frame\n",
(tx) ? "TX" : "RX");
break;
}
} else if (brcmf_p2p_is_p2p_action(frame, frame_len)) {
act_frm = (struct brcmf_p2p_action_frame *)frame;
switch (act_frm->subtype) {
case P2P_AF_NOTICE_OF_ABSENCE:
brcmf_dbg(TRACE, "%s P2P Notice of Absence Frame\n",
(tx) ? "TX" : "RX");
break;
case P2P_AF_PRESENCE_REQ:
brcmf_dbg(TRACE, "%s P2P Presence Request Frame\n",
(tx) ? "TX" : "RX");
break;
case P2P_AF_PRESENCE_RSP:
brcmf_dbg(TRACE, "%s P2P Presence Response Frame\n",
(tx) ? "TX" : "RX");
break;
case P2P_AF_GO_DISC_REQ:
brcmf_dbg(TRACE, "%s P2P Discoverability Request Frame\n",
(tx) ? "TX" : "RX");
break;
default:
brcmf_dbg(TRACE, "%s Unknown P2P Action Frame\n",
(tx) ? "TX" : "RX");
}
} else if (brcmf_p2p_is_gas_action(frame, frame_len)) {
sd_act_frm = (struct brcmf_p2psd_gas_pub_act_frame *)frame;
switch (sd_act_frm->action) {
case P2PSD_ACTION_ID_GAS_IREQ:
brcmf_dbg(TRACE, "%s P2P GAS Initial Request\n",
(tx) ? "TX" : "RX");
break;
case P2PSD_ACTION_ID_GAS_IRESP:
brcmf_dbg(TRACE, "%s P2P GAS Initial Response\n",
(tx) ? "TX" : "RX");
break;
case P2PSD_ACTION_ID_GAS_CREQ:
brcmf_dbg(TRACE, "%s P2P GAS Comback Request\n",
(tx) ? "TX" : "RX");
break;
case P2PSD_ACTION_ID_GAS_CRESP:
brcmf_dbg(TRACE, "%s P2P GAS Comback Response\n",
(tx) ? "TX" : "RX");
break;
default:
brcmf_dbg(TRACE, "%s Unknown P2P GAS Frame\n",
(tx) ? "TX" : "RX");
break;
}
}
}
#else
static void brcmf_p2p_print_actframe(bool tx, void *frame, u32 frame_len)
{
}
#endif
/**
* brcmf_p2p_set_firmware() - prepare firmware for peer-to-peer operation.
*
* @ifp: ifp to use for iovars (primary).
* @p2p_mac: mac address to configure for p2p_da_override
*/
static int brcmf_p2p_set_firmware(struct brcmf_if *ifp, u8 *p2p_mac)
{
s32 ret = 0;
brcmf_fil_cmd_int_set(ifp, BRCMF_C_DOWN, 1);
brcmf_fil_iovar_int_set(ifp, "apsta", 1);
brcmf_fil_cmd_int_set(ifp, BRCMF_C_UP, 1);
/* In case of COB type, firmware has default mac address
* After Initializing firmware, we have to set current mac address to
* firmware for P2P device address
*/
ret = brcmf_fil_iovar_data_set(ifp, "p2p_da_override", p2p_mac,
ETH_ALEN);
if (ret)
brcmf_err("failed to update device address ret %d\n", ret);
return ret;
}
/**
* brcmf_p2p_generate_bss_mac() - derive mac addresses for P2P.
*
* @p2p: P2P specific data.
* @dev_addr: optional device address.
*
* P2P needs mac addresses for P2P device and interface. If no device
* address it specified, these are derived from the primary net device, ie.
* the permanent ethernet address of the device.
*/
static void brcmf_p2p_generate_bss_mac(struct brcmf_p2p_info *p2p, u8 *dev_addr)
{
struct brcmf_if *pri_ifp = p2p->bss_idx[P2PAPI_BSSCFG_PRIMARY].vif->ifp;
bool local_admin = false;
if (!dev_addr || is_zero_ether_addr(dev_addr)) {
dev_addr = pri_ifp->mac_addr;
local_admin = true;
}
/* Generate the P2P Device Address. This consists of the device's
* primary MAC address with the locally administered bit set.
*/
memcpy(p2p->dev_addr, dev_addr, ETH_ALEN);
if (local_admin)
p2p->dev_addr[0] |= 0x02;
/* Generate the P2P Interface Address. If the discovery and connection
* BSSCFGs need to simultaneously co-exist, then this address must be
* different from the P2P Device Address, but also locally administered.
*/
memcpy(p2p->int_addr, p2p->dev_addr, ETH_ALEN);
p2p->int_addr[0] |= 0x02;
p2p->int_addr[4] ^= 0x80;
}
/**
* brcmf_p2p_scan_is_p2p_request() - is cfg80211 scan request a P2P scan.
*
* @request: the scan request as received from cfg80211.
*
* returns true if one of the ssids in the request matches the
* P2P wildcard ssid; otherwise returns false.
*/
static bool brcmf_p2p_scan_is_p2p_request(struct cfg80211_scan_request *request)
{
struct cfg80211_ssid *ssids = request->ssids;
int i;
for (i = 0; i < request->n_ssids; i++) {
if (ssids[i].ssid_len != BRCMF_P2P_WILDCARD_SSID_LEN)
continue;
brcmf_dbg(INFO, "comparing ssid \"%s\"", ssids[i].ssid);
if (!memcmp(BRCMF_P2P_WILDCARD_SSID, ssids[i].ssid,
BRCMF_P2P_WILDCARD_SSID_LEN))
return true;
}
return false;
}
/**
* brcmf_p2p_set_discover_state - set discover state in firmware.
*
* @ifp: low-level interface object.
* @state: discover state to set.
* @chanspec: channel parameters (for state @WL_P2P_DISC_ST_LISTEN only).
* @listen_ms: duration to listen (for state @WL_P2P_DISC_ST_LISTEN only).
*/
static s32 brcmf_p2p_set_discover_state(struct brcmf_if *ifp, u8 state,
u16 chanspec, u16 listen_ms)
{
struct brcmf_p2p_disc_st_le discover_state;
s32 ret = 0;
brcmf_dbg(TRACE, "enter\n");
discover_state.state = state;
discover_state.chspec = cpu_to_le16(chanspec);
discover_state.dwell = cpu_to_le16(listen_ms);
ret = brcmf_fil_bsscfg_data_set(ifp, "p2p_state", &discover_state,
sizeof(discover_state));
return ret;
}
/**
* brcmf_p2p_deinit_discovery() - disable P2P device discovery.
*
* @p2p: P2P specific data.
*
* Resets the discovery state and disables it in firmware.
*/
static s32 brcmf_p2p_deinit_discovery(struct brcmf_p2p_info *p2p)
{
struct brcmf_cfg80211_vif *vif;
brcmf_dbg(TRACE, "enter\n");
/* Set the discovery state to SCAN */
vif = p2p->bss_idx[P2PAPI_BSSCFG_DEVICE].vif;
(void)brcmf_p2p_set_discover_state(vif->ifp, WL_P2P_DISC_ST_SCAN, 0, 0);
/* Disable P2P discovery in the firmware */
vif = p2p->bss_idx[P2PAPI_BSSCFG_PRIMARY].vif;
(void)brcmf_fil_iovar_int_set(vif->ifp, "p2p_disc", 0);
return 0;
}
/**
* brcmf_p2p_enable_discovery() - initialize and configure discovery.
*
* @p2p: P2P specific data.
*
* Initializes the discovery device and configure the virtual interface.
*/
static int brcmf_p2p_enable_discovery(struct brcmf_p2p_info *p2p)
{
struct brcmf_cfg80211_vif *vif;
s32 ret = 0;
brcmf_dbg(TRACE, "enter\n");
vif = p2p->bss_idx[P2PAPI_BSSCFG_DEVICE].vif;
if (!vif) {
brcmf_err("P2P config device not available\n");
ret = -EPERM;
goto exit;
}
if (test_bit(BRCMF_P2P_STATUS_ENABLED, &p2p->status)) {
brcmf_dbg(INFO, "P2P config device already configured\n");
goto exit;
}
/* Re-initialize P2P Discovery in the firmware */
vif = p2p->bss_idx[P2PAPI_BSSCFG_PRIMARY].vif;
ret = brcmf_fil_iovar_int_set(vif->ifp, "p2p_disc", 1);
if (ret < 0) {
brcmf_err("set p2p_disc error\n");
goto exit;
}
vif = p2p->bss_idx[P2PAPI_BSSCFG_DEVICE].vif;
ret = brcmf_p2p_set_discover_state(vif->ifp, WL_P2P_DISC_ST_SCAN, 0, 0);
if (ret < 0) {
brcmf_err("unable to set WL_P2P_DISC_ST_SCAN\n");
goto exit;
}
/*
* Set wsec to any non-zero value in the discovery bsscfg
* to ensure our P2P probe responses have the privacy bit
* set in the 802.11 WPA IE. Some peer devices may not
* initiate WPS with us if this bit is not set.
*/
ret = brcmf_fil_bsscfg_int_set(vif->ifp, "wsec", AES_ENABLED);
if (ret < 0) {
brcmf_err("wsec error %d\n", ret);
goto exit;
}
set_bit(BRCMF_P2P_STATUS_ENABLED, &p2p->status);
exit:
return ret;
}
/**
* brcmf_p2p_escan() - initiate a P2P scan.
*
* @p2p: P2P specific data.
* @num_chans: number of channels to scan.
* @chanspecs: channel parameters for @num_chans channels.
* @search_state: P2P discover state to use.
* @action: scan action to pass to firmware.
* @bss_type: type of P2P bss.
*/
static s32 brcmf_p2p_escan(struct brcmf_p2p_info *p2p, u32 num_chans,
u16 chanspecs[], s32 search_state, u16 action,
enum p2p_bss_type bss_type)
{
s32 ret = 0;
s32 memsize = offsetof(struct brcmf_p2p_scan_le,
eparams.params_le.channel_list);
s32 nprobes;
s32 active;
u32 i;
u8 *memblk;
struct brcmf_cfg80211_vif *vif;
struct brcmf_p2p_scan_le *p2p_params;
struct brcmf_scan_params_le *sparams;
struct brcmf_ssid ssid;
memsize += num_chans * sizeof(__le16);
memblk = kzalloc(memsize, GFP_KERNEL);
if (!memblk)
return -ENOMEM;
vif = p2p->bss_idx[bss_type].vif;
if (vif == NULL) {
brcmf_err("no vif for bss type %d\n", bss_type);
ret = -EINVAL;
goto exit;
}
switch (search_state) {
case WL_P2P_DISC_ST_SEARCH:
/*
* If we in SEARCH STATE, we don't need to set SSID explictly
* because dongle use P2P WILDCARD internally by default
*/
/* use null ssid */
ssid.SSID_len = 0;
memset(ssid.SSID, 0, sizeof(ssid.SSID));
break;
case WL_P2P_DISC_ST_SCAN:
/*
* wpa_supplicant has p2p_find command with type social or
* progressive. For progressive, we need to set the ssid to
* P2P WILDCARD because we just do broadcast scan unless
* setting SSID.
*/
ssid.SSID_len = BRCMF_P2P_WILDCARD_SSID_LEN;
memcpy(ssid.SSID, BRCMF_P2P_WILDCARD_SSID, ssid.SSID_len);
break;
default:
brcmf_err(" invalid search state %d\n", search_state);
ret = -EINVAL;
goto exit;
}
brcmf_p2p_set_discover_state(vif->ifp, search_state, 0, 0);
/*
* set p2p scan parameters.
*/
p2p_params = (struct brcmf_p2p_scan_le *)memblk;
p2p_params->type = 'E';
/* determine the scan engine parameters */
sparams = &p2p_params->eparams.params_le;
sparams->bss_type = DOT11_BSSTYPE_ANY;
if (p2p->cfg->active_scan)
sparams->scan_type = 0;
else
sparams->scan_type = 1;
memset(&sparams->bssid, 0xFF, ETH_ALEN);
if (ssid.SSID_len)
memcpy(sparams->ssid_le.SSID, ssid.SSID, ssid.SSID_len);
sparams->ssid_le.SSID_len = cpu_to_le32(ssid.SSID_len);
sparams->home_time = cpu_to_le32(P2PAPI_SCAN_HOME_TIME_MS);
/*
* SOCIAL_CHAN_CNT + 1 takes care of the Progressive scan
* supported by the supplicant.
*/
if (num_chans == SOCIAL_CHAN_CNT || num_chans == (SOCIAL_CHAN_CNT + 1))
active = P2PAPI_SCAN_SOCIAL_DWELL_TIME_MS;
else if (num_chans == AF_PEER_SEARCH_CNT)
active = P2PAPI_SCAN_AF_SEARCH_DWELL_TIME_MS;
else if (wl_get_vif_state_all(p2p->cfg, BRCMF_VIF_STATUS_CONNECTED))
active = -1;
else
active = P2PAPI_SCAN_DWELL_TIME_MS;
/* Override scan params to find a peer for a connection */
if (num_chans == 1) {
active = WL_SCAN_CONNECT_DWELL_TIME_MS;
/* WAR to sync with presence period of VSDB GO.
* send probe request more frequently
*/
nprobes = active / WL_SCAN_JOIN_PROBE_INTERVAL_MS;
} else {
nprobes = active / P2PAPI_SCAN_NPROBS_TIME_MS;
}
if (nprobes <= 0)
nprobes = 1;
brcmf_dbg(INFO, "nprobes # %d, active_time %d\n", nprobes, active);
sparams->active_time = cpu_to_le32(active);
sparams->nprobes = cpu_to_le32(nprobes);
sparams->passive_time = cpu_to_le32(-1);
sparams->channel_num = cpu_to_le32(num_chans &
BRCMF_SCAN_PARAMS_COUNT_MASK);
for (i = 0; i < num_chans; i++)
sparams->channel_list[i] = cpu_to_le16(chanspecs[i]);
/* set the escan specific parameters */
p2p_params->eparams.version = cpu_to_le32(BRCMF_ESCAN_REQ_VERSION);
p2p_params->eparams.action = cpu_to_le16(action);
p2p_params->eparams.sync_id = cpu_to_le16(0x1234);
/* perform p2p scan on primary device */
ret = brcmf_fil_bsscfg_data_set(vif->ifp, "p2p_scan", memblk, memsize);
if (!ret)
set_bit(BRCMF_SCAN_STATUS_BUSY, &p2p->cfg->scan_status);
exit:
kfree(memblk);
return ret;
}
/**
* brcmf_p2p_run_escan() - escan callback for peer-to-peer.
*
* @cfg: driver private data for cfg80211 interface.
* @ndev: net device for which scan is requested.
* @request: scan request from cfg80211.
* @action: scan action.
*
* Determines the P2P discovery state based to scan request parameters and
* validates the channels in the request.
*/
static s32 brcmf_p2p_run_escan(struct brcmf_cfg80211_info *cfg,
struct brcmf_if *ifp,
struct cfg80211_scan_request *request,
u16 action)
{
struct brcmf_p2p_info *p2p = &cfg->p2p;
s32 err = 0;
s32 search_state = WL_P2P_DISC_ST_SCAN;
struct brcmf_cfg80211_vif *vif;
struct net_device *dev = NULL;
int i, num_nodfs = 0;
u16 *chanspecs;
brcmf_dbg(TRACE, "enter\n");
if (!request) {
err = -EINVAL;
goto exit;
}
if (request->n_channels) {
chanspecs = kcalloc(request->n_channels, sizeof(*chanspecs),
GFP_KERNEL);
if (!chanspecs) {
err = -ENOMEM;
goto exit;
}
vif = p2p->bss_idx[P2PAPI_BSSCFG_CONNECTION].vif;
if (vif)
dev = vif->wdev.netdev;
if (request->n_channels == 3 &&
request->channels[0]->hw_value == SOCIAL_CHAN_1 &&
request->channels[1]->hw_value == SOCIAL_CHAN_2 &&
request->channels[2]->hw_value == SOCIAL_CHAN_3) {
/* SOCIAL CHANNELS 1, 6, 11 */
search_state = WL_P2P_DISC_ST_SEARCH;
brcmf_dbg(INFO, "P2P SEARCH PHASE START\n");
} else if (dev != NULL && vif->mode == WL_MODE_AP) {
/* If you are already a GO, then do SEARCH only */
brcmf_dbg(INFO, "Already a GO. Do SEARCH Only\n");
search_state = WL_P2P_DISC_ST_SEARCH;
} else {
brcmf_dbg(INFO, "P2P SCAN STATE START\n");
}
/*
* no P2P scanning on passive or DFS channels.
*/
for (i = 0; i < request->n_channels; i++) {
struct ieee80211_channel *chan = request->channels[i];
if (chan->flags & (IEEE80211_CHAN_RADAR |
IEEE80211_CHAN_PASSIVE_SCAN))
continue;
chanspecs[i] = channel_to_chanspec(&p2p->cfg->d11inf,
chan);
brcmf_dbg(INFO, "%d: chan=%d, channel spec=%x\n",
num_nodfs, chan->hw_value, chanspecs[i]);
num_nodfs++;
}
err = brcmf_p2p_escan(p2p, num_nodfs, chanspecs, search_state,
action, P2PAPI_BSSCFG_DEVICE);
}
exit:
if (err)
brcmf_err("error (%d)\n", err);
return err;
}
/**
* brcmf_p2p_find_listen_channel() - find listen channel in ie string.
*
* @ie: string of information elements.
* @ie_len: length of string.
*
* Scan ie for p2p ie and look for attribute 6 channel. If available determine
* channel and return it.
*/
static s32 brcmf_p2p_find_listen_channel(const u8 *ie, u32 ie_len)
{
u8 channel_ie[5];
s32 listen_channel;
s32 err;
err = cfg80211_get_p2p_attr(ie, ie_len,
IEEE80211_P2P_ATTR_LISTEN_CHANNEL,
channel_ie, sizeof(channel_ie));
if (err < 0)
return err;
/* listen channel subel length format: */
/* 3(country) + 1(op. class) + 1(chan num) */
listen_channel = (s32)channel_ie[3 + 1];
if (listen_channel == SOCIAL_CHAN_1 ||
listen_channel == SOCIAL_CHAN_2 ||
listen_channel == SOCIAL_CHAN_3) {
brcmf_dbg(INFO, "Found my Listen Channel %d\n", listen_channel);
return listen_channel;
}
return -EPERM;
}
/**
* brcmf_p2p_scan_prep() - prepare scan based on request.
*
* @wiphy: wiphy device.
* @request: scan request from cfg80211.
* @vif: vif on which scan request is to be executed.
*
* Prepare the scan appropriately for type of scan requested. Overrides the
* escan .run() callback for peer-to-peer scanning.
*/
int brcmf_p2p_scan_prep(struct wiphy *wiphy,
struct cfg80211_scan_request *request,
struct brcmf_cfg80211_vif *vif)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_p2p_info *p2p = &cfg->p2p;
int err = 0;
if (brcmf_p2p_scan_is_p2p_request(request)) {
/* find my listen channel */
err = brcmf_p2p_find_listen_channel(request->ie,
request->ie_len);
if (err < 0)
return err;
p2p->afx_hdl.my_listen_chan = err;
clear_bit(BRCMF_P2P_STATUS_GO_NEG_PHASE, &p2p->status);
brcmf_dbg(INFO, "P2P: GO_NEG_PHASE status cleared\n");
err = brcmf_p2p_enable_discovery(p2p);
if (err)
return err;
vif = p2p->bss_idx[P2PAPI_BSSCFG_DEVICE].vif;
/* override .run_escan() callback. */
cfg->escan_info.run = brcmf_p2p_run_escan;
}
err = brcmf_vif_set_mgmt_ie(vif, BRCMF_VNDR_IE_PRBREQ_FLAG,
request->ie, request->ie_len);
return err;
}
/**
* brcmf_p2p_discover_listen() - set firmware to discover listen state.
*
* @p2p: p2p device.
* @channel: channel nr for discover listen.
* @duration: time in ms to stay on channel.
*
*/
static s32
brcmf_p2p_discover_listen(struct brcmf_p2p_info *p2p, u16 channel, u32 duration)
{
struct brcmf_cfg80211_vif *vif;
struct brcmu_chan ch;
s32 err = 0;
vif = p2p->bss_idx[P2PAPI_BSSCFG_DEVICE].vif;
if (!vif) {
brcmf_err("Discovery is not set, so we have nothing to do\n");
err = -EPERM;
goto exit;
}
if (test_bit(BRCMF_P2P_STATUS_DISCOVER_LISTEN, &p2p->status)) {
brcmf_err("Previous LISTEN is not completed yet\n");
/* WAR: prevent cookie mismatch in wpa_supplicant return OK */
goto exit;
}
ch.chnum = channel;
ch.bw = BRCMU_CHAN_BW_20;
p2p->cfg->d11inf.encchspec(&ch);
err = brcmf_p2p_set_discover_state(vif->ifp, WL_P2P_DISC_ST_LISTEN,
ch.chspec, (u16)duration);
if (!err) {
set_bit(BRCMF_P2P_STATUS_DISCOVER_LISTEN, &p2p->status);
p2p->remain_on_channel_cookie++;
}
exit:
return err;
}
/**
* brcmf_p2p_remain_on_channel() - put device on channel and stay there.
*
* @wiphy: wiphy device.
* @channel: channel to stay on.
* @duration: time in ms to remain on channel.
*
*/
int brcmf_p2p_remain_on_channel(struct wiphy *wiphy, struct wireless_dev *wdev,
struct ieee80211_channel *channel,
unsigned int duration, u64 *cookie)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_p2p_info *p2p = &cfg->p2p;
s32 err;
u16 channel_nr;
channel_nr = ieee80211_frequency_to_channel(channel->center_freq);
brcmf_dbg(TRACE, "Enter, channel: %d, duration ms (%d)\n", channel_nr,
duration);
err = brcmf_p2p_enable_discovery(p2p);
if (err)
goto exit;
err = brcmf_p2p_discover_listen(p2p, channel_nr, duration);
if (err)
goto exit;
memcpy(&p2p->remain_on_channel, channel, sizeof(*channel));
*cookie = p2p->remain_on_channel_cookie;
cfg80211_ready_on_channel(wdev, *cookie, channel, duration, GFP_KERNEL);
exit:
return err;
}
/**
* brcmf_p2p_notify_listen_complete() - p2p listen has completed.
*
* @ifp: interfac control.
* @e: event message. Not used, to make it usable for fweh event dispatcher.
* @data: payload of message. Not used.
*
*/
int brcmf_p2p_notify_listen_complete(struct brcmf_if *ifp,
const struct brcmf_event_msg *e,
void *data)
{
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
struct brcmf_p2p_info *p2p = &cfg->p2p;
brcmf_dbg(TRACE, "Enter\n");
if (test_and_clear_bit(BRCMF_P2P_STATUS_DISCOVER_LISTEN,
&p2p->status)) {
if (test_and_clear_bit(BRCMF_P2P_STATUS_WAITING_NEXT_AF_LISTEN,
&p2p->status)) {
clear_bit(BRCMF_P2P_STATUS_WAITING_NEXT_ACT_FRAME,
&p2p->status);
brcmf_dbg(INFO, "Listen DONE, wake up wait_next_af\n");
complete(&p2p->wait_next_af);
}
cfg80211_remain_on_channel_expired(&ifp->vif->wdev,
p2p->remain_on_channel_cookie,
&p2p->remain_on_channel,
GFP_KERNEL);
}
return 0;
}
/**
* brcmf_p2p_cancel_remain_on_channel() - cancel p2p listen state.
*
* @ifp: interfac control.
*
*/
void brcmf_p2p_cancel_remain_on_channel(struct brcmf_if *ifp)
{
if (!ifp)
return;
brcmf_p2p_set_discover_state(ifp, WL_P2P_DISC_ST_SCAN, 0, 0);
brcmf_p2p_notify_listen_complete(ifp, NULL, NULL);
}
/**
* brcmf_p2p_act_frm_search() - search function for action frame.
*
* @p2p: p2p device.
* channel: channel on which action frame is to be trasmitted.
*
* search function to reach at common channel to send action frame. When
* channel is 0 then all social channels will be used to send af
*/
static s32 brcmf_p2p_act_frm_search(struct brcmf_p2p_info *p2p, u16 channel)
{
s32 err;
u32 channel_cnt;
u16 *default_chan_list;
u32 i;
struct brcmu_chan ch;
brcmf_dbg(TRACE, "Enter\n");
if (channel)
channel_cnt = AF_PEER_SEARCH_CNT;
else
channel_cnt = SOCIAL_CHAN_CNT;
default_chan_list = kzalloc(channel_cnt * sizeof(*default_chan_list),
GFP_KERNEL);
if (default_chan_list == NULL) {
brcmf_err("channel list allocation failed\n");
err = -ENOMEM;
goto exit;
}
ch.bw = BRCMU_CHAN_BW_20;
if (channel) {
ch.chnum = channel;
p2p->cfg->d11inf.encchspec(&ch);
/* insert same channel to the chan_list */
for (i = 0; i < channel_cnt; i++)
default_chan_list[i] = ch.chspec;
} else {
ch.chnum = SOCIAL_CHAN_1;
p2p->cfg->d11inf.encchspec(&ch);
default_chan_list[0] = ch.chspec;
ch.chnum = SOCIAL_CHAN_2;
p2p->cfg->d11inf.encchspec(&ch);
default_chan_list[1] = ch.chspec;
ch.chnum = SOCIAL_CHAN_3;
p2p->cfg->d11inf.encchspec(&ch);
default_chan_list[2] = ch.chspec;
}
err = brcmf_p2p_escan(p2p, channel_cnt, default_chan_list,
WL_P2P_DISC_ST_SEARCH, WL_ESCAN_ACTION_START,
P2PAPI_BSSCFG_DEVICE);
kfree(default_chan_list);
exit:
return err;
}
/**
* brcmf_p2p_afx_handler() - afx worker thread.
*
* @work:
*
*/
static void brcmf_p2p_afx_handler(struct work_struct *work)
{
struct afx_hdl *afx_hdl = container_of(work, struct afx_hdl, afx_work);
struct brcmf_p2p_info *p2p = container_of(afx_hdl,
struct brcmf_p2p_info,
afx_hdl);
s32 err;
if (!afx_hdl->is_active)
return;
if (afx_hdl->is_listen && afx_hdl->my_listen_chan)
/* 100ms ~ 300ms */
err = brcmf_p2p_discover_listen(p2p, afx_hdl->my_listen_chan,
100 * (1 + prandom_u32() % 3));
else
err = brcmf_p2p_act_frm_search(p2p, afx_hdl->peer_listen_chan);
if (err) {
brcmf_err("ERROR occurred! value is (%d)\n", err);
if (test_bit(BRCMF_P2P_STATUS_FINDING_COMMON_CHANNEL,
&p2p->status))
complete(&afx_hdl->act_frm_scan);
}
}
/**
* brcmf_p2p_af_searching_channel() - search channel.
*
* @p2p: p2p device info struct.
*
*/
static s32 brcmf_p2p_af_searching_channel(struct brcmf_p2p_info *p2p)
{
struct afx_hdl *afx_hdl = &p2p->afx_hdl;
struct brcmf_cfg80211_vif *pri_vif;
unsigned long duration;
s32 retry;
brcmf_dbg(TRACE, "Enter\n");
pri_vif = p2p->bss_idx[P2PAPI_BSSCFG_PRIMARY].vif;
INIT_COMPLETION(afx_hdl->act_frm_scan);
set_bit(BRCMF_P2P_STATUS_FINDING_COMMON_CHANNEL, &p2p->status);
afx_hdl->is_active = true;
afx_hdl->peer_chan = P2P_INVALID_CHANNEL;
/* Loop to wait until we find a peer's channel or the
* pending action frame tx is cancelled.
*/
retry = 0;
duration = msecs_to_jiffies(P2P_AF_FRM_SCAN_MAX_WAIT);
while ((retry < P2P_CHANNEL_SYNC_RETRY) &&
(afx_hdl->peer_chan == P2P_INVALID_CHANNEL)) {
afx_hdl->is_listen = false;
brcmf_dbg(TRACE, "Scheduling action frame for sending.. (%d)\n",
retry);
/* search peer on peer's listen channel */
schedule_work(&afx_hdl->afx_work);
wait_for_completion_timeout(&afx_hdl->act_frm_scan, duration);
if ((afx_hdl->peer_chan != P2P_INVALID_CHANNEL) ||
(!test_bit(BRCMF_P2P_STATUS_FINDING_COMMON_CHANNEL,
&p2p->status)))
break;
if (afx_hdl->my_listen_chan) {
brcmf_dbg(TRACE, "Scheduling listen peer, channel=%d\n",
afx_hdl->my_listen_chan);
/* listen on my listen channel */
afx_hdl->is_listen = true;
schedule_work(&afx_hdl->afx_work);
wait_for_completion_timeout(&afx_hdl->act_frm_scan,
duration);
}
if ((afx_hdl->peer_chan != P2P_INVALID_CHANNEL) ||
(!test_bit(BRCMF_P2P_STATUS_FINDING_COMMON_CHANNEL,
&p2p->status)))
break;
retry++;
/* if sta is connected or connecting, sleep for a while before
* retry af tx or finding a peer
*/
if (test_bit(BRCMF_VIF_STATUS_CONNECTED, &pri_vif->sme_state) ||
test_bit(BRCMF_VIF_STATUS_CONNECTING, &pri_vif->sme_state))
msleep(P2P_DEFAULT_SLEEP_TIME_VSDB);
}
brcmf_dbg(TRACE, "Completed search/listen peer_chan=%d\n",
afx_hdl->peer_chan);
afx_hdl->is_active = false;
clear_bit(BRCMF_P2P_STATUS_FINDING_COMMON_CHANNEL, &p2p->status);
return afx_hdl->peer_chan;
}
/**
* brcmf_p2p_scan_finding_common_channel() - was escan used for finding channel
*
* @cfg: common configuration struct.
* @bi: bss info struct, result from scan.
*
*/
bool brcmf_p2p_scan_finding_common_channel(struct brcmf_cfg80211_info *cfg,
struct brcmf_bss_info_le *bi)
{
struct brcmf_p2p_info *p2p = &cfg->p2p;
struct afx_hdl *afx_hdl = &p2p->afx_hdl;
struct brcmu_chan ch;
u8 *ie;
s32 err;
u8 p2p_dev_addr[ETH_ALEN];
if (!test_bit(BRCMF_P2P_STATUS_FINDING_COMMON_CHANNEL, &p2p->status))
return false;
if (bi == NULL) {
brcmf_dbg(TRACE, "ACTION FRAME SCAN Done\n");
if (afx_hdl->peer_chan == P2P_INVALID_CHANNEL)
complete(&afx_hdl->act_frm_scan);
return true;
}
ie = ((u8 *)bi) + le16_to_cpu(bi->ie_offset);
memset(p2p_dev_addr, 0, sizeof(p2p_dev_addr));
err = cfg80211_get_p2p_attr(ie, le32_to_cpu(bi->ie_length),
IEEE80211_P2P_ATTR_DEVICE_INFO,
p2p_dev_addr, sizeof(p2p_dev_addr));
if (err < 0)
err = cfg80211_get_p2p_attr(ie, le32_to_cpu(bi->ie_length),
IEEE80211_P2P_ATTR_DEVICE_ID,
p2p_dev_addr, sizeof(p2p_dev_addr));
if ((err >= 0) &&
(!memcmp(p2p_dev_addr, afx_hdl->tx_dst_addr, ETH_ALEN))) {
if (!bi->ctl_ch) {
ch.chspec = le16_to_cpu(bi->chanspec);
cfg->d11inf.decchspec(&ch);
bi->ctl_ch = ch.chnum;
}
afx_hdl->peer_chan = bi->ctl_ch;
brcmf_dbg(TRACE, "ACTION FRAME SCAN : Peer %pM found, channel : %d\n",
afx_hdl->tx_dst_addr, afx_hdl->peer_chan);
complete(&afx_hdl->act_frm_scan);
}
return true;
}
/**
* brcmf_p2p_stop_wait_next_action_frame() - finish scan if af tx complete.
*
* @cfg: common configuration struct.
*
*/
static void
brcmf_p2p_stop_wait_next_action_frame(struct brcmf_cfg80211_info *cfg)
{
struct brcmf_p2p_info *p2p = &cfg->p2p;
struct brcmf_if *ifp = cfg->escan_info.ifp;
if (test_bit(BRCMF_P2P_STATUS_SENDING_ACT_FRAME, &p2p->status) &&
(test_bit(BRCMF_P2P_STATUS_ACTION_TX_COMPLETED, &p2p->status) ||
test_bit(BRCMF_P2P_STATUS_ACTION_TX_NOACK, &p2p->status))) {
brcmf_dbg(TRACE, "*** Wake UP ** abort actframe iovar\n");
/* if channel is not zero, "actfame" uses off channel scan.
* So abort scan for off channel completion.
*/
if (p2p->af_sent_channel)
brcmf_notify_escan_complete(cfg, ifp, true, true);
} else if (test_bit(BRCMF_P2P_STATUS_WAITING_NEXT_AF_LISTEN,
&p2p->status)) {
brcmf_dbg(TRACE, "*** Wake UP ** abort listen for next af frame\n");
/* So abort scan to cancel listen */
brcmf_notify_escan_complete(cfg, ifp, true, true);
}
}
/**
* brcmf_p2p_gon_req_collision() - Check if go negotiaton collission
*
* @p2p: p2p device info struct.
*
* return true if recevied action frame is to be dropped.
*/
static bool
brcmf_p2p_gon_req_collision(struct brcmf_p2p_info *p2p, u8 *mac)
{
struct brcmf_cfg80211_info *cfg = p2p->cfg;
struct brcmf_if *ifp;
brcmf_dbg(TRACE, "Enter\n");
if (!test_bit(BRCMF_P2P_STATUS_WAITING_NEXT_ACT_FRAME, &p2p->status) ||
!p2p->gon_req_action)
return false;
brcmf_dbg(TRACE, "GO Negotiation Request COLLISION !!!\n");
/* if sa(peer) addr is less than da(my) addr, then this device
* process peer's gon request and block to send gon req.
* if not (sa addr > da addr),
* this device will process gon request and drop gon req of peer.
*/
ifp = p2p->bss_idx[P2PAPI_BSSCFG_DEVICE].vif->ifp;
if (memcmp(mac, ifp->mac_addr, ETH_ALEN) < 0) {
brcmf_dbg(INFO, "Block transmit gon req !!!\n");
p2p->block_gon_req_tx = true;
/* if we are finding a common channel for sending af,
* do not scan more to block to send current gon req
*/
if (test_and_clear_bit(BRCMF_P2P_STATUS_FINDING_COMMON_CHANNEL,
&p2p->status))
complete(&p2p->afx_hdl.act_frm_scan);
if (test_and_clear_bit(BRCMF_P2P_STATUS_WAITING_NEXT_ACT_FRAME,
&p2p->status))
brcmf_p2p_stop_wait_next_action_frame(cfg);
return false;
}
/* drop gon request of peer to process gon request by this device. */
brcmf_dbg(INFO, "Drop received gon req !!!\n");
return true;
}
/**
* brcmf_p2p_notify_action_frame_rx() - received action frame.
*
* @ifp: interfac control.
* @e: event message. Not used, to make it usable for fweh event dispatcher.
* @data: payload of message, containing action frame data.
*
*/
int brcmf_p2p_notify_action_frame_rx(struct brcmf_if *ifp,
const struct brcmf_event_msg *e,
void *data)
{
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
struct brcmf_p2p_info *p2p = &cfg->p2p;
struct afx_hdl *afx_hdl = &p2p->afx_hdl;
struct wireless_dev *wdev;
u32 mgmt_frame_len = e->datalen - sizeof(struct brcmf_rx_mgmt_data);
struct brcmf_rx_mgmt_data *rxframe = (struct brcmf_rx_mgmt_data *)data;
u8 *frame = (u8 *)(rxframe + 1);
struct brcmf_p2p_pub_act_frame *act_frm;
struct brcmf_p2psd_gas_pub_act_frame *sd_act_frm;
struct brcmu_chan ch;
struct ieee80211_mgmt *mgmt_frame;
s32 freq;
u16 mgmt_type;
u8 action;
ch.chspec = be16_to_cpu(rxframe->chanspec);
cfg->d11inf.decchspec(&ch);
/* Check if wpa_supplicant has registered for this frame */
brcmf_dbg(INFO, "ifp->vif->mgmt_rx_reg %04x\n", ifp->vif->mgmt_rx_reg);
mgmt_type = (IEEE80211_STYPE_ACTION & IEEE80211_FCTL_STYPE) >> 4;
if ((ifp->vif->mgmt_rx_reg & BIT(mgmt_type)) == 0)
return 0;
brcmf_p2p_print_actframe(false, frame, mgmt_frame_len);
action = P2P_PAF_SUBTYPE_INVALID;
if (brcmf_p2p_is_pub_action(frame, mgmt_frame_len)) {
act_frm = (struct brcmf_p2p_pub_act_frame *)frame;
action = act_frm->subtype;
if ((action == P2P_PAF_GON_REQ) &&
(brcmf_p2p_gon_req_collision(p2p, (u8 *)e->addr))) {
if (test_bit(BRCMF_P2P_STATUS_FINDING_COMMON_CHANNEL,
&p2p->status) &&
(memcmp(afx_hdl->tx_dst_addr, e->addr,
ETH_ALEN) == 0)) {
afx_hdl->peer_chan = ch.chnum;
brcmf_dbg(INFO, "GON request: Peer found, channel=%d\n",
afx_hdl->peer_chan);
complete(&afx_hdl->act_frm_scan);
}
return 0;
}
/* After complete GO Negotiation, roll back to mpc mode */
if ((action == P2P_PAF_GON_CONF) ||
(action == P2P_PAF_PROVDIS_RSP))
brcmf_set_mpc(ifp, 1);
if (action == P2P_PAF_GON_CONF) {
brcmf_dbg(TRACE, "P2P: GO_NEG_PHASE status cleared\n");
clear_bit(BRCMF_P2P_STATUS_GO_NEG_PHASE, &p2p->status);
}
} else if (brcmf_p2p_is_gas_action(frame, mgmt_frame_len)) {
sd_act_frm = (struct brcmf_p2psd_gas_pub_act_frame *)frame;
action = sd_act_frm->action;
}
if (test_bit(BRCMF_P2P_STATUS_WAITING_NEXT_ACT_FRAME, &p2p->status) &&
(p2p->next_af_subtype == action)) {
brcmf_dbg(TRACE, "We got a right next frame! (%d)\n", action);
clear_bit(BRCMF_P2P_STATUS_WAITING_NEXT_ACT_FRAME,
&p2p->status);
/* Stop waiting for next AF. */
brcmf_p2p_stop_wait_next_action_frame(cfg);
}
mgmt_frame = kzalloc(offsetof(struct ieee80211_mgmt, u) +
mgmt_frame_len, GFP_KERNEL);
if (!mgmt_frame) {
brcmf_err("No memory available for action frame\n");
return -ENOMEM;
}
memcpy(mgmt_frame->da, ifp->mac_addr, ETH_ALEN);
brcmf_fil_cmd_data_get(ifp, BRCMF_C_GET_BSSID, mgmt_frame->bssid,
ETH_ALEN);
memcpy(mgmt_frame->sa, e->addr, ETH_ALEN);
mgmt_frame->frame_control = cpu_to_le16(IEEE80211_STYPE_ACTION);
memcpy(&mgmt_frame->u, frame, mgmt_frame_len);
mgmt_frame_len += offsetof(struct ieee80211_mgmt, u);
freq = ieee80211_channel_to_frequency(ch.chnum,
ch.band == BRCMU_CHAN_BAND_2G ?
IEEE80211_BAND_2GHZ :
IEEE80211_BAND_5GHZ);
wdev = &ifp->vif->wdev;
cfg80211_rx_mgmt(wdev, freq, 0, (u8 *)mgmt_frame, mgmt_frame_len,
GFP_ATOMIC);
kfree(mgmt_frame);
return 0;
}
/**
* brcmf_p2p_notify_action_tx_complete() - transmit action frame complete
*
* @ifp: interfac control.
* @e: event message. Not used, to make it usable for fweh event dispatcher.
* @data: not used.
*
*/
int brcmf_p2p_notify_action_tx_complete(struct brcmf_if *ifp,
const struct brcmf_event_msg *e,
void *data)
{
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
struct brcmf_p2p_info *p2p = &cfg->p2p;
brcmf_dbg(INFO, "Enter: event %s, status=%d\n",
e->event_code == BRCMF_E_ACTION_FRAME_OFF_CHAN_COMPLETE ?
"ACTION_FRAME_OFF_CHAN_COMPLETE" : "ACTION_FRAME_COMPLETE",
e->status);
if (!test_bit(BRCMF_P2P_STATUS_SENDING_ACT_FRAME, &p2p->status))
return 0;
if (e->event_code == BRCMF_E_ACTION_FRAME_COMPLETE) {
if (e->status == BRCMF_E_STATUS_SUCCESS)
set_bit(BRCMF_P2P_STATUS_ACTION_TX_COMPLETED,
&p2p->status);
else {
set_bit(BRCMF_P2P_STATUS_ACTION_TX_NOACK, &p2p->status);
/* If there is no ack, we don't need to wait for
* WLC_E_ACTION_FRAME_OFFCHAN_COMPLETE event
*/
brcmf_p2p_stop_wait_next_action_frame(cfg);
}
} else {
complete(&p2p->send_af_done);
}
return 0;
}
/**
* brcmf_p2p_tx_action_frame() - send action frame over fil.
*
* @p2p: p2p info struct for vif.
* @af_params: action frame data/info.
*
* Send an action frame immediately without doing channel synchronization.
*
* This function waits for a completion event before returning.
* The WLC_E_ACTION_FRAME_COMPLETE event will be received when the action
* frame is transmitted.
*/
static s32 brcmf_p2p_tx_action_frame(struct brcmf_p2p_info *p2p,
struct brcmf_fil_af_params_le *af_params)
{
struct brcmf_cfg80211_vif *vif;
s32 err = 0;
s32 timeout = 0;
brcmf_dbg(TRACE, "Enter\n");
INIT_COMPLETION(p2p->send_af_done);
clear_bit(BRCMF_P2P_STATUS_ACTION_TX_COMPLETED, &p2p->status);
clear_bit(BRCMF_P2P_STATUS_ACTION_TX_NOACK, &p2p->status);
vif = p2p->bss_idx[P2PAPI_BSSCFG_DEVICE].vif;
err = brcmf_fil_bsscfg_data_set(vif->ifp, "actframe", af_params,
sizeof(*af_params));
if (err) {
brcmf_err(" sending action frame has failed\n");
goto exit;
}
p2p->af_sent_channel = le32_to_cpu(af_params->channel);
p2p->af_tx_sent_jiffies = jiffies;
timeout = wait_for_completion_timeout(&p2p->send_af_done,
msecs_to_jiffies(P2P_AF_MAX_WAIT_TIME));
if (test_bit(BRCMF_P2P_STATUS_ACTION_TX_COMPLETED, &p2p->status)) {
brcmf_dbg(TRACE, "TX action frame operation is success\n");
} else {
err = -EIO;
brcmf_dbg(TRACE, "TX action frame operation has failed\n");
}
/* clear status bit for action tx */
clear_bit(BRCMF_P2P_STATUS_ACTION_TX_COMPLETED, &p2p->status);
clear_bit(BRCMF_P2P_STATUS_ACTION_TX_NOACK, &p2p->status);
exit:
return err;
}
/**
* brcmf_p2p_pub_af_tx() - public action frame tx routine.
*
* @cfg: driver private data for cfg80211 interface.
* @af_params: action frame data/info.
* @config_af_params: configuration data for action frame.
*
* routine which transmits ation frame public type.
*/
static s32 brcmf_p2p_pub_af_tx(struct brcmf_cfg80211_info *cfg,
struct brcmf_fil_af_params_le *af_params,
struct brcmf_config_af_params *config_af_params)
{
struct brcmf_p2p_info *p2p = &cfg->p2p;
struct brcmf_fil_action_frame_le *action_frame;
struct brcmf_p2p_pub_act_frame *act_frm;
s32 err = 0;
u16 ie_len;
action_frame = &af_params->action_frame;
act_frm = (struct brcmf_p2p_pub_act_frame *)(action_frame->data);
config_af_params->extra_listen = true;
switch (act_frm->subtype) {
case P2P_PAF_GON_REQ:
brcmf_dbg(TRACE, "P2P: GO_NEG_PHASE status set\n");
set_bit(BRCMF_P2P_STATUS_GO_NEG_PHASE, &p2p->status);
config_af_params->mpc_onoff = 0;
config_af_params->search_channel = true;
p2p->next_af_subtype = act_frm->subtype + 1;
p2p->gon_req_action = true;
/* increase dwell time to wait for RESP frame */
af_params->dwell_time = cpu_to_le32(P2P_AF_MED_DWELL_TIME);
break;
case P2P_PAF_GON_RSP:
p2p->next_af_subtype = act_frm->subtype + 1;
/* increase dwell time to wait for CONF frame */
af_params->dwell_time = cpu_to_le32(P2P_AF_MED_DWELL_TIME);
break;
case P2P_PAF_GON_CONF:
/* If we reached till GO Neg confirmation reset the filter */
brcmf_dbg(TRACE, "P2P: GO_NEG_PHASE status cleared\n");
clear_bit(BRCMF_P2P_STATUS_GO_NEG_PHASE, &p2p->status);
/* turn on mpc again if go nego is done */
config_af_params->mpc_onoff = 1;
/* minimize dwell time */
af_params->dwell_time = cpu_to_le32(P2P_AF_MIN_DWELL_TIME);
config_af_params->extra_listen = false;
break;
case P2P_PAF_INVITE_REQ:
config_af_params->search_channel = true;
p2p->next_af_subtype = act_frm->subtype + 1;
/* increase dwell time */
af_params->dwell_time = cpu_to_le32(P2P_AF_MED_DWELL_TIME);
break;
case P2P_PAF_INVITE_RSP:
/* minimize dwell time */
af_params->dwell_time = cpu_to_le32(P2P_AF_MIN_DWELL_TIME);
config_af_params->extra_listen = false;
break;
case P2P_PAF_DEVDIS_REQ:
config_af_params->search_channel = true;
p2p->next_af_subtype = act_frm->subtype + 1;
/* maximize dwell time to wait for RESP frame */
af_params->dwell_time = cpu_to_le32(P2P_AF_LONG_DWELL_TIME);
break;
case P2P_PAF_DEVDIS_RSP:
/* minimize dwell time */
af_params->dwell_time = cpu_to_le32(P2P_AF_MIN_DWELL_TIME);
config_af_params->extra_listen = false;
break;
case P2P_PAF_PROVDIS_REQ:
ie_len = le16_to_cpu(action_frame->len) -
offsetof(struct brcmf_p2p_pub_act_frame, elts);
if (cfg80211_get_p2p_attr(&act_frm->elts[0], ie_len,
IEEE80211_P2P_ATTR_GROUP_ID,
NULL, 0) < 0)
config_af_params->search_channel = true;
config_af_params->mpc_onoff = 0;
p2p->next_af_subtype = act_frm->subtype + 1;
/* increase dwell time to wait for RESP frame */
af_params->dwell_time = cpu_to_le32(P2P_AF_MED_DWELL_TIME);
break;
case P2P_PAF_PROVDIS_RSP:
/* wpa_supplicant send go nego req right after prov disc */
p2p->next_af_subtype = P2P_PAF_GON_REQ;
/* increase dwell time to MED level */
af_params->dwell_time = cpu_to_le32(P2P_AF_MED_DWELL_TIME);
config_af_params->extra_listen = false;
break;
default:
brcmf_err("Unknown p2p pub act frame subtype: %d\n",
act_frm->subtype);
err = -EINVAL;
}
return err;
}
/**
* brcmf_p2p_send_action_frame() - send action frame .
*
* @cfg: driver private data for cfg80211 interface.
* @ndev: net device to transmit on.
* @af_params: configuration data for action frame.
*/
bool brcmf_p2p_send_action_frame(struct brcmf_cfg80211_info *cfg,
struct net_device *ndev,
struct brcmf_fil_af_params_le *af_params)
{
struct brcmf_p2p_info *p2p = &cfg->p2p;
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_fil_action_frame_le *action_frame;
struct brcmf_config_af_params config_af_params;
struct afx_hdl *afx_hdl = &p2p->afx_hdl;
u16 action_frame_len;
bool ack = false;
u8 category;
u8 action;
s32 tx_retry;
s32 extra_listen_time;
uint delta_ms;
action_frame = &af_params->action_frame;
action_frame_len = le16_to_cpu(action_frame->len);
brcmf_p2p_print_actframe(true, action_frame->data, action_frame_len);
/* Add the default dwell time. Dwell time to stay off-channel */
/* to wait for a response action frame after transmitting an */
/* GO Negotiation action frame */
af_params->dwell_time = cpu_to_le32(P2P_AF_DWELL_TIME);
category = action_frame->data[DOT11_ACTION_CAT_OFF];
action = action_frame->data[DOT11_ACTION_ACT_OFF];
/* initialize variables */
p2p->next_af_subtype = P2P_PAF_SUBTYPE_INVALID;
p2p->gon_req_action = false;
/* config parameters */
config_af_params.mpc_onoff = -1;
config_af_params.search_channel = false;
config_af_params.extra_listen = false;
if (brcmf_p2p_is_pub_action(action_frame->data, action_frame_len)) {
/* p2p public action frame process */
if (brcmf_p2p_pub_af_tx(cfg, af_params, &config_af_params)) {
/* Just send unknown subtype frame with */
/* default parameters. */
brcmf_err("P2P Public action frame, unknown subtype.\n");
}
} else if (brcmf_p2p_is_gas_action(action_frame->data,
action_frame_len)) {
/* service discovery process */
if (action == P2PSD_ACTION_ID_GAS_IREQ ||
action == P2PSD_ACTION_ID_GAS_CREQ) {
/* configure service discovery query frame */
config_af_params.search_channel = true;
/* save next af suptype to cancel */
/* remaining dwell time */
p2p->next_af_subtype = action + 1;
af_params->dwell_time =
cpu_to_le32(P2P_AF_MED_DWELL_TIME);
} else if (action == P2PSD_ACTION_ID_GAS_IRESP ||
action == P2PSD_ACTION_ID_GAS_CRESP) {
/* configure service discovery response frame */
af_params->dwell_time =
cpu_to_le32(P2P_AF_MIN_DWELL_TIME);
} else {
brcmf_err("Unknown action type: %d\n", action);
goto exit;
}
} else if (brcmf_p2p_is_p2p_action(action_frame->data,
action_frame_len)) {
/* do not configure anything. it will be */
/* sent with a default configuration */
} else {
brcmf_err("Unknown Frame: category 0x%x, action 0x%x\n",
category, action);
return false;
}
/* if connecting on primary iface, sleep for a while before sending
* af tx for VSDB
*/
if (test_bit(BRCMF_VIF_STATUS_CONNECTING,
&p2p->bss_idx[P2PAPI_BSSCFG_PRIMARY].vif->sme_state))
msleep(50);
/* if scan is ongoing, abort current scan. */
if (test_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status))
brcmf_abort_scanning(cfg);
memcpy(afx_hdl->tx_dst_addr, action_frame->da, ETH_ALEN);
/* To make sure to send successfully action frame, turn off mpc */
if (config_af_params.mpc_onoff == 0)
brcmf_set_mpc(ifp, 0);
/* set status and destination address before sending af */
if (p2p->next_af_subtype != P2P_PAF_SUBTYPE_INVALID) {
/* set status to cancel the remained dwell time in rx process */
set_bit(BRCMF_P2P_STATUS_WAITING_NEXT_ACT_FRAME, &p2p->status);
}
p2p->af_sent_channel = 0;
set_bit(BRCMF_P2P_STATUS_SENDING_ACT_FRAME, &p2p->status);
/* validate channel and p2p ies */
if (config_af_params.search_channel &&
IS_P2P_SOCIAL_CHANNEL(le32_to_cpu(af_params->channel)) &&
p2p->bss_idx[P2PAPI_BSSCFG_DEVICE].vif->saved_ie.probe_req_ie_len) {
afx_hdl = &p2p->afx_hdl;
afx_hdl->peer_listen_chan = le32_to_cpu(af_params->channel);
if (brcmf_p2p_af_searching_channel(p2p) ==
P2P_INVALID_CHANNEL) {
brcmf_err("Couldn't find peer's channel.\n");
goto exit;
}
/* Abort scan even for VSDB scenarios. Scan gets aborted in
* firmware but after the check of piggyback algorithm. To take
* care of current piggback algo, lets abort the scan here
* itself.
*/
brcmf_notify_escan_complete(cfg, ifp, true, true);
/* update channel */
af_params->channel = cpu_to_le32(afx_hdl->peer_chan);
}
tx_retry = 0;
while (!p2p->block_gon_req_tx &&
(ack == false) && (tx_retry < P2P_AF_TX_MAX_RETRY)) {
ack = !brcmf_p2p_tx_action_frame(p2p, af_params);
tx_retry++;
}
if (ack == false) {
brcmf_err("Failed to send Action Frame(retry %d)\n", tx_retry);
clear_bit(BRCMF_P2P_STATUS_GO_NEG_PHASE, &p2p->status);
}
exit:
clear_bit(BRCMF_P2P_STATUS_SENDING_ACT_FRAME, &p2p->status);
/* WAR: sometimes dongle does not keep the dwell time of 'actframe'.
* if we coundn't get the next action response frame and dongle does
* not keep the dwell time, go to listen state again to get next action
* response frame.
*/
if (ack && config_af_params.extra_listen && !p2p->block_gon_req_tx &&
test_bit(BRCMF_P2P_STATUS_WAITING_NEXT_ACT_FRAME, &p2p->status) &&
p2p->af_sent_channel == afx_hdl->my_listen_chan) {
delta_ms = jiffies_to_msecs(jiffies - p2p->af_tx_sent_jiffies);
if (le32_to_cpu(af_params->dwell_time) > delta_ms)
extra_listen_time = le32_to_cpu(af_params->dwell_time) -
delta_ms;
else
extra_listen_time = 0;
if (extra_listen_time > 50) {
set_bit(BRCMF_P2P_STATUS_WAITING_NEXT_AF_LISTEN,
&p2p->status);
brcmf_dbg(INFO, "Wait more time! actual af time:%d, calculated extra listen:%d\n",
le32_to_cpu(af_params->dwell_time),
extra_listen_time);
extra_listen_time += 100;
if (!brcmf_p2p_discover_listen(p2p,
p2p->af_sent_channel,
extra_listen_time)) {
unsigned long duration;
extra_listen_time += 100;
duration = msecs_to_jiffies(extra_listen_time);
wait_for_completion_timeout(&p2p->wait_next_af,
duration);
}
clear_bit(BRCMF_P2P_STATUS_WAITING_NEXT_AF_LISTEN,
&p2p->status);
}
}
if (p2p->block_gon_req_tx) {
/* if ack is true, supplicant will wait more time(100ms).
* so we will return it as a success to get more time .
*/
p2p->block_gon_req_tx = false;
ack = true;
}
clear_bit(BRCMF_P2P_STATUS_WAITING_NEXT_ACT_FRAME, &p2p->status);
/* if all done, turn mpc on again */
if (config_af_params.mpc_onoff == 1)
brcmf_set_mpc(ifp, 1);
return ack;
}
/**
* brcmf_p2p_notify_rx_mgmt_p2p_probereq() - Event handler for p2p probe req.
*
* @ifp: interface pointer for which event was received.
* @e: even message.
* @data: payload of event message (probe request).
*/
s32 brcmf_p2p_notify_rx_mgmt_p2p_probereq(struct brcmf_if *ifp,
const struct brcmf_event_msg *e,
void *data)
{
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
struct brcmf_p2p_info *p2p = &cfg->p2p;
struct afx_hdl *afx_hdl = &p2p->afx_hdl;
struct brcmf_cfg80211_vif *vif = ifp->vif;
struct brcmf_rx_mgmt_data *rxframe = (struct brcmf_rx_mgmt_data *)data;
u16 chanspec = be16_to_cpu(rxframe->chanspec);
struct brcmu_chan ch;
u8 *mgmt_frame;
u32 mgmt_frame_len;
s32 freq;
u16 mgmt_type;
brcmf_dbg(INFO, "Enter: event %d reason %d\n", e->event_code,
e->reason);
ch.chspec = be16_to_cpu(rxframe->chanspec);
cfg->d11inf.decchspec(&ch);
if (test_bit(BRCMF_P2P_STATUS_FINDING_COMMON_CHANNEL, &p2p->status) &&
(memcmp(afx_hdl->tx_dst_addr, e->addr, ETH_ALEN) == 0)) {
afx_hdl->peer_chan = ch.chnum;
brcmf_dbg(INFO, "PROBE REQUEST: Peer found, channel=%d\n",
afx_hdl->peer_chan);
complete(&afx_hdl->act_frm_scan);
}
/* Firmware sends us two proberesponses for each idx one. At the */
/* moment anything but bsscfgidx 0 is passed up to supplicant */
if (e->bsscfgidx == 0)
return 0;
/* Filter any P2P probe reqs arriving during the GO-NEG Phase */
if (test_bit(BRCMF_P2P_STATUS_GO_NEG_PHASE, &p2p->status)) {
brcmf_dbg(INFO, "Filtering P2P probe_req in GO-NEG phase\n");
return 0;
}
/* Check if wpa_supplicant has registered for this frame */
brcmf_dbg(INFO, "vif->mgmt_rx_reg %04x\n", vif->mgmt_rx_reg);
mgmt_type = (IEEE80211_STYPE_PROBE_REQ & IEEE80211_FCTL_STYPE) >> 4;
if ((vif->mgmt_rx_reg & BIT(mgmt_type)) == 0)
return 0;
mgmt_frame = (u8 *)(rxframe + 1);
mgmt_frame_len = e->datalen - sizeof(*rxframe);
freq = ieee80211_channel_to_frequency(ch.chnum,
ch.band == BRCMU_CHAN_BAND_2G ?
IEEE80211_BAND_2GHZ :
IEEE80211_BAND_5GHZ);
cfg80211_rx_mgmt(&vif->wdev, freq, 0, mgmt_frame, mgmt_frame_len,
GFP_ATOMIC);
brcmf_dbg(INFO, "mgmt_frame_len (%d) , e->datalen (%d), chanspec (%04x), freq (%d)\n",
mgmt_frame_len, e->datalen, chanspec, freq);
return 0;
}
/**
* brcmf_p2p_attach() - attach for P2P.
*
* @cfg: driver private data for cfg80211 interface.
*/
s32 brcmf_p2p_attach(struct brcmf_cfg80211_info *cfg)
{
struct brcmf_if *pri_ifp;
struct brcmf_if *p2p_ifp;
struct brcmf_cfg80211_vif *p2p_vif;
struct brcmf_p2p_info *p2p;
struct brcmf_pub *drvr;
s32 bssidx;
s32 err = 0;
p2p = &cfg->p2p;
p2p->cfg = cfg;
drvr = cfg->pub;
pri_ifp = drvr->iflist[0];
p2p_ifp = drvr->iflist[1];
p2p->bss_idx[P2PAPI_BSSCFG_PRIMARY].vif = pri_ifp->vif;
if (p2p_ifp) {
p2p_vif = brcmf_alloc_vif(cfg, NL80211_IFTYPE_P2P_DEVICE,
false);
if (IS_ERR(p2p_vif)) {
brcmf_err("could not create discovery vif\n");
err = -ENOMEM;
goto exit;
}
p2p_vif->ifp = p2p_ifp;
p2p_ifp->vif = p2p_vif;
p2p_vif->wdev.netdev = p2p_ifp->ndev;
p2p_ifp->ndev->ieee80211_ptr = &p2p_vif->wdev;
SET_NETDEV_DEV(p2p_ifp->ndev, wiphy_dev(cfg->wiphy));
p2p->bss_idx[P2PAPI_BSSCFG_DEVICE].vif = p2p_vif;
brcmf_p2p_generate_bss_mac(p2p, NULL);
memcpy(p2p_ifp->mac_addr, p2p->dev_addr, ETH_ALEN);
brcmf_p2p_set_firmware(pri_ifp, p2p->dev_addr);
/* Initialize P2P Discovery in the firmware */
err = brcmf_fil_iovar_int_set(pri_ifp, "p2p_disc", 1);
if (err < 0) {
brcmf_err("set p2p_disc error\n");
brcmf_free_vif(cfg, p2p_vif);
goto exit;
}
/* obtain bsscfg index for P2P discovery */
err = brcmf_fil_iovar_int_get(pri_ifp, "p2p_dev", &bssidx);
if (err < 0) {
brcmf_err("retrieving discover bsscfg index failed\n");
brcmf_free_vif(cfg, p2p_vif);
goto exit;
}
/* Verify that firmware uses same bssidx as driver !! */
if (p2p_ifp->bssidx != bssidx) {
brcmf_err("Incorrect bssidx=%d, compared to p2p_ifp->bssidx=%d\n",
bssidx, p2p_ifp->bssidx);
brcmf_free_vif(cfg, p2p_vif);
goto exit;
}
init_completion(&p2p->send_af_done);
INIT_WORK(&p2p->afx_hdl.afx_work, brcmf_p2p_afx_handler);
init_completion(&p2p->afx_hdl.act_frm_scan);
init_completion(&p2p->wait_next_af);
}
exit:
return err;
}
/**
* brcmf_p2p_detach() - detach P2P.
*
* @p2p: P2P specific data.
*/
void brcmf_p2p_detach(struct brcmf_p2p_info *p2p)
{
struct brcmf_cfg80211_vif *vif;
vif = p2p->bss_idx[P2PAPI_BSSCFG_DEVICE].vif;
if (vif != NULL) {
brcmf_p2p_cancel_remain_on_channel(vif->ifp);
brcmf_p2p_deinit_discovery(p2p);
/* remove discovery interface */
brcmf_free_vif(p2p->cfg, vif);
p2p->bss_idx[P2PAPI_BSSCFG_DEVICE].vif = NULL;
}
/* just set it all to zero */
memset(p2p, 0, sizeof(*p2p));
}
/**
* brcmf_p2p_get_current_chanspec() - Get current operation channel.
*
* @p2p: P2P specific data.
* @chanspec: chanspec to be returned.
*/
static void brcmf_p2p_get_current_chanspec(struct brcmf_p2p_info *p2p,
u16 *chanspec)
{
struct brcmf_if *ifp;
u8 mac_addr[ETH_ALEN];
struct brcmu_chan ch;
struct brcmf_bss_info_le *bi;
u8 *buf;
ifp = p2p->bss_idx[P2PAPI_BSSCFG_PRIMARY].vif->ifp;
if (brcmf_fil_cmd_data_get(ifp, BRCMF_C_GET_BSSID, mac_addr,
ETH_ALEN) == 0) {
buf = kzalloc(WL_BSS_INFO_MAX, GFP_KERNEL);
if (buf != NULL) {
*(__le32 *)buf = cpu_to_le32(WL_BSS_INFO_MAX);
if (brcmf_fil_cmd_data_get(ifp, BRCMF_C_GET_BSS_INFO,
buf, WL_BSS_INFO_MAX) == 0) {
bi = (struct brcmf_bss_info_le *)(buf + 4);
*chanspec = le16_to_cpu(bi->chanspec);
kfree(buf);
return;
}
kfree(buf);
}
}
/* Use default channel for P2P */
ch.chnum = BRCMF_P2P_TEMP_CHAN;
ch.bw = BRCMU_CHAN_BW_20;
p2p->cfg->d11inf.encchspec(&ch);
*chanspec = ch.chspec;
}
/**
* Change a P2P Role.
* Parameters:
* @mac: MAC address of the BSS to change a role
* Returns 0 if success.
*/
int brcmf_p2p_ifchange(struct brcmf_cfg80211_info *cfg,
enum brcmf_fil_p2p_if_types if_type)
{
struct brcmf_p2p_info *p2p = &cfg->p2p;
struct brcmf_cfg80211_vif *vif;
struct brcmf_fil_p2p_if_le if_request;
s32 err;
u16 chanspec;
brcmf_dbg(TRACE, "Enter\n");
vif = p2p->bss_idx[P2PAPI_BSSCFG_PRIMARY].vif;
if (!vif) {
brcmf_err("vif for P2PAPI_BSSCFG_PRIMARY does not exist\n");
return -EPERM;
}
brcmf_notify_escan_complete(cfg, vif->ifp, true, true);
vif = p2p->bss_idx[P2PAPI_BSSCFG_CONNECTION].vif;
if (!vif) {
brcmf_err("vif for P2PAPI_BSSCFG_CONNECTION does not exist\n");
return -EPERM;
}
brcmf_set_mpc(vif->ifp, 0);
/* In concurrency case, STA may be already associated in a particular */
/* channel. so retrieve the current channel of primary interface and */
/* then start the virtual interface on that. */
brcmf_p2p_get_current_chanspec(p2p, &chanspec);
if_request.type = cpu_to_le16((u16)if_type);
if_request.chspec = cpu_to_le16(chanspec);
memcpy(if_request.addr, p2p->int_addr, sizeof(if_request.addr));
brcmf_cfg80211_arm_vif_event(cfg, vif);
err = brcmf_fil_iovar_data_set(vif->ifp, "p2p_ifupd", &if_request,
sizeof(if_request));
if (err) {
brcmf_err("p2p_ifupd FAILED, err=%d\n", err);
brcmf_cfg80211_arm_vif_event(cfg, NULL);
return err;
}
err = brcmf_cfg80211_wait_vif_event_timeout(cfg, BRCMF_E_IF_CHANGE,
msecs_to_jiffies(1500));
brcmf_cfg80211_arm_vif_event(cfg, NULL);
if (!err) {
brcmf_err("No BRCMF_E_IF_CHANGE event received\n");
return -EIO;
}
err = brcmf_fil_cmd_int_set(vif->ifp, BRCMF_C_SET_SCB_TIMEOUT,
BRCMF_SCB_TIMEOUT_VALUE);
return err;
}
static int brcmf_p2p_request_p2p_if(struct brcmf_p2p_info *p2p,
struct brcmf_if *ifp, u8 ea[ETH_ALEN],
enum brcmf_fil_p2p_if_types iftype)
{
struct brcmf_fil_p2p_if_le if_request;
int err;
u16 chanspec;
/* we need a default channel */
brcmf_p2p_get_current_chanspec(p2p, &chanspec);
/* fill the firmware request */
memcpy(if_request.addr, ea, ETH_ALEN);
if_request.type = cpu_to_le16((u16)iftype);
if_request.chspec = cpu_to_le16(chanspec);
err = brcmf_fil_iovar_data_set(ifp, "p2p_ifadd", &if_request,
sizeof(if_request));
if (err)
return err;
return err;
}
static int brcmf_p2p_disable_p2p_if(struct brcmf_cfg80211_vif *vif)
{
struct brcmf_cfg80211_info *cfg = wdev_to_cfg(&vif->wdev);
struct net_device *pri_ndev = cfg_to_ndev(cfg);
struct brcmf_if *ifp = netdev_priv(pri_ndev);
u8 *addr = vif->wdev.netdev->dev_addr;
return brcmf_fil_iovar_data_set(ifp, "p2p_ifdis", addr, ETH_ALEN);
}
static int brcmf_p2p_release_p2p_if(struct brcmf_cfg80211_vif *vif)
{
struct brcmf_cfg80211_info *cfg = wdev_to_cfg(&vif->wdev);
struct net_device *pri_ndev = cfg_to_ndev(cfg);
struct brcmf_if *ifp = netdev_priv(pri_ndev);
u8 *addr = vif->wdev.netdev->dev_addr;
return brcmf_fil_iovar_data_set(ifp, "p2p_ifdel", addr, ETH_ALEN);
}
/**
* brcmf_p2p_create_p2pdev() - create a P2P_DEVICE virtual interface.
*
* @p2p: P2P specific data.
* @wiphy: wiphy device of new interface.
* @addr: mac address for this new interface.
*/
static struct wireless_dev *brcmf_p2p_create_p2pdev(struct brcmf_p2p_info *p2p,
struct wiphy *wiphy,
u8 *addr)
{
struct brcmf_cfg80211_vif *p2p_vif;
struct brcmf_if *p2p_ifp;
struct brcmf_if *pri_ifp;
int err;
u32 bssidx;
if (p2p->bss_idx[P2PAPI_BSSCFG_DEVICE].vif)
return ERR_PTR(-ENOSPC);
p2p_vif = brcmf_alloc_vif(p2p->cfg, NL80211_IFTYPE_P2P_DEVICE,
false);
if (IS_ERR(p2p_vif)) {
brcmf_err("could not create discovery vif\n");
return (struct wireless_dev *)p2p_vif;
}
pri_ifp = p2p->bss_idx[P2PAPI_BSSCFG_PRIMARY].vif->ifp;
brcmf_p2p_generate_bss_mac(p2p, addr);
brcmf_p2p_set_firmware(pri_ifp, p2p->dev_addr);
brcmf_cfg80211_arm_vif_event(p2p->cfg, p2p_vif);
/* Initialize P2P Discovery in the firmware */
err = brcmf_fil_iovar_int_set(pri_ifp, "p2p_disc", 1);
if (err < 0) {
brcmf_err("set p2p_disc error\n");
brcmf_cfg80211_arm_vif_event(p2p->cfg, NULL);
goto fail;
}
/* wait for firmware event */
err = brcmf_cfg80211_wait_vif_event_timeout(p2p->cfg, BRCMF_E_IF_ADD,
msecs_to_jiffies(1500));
brcmf_cfg80211_arm_vif_event(p2p->cfg, NULL);
if (!err) {
brcmf_err("timeout occurred\n");
err = -EIO;
goto fail;
}
/* discovery interface created */
p2p_ifp = p2p_vif->ifp;
p2p->bss_idx[P2PAPI_BSSCFG_DEVICE].vif = p2p_vif;
memcpy(p2p_ifp->mac_addr, p2p->dev_addr, ETH_ALEN);
memcpy(&p2p_vif->wdev.address, p2p->dev_addr, sizeof(p2p->dev_addr));
/* verify bsscfg index for P2P discovery */
err = brcmf_fil_iovar_int_get(pri_ifp, "p2p_dev", &bssidx);
if (err < 0) {
brcmf_err("retrieving discover bsscfg index failed\n");
goto fail;
}
WARN_ON(p2p_ifp->bssidx != bssidx);
init_completion(&p2p->send_af_done);
INIT_WORK(&p2p->afx_hdl.afx_work, brcmf_p2p_afx_handler);
init_completion(&p2p->afx_hdl.act_frm_scan);
init_completion(&p2p->wait_next_af);
return &p2p_vif->wdev;
fail:
brcmf_free_vif(p2p->cfg, p2p_vif);
return ERR_PTR(err);
}
/**
* brcmf_p2p_delete_p2pdev() - delete P2P_DEVICE virtual interface.
*
* @vif: virtual interface object to delete.
*/
static void brcmf_p2p_delete_p2pdev(struct brcmf_cfg80211_info *cfg,
struct brcmf_cfg80211_vif *vif)
{
cfg80211_unregister_wdev(&vif->wdev);
cfg->p2p.bss_idx[P2PAPI_BSSCFG_DEVICE].vif = NULL;
brcmf_free_vif(cfg, vif);
}
/**
* brcmf_p2p_free_p2p_if() - free up net device related data.
*
* @ndev: net device that needs to be freed.
*/
static void brcmf_p2p_free_p2p_if(struct net_device *ndev)
{
struct brcmf_cfg80211_info *cfg;
struct brcmf_cfg80211_vif *vif;
struct brcmf_if *ifp;
ifp = netdev_priv(ndev);
cfg = ifp->drvr->config;
vif = ifp->vif;
brcmf_free_vif(cfg, vif);
free_netdev(ifp->ndev);
}
/**
* brcmf_p2p_add_vif() - create a new P2P virtual interface.
*
* @wiphy: wiphy device of new interface.
* @name: name of the new interface.
* @type: nl80211 interface type.
* @flags: not used.
* @params: contains mac address for P2P device.
*/
struct wireless_dev *brcmf_p2p_add_vif(struct wiphy *wiphy, const char *name,
enum nl80211_iftype type, u32 *flags,
struct vif_params *params)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(cfg_to_ndev(cfg));
struct brcmf_cfg80211_vif *vif;
enum brcmf_fil_p2p_if_types iftype;
enum wl_mode mode;
int err;
if (brcmf_cfg80211_vif_event_armed(cfg))
return ERR_PTR(-EBUSY);
brcmf_dbg(INFO, "adding vif \"%s\" (type=%d)\n", name, type);
switch (type) {
case NL80211_IFTYPE_P2P_CLIENT:
iftype = BRCMF_FIL_P2P_IF_CLIENT;
mode = WL_MODE_BSS;
break;
case NL80211_IFTYPE_P2P_GO:
iftype = BRCMF_FIL_P2P_IF_GO;
mode = WL_MODE_AP;
break;
case NL80211_IFTYPE_P2P_DEVICE:
return brcmf_p2p_create_p2pdev(&cfg->p2p, wiphy,
params->macaddr);
default:
return ERR_PTR(-EOPNOTSUPP);
}
vif = brcmf_alloc_vif(cfg, type, false);
if (IS_ERR(vif))
return (struct wireless_dev *)vif;
brcmf_cfg80211_arm_vif_event(cfg, vif);
err = brcmf_p2p_request_p2p_if(&cfg->p2p, ifp, cfg->p2p.int_addr,
iftype);
if (err) {
brcmf_cfg80211_arm_vif_event(cfg, NULL);
goto fail;
}
/* wait for firmware event */
err = brcmf_cfg80211_wait_vif_event_timeout(cfg, BRCMF_E_IF_ADD,
msecs_to_jiffies(1500));
brcmf_cfg80211_arm_vif_event(cfg, NULL);
if (!err) {
brcmf_err("timeout occurred\n");
err = -EIO;
goto fail;
}
/* interface created in firmware */
ifp = vif->ifp;
if (!ifp) {
brcmf_err("no if pointer provided\n");
err = -ENOENT;
goto fail;
}
strncpy(ifp->ndev->name, name, sizeof(ifp->ndev->name) - 1);
err = brcmf_net_attach(ifp, true);
if (err) {
brcmf_err("Registering netdevice failed\n");
goto fail;
}
/* override destructor */
ifp->ndev->destructor = brcmf_p2p_free_p2p_if;
cfg->p2p.bss_idx[P2PAPI_BSSCFG_CONNECTION].vif = vif;
/* Disable firmware roaming for P2P interface */
brcmf_fil_iovar_int_set(ifp, "roam_off", 1);
if (iftype == BRCMF_FIL_P2P_IF_GO) {
/* set station timeout for p2p */
brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_SCB_TIMEOUT,
BRCMF_SCB_TIMEOUT_VALUE);
}
return &ifp->vif->wdev;
fail:
brcmf_free_vif(cfg, vif);
return ERR_PTR(err);
}
/**
* brcmf_p2p_del_vif() - delete a P2P virtual interface.
*
* @wiphy: wiphy device of interface.
* @wdev: wireless device of interface.
*
* TODO: not yet supported.
*/
int brcmf_p2p_del_vif(struct wiphy *wiphy, struct wireless_dev *wdev)
{
struct brcmf_cfg80211_info *cfg = wiphy_priv(wiphy);
struct brcmf_p2p_info *p2p = &cfg->p2p;
struct brcmf_cfg80211_vif *vif;
unsigned long jiffie_timeout = msecs_to_jiffies(1500);
bool wait_for_disable = false;
int err;
brcmf_dbg(TRACE, "delete P2P vif\n");
vif = container_of(wdev, struct brcmf_cfg80211_vif, wdev);
switch (vif->wdev.iftype) {
case NL80211_IFTYPE_P2P_CLIENT:
if (test_bit(BRCMF_VIF_STATUS_DISCONNECTING, &vif->sme_state))
wait_for_disable = true;
break;
case NL80211_IFTYPE_P2P_GO:
if (!brcmf_p2p_disable_p2p_if(vif))
wait_for_disable = true;
break;
case NL80211_IFTYPE_P2P_DEVICE:
brcmf_p2p_delete_p2pdev(cfg, vif);
return 0;
default:
return -ENOTSUPP;
break;
}
clear_bit(BRCMF_P2P_STATUS_GO_NEG_PHASE, &p2p->status);
brcmf_dbg(INFO, "P2P: GO_NEG_PHASE status cleared\n");
if (wait_for_disable)
wait_for_completion_timeout(&cfg->vif_disabled,
msecs_to_jiffies(500));
brcmf_vif_clear_mgmt_ies(vif);
brcmf_cfg80211_arm_vif_event(cfg, vif);
err = brcmf_p2p_release_p2p_if(vif);
if (!err) {
/* wait for firmware event */
err = brcmf_cfg80211_wait_vif_event_timeout(cfg, BRCMF_E_IF_DEL,
jiffie_timeout);
if (!err)
err = -EIO;
else
err = 0;
}
brcmf_cfg80211_arm_vif_event(cfg, NULL);
p2p->bss_idx[P2PAPI_BSSCFG_CONNECTION].vif = NULL;
return err;
}
int brcmf_p2p_start_device(struct wiphy *wiphy, struct wireless_dev *wdev)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_p2p_info *p2p = &cfg->p2p;
struct brcmf_cfg80211_vif *vif;
int err;
vif = container_of(wdev, struct brcmf_cfg80211_vif, wdev);
mutex_lock(&cfg->usr_sync);
err = brcmf_p2p_enable_discovery(p2p);
if (!err)
set_bit(BRCMF_VIF_STATUS_READY, &vif->sme_state);
mutex_unlock(&cfg->usr_sync);
return err;
}
void brcmf_p2p_stop_device(struct wiphy *wiphy, struct wireless_dev *wdev)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_p2p_info *p2p = &cfg->p2p;
struct brcmf_cfg80211_vif *vif;
vif = container_of(wdev, struct brcmf_cfg80211_vif, wdev);
mutex_lock(&cfg->usr_sync);
(void)brcmf_p2p_deinit_discovery(p2p);
brcmf_abort_scanning(cfg);
clear_bit(BRCMF_VIF_STATUS_READY, &vif->sme_state);
mutex_unlock(&cfg->usr_sync);
}
| gpl-2.0 |
kyapa/linux-3.0.y | arch/arm/mach-exynos4/dev-sysmmu.c | 2400 | 5250 | /* linux/arch/arm/mach-exynos4/dev-sysmmu.c
*
* Copyright (c) 2010 Samsung Electronics Co., Ltd.
* http://www.samsung.com
*
* EXYNOS4 - System MMU 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/platform_device.h>
#include <linux/dma-mapping.h>
#include <mach/map.h>
#include <mach/irqs.h>
#include <mach/sysmmu.h>
#include <plat/s5p-clock.h>
/* These names must be equal to the clock names in mach-exynos4/clock.c */
const char *sysmmu_ips_name[EXYNOS4_SYSMMU_TOTAL_IPNUM] = {
"SYSMMU_MDMA" ,
"SYSMMU_SSS" ,
"SYSMMU_FIMC0" ,
"SYSMMU_FIMC1" ,
"SYSMMU_FIMC2" ,
"SYSMMU_FIMC3" ,
"SYSMMU_JPEG" ,
"SYSMMU_FIMD0" ,
"SYSMMU_FIMD1" ,
"SYSMMU_PCIe" ,
"SYSMMU_G2D" ,
"SYSMMU_ROTATOR",
"SYSMMU_MDMA2" ,
"SYSMMU_TV" ,
"SYSMMU_MFC_L" ,
"SYSMMU_MFC_R" ,
};
static struct resource exynos4_sysmmu_resource[] = {
[0] = {
.start = EXYNOS4_PA_SYSMMU_MDMA,
.end = EXYNOS4_PA_SYSMMU_MDMA + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_SYSMMU_MDMA0_0,
.end = IRQ_SYSMMU_MDMA0_0,
.flags = IORESOURCE_IRQ,
},
[2] = {
.start = EXYNOS4_PA_SYSMMU_SSS,
.end = EXYNOS4_PA_SYSMMU_SSS + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[3] = {
.start = IRQ_SYSMMU_SSS_0,
.end = IRQ_SYSMMU_SSS_0,
.flags = IORESOURCE_IRQ,
},
[4] = {
.start = EXYNOS4_PA_SYSMMU_FIMC0,
.end = EXYNOS4_PA_SYSMMU_FIMC0 + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[5] = {
.start = IRQ_SYSMMU_FIMC0_0,
.end = IRQ_SYSMMU_FIMC0_0,
.flags = IORESOURCE_IRQ,
},
[6] = {
.start = EXYNOS4_PA_SYSMMU_FIMC1,
.end = EXYNOS4_PA_SYSMMU_FIMC1 + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[7] = {
.start = IRQ_SYSMMU_FIMC1_0,
.end = IRQ_SYSMMU_FIMC1_0,
.flags = IORESOURCE_IRQ,
},
[8] = {
.start = EXYNOS4_PA_SYSMMU_FIMC2,
.end = EXYNOS4_PA_SYSMMU_FIMC2 + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[9] = {
.start = IRQ_SYSMMU_FIMC2_0,
.end = IRQ_SYSMMU_FIMC2_0,
.flags = IORESOURCE_IRQ,
},
[10] = {
.start = EXYNOS4_PA_SYSMMU_FIMC3,
.end = EXYNOS4_PA_SYSMMU_FIMC3 + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[11] = {
.start = IRQ_SYSMMU_FIMC3_0,
.end = IRQ_SYSMMU_FIMC3_0,
.flags = IORESOURCE_IRQ,
},
[12] = {
.start = EXYNOS4_PA_SYSMMU_JPEG,
.end = EXYNOS4_PA_SYSMMU_JPEG + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[13] = {
.start = IRQ_SYSMMU_JPEG_0,
.end = IRQ_SYSMMU_JPEG_0,
.flags = IORESOURCE_IRQ,
},
[14] = {
.start = EXYNOS4_PA_SYSMMU_FIMD0,
.end = EXYNOS4_PA_SYSMMU_FIMD0 + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[15] = {
.start = IRQ_SYSMMU_LCD0_M0_0,
.end = IRQ_SYSMMU_LCD0_M0_0,
.flags = IORESOURCE_IRQ,
},
[16] = {
.start = EXYNOS4_PA_SYSMMU_FIMD1,
.end = EXYNOS4_PA_SYSMMU_FIMD1 + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[17] = {
.start = IRQ_SYSMMU_LCD1_M1_0,
.end = IRQ_SYSMMU_LCD1_M1_0,
.flags = IORESOURCE_IRQ,
},
[18] = {
.start = EXYNOS4_PA_SYSMMU_PCIe,
.end = EXYNOS4_PA_SYSMMU_PCIe + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[19] = {
.start = IRQ_SYSMMU_PCIE_0,
.end = IRQ_SYSMMU_PCIE_0,
.flags = IORESOURCE_IRQ,
},
[20] = {
.start = EXYNOS4_PA_SYSMMU_G2D,
.end = EXYNOS4_PA_SYSMMU_G2D + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[21] = {
.start = IRQ_SYSMMU_2D_0,
.end = IRQ_SYSMMU_2D_0,
.flags = IORESOURCE_IRQ,
},
[22] = {
.start = EXYNOS4_PA_SYSMMU_ROTATOR,
.end = EXYNOS4_PA_SYSMMU_ROTATOR + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[23] = {
.start = IRQ_SYSMMU_ROTATOR_0,
.end = IRQ_SYSMMU_ROTATOR_0,
.flags = IORESOURCE_IRQ,
},
[24] = {
.start = EXYNOS4_PA_SYSMMU_MDMA2,
.end = EXYNOS4_PA_SYSMMU_MDMA2 + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[25] = {
.start = IRQ_SYSMMU_MDMA1_0,
.end = IRQ_SYSMMU_MDMA1_0,
.flags = IORESOURCE_IRQ,
},
[26] = {
.start = EXYNOS4_PA_SYSMMU_TV,
.end = EXYNOS4_PA_SYSMMU_TV + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[27] = {
.start = IRQ_SYSMMU_TV_M0_0,
.end = IRQ_SYSMMU_TV_M0_0,
.flags = IORESOURCE_IRQ,
},
[28] = {
.start = EXYNOS4_PA_SYSMMU_MFC_L,
.end = EXYNOS4_PA_SYSMMU_MFC_L + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[29] = {
.start = IRQ_SYSMMU_MFC_M0_0,
.end = IRQ_SYSMMU_MFC_M0_0,
.flags = IORESOURCE_IRQ,
},
[30] = {
.start = EXYNOS4_PA_SYSMMU_MFC_R,
.end = EXYNOS4_PA_SYSMMU_MFC_R + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[31] = {
.start = IRQ_SYSMMU_MFC_M1_0,
.end = IRQ_SYSMMU_MFC_M1_0,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device exynos4_device_sysmmu = {
.name = "s5p-sysmmu",
.id = 32,
.num_resources = ARRAY_SIZE(exynos4_sysmmu_resource),
.resource = exynos4_sysmmu_resource,
};
EXPORT_SYMBOL(exynos4_device_sysmmu);
static struct clk *sysmmu_clk[S5P_SYSMMU_TOTAL_IPNUM];
void sysmmu_clk_init(struct device *dev, sysmmu_ips ips)
{
sysmmu_clk[ips] = clk_get(dev, sysmmu_ips_name[ips]);
if (IS_ERR(sysmmu_clk[ips]))
sysmmu_clk[ips] = NULL;
else
clk_put(sysmmu_clk[ips]);
}
void sysmmu_clk_enable(sysmmu_ips ips)
{
if (sysmmu_clk[ips])
clk_enable(sysmmu_clk[ips]);
}
void sysmmu_clk_disable(sysmmu_ips ips)
{
if (sysmmu_clk[ips])
clk_disable(sysmmu_clk[ips]);
}
| gpl-2.0 |
SimonSickle/android_kernel_htc_primou | drivers/gpu/drm/drm_ioctl.c | 2656 | 8710 | /**
* \file drm_ioctl.c
* IOCTL processing for DRM
*
* \author Rickard E. (Rik) Faith <faith@valinux.com>
* \author Gareth Hughes <gareth@valinux.com>
*/
/*
* Created: Fri Jan 8 09:01:26 1999 by faith@valinux.com
*
* Copyright 1999 Precision Insight, Inc., Cedar Park, Texas.
* Copyright 2000 VA Linux Systems, Inc., Sunnyvale, California.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* VA LINUX SYSTEMS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "drmP.h"
#include "drm_core.h"
#include "linux/pci.h"
/**
* Get the bus id.
*
* \param inode device inode.
* \param file_priv DRM file private.
* \param cmd command.
* \param arg user argument, pointing to a drm_unique structure.
* \return zero on success or a negative number on failure.
*
* Copies the bus id from drm_device::unique into user space.
*/
int drm_getunique(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_unique *u = data;
struct drm_master *master = file_priv->master;
if (u->unique_len >= master->unique_len) {
if (copy_to_user(u->unique, master->unique, master->unique_len))
return -EFAULT;
}
u->unique_len = master->unique_len;
return 0;
}
static void
drm_unset_busid(struct drm_device *dev,
struct drm_master *master)
{
kfree(dev->devname);
dev->devname = NULL;
kfree(master->unique);
master->unique = NULL;
master->unique_len = 0;
master->unique_size = 0;
}
/**
* Set the bus id.
*
* \param inode device inode.
* \param file_priv DRM file private.
* \param cmd command.
* \param arg user argument, pointing to a drm_unique structure.
* \return zero on success or a negative number on failure.
*
* Copies the bus id from userspace into drm_device::unique, and verifies that
* it matches the device this DRM is attached to (EINVAL otherwise). Deprecated
* in interface version 1.1 and will return EBUSY when setversion has requested
* version 1.1 or greater.
*/
int drm_setunique(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_unique *u = data;
struct drm_master *master = file_priv->master;
int ret;
if (master->unique_len || master->unique)
return -EBUSY;
if (!u->unique_len || u->unique_len > 1024)
return -EINVAL;
if (!dev->driver->bus->set_unique)
return -EINVAL;
ret = dev->driver->bus->set_unique(dev, master, u);
if (ret)
goto err;
return 0;
err:
drm_unset_busid(dev, master);
return ret;
}
static int drm_set_busid(struct drm_device *dev, struct drm_file *file_priv)
{
struct drm_master *master = file_priv->master;
int ret;
if (master->unique != NULL)
drm_unset_busid(dev, master);
ret = dev->driver->bus->set_busid(dev, master);
if (ret)
goto err;
return 0;
err:
drm_unset_busid(dev, master);
return ret;
}
/**
* Get a mapping information.
*
* \param inode device inode.
* \param file_priv DRM file private.
* \param cmd command.
* \param arg user argument, pointing to a drm_map structure.
*
* \return zero on success or a negative number on failure.
*
* Searches for the mapping with the specified offset and copies its information
* into userspace
*/
int drm_getmap(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_map *map = data;
struct drm_map_list *r_list = NULL;
struct list_head *list;
int idx;
int i;
idx = map->offset;
mutex_lock(&dev->struct_mutex);
if (idx < 0) {
mutex_unlock(&dev->struct_mutex);
return -EINVAL;
}
i = 0;
list_for_each(list, &dev->maplist) {
if (i == idx) {
r_list = list_entry(list, struct drm_map_list, head);
break;
}
i++;
}
if (!r_list || !r_list->map) {
mutex_unlock(&dev->struct_mutex);
return -EINVAL;
}
map->offset = r_list->map->offset;
map->size = r_list->map->size;
map->type = r_list->map->type;
map->flags = r_list->map->flags;
map->handle = (void *)(unsigned long) r_list->user_token;
map->mtrr = r_list->map->mtrr;
mutex_unlock(&dev->struct_mutex);
return 0;
}
/**
* Get client information.
*
* \param inode device inode.
* \param file_priv DRM file private.
* \param cmd command.
* \param arg user argument, pointing to a drm_client structure.
*
* \return zero on success or a negative number on failure.
*
* Searches for the client with the specified index and copies its information
* into userspace
*/
int drm_getclient(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_client *client = data;
struct drm_file *pt;
int idx;
int i;
idx = client->idx;
mutex_lock(&dev->struct_mutex);
i = 0;
list_for_each_entry(pt, &dev->filelist, lhead) {
if (i++ >= idx) {
client->auth = pt->authenticated;
client->pid = pt->pid;
client->uid = pt->uid;
client->magic = pt->magic;
client->iocs = pt->ioctl_count;
mutex_unlock(&dev->struct_mutex);
return 0;
}
}
mutex_unlock(&dev->struct_mutex);
return -EINVAL;
}
/**
* Get statistics information.
*
* \param inode device inode.
* \param file_priv DRM file private.
* \param cmd command.
* \param arg user argument, pointing to a drm_stats structure.
*
* \return zero on success or a negative number on failure.
*/
int drm_getstats(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
struct drm_stats *stats = data;
int i;
memset(stats, 0, sizeof(*stats));
mutex_lock(&dev->struct_mutex);
for (i = 0; i < dev->counters; i++) {
if (dev->types[i] == _DRM_STAT_LOCK)
stats->data[i].value =
(file_priv->master->lock.hw_lock ? file_priv->master->lock.hw_lock->lock : 0);
else
stats->data[i].value = atomic_read(&dev->counts[i]);
stats->data[i].type = dev->types[i];
}
stats->count = dev->counters;
mutex_unlock(&dev->struct_mutex);
return 0;
}
/**
* Get device/driver capabilities
*/
int drm_getcap(struct drm_device *dev, void *data, struct drm_file *file_priv)
{
struct drm_get_cap *req = data;
req->value = 0;
switch (req->capability) {
case DRM_CAP_DUMB_BUFFER:
if (dev->driver->dumb_create)
req->value = 1;
break;
case DRM_CAP_VBLANK_HIGH_CRTC:
req->value = 1;
break;
default:
return -EINVAL;
}
return 0;
}
/**
* Setversion ioctl.
*
* \param inode device inode.
* \param file_priv DRM file private.
* \param cmd command.
* \param arg user argument, pointing to a drm_lock structure.
* \return zero on success or negative number on failure.
*
* Sets the requested interface version
*/
int drm_setversion(struct drm_device *dev, void *data, struct drm_file *file_priv)
{
struct drm_set_version *sv = data;
int if_version, retcode = 0;
if (sv->drm_di_major != -1) {
if (sv->drm_di_major != DRM_IF_MAJOR ||
sv->drm_di_minor < 0 || sv->drm_di_minor > DRM_IF_MINOR) {
retcode = -EINVAL;
goto done;
}
if_version = DRM_IF_VERSION(sv->drm_di_major,
sv->drm_di_minor);
dev->if_version = max(if_version, dev->if_version);
if (sv->drm_di_minor >= 1) {
/*
* Version 1.1 includes tying of DRM to specific device
* Version 1.4 has proper PCI domain support
*/
retcode = drm_set_busid(dev, file_priv);
if (retcode)
goto done;
}
}
if (sv->drm_dd_major != -1) {
if (sv->drm_dd_major != dev->driver->major ||
sv->drm_dd_minor < 0 || sv->drm_dd_minor >
dev->driver->minor) {
retcode = -EINVAL;
goto done;
}
if (dev->driver->set_version)
dev->driver->set_version(dev, sv);
}
done:
sv->drm_di_major = DRM_IF_MAJOR;
sv->drm_di_minor = DRM_IF_MINOR;
sv->drm_dd_major = dev->driver->major;
sv->drm_dd_minor = dev->driver->minor;
return retcode;
}
/** No-op ioctl. */
int drm_noop(struct drm_device *dev, void *data,
struct drm_file *file_priv)
{
DRM_DEBUG("\n");
return 0;
}
| gpl-2.0 |
manuels/pdftex.js | src/libs/libpng/libpng-1.2.40/pngwtran.c | 97 | 17347 |
/* pngwtran.c - transforms the data in a row for PNG writers
*
* Last changed in libpng 1.2.37 [June 4, 2009]
* Copyright (c) 1998-2009 Glenn Randers-Pehrson
* (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
* (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
*
* This code is released under the libpng license.
* For conditions of distribution and use, see the disclaimer
* and license in png.h
*/
#define PNG_INTERNAL
#include "png.h"
#ifdef PNG_WRITE_SUPPORTED
/* Transform the data according to the user's wishes. The order of
* transformations is significant.
*/
void /* PRIVATE */
png_do_write_transformations(png_structp png_ptr)
{
png_debug(1, "in png_do_write_transformations");
if (png_ptr == NULL)
return;
#if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
if (png_ptr->transformations & PNG_USER_TRANSFORM)
if (png_ptr->write_user_transform_fn != NULL)
(*(png_ptr->write_user_transform_fn)) /* User write transform function */
(png_ptr, /* png_ptr */
&(png_ptr->row_info), /* row_info: */
/* png_uint_32 width; width of row */
/* png_uint_32 rowbytes; number of bytes in row */
/* png_byte color_type; color type of pixels */
/* png_byte bit_depth; bit depth of samples */
/* png_byte channels; number of channels (1-4) */
/* png_byte pixel_depth; bits per pixel (depth*channels) */
png_ptr->row_buf + 1); /* start of pixel data for row */
#endif
#if defined(PNG_WRITE_FILLER_SUPPORTED)
if (png_ptr->transformations & PNG_FILLER)
png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
png_ptr->flags);
#endif
#if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
if (png_ptr->transformations & PNG_PACKSWAP)
png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
#endif
#if defined(PNG_WRITE_PACK_SUPPORTED)
if (png_ptr->transformations & PNG_PACK)
png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
(png_uint_32)png_ptr->bit_depth);
#endif
#if defined(PNG_WRITE_SWAP_SUPPORTED)
if (png_ptr->transformations & PNG_SWAP_BYTES)
png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
#endif
#if defined(PNG_WRITE_SHIFT_SUPPORTED)
if (png_ptr->transformations & PNG_SHIFT)
png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
&(png_ptr->shift));
#endif
#if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
if (png_ptr->transformations & PNG_SWAP_ALPHA)
png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
#endif
#if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
if (png_ptr->transformations & PNG_INVERT_ALPHA)
png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
#endif
#if defined(PNG_WRITE_BGR_SUPPORTED)
if (png_ptr->transformations & PNG_BGR)
png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
#endif
#if defined(PNG_WRITE_INVERT_SUPPORTED)
if (png_ptr->transformations & PNG_INVERT_MONO)
png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
#endif
}
#if defined(PNG_WRITE_PACK_SUPPORTED)
/* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
* row_info bit depth should be 8 (one pixel per byte). The channels
* should be 1 (this only happens on grayscale and paletted images).
*/
void /* PRIVATE */
png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
{
png_debug(1, "in png_do_pack");
if (row_info->bit_depth == 8 &&
#if defined(PNG_USELESS_TESTS_SUPPORTED)
row != NULL && row_info != NULL &&
#endif
row_info->channels == 1)
{
switch ((int)bit_depth)
{
case 1:
{
png_bytep sp, dp;
int mask, v;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
sp = row;
dp = row;
mask = 0x80;
v = 0;
for (i = 0; i < row_width; i++)
{
if (*sp != 0)
v |= mask;
sp++;
if (mask > 1)
mask >>= 1;
else
{
mask = 0x80;
*dp = (png_byte)v;
dp++;
v = 0;
}
}
if (mask != 0x80)
*dp = (png_byte)v;
break;
}
case 2:
{
png_bytep sp, dp;
int shift, v;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
sp = row;
dp = row;
shift = 6;
v = 0;
for (i = 0; i < row_width; i++)
{
png_byte value;
value = (png_byte)(*sp & 0x03);
v |= (value << shift);
if (shift == 0)
{
shift = 6;
*dp = (png_byte)v;
dp++;
v = 0;
}
else
shift -= 2;
sp++;
}
if (shift != 6)
*dp = (png_byte)v;
break;
}
case 4:
{
png_bytep sp, dp;
int shift, v;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
sp = row;
dp = row;
shift = 4;
v = 0;
for (i = 0; i < row_width; i++)
{
png_byte value;
value = (png_byte)(*sp & 0x0f);
v |= (value << shift);
if (shift == 0)
{
shift = 4;
*dp = (png_byte)v;
dp++;
v = 0;
}
else
shift -= 4;
sp++;
}
if (shift != 4)
*dp = (png_byte)v;
break;
}
}
row_info->bit_depth = (png_byte)bit_depth;
row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
row_info->width);
}
}
#endif
#if defined(PNG_WRITE_SHIFT_SUPPORTED)
/* Shift pixel values to take advantage of whole range. Pass the
* true number of bits in bit_depth. The row should be packed
* according to row_info->bit_depth. Thus, if you had a row of
* bit depth 4, but the pixels only had values from 0 to 7, you
* would pass 3 as bit_depth, and this routine would translate the
* data to 0 to 15.
*/
void /* PRIVATE */
png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
{
png_debug(1, "in png_do_shift");
#if defined(PNG_USELESS_TESTS_SUPPORTED)
if (row != NULL && row_info != NULL &&
#else
if (
#endif
row_info->color_type != PNG_COLOR_TYPE_PALETTE)
{
int shift_start[4], shift_dec[4];
int channels = 0;
if (row_info->color_type & PNG_COLOR_MASK_COLOR)
{
shift_start[channels] = row_info->bit_depth - bit_depth->red;
shift_dec[channels] = bit_depth->red;
channels++;
shift_start[channels] = row_info->bit_depth - bit_depth->green;
shift_dec[channels] = bit_depth->green;
channels++;
shift_start[channels] = row_info->bit_depth - bit_depth->blue;
shift_dec[channels] = bit_depth->blue;
channels++;
}
else
{
shift_start[channels] = row_info->bit_depth - bit_depth->gray;
shift_dec[channels] = bit_depth->gray;
channels++;
}
if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
{
shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
shift_dec[channels] = bit_depth->alpha;
channels++;
}
/* With low row depths, could only be grayscale, so one channel */
if (row_info->bit_depth < 8)
{
png_bytep bp = row;
png_uint_32 i;
png_byte mask;
png_uint_32 row_bytes = row_info->rowbytes;
if (bit_depth->gray == 1 && row_info->bit_depth == 2)
mask = 0x55;
else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
mask = 0x11;
else
mask = 0xff;
for (i = 0; i < row_bytes; i++, bp++)
{
png_uint_16 v;
int j;
v = *bp;
*bp = 0;
for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
{
if (j > 0)
*bp |= (png_byte)((v << j) & 0xff);
else
*bp |= (png_byte)((v >> (-j)) & mask);
}
}
}
else if (row_info->bit_depth == 8)
{
png_bytep bp = row;
png_uint_32 i;
png_uint_32 istop = channels * row_info->width;
for (i = 0; i < istop; i++, bp++)
{
png_uint_16 v;
int j;
int c = (int)(i%channels);
v = *bp;
*bp = 0;
for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
{
if (j > 0)
*bp |= (png_byte)((v << j) & 0xff);
else
*bp |= (png_byte)((v >> (-j)) & 0xff);
}
}
}
else
{
png_bytep bp;
png_uint_32 i;
png_uint_32 istop = channels * row_info->width;
for (bp = row, i = 0; i < istop; i++)
{
int c = (int)(i%channels);
png_uint_16 value, v;
int j;
v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
value = 0;
for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
{
if (j > 0)
value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
else
value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
}
*bp++ = (png_byte)(value >> 8);
*bp++ = (png_byte)(value & 0xff);
}
}
}
}
#endif
#if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
void /* PRIVATE */
png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
{
png_debug(1, "in png_do_write_swap_alpha");
#if defined(PNG_USELESS_TESTS_SUPPORTED)
if (row != NULL && row_info != NULL)
#endif
{
if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
{
/* This converts from ARGB to RGBA */
if (row_info->bit_depth == 8)
{
png_bytep sp, dp;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
for (i = 0, sp = dp = row; i < row_width; i++)
{
png_byte save = *(sp++);
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*(dp++) = save;
}
}
/* This converts from AARRGGBB to RRGGBBAA */
else
{
png_bytep sp, dp;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
for (i = 0, sp = dp = row; i < row_width; i++)
{
png_byte save[2];
save[0] = *(sp++);
save[1] = *(sp++);
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*(dp++) = save[0];
*(dp++) = save[1];
}
}
}
else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
{
/* This converts from AG to GA */
if (row_info->bit_depth == 8)
{
png_bytep sp, dp;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
for (i = 0, sp = dp = row; i < row_width; i++)
{
png_byte save = *(sp++);
*(dp++) = *(sp++);
*(dp++) = save;
}
}
/* This converts from AAGG to GGAA */
else
{
png_bytep sp, dp;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
for (i = 0, sp = dp = row; i < row_width; i++)
{
png_byte save[2];
save[0] = *(sp++);
save[1] = *(sp++);
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*(dp++) = save[0];
*(dp++) = save[1];
}
}
}
}
}
#endif
#if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
void /* PRIVATE */
png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
{
png_debug(1, "in png_do_write_invert_alpha");
#if defined(PNG_USELESS_TESTS_SUPPORTED)
if (row != NULL && row_info != NULL)
#endif
{
if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
{
/* This inverts the alpha channel in RGBA */
if (row_info->bit_depth == 8)
{
png_bytep sp, dp;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
for (i = 0, sp = dp = row; i < row_width; i++)
{
/* Does nothing
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*/
sp+=3; dp = sp;
*(dp++) = (png_byte)(255 - *(sp++));
}
}
/* This inverts the alpha channel in RRGGBBAA */
else
{
png_bytep sp, dp;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
for (i = 0, sp = dp = row; i < row_width; i++)
{
/* Does nothing
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*/
sp+=6; dp = sp;
*(dp++) = (png_byte)(255 - *(sp++));
*(dp++) = (png_byte)(255 - *(sp++));
}
}
}
else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
{
/* This inverts the alpha channel in GA */
if (row_info->bit_depth == 8)
{
png_bytep sp, dp;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
for (i = 0, sp = dp = row; i < row_width; i++)
{
*(dp++) = *(sp++);
*(dp++) = (png_byte)(255 - *(sp++));
}
}
/* This inverts the alpha channel in GGAA */
else
{
png_bytep sp, dp;
png_uint_32 i;
png_uint_32 row_width = row_info->width;
for (i = 0, sp = dp = row; i < row_width; i++)
{
/* Does nothing
*(dp++) = *(sp++);
*(dp++) = *(sp++);
*/
sp+=2; dp = sp;
*(dp++) = (png_byte)(255 - *(sp++));
*(dp++) = (png_byte)(255 - *(sp++));
}
}
}
}
}
#endif
#if defined(PNG_MNG_FEATURES_SUPPORTED)
/* Undoes intrapixel differencing */
void /* PRIVATE */
png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
{
png_debug(1, "in png_do_write_intrapixel");
if (
#if defined(PNG_USELESS_TESTS_SUPPORTED)
row != NULL && row_info != NULL &&
#endif
(row_info->color_type & PNG_COLOR_MASK_COLOR))
{
int bytes_per_pixel;
png_uint_32 row_width = row_info->width;
if (row_info->bit_depth == 8)
{
png_bytep rp;
png_uint_32 i;
if (row_info->color_type == PNG_COLOR_TYPE_RGB)
bytes_per_pixel = 3;
else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
bytes_per_pixel = 4;
else
return;
for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
{
*(rp) = (png_byte)((*rp - *(rp+1))&0xff);
*(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
}
}
else if (row_info->bit_depth == 16)
{
png_bytep rp;
png_uint_32 i;
if (row_info->color_type == PNG_COLOR_TYPE_RGB)
bytes_per_pixel = 6;
else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
bytes_per_pixel = 8;
else
return;
for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
{
png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
png_uint_32 red = (png_uint_32)((s0 - s1) & 0xffffL);
png_uint_32 blue = (png_uint_32)((s2 - s1) & 0xffffL);
*(rp ) = (png_byte)((red >> 8) & 0xff);
*(rp+1) = (png_byte)(red & 0xff);
*(rp+4) = (png_byte)((blue >> 8) & 0xff);
*(rp+5) = (png_byte)(blue & 0xff);
}
}
}
}
#endif /* PNG_MNG_FEATURES_SUPPORTED */
#endif /* PNG_WRITE_SUPPORTED */
| gpl-2.0 |
piercexue/linux-3.10-ltsi | drivers/video/backlight/lp8788_bl.c | 353 | 7941 | /*
* TI LP8788 MFD - backlight driver
*
* Copyright 2012 Texas Instruments
*
* Author: Milo(Woogyom) Kim <milo.kim@ti.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/backlight.h>
#include <linux/err.h>
#include <linux/mfd/lp8788.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/pwm.h>
#include <linux/slab.h>
/* Register address */
#define LP8788_BL_CONFIG 0x96
#define LP8788_BL_EN BIT(0)
#define LP8788_BL_PWM_INPUT_EN BIT(5)
#define LP8788_BL_FULLSCALE_SHIFT 2
#define LP8788_BL_DIM_MODE_SHIFT 1
#define LP8788_BL_PWM_POLARITY_SHIFT 6
#define LP8788_BL_BRIGHTNESS 0x97
#define LP8788_BL_RAMP 0x98
#define LP8788_BL_RAMP_RISE_SHIFT 4
#define MAX_BRIGHTNESS 127
#define DEFAULT_BL_NAME "lcd-backlight"
struct lp8788_bl_config {
enum lp8788_bl_ctrl_mode bl_mode;
enum lp8788_bl_dim_mode dim_mode;
enum lp8788_bl_full_scale_current full_scale;
enum lp8788_bl_ramp_step rise_time;
enum lp8788_bl_ramp_step fall_time;
enum pwm_polarity pwm_pol;
};
struct lp8788_bl {
struct lp8788 *lp;
struct backlight_device *bl_dev;
struct lp8788_backlight_platform_data *pdata;
enum lp8788_bl_ctrl_mode mode;
struct pwm_device *pwm;
};
static struct lp8788_bl_config default_bl_config = {
.bl_mode = LP8788_BL_REGISTER_ONLY,
.dim_mode = LP8788_DIM_EXPONENTIAL,
.full_scale = LP8788_FULLSCALE_1900uA,
.rise_time = LP8788_RAMP_8192us,
.fall_time = LP8788_RAMP_8192us,
.pwm_pol = PWM_POLARITY_NORMAL,
};
static inline bool is_brightness_ctrl_by_pwm(enum lp8788_bl_ctrl_mode mode)
{
return mode == LP8788_BL_COMB_PWM_BASED;
}
static inline bool is_brightness_ctrl_by_register(enum lp8788_bl_ctrl_mode mode)
{
return mode == LP8788_BL_REGISTER_ONLY ||
mode == LP8788_BL_COMB_REGISTER_BASED;
}
static int lp8788_backlight_configure(struct lp8788_bl *bl)
{
struct lp8788_backlight_platform_data *pdata = bl->pdata;
struct lp8788_bl_config *cfg = &default_bl_config;
int ret;
u8 val;
/*
* Update chip configuration if platform data exists,
* otherwise use the default settings.
*/
if (pdata) {
cfg->bl_mode = pdata->bl_mode;
cfg->dim_mode = pdata->dim_mode;
cfg->full_scale = pdata->full_scale;
cfg->rise_time = pdata->rise_time;
cfg->fall_time = pdata->fall_time;
cfg->pwm_pol = pdata->pwm_pol;
}
/* Brightness ramp up/down */
val = (cfg->rise_time << LP8788_BL_RAMP_RISE_SHIFT) | cfg->fall_time;
ret = lp8788_write_byte(bl->lp, LP8788_BL_RAMP, val);
if (ret)
return ret;
/* Fullscale current setting */
val = (cfg->full_scale << LP8788_BL_FULLSCALE_SHIFT) |
(cfg->dim_mode << LP8788_BL_DIM_MODE_SHIFT);
/* Brightness control mode */
switch (cfg->bl_mode) {
case LP8788_BL_REGISTER_ONLY:
val |= LP8788_BL_EN;
break;
case LP8788_BL_COMB_PWM_BASED:
case LP8788_BL_COMB_REGISTER_BASED:
val |= LP8788_BL_EN | LP8788_BL_PWM_INPUT_EN |
(cfg->pwm_pol << LP8788_BL_PWM_POLARITY_SHIFT);
break;
default:
dev_err(bl->lp->dev, "invalid mode: %d\n", cfg->bl_mode);
return -EINVAL;
}
bl->mode = cfg->bl_mode;
return lp8788_write_byte(bl->lp, LP8788_BL_CONFIG, val);
}
static void lp8788_pwm_ctrl(struct lp8788_bl *bl, int br, int max_br)
{
unsigned int period;
unsigned int duty;
struct device *dev;
struct pwm_device *pwm;
if (!bl->pdata)
return;
period = bl->pdata->period_ns;
duty = br * period / max_br;
dev = bl->lp->dev;
/* request PWM device with the consumer name */
if (!bl->pwm) {
pwm = devm_pwm_get(dev, LP8788_DEV_BACKLIGHT);
if (IS_ERR(pwm)) {
dev_err(dev, "can not get PWM device\n");
return;
}
bl->pwm = pwm;
}
pwm_config(bl->pwm, duty, period);
if (duty)
pwm_enable(bl->pwm);
else
pwm_disable(bl->pwm);
}
static int lp8788_bl_update_status(struct backlight_device *bl_dev)
{
struct lp8788_bl *bl = bl_get_data(bl_dev);
enum lp8788_bl_ctrl_mode mode = bl->mode;
if (bl_dev->props.state & BL_CORE_SUSPENDED)
bl_dev->props.brightness = 0;
if (is_brightness_ctrl_by_pwm(mode)) {
int brt = bl_dev->props.brightness;
int max = bl_dev->props.max_brightness;
lp8788_pwm_ctrl(bl, brt, max);
} else if (is_brightness_ctrl_by_register(mode)) {
u8 brt = bl_dev->props.brightness;
lp8788_write_byte(bl->lp, LP8788_BL_BRIGHTNESS, brt);
}
return 0;
}
static int lp8788_bl_get_brightness(struct backlight_device *bl_dev)
{
return bl_dev->props.brightness;
}
static const struct backlight_ops lp8788_bl_ops = {
.options = BL_CORE_SUSPENDRESUME,
.update_status = lp8788_bl_update_status,
.get_brightness = lp8788_bl_get_brightness,
};
static int lp8788_backlight_register(struct lp8788_bl *bl)
{
struct backlight_device *bl_dev;
struct backlight_properties props;
struct lp8788_backlight_platform_data *pdata = bl->pdata;
int init_brt;
char *name;
props.type = BACKLIGHT_PLATFORM;
props.max_brightness = MAX_BRIGHTNESS;
/* Initial brightness */
if (pdata)
init_brt = min_t(int, pdata->initial_brightness,
props.max_brightness);
else
init_brt = 0;
props.brightness = init_brt;
/* Backlight device name */
if (!pdata || !pdata->name)
name = DEFAULT_BL_NAME;
else
name = pdata->name;
bl_dev = backlight_device_register(name, bl->lp->dev, bl,
&lp8788_bl_ops, &props);
if (IS_ERR(bl_dev))
return PTR_ERR(bl_dev);
bl->bl_dev = bl_dev;
return 0;
}
static void lp8788_backlight_unregister(struct lp8788_bl *bl)
{
struct backlight_device *bl_dev = bl->bl_dev;
if (bl_dev)
backlight_device_unregister(bl_dev);
}
static ssize_t lp8788_get_bl_ctl_mode(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct lp8788_bl *bl = dev_get_drvdata(dev);
enum lp8788_bl_ctrl_mode mode = bl->mode;
char *strmode;
if (is_brightness_ctrl_by_pwm(mode))
strmode = "PWM based";
else if (is_brightness_ctrl_by_register(mode))
strmode = "Register based";
else
strmode = "Invalid mode";
return scnprintf(buf, PAGE_SIZE, "%s\n", strmode);
}
static DEVICE_ATTR(bl_ctl_mode, S_IRUGO, lp8788_get_bl_ctl_mode, NULL);
static struct attribute *lp8788_attributes[] = {
&dev_attr_bl_ctl_mode.attr,
NULL,
};
static const struct attribute_group lp8788_attr_group = {
.attrs = lp8788_attributes,
};
static int lp8788_backlight_probe(struct platform_device *pdev)
{
struct lp8788 *lp = dev_get_drvdata(pdev->dev.parent);
struct lp8788_bl *bl;
int ret;
bl = devm_kzalloc(lp->dev, sizeof(struct lp8788_bl), GFP_KERNEL);
if (!bl)
return -ENOMEM;
bl->lp = lp;
if (lp->pdata)
bl->pdata = lp->pdata->bl_pdata;
platform_set_drvdata(pdev, bl);
ret = lp8788_backlight_configure(bl);
if (ret) {
dev_err(lp->dev, "backlight config err: %d\n", ret);
goto err_dev;
}
ret = lp8788_backlight_register(bl);
if (ret) {
dev_err(lp->dev, "register backlight err: %d\n", ret);
goto err_dev;
}
ret = sysfs_create_group(&pdev->dev.kobj, &lp8788_attr_group);
if (ret) {
dev_err(lp->dev, "register sysfs err: %d\n", ret);
goto err_sysfs;
}
backlight_update_status(bl->bl_dev);
return 0;
err_sysfs:
lp8788_backlight_unregister(bl);
err_dev:
return ret;
}
static int lp8788_backlight_remove(struct platform_device *pdev)
{
struct lp8788_bl *bl = platform_get_drvdata(pdev);
struct backlight_device *bl_dev = bl->bl_dev;
bl_dev->props.brightness = 0;
backlight_update_status(bl_dev);
sysfs_remove_group(&pdev->dev.kobj, &lp8788_attr_group);
lp8788_backlight_unregister(bl);
return 0;
}
static struct platform_driver lp8788_bl_driver = {
.probe = lp8788_backlight_probe,
.remove = lp8788_backlight_remove,
.driver = {
.name = LP8788_DEV_BACKLIGHT,
.owner = THIS_MODULE,
},
};
module_platform_driver(lp8788_bl_driver);
MODULE_DESCRIPTION("Texas Instruments LP8788 Backlight Driver");
MODULE_AUTHOR("Milo Kim");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:lp8788-backlight");
| gpl-2.0 |
nrgmilk/linux | lib/llist.c | 353 | 3868 | /*
* Lock-less NULL terminated single linked list
*
* The basic atomic operation of this list is cmpxchg on long. On
* architectures that don't have NMI-safe cmpxchg implementation, the
* list can NOT be used in NMI handler. So code uses the list in NMI
* handler should depend on CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG.
*
* Copyright 2010,2011 Intel Corp.
* Author: Huang Ying <ying.huang@intel.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 as published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/llist.h>
#include <asm/system.h>
/**
* llist_add - add a new entry
* @new: new entry to be added
* @head: the head for your lock-less list
*/
void llist_add(struct llist_node *new, struct llist_head *head)
{
struct llist_node *entry, *old_entry;
#ifndef CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG
BUG_ON(in_nmi());
#endif
entry = head->first;
do {
old_entry = entry;
new->next = entry;
cpu_relax();
} while ((entry = cmpxchg(&head->first, old_entry, new)) != old_entry);
}
EXPORT_SYMBOL_GPL(llist_add);
/**
* llist_add_batch - add several linked entries in batch
* @new_first: first entry in batch to be added
* @new_last: last entry in batch to be added
* @head: the head for your lock-less list
*/
void llist_add_batch(struct llist_node *new_first, struct llist_node *new_last,
struct llist_head *head)
{
struct llist_node *entry, *old_entry;
#ifndef CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG
BUG_ON(in_nmi());
#endif
entry = head->first;
do {
old_entry = entry;
new_last->next = entry;
cpu_relax();
} while ((entry = cmpxchg(&head->first, old_entry, new_first)) != old_entry);
}
EXPORT_SYMBOL_GPL(llist_add_batch);
/**
* llist_del_first - delete the first entry of lock-less list
* @head: the head for your lock-less list
*
* If list is empty, return NULL, otherwise, return the first entry
* deleted, this is the newest added one.
*
* Only one llist_del_first user can be used simultaneously with
* multiple llist_add users without lock. Because otherwise
* llist_del_first, llist_add, llist_add (or llist_del_all, llist_add,
* llist_add) sequence in another user may change @head->first->next,
* but keep @head->first. If multiple consumers are needed, please
* use llist_del_all or use lock between consumers.
*/
struct llist_node *llist_del_first(struct llist_head *head)
{
struct llist_node *entry, *old_entry, *next;
#ifndef CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG
BUG_ON(in_nmi());
#endif
entry = head->first;
do {
if (entry == NULL)
return NULL;
old_entry = entry;
next = entry->next;
cpu_relax();
} while ((entry = cmpxchg(&head->first, old_entry, next)) != old_entry);
return entry;
}
EXPORT_SYMBOL_GPL(llist_del_first);
/**
* llist_del_all - delete all entries from lock-less list
* @head: the head of lock-less list to delete all entries
*
* If list is empty, return NULL, otherwise, delete all entries and
* return the pointer to the first entry. The order of entries
* deleted is from the newest to the oldest added one.
*/
struct llist_node *llist_del_all(struct llist_head *head)
{
#ifndef CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG
BUG_ON(in_nmi());
#endif
return xchg(&head->first, NULL);
}
EXPORT_SYMBOL_GPL(llist_del_all);
| gpl-2.0 |
gem5/linux-arm64-gem5 | drivers/staging/media/go7007/go7007-driver.c | 353 | 18284 | /*
* Copyright (C) 2005-2006 Micronas USA Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License (Version 2) as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, USA.
*/
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/sched.h>
#include <linux/spinlock.h>
#include <linux/unistd.h>
#include <linux/time.h>
#include <linux/mm.h>
#include <linux/vmalloc.h>
#include <linux/device.h>
#include <linux/i2c.h>
#include <linux/firmware.h>
#include <linux/mutex.h>
#include <linux/uaccess.h>
#include <linux/slab.h>
#include <linux/videodev2.h>
#include <media/tuner.h>
#include <media/v4l2-common.h>
#include "go7007-priv.h"
/*
* Wait for an interrupt to be delivered from the GO7007SB and return
* the associated value and data.
*
* Must be called with the hw_lock held.
*/
int go7007_read_interrupt(struct go7007 *go, u16 *value, u16 *data)
{
go->interrupt_available = 0;
go->hpi_ops->read_interrupt(go);
if (wait_event_timeout(go->interrupt_waitq,
go->interrupt_available, 5*HZ) < 0) {
v4l2_err(&go->v4l2_dev, "timeout waiting for read interrupt\n");
return -1;
}
if (!go->interrupt_available)
return -1;
go->interrupt_available = 0;
*value = go->interrupt_value & 0xfffe;
*data = go->interrupt_data;
return 0;
}
EXPORT_SYMBOL(go7007_read_interrupt);
/*
* Read a register/address on the GO7007SB.
*
* Must be called with the hw_lock held.
*/
int go7007_read_addr(struct go7007 *go, u16 addr, u16 *data)
{
int count = 100;
u16 value;
if (go7007_write_interrupt(go, 0x0010, addr) < 0)
return -EIO;
while (count-- > 0) {
if (go7007_read_interrupt(go, &value, data) == 0 &&
value == 0xa000)
return 0;
}
return -EIO;
}
EXPORT_SYMBOL(go7007_read_addr);
/*
* Send the boot firmware to the encoder, which just wakes it up and lets
* us talk to the GPIO pins and on-board I2C adapter.
*
* Must be called with the hw_lock held.
*/
static int go7007_load_encoder(struct go7007 *go)
{
const struct firmware *fw_entry;
char fw_name[] = "go7007/go7007fw.bin";
void *bounce;
int fw_len, rv = 0;
u16 intr_val, intr_data;
if (go->boot_fw == NULL) {
if (request_firmware(&fw_entry, fw_name, go->dev)) {
v4l2_err(go, "unable to load firmware from file \"%s\"\n", fw_name);
return -1;
}
if (fw_entry->size < 16 || memcmp(fw_entry->data, "WISGO7007FW", 11)) {
v4l2_err(go, "file \"%s\" does not appear to be go7007 firmware\n", fw_name);
release_firmware(fw_entry);
return -1;
}
fw_len = fw_entry->size - 16;
bounce = kmemdup(fw_entry->data + 16, fw_len, GFP_KERNEL);
if (bounce == NULL) {
v4l2_err(go, "unable to allocate %d bytes for firmware transfer\n", fw_len);
release_firmware(fw_entry);
return -1;
}
release_firmware(fw_entry);
go->boot_fw_len = fw_len;
go->boot_fw = bounce;
}
if (go7007_interface_reset(go) < 0 ||
go7007_send_firmware(go, go->boot_fw, go->boot_fw_len) < 0 ||
go7007_read_interrupt(go, &intr_val, &intr_data) < 0 ||
(intr_val & ~0x1) != 0x5a5a) {
v4l2_err(go, "error transferring firmware\n");
rv = -1;
}
return rv;
}
MODULE_FIRMWARE("go7007/go7007fw.bin");
/*
* Boot the encoder and register the I2C adapter if requested. Do the
* minimum initialization necessary, since the board-specific code may
* still need to probe the board ID.
*
* Must NOT be called with the hw_lock held.
*/
int go7007_boot_encoder(struct go7007 *go, int init_i2c)
{
int ret;
mutex_lock(&go->hw_lock);
ret = go7007_load_encoder(go);
mutex_unlock(&go->hw_lock);
if (ret < 0)
return -1;
if (!init_i2c)
return 0;
if (go7007_i2c_init(go) < 0)
return -1;
go->i2c_adapter_online = 1;
return 0;
}
EXPORT_SYMBOL(go7007_boot_encoder);
/*
* Configure any hardware-related registers in the GO7007, such as GPIO
* pins and bus parameters, which are board-specific. This assumes
* the boot firmware has already been downloaded.
*
* Must be called with the hw_lock held.
*/
static int go7007_init_encoder(struct go7007 *go)
{
if (go->board_info->audio_flags & GO7007_AUDIO_I2S_MASTER) {
go7007_write_addr(go, 0x1000, 0x0811);
go7007_write_addr(go, 0x1000, 0x0c11);
}
switch (go->board_id) {
case GO7007_BOARDID_MATRIX_REV:
/* Set GPIO pin 0 to be an output (audio clock control) */
go7007_write_addr(go, 0x3c82, 0x0001);
go7007_write_addr(go, 0x3c80, 0x00fe);
break;
case GO7007_BOARDID_ADLINK_MPG24:
/* set GPIO5 to be an output, currently low */
go7007_write_addr(go, 0x3c82, 0x0000);
go7007_write_addr(go, 0x3c80, 0x00df);
break;
case GO7007_BOARDID_ADS_USBAV_709:
/* GPIO pin 0: audio clock control */
/* pin 2: TW9906 reset */
/* pin 3: capture LED */
go7007_write_addr(go, 0x3c82, 0x000d);
go7007_write_addr(go, 0x3c80, 0x00f2);
break;
}
return 0;
}
/*
* Send the boot firmware to the GO7007 and configure the registers. This
* is the only way to stop the encoder once it has started streaming video.
*
* Must be called with the hw_lock held.
*/
int go7007_reset_encoder(struct go7007 *go)
{
if (go7007_load_encoder(go) < 0)
return -1;
return go7007_init_encoder(go);
}
/*
* Attempt to instantiate an I2C client by ID, probably loading a module.
*/
static int init_i2c_module(struct i2c_adapter *adapter, const struct go_i2c *const i2c)
{
struct go7007 *go = i2c_get_adapdata(adapter);
struct v4l2_device *v4l2_dev = &go->v4l2_dev;
struct v4l2_subdev *sd;
struct i2c_board_info info;
memset(&info, 0, sizeof(info));
strlcpy(info.type, i2c->type, sizeof(info.type));
info.addr = i2c->addr;
info.flags = i2c->flags;
sd = v4l2_i2c_new_subdev_board(v4l2_dev, adapter, &info, NULL);
if (sd) {
if (i2c->is_video)
go->sd_video = sd;
if (i2c->is_audio)
go->sd_audio = sd;
return 0;
}
printk(KERN_INFO "go7007: probing for module i2c:%s failed\n", i2c->type);
return -EINVAL;
}
/*
* Detach and unregister the encoder. The go7007 struct won't be freed
* until v4l2 finishes releasing its resources and all associated fds are
* closed by applications.
*/
static void go7007_remove(struct v4l2_device *v4l2_dev)
{
struct go7007 *go = container_of(v4l2_dev, struct go7007, v4l2_dev);
v4l2_device_unregister(v4l2_dev);
if (go->hpi_ops->release)
go->hpi_ops->release(go);
if (go->i2c_adapter_online) {
i2c_del_adapter(&go->i2c_adapter);
go->i2c_adapter_online = 0;
}
kfree(go->boot_fw);
go7007_v4l2_remove(go);
kfree(go);
}
/*
* Finalize the GO7007 hardware setup, register the on-board I2C adapter
* (if used on this board), load the I2C client driver for the sensor
* (SAA7115 or whatever) and other devices, and register the ALSA and V4L2
* interfaces.
*
* Must NOT be called with the hw_lock held.
*/
int go7007_register_encoder(struct go7007 *go, unsigned num_i2c_devs)
{
int i, ret;
dev_info(go->dev, "go7007: registering new %s\n", go->name);
go->v4l2_dev.release = go7007_remove;
ret = v4l2_device_register(go->dev, &go->v4l2_dev);
if (ret < 0)
return ret;
mutex_lock(&go->hw_lock);
ret = go7007_init_encoder(go);
mutex_unlock(&go->hw_lock);
if (ret < 0)
return ret;
ret = go7007_v4l2_ctrl_init(go);
if (ret < 0)
return ret;
if (!go->i2c_adapter_online &&
go->board_info->flags & GO7007_BOARD_USE_ONBOARD_I2C) {
ret = go7007_i2c_init(go);
if (ret < 0)
return ret;
go->i2c_adapter_online = 1;
}
if (go->i2c_adapter_online) {
if (go->board_id == GO7007_BOARDID_ADS_USBAV_709) {
/* Reset the TW9906 */
go7007_write_addr(go, 0x3c82, 0x0009);
msleep(50);
go7007_write_addr(go, 0x3c82, 0x000d);
}
for (i = 0; i < num_i2c_devs; ++i)
init_i2c_module(&go->i2c_adapter, &go->board_info->i2c_devs[i]);
if (go->tuner_type >= 0) {
struct tuner_setup setup = {
.addr = ADDR_UNSET,
.type = go->tuner_type,
.mode_mask = T_ANALOG_TV,
};
v4l2_device_call_all(&go->v4l2_dev, 0, tuner,
s_type_addr, &setup);
}
if (go->board_id == GO7007_BOARDID_ADLINK_MPG24)
v4l2_subdev_call(go->sd_video, video, s_routing,
0, 0, go->channel_number + 1);
}
ret = go7007_v4l2_init(go);
if (ret < 0)
return ret;
if (go->board_info->flags & GO7007_BOARD_HAS_AUDIO) {
go->audio_enabled = 1;
go7007_snd_init(go);
}
return 0;
}
EXPORT_SYMBOL(go7007_register_encoder);
/*
* Send the encode firmware to the encoder, which will cause it
* to immediately start delivering the video and audio streams.
*
* Must be called with the hw_lock held.
*/
int go7007_start_encoder(struct go7007 *go)
{
u8 *fw;
int fw_len, rv = 0, i;
u16 intr_val, intr_data;
go->modet_enable = 0;
if (!go->dvd_mode)
for (i = 0; i < 4; ++i) {
if (go->modet[i].enable) {
go->modet_enable = 1;
continue;
}
go->modet[i].pixel_threshold = 32767;
go->modet[i].motion_threshold = 32767;
go->modet[i].mb_threshold = 32767;
}
if (go7007_construct_fw_image(go, &fw, &fw_len) < 0)
return -1;
if (go7007_send_firmware(go, fw, fw_len) < 0 ||
go7007_read_interrupt(go, &intr_val, &intr_data) < 0) {
v4l2_err(&go->v4l2_dev, "error transferring firmware\n");
rv = -1;
goto start_error;
}
go->state = STATE_DATA;
go->parse_length = 0;
go->seen_frame = 0;
if (go7007_stream_start(go) < 0) {
v4l2_err(&go->v4l2_dev, "error starting stream transfer\n");
rv = -1;
goto start_error;
}
start_error:
kfree(fw);
return rv;
}
/*
* Store a byte in the current video buffer, if there is one.
*/
static inline void store_byte(struct go7007_buffer *vb, u8 byte)
{
if (vb && vb->vb.v4l2_planes[0].bytesused < GO7007_BUF_SIZE) {
u8 *ptr = vb2_plane_vaddr(&vb->vb, 0);
ptr[vb->vb.v4l2_planes[0].bytesused++] = byte;
}
}
/*
* Deliver the last video buffer and get a new one to start writing to.
*/
static struct go7007_buffer *frame_boundary(struct go7007 *go, struct go7007_buffer *vb)
{
struct go7007_buffer *vb_tmp = NULL;
u32 *bytesused = &vb->vb.v4l2_planes[0].bytesused;
int i;
if (vb) {
if (vb->modet_active) {
if (*bytesused + 216 < GO7007_BUF_SIZE) {
for (i = 0; i < 216; ++i)
store_byte(vb, go->active_map[i]);
*bytesused -= 216;
} else
vb->modet_active = 0;
}
vb->vb.v4l2_buf.sequence = go->next_seq++;
v4l2_get_timestamp(&vb->vb.v4l2_buf.timestamp);
vb_tmp = vb;
spin_lock(&go->spinlock);
list_del(&vb->list);
if (list_empty(&go->vidq_active))
vb = NULL;
else
vb = list_first_entry(&go->vidq_active, struct go7007_buffer, list);
go->active_buf = vb;
spin_unlock(&go->spinlock);
vb2_buffer_done(&vb_tmp->vb, VB2_BUF_STATE_DONE);
return vb;
}
spin_lock(&go->spinlock);
if (!list_empty(&go->vidq_active))
vb = go->active_buf =
list_first_entry(&go->vidq_active, struct go7007_buffer, list);
spin_unlock(&go->spinlock);
go->next_seq++;
return vb;
}
static void write_bitmap_word(struct go7007 *go)
{
int x, y, i, stride = ((go->width >> 4) + 7) >> 3;
for (i = 0; i < 16; ++i) {
y = (((go->parse_length - 1) << 3) + i) / (go->width >> 4);
x = (((go->parse_length - 1) << 3) + i) % (go->width >> 4);
if (stride * y + (x >> 3) < sizeof(go->active_map))
go->active_map[stride * y + (x >> 3)] |=
(go->modet_word & 1) << (x & 0x7);
go->modet_word >>= 1;
}
}
/*
* Parse a chunk of the video stream into frames. The frames are not
* delimited by the hardware, so we have to parse the frame boundaries
* based on the type of video stream we're receiving.
*/
void go7007_parse_video_stream(struct go7007 *go, u8 *buf, int length)
{
struct go7007_buffer *vb = go->active_buf;
int i, seq_start_code = -1, gop_start_code = -1, frame_start_code = -1;
switch (go->format) {
case V4L2_PIX_FMT_MPEG4:
seq_start_code = 0xB0;
gop_start_code = 0xB3;
frame_start_code = 0xB6;
break;
case V4L2_PIX_FMT_MPEG1:
case V4L2_PIX_FMT_MPEG2:
seq_start_code = 0xB3;
gop_start_code = 0xB8;
frame_start_code = 0x00;
break;
}
for (i = 0; i < length; ++i) {
if (vb && vb->vb.v4l2_planes[0].bytesused >= GO7007_BUF_SIZE - 3) {
v4l2_info(&go->v4l2_dev, "dropping oversized frame\n");
vb->vb.v4l2_planes[0].bytesused = 0;
vb->frame_offset = 0;
vb->modet_active = 0;
vb = go->active_buf = NULL;
}
switch (go->state) {
case STATE_DATA:
switch (buf[i]) {
case 0x00:
go->state = STATE_00;
break;
case 0xFF:
go->state = STATE_FF;
break;
default:
store_byte(vb, buf[i]);
break;
}
break;
case STATE_00:
switch (buf[i]) {
case 0x00:
go->state = STATE_00_00;
break;
case 0xFF:
store_byte(vb, 0x00);
go->state = STATE_FF;
break;
default:
store_byte(vb, 0x00);
store_byte(vb, buf[i]);
go->state = STATE_DATA;
break;
}
break;
case STATE_00_00:
switch (buf[i]) {
case 0x00:
store_byte(vb, 0x00);
/* go->state remains STATE_00_00 */
break;
case 0x01:
go->state = STATE_00_00_01;
break;
case 0xFF:
store_byte(vb, 0x00);
store_byte(vb, 0x00);
go->state = STATE_FF;
break;
default:
store_byte(vb, 0x00);
store_byte(vb, 0x00);
store_byte(vb, buf[i]);
go->state = STATE_DATA;
break;
}
break;
case STATE_00_00_01:
if (buf[i] == 0xF8 && go->modet_enable == 0) {
/* MODET start code, but MODET not enabled */
store_byte(vb, 0x00);
store_byte(vb, 0x00);
store_byte(vb, 0x01);
store_byte(vb, 0xF8);
go->state = STATE_DATA;
break;
}
/* If this is the start of a new MPEG frame,
* get a new buffer */
if ((go->format == V4L2_PIX_FMT_MPEG1 ||
go->format == V4L2_PIX_FMT_MPEG2 ||
go->format == V4L2_PIX_FMT_MPEG4) &&
(buf[i] == seq_start_code ||
buf[i] == gop_start_code ||
buf[i] == frame_start_code)) {
if (vb == NULL || go->seen_frame)
vb = frame_boundary(go, vb);
go->seen_frame = buf[i] == frame_start_code;
if (vb && go->seen_frame)
vb->frame_offset = vb->vb.v4l2_planes[0].bytesused;
}
/* Handle any special chunk types, or just write the
* start code to the (potentially new) buffer */
switch (buf[i]) {
case 0xF5: /* timestamp */
go->parse_length = 12;
go->state = STATE_UNPARSED;
break;
case 0xF6: /* vbi */
go->state = STATE_VBI_LEN_A;
break;
case 0xF8: /* MD map */
go->parse_length = 0;
memset(go->active_map, 0,
sizeof(go->active_map));
go->state = STATE_MODET_MAP;
break;
case 0xFF: /* Potential JPEG start code */
store_byte(vb, 0x00);
store_byte(vb, 0x00);
store_byte(vb, 0x01);
go->state = STATE_FF;
break;
default:
store_byte(vb, 0x00);
store_byte(vb, 0x00);
store_byte(vb, 0x01);
store_byte(vb, buf[i]);
go->state = STATE_DATA;
break;
}
break;
case STATE_FF:
switch (buf[i]) {
case 0x00:
store_byte(vb, 0xFF);
go->state = STATE_00;
break;
case 0xFF:
store_byte(vb, 0xFF);
/* go->state remains STATE_FF */
break;
case 0xD8:
if (go->format == V4L2_PIX_FMT_MJPEG)
vb = frame_boundary(go, vb);
/* fall through */
default:
store_byte(vb, 0xFF);
store_byte(vb, buf[i]);
go->state = STATE_DATA;
break;
}
break;
case STATE_VBI_LEN_A:
go->parse_length = buf[i] << 8;
go->state = STATE_VBI_LEN_B;
break;
case STATE_VBI_LEN_B:
go->parse_length |= buf[i];
if (go->parse_length > 0)
go->state = STATE_UNPARSED;
else
go->state = STATE_DATA;
break;
case STATE_MODET_MAP:
if (go->parse_length < 204) {
if (go->parse_length & 1) {
go->modet_word |= buf[i];
write_bitmap_word(go);
} else
go->modet_word = buf[i] << 8;
} else if (go->parse_length == 207 && vb) {
vb->modet_active = buf[i];
}
if (++go->parse_length == 208)
go->state = STATE_DATA;
break;
case STATE_UNPARSED:
if (--go->parse_length == 0)
go->state = STATE_DATA;
break;
}
}
}
EXPORT_SYMBOL(go7007_parse_video_stream);
/*
* Allocate a new go7007 struct. Used by the hardware-specific probe.
*/
struct go7007 *go7007_alloc(const struct go7007_board_info *board,
struct device *dev)
{
struct go7007 *go;
int i;
go = kzalloc(sizeof(struct go7007), GFP_KERNEL);
if (go == NULL)
return NULL;
go->dev = dev;
go->board_info = board;
go->board_id = 0;
go->tuner_type = -1;
go->channel_number = 0;
go->name[0] = 0;
mutex_init(&go->hw_lock);
init_waitqueue_head(&go->frame_waitq);
spin_lock_init(&go->spinlock);
go->status = STATUS_INIT;
memset(&go->i2c_adapter, 0, sizeof(go->i2c_adapter));
go->i2c_adapter_online = 0;
go->interrupt_available = 0;
init_waitqueue_head(&go->interrupt_waitq);
go->input = 0;
go7007_update_board(go);
go->encoder_h_halve = 0;
go->encoder_v_halve = 0;
go->encoder_subsample = 0;
go->format = V4L2_PIX_FMT_MJPEG;
go->bitrate = 1500000;
go->fps_scale = 1;
go->pali = 0;
go->aspect_ratio = GO7007_RATIO_1_1;
go->gop_size = 0;
go->ipb = 0;
go->closed_gop = 0;
go->repeat_seqhead = 0;
go->seq_header_enable = 0;
go->gop_header_enable = 0;
go->dvd_mode = 0;
go->interlace_coding = 0;
for (i = 0; i < 4; ++i)
go->modet[i].enable = 0;
for (i = 0; i < 1624; ++i)
go->modet_map[i] = 0;
go->audio_deliver = NULL;
go->audio_enabled = 0;
return go;
}
EXPORT_SYMBOL(go7007_alloc);
void go7007_update_board(struct go7007 *go)
{
const struct go7007_board_info *board = go->board_info;
if (board->sensor_flags & GO7007_SENSOR_TV) {
go->standard = GO7007_STD_NTSC;
go->std = V4L2_STD_NTSC_M;
go->width = 720;
go->height = 480;
go->sensor_framerate = 30000;
} else {
go->standard = GO7007_STD_OTHER;
go->width = board->sensor_width;
go->height = board->sensor_height;
go->sensor_framerate = board->sensor_framerate;
}
go->encoder_v_offset = board->sensor_v_offset;
go->encoder_h_offset = board->sensor_h_offset;
}
EXPORT_SYMBOL(go7007_update_board);
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
fabiocannizzo/linux | arch/arm/mach-omap1/ocpi.c | 353 | 2116 | // SPDX-License-Identifier: GPL-2.0-or-later
/*
* linux/arch/arm/plat-omap/ocpi.c
*
* Minimal OCP bus support for omap16xx
*
* Copyright (C) 2003 - 2005 Nokia Corporation
* Copyright (C) 2012 Texas Instruments, Inc.
* Written by Tony Lindgren <tony@atomide.com>
*
* Modified for clock framework by Paul Mundt <paul.mundt@nokia.com>.
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/spinlock.h>
#include <linux/err.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <mach/hardware.h>
#include "common.h"
#define OCPI_BASE 0xfffec320
#define OCPI_FAULT (OCPI_BASE + 0x00)
#define OCPI_CMD_FAULT (OCPI_BASE + 0x04)
#define OCPI_SINT0 (OCPI_BASE + 0x08)
#define OCPI_TABORT (OCPI_BASE + 0x0c)
#define OCPI_SINT1 (OCPI_BASE + 0x10)
#define OCPI_PROT (OCPI_BASE + 0x14)
#define OCPI_SEC (OCPI_BASE + 0x18)
/* USB OHCI OCPI access error registers */
#define HOSTUEADDR 0xfffba0e0
#define HOSTUESTATUS 0xfffba0e4
static struct clk *ocpi_ck;
/*
* Enables device access to OMAP buses via the OCPI bridge
*/
int ocpi_enable(void)
{
unsigned int val;
if (!cpu_is_omap16xx())
return -ENODEV;
/* Enable access for OHCI in OCPI */
val = omap_readl(OCPI_PROT);
val &= ~0xff;
/* val &= (1 << 0); Allow access only to EMIFS */
omap_writel(val, OCPI_PROT);
val = omap_readl(OCPI_SEC);
val &= ~0xff;
omap_writel(val, OCPI_SEC);
return 0;
}
EXPORT_SYMBOL(ocpi_enable);
static int __init omap_ocpi_init(void)
{
if (!cpu_is_omap16xx())
return -ENODEV;
ocpi_ck = clk_get(NULL, "l3_ocpi_ck");
if (IS_ERR(ocpi_ck))
return PTR_ERR(ocpi_ck);
clk_enable(ocpi_ck);
ocpi_enable();
pr_info("OMAP OCPI interconnect driver loaded\n");
return 0;
}
static void __exit omap_ocpi_exit(void)
{
/* REVISIT: Disable OCPI */
if (!cpu_is_omap16xx())
return;
clk_disable(ocpi_ck);
clk_put(ocpi_ck);
}
MODULE_AUTHOR("Tony Lindgren <tony@atomide.com>");
MODULE_DESCRIPTION("OMAP OCPI bus controller module");
MODULE_LICENSE("GPL");
module_init(omap_ocpi_init);
module_exit(omap_ocpi_exit);
| gpl-2.0 |
Excito/kernel-3.18 | drivers/rtc/rtc-puv3.c | 609 | 7895 | /*
* RTC driver code specific to PKUnity SoC and UniCore ISA
*
* Maintained by GUAN Xue-tao <gxt@mprc.pku.edu.cn>
* Copyright (C) 2001-2010 Guan Xuetao
*
* 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/fs.h>
#include <linux/string.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/interrupt.h>
#include <linux/rtc.h>
#include <linux/bcd.h>
#include <linux/clk.h>
#include <linux/log2.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/io.h>
#include <asm/irq.h>
#include <mach/hardware.h>
static struct resource *puv3_rtc_mem;
static int puv3_rtc_alarmno = IRQ_RTCAlarm;
static int puv3_rtc_tickno = IRQ_RTC;
static DEFINE_SPINLOCK(puv3_rtc_pie_lock);
/* IRQ Handlers */
static irqreturn_t puv3_rtc_alarmirq(int irq, void *id)
{
struct rtc_device *rdev = id;
writel(readl(RTC_RTSR) | RTC_RTSR_AL, RTC_RTSR);
rtc_update_irq(rdev, 1, RTC_AF | RTC_IRQF);
return IRQ_HANDLED;
}
static irqreturn_t puv3_rtc_tickirq(int irq, void *id)
{
struct rtc_device *rdev = id;
writel(readl(RTC_RTSR) | RTC_RTSR_HZ, RTC_RTSR);
rtc_update_irq(rdev, 1, RTC_PF | RTC_IRQF);
return IRQ_HANDLED;
}
/* Update control registers */
static void puv3_rtc_setaie(struct device *dev, int to)
{
unsigned int tmp;
dev_dbg(dev, "%s: aie=%d\n", __func__, to);
tmp = readl(RTC_RTSR) & ~RTC_RTSR_ALE;
if (to)
tmp |= RTC_RTSR_ALE;
writel(tmp, RTC_RTSR);
}
static int puv3_rtc_setpie(struct device *dev, int enabled)
{
unsigned int tmp;
dev_dbg(dev, "%s: pie=%d\n", __func__, enabled);
spin_lock_irq(&puv3_rtc_pie_lock);
tmp = readl(RTC_RTSR) & ~RTC_RTSR_HZE;
if (enabled)
tmp |= RTC_RTSR_HZE;
writel(tmp, RTC_RTSR);
spin_unlock_irq(&puv3_rtc_pie_lock);
return 0;
}
/* Time read/write */
static int puv3_rtc_gettime(struct device *dev, struct rtc_time *rtc_tm)
{
rtc_time_to_tm(readl(RTC_RCNR), rtc_tm);
dev_dbg(dev, "read time %02x.%02x.%02x %02x/%02x/%02x\n",
rtc_tm->tm_year, rtc_tm->tm_mon, rtc_tm->tm_mday,
rtc_tm->tm_hour, rtc_tm->tm_min, rtc_tm->tm_sec);
return 0;
}
static int puv3_rtc_settime(struct device *dev, struct rtc_time *tm)
{
unsigned long rtc_count = 0;
dev_dbg(dev, "set time %02d.%02d.%02d %02d/%02d/%02d\n",
tm->tm_year, tm->tm_mon, tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec);
rtc_tm_to_time(tm, &rtc_count);
writel(rtc_count, RTC_RCNR);
return 0;
}
static int puv3_rtc_getalarm(struct device *dev, struct rtc_wkalrm *alrm)
{
struct rtc_time *alm_tm = &alrm->time;
rtc_time_to_tm(readl(RTC_RTAR), alm_tm);
alrm->enabled = readl(RTC_RTSR) & RTC_RTSR_ALE;
dev_dbg(dev, "read alarm %02x %02x.%02x.%02x %02x/%02x/%02x\n",
alrm->enabled,
alm_tm->tm_year, alm_tm->tm_mon, alm_tm->tm_mday,
alm_tm->tm_hour, alm_tm->tm_min, alm_tm->tm_sec);
return 0;
}
static int puv3_rtc_setalarm(struct device *dev, struct rtc_wkalrm *alrm)
{
struct rtc_time *tm = &alrm->time;
unsigned long rtcalarm_count = 0;
dev_dbg(dev, "puv3_rtc_setalarm: %d, %02x/%02x/%02x %02x.%02x.%02x\n",
alrm->enabled,
tm->tm_mday & 0xff, tm->tm_mon & 0xff, tm->tm_year & 0xff,
tm->tm_hour & 0xff, tm->tm_min & 0xff, tm->tm_sec);
rtc_tm_to_time(tm, &rtcalarm_count);
writel(rtcalarm_count, RTC_RTAR);
puv3_rtc_setaie(dev, alrm->enabled);
if (alrm->enabled)
enable_irq_wake(puv3_rtc_alarmno);
else
disable_irq_wake(puv3_rtc_alarmno);
return 0;
}
static int puv3_rtc_proc(struct device *dev, struct seq_file *seq)
{
seq_printf(seq, "periodic_IRQ\t: %s\n",
(readl(RTC_RTSR) & RTC_RTSR_HZE) ? "yes" : "no");
return 0;
}
static int puv3_rtc_open(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct rtc_device *rtc_dev = platform_get_drvdata(pdev);
int ret;
ret = request_irq(puv3_rtc_alarmno, puv3_rtc_alarmirq,
0, "pkunity-rtc alarm", rtc_dev);
if (ret) {
dev_err(dev, "IRQ%d error %d\n", puv3_rtc_alarmno, ret);
return ret;
}
ret = request_irq(puv3_rtc_tickno, puv3_rtc_tickirq,
0, "pkunity-rtc tick", rtc_dev);
if (ret) {
dev_err(dev, "IRQ%d error %d\n", puv3_rtc_tickno, ret);
goto tick_err;
}
return ret;
tick_err:
free_irq(puv3_rtc_alarmno, rtc_dev);
return ret;
}
static void puv3_rtc_release(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct rtc_device *rtc_dev = platform_get_drvdata(pdev);
/* do not clear AIE here, it may be needed for wake */
puv3_rtc_setpie(dev, 0);
free_irq(puv3_rtc_alarmno, rtc_dev);
free_irq(puv3_rtc_tickno, rtc_dev);
}
static const struct rtc_class_ops puv3_rtcops = {
.open = puv3_rtc_open,
.release = puv3_rtc_release,
.read_time = puv3_rtc_gettime,
.set_time = puv3_rtc_settime,
.read_alarm = puv3_rtc_getalarm,
.set_alarm = puv3_rtc_setalarm,
.proc = puv3_rtc_proc,
};
static void puv3_rtc_enable(struct device *dev, int en)
{
if (!en) {
writel(readl(RTC_RTSR) & ~RTC_RTSR_HZE, RTC_RTSR);
} else {
/* re-enable the device, and check it is ok */
if ((readl(RTC_RTSR) & RTC_RTSR_HZE) == 0) {
dev_info(dev, "rtc disabled, re-enabling\n");
writel(readl(RTC_RTSR) | RTC_RTSR_HZE, RTC_RTSR);
}
}
}
static int puv3_rtc_remove(struct platform_device *dev)
{
struct rtc_device *rtc = platform_get_drvdata(dev);
rtc_device_unregister(rtc);
puv3_rtc_setpie(&dev->dev, 0);
puv3_rtc_setaie(&dev->dev, 0);
release_resource(puv3_rtc_mem);
kfree(puv3_rtc_mem);
return 0;
}
static int puv3_rtc_probe(struct platform_device *pdev)
{
struct rtc_device *rtc;
struct resource *res;
int ret;
dev_dbg(&pdev->dev, "%s: probe=%p\n", __func__, pdev);
/* find the IRQs */
puv3_rtc_tickno = platform_get_irq(pdev, 1);
if (puv3_rtc_tickno < 0) {
dev_err(&pdev->dev, "no irq for rtc tick\n");
return -ENOENT;
}
puv3_rtc_alarmno = platform_get_irq(pdev, 0);
if (puv3_rtc_alarmno < 0) {
dev_err(&pdev->dev, "no irq for alarm\n");
return -ENOENT;
}
dev_dbg(&pdev->dev, "PKUnity_rtc: tick irq %d, alarm irq %d\n",
puv3_rtc_tickno, puv3_rtc_alarmno);
/* get the memory region */
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (res == NULL) {
dev_err(&pdev->dev, "failed to get memory region resource\n");
return -ENOENT;
}
puv3_rtc_mem = request_mem_region(res->start, resource_size(res),
pdev->name);
if (puv3_rtc_mem == NULL) {
dev_err(&pdev->dev, "failed to reserve memory region\n");
ret = -ENOENT;
goto err_nores;
}
puv3_rtc_enable(&pdev->dev, 1);
/* register RTC and exit */
rtc = rtc_device_register("pkunity", &pdev->dev, &puv3_rtcops,
THIS_MODULE);
if (IS_ERR(rtc)) {
dev_err(&pdev->dev, "cannot attach rtc\n");
ret = PTR_ERR(rtc);
goto err_nortc;
}
/* platform setup code should have handled this; sigh */
if (!device_can_wakeup(&pdev->dev))
device_init_wakeup(&pdev->dev, 1);
platform_set_drvdata(pdev, rtc);
return 0;
err_nortc:
puv3_rtc_enable(&pdev->dev, 0);
release_resource(puv3_rtc_mem);
err_nores:
return ret;
}
#ifdef CONFIG_PM_SLEEP
static int ticnt_save;
static int puv3_rtc_suspend(struct device *dev)
{
/* save RTAR for anyone using periodic interrupts */
ticnt_save = readl(RTC_RTAR);
puv3_rtc_enable(dev, 0);
return 0;
}
static int puv3_rtc_resume(struct device *dev)
{
puv3_rtc_enable(dev, 1);
writel(ticnt_save, RTC_RTAR);
return 0;
}
#endif
static SIMPLE_DEV_PM_OPS(puv3_rtc_pm_ops, puv3_rtc_suspend, puv3_rtc_resume);
static struct platform_driver puv3_rtc_driver = {
.probe = puv3_rtc_probe,
.remove = puv3_rtc_remove,
.driver = {
.name = "PKUnity-v3-RTC",
.owner = THIS_MODULE,
.pm = &puv3_rtc_pm_ops,
}
};
module_platform_driver(puv3_rtc_driver);
MODULE_DESCRIPTION("RTC Driver for the PKUnity v3 chip");
MODULE_AUTHOR("Hu Dongliang");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
boype/kernel_tuna_jb42 | drivers/target/target_core_alua.c | 609 | 57089 | /*******************************************************************************
* Filename: target_core_alua.c
*
* This file contains SPC-3 compliant asymmetric logical unit assigntment (ALUA)
*
* Copyright (c) 2009-2010 Rising Tide Systems
* Copyright (c) 2009-2010 Linux-iSCSI.org
*
* Nicholas A. Bellinger <nab@kernel.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
******************************************************************************/
#include <linux/version.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/configfs.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <asm/unaligned.h>
#include <target/target_core_base.h>
#include <target/target_core_device.h>
#include <target/target_core_transport.h>
#include <target/target_core_fabric_ops.h>
#include <target/target_core_configfs.h>
#include "target_core_alua.h"
#include "target_core_hba.h"
#include "target_core_ua.h"
static int core_alua_check_transition(int state, int *primary);
static int core_alua_set_tg_pt_secondary_state(
struct t10_alua_tg_pt_gp_member *tg_pt_gp_mem,
struct se_port *port, int explict, int offline);
/*
* REPORT_TARGET_PORT_GROUPS
*
* See spc4r17 section 6.27
*/
int core_emulate_report_target_port_groups(struct se_cmd *cmd)
{
struct se_subsystem_dev *su_dev = SE_DEV(cmd)->se_sub_dev;
struct se_port *port;
struct t10_alua_tg_pt_gp *tg_pt_gp;
struct t10_alua_tg_pt_gp_member *tg_pt_gp_mem;
unsigned char *buf = (unsigned char *)T_TASK(cmd)->t_task_buf;
u32 rd_len = 0, off = 4; /* Skip over RESERVED area to first
Target port group descriptor */
/*
* Need at least 4 bytes of response data or else we can't
* even fit the return data length.
*/
if (cmd->data_length < 4) {
pr_warn("REPORT TARGET PORT GROUPS allocation length %u"
" too small\n", cmd->data_length);
return -EINVAL;
}
spin_lock(&T10_ALUA(su_dev)->tg_pt_gps_lock);
list_for_each_entry(tg_pt_gp, &T10_ALUA(su_dev)->tg_pt_gps_list,
tg_pt_gp_list) {
/*
* Check if the Target port group and Target port descriptor list
* based on tg_pt_gp_members count will fit into the response payload.
* Otherwise, bump rd_len to let the initiator know we have exceeded
* the allocation length and the response is truncated.
*/
if ((off + 8 + (tg_pt_gp->tg_pt_gp_members * 4)) >
cmd->data_length) {
rd_len += 8 + (tg_pt_gp->tg_pt_gp_members * 4);
continue;
}
/*
* PREF: Preferred target port bit, determine if this
* bit should be set for port group.
*/
if (tg_pt_gp->tg_pt_gp_pref)
buf[off] = 0x80;
/*
* Set the ASYMMETRIC ACCESS State
*/
buf[off++] |= (atomic_read(
&tg_pt_gp->tg_pt_gp_alua_access_state) & 0xff);
/*
* Set supported ASYMMETRIC ACCESS State bits
*/
buf[off] = 0x80; /* T_SUP */
buf[off] |= 0x40; /* O_SUP */
buf[off] |= 0x8; /* U_SUP */
buf[off] |= 0x4; /* S_SUP */
buf[off] |= 0x2; /* AN_SUP */
buf[off++] |= 0x1; /* AO_SUP */
/*
* TARGET PORT GROUP
*/
buf[off++] = ((tg_pt_gp->tg_pt_gp_id >> 8) & 0xff);
buf[off++] = (tg_pt_gp->tg_pt_gp_id & 0xff);
off++; /* Skip over Reserved */
/*
* STATUS CODE
*/
buf[off++] = (tg_pt_gp->tg_pt_gp_alua_access_status & 0xff);
/*
* Vendor Specific field
*/
buf[off++] = 0x00;
/*
* TARGET PORT COUNT
*/
buf[off++] = (tg_pt_gp->tg_pt_gp_members & 0xff);
rd_len += 8;
spin_lock(&tg_pt_gp->tg_pt_gp_lock);
list_for_each_entry(tg_pt_gp_mem, &tg_pt_gp->tg_pt_gp_mem_list,
tg_pt_gp_mem_list) {
port = tg_pt_gp_mem->tg_pt;
/*
* Start Target Port descriptor format
*
* See spc4r17 section 6.2.7 Table 247
*/
off += 2; /* Skip over Obsolete */
/*
* Set RELATIVE TARGET PORT IDENTIFIER
*/
buf[off++] = ((port->sep_rtpi >> 8) & 0xff);
buf[off++] = (port->sep_rtpi & 0xff);
rd_len += 4;
}
spin_unlock(&tg_pt_gp->tg_pt_gp_lock);
}
spin_unlock(&T10_ALUA(su_dev)->tg_pt_gps_lock);
/*
* Set the RETURN DATA LENGTH set in the header of the DataIN Payload
*/
buf[0] = ((rd_len >> 24) & 0xff);
buf[1] = ((rd_len >> 16) & 0xff);
buf[2] = ((rd_len >> 8) & 0xff);
buf[3] = (rd_len & 0xff);
return 0;
}
/*
* SET_TARGET_PORT_GROUPS for explict ALUA operation.
*
* See spc4r17 section 6.35
*/
int core_emulate_set_target_port_groups(struct se_cmd *cmd)
{
struct se_device *dev = SE_DEV(cmd);
struct se_subsystem_dev *su_dev = SE_DEV(cmd)->se_sub_dev;
struct se_port *port, *l_port = SE_LUN(cmd)->lun_sep;
struct se_node_acl *nacl = SE_SESS(cmd)->se_node_acl;
struct t10_alua_tg_pt_gp *tg_pt_gp = NULL, *l_tg_pt_gp;
struct t10_alua_tg_pt_gp_member *tg_pt_gp_mem, *l_tg_pt_gp_mem;
unsigned char *buf = (unsigned char *)T_TASK(cmd)->t_task_buf;
unsigned char *ptr = &buf[4]; /* Skip over RESERVED area in header */
u32 len = 4; /* Skip over RESERVED area in header */
int alua_access_state, primary = 0, rc;
u16 tg_pt_id, rtpi;
if (!(l_port))
return PYX_TRANSPORT_LU_COMM_FAILURE;
/*
* Determine if explict ALUA via SET_TARGET_PORT_GROUPS is allowed
* for the local tg_pt_gp.
*/
l_tg_pt_gp_mem = l_port->sep_alua_tg_pt_gp_mem;
if (!(l_tg_pt_gp_mem)) {
printk(KERN_ERR "Unable to access l_port->sep_alua_tg_pt_gp_mem\n");
return PYX_TRANSPORT_UNKNOWN_SAM_OPCODE;
}
spin_lock(&l_tg_pt_gp_mem->tg_pt_gp_mem_lock);
l_tg_pt_gp = l_tg_pt_gp_mem->tg_pt_gp;
if (!(l_tg_pt_gp)) {
spin_unlock(&l_tg_pt_gp_mem->tg_pt_gp_mem_lock);
printk(KERN_ERR "Unable to access *l_tg_pt_gp_mem->tg_pt_gp\n");
return PYX_TRANSPORT_UNKNOWN_SAM_OPCODE;
}
rc = (l_tg_pt_gp->tg_pt_gp_alua_access_type & TPGS_EXPLICT_ALUA);
spin_unlock(&l_tg_pt_gp_mem->tg_pt_gp_mem_lock);
if (!(rc)) {
printk(KERN_INFO "Unable to process SET_TARGET_PORT_GROUPS"
" while TPGS_EXPLICT_ALUA is disabled\n");
return PYX_TRANSPORT_UNKNOWN_SAM_OPCODE;
}
while (len < cmd->data_length) {
alua_access_state = (ptr[0] & 0x0f);
/*
* Check the received ALUA access state, and determine if
* the state is a primary or secondary target port asymmetric
* access state.
*/
rc = core_alua_check_transition(alua_access_state, &primary);
if (rc != 0) {
/*
* If the SET TARGET PORT GROUPS attempts to establish
* an invalid combination of target port asymmetric
* access states or attempts to establish an
* unsupported target port asymmetric access state,
* then the command shall be terminated with CHECK
* CONDITION status, with the sense key set to ILLEGAL
* REQUEST, and the additional sense code set to INVALID
* FIELD IN PARAMETER LIST.
*/
return PYX_TRANSPORT_INVALID_PARAMETER_LIST;
}
rc = -1;
/*
* If the ASYMMETRIC ACCESS STATE field (see table 267)
* specifies a primary target port asymmetric access state,
* then the TARGET PORT GROUP OR TARGET PORT field specifies
* a primary target port group for which the primary target
* port asymmetric access state shall be changed. If the
* ASYMMETRIC ACCESS STATE field specifies a secondary target
* port asymmetric access state, then the TARGET PORT GROUP OR
* TARGET PORT field specifies the relative target port
* identifier (see 3.1.120) of the target port for which the
* secondary target port asymmetric access state shall be
* changed.
*/
if (primary) {
tg_pt_id = get_unaligned_be16(ptr + 2);
/*
* Locate the matching target port group ID from
* the global tg_pt_gp list
*/
spin_lock(&T10_ALUA(su_dev)->tg_pt_gps_lock);
list_for_each_entry(tg_pt_gp,
&T10_ALUA(su_dev)->tg_pt_gps_list,
tg_pt_gp_list) {
if (!(tg_pt_gp->tg_pt_gp_valid_id))
continue;
if (tg_pt_id != tg_pt_gp->tg_pt_gp_id)
continue;
atomic_inc(&tg_pt_gp->tg_pt_gp_ref_cnt);
smp_mb__after_atomic_inc();
spin_unlock(&T10_ALUA(su_dev)->tg_pt_gps_lock);
rc = core_alua_do_port_transition(tg_pt_gp,
dev, l_port, nacl,
alua_access_state, 1);
spin_lock(&T10_ALUA(su_dev)->tg_pt_gps_lock);
atomic_dec(&tg_pt_gp->tg_pt_gp_ref_cnt);
smp_mb__after_atomic_dec();
break;
}
spin_unlock(&T10_ALUA(su_dev)->tg_pt_gps_lock);
/*
* If not matching target port group ID can be located
* throw an exception with ASCQ: INVALID_PARAMETER_LIST
*/
if (rc != 0)
return PYX_TRANSPORT_INVALID_PARAMETER_LIST;
} else {
/*
* Extact the RELATIVE TARGET PORT IDENTIFIER to identify
* the Target Port in question for the the incoming
* SET_TARGET_PORT_GROUPS op.
*/
rtpi = get_unaligned_be16(ptr + 2);
/*
* Locate the matching relative target port identifer
* for the struct se_device storage object.
*/
spin_lock(&dev->se_port_lock);
list_for_each_entry(port, &dev->dev_sep_list,
sep_list) {
if (port->sep_rtpi != rtpi)
continue;
tg_pt_gp_mem = port->sep_alua_tg_pt_gp_mem;
spin_unlock(&dev->se_port_lock);
rc = core_alua_set_tg_pt_secondary_state(
tg_pt_gp_mem, port, 1, 1);
spin_lock(&dev->se_port_lock);
break;
}
spin_unlock(&dev->se_port_lock);
/*
* If not matching relative target port identifier can
* be located, throw an exception with ASCQ:
* INVALID_PARAMETER_LIST
*/
if (rc != 0)
return PYX_TRANSPORT_INVALID_PARAMETER_LIST;
}
ptr += 4;
len += 4;
}
return 0;
}
static inline int core_alua_state_nonoptimized(
struct se_cmd *cmd,
unsigned char *cdb,
int nonop_delay_msecs,
u8 *alua_ascq)
{
/*
* Set SCF_ALUA_NON_OPTIMIZED here, this value will be checked
* later to determine if processing of this cmd needs to be
* temporarily delayed for the Active/NonOptimized primary access state.
*/
cmd->se_cmd_flags |= SCF_ALUA_NON_OPTIMIZED;
cmd->alua_nonop_delay = nonop_delay_msecs;
return 0;
}
static inline int core_alua_state_standby(
struct se_cmd *cmd,
unsigned char *cdb,
u8 *alua_ascq)
{
/*
* Allowed CDBs for ALUA_ACCESS_STATE_STANDBY as defined by
* spc4r17 section 5.9.2.4.4
*/
switch (cdb[0]) {
case INQUIRY:
case LOG_SELECT:
case LOG_SENSE:
case MODE_SELECT:
case MODE_SENSE:
case REPORT_LUNS:
case RECEIVE_DIAGNOSTIC:
case SEND_DIAGNOSTIC:
return 0;
case MAINTENANCE_IN:
switch (cdb[1]) {
case MI_REPORT_TARGET_PGS:
return 0;
default:
*alua_ascq = ASCQ_04H_ALUA_TG_PT_STANDBY;
return 1;
}
case MAINTENANCE_OUT:
switch (cdb[1]) {
case MO_SET_TARGET_PGS:
return 0;
default:
*alua_ascq = ASCQ_04H_ALUA_TG_PT_STANDBY;
return 1;
}
case REQUEST_SENSE:
case PERSISTENT_RESERVE_IN:
case PERSISTENT_RESERVE_OUT:
case READ_BUFFER:
case WRITE_BUFFER:
return 0;
default:
*alua_ascq = ASCQ_04H_ALUA_TG_PT_STANDBY;
return 1;
}
return 0;
}
static inline int core_alua_state_unavailable(
struct se_cmd *cmd,
unsigned char *cdb,
u8 *alua_ascq)
{
/*
* Allowed CDBs for ALUA_ACCESS_STATE_UNAVAILABLE as defined by
* spc4r17 section 5.9.2.4.5
*/
switch (cdb[0]) {
case INQUIRY:
case REPORT_LUNS:
return 0;
case MAINTENANCE_IN:
switch (cdb[1]) {
case MI_REPORT_TARGET_PGS:
return 0;
default:
*alua_ascq = ASCQ_04H_ALUA_TG_PT_UNAVAILABLE;
return 1;
}
case MAINTENANCE_OUT:
switch (cdb[1]) {
case MO_SET_TARGET_PGS:
return 0;
default:
*alua_ascq = ASCQ_04H_ALUA_TG_PT_UNAVAILABLE;
return 1;
}
case REQUEST_SENSE:
case READ_BUFFER:
case WRITE_BUFFER:
return 0;
default:
*alua_ascq = ASCQ_04H_ALUA_TG_PT_UNAVAILABLE;
return 1;
}
return 0;
}
static inline int core_alua_state_transition(
struct se_cmd *cmd,
unsigned char *cdb,
u8 *alua_ascq)
{
/*
* Allowed CDBs for ALUA_ACCESS_STATE_TRANSITIO as defined by
* spc4r17 section 5.9.2.5
*/
switch (cdb[0]) {
case INQUIRY:
case REPORT_LUNS:
return 0;
case MAINTENANCE_IN:
switch (cdb[1]) {
case MI_REPORT_TARGET_PGS:
return 0;
default:
*alua_ascq = ASCQ_04H_ALUA_STATE_TRANSITION;
return 1;
}
case REQUEST_SENSE:
case READ_BUFFER:
case WRITE_BUFFER:
return 0;
default:
*alua_ascq = ASCQ_04H_ALUA_STATE_TRANSITION;
return 1;
}
return 0;
}
/*
* Used for alua_type SPC_ALUA_PASSTHROUGH and SPC2_ALUA_DISABLED
* in transport_cmd_sequencer(). This function is assigned to
* struct t10_alua *->state_check() in core_setup_alua()
*/
static int core_alua_state_check_nop(
struct se_cmd *cmd,
unsigned char *cdb,
u8 *alua_ascq)
{
return 0;
}
/*
* Used for alua_type SPC3_ALUA_EMULATED in transport_cmd_sequencer().
* This function is assigned to struct t10_alua *->state_check() in
* core_setup_alua()
*
* Also, this function can return three different return codes to
* signal transport_generic_cmd_sequencer()
*
* return 1: Is used to signal LUN not accecsable, and check condition/not ready
* return 0: Used to signal success
* reutrn -1: Used to signal failure, and invalid cdb field
*/
static int core_alua_state_check(
struct se_cmd *cmd,
unsigned char *cdb,
u8 *alua_ascq)
{
struct se_lun *lun = SE_LUN(cmd);
struct se_port *port = lun->lun_sep;
struct t10_alua_tg_pt_gp *tg_pt_gp;
struct t10_alua_tg_pt_gp_member *tg_pt_gp_mem;
int out_alua_state, nonop_delay_msecs;
if (!(port))
return 0;
/*
* First, check for a struct se_port specific secondary ALUA target port
* access state: OFFLINE
*/
if (atomic_read(&port->sep_tg_pt_secondary_offline)) {
*alua_ascq = ASCQ_04H_ALUA_OFFLINE;
printk(KERN_INFO "ALUA: Got secondary offline status for local"
" target port\n");
*alua_ascq = ASCQ_04H_ALUA_OFFLINE;
return 1;
}
/*
* Second, obtain the struct t10_alua_tg_pt_gp_member pointer to the
* ALUA target port group, to obtain current ALUA access state.
* Otherwise look for the underlying struct se_device association with
* a ALUA logical unit group.
*/
tg_pt_gp_mem = port->sep_alua_tg_pt_gp_mem;
spin_lock(&tg_pt_gp_mem->tg_pt_gp_mem_lock);
tg_pt_gp = tg_pt_gp_mem->tg_pt_gp;
out_alua_state = atomic_read(&tg_pt_gp->tg_pt_gp_alua_access_state);
nonop_delay_msecs = tg_pt_gp->tg_pt_gp_nonop_delay_msecs;
spin_unlock(&tg_pt_gp_mem->tg_pt_gp_mem_lock);
/*
* Process ALUA_ACCESS_STATE_ACTIVE_OPTMIZED in a separate conditional
* statement so the compiler knows explicitly to check this case first.
* For the Optimized ALUA access state case, we want to process the
* incoming fabric cmd ASAP..
*/
if (out_alua_state == ALUA_ACCESS_STATE_ACTIVE_OPTMIZED)
return 0;
switch (out_alua_state) {
case ALUA_ACCESS_STATE_ACTIVE_NON_OPTIMIZED:
return core_alua_state_nonoptimized(cmd, cdb,
nonop_delay_msecs, alua_ascq);
case ALUA_ACCESS_STATE_STANDBY:
return core_alua_state_standby(cmd, cdb, alua_ascq);
case ALUA_ACCESS_STATE_UNAVAILABLE:
return core_alua_state_unavailable(cmd, cdb, alua_ascq);
case ALUA_ACCESS_STATE_TRANSITION:
return core_alua_state_transition(cmd, cdb, alua_ascq);
/*
* OFFLINE is a secondary ALUA target port group access state, that is
* handled above with struct se_port->sep_tg_pt_secondary_offline=1
*/
case ALUA_ACCESS_STATE_OFFLINE:
default:
printk(KERN_ERR "Unknown ALUA access state: 0x%02x\n",
out_alua_state);
return -1;
}
return 0;
}
/*
* Check implict and explict ALUA state change request.
*/
static int core_alua_check_transition(int state, int *primary)
{
switch (state) {
case ALUA_ACCESS_STATE_ACTIVE_OPTMIZED:
case ALUA_ACCESS_STATE_ACTIVE_NON_OPTIMIZED:
case ALUA_ACCESS_STATE_STANDBY:
case ALUA_ACCESS_STATE_UNAVAILABLE:
/*
* OPTIMIZED, NON-OPTIMIZED, STANDBY and UNAVAILABLE are
* defined as primary target port asymmetric access states.
*/
*primary = 1;
break;
case ALUA_ACCESS_STATE_OFFLINE:
/*
* OFFLINE state is defined as a secondary target port
* asymmetric access state.
*/
*primary = 0;
break;
default:
printk(KERN_ERR "Unknown ALUA access state: 0x%02x\n", state);
return -1;
}
return 0;
}
static char *core_alua_dump_state(int state)
{
switch (state) {
case ALUA_ACCESS_STATE_ACTIVE_OPTMIZED:
return "Active/Optimized";
case ALUA_ACCESS_STATE_ACTIVE_NON_OPTIMIZED:
return "Active/NonOptimized";
case ALUA_ACCESS_STATE_STANDBY:
return "Standby";
case ALUA_ACCESS_STATE_UNAVAILABLE:
return "Unavailable";
case ALUA_ACCESS_STATE_OFFLINE:
return "Offline";
default:
return "Unknown";
}
return NULL;
}
char *core_alua_dump_status(int status)
{
switch (status) {
case ALUA_STATUS_NONE:
return "None";
case ALUA_STATUS_ALTERED_BY_EXPLICT_STPG:
return "Altered by Explict STPG";
case ALUA_STATUS_ALTERED_BY_IMPLICT_ALUA:
return "Altered by Implict ALUA";
default:
return "Unknown";
}
return NULL;
}
/*
* Used by fabric modules to determine when we need to delay processing
* for the Active/NonOptimized paths..
*/
int core_alua_check_nonop_delay(
struct se_cmd *cmd)
{
if (!(cmd->se_cmd_flags & SCF_ALUA_NON_OPTIMIZED))
return 0;
if (in_interrupt())
return 0;
/*
* The ALUA Active/NonOptimized access state delay can be disabled
* in via configfs with a value of zero
*/
if (!(cmd->alua_nonop_delay))
return 0;
/*
* struct se_cmd->alua_nonop_delay gets set by a target port group
* defined interval in core_alua_state_nonoptimized()
*/
msleep_interruptible(cmd->alua_nonop_delay);
return 0;
}
EXPORT_SYMBOL(core_alua_check_nonop_delay);
/*
* Called with tg_pt_gp->tg_pt_gp_md_mutex or tg_pt_gp_mem->sep_tg_pt_md_mutex
*
*/
static int core_alua_write_tpg_metadata(
const char *path,
unsigned char *md_buf,
u32 md_buf_len)
{
mm_segment_t old_fs;
struct file *file;
struct iovec iov[1];
int flags = O_RDWR | O_CREAT | O_TRUNC, ret;
memset(iov, 0, sizeof(struct iovec));
file = filp_open(path, flags, 0600);
if (IS_ERR(file) || !file || !file->f_dentry) {
printk(KERN_ERR "filp_open(%s) for ALUA metadata failed\n",
path);
return -ENODEV;
}
iov[0].iov_base = &md_buf[0];
iov[0].iov_len = md_buf_len;
old_fs = get_fs();
set_fs(get_ds());
ret = vfs_writev(file, &iov[0], 1, &file->f_pos);
set_fs(old_fs);
if (ret < 0) {
printk(KERN_ERR "Error writing ALUA metadata file: %s\n", path);
filp_close(file, NULL);
return -EIO;
}
filp_close(file, NULL);
return 0;
}
/*
* Called with tg_pt_gp->tg_pt_gp_md_mutex held
*/
static int core_alua_update_tpg_primary_metadata(
struct t10_alua_tg_pt_gp *tg_pt_gp,
int primary_state,
unsigned char *md_buf)
{
struct se_subsystem_dev *su_dev = tg_pt_gp->tg_pt_gp_su_dev;
struct t10_wwn *wwn = &su_dev->t10_wwn;
char path[ALUA_METADATA_PATH_LEN];
int len;
memset(path, 0, ALUA_METADATA_PATH_LEN);
len = snprintf(md_buf, tg_pt_gp->tg_pt_gp_md_buf_len,
"tg_pt_gp_id=%hu\n"
"alua_access_state=0x%02x\n"
"alua_access_status=0x%02x\n",
tg_pt_gp->tg_pt_gp_id, primary_state,
tg_pt_gp->tg_pt_gp_alua_access_status);
snprintf(path, ALUA_METADATA_PATH_LEN,
"/var/target/alua/tpgs_%s/%s", &wwn->unit_serial[0],
config_item_name(&tg_pt_gp->tg_pt_gp_group.cg_item));
return core_alua_write_tpg_metadata(path, md_buf, len);
}
static int core_alua_do_transition_tg_pt(
struct t10_alua_tg_pt_gp *tg_pt_gp,
struct se_port *l_port,
struct se_node_acl *nacl,
unsigned char *md_buf,
int new_state,
int explict)
{
struct se_dev_entry *se_deve;
struct se_lun_acl *lacl;
struct se_port *port;
struct t10_alua_tg_pt_gp_member *mem;
int old_state = 0;
/*
* Save the old primary ALUA access state, and set the current state
* to ALUA_ACCESS_STATE_TRANSITION.
*/
old_state = atomic_read(&tg_pt_gp->tg_pt_gp_alua_access_state);
atomic_set(&tg_pt_gp->tg_pt_gp_alua_access_state,
ALUA_ACCESS_STATE_TRANSITION);
tg_pt_gp->tg_pt_gp_alua_access_status = (explict) ?
ALUA_STATUS_ALTERED_BY_EXPLICT_STPG :
ALUA_STATUS_ALTERED_BY_IMPLICT_ALUA;
/*
* Check for the optional ALUA primary state transition delay
*/
if (tg_pt_gp->tg_pt_gp_trans_delay_msecs != 0)
msleep_interruptible(tg_pt_gp->tg_pt_gp_trans_delay_msecs);
spin_lock(&tg_pt_gp->tg_pt_gp_lock);
list_for_each_entry(mem, &tg_pt_gp->tg_pt_gp_mem_list,
tg_pt_gp_mem_list) {
port = mem->tg_pt;
/*
* After an implicit target port asymmetric access state
* change, a device server shall establish a unit attention
* condition for the initiator port associated with every I_T
* nexus with the additional sense code set to ASYMMETRIC
* ACCESS STATE CHAGED.
*
* After an explicit target port asymmetric access state
* change, a device server shall establish a unit attention
* condition with the additional sense code set to ASYMMETRIC
* ACCESS STATE CHANGED for the initiator port associated with
* every I_T nexus other than the I_T nexus on which the SET
* TARGET PORT GROUPS command
*/
atomic_inc(&mem->tg_pt_gp_mem_ref_cnt);
smp_mb__after_atomic_inc();
spin_unlock(&tg_pt_gp->tg_pt_gp_lock);
spin_lock_bh(&port->sep_alua_lock);
list_for_each_entry(se_deve, &port->sep_alua_list,
alua_port_list) {
lacl = se_deve->se_lun_acl;
/*
* se_deve->se_lun_acl pointer may be NULL for a
* entry created without explict Node+MappedLUN ACLs
*/
if (!(lacl))
continue;
if (explict &&
(nacl != NULL) && (nacl == lacl->se_lun_nacl) &&
(l_port != NULL) && (l_port == port))
continue;
core_scsi3_ua_allocate(lacl->se_lun_nacl,
se_deve->mapped_lun, 0x2A,
ASCQ_2AH_ASYMMETRIC_ACCESS_STATE_CHANGED);
}
spin_unlock_bh(&port->sep_alua_lock);
spin_lock(&tg_pt_gp->tg_pt_gp_lock);
atomic_dec(&mem->tg_pt_gp_mem_ref_cnt);
smp_mb__after_atomic_dec();
}
spin_unlock(&tg_pt_gp->tg_pt_gp_lock);
/*
* Update the ALUA metadata buf that has been allocated in
* core_alua_do_port_transition(), this metadata will be written
* to struct file.
*
* Note that there is the case where we do not want to update the
* metadata when the saved metadata is being parsed in userspace
* when setting the existing port access state and access status.
*
* Also note that the failure to write out the ALUA metadata to
* struct file does NOT affect the actual ALUA transition.
*/
if (tg_pt_gp->tg_pt_gp_write_metadata) {
mutex_lock(&tg_pt_gp->tg_pt_gp_md_mutex);
core_alua_update_tpg_primary_metadata(tg_pt_gp,
new_state, md_buf);
mutex_unlock(&tg_pt_gp->tg_pt_gp_md_mutex);
}
/*
* Set the current primary ALUA access state to the requested new state
*/
atomic_set(&tg_pt_gp->tg_pt_gp_alua_access_state, new_state);
printk(KERN_INFO "Successful %s ALUA transition TG PT Group: %s ID: %hu"
" from primary access state %s to %s\n", (explict) ? "explict" :
"implict", config_item_name(&tg_pt_gp->tg_pt_gp_group.cg_item),
tg_pt_gp->tg_pt_gp_id, core_alua_dump_state(old_state),
core_alua_dump_state(new_state));
return 0;
}
int core_alua_do_port_transition(
struct t10_alua_tg_pt_gp *l_tg_pt_gp,
struct se_device *l_dev,
struct se_port *l_port,
struct se_node_acl *l_nacl,
int new_state,
int explict)
{
struct se_device *dev;
struct se_port *port;
struct se_subsystem_dev *su_dev;
struct se_node_acl *nacl;
struct t10_alua_lu_gp *lu_gp;
struct t10_alua_lu_gp_member *lu_gp_mem, *local_lu_gp_mem;
struct t10_alua_tg_pt_gp *tg_pt_gp;
unsigned char *md_buf;
int primary;
if (core_alua_check_transition(new_state, &primary) != 0)
return -EINVAL;
md_buf = kzalloc(l_tg_pt_gp->tg_pt_gp_md_buf_len, GFP_KERNEL);
if (!(md_buf)) {
printk("Unable to allocate buf for ALUA metadata\n");
return -ENOMEM;
}
local_lu_gp_mem = l_dev->dev_alua_lu_gp_mem;
spin_lock(&local_lu_gp_mem->lu_gp_mem_lock);
lu_gp = local_lu_gp_mem->lu_gp;
atomic_inc(&lu_gp->lu_gp_ref_cnt);
smp_mb__after_atomic_inc();
spin_unlock(&local_lu_gp_mem->lu_gp_mem_lock);
/*
* For storage objects that are members of the 'default_lu_gp',
* we only do transition on the passed *l_tp_pt_gp, and not
* on all of the matching target port groups IDs in default_lu_gp.
*/
if (!(lu_gp->lu_gp_id)) {
/*
* core_alua_do_transition_tg_pt() will always return
* success.
*/
core_alua_do_transition_tg_pt(l_tg_pt_gp, l_port, l_nacl,
md_buf, new_state, explict);
atomic_dec(&lu_gp->lu_gp_ref_cnt);
smp_mb__after_atomic_dec();
kfree(md_buf);
return 0;
}
/*
* For all other LU groups aside from 'default_lu_gp', walk all of
* the associated storage objects looking for a matching target port
* group ID from the local target port group.
*/
spin_lock(&lu_gp->lu_gp_lock);
list_for_each_entry(lu_gp_mem, &lu_gp->lu_gp_mem_list,
lu_gp_mem_list) {
dev = lu_gp_mem->lu_gp_mem_dev;
su_dev = dev->se_sub_dev;
atomic_inc(&lu_gp_mem->lu_gp_mem_ref_cnt);
smp_mb__after_atomic_inc();
spin_unlock(&lu_gp->lu_gp_lock);
spin_lock(&T10_ALUA(su_dev)->tg_pt_gps_lock);
list_for_each_entry(tg_pt_gp,
&T10_ALUA(su_dev)->tg_pt_gps_list,
tg_pt_gp_list) {
if (!(tg_pt_gp->tg_pt_gp_valid_id))
continue;
/*
* If the target behavior port asymmetric access state
* is changed for any target port group accessiable via
* a logical unit within a LU group, the target port
* behavior group asymmetric access states for the same
* target port group accessible via other logical units
* in that LU group will also change.
*/
if (l_tg_pt_gp->tg_pt_gp_id != tg_pt_gp->tg_pt_gp_id)
continue;
if (l_tg_pt_gp == tg_pt_gp) {
port = l_port;
nacl = l_nacl;
} else {
port = NULL;
nacl = NULL;
}
atomic_inc(&tg_pt_gp->tg_pt_gp_ref_cnt);
smp_mb__after_atomic_inc();
spin_unlock(&T10_ALUA(su_dev)->tg_pt_gps_lock);
/*
* core_alua_do_transition_tg_pt() will always return
* success.
*/
core_alua_do_transition_tg_pt(tg_pt_gp, port,
nacl, md_buf, new_state, explict);
spin_lock(&T10_ALUA(su_dev)->tg_pt_gps_lock);
atomic_dec(&tg_pt_gp->tg_pt_gp_ref_cnt);
smp_mb__after_atomic_dec();
}
spin_unlock(&T10_ALUA(su_dev)->tg_pt_gps_lock);
spin_lock(&lu_gp->lu_gp_lock);
atomic_dec(&lu_gp_mem->lu_gp_mem_ref_cnt);
smp_mb__after_atomic_dec();
}
spin_unlock(&lu_gp->lu_gp_lock);
printk(KERN_INFO "Successfully processed LU Group: %s all ALUA TG PT"
" Group IDs: %hu %s transition to primary state: %s\n",
config_item_name(&lu_gp->lu_gp_group.cg_item),
l_tg_pt_gp->tg_pt_gp_id, (explict) ? "explict" : "implict",
core_alua_dump_state(new_state));
atomic_dec(&lu_gp->lu_gp_ref_cnt);
smp_mb__after_atomic_dec();
kfree(md_buf);
return 0;
}
/*
* Called with tg_pt_gp_mem->sep_tg_pt_md_mutex held
*/
static int core_alua_update_tpg_secondary_metadata(
struct t10_alua_tg_pt_gp_member *tg_pt_gp_mem,
struct se_port *port,
unsigned char *md_buf,
u32 md_buf_len)
{
struct se_portal_group *se_tpg = port->sep_tpg;
char path[ALUA_METADATA_PATH_LEN], wwn[ALUA_SECONDARY_METADATA_WWN_LEN];
int len;
memset(path, 0, ALUA_METADATA_PATH_LEN);
memset(wwn, 0, ALUA_SECONDARY_METADATA_WWN_LEN);
len = snprintf(wwn, ALUA_SECONDARY_METADATA_WWN_LEN, "%s",
TPG_TFO(se_tpg)->tpg_get_wwn(se_tpg));
if (TPG_TFO(se_tpg)->tpg_get_tag != NULL)
snprintf(wwn+len, ALUA_SECONDARY_METADATA_WWN_LEN-len, "+%hu",
TPG_TFO(se_tpg)->tpg_get_tag(se_tpg));
len = snprintf(md_buf, md_buf_len, "alua_tg_pt_offline=%d\n"
"alua_tg_pt_status=0x%02x\n",
atomic_read(&port->sep_tg_pt_secondary_offline),
port->sep_tg_pt_secondary_stat);
snprintf(path, ALUA_METADATA_PATH_LEN, "/var/target/alua/%s/%s/lun_%u",
TPG_TFO(se_tpg)->get_fabric_name(), wwn,
port->sep_lun->unpacked_lun);
return core_alua_write_tpg_metadata(path, md_buf, len);
}
static int core_alua_set_tg_pt_secondary_state(
struct t10_alua_tg_pt_gp_member *tg_pt_gp_mem,
struct se_port *port,
int explict,
int offline)
{
struct t10_alua_tg_pt_gp *tg_pt_gp;
unsigned char *md_buf;
u32 md_buf_len;
int trans_delay_msecs;
spin_lock(&tg_pt_gp_mem->tg_pt_gp_mem_lock);
tg_pt_gp = tg_pt_gp_mem->tg_pt_gp;
if (!(tg_pt_gp)) {
spin_unlock(&tg_pt_gp_mem->tg_pt_gp_mem_lock);
printk(KERN_ERR "Unable to complete secondary state"
" transition\n");
return -1;
}
trans_delay_msecs = tg_pt_gp->tg_pt_gp_trans_delay_msecs;
/*
* Set the secondary ALUA target port access state to OFFLINE
* or release the previously secondary state for struct se_port
*/
if (offline)
atomic_set(&port->sep_tg_pt_secondary_offline, 1);
else
atomic_set(&port->sep_tg_pt_secondary_offline, 0);
md_buf_len = tg_pt_gp->tg_pt_gp_md_buf_len;
port->sep_tg_pt_secondary_stat = (explict) ?
ALUA_STATUS_ALTERED_BY_EXPLICT_STPG :
ALUA_STATUS_ALTERED_BY_IMPLICT_ALUA;
printk(KERN_INFO "Successful %s ALUA transition TG PT Group: %s ID: %hu"
" to secondary access state: %s\n", (explict) ? "explict" :
"implict", config_item_name(&tg_pt_gp->tg_pt_gp_group.cg_item),
tg_pt_gp->tg_pt_gp_id, (offline) ? "OFFLINE" : "ONLINE");
spin_unlock(&tg_pt_gp_mem->tg_pt_gp_mem_lock);
/*
* Do the optional transition delay after we set the secondary
* ALUA access state.
*/
if (trans_delay_msecs != 0)
msleep_interruptible(trans_delay_msecs);
/*
* See if we need to update the ALUA fabric port metadata for
* secondary state and status
*/
if (port->sep_tg_pt_secondary_write_md) {
md_buf = kzalloc(md_buf_len, GFP_KERNEL);
if (!(md_buf)) {
printk(KERN_ERR "Unable to allocate md_buf for"
" secondary ALUA access metadata\n");
return -1;
}
mutex_lock(&port->sep_tg_pt_md_mutex);
core_alua_update_tpg_secondary_metadata(tg_pt_gp_mem, port,
md_buf, md_buf_len);
mutex_unlock(&port->sep_tg_pt_md_mutex);
kfree(md_buf);
}
return 0;
}
struct t10_alua_lu_gp *
core_alua_allocate_lu_gp(const char *name, int def_group)
{
struct t10_alua_lu_gp *lu_gp;
lu_gp = kmem_cache_zalloc(t10_alua_lu_gp_cache, GFP_KERNEL);
if (!(lu_gp)) {
printk(KERN_ERR "Unable to allocate struct t10_alua_lu_gp\n");
return ERR_PTR(-ENOMEM);
}
INIT_LIST_HEAD(&lu_gp->lu_gp_list);
INIT_LIST_HEAD(&lu_gp->lu_gp_mem_list);
spin_lock_init(&lu_gp->lu_gp_lock);
atomic_set(&lu_gp->lu_gp_ref_cnt, 0);
if (def_group) {
lu_gp->lu_gp_id = se_global->alua_lu_gps_counter++;
lu_gp->lu_gp_valid_id = 1;
se_global->alua_lu_gps_count++;
}
return lu_gp;
}
int core_alua_set_lu_gp_id(struct t10_alua_lu_gp *lu_gp, u16 lu_gp_id)
{
struct t10_alua_lu_gp *lu_gp_tmp;
u16 lu_gp_id_tmp;
/*
* The lu_gp->lu_gp_id may only be set once..
*/
if (lu_gp->lu_gp_valid_id) {
printk(KERN_WARNING "ALUA LU Group already has a valid ID,"
" ignoring request\n");
return -1;
}
spin_lock(&se_global->lu_gps_lock);
if (se_global->alua_lu_gps_count == 0x0000ffff) {
printk(KERN_ERR "Maximum ALUA se_global->alua_lu_gps_count:"
" 0x0000ffff reached\n");
spin_unlock(&se_global->lu_gps_lock);
kmem_cache_free(t10_alua_lu_gp_cache, lu_gp);
return -1;
}
again:
lu_gp_id_tmp = (lu_gp_id != 0) ? lu_gp_id :
se_global->alua_lu_gps_counter++;
list_for_each_entry(lu_gp_tmp, &se_global->g_lu_gps_list, lu_gp_list) {
if (lu_gp_tmp->lu_gp_id == lu_gp_id_tmp) {
if (!(lu_gp_id))
goto again;
printk(KERN_WARNING "ALUA Logical Unit Group ID: %hu"
" already exists, ignoring request\n",
lu_gp_id);
spin_unlock(&se_global->lu_gps_lock);
return -1;
}
}
lu_gp->lu_gp_id = lu_gp_id_tmp;
lu_gp->lu_gp_valid_id = 1;
list_add_tail(&lu_gp->lu_gp_list, &se_global->g_lu_gps_list);
se_global->alua_lu_gps_count++;
spin_unlock(&se_global->lu_gps_lock);
return 0;
}
static struct t10_alua_lu_gp_member *
core_alua_allocate_lu_gp_mem(struct se_device *dev)
{
struct t10_alua_lu_gp_member *lu_gp_mem;
lu_gp_mem = kmem_cache_zalloc(t10_alua_lu_gp_mem_cache, GFP_KERNEL);
if (!(lu_gp_mem)) {
printk(KERN_ERR "Unable to allocate struct t10_alua_lu_gp_member\n");
return ERR_PTR(-ENOMEM);
}
INIT_LIST_HEAD(&lu_gp_mem->lu_gp_mem_list);
spin_lock_init(&lu_gp_mem->lu_gp_mem_lock);
atomic_set(&lu_gp_mem->lu_gp_mem_ref_cnt, 0);
lu_gp_mem->lu_gp_mem_dev = dev;
dev->dev_alua_lu_gp_mem = lu_gp_mem;
return lu_gp_mem;
}
void core_alua_free_lu_gp(struct t10_alua_lu_gp *lu_gp)
{
struct t10_alua_lu_gp_member *lu_gp_mem, *lu_gp_mem_tmp;
/*
* Once we have reached this point, config_item_put() has
* already been called from target_core_alua_drop_lu_gp().
*
* Here, we remove the *lu_gp from the global list so that
* no associations can be made while we are releasing
* struct t10_alua_lu_gp.
*/
spin_lock(&se_global->lu_gps_lock);
atomic_set(&lu_gp->lu_gp_shutdown, 1);
list_del(&lu_gp->lu_gp_list);
se_global->alua_lu_gps_count--;
spin_unlock(&se_global->lu_gps_lock);
/*
* Allow struct t10_alua_lu_gp * referenced by core_alua_get_lu_gp_by_name()
* in target_core_configfs.c:target_core_store_alua_lu_gp() to be
* released with core_alua_put_lu_gp_from_name()
*/
while (atomic_read(&lu_gp->lu_gp_ref_cnt))
cpu_relax();
/*
* Release reference to struct t10_alua_lu_gp * from all associated
* struct se_device.
*/
spin_lock(&lu_gp->lu_gp_lock);
list_for_each_entry_safe(lu_gp_mem, lu_gp_mem_tmp,
&lu_gp->lu_gp_mem_list, lu_gp_mem_list) {
if (lu_gp_mem->lu_gp_assoc) {
list_del(&lu_gp_mem->lu_gp_mem_list);
lu_gp->lu_gp_members--;
lu_gp_mem->lu_gp_assoc = 0;
}
spin_unlock(&lu_gp->lu_gp_lock);
/*
*
* lu_gp_mem is associated with a single
* struct se_device->dev_alua_lu_gp_mem, and is released when
* struct se_device is released via core_alua_free_lu_gp_mem().
*
* If the passed lu_gp does NOT match the default_lu_gp, assume
* we want to re-assocate a given lu_gp_mem with default_lu_gp.
*/
spin_lock(&lu_gp_mem->lu_gp_mem_lock);
if (lu_gp != se_global->default_lu_gp)
__core_alua_attach_lu_gp_mem(lu_gp_mem,
se_global->default_lu_gp);
else
lu_gp_mem->lu_gp = NULL;
spin_unlock(&lu_gp_mem->lu_gp_mem_lock);
spin_lock(&lu_gp->lu_gp_lock);
}
spin_unlock(&lu_gp->lu_gp_lock);
kmem_cache_free(t10_alua_lu_gp_cache, lu_gp);
}
void core_alua_free_lu_gp_mem(struct se_device *dev)
{
struct se_subsystem_dev *su_dev = dev->se_sub_dev;
struct t10_alua *alua = T10_ALUA(su_dev);
struct t10_alua_lu_gp *lu_gp;
struct t10_alua_lu_gp_member *lu_gp_mem;
if (alua->alua_type != SPC3_ALUA_EMULATED)
return;
lu_gp_mem = dev->dev_alua_lu_gp_mem;
if (!(lu_gp_mem))
return;
while (atomic_read(&lu_gp_mem->lu_gp_mem_ref_cnt))
cpu_relax();
spin_lock(&lu_gp_mem->lu_gp_mem_lock);
lu_gp = lu_gp_mem->lu_gp;
if ((lu_gp)) {
spin_lock(&lu_gp->lu_gp_lock);
if (lu_gp_mem->lu_gp_assoc) {
list_del(&lu_gp_mem->lu_gp_mem_list);
lu_gp->lu_gp_members--;
lu_gp_mem->lu_gp_assoc = 0;
}
spin_unlock(&lu_gp->lu_gp_lock);
lu_gp_mem->lu_gp = NULL;
}
spin_unlock(&lu_gp_mem->lu_gp_mem_lock);
kmem_cache_free(t10_alua_lu_gp_mem_cache, lu_gp_mem);
}
struct t10_alua_lu_gp *core_alua_get_lu_gp_by_name(const char *name)
{
struct t10_alua_lu_gp *lu_gp;
struct config_item *ci;
spin_lock(&se_global->lu_gps_lock);
list_for_each_entry(lu_gp, &se_global->g_lu_gps_list, lu_gp_list) {
if (!(lu_gp->lu_gp_valid_id))
continue;
ci = &lu_gp->lu_gp_group.cg_item;
if (!(strcmp(config_item_name(ci), name))) {
atomic_inc(&lu_gp->lu_gp_ref_cnt);
spin_unlock(&se_global->lu_gps_lock);
return lu_gp;
}
}
spin_unlock(&se_global->lu_gps_lock);
return NULL;
}
void core_alua_put_lu_gp_from_name(struct t10_alua_lu_gp *lu_gp)
{
spin_lock(&se_global->lu_gps_lock);
atomic_dec(&lu_gp->lu_gp_ref_cnt);
spin_unlock(&se_global->lu_gps_lock);
}
/*
* Called with struct t10_alua_lu_gp_member->lu_gp_mem_lock
*/
void __core_alua_attach_lu_gp_mem(
struct t10_alua_lu_gp_member *lu_gp_mem,
struct t10_alua_lu_gp *lu_gp)
{
spin_lock(&lu_gp->lu_gp_lock);
lu_gp_mem->lu_gp = lu_gp;
lu_gp_mem->lu_gp_assoc = 1;
list_add_tail(&lu_gp_mem->lu_gp_mem_list, &lu_gp->lu_gp_mem_list);
lu_gp->lu_gp_members++;
spin_unlock(&lu_gp->lu_gp_lock);
}
/*
* Called with struct t10_alua_lu_gp_member->lu_gp_mem_lock
*/
void __core_alua_drop_lu_gp_mem(
struct t10_alua_lu_gp_member *lu_gp_mem,
struct t10_alua_lu_gp *lu_gp)
{
spin_lock(&lu_gp->lu_gp_lock);
list_del(&lu_gp_mem->lu_gp_mem_list);
lu_gp_mem->lu_gp = NULL;
lu_gp_mem->lu_gp_assoc = 0;
lu_gp->lu_gp_members--;
spin_unlock(&lu_gp->lu_gp_lock);
}
struct t10_alua_tg_pt_gp *core_alua_allocate_tg_pt_gp(
struct se_subsystem_dev *su_dev,
const char *name,
int def_group)
{
struct t10_alua_tg_pt_gp *tg_pt_gp;
tg_pt_gp = kmem_cache_zalloc(t10_alua_tg_pt_gp_cache, GFP_KERNEL);
if (!(tg_pt_gp)) {
printk(KERN_ERR "Unable to allocate struct t10_alua_tg_pt_gp\n");
return NULL;
}
INIT_LIST_HEAD(&tg_pt_gp->tg_pt_gp_list);
INIT_LIST_HEAD(&tg_pt_gp->tg_pt_gp_mem_list);
mutex_init(&tg_pt_gp->tg_pt_gp_md_mutex);
spin_lock_init(&tg_pt_gp->tg_pt_gp_lock);
atomic_set(&tg_pt_gp->tg_pt_gp_ref_cnt, 0);
tg_pt_gp->tg_pt_gp_su_dev = su_dev;
tg_pt_gp->tg_pt_gp_md_buf_len = ALUA_MD_BUF_LEN;
atomic_set(&tg_pt_gp->tg_pt_gp_alua_access_state,
ALUA_ACCESS_STATE_ACTIVE_OPTMIZED);
/*
* Enable both explict and implict ALUA support by default
*/
tg_pt_gp->tg_pt_gp_alua_access_type =
TPGS_EXPLICT_ALUA | TPGS_IMPLICT_ALUA;
/*
* Set the default Active/NonOptimized Delay in milliseconds
*/
tg_pt_gp->tg_pt_gp_nonop_delay_msecs = ALUA_DEFAULT_NONOP_DELAY_MSECS;
tg_pt_gp->tg_pt_gp_trans_delay_msecs = ALUA_DEFAULT_TRANS_DELAY_MSECS;
if (def_group) {
spin_lock(&T10_ALUA(su_dev)->tg_pt_gps_lock);
tg_pt_gp->tg_pt_gp_id =
T10_ALUA(su_dev)->alua_tg_pt_gps_counter++;
tg_pt_gp->tg_pt_gp_valid_id = 1;
T10_ALUA(su_dev)->alua_tg_pt_gps_count++;
list_add_tail(&tg_pt_gp->tg_pt_gp_list,
&T10_ALUA(su_dev)->tg_pt_gps_list);
spin_unlock(&T10_ALUA(su_dev)->tg_pt_gps_lock);
}
return tg_pt_gp;
}
int core_alua_set_tg_pt_gp_id(
struct t10_alua_tg_pt_gp *tg_pt_gp,
u16 tg_pt_gp_id)
{
struct se_subsystem_dev *su_dev = tg_pt_gp->tg_pt_gp_su_dev;
struct t10_alua_tg_pt_gp *tg_pt_gp_tmp;
u16 tg_pt_gp_id_tmp;
/*
* The tg_pt_gp->tg_pt_gp_id may only be set once..
*/
if (tg_pt_gp->tg_pt_gp_valid_id) {
printk(KERN_WARNING "ALUA TG PT Group already has a valid ID,"
" ignoring request\n");
return -1;
}
spin_lock(&T10_ALUA(su_dev)->tg_pt_gps_lock);
if (T10_ALUA(su_dev)->alua_tg_pt_gps_count == 0x0000ffff) {
printk(KERN_ERR "Maximum ALUA alua_tg_pt_gps_count:"
" 0x0000ffff reached\n");
spin_unlock(&T10_ALUA(su_dev)->tg_pt_gps_lock);
kmem_cache_free(t10_alua_tg_pt_gp_cache, tg_pt_gp);
return -1;
}
again:
tg_pt_gp_id_tmp = (tg_pt_gp_id != 0) ? tg_pt_gp_id :
T10_ALUA(su_dev)->alua_tg_pt_gps_counter++;
list_for_each_entry(tg_pt_gp_tmp, &T10_ALUA(su_dev)->tg_pt_gps_list,
tg_pt_gp_list) {
if (tg_pt_gp_tmp->tg_pt_gp_id == tg_pt_gp_id_tmp) {
if (!(tg_pt_gp_id))
goto again;
printk(KERN_ERR "ALUA Target Port Group ID: %hu already"
" exists, ignoring request\n", tg_pt_gp_id);
spin_unlock(&T10_ALUA(su_dev)->tg_pt_gps_lock);
return -1;
}
}
tg_pt_gp->tg_pt_gp_id = tg_pt_gp_id_tmp;
tg_pt_gp->tg_pt_gp_valid_id = 1;
list_add_tail(&tg_pt_gp->tg_pt_gp_list,
&T10_ALUA(su_dev)->tg_pt_gps_list);
T10_ALUA(su_dev)->alua_tg_pt_gps_count++;
spin_unlock(&T10_ALUA(su_dev)->tg_pt_gps_lock);
return 0;
}
struct t10_alua_tg_pt_gp_member *core_alua_allocate_tg_pt_gp_mem(
struct se_port *port)
{
struct t10_alua_tg_pt_gp_member *tg_pt_gp_mem;
tg_pt_gp_mem = kmem_cache_zalloc(t10_alua_tg_pt_gp_mem_cache,
GFP_KERNEL);
if (!(tg_pt_gp_mem)) {
printk(KERN_ERR "Unable to allocate struct t10_alua_tg_pt_gp_member\n");
return ERR_PTR(-ENOMEM);
}
INIT_LIST_HEAD(&tg_pt_gp_mem->tg_pt_gp_mem_list);
spin_lock_init(&tg_pt_gp_mem->tg_pt_gp_mem_lock);
atomic_set(&tg_pt_gp_mem->tg_pt_gp_mem_ref_cnt, 0);
tg_pt_gp_mem->tg_pt = port;
port->sep_alua_tg_pt_gp_mem = tg_pt_gp_mem;
atomic_set(&port->sep_tg_pt_gp_active, 1);
return tg_pt_gp_mem;
}
void core_alua_free_tg_pt_gp(
struct t10_alua_tg_pt_gp *tg_pt_gp)
{
struct se_subsystem_dev *su_dev = tg_pt_gp->tg_pt_gp_su_dev;
struct t10_alua_tg_pt_gp_member *tg_pt_gp_mem, *tg_pt_gp_mem_tmp;
/*
* Once we have reached this point, config_item_put() has already
* been called from target_core_alua_drop_tg_pt_gp().
*
* Here we remove *tg_pt_gp from the global list so that
* no assications *OR* explict ALUA via SET_TARGET_PORT_GROUPS
* can be made while we are releasing struct t10_alua_tg_pt_gp.
*/
spin_lock(&T10_ALUA(su_dev)->tg_pt_gps_lock);
list_del(&tg_pt_gp->tg_pt_gp_list);
T10_ALUA(su_dev)->alua_tg_pt_gps_counter--;
spin_unlock(&T10_ALUA(su_dev)->tg_pt_gps_lock);
/*
* Allow a struct t10_alua_tg_pt_gp_member * referenced by
* core_alua_get_tg_pt_gp_by_name() in
* target_core_configfs.c:target_core_store_alua_tg_pt_gp()
* to be released with core_alua_put_tg_pt_gp_from_name().
*/
while (atomic_read(&tg_pt_gp->tg_pt_gp_ref_cnt))
cpu_relax();
/*
* Release reference to struct t10_alua_tg_pt_gp from all associated
* struct se_port.
*/
spin_lock(&tg_pt_gp->tg_pt_gp_lock);
list_for_each_entry_safe(tg_pt_gp_mem, tg_pt_gp_mem_tmp,
&tg_pt_gp->tg_pt_gp_mem_list, tg_pt_gp_mem_list) {
if (tg_pt_gp_mem->tg_pt_gp_assoc) {
list_del(&tg_pt_gp_mem->tg_pt_gp_mem_list);
tg_pt_gp->tg_pt_gp_members--;
tg_pt_gp_mem->tg_pt_gp_assoc = 0;
}
spin_unlock(&tg_pt_gp->tg_pt_gp_lock);
/*
* tg_pt_gp_mem is associated with a single
* se_port->sep_alua_tg_pt_gp_mem, and is released via
* core_alua_free_tg_pt_gp_mem().
*
* If the passed tg_pt_gp does NOT match the default_tg_pt_gp,
* assume we want to re-assocate a given tg_pt_gp_mem with
* default_tg_pt_gp.
*/
spin_lock(&tg_pt_gp_mem->tg_pt_gp_mem_lock);
if (tg_pt_gp != T10_ALUA(su_dev)->default_tg_pt_gp) {
__core_alua_attach_tg_pt_gp_mem(tg_pt_gp_mem,
T10_ALUA(su_dev)->default_tg_pt_gp);
} else
tg_pt_gp_mem->tg_pt_gp = NULL;
spin_unlock(&tg_pt_gp_mem->tg_pt_gp_mem_lock);
spin_lock(&tg_pt_gp->tg_pt_gp_lock);
}
spin_unlock(&tg_pt_gp->tg_pt_gp_lock);
kmem_cache_free(t10_alua_tg_pt_gp_cache, tg_pt_gp);
}
void core_alua_free_tg_pt_gp_mem(struct se_port *port)
{
struct se_subsystem_dev *su_dev = port->sep_lun->lun_se_dev->se_sub_dev;
struct t10_alua *alua = T10_ALUA(su_dev);
struct t10_alua_tg_pt_gp *tg_pt_gp;
struct t10_alua_tg_pt_gp_member *tg_pt_gp_mem;
if (alua->alua_type != SPC3_ALUA_EMULATED)
return;
tg_pt_gp_mem = port->sep_alua_tg_pt_gp_mem;
if (!(tg_pt_gp_mem))
return;
while (atomic_read(&tg_pt_gp_mem->tg_pt_gp_mem_ref_cnt))
cpu_relax();
spin_lock(&tg_pt_gp_mem->tg_pt_gp_mem_lock);
tg_pt_gp = tg_pt_gp_mem->tg_pt_gp;
if ((tg_pt_gp)) {
spin_lock(&tg_pt_gp->tg_pt_gp_lock);
if (tg_pt_gp_mem->tg_pt_gp_assoc) {
list_del(&tg_pt_gp_mem->tg_pt_gp_mem_list);
tg_pt_gp->tg_pt_gp_members--;
tg_pt_gp_mem->tg_pt_gp_assoc = 0;
}
spin_unlock(&tg_pt_gp->tg_pt_gp_lock);
tg_pt_gp_mem->tg_pt_gp = NULL;
}
spin_unlock(&tg_pt_gp_mem->tg_pt_gp_mem_lock);
kmem_cache_free(t10_alua_tg_pt_gp_mem_cache, tg_pt_gp_mem);
}
static struct t10_alua_tg_pt_gp *core_alua_get_tg_pt_gp_by_name(
struct se_subsystem_dev *su_dev,
const char *name)
{
struct t10_alua_tg_pt_gp *tg_pt_gp;
struct config_item *ci;
spin_lock(&T10_ALUA(su_dev)->tg_pt_gps_lock);
list_for_each_entry(tg_pt_gp, &T10_ALUA(su_dev)->tg_pt_gps_list,
tg_pt_gp_list) {
if (!(tg_pt_gp->tg_pt_gp_valid_id))
continue;
ci = &tg_pt_gp->tg_pt_gp_group.cg_item;
if (!(strcmp(config_item_name(ci), name))) {
atomic_inc(&tg_pt_gp->tg_pt_gp_ref_cnt);
spin_unlock(&T10_ALUA(su_dev)->tg_pt_gps_lock);
return tg_pt_gp;
}
}
spin_unlock(&T10_ALUA(su_dev)->tg_pt_gps_lock);
return NULL;
}
static void core_alua_put_tg_pt_gp_from_name(
struct t10_alua_tg_pt_gp *tg_pt_gp)
{
struct se_subsystem_dev *su_dev = tg_pt_gp->tg_pt_gp_su_dev;
spin_lock(&T10_ALUA(su_dev)->tg_pt_gps_lock);
atomic_dec(&tg_pt_gp->tg_pt_gp_ref_cnt);
spin_unlock(&T10_ALUA(su_dev)->tg_pt_gps_lock);
}
/*
* Called with struct t10_alua_tg_pt_gp_member->tg_pt_gp_mem_lock held
*/
void __core_alua_attach_tg_pt_gp_mem(
struct t10_alua_tg_pt_gp_member *tg_pt_gp_mem,
struct t10_alua_tg_pt_gp *tg_pt_gp)
{
spin_lock(&tg_pt_gp->tg_pt_gp_lock);
tg_pt_gp_mem->tg_pt_gp = tg_pt_gp;
tg_pt_gp_mem->tg_pt_gp_assoc = 1;
list_add_tail(&tg_pt_gp_mem->tg_pt_gp_mem_list,
&tg_pt_gp->tg_pt_gp_mem_list);
tg_pt_gp->tg_pt_gp_members++;
spin_unlock(&tg_pt_gp->tg_pt_gp_lock);
}
/*
* Called with struct t10_alua_tg_pt_gp_member->tg_pt_gp_mem_lock held
*/
static void __core_alua_drop_tg_pt_gp_mem(
struct t10_alua_tg_pt_gp_member *tg_pt_gp_mem,
struct t10_alua_tg_pt_gp *tg_pt_gp)
{
spin_lock(&tg_pt_gp->tg_pt_gp_lock);
list_del(&tg_pt_gp_mem->tg_pt_gp_mem_list);
tg_pt_gp_mem->tg_pt_gp = NULL;
tg_pt_gp_mem->tg_pt_gp_assoc = 0;
tg_pt_gp->tg_pt_gp_members--;
spin_unlock(&tg_pt_gp->tg_pt_gp_lock);
}
ssize_t core_alua_show_tg_pt_gp_info(struct se_port *port, char *page)
{
struct se_subsystem_dev *su_dev = port->sep_lun->lun_se_dev->se_sub_dev;
struct config_item *tg_pt_ci;
struct t10_alua *alua = T10_ALUA(su_dev);
struct t10_alua_tg_pt_gp *tg_pt_gp;
struct t10_alua_tg_pt_gp_member *tg_pt_gp_mem;
ssize_t len = 0;
if (alua->alua_type != SPC3_ALUA_EMULATED)
return len;
tg_pt_gp_mem = port->sep_alua_tg_pt_gp_mem;
if (!(tg_pt_gp_mem))
return len;
spin_lock(&tg_pt_gp_mem->tg_pt_gp_mem_lock);
tg_pt_gp = tg_pt_gp_mem->tg_pt_gp;
if ((tg_pt_gp)) {
tg_pt_ci = &tg_pt_gp->tg_pt_gp_group.cg_item;
len += sprintf(page, "TG Port Alias: %s\nTG Port Group ID:"
" %hu\nTG Port Primary Access State: %s\nTG Port "
"Primary Access Status: %s\nTG Port Secondary Access"
" State: %s\nTG Port Secondary Access Status: %s\n",
config_item_name(tg_pt_ci), tg_pt_gp->tg_pt_gp_id,
core_alua_dump_state(atomic_read(
&tg_pt_gp->tg_pt_gp_alua_access_state)),
core_alua_dump_status(
tg_pt_gp->tg_pt_gp_alua_access_status),
(atomic_read(&port->sep_tg_pt_secondary_offline)) ?
"Offline" : "None",
core_alua_dump_status(port->sep_tg_pt_secondary_stat));
}
spin_unlock(&tg_pt_gp_mem->tg_pt_gp_mem_lock);
return len;
}
ssize_t core_alua_store_tg_pt_gp_info(
struct se_port *port,
const char *page,
size_t count)
{
struct se_portal_group *tpg;
struct se_lun *lun;
struct se_subsystem_dev *su_dev = port->sep_lun->lun_se_dev->se_sub_dev;
struct t10_alua_tg_pt_gp *tg_pt_gp = NULL, *tg_pt_gp_new = NULL;
struct t10_alua_tg_pt_gp_member *tg_pt_gp_mem;
unsigned char buf[TG_PT_GROUP_NAME_BUF];
int move = 0;
tpg = port->sep_tpg;
lun = port->sep_lun;
if (T10_ALUA(su_dev)->alua_type != SPC3_ALUA_EMULATED) {
printk(KERN_WARNING "SPC3_ALUA_EMULATED not enabled for"
" %s/tpgt_%hu/%s\n", TPG_TFO(tpg)->tpg_get_wwn(tpg),
TPG_TFO(tpg)->tpg_get_tag(tpg),
config_item_name(&lun->lun_group.cg_item));
return -EINVAL;
}
if (count > TG_PT_GROUP_NAME_BUF) {
printk(KERN_ERR "ALUA Target Port Group alias too large!\n");
return -EINVAL;
}
memset(buf, 0, TG_PT_GROUP_NAME_BUF);
memcpy(buf, page, count);
/*
* Any ALUA target port group alias besides "NULL" means we will be
* making a new group association.
*/
if (strcmp(strstrip(buf), "NULL")) {
/*
* core_alua_get_tg_pt_gp_by_name() will increment reference to
* struct t10_alua_tg_pt_gp. This reference is released with
* core_alua_put_tg_pt_gp_from_name() below.
*/
tg_pt_gp_new = core_alua_get_tg_pt_gp_by_name(su_dev,
strstrip(buf));
if (!(tg_pt_gp_new))
return -ENODEV;
}
tg_pt_gp_mem = port->sep_alua_tg_pt_gp_mem;
if (!(tg_pt_gp_mem)) {
if (tg_pt_gp_new)
core_alua_put_tg_pt_gp_from_name(tg_pt_gp_new);
printk(KERN_ERR "NULL struct se_port->sep_alua_tg_pt_gp_mem pointer\n");
return -EINVAL;
}
spin_lock(&tg_pt_gp_mem->tg_pt_gp_mem_lock);
tg_pt_gp = tg_pt_gp_mem->tg_pt_gp;
if ((tg_pt_gp)) {
/*
* Clearing an existing tg_pt_gp association, and replacing
* with the default_tg_pt_gp.
*/
if (!(tg_pt_gp_new)) {
printk(KERN_INFO "Target_Core_ConfigFS: Moving"
" %s/tpgt_%hu/%s from ALUA Target Port Group:"
" alua/%s, ID: %hu back to"
" default_tg_pt_gp\n",
TPG_TFO(tpg)->tpg_get_wwn(tpg),
TPG_TFO(tpg)->tpg_get_tag(tpg),
config_item_name(&lun->lun_group.cg_item),
config_item_name(
&tg_pt_gp->tg_pt_gp_group.cg_item),
tg_pt_gp->tg_pt_gp_id);
__core_alua_drop_tg_pt_gp_mem(tg_pt_gp_mem, tg_pt_gp);
__core_alua_attach_tg_pt_gp_mem(tg_pt_gp_mem,
T10_ALUA(su_dev)->default_tg_pt_gp);
spin_unlock(&tg_pt_gp_mem->tg_pt_gp_mem_lock);
return count;
}
/*
* Removing existing association of tg_pt_gp_mem with tg_pt_gp
*/
__core_alua_drop_tg_pt_gp_mem(tg_pt_gp_mem, tg_pt_gp);
move = 1;
}
/*
* Associate tg_pt_gp_mem with tg_pt_gp_new.
*/
__core_alua_attach_tg_pt_gp_mem(tg_pt_gp_mem, tg_pt_gp_new);
spin_unlock(&tg_pt_gp_mem->tg_pt_gp_mem_lock);
printk(KERN_INFO "Target_Core_ConfigFS: %s %s/tpgt_%hu/%s to ALUA"
" Target Port Group: alua/%s, ID: %hu\n", (move) ?
"Moving" : "Adding", TPG_TFO(tpg)->tpg_get_wwn(tpg),
TPG_TFO(tpg)->tpg_get_tag(tpg),
config_item_name(&lun->lun_group.cg_item),
config_item_name(&tg_pt_gp_new->tg_pt_gp_group.cg_item),
tg_pt_gp_new->tg_pt_gp_id);
core_alua_put_tg_pt_gp_from_name(tg_pt_gp_new);
return count;
}
ssize_t core_alua_show_access_type(
struct t10_alua_tg_pt_gp *tg_pt_gp,
char *page)
{
if ((tg_pt_gp->tg_pt_gp_alua_access_type & TPGS_EXPLICT_ALUA) &&
(tg_pt_gp->tg_pt_gp_alua_access_type & TPGS_IMPLICT_ALUA))
return sprintf(page, "Implict and Explict\n");
else if (tg_pt_gp->tg_pt_gp_alua_access_type & TPGS_IMPLICT_ALUA)
return sprintf(page, "Implict\n");
else if (tg_pt_gp->tg_pt_gp_alua_access_type & TPGS_EXPLICT_ALUA)
return sprintf(page, "Explict\n");
else
return sprintf(page, "None\n");
}
ssize_t core_alua_store_access_type(
struct t10_alua_tg_pt_gp *tg_pt_gp,
const char *page,
size_t count)
{
unsigned long tmp;
int ret;
ret = strict_strtoul(page, 0, &tmp);
if (ret < 0) {
printk(KERN_ERR "Unable to extract alua_access_type\n");
return -EINVAL;
}
if ((tmp != 0) && (tmp != 1) && (tmp != 2) && (tmp != 3)) {
printk(KERN_ERR "Illegal value for alua_access_type:"
" %lu\n", tmp);
return -EINVAL;
}
if (tmp == 3)
tg_pt_gp->tg_pt_gp_alua_access_type =
TPGS_IMPLICT_ALUA | TPGS_EXPLICT_ALUA;
else if (tmp == 2)
tg_pt_gp->tg_pt_gp_alua_access_type = TPGS_EXPLICT_ALUA;
else if (tmp == 1)
tg_pt_gp->tg_pt_gp_alua_access_type = TPGS_IMPLICT_ALUA;
else
tg_pt_gp->tg_pt_gp_alua_access_type = 0;
return count;
}
ssize_t core_alua_show_nonop_delay_msecs(
struct t10_alua_tg_pt_gp *tg_pt_gp,
char *page)
{
return sprintf(page, "%d\n", tg_pt_gp->tg_pt_gp_nonop_delay_msecs);
}
ssize_t core_alua_store_nonop_delay_msecs(
struct t10_alua_tg_pt_gp *tg_pt_gp,
const char *page,
size_t count)
{
unsigned long tmp;
int ret;
ret = strict_strtoul(page, 0, &tmp);
if (ret < 0) {
printk(KERN_ERR "Unable to extract nonop_delay_msecs\n");
return -EINVAL;
}
if (tmp > ALUA_MAX_NONOP_DELAY_MSECS) {
printk(KERN_ERR "Passed nonop_delay_msecs: %lu, exceeds"
" ALUA_MAX_NONOP_DELAY_MSECS: %d\n", tmp,
ALUA_MAX_NONOP_DELAY_MSECS);
return -EINVAL;
}
tg_pt_gp->tg_pt_gp_nonop_delay_msecs = (int)tmp;
return count;
}
ssize_t core_alua_show_trans_delay_msecs(
struct t10_alua_tg_pt_gp *tg_pt_gp,
char *page)
{
return sprintf(page, "%d\n", tg_pt_gp->tg_pt_gp_trans_delay_msecs);
}
ssize_t core_alua_store_trans_delay_msecs(
struct t10_alua_tg_pt_gp *tg_pt_gp,
const char *page,
size_t count)
{
unsigned long tmp;
int ret;
ret = strict_strtoul(page, 0, &tmp);
if (ret < 0) {
printk(KERN_ERR "Unable to extract trans_delay_msecs\n");
return -EINVAL;
}
if (tmp > ALUA_MAX_TRANS_DELAY_MSECS) {
printk(KERN_ERR "Passed trans_delay_msecs: %lu, exceeds"
" ALUA_MAX_TRANS_DELAY_MSECS: %d\n", tmp,
ALUA_MAX_TRANS_DELAY_MSECS);
return -EINVAL;
}
tg_pt_gp->tg_pt_gp_trans_delay_msecs = (int)tmp;
return count;
}
ssize_t core_alua_show_preferred_bit(
struct t10_alua_tg_pt_gp *tg_pt_gp,
char *page)
{
return sprintf(page, "%d\n", tg_pt_gp->tg_pt_gp_pref);
}
ssize_t core_alua_store_preferred_bit(
struct t10_alua_tg_pt_gp *tg_pt_gp,
const char *page,
size_t count)
{
unsigned long tmp;
int ret;
ret = strict_strtoul(page, 0, &tmp);
if (ret < 0) {
printk(KERN_ERR "Unable to extract preferred ALUA value\n");
return -EINVAL;
}
if ((tmp != 0) && (tmp != 1)) {
printk(KERN_ERR "Illegal value for preferred ALUA: %lu\n", tmp);
return -EINVAL;
}
tg_pt_gp->tg_pt_gp_pref = (int)tmp;
return count;
}
ssize_t core_alua_show_offline_bit(struct se_lun *lun, char *page)
{
if (!(lun->lun_sep))
return -ENODEV;
return sprintf(page, "%d\n",
atomic_read(&lun->lun_sep->sep_tg_pt_secondary_offline));
}
ssize_t core_alua_store_offline_bit(
struct se_lun *lun,
const char *page,
size_t count)
{
struct t10_alua_tg_pt_gp_member *tg_pt_gp_mem;
unsigned long tmp;
int ret;
if (!(lun->lun_sep))
return -ENODEV;
ret = strict_strtoul(page, 0, &tmp);
if (ret < 0) {
printk(KERN_ERR "Unable to extract alua_tg_pt_offline value\n");
return -EINVAL;
}
if ((tmp != 0) && (tmp != 1)) {
printk(KERN_ERR "Illegal value for alua_tg_pt_offline: %lu\n",
tmp);
return -EINVAL;
}
tg_pt_gp_mem = lun->lun_sep->sep_alua_tg_pt_gp_mem;
if (!(tg_pt_gp_mem)) {
printk(KERN_ERR "Unable to locate *tg_pt_gp_mem\n");
return -EINVAL;
}
ret = core_alua_set_tg_pt_secondary_state(tg_pt_gp_mem,
lun->lun_sep, 0, (int)tmp);
if (ret < 0)
return -EINVAL;
return count;
}
ssize_t core_alua_show_secondary_status(
struct se_lun *lun,
char *page)
{
return sprintf(page, "%d\n", lun->lun_sep->sep_tg_pt_secondary_stat);
}
ssize_t core_alua_store_secondary_status(
struct se_lun *lun,
const char *page,
size_t count)
{
unsigned long tmp;
int ret;
ret = strict_strtoul(page, 0, &tmp);
if (ret < 0) {
printk(KERN_ERR "Unable to extract alua_tg_pt_status\n");
return -EINVAL;
}
if ((tmp != ALUA_STATUS_NONE) &&
(tmp != ALUA_STATUS_ALTERED_BY_EXPLICT_STPG) &&
(tmp != ALUA_STATUS_ALTERED_BY_IMPLICT_ALUA)) {
printk(KERN_ERR "Illegal value for alua_tg_pt_status: %lu\n",
tmp);
return -EINVAL;
}
lun->lun_sep->sep_tg_pt_secondary_stat = (int)tmp;
return count;
}
ssize_t core_alua_show_secondary_write_metadata(
struct se_lun *lun,
char *page)
{
return sprintf(page, "%d\n",
lun->lun_sep->sep_tg_pt_secondary_write_md);
}
ssize_t core_alua_store_secondary_write_metadata(
struct se_lun *lun,
const char *page,
size_t count)
{
unsigned long tmp;
int ret;
ret = strict_strtoul(page, 0, &tmp);
if (ret < 0) {
printk(KERN_ERR "Unable to extract alua_tg_pt_write_md\n");
return -EINVAL;
}
if ((tmp != 0) && (tmp != 1)) {
printk(KERN_ERR "Illegal value for alua_tg_pt_write_md:"
" %lu\n", tmp);
return -EINVAL;
}
lun->lun_sep->sep_tg_pt_secondary_write_md = (int)tmp;
return count;
}
int core_setup_alua(struct se_device *dev, int force_pt)
{
struct se_subsystem_dev *su_dev = dev->se_sub_dev;
struct t10_alua *alua = T10_ALUA(su_dev);
struct t10_alua_lu_gp_member *lu_gp_mem;
/*
* If this device is from Target_Core_Mod/pSCSI, use the ALUA logic
* of the Underlying SCSI hardware. In Linux/SCSI terms, this can
* cause a problem because libata and some SATA RAID HBAs appear
* under Linux/SCSI, but emulate SCSI logic themselves.
*/
if (((TRANSPORT(dev)->transport_type == TRANSPORT_PLUGIN_PHBA_PDEV) &&
!(DEV_ATTRIB(dev)->emulate_alua)) || force_pt) {
alua->alua_type = SPC_ALUA_PASSTHROUGH;
alua->alua_state_check = &core_alua_state_check_nop;
printk(KERN_INFO "%s: Using SPC_ALUA_PASSTHROUGH, no ALUA"
" emulation\n", TRANSPORT(dev)->name);
return 0;
}
/*
* If SPC-3 or above is reported by real or emulated struct se_device,
* use emulated ALUA.
*/
if (TRANSPORT(dev)->get_device_rev(dev) >= SCSI_3) {
printk(KERN_INFO "%s: Enabling ALUA Emulation for SPC-3"
" device\n", TRANSPORT(dev)->name);
/*
* Associate this struct se_device with the default ALUA
* LUN Group.
*/
lu_gp_mem = core_alua_allocate_lu_gp_mem(dev);
if (IS_ERR(lu_gp_mem) || !lu_gp_mem)
return -1;
alua->alua_type = SPC3_ALUA_EMULATED;
alua->alua_state_check = &core_alua_state_check;
spin_lock(&lu_gp_mem->lu_gp_mem_lock);
__core_alua_attach_lu_gp_mem(lu_gp_mem,
se_global->default_lu_gp);
spin_unlock(&lu_gp_mem->lu_gp_mem_lock);
printk(KERN_INFO "%s: Adding to default ALUA LU Group:"
" core/alua/lu_gps/default_lu_gp\n",
TRANSPORT(dev)->name);
} else {
alua->alua_type = SPC2_ALUA_DISABLED;
alua->alua_state_check = &core_alua_state_check_nop;
printk(KERN_INFO "%s: Disabling ALUA Emulation for SPC-2"
" device\n", TRANSPORT(dev)->name);
}
return 0;
}
| gpl-2.0 |
Hani-K/H-Vitamin2_trelte | drivers/gpu/drm/nouveau/core/subdev/bios/init.c | 1633 | 51078 | #include <core/engine.h>
#include <core/device.h>
#include <subdev/bios.h>
#include <subdev/bios/bmp.h>
#include <subdev/bios/bit.h>
#include <subdev/bios/conn.h>
#include <subdev/bios/dcb.h>
#include <subdev/bios/dp.h>
#include <subdev/bios/gpio.h>
#include <subdev/bios/init.h>
#include <subdev/devinit.h>
#include <subdev/clock.h>
#include <subdev/i2c.h>
#include <subdev/vga.h>
#include <subdev/gpio.h>
#define bioslog(lvl, fmt, args...) do { \
nv_printk(init->bios, lvl, "0x%04x[%c]: "fmt, init->offset, \
init_exec(init) ? '0' + (init->nested - 1) : ' ', ##args); \
} while(0)
#define cont(fmt, args...) do { \
if (nv_subdev(init->bios)->debug >= NV_DBG_TRACE) \
printk(fmt, ##args); \
} while(0)
#define trace(fmt, args...) bioslog(TRACE, fmt, ##args)
#define warn(fmt, args...) bioslog(WARN, fmt, ##args)
#define error(fmt, args...) bioslog(ERROR, fmt, ##args)
/******************************************************************************
* init parser control flow helpers
*****************************************************************************/
static inline bool
init_exec(struct nvbios_init *init)
{
return (init->execute == 1) || ((init->execute & 5) == 5);
}
static inline void
init_exec_set(struct nvbios_init *init, bool exec)
{
if (exec) init->execute &= 0xfd;
else init->execute |= 0x02;
}
static inline void
init_exec_inv(struct nvbios_init *init)
{
init->execute ^= 0x02;
}
static inline void
init_exec_force(struct nvbios_init *init, bool exec)
{
if (exec) init->execute |= 0x04;
else init->execute &= 0xfb;
}
/******************************************************************************
* init parser wrappers for normal register/i2c/whatever accessors
*****************************************************************************/
static inline int
init_or(struct nvbios_init *init)
{
if (init_exec(init)) {
if (init->outp)
return ffs(init->outp->or) - 1;
error("script needs OR!!\n");
}
return 0;
}
static inline int
init_link(struct nvbios_init *init)
{
if (init_exec(init)) {
if (init->outp)
return !(init->outp->sorconf.link & 1);
error("script needs OR link\n");
}
return 0;
}
static inline int
init_crtc(struct nvbios_init *init)
{
if (init_exec(init)) {
if (init->crtc >= 0)
return init->crtc;
error("script needs crtc\n");
}
return 0;
}
static u8
init_conn(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 ver, len;
u16 conn;
if (init_exec(init)) {
if (init->outp) {
conn = init->outp->connector;
conn = dcb_conn(bios, conn, &ver, &len);
if (conn)
return nv_ro08(bios, conn);
}
error("script needs connector type\n");
}
return 0xff;
}
static inline u32
init_nvreg(struct nvbios_init *init, u32 reg)
{
/* C51 (at least) sometimes has the lower bits set which the VBIOS
* interprets to mean that access needs to go through certain IO
* ports instead. The NVIDIA binary driver has been seen to access
* these through the NV register address, so lets assume we can
* do the same
*/
reg &= ~0x00000003;
/* GF8+ display scripts need register addresses mangled a bit to
* select a specific CRTC/OR
*/
if (nv_device(init->bios)->card_type >= NV_50) {
if (reg & 0x80000000) {
reg += init_crtc(init) * 0x800;
reg &= ~0x80000000;
}
if (reg & 0x40000000) {
reg += init_or(init) * 0x800;
reg &= ~0x40000000;
if (reg & 0x20000000) {
reg += init_link(init) * 0x80;
reg &= ~0x20000000;
}
}
}
if (reg & ~0x00fffffc)
warn("unknown bits in register 0x%08x\n", reg);
return reg;
}
static u32
init_rd32(struct nvbios_init *init, u32 reg)
{
reg = init_nvreg(init, reg);
if (init_exec(init))
return nv_rd32(init->subdev, reg);
return 0x00000000;
}
static void
init_wr32(struct nvbios_init *init, u32 reg, u32 val)
{
reg = init_nvreg(init, reg);
if (init_exec(init))
nv_wr32(init->subdev, reg, val);
}
static u32
init_mask(struct nvbios_init *init, u32 reg, u32 mask, u32 val)
{
reg = init_nvreg(init, reg);
if (init_exec(init)) {
u32 tmp = nv_rd32(init->subdev, reg);
nv_wr32(init->subdev, reg, (tmp & ~mask) | val);
return tmp;
}
return 0x00000000;
}
static u8
init_rdport(struct nvbios_init *init, u16 port)
{
if (init_exec(init))
return nv_rdport(init->subdev, init->crtc, port);
return 0x00;
}
static void
init_wrport(struct nvbios_init *init, u16 port, u8 value)
{
if (init_exec(init))
nv_wrport(init->subdev, init->crtc, port, value);
}
static u8
init_rdvgai(struct nvbios_init *init, u16 port, u8 index)
{
struct nouveau_subdev *subdev = init->subdev;
if (init_exec(init)) {
int head = init->crtc < 0 ? 0 : init->crtc;
return nv_rdvgai(subdev, head, port, index);
}
return 0x00;
}
static void
init_wrvgai(struct nvbios_init *init, u16 port, u8 index, u8 value)
{
/* force head 0 for updates to cr44, it only exists on first head */
if (nv_device(init->subdev)->card_type < NV_50) {
if (port == 0x03d4 && index == 0x44)
init->crtc = 0;
}
if (init_exec(init)) {
int head = init->crtc < 0 ? 0 : init->crtc;
nv_wrvgai(init->subdev, head, port, index, value);
}
/* select head 1 if cr44 write selected it */
if (nv_device(init->subdev)->card_type < NV_50) {
if (port == 0x03d4 && index == 0x44 && value == 3)
init->crtc = 1;
}
}
static struct nouveau_i2c_port *
init_i2c(struct nvbios_init *init, int index)
{
struct nouveau_i2c *i2c = nouveau_i2c(init->bios);
if (index == 0xff) {
index = NV_I2C_DEFAULT(0);
if (init->outp && init->outp->i2c_upper_default)
index = NV_I2C_DEFAULT(1);
} else
if (index < 0) {
if (!init->outp) {
if (init_exec(init))
error("script needs output for i2c\n");
return NULL;
}
if (index == -2 && init->outp->location) {
index = NV_I2C_TYPE_EXTAUX(init->outp->extdev);
return i2c->find_type(i2c, index);
}
index = init->outp->i2c_index;
}
return i2c->find(i2c, index);
}
static int
init_rdi2cr(struct nvbios_init *init, u8 index, u8 addr, u8 reg)
{
struct nouveau_i2c_port *port = init_i2c(init, index);
if (port && init_exec(init))
return nv_rdi2cr(port, addr, reg);
return -ENODEV;
}
static int
init_wri2cr(struct nvbios_init *init, u8 index, u8 addr, u8 reg, u8 val)
{
struct nouveau_i2c_port *port = init_i2c(init, index);
if (port && init_exec(init))
return nv_wri2cr(port, addr, reg, val);
return -ENODEV;
}
static int
init_rdauxr(struct nvbios_init *init, u32 addr)
{
struct nouveau_i2c_port *port = init_i2c(init, -2);
u8 data;
if (port && init_exec(init)) {
int ret = nv_rdaux(port, addr, &data, 1);
if (ret)
return ret;
return data;
}
return -ENODEV;
}
static int
init_wrauxr(struct nvbios_init *init, u32 addr, u8 data)
{
struct nouveau_i2c_port *port = init_i2c(init, -2);
if (port && init_exec(init))
return nv_wraux(port, addr, &data, 1);
return -ENODEV;
}
static void
init_prog_pll(struct nvbios_init *init, u32 id, u32 freq)
{
struct nouveau_clock *clk = nouveau_clock(init->bios);
if (clk && clk->pll_set && init_exec(init)) {
int ret = clk->pll_set(clk, id, freq);
if (ret)
warn("failed to prog pll 0x%08x to %dkHz\n", id, freq);
}
}
/******************************************************************************
* parsing of bios structures that are required to execute init tables
*****************************************************************************/
static u16
init_table(struct nouveau_bios *bios, u16 *len)
{
struct bit_entry bit_I;
if (!bit_entry(bios, 'I', &bit_I)) {
*len = bit_I.length;
return bit_I.offset;
}
if (bmp_version(bios) >= 0x0510) {
*len = 14;
return bios->bmp_offset + 75;
}
return 0x0000;
}
static u16
init_table_(struct nvbios_init *init, u16 offset, const char *name)
{
struct nouveau_bios *bios = init->bios;
u16 len, data = init_table(bios, &len);
if (data) {
if (len >= offset + 2) {
data = nv_ro16(bios, data + offset);
if (data)
return data;
warn("%s pointer invalid\n", name);
return 0x0000;
}
warn("init data too short for %s pointer", name);
return 0x0000;
}
warn("init data not found\n");
return 0x0000;
}
#define init_script_table(b) init_table_((b), 0x00, "script table")
#define init_macro_index_table(b) init_table_((b), 0x02, "macro index table")
#define init_macro_table(b) init_table_((b), 0x04, "macro table")
#define init_condition_table(b) init_table_((b), 0x06, "condition table")
#define init_io_condition_table(b) init_table_((b), 0x08, "io condition table")
#define init_io_flag_condition_table(b) init_table_((b), 0x0a, "io flag conditon table")
#define init_function_table(b) init_table_((b), 0x0c, "function table")
#define init_xlat_table(b) init_table_((b), 0x10, "xlat table");
static u16
init_script(struct nouveau_bios *bios, int index)
{
struct nvbios_init init = { .bios = bios };
u16 bmp_ver = bmp_version(bios), data;
if (bmp_ver && bmp_ver < 0x0510) {
if (index > 1 || bmp_ver < 0x0100)
return 0x0000;
data = bios->bmp_offset + (bmp_ver < 0x0200 ? 14 : 18);
return nv_ro16(bios, data + (index * 2));
}
data = init_script_table(&init);
if (data)
return nv_ro16(bios, data + (index * 2));
return 0x0000;
}
static u16
init_unknown_script(struct nouveau_bios *bios)
{
u16 len, data = init_table(bios, &len);
if (data && len >= 16)
return nv_ro16(bios, data + 14);
return 0x0000;
}
static u16
init_ram_restrict_table(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
struct bit_entry bit_M;
u16 data = 0x0000;
if (!bit_entry(bios, 'M', &bit_M)) {
if (bit_M.version == 1 && bit_M.length >= 5)
data = nv_ro16(bios, bit_M.offset + 3);
if (bit_M.version == 2 && bit_M.length >= 3)
data = nv_ro16(bios, bit_M.offset + 1);
}
if (data == 0x0000)
warn("ram restrict table not found\n");
return data;
}
static u8
init_ram_restrict_group_count(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
struct bit_entry bit_M;
if (!bit_entry(bios, 'M', &bit_M)) {
if (bit_M.version == 1 && bit_M.length >= 5)
return nv_ro08(bios, bit_M.offset + 2);
if (bit_M.version == 2 && bit_M.length >= 3)
return nv_ro08(bios, bit_M.offset + 0);
}
return 0x00;
}
static u8
init_ram_restrict_strap(struct nvbios_init *init)
{
/* This appears to be the behaviour of the VBIOS parser, and *is*
* important to cache the NV_PEXTDEV_BOOT0 on later chipsets to
* avoid fucking up the memory controller (somehow) by reading it
* on every INIT_RAM_RESTRICT_ZM_GROUP opcode.
*
* Preserving the non-caching behaviour on earlier chipsets just
* in case *not* re-reading the strap causes similar breakage.
*/
if (!init->ramcfg || init->bios->version.major < 0x70)
init->ramcfg = init_rd32(init, 0x101000);
return (init->ramcfg & 0x00000003c) >> 2;
}
static u8
init_ram_restrict(struct nvbios_init *init)
{
u8 strap = init_ram_restrict_strap(init);
u16 table = init_ram_restrict_table(init);
if (table)
return nv_ro08(init->bios, table + strap);
return 0x00;
}
static u8
init_xlat_(struct nvbios_init *init, u8 index, u8 offset)
{
struct nouveau_bios *bios = init->bios;
u16 table = init_xlat_table(init);
if (table) {
u16 data = nv_ro16(bios, table + (index * 2));
if (data)
return nv_ro08(bios, data + offset);
warn("xlat table pointer %d invalid\n", index);
}
return 0x00;
}
/******************************************************************************
* utility functions used by various init opcode handlers
*****************************************************************************/
static bool
init_condition_met(struct nvbios_init *init, u8 cond)
{
struct nouveau_bios *bios = init->bios;
u16 table = init_condition_table(init);
if (table) {
u32 reg = nv_ro32(bios, table + (cond * 12) + 0);
u32 msk = nv_ro32(bios, table + (cond * 12) + 4);
u32 val = nv_ro32(bios, table + (cond * 12) + 8);
trace("\t[0x%02x] (R[0x%06x] & 0x%08x) == 0x%08x\n",
cond, reg, msk, val);
return (init_rd32(init, reg) & msk) == val;
}
return false;
}
static bool
init_io_condition_met(struct nvbios_init *init, u8 cond)
{
struct nouveau_bios *bios = init->bios;
u16 table = init_io_condition_table(init);
if (table) {
u16 port = nv_ro16(bios, table + (cond * 5) + 0);
u8 index = nv_ro08(bios, table + (cond * 5) + 2);
u8 mask = nv_ro08(bios, table + (cond * 5) + 3);
u8 value = nv_ro08(bios, table + (cond * 5) + 4);
trace("\t[0x%02x] (0x%04x[0x%02x] & 0x%02x) == 0x%02x\n",
cond, port, index, mask, value);
return (init_rdvgai(init, port, index) & mask) == value;
}
return false;
}
static bool
init_io_flag_condition_met(struct nvbios_init *init, u8 cond)
{
struct nouveau_bios *bios = init->bios;
u16 table = init_io_flag_condition_table(init);
if (table) {
u16 port = nv_ro16(bios, table + (cond * 9) + 0);
u8 index = nv_ro08(bios, table + (cond * 9) + 2);
u8 mask = nv_ro08(bios, table + (cond * 9) + 3);
u8 shift = nv_ro08(bios, table + (cond * 9) + 4);
u16 data = nv_ro16(bios, table + (cond * 9) + 5);
u8 dmask = nv_ro08(bios, table + (cond * 9) + 7);
u8 value = nv_ro08(bios, table + (cond * 9) + 8);
u8 ioval = (init_rdvgai(init, port, index) & mask) >> shift;
return (nv_ro08(bios, data + ioval) & dmask) == value;
}
return false;
}
static inline u32
init_shift(u32 data, u8 shift)
{
if (shift < 0x80)
return data >> shift;
return data << (0x100 - shift);
}
static u32
init_tmds_reg(struct nvbios_init *init, u8 tmds)
{
/* For mlv < 0x80, it is an index into a table of TMDS base addresses.
* For mlv == 0x80 use the "or" value of the dcb_entry indexed by
* CR58 for CR57 = 0 to index a table of offsets to the basic
* 0x6808b0 address.
* For mlv == 0x81 use the "or" value of the dcb_entry indexed by
* CR58 for CR57 = 0 to index a table of offsets to the basic
* 0x6808b0 address, and then flip the offset by 8.
*/
const int pramdac_offset[13] = {
0, 0, 0x8, 0, 0x2000, 0, 0, 0, 0x2008, 0, 0, 0, 0x2000 };
const u32 pramdac_table[4] = {
0x6808b0, 0x6808b8, 0x6828b0, 0x6828b8 };
if (tmds >= 0x80) {
if (init->outp) {
u32 dacoffset = pramdac_offset[init->outp->or];
if (tmds == 0x81)
dacoffset ^= 8;
return 0x6808b0 + dacoffset;
}
if (init_exec(init))
error("tmds opcodes need dcb\n");
} else {
if (tmds < ARRAY_SIZE(pramdac_table))
return pramdac_table[tmds];
error("tmds selector 0x%02x unknown\n", tmds);
}
return 0;
}
/******************************************************************************
* init opcode handlers
*****************************************************************************/
/**
* init_reserved - stub for various unknown/unused single-byte opcodes
*
*/
static void
init_reserved(struct nvbios_init *init)
{
u8 opcode = nv_ro08(init->bios, init->offset);
u8 length, i;
switch (opcode) {
case 0xaa:
length = 4;
break;
default:
length = 1;
break;
}
trace("RESERVED 0x%02x\t", opcode);
for (i = 1; i < length; i++)
cont(" 0x%02x", nv_ro08(init->bios, init->offset + i));
cont("\n");
init->offset += length;
}
/**
* INIT_DONE - opcode 0x71
*
*/
static void
init_done(struct nvbios_init *init)
{
trace("DONE\n");
init->offset = 0x0000;
}
/**
* INIT_IO_RESTRICT_PROG - opcode 0x32
*
*/
static void
init_io_restrict_prog(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 port = nv_ro16(bios, init->offset + 1);
u8 index = nv_ro08(bios, init->offset + 3);
u8 mask = nv_ro08(bios, init->offset + 4);
u8 shift = nv_ro08(bios, init->offset + 5);
u8 count = nv_ro08(bios, init->offset + 6);
u32 reg = nv_ro32(bios, init->offset + 7);
u8 conf, i;
trace("IO_RESTRICT_PROG\tR[0x%06x] = "
"((0x%04x[0x%02x] & 0x%02x) >> %d) [{\n",
reg, port, index, mask, shift);
init->offset += 11;
conf = (init_rdvgai(init, port, index) & mask) >> shift;
for (i = 0; i < count; i++) {
u32 data = nv_ro32(bios, init->offset);
if (i == conf) {
trace("\t0x%08x *\n", data);
init_wr32(init, reg, data);
} else {
trace("\t0x%08x\n", data);
}
init->offset += 4;
}
trace("}]\n");
}
/**
* INIT_REPEAT - opcode 0x33
*
*/
static void
init_repeat(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 count = nv_ro08(bios, init->offset + 1);
u16 repeat = init->repeat;
trace("REPEAT\t0x%02x\n", count);
init->offset += 2;
init->repeat = init->offset;
init->repend = init->offset;
while (count--) {
init->offset = init->repeat;
nvbios_exec(init);
if (count)
trace("REPEAT\t0x%02x\n", count);
}
init->offset = init->repend;
init->repeat = repeat;
}
/**
* INIT_IO_RESTRICT_PLL - opcode 0x34
*
*/
static void
init_io_restrict_pll(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 port = nv_ro16(bios, init->offset + 1);
u8 index = nv_ro08(bios, init->offset + 3);
u8 mask = nv_ro08(bios, init->offset + 4);
u8 shift = nv_ro08(bios, init->offset + 5);
s8 iofc = nv_ro08(bios, init->offset + 6);
u8 count = nv_ro08(bios, init->offset + 7);
u32 reg = nv_ro32(bios, init->offset + 8);
u8 conf, i;
trace("IO_RESTRICT_PLL\tR[0x%06x] =PLL= "
"((0x%04x[0x%02x] & 0x%02x) >> 0x%02x) IOFCOND 0x%02x [{\n",
reg, port, index, mask, shift, iofc);
init->offset += 12;
conf = (init_rdvgai(init, port, index) & mask) >> shift;
for (i = 0; i < count; i++) {
u32 freq = nv_ro16(bios, init->offset) * 10;
if (i == conf) {
trace("\t%dkHz *\n", freq);
if (iofc > 0 && init_io_flag_condition_met(init, iofc))
freq *= 2;
init_prog_pll(init, reg, freq);
} else {
trace("\t%dkHz\n", freq);
}
init->offset += 2;
}
trace("}]\n");
}
/**
* INIT_END_REPEAT - opcode 0x36
*
*/
static void
init_end_repeat(struct nvbios_init *init)
{
trace("END_REPEAT\n");
init->offset += 1;
if (init->repeat) {
init->repend = init->offset;
init->offset = 0;
}
}
/**
* INIT_COPY - opcode 0x37
*
*/
static void
init_copy(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 reg = nv_ro32(bios, init->offset + 1);
u8 shift = nv_ro08(bios, init->offset + 5);
u8 smask = nv_ro08(bios, init->offset + 6);
u16 port = nv_ro16(bios, init->offset + 7);
u8 index = nv_ro08(bios, init->offset + 9);
u8 mask = nv_ro08(bios, init->offset + 10);
u8 data;
trace("COPY\t0x%04x[0x%02x] &= 0x%02x |= "
"((R[0x%06x] %s 0x%02x) & 0x%02x)\n",
port, index, mask, reg, (shift & 0x80) ? "<<" : ">>",
(shift & 0x80) ? (0x100 - shift) : shift, smask);
init->offset += 11;
data = init_rdvgai(init, port, index) & mask;
data |= init_shift(init_rd32(init, reg), shift) & smask;
init_wrvgai(init, port, index, data);
}
/**
* INIT_NOT - opcode 0x38
*
*/
static void
init_not(struct nvbios_init *init)
{
trace("NOT\n");
init->offset += 1;
init_exec_inv(init);
}
/**
* INIT_IO_FLAG_CONDITION - opcode 0x39
*
*/
static void
init_io_flag_condition(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 cond = nv_ro08(bios, init->offset + 1);
trace("IO_FLAG_CONDITION\t0x%02x\n", cond);
init->offset += 2;
if (!init_io_flag_condition_met(init, cond))
init_exec_set(init, false);
}
/**
* INIT_DP_CONDITION - opcode 0x3a
*
*/
static void
init_dp_condition(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
struct nvbios_dpout info;
u8 cond = nv_ro08(bios, init->offset + 1);
u8 unkn = nv_ro08(bios, init->offset + 2);
u8 ver, hdr, cnt, len;
u16 data;
trace("DP_CONDITION\t0x%02x 0x%02x\n", cond, unkn);
init->offset += 3;
switch (cond) {
case 0:
if (init_conn(init) != DCB_CONNECTOR_eDP)
init_exec_set(init, false);
break;
case 1:
case 2:
if ( init->outp &&
(data = nvbios_dpout_match(bios, DCB_OUTPUT_DP,
(init->outp->or << 0) |
(init->outp->sorconf.link << 6),
&ver, &hdr, &cnt, &len, &info)))
{
if (!(info.flags & cond))
init_exec_set(init, false);
break;
}
if (init_exec(init))
warn("script needs dp output table data\n");
break;
case 5:
if (!(init_rdauxr(init, 0x0d) & 1))
init_exec_set(init, false);
break;
default:
warn("unknown dp condition 0x%02x\n", cond);
break;
}
}
/**
* INIT_IO_MASK_OR - opcode 0x3b
*
*/
static void
init_io_mask_or(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 index = nv_ro08(bios, init->offset + 1);
u8 or = init_or(init);
u8 data;
trace("IO_MASK_OR\t0x03d4[0x%02x] &= ~(1 << 0x%02x)\n", index, or);
init->offset += 2;
data = init_rdvgai(init, 0x03d4, index);
init_wrvgai(init, 0x03d4, index, data &= ~(1 << or));
}
/**
* INIT_IO_OR - opcode 0x3c
*
*/
static void
init_io_or(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 index = nv_ro08(bios, init->offset + 1);
u8 or = init_or(init);
u8 data;
trace("IO_OR\t0x03d4[0x%02x] |= (1 << 0x%02x)\n", index, or);
init->offset += 2;
data = init_rdvgai(init, 0x03d4, index);
init_wrvgai(init, 0x03d4, index, data | (1 << or));
}
/**
* INIT_INDEX_ADDRESS_LATCHED - opcode 0x49
*
*/
static void
init_idx_addr_latched(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 creg = nv_ro32(bios, init->offset + 1);
u32 dreg = nv_ro32(bios, init->offset + 5);
u32 mask = nv_ro32(bios, init->offset + 9);
u32 data = nv_ro32(bios, init->offset + 13);
u8 count = nv_ro08(bios, init->offset + 17);
trace("INDEX_ADDRESS_LATCHED\t"
"R[0x%06x] : R[0x%06x]\n\tCTRL &= 0x%08x |= 0x%08x\n",
creg, dreg, mask, data);
init->offset += 18;
while (count--) {
u8 iaddr = nv_ro08(bios, init->offset + 0);
u8 idata = nv_ro08(bios, init->offset + 1);
trace("\t[0x%02x] = 0x%02x\n", iaddr, idata);
init->offset += 2;
init_wr32(init, dreg, idata);
init_mask(init, creg, ~mask, data | iaddr);
}
}
/**
* INIT_IO_RESTRICT_PLL2 - opcode 0x4a
*
*/
static void
init_io_restrict_pll2(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 port = nv_ro16(bios, init->offset + 1);
u8 index = nv_ro08(bios, init->offset + 3);
u8 mask = nv_ro08(bios, init->offset + 4);
u8 shift = nv_ro08(bios, init->offset + 5);
u8 count = nv_ro08(bios, init->offset + 6);
u32 reg = nv_ro32(bios, init->offset + 7);
u8 conf, i;
trace("IO_RESTRICT_PLL2\t"
"R[0x%06x] =PLL= ((0x%04x[0x%02x] & 0x%02x) >> 0x%02x) [{\n",
reg, port, index, mask, shift);
init->offset += 11;
conf = (init_rdvgai(init, port, index) & mask) >> shift;
for (i = 0; i < count; i++) {
u32 freq = nv_ro32(bios, init->offset);
if (i == conf) {
trace("\t%dkHz *\n", freq);
init_prog_pll(init, reg, freq);
} else {
trace("\t%dkHz\n", freq);
}
init->offset += 4;
}
trace("}]\n");
}
/**
* INIT_PLL2 - opcode 0x4b
*
*/
static void
init_pll2(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 reg = nv_ro32(bios, init->offset + 1);
u32 freq = nv_ro32(bios, init->offset + 5);
trace("PLL2\tR[0x%06x] =PLL= %dkHz\n", reg, freq);
init->offset += 9;
init_prog_pll(init, reg, freq);
}
/**
* INIT_I2C_BYTE - opcode 0x4c
*
*/
static void
init_i2c_byte(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 index = nv_ro08(bios, init->offset + 1);
u8 addr = nv_ro08(bios, init->offset + 2) >> 1;
u8 count = nv_ro08(bios, init->offset + 3);
trace("I2C_BYTE\tI2C[0x%02x][0x%02x]\n", index, addr);
init->offset += 4;
while (count--) {
u8 reg = nv_ro08(bios, init->offset + 0);
u8 mask = nv_ro08(bios, init->offset + 1);
u8 data = nv_ro08(bios, init->offset + 2);
int val;
trace("\t[0x%02x] &= 0x%02x |= 0x%02x\n", reg, mask, data);
init->offset += 3;
val = init_rdi2cr(init, index, addr, reg);
if (val < 0)
continue;
init_wri2cr(init, index, addr, reg, (val & mask) | data);
}
}
/**
* INIT_ZM_I2C_BYTE - opcode 0x4d
*
*/
static void
init_zm_i2c_byte(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 index = nv_ro08(bios, init->offset + 1);
u8 addr = nv_ro08(bios, init->offset + 2) >> 1;
u8 count = nv_ro08(bios, init->offset + 3);
trace("ZM_I2C_BYTE\tI2C[0x%02x][0x%02x]\n", index, addr);
init->offset += 4;
while (count--) {
u8 reg = nv_ro08(bios, init->offset + 0);
u8 data = nv_ro08(bios, init->offset + 1);
trace("\t[0x%02x] = 0x%02x\n", reg, data);
init->offset += 2;
init_wri2cr(init, index, addr, reg, data);
}
}
/**
* INIT_ZM_I2C - opcode 0x4e
*
*/
static void
init_zm_i2c(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 index = nv_ro08(bios, init->offset + 1);
u8 addr = nv_ro08(bios, init->offset + 2) >> 1;
u8 count = nv_ro08(bios, init->offset + 3);
u8 data[256], i;
trace("ZM_I2C\tI2C[0x%02x][0x%02x]\n", index, addr);
init->offset += 4;
for (i = 0; i < count; i++) {
data[i] = nv_ro08(bios, init->offset);
trace("\t0x%02x\n", data[i]);
init->offset++;
}
if (init_exec(init)) {
struct nouveau_i2c_port *port = init_i2c(init, index);
struct i2c_msg msg = {
.addr = addr, .flags = 0, .len = count, .buf = data,
};
int ret;
if (port && (ret = i2c_transfer(&port->adapter, &msg, 1)) != 1)
warn("i2c wr failed, %d\n", ret);
}
}
/**
* INIT_TMDS - opcode 0x4f
*
*/
static void
init_tmds(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 tmds = nv_ro08(bios, init->offset + 1);
u8 addr = nv_ro08(bios, init->offset + 2);
u8 mask = nv_ro08(bios, init->offset + 3);
u8 data = nv_ro08(bios, init->offset + 4);
u32 reg = init_tmds_reg(init, tmds);
trace("TMDS\tT[0x%02x][0x%02x] &= 0x%02x |= 0x%02x\n",
tmds, addr, mask, data);
init->offset += 5;
if (reg == 0)
return;
init_wr32(init, reg + 0, addr | 0x00010000);
init_wr32(init, reg + 4, data | (init_rd32(init, reg + 4) & mask));
init_wr32(init, reg + 0, addr);
}
/**
* INIT_ZM_TMDS_GROUP - opcode 0x50
*
*/
static void
init_zm_tmds_group(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 tmds = nv_ro08(bios, init->offset + 1);
u8 count = nv_ro08(bios, init->offset + 2);
u32 reg = init_tmds_reg(init, tmds);
trace("TMDS_ZM_GROUP\tT[0x%02x]\n", tmds);
init->offset += 3;
while (count--) {
u8 addr = nv_ro08(bios, init->offset + 0);
u8 data = nv_ro08(bios, init->offset + 1);
trace("\t[0x%02x] = 0x%02x\n", addr, data);
init->offset += 2;
init_wr32(init, reg + 4, data);
init_wr32(init, reg + 0, addr);
}
}
/**
* INIT_CR_INDEX_ADDRESS_LATCHED - opcode 0x51
*
*/
static void
init_cr_idx_adr_latch(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 addr0 = nv_ro08(bios, init->offset + 1);
u8 addr1 = nv_ro08(bios, init->offset + 2);
u8 base = nv_ro08(bios, init->offset + 3);
u8 count = nv_ro08(bios, init->offset + 4);
u8 save0;
trace("CR_INDEX_ADDR C[%02x] C[%02x]\n", addr0, addr1);
init->offset += 5;
save0 = init_rdvgai(init, 0x03d4, addr0);
while (count--) {
u8 data = nv_ro08(bios, init->offset);
trace("\t\t[0x%02x] = 0x%02x\n", base, data);
init->offset += 1;
init_wrvgai(init, 0x03d4, addr0, base++);
init_wrvgai(init, 0x03d4, addr1, data);
}
init_wrvgai(init, 0x03d4, addr0, save0);
}
/**
* INIT_CR - opcode 0x52
*
*/
static void
init_cr(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 addr = nv_ro08(bios, init->offset + 1);
u8 mask = nv_ro08(bios, init->offset + 2);
u8 data = nv_ro08(bios, init->offset + 3);
u8 val;
trace("CR\t\tC[0x%02x] &= 0x%02x |= 0x%02x\n", addr, mask, data);
init->offset += 4;
val = init_rdvgai(init, 0x03d4, addr) & mask;
init_wrvgai(init, 0x03d4, addr, val | data);
}
/**
* INIT_ZM_CR - opcode 0x53
*
*/
static void
init_zm_cr(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 addr = nv_ro08(bios, init->offset + 1);
u8 data = nv_ro08(bios, init->offset + 2);
trace("ZM_CR\tC[0x%02x] = 0x%02x\n", addr, data);
init->offset += 3;
init_wrvgai(init, 0x03d4, addr, data);
}
/**
* INIT_ZM_CR_GROUP - opcode 0x54
*
*/
static void
init_zm_cr_group(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 count = nv_ro08(bios, init->offset + 1);
trace("ZM_CR_GROUP\n");
init->offset += 2;
while (count--) {
u8 addr = nv_ro08(bios, init->offset + 0);
u8 data = nv_ro08(bios, init->offset + 1);
trace("\t\tC[0x%02x] = 0x%02x\n", addr, data);
init->offset += 2;
init_wrvgai(init, 0x03d4, addr, data);
}
}
/**
* INIT_CONDITION_TIME - opcode 0x56
*
*/
static void
init_condition_time(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 cond = nv_ro08(bios, init->offset + 1);
u8 retry = nv_ro08(bios, init->offset + 2);
u8 wait = min((u16)retry * 50, 100);
trace("CONDITION_TIME\t0x%02x 0x%02x\n", cond, retry);
init->offset += 3;
if (!init_exec(init))
return;
while (wait--) {
if (init_condition_met(init, cond))
return;
mdelay(20);
}
init_exec_set(init, false);
}
/**
* INIT_LTIME - opcode 0x57
*
*/
static void
init_ltime(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 msec = nv_ro16(bios, init->offset + 1);
trace("LTIME\t0x%04x\n", msec);
init->offset += 3;
if (init_exec(init))
mdelay(msec);
}
/**
* INIT_ZM_REG_SEQUENCE - opcode 0x58
*
*/
static void
init_zm_reg_sequence(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 base = nv_ro32(bios, init->offset + 1);
u8 count = nv_ro08(bios, init->offset + 5);
trace("ZM_REG_SEQUENCE\t0x%02x\n", count);
init->offset += 6;
while (count--) {
u32 data = nv_ro32(bios, init->offset);
trace("\t\tR[0x%06x] = 0x%08x\n", base, data);
init->offset += 4;
init_wr32(init, base, data);
base += 4;
}
}
/**
* INIT_SUB_DIRECT - opcode 0x5b
*
*/
static void
init_sub_direct(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 addr = nv_ro16(bios, init->offset + 1);
u16 save;
trace("SUB_DIRECT\t0x%04x\n", addr);
if (init_exec(init)) {
save = init->offset;
init->offset = addr;
if (nvbios_exec(init)) {
error("error parsing sub-table\n");
return;
}
init->offset = save;
}
init->offset += 3;
}
/**
* INIT_JUMP - opcode 0x5c
*
*/
static void
init_jump(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 offset = nv_ro16(bios, init->offset + 1);
trace("JUMP\t0x%04x\n", offset);
if (init_exec(init))
init->offset = offset;
else
init->offset += 3;
}
/**
* INIT_I2C_IF - opcode 0x5e
*
*/
static void
init_i2c_if(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 index = nv_ro08(bios, init->offset + 1);
u8 addr = nv_ro08(bios, init->offset + 2);
u8 reg = nv_ro08(bios, init->offset + 3);
u8 mask = nv_ro08(bios, init->offset + 4);
u8 data = nv_ro08(bios, init->offset + 5);
u8 value;
trace("I2C_IF\tI2C[0x%02x][0x%02x][0x%02x] & 0x%02x == 0x%02x\n",
index, addr, reg, mask, data);
init->offset += 6;
init_exec_force(init, true);
value = init_rdi2cr(init, index, addr, reg);
if ((value & mask) != data)
init_exec_set(init, false);
init_exec_force(init, false);
}
/**
* INIT_COPY_NV_REG - opcode 0x5f
*
*/
static void
init_copy_nv_reg(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 sreg = nv_ro32(bios, init->offset + 1);
u8 shift = nv_ro08(bios, init->offset + 5);
u32 smask = nv_ro32(bios, init->offset + 6);
u32 sxor = nv_ro32(bios, init->offset + 10);
u32 dreg = nv_ro32(bios, init->offset + 14);
u32 dmask = nv_ro32(bios, init->offset + 18);
u32 data;
trace("COPY_NV_REG\tR[0x%06x] &= 0x%08x |= "
"((R[0x%06x] %s 0x%02x) & 0x%08x ^ 0x%08x)\n",
dreg, dmask, sreg, (shift & 0x80) ? "<<" : ">>",
(shift & 0x80) ? (0x100 - shift) : shift, smask, sxor);
init->offset += 22;
data = init_shift(init_rd32(init, sreg), shift);
init_mask(init, dreg, ~dmask, (data & smask) ^ sxor);
}
/**
* INIT_ZM_INDEX_IO - opcode 0x62
*
*/
static void
init_zm_index_io(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 port = nv_ro16(bios, init->offset + 1);
u8 index = nv_ro08(bios, init->offset + 3);
u8 data = nv_ro08(bios, init->offset + 4);
trace("ZM_INDEX_IO\tI[0x%04x][0x%02x] = 0x%02x\n", port, index, data);
init->offset += 5;
init_wrvgai(init, port, index, data);
}
/**
* INIT_COMPUTE_MEM - opcode 0x63
*
*/
static void
init_compute_mem(struct nvbios_init *init)
{
struct nouveau_devinit *devinit = nouveau_devinit(init->bios);
trace("COMPUTE_MEM\n");
init->offset += 1;
init_exec_force(init, true);
if (init_exec(init) && devinit->meminit)
devinit->meminit(devinit);
init_exec_force(init, false);
}
/**
* INIT_RESET - opcode 0x65
*
*/
static void
init_reset(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 reg = nv_ro32(bios, init->offset + 1);
u32 data1 = nv_ro32(bios, init->offset + 5);
u32 data2 = nv_ro32(bios, init->offset + 9);
u32 savepci19;
trace("RESET\tR[0x%08x] = 0x%08x, 0x%08x", reg, data1, data2);
init->offset += 13;
init_exec_force(init, true);
savepci19 = init_mask(init, 0x00184c, 0x00000f00, 0x00000000);
init_wr32(init, reg, data1);
udelay(10);
init_wr32(init, reg, data2);
init_wr32(init, 0x00184c, savepci19);
init_mask(init, 0x001850, 0x00000001, 0x00000000);
init_exec_force(init, false);
}
/**
* INIT_CONFIGURE_MEM - opcode 0x66
*
*/
static u16
init_configure_mem_clk(struct nvbios_init *init)
{
u16 mdata = bmp_mem_init_table(init->bios);
if (mdata)
mdata += (init_rdvgai(init, 0x03d4, 0x3c) >> 4) * 66;
return mdata;
}
static void
init_configure_mem(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 mdata, sdata;
u32 addr, data;
trace("CONFIGURE_MEM\n");
init->offset += 1;
if (bios->version.major > 2) {
init_done(init);
return;
}
init_exec_force(init, true);
mdata = init_configure_mem_clk(init);
sdata = bmp_sdr_seq_table(bios);
if (nv_ro08(bios, mdata) & 0x01)
sdata = bmp_ddr_seq_table(bios);
mdata += 6; /* skip to data */
data = init_rdvgai(init, 0x03c4, 0x01);
init_wrvgai(init, 0x03c4, 0x01, data | 0x20);
while ((addr = nv_ro32(bios, sdata)) != 0xffffffff) {
switch (addr) {
case 0x10021c: /* CKE_NORMAL */
case 0x1002d0: /* CMD_REFRESH */
case 0x1002d4: /* CMD_PRECHARGE */
data = 0x00000001;
break;
default:
data = nv_ro32(bios, mdata);
mdata += 4;
if (data == 0xffffffff)
continue;
break;
}
init_wr32(init, addr, data);
}
init_exec_force(init, false);
}
/**
* INIT_CONFIGURE_CLK - opcode 0x67
*
*/
static void
init_configure_clk(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 mdata, clock;
trace("CONFIGURE_CLK\n");
init->offset += 1;
if (bios->version.major > 2) {
init_done(init);
return;
}
init_exec_force(init, true);
mdata = init_configure_mem_clk(init);
/* NVPLL */
clock = nv_ro16(bios, mdata + 4) * 10;
init_prog_pll(init, 0x680500, clock);
/* MPLL */
clock = nv_ro16(bios, mdata + 2) * 10;
if (nv_ro08(bios, mdata) & 0x01)
clock *= 2;
init_prog_pll(init, 0x680504, clock);
init_exec_force(init, false);
}
/**
* INIT_CONFIGURE_PREINIT - opcode 0x68
*
*/
static void
init_configure_preinit(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 strap;
trace("CONFIGURE_PREINIT\n");
init->offset += 1;
if (bios->version.major > 2) {
init_done(init);
return;
}
init_exec_force(init, true);
strap = init_rd32(init, 0x101000);
strap = ((strap << 2) & 0xf0) | ((strap & 0x40) >> 6);
init_wrvgai(init, 0x03d4, 0x3c, strap);
init_exec_force(init, false);
}
/**
* INIT_IO - opcode 0x69
*
*/
static void
init_io(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 port = nv_ro16(bios, init->offset + 1);
u8 mask = nv_ro16(bios, init->offset + 3);
u8 data = nv_ro16(bios, init->offset + 4);
u8 value;
trace("IO\t\tI[0x%04x] &= 0x%02x |= 0x%02x\n", port, mask, data);
init->offset += 5;
/* ummm.. yes.. should really figure out wtf this is and why it's
* needed some day.. it's almost certainly wrong, but, it also
* somehow makes things work...
*/
if (nv_device(init->bios)->card_type >= NV_50 &&
port == 0x03c3 && data == 0x01) {
init_mask(init, 0x614100, 0xf0800000, 0x00800000);
init_mask(init, 0x00e18c, 0x00020000, 0x00020000);
init_mask(init, 0x614900, 0xf0800000, 0x00800000);
init_mask(init, 0x000200, 0x40000000, 0x00000000);
mdelay(10);
init_mask(init, 0x00e18c, 0x00020000, 0x00000000);
init_mask(init, 0x000200, 0x40000000, 0x40000000);
init_wr32(init, 0x614100, 0x00800018);
init_wr32(init, 0x614900, 0x00800018);
mdelay(10);
init_wr32(init, 0x614100, 0x10000018);
init_wr32(init, 0x614900, 0x10000018);
}
value = init_rdport(init, port) & mask;
init_wrport(init, port, data | value);
}
/**
* INIT_SUB - opcode 0x6b
*
*/
static void
init_sub(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 index = nv_ro08(bios, init->offset + 1);
u16 addr, save;
trace("SUB\t0x%02x\n", index);
addr = init_script(bios, index);
if (addr && init_exec(init)) {
save = init->offset;
init->offset = addr;
if (nvbios_exec(init)) {
error("error parsing sub-table\n");
return;
}
init->offset = save;
}
init->offset += 2;
}
/**
* INIT_RAM_CONDITION - opcode 0x6d
*
*/
static void
init_ram_condition(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 mask = nv_ro08(bios, init->offset + 1);
u8 value = nv_ro08(bios, init->offset + 2);
trace("RAM_CONDITION\t"
"(R[0x100000] & 0x%02x) == 0x%02x\n", mask, value);
init->offset += 3;
if ((init_rd32(init, 0x100000) & mask) != value)
init_exec_set(init, false);
}
/**
* INIT_NV_REG - opcode 0x6e
*
*/
static void
init_nv_reg(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 reg = nv_ro32(bios, init->offset + 1);
u32 mask = nv_ro32(bios, init->offset + 5);
u32 data = nv_ro32(bios, init->offset + 9);
trace("NV_REG\tR[0x%06x] &= 0x%08x |= 0x%08x\n", reg, mask, data);
init->offset += 13;
init_mask(init, reg, ~mask, data);
}
/**
* INIT_MACRO - opcode 0x6f
*
*/
static void
init_macro(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 macro = nv_ro08(bios, init->offset + 1);
u16 table;
trace("MACRO\t0x%02x\n", macro);
table = init_macro_table(init);
if (table) {
u32 addr = nv_ro32(bios, table + (macro * 8) + 0);
u32 data = nv_ro32(bios, table + (macro * 8) + 4);
trace("\t\tR[0x%06x] = 0x%08x\n", addr, data);
init_wr32(init, addr, data);
}
init->offset += 2;
}
/**
* INIT_RESUME - opcode 0x72
*
*/
static void
init_resume(struct nvbios_init *init)
{
trace("RESUME\n");
init->offset += 1;
init_exec_set(init, true);
}
/**
* INIT_TIME - opcode 0x74
*
*/
static void
init_time(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 usec = nv_ro16(bios, init->offset + 1);
trace("TIME\t0x%04x\n", usec);
init->offset += 3;
if (init_exec(init)) {
if (usec < 1000)
udelay(usec);
else
mdelay((usec + 900) / 1000);
}
}
/**
* INIT_CONDITION - opcode 0x75
*
*/
static void
init_condition(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 cond = nv_ro08(bios, init->offset + 1);
trace("CONDITION\t0x%02x\n", cond);
init->offset += 2;
if (!init_condition_met(init, cond))
init_exec_set(init, false);
}
/**
* INIT_IO_CONDITION - opcode 0x76
*
*/
static void
init_io_condition(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 cond = nv_ro08(bios, init->offset + 1);
trace("IO_CONDITION\t0x%02x\n", cond);
init->offset += 2;
if (!init_io_condition_met(init, cond))
init_exec_set(init, false);
}
/**
* INIT_INDEX_IO - opcode 0x78
*
*/
static void
init_index_io(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 port = nv_ro16(bios, init->offset + 1);
u8 index = nv_ro16(bios, init->offset + 3);
u8 mask = nv_ro08(bios, init->offset + 4);
u8 data = nv_ro08(bios, init->offset + 5);
u8 value;
trace("INDEX_IO\tI[0x%04x][0x%02x] &= 0x%02x |= 0x%02x\n",
port, index, mask, data);
init->offset += 6;
value = init_rdvgai(init, port, index) & mask;
init_wrvgai(init, port, index, data | value);
}
/**
* INIT_PLL - opcode 0x79
*
*/
static void
init_pll(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 reg = nv_ro32(bios, init->offset + 1);
u32 freq = nv_ro16(bios, init->offset + 5) * 10;
trace("PLL\tR[0x%06x] =PLL= %dkHz\n", reg, freq);
init->offset += 7;
init_prog_pll(init, reg, freq);
}
/**
* INIT_ZM_REG - opcode 0x7a
*
*/
static void
init_zm_reg(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 addr = nv_ro32(bios, init->offset + 1);
u32 data = nv_ro32(bios, init->offset + 5);
trace("ZM_REG\tR[0x%06x] = 0x%08x\n", addr, data);
init->offset += 9;
if (addr == 0x000200)
data |= 0x00000001;
init_wr32(init, addr, data);
}
/**
* INIT_RAM_RESTRICT_PLL - opcde 0x87
*
*/
static void
init_ram_restrict_pll(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 type = nv_ro08(bios, init->offset + 1);
u8 count = init_ram_restrict_group_count(init);
u8 strap = init_ram_restrict(init);
u8 cconf;
trace("RAM_RESTRICT_PLL\t0x%02x\n", type);
init->offset += 2;
for (cconf = 0; cconf < count; cconf++) {
u32 freq = nv_ro32(bios, init->offset);
if (cconf == strap) {
trace("%dkHz *\n", freq);
init_prog_pll(init, type, freq);
} else {
trace("%dkHz\n", freq);
}
init->offset += 4;
}
}
/**
* INIT_GPIO - opcode 0x8e
*
*/
static void
init_gpio(struct nvbios_init *init)
{
struct nouveau_gpio *gpio = nouveau_gpio(init->bios);
trace("GPIO\n");
init->offset += 1;
if (init_exec(init) && gpio && gpio->reset)
gpio->reset(gpio, DCB_GPIO_UNUSED);
}
/**
* INIT_RAM_RESTRICT_ZM_GROUP - opcode 0x8f
*
*/
static void
init_ram_restrict_zm_reg_group(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 addr = nv_ro32(bios, init->offset + 1);
u8 incr = nv_ro08(bios, init->offset + 5);
u8 num = nv_ro08(bios, init->offset + 6);
u8 count = init_ram_restrict_group_count(init);
u8 index = init_ram_restrict(init);
u8 i, j;
trace("RAM_RESTRICT_ZM_REG_GROUP\t"
"R[0x%08x] 0x%02x 0x%02x\n", addr, incr, num);
init->offset += 7;
for (i = 0; i < num; i++) {
trace("\tR[0x%06x] = {\n", addr);
for (j = 0; j < count; j++) {
u32 data = nv_ro32(bios, init->offset);
if (j == index) {
trace("\t\t0x%08x *\n", data);
init_wr32(init, addr, data);
} else {
trace("\t\t0x%08x\n", data);
}
init->offset += 4;
}
trace("\t}\n");
addr += incr;
}
}
/**
* INIT_COPY_ZM_REG - opcode 0x90
*
*/
static void
init_copy_zm_reg(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 sreg = nv_ro32(bios, init->offset + 1);
u32 dreg = nv_ro32(bios, init->offset + 5);
trace("COPY_ZM_REG\tR[0x%06x] = R[0x%06x]\n", dreg, sreg);
init->offset += 9;
init_wr32(init, dreg, init_rd32(init, sreg));
}
/**
* INIT_ZM_REG_GROUP - opcode 0x91
*
*/
static void
init_zm_reg_group(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 addr = nv_ro32(bios, init->offset + 1);
u8 count = nv_ro08(bios, init->offset + 5);
trace("ZM_REG_GROUP\tR[0x%06x] =\n", addr);
init->offset += 6;
while (count--) {
u32 data = nv_ro32(bios, init->offset);
trace("\t0x%08x\n", data);
init_wr32(init, addr, data);
init->offset += 4;
}
}
/**
* INIT_XLAT - opcode 0x96
*
*/
static void
init_xlat(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 saddr = nv_ro32(bios, init->offset + 1);
u8 sshift = nv_ro08(bios, init->offset + 5);
u8 smask = nv_ro08(bios, init->offset + 6);
u8 index = nv_ro08(bios, init->offset + 7);
u32 daddr = nv_ro32(bios, init->offset + 8);
u32 dmask = nv_ro32(bios, init->offset + 12);
u8 shift = nv_ro08(bios, init->offset + 16);
u32 data;
trace("INIT_XLAT\tR[0x%06x] &= 0x%08x |= "
"(X%02x((R[0x%06x] %s 0x%02x) & 0x%02x) << 0x%02x)\n",
daddr, dmask, index, saddr, (sshift & 0x80) ? "<<" : ">>",
(sshift & 0x80) ? (0x100 - sshift) : sshift, smask, shift);
init->offset += 17;
data = init_shift(init_rd32(init, saddr), sshift) & smask;
data = init_xlat_(init, index, data) << shift;
init_mask(init, daddr, ~dmask, data);
}
/**
* INIT_ZM_MASK_ADD - opcode 0x97
*
*/
static void
init_zm_mask_add(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 addr = nv_ro32(bios, init->offset + 1);
u32 mask = nv_ro32(bios, init->offset + 5);
u32 add = nv_ro32(bios, init->offset + 9);
u32 data;
trace("ZM_MASK_ADD\tR[0x%06x] &= 0x%08x += 0x%08x\n", addr, mask, add);
init->offset += 13;
data = init_rd32(init, addr);
data = (data & mask) | ((data + add) & ~mask);
init_wr32(init, addr, data);
}
/**
* INIT_AUXCH - opcode 0x98
*
*/
static void
init_auxch(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 addr = nv_ro32(bios, init->offset + 1);
u8 count = nv_ro08(bios, init->offset + 5);
trace("AUXCH\tAUX[0x%08x] 0x%02x\n", addr, count);
init->offset += 6;
while (count--) {
u8 mask = nv_ro08(bios, init->offset + 0);
u8 data = nv_ro08(bios, init->offset + 1);
trace("\tAUX[0x%08x] &= 0x%02x |= 0x%02x\n", addr, mask, data);
mask = init_rdauxr(init, addr) & mask;
init_wrauxr(init, addr, mask | data);
init->offset += 2;
}
}
/**
* INIT_AUXCH - opcode 0x99
*
*/
static void
init_zm_auxch(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 addr = nv_ro32(bios, init->offset + 1);
u8 count = nv_ro08(bios, init->offset + 5);
trace("ZM_AUXCH\tAUX[0x%08x] 0x%02x\n", addr, count);
init->offset += 6;
while (count--) {
u8 data = nv_ro08(bios, init->offset + 0);
trace("\tAUX[0x%08x] = 0x%02x\n", addr, data);
init_wrauxr(init, addr, data);
init->offset += 1;
}
}
/**
* INIT_I2C_LONG_IF - opcode 0x9a
*
*/
static void
init_i2c_long_if(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 index = nv_ro08(bios, init->offset + 1);
u8 addr = nv_ro08(bios, init->offset + 2) >> 1;
u8 reglo = nv_ro08(bios, init->offset + 3);
u8 reghi = nv_ro08(bios, init->offset + 4);
u8 mask = nv_ro08(bios, init->offset + 5);
u8 data = nv_ro08(bios, init->offset + 6);
struct nouveau_i2c_port *port;
trace("I2C_LONG_IF\t"
"I2C[0x%02x][0x%02x][0x%02x%02x] & 0x%02x == 0x%02x\n",
index, addr, reglo, reghi, mask, data);
init->offset += 7;
port = init_i2c(init, index);
if (port) {
u8 i[2] = { reghi, reglo };
u8 o[1] = {};
struct i2c_msg msg[] = {
{ .addr = addr, .flags = 0, .len = 2, .buf = i },
{ .addr = addr, .flags = I2C_M_RD, .len = 1, .buf = o }
};
int ret;
ret = i2c_transfer(&port->adapter, msg, 2);
if (ret == 2 && ((o[0] & mask) == data))
return;
}
init_exec_set(init, false);
}
/**
* INIT_GPIO_NE - opcode 0xa9
*
*/
static void
init_gpio_ne(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
struct nouveau_gpio *gpio = nouveau_gpio(bios);
struct dcb_gpio_func func;
u8 count = nv_ro08(bios, init->offset + 1);
u8 idx = 0, ver, len;
u16 data, i;
trace("GPIO_NE\t");
init->offset += 2;
for (i = init->offset; i < init->offset + count; i++)
cont("0x%02x ", nv_ro08(bios, i));
cont("\n");
while ((data = dcb_gpio_parse(bios, 0, idx++, &ver, &len, &func))) {
if (func.func != DCB_GPIO_UNUSED) {
for (i = init->offset; i < init->offset + count; i++) {
if (func.func == nv_ro08(bios, i))
break;
}
trace("\tFUNC[0x%02x]", func.func);
if (i == (init->offset + count)) {
cont(" *");
if (init_exec(init) && gpio && gpio->reset)
gpio->reset(gpio, func.func);
}
cont("\n");
}
}
init->offset += count;
}
static struct nvbios_init_opcode {
void (*exec)(struct nvbios_init *);
} init_opcode[] = {
[0x32] = { init_io_restrict_prog },
[0x33] = { init_repeat },
[0x34] = { init_io_restrict_pll },
[0x36] = { init_end_repeat },
[0x37] = { init_copy },
[0x38] = { init_not },
[0x39] = { init_io_flag_condition },
[0x3a] = { init_dp_condition },
[0x3b] = { init_io_mask_or },
[0x3c] = { init_io_or },
[0x49] = { init_idx_addr_latched },
[0x4a] = { init_io_restrict_pll2 },
[0x4b] = { init_pll2 },
[0x4c] = { init_i2c_byte },
[0x4d] = { init_zm_i2c_byte },
[0x4e] = { init_zm_i2c },
[0x4f] = { init_tmds },
[0x50] = { init_zm_tmds_group },
[0x51] = { init_cr_idx_adr_latch },
[0x52] = { init_cr },
[0x53] = { init_zm_cr },
[0x54] = { init_zm_cr_group },
[0x56] = { init_condition_time },
[0x57] = { init_ltime },
[0x58] = { init_zm_reg_sequence },
[0x5b] = { init_sub_direct },
[0x5c] = { init_jump },
[0x5e] = { init_i2c_if },
[0x5f] = { init_copy_nv_reg },
[0x62] = { init_zm_index_io },
[0x63] = { init_compute_mem },
[0x65] = { init_reset },
[0x66] = { init_configure_mem },
[0x67] = { init_configure_clk },
[0x68] = { init_configure_preinit },
[0x69] = { init_io },
[0x6b] = { init_sub },
[0x6d] = { init_ram_condition },
[0x6e] = { init_nv_reg },
[0x6f] = { init_macro },
[0x71] = { init_done },
[0x72] = { init_resume },
[0x74] = { init_time },
[0x75] = { init_condition },
[0x76] = { init_io_condition },
[0x78] = { init_index_io },
[0x79] = { init_pll },
[0x7a] = { init_zm_reg },
[0x87] = { init_ram_restrict_pll },
[0x8c] = { init_reserved },
[0x8d] = { init_reserved },
[0x8e] = { init_gpio },
[0x8f] = { init_ram_restrict_zm_reg_group },
[0x90] = { init_copy_zm_reg },
[0x91] = { init_zm_reg_group },
[0x92] = { init_reserved },
[0x96] = { init_xlat },
[0x97] = { init_zm_mask_add },
[0x98] = { init_auxch },
[0x99] = { init_zm_auxch },
[0x9a] = { init_i2c_long_if },
[0xa9] = { init_gpio_ne },
[0xaa] = { init_reserved },
};
#define init_opcode_nr (sizeof(init_opcode) / sizeof(init_opcode[0]))
int
nvbios_exec(struct nvbios_init *init)
{
init->nested++;
while (init->offset) {
u8 opcode = nv_ro08(init->bios, init->offset);
if (opcode >= init_opcode_nr || !init_opcode[opcode].exec) {
error("unknown opcode 0x%02x\n", opcode);
return -EINVAL;
}
init_opcode[opcode].exec(init);
}
init->nested--;
return 0;
}
int
nvbios_init(struct nouveau_subdev *subdev, bool execute)
{
struct nouveau_bios *bios = nouveau_bios(subdev);
int ret = 0;
int i = -1;
u16 data;
if (execute)
nv_info(bios, "running init tables\n");
while (!ret && (data = (init_script(bios, ++i)))) {
struct nvbios_init init = {
.subdev = subdev,
.bios = bios,
.offset = data,
.outp = NULL,
.crtc = -1,
.execute = execute ? 1 : 0,
};
ret = nvbios_exec(&init);
}
/* the vbios parser will run this right after the normal init
* tables, whereas the binary driver appears to run it later.
*/
if (!ret && (data = init_unknown_script(bios))) {
struct nvbios_init init = {
.subdev = subdev,
.bios = bios,
.offset = data,
.outp = NULL,
.crtc = -1,
.execute = execute ? 1 : 0,
};
ret = nvbios_exec(&init);
}
return 0;
}
| gpl-2.0 |
zhaochengw/NX511J_kernel | drivers/gpu/drm/nouveau/core/subdev/bios/init.c | 1633 | 51078 | #include <core/engine.h>
#include <core/device.h>
#include <subdev/bios.h>
#include <subdev/bios/bmp.h>
#include <subdev/bios/bit.h>
#include <subdev/bios/conn.h>
#include <subdev/bios/dcb.h>
#include <subdev/bios/dp.h>
#include <subdev/bios/gpio.h>
#include <subdev/bios/init.h>
#include <subdev/devinit.h>
#include <subdev/clock.h>
#include <subdev/i2c.h>
#include <subdev/vga.h>
#include <subdev/gpio.h>
#define bioslog(lvl, fmt, args...) do { \
nv_printk(init->bios, lvl, "0x%04x[%c]: "fmt, init->offset, \
init_exec(init) ? '0' + (init->nested - 1) : ' ', ##args); \
} while(0)
#define cont(fmt, args...) do { \
if (nv_subdev(init->bios)->debug >= NV_DBG_TRACE) \
printk(fmt, ##args); \
} while(0)
#define trace(fmt, args...) bioslog(TRACE, fmt, ##args)
#define warn(fmt, args...) bioslog(WARN, fmt, ##args)
#define error(fmt, args...) bioslog(ERROR, fmt, ##args)
/******************************************************************************
* init parser control flow helpers
*****************************************************************************/
static inline bool
init_exec(struct nvbios_init *init)
{
return (init->execute == 1) || ((init->execute & 5) == 5);
}
static inline void
init_exec_set(struct nvbios_init *init, bool exec)
{
if (exec) init->execute &= 0xfd;
else init->execute |= 0x02;
}
static inline void
init_exec_inv(struct nvbios_init *init)
{
init->execute ^= 0x02;
}
static inline void
init_exec_force(struct nvbios_init *init, bool exec)
{
if (exec) init->execute |= 0x04;
else init->execute &= 0xfb;
}
/******************************************************************************
* init parser wrappers for normal register/i2c/whatever accessors
*****************************************************************************/
static inline int
init_or(struct nvbios_init *init)
{
if (init_exec(init)) {
if (init->outp)
return ffs(init->outp->or) - 1;
error("script needs OR!!\n");
}
return 0;
}
static inline int
init_link(struct nvbios_init *init)
{
if (init_exec(init)) {
if (init->outp)
return !(init->outp->sorconf.link & 1);
error("script needs OR link\n");
}
return 0;
}
static inline int
init_crtc(struct nvbios_init *init)
{
if (init_exec(init)) {
if (init->crtc >= 0)
return init->crtc;
error("script needs crtc\n");
}
return 0;
}
static u8
init_conn(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 ver, len;
u16 conn;
if (init_exec(init)) {
if (init->outp) {
conn = init->outp->connector;
conn = dcb_conn(bios, conn, &ver, &len);
if (conn)
return nv_ro08(bios, conn);
}
error("script needs connector type\n");
}
return 0xff;
}
static inline u32
init_nvreg(struct nvbios_init *init, u32 reg)
{
/* C51 (at least) sometimes has the lower bits set which the VBIOS
* interprets to mean that access needs to go through certain IO
* ports instead. The NVIDIA binary driver has been seen to access
* these through the NV register address, so lets assume we can
* do the same
*/
reg &= ~0x00000003;
/* GF8+ display scripts need register addresses mangled a bit to
* select a specific CRTC/OR
*/
if (nv_device(init->bios)->card_type >= NV_50) {
if (reg & 0x80000000) {
reg += init_crtc(init) * 0x800;
reg &= ~0x80000000;
}
if (reg & 0x40000000) {
reg += init_or(init) * 0x800;
reg &= ~0x40000000;
if (reg & 0x20000000) {
reg += init_link(init) * 0x80;
reg &= ~0x20000000;
}
}
}
if (reg & ~0x00fffffc)
warn("unknown bits in register 0x%08x\n", reg);
return reg;
}
static u32
init_rd32(struct nvbios_init *init, u32 reg)
{
reg = init_nvreg(init, reg);
if (init_exec(init))
return nv_rd32(init->subdev, reg);
return 0x00000000;
}
static void
init_wr32(struct nvbios_init *init, u32 reg, u32 val)
{
reg = init_nvreg(init, reg);
if (init_exec(init))
nv_wr32(init->subdev, reg, val);
}
static u32
init_mask(struct nvbios_init *init, u32 reg, u32 mask, u32 val)
{
reg = init_nvreg(init, reg);
if (init_exec(init)) {
u32 tmp = nv_rd32(init->subdev, reg);
nv_wr32(init->subdev, reg, (tmp & ~mask) | val);
return tmp;
}
return 0x00000000;
}
static u8
init_rdport(struct nvbios_init *init, u16 port)
{
if (init_exec(init))
return nv_rdport(init->subdev, init->crtc, port);
return 0x00;
}
static void
init_wrport(struct nvbios_init *init, u16 port, u8 value)
{
if (init_exec(init))
nv_wrport(init->subdev, init->crtc, port, value);
}
static u8
init_rdvgai(struct nvbios_init *init, u16 port, u8 index)
{
struct nouveau_subdev *subdev = init->subdev;
if (init_exec(init)) {
int head = init->crtc < 0 ? 0 : init->crtc;
return nv_rdvgai(subdev, head, port, index);
}
return 0x00;
}
static void
init_wrvgai(struct nvbios_init *init, u16 port, u8 index, u8 value)
{
/* force head 0 for updates to cr44, it only exists on first head */
if (nv_device(init->subdev)->card_type < NV_50) {
if (port == 0x03d4 && index == 0x44)
init->crtc = 0;
}
if (init_exec(init)) {
int head = init->crtc < 0 ? 0 : init->crtc;
nv_wrvgai(init->subdev, head, port, index, value);
}
/* select head 1 if cr44 write selected it */
if (nv_device(init->subdev)->card_type < NV_50) {
if (port == 0x03d4 && index == 0x44 && value == 3)
init->crtc = 1;
}
}
static struct nouveau_i2c_port *
init_i2c(struct nvbios_init *init, int index)
{
struct nouveau_i2c *i2c = nouveau_i2c(init->bios);
if (index == 0xff) {
index = NV_I2C_DEFAULT(0);
if (init->outp && init->outp->i2c_upper_default)
index = NV_I2C_DEFAULT(1);
} else
if (index < 0) {
if (!init->outp) {
if (init_exec(init))
error("script needs output for i2c\n");
return NULL;
}
if (index == -2 && init->outp->location) {
index = NV_I2C_TYPE_EXTAUX(init->outp->extdev);
return i2c->find_type(i2c, index);
}
index = init->outp->i2c_index;
}
return i2c->find(i2c, index);
}
static int
init_rdi2cr(struct nvbios_init *init, u8 index, u8 addr, u8 reg)
{
struct nouveau_i2c_port *port = init_i2c(init, index);
if (port && init_exec(init))
return nv_rdi2cr(port, addr, reg);
return -ENODEV;
}
static int
init_wri2cr(struct nvbios_init *init, u8 index, u8 addr, u8 reg, u8 val)
{
struct nouveau_i2c_port *port = init_i2c(init, index);
if (port && init_exec(init))
return nv_wri2cr(port, addr, reg, val);
return -ENODEV;
}
static int
init_rdauxr(struct nvbios_init *init, u32 addr)
{
struct nouveau_i2c_port *port = init_i2c(init, -2);
u8 data;
if (port && init_exec(init)) {
int ret = nv_rdaux(port, addr, &data, 1);
if (ret)
return ret;
return data;
}
return -ENODEV;
}
static int
init_wrauxr(struct nvbios_init *init, u32 addr, u8 data)
{
struct nouveau_i2c_port *port = init_i2c(init, -2);
if (port && init_exec(init))
return nv_wraux(port, addr, &data, 1);
return -ENODEV;
}
static void
init_prog_pll(struct nvbios_init *init, u32 id, u32 freq)
{
struct nouveau_clock *clk = nouveau_clock(init->bios);
if (clk && clk->pll_set && init_exec(init)) {
int ret = clk->pll_set(clk, id, freq);
if (ret)
warn("failed to prog pll 0x%08x to %dkHz\n", id, freq);
}
}
/******************************************************************************
* parsing of bios structures that are required to execute init tables
*****************************************************************************/
static u16
init_table(struct nouveau_bios *bios, u16 *len)
{
struct bit_entry bit_I;
if (!bit_entry(bios, 'I', &bit_I)) {
*len = bit_I.length;
return bit_I.offset;
}
if (bmp_version(bios) >= 0x0510) {
*len = 14;
return bios->bmp_offset + 75;
}
return 0x0000;
}
static u16
init_table_(struct nvbios_init *init, u16 offset, const char *name)
{
struct nouveau_bios *bios = init->bios;
u16 len, data = init_table(bios, &len);
if (data) {
if (len >= offset + 2) {
data = nv_ro16(bios, data + offset);
if (data)
return data;
warn("%s pointer invalid\n", name);
return 0x0000;
}
warn("init data too short for %s pointer", name);
return 0x0000;
}
warn("init data not found\n");
return 0x0000;
}
#define init_script_table(b) init_table_((b), 0x00, "script table")
#define init_macro_index_table(b) init_table_((b), 0x02, "macro index table")
#define init_macro_table(b) init_table_((b), 0x04, "macro table")
#define init_condition_table(b) init_table_((b), 0x06, "condition table")
#define init_io_condition_table(b) init_table_((b), 0x08, "io condition table")
#define init_io_flag_condition_table(b) init_table_((b), 0x0a, "io flag conditon table")
#define init_function_table(b) init_table_((b), 0x0c, "function table")
#define init_xlat_table(b) init_table_((b), 0x10, "xlat table");
static u16
init_script(struct nouveau_bios *bios, int index)
{
struct nvbios_init init = { .bios = bios };
u16 bmp_ver = bmp_version(bios), data;
if (bmp_ver && bmp_ver < 0x0510) {
if (index > 1 || bmp_ver < 0x0100)
return 0x0000;
data = bios->bmp_offset + (bmp_ver < 0x0200 ? 14 : 18);
return nv_ro16(bios, data + (index * 2));
}
data = init_script_table(&init);
if (data)
return nv_ro16(bios, data + (index * 2));
return 0x0000;
}
static u16
init_unknown_script(struct nouveau_bios *bios)
{
u16 len, data = init_table(bios, &len);
if (data && len >= 16)
return nv_ro16(bios, data + 14);
return 0x0000;
}
static u16
init_ram_restrict_table(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
struct bit_entry bit_M;
u16 data = 0x0000;
if (!bit_entry(bios, 'M', &bit_M)) {
if (bit_M.version == 1 && bit_M.length >= 5)
data = nv_ro16(bios, bit_M.offset + 3);
if (bit_M.version == 2 && bit_M.length >= 3)
data = nv_ro16(bios, bit_M.offset + 1);
}
if (data == 0x0000)
warn("ram restrict table not found\n");
return data;
}
static u8
init_ram_restrict_group_count(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
struct bit_entry bit_M;
if (!bit_entry(bios, 'M', &bit_M)) {
if (bit_M.version == 1 && bit_M.length >= 5)
return nv_ro08(bios, bit_M.offset + 2);
if (bit_M.version == 2 && bit_M.length >= 3)
return nv_ro08(bios, bit_M.offset + 0);
}
return 0x00;
}
static u8
init_ram_restrict_strap(struct nvbios_init *init)
{
/* This appears to be the behaviour of the VBIOS parser, and *is*
* important to cache the NV_PEXTDEV_BOOT0 on later chipsets to
* avoid fucking up the memory controller (somehow) by reading it
* on every INIT_RAM_RESTRICT_ZM_GROUP opcode.
*
* Preserving the non-caching behaviour on earlier chipsets just
* in case *not* re-reading the strap causes similar breakage.
*/
if (!init->ramcfg || init->bios->version.major < 0x70)
init->ramcfg = init_rd32(init, 0x101000);
return (init->ramcfg & 0x00000003c) >> 2;
}
static u8
init_ram_restrict(struct nvbios_init *init)
{
u8 strap = init_ram_restrict_strap(init);
u16 table = init_ram_restrict_table(init);
if (table)
return nv_ro08(init->bios, table + strap);
return 0x00;
}
static u8
init_xlat_(struct nvbios_init *init, u8 index, u8 offset)
{
struct nouveau_bios *bios = init->bios;
u16 table = init_xlat_table(init);
if (table) {
u16 data = nv_ro16(bios, table + (index * 2));
if (data)
return nv_ro08(bios, data + offset);
warn("xlat table pointer %d invalid\n", index);
}
return 0x00;
}
/******************************************************************************
* utility functions used by various init opcode handlers
*****************************************************************************/
static bool
init_condition_met(struct nvbios_init *init, u8 cond)
{
struct nouveau_bios *bios = init->bios;
u16 table = init_condition_table(init);
if (table) {
u32 reg = nv_ro32(bios, table + (cond * 12) + 0);
u32 msk = nv_ro32(bios, table + (cond * 12) + 4);
u32 val = nv_ro32(bios, table + (cond * 12) + 8);
trace("\t[0x%02x] (R[0x%06x] & 0x%08x) == 0x%08x\n",
cond, reg, msk, val);
return (init_rd32(init, reg) & msk) == val;
}
return false;
}
static bool
init_io_condition_met(struct nvbios_init *init, u8 cond)
{
struct nouveau_bios *bios = init->bios;
u16 table = init_io_condition_table(init);
if (table) {
u16 port = nv_ro16(bios, table + (cond * 5) + 0);
u8 index = nv_ro08(bios, table + (cond * 5) + 2);
u8 mask = nv_ro08(bios, table + (cond * 5) + 3);
u8 value = nv_ro08(bios, table + (cond * 5) + 4);
trace("\t[0x%02x] (0x%04x[0x%02x] & 0x%02x) == 0x%02x\n",
cond, port, index, mask, value);
return (init_rdvgai(init, port, index) & mask) == value;
}
return false;
}
static bool
init_io_flag_condition_met(struct nvbios_init *init, u8 cond)
{
struct nouveau_bios *bios = init->bios;
u16 table = init_io_flag_condition_table(init);
if (table) {
u16 port = nv_ro16(bios, table + (cond * 9) + 0);
u8 index = nv_ro08(bios, table + (cond * 9) + 2);
u8 mask = nv_ro08(bios, table + (cond * 9) + 3);
u8 shift = nv_ro08(bios, table + (cond * 9) + 4);
u16 data = nv_ro16(bios, table + (cond * 9) + 5);
u8 dmask = nv_ro08(bios, table + (cond * 9) + 7);
u8 value = nv_ro08(bios, table + (cond * 9) + 8);
u8 ioval = (init_rdvgai(init, port, index) & mask) >> shift;
return (nv_ro08(bios, data + ioval) & dmask) == value;
}
return false;
}
static inline u32
init_shift(u32 data, u8 shift)
{
if (shift < 0x80)
return data >> shift;
return data << (0x100 - shift);
}
static u32
init_tmds_reg(struct nvbios_init *init, u8 tmds)
{
/* For mlv < 0x80, it is an index into a table of TMDS base addresses.
* For mlv == 0x80 use the "or" value of the dcb_entry indexed by
* CR58 for CR57 = 0 to index a table of offsets to the basic
* 0x6808b0 address.
* For mlv == 0x81 use the "or" value of the dcb_entry indexed by
* CR58 for CR57 = 0 to index a table of offsets to the basic
* 0x6808b0 address, and then flip the offset by 8.
*/
const int pramdac_offset[13] = {
0, 0, 0x8, 0, 0x2000, 0, 0, 0, 0x2008, 0, 0, 0, 0x2000 };
const u32 pramdac_table[4] = {
0x6808b0, 0x6808b8, 0x6828b0, 0x6828b8 };
if (tmds >= 0x80) {
if (init->outp) {
u32 dacoffset = pramdac_offset[init->outp->or];
if (tmds == 0x81)
dacoffset ^= 8;
return 0x6808b0 + dacoffset;
}
if (init_exec(init))
error("tmds opcodes need dcb\n");
} else {
if (tmds < ARRAY_SIZE(pramdac_table))
return pramdac_table[tmds];
error("tmds selector 0x%02x unknown\n", tmds);
}
return 0;
}
/******************************************************************************
* init opcode handlers
*****************************************************************************/
/**
* init_reserved - stub for various unknown/unused single-byte opcodes
*
*/
static void
init_reserved(struct nvbios_init *init)
{
u8 opcode = nv_ro08(init->bios, init->offset);
u8 length, i;
switch (opcode) {
case 0xaa:
length = 4;
break;
default:
length = 1;
break;
}
trace("RESERVED 0x%02x\t", opcode);
for (i = 1; i < length; i++)
cont(" 0x%02x", nv_ro08(init->bios, init->offset + i));
cont("\n");
init->offset += length;
}
/**
* INIT_DONE - opcode 0x71
*
*/
static void
init_done(struct nvbios_init *init)
{
trace("DONE\n");
init->offset = 0x0000;
}
/**
* INIT_IO_RESTRICT_PROG - opcode 0x32
*
*/
static void
init_io_restrict_prog(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 port = nv_ro16(bios, init->offset + 1);
u8 index = nv_ro08(bios, init->offset + 3);
u8 mask = nv_ro08(bios, init->offset + 4);
u8 shift = nv_ro08(bios, init->offset + 5);
u8 count = nv_ro08(bios, init->offset + 6);
u32 reg = nv_ro32(bios, init->offset + 7);
u8 conf, i;
trace("IO_RESTRICT_PROG\tR[0x%06x] = "
"((0x%04x[0x%02x] & 0x%02x) >> %d) [{\n",
reg, port, index, mask, shift);
init->offset += 11;
conf = (init_rdvgai(init, port, index) & mask) >> shift;
for (i = 0; i < count; i++) {
u32 data = nv_ro32(bios, init->offset);
if (i == conf) {
trace("\t0x%08x *\n", data);
init_wr32(init, reg, data);
} else {
trace("\t0x%08x\n", data);
}
init->offset += 4;
}
trace("}]\n");
}
/**
* INIT_REPEAT - opcode 0x33
*
*/
static void
init_repeat(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 count = nv_ro08(bios, init->offset + 1);
u16 repeat = init->repeat;
trace("REPEAT\t0x%02x\n", count);
init->offset += 2;
init->repeat = init->offset;
init->repend = init->offset;
while (count--) {
init->offset = init->repeat;
nvbios_exec(init);
if (count)
trace("REPEAT\t0x%02x\n", count);
}
init->offset = init->repend;
init->repeat = repeat;
}
/**
* INIT_IO_RESTRICT_PLL - opcode 0x34
*
*/
static void
init_io_restrict_pll(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 port = nv_ro16(bios, init->offset + 1);
u8 index = nv_ro08(bios, init->offset + 3);
u8 mask = nv_ro08(bios, init->offset + 4);
u8 shift = nv_ro08(bios, init->offset + 5);
s8 iofc = nv_ro08(bios, init->offset + 6);
u8 count = nv_ro08(bios, init->offset + 7);
u32 reg = nv_ro32(bios, init->offset + 8);
u8 conf, i;
trace("IO_RESTRICT_PLL\tR[0x%06x] =PLL= "
"((0x%04x[0x%02x] & 0x%02x) >> 0x%02x) IOFCOND 0x%02x [{\n",
reg, port, index, mask, shift, iofc);
init->offset += 12;
conf = (init_rdvgai(init, port, index) & mask) >> shift;
for (i = 0; i < count; i++) {
u32 freq = nv_ro16(bios, init->offset) * 10;
if (i == conf) {
trace("\t%dkHz *\n", freq);
if (iofc > 0 && init_io_flag_condition_met(init, iofc))
freq *= 2;
init_prog_pll(init, reg, freq);
} else {
trace("\t%dkHz\n", freq);
}
init->offset += 2;
}
trace("}]\n");
}
/**
* INIT_END_REPEAT - opcode 0x36
*
*/
static void
init_end_repeat(struct nvbios_init *init)
{
trace("END_REPEAT\n");
init->offset += 1;
if (init->repeat) {
init->repend = init->offset;
init->offset = 0;
}
}
/**
* INIT_COPY - opcode 0x37
*
*/
static void
init_copy(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 reg = nv_ro32(bios, init->offset + 1);
u8 shift = nv_ro08(bios, init->offset + 5);
u8 smask = nv_ro08(bios, init->offset + 6);
u16 port = nv_ro16(bios, init->offset + 7);
u8 index = nv_ro08(bios, init->offset + 9);
u8 mask = nv_ro08(bios, init->offset + 10);
u8 data;
trace("COPY\t0x%04x[0x%02x] &= 0x%02x |= "
"((R[0x%06x] %s 0x%02x) & 0x%02x)\n",
port, index, mask, reg, (shift & 0x80) ? "<<" : ">>",
(shift & 0x80) ? (0x100 - shift) : shift, smask);
init->offset += 11;
data = init_rdvgai(init, port, index) & mask;
data |= init_shift(init_rd32(init, reg), shift) & smask;
init_wrvgai(init, port, index, data);
}
/**
* INIT_NOT - opcode 0x38
*
*/
static void
init_not(struct nvbios_init *init)
{
trace("NOT\n");
init->offset += 1;
init_exec_inv(init);
}
/**
* INIT_IO_FLAG_CONDITION - opcode 0x39
*
*/
static void
init_io_flag_condition(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 cond = nv_ro08(bios, init->offset + 1);
trace("IO_FLAG_CONDITION\t0x%02x\n", cond);
init->offset += 2;
if (!init_io_flag_condition_met(init, cond))
init_exec_set(init, false);
}
/**
* INIT_DP_CONDITION - opcode 0x3a
*
*/
static void
init_dp_condition(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
struct nvbios_dpout info;
u8 cond = nv_ro08(bios, init->offset + 1);
u8 unkn = nv_ro08(bios, init->offset + 2);
u8 ver, hdr, cnt, len;
u16 data;
trace("DP_CONDITION\t0x%02x 0x%02x\n", cond, unkn);
init->offset += 3;
switch (cond) {
case 0:
if (init_conn(init) != DCB_CONNECTOR_eDP)
init_exec_set(init, false);
break;
case 1:
case 2:
if ( init->outp &&
(data = nvbios_dpout_match(bios, DCB_OUTPUT_DP,
(init->outp->or << 0) |
(init->outp->sorconf.link << 6),
&ver, &hdr, &cnt, &len, &info)))
{
if (!(info.flags & cond))
init_exec_set(init, false);
break;
}
if (init_exec(init))
warn("script needs dp output table data\n");
break;
case 5:
if (!(init_rdauxr(init, 0x0d) & 1))
init_exec_set(init, false);
break;
default:
warn("unknown dp condition 0x%02x\n", cond);
break;
}
}
/**
* INIT_IO_MASK_OR - opcode 0x3b
*
*/
static void
init_io_mask_or(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 index = nv_ro08(bios, init->offset + 1);
u8 or = init_or(init);
u8 data;
trace("IO_MASK_OR\t0x03d4[0x%02x] &= ~(1 << 0x%02x)\n", index, or);
init->offset += 2;
data = init_rdvgai(init, 0x03d4, index);
init_wrvgai(init, 0x03d4, index, data &= ~(1 << or));
}
/**
* INIT_IO_OR - opcode 0x3c
*
*/
static void
init_io_or(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 index = nv_ro08(bios, init->offset + 1);
u8 or = init_or(init);
u8 data;
trace("IO_OR\t0x03d4[0x%02x] |= (1 << 0x%02x)\n", index, or);
init->offset += 2;
data = init_rdvgai(init, 0x03d4, index);
init_wrvgai(init, 0x03d4, index, data | (1 << or));
}
/**
* INIT_INDEX_ADDRESS_LATCHED - opcode 0x49
*
*/
static void
init_idx_addr_latched(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 creg = nv_ro32(bios, init->offset + 1);
u32 dreg = nv_ro32(bios, init->offset + 5);
u32 mask = nv_ro32(bios, init->offset + 9);
u32 data = nv_ro32(bios, init->offset + 13);
u8 count = nv_ro08(bios, init->offset + 17);
trace("INDEX_ADDRESS_LATCHED\t"
"R[0x%06x] : R[0x%06x]\n\tCTRL &= 0x%08x |= 0x%08x\n",
creg, dreg, mask, data);
init->offset += 18;
while (count--) {
u8 iaddr = nv_ro08(bios, init->offset + 0);
u8 idata = nv_ro08(bios, init->offset + 1);
trace("\t[0x%02x] = 0x%02x\n", iaddr, idata);
init->offset += 2;
init_wr32(init, dreg, idata);
init_mask(init, creg, ~mask, data | iaddr);
}
}
/**
* INIT_IO_RESTRICT_PLL2 - opcode 0x4a
*
*/
static void
init_io_restrict_pll2(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 port = nv_ro16(bios, init->offset + 1);
u8 index = nv_ro08(bios, init->offset + 3);
u8 mask = nv_ro08(bios, init->offset + 4);
u8 shift = nv_ro08(bios, init->offset + 5);
u8 count = nv_ro08(bios, init->offset + 6);
u32 reg = nv_ro32(bios, init->offset + 7);
u8 conf, i;
trace("IO_RESTRICT_PLL2\t"
"R[0x%06x] =PLL= ((0x%04x[0x%02x] & 0x%02x) >> 0x%02x) [{\n",
reg, port, index, mask, shift);
init->offset += 11;
conf = (init_rdvgai(init, port, index) & mask) >> shift;
for (i = 0; i < count; i++) {
u32 freq = nv_ro32(bios, init->offset);
if (i == conf) {
trace("\t%dkHz *\n", freq);
init_prog_pll(init, reg, freq);
} else {
trace("\t%dkHz\n", freq);
}
init->offset += 4;
}
trace("}]\n");
}
/**
* INIT_PLL2 - opcode 0x4b
*
*/
static void
init_pll2(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 reg = nv_ro32(bios, init->offset + 1);
u32 freq = nv_ro32(bios, init->offset + 5);
trace("PLL2\tR[0x%06x] =PLL= %dkHz\n", reg, freq);
init->offset += 9;
init_prog_pll(init, reg, freq);
}
/**
* INIT_I2C_BYTE - opcode 0x4c
*
*/
static void
init_i2c_byte(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 index = nv_ro08(bios, init->offset + 1);
u8 addr = nv_ro08(bios, init->offset + 2) >> 1;
u8 count = nv_ro08(bios, init->offset + 3);
trace("I2C_BYTE\tI2C[0x%02x][0x%02x]\n", index, addr);
init->offset += 4;
while (count--) {
u8 reg = nv_ro08(bios, init->offset + 0);
u8 mask = nv_ro08(bios, init->offset + 1);
u8 data = nv_ro08(bios, init->offset + 2);
int val;
trace("\t[0x%02x] &= 0x%02x |= 0x%02x\n", reg, mask, data);
init->offset += 3;
val = init_rdi2cr(init, index, addr, reg);
if (val < 0)
continue;
init_wri2cr(init, index, addr, reg, (val & mask) | data);
}
}
/**
* INIT_ZM_I2C_BYTE - opcode 0x4d
*
*/
static void
init_zm_i2c_byte(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 index = nv_ro08(bios, init->offset + 1);
u8 addr = nv_ro08(bios, init->offset + 2) >> 1;
u8 count = nv_ro08(bios, init->offset + 3);
trace("ZM_I2C_BYTE\tI2C[0x%02x][0x%02x]\n", index, addr);
init->offset += 4;
while (count--) {
u8 reg = nv_ro08(bios, init->offset + 0);
u8 data = nv_ro08(bios, init->offset + 1);
trace("\t[0x%02x] = 0x%02x\n", reg, data);
init->offset += 2;
init_wri2cr(init, index, addr, reg, data);
}
}
/**
* INIT_ZM_I2C - opcode 0x4e
*
*/
static void
init_zm_i2c(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 index = nv_ro08(bios, init->offset + 1);
u8 addr = nv_ro08(bios, init->offset + 2) >> 1;
u8 count = nv_ro08(bios, init->offset + 3);
u8 data[256], i;
trace("ZM_I2C\tI2C[0x%02x][0x%02x]\n", index, addr);
init->offset += 4;
for (i = 0; i < count; i++) {
data[i] = nv_ro08(bios, init->offset);
trace("\t0x%02x\n", data[i]);
init->offset++;
}
if (init_exec(init)) {
struct nouveau_i2c_port *port = init_i2c(init, index);
struct i2c_msg msg = {
.addr = addr, .flags = 0, .len = count, .buf = data,
};
int ret;
if (port && (ret = i2c_transfer(&port->adapter, &msg, 1)) != 1)
warn("i2c wr failed, %d\n", ret);
}
}
/**
* INIT_TMDS - opcode 0x4f
*
*/
static void
init_tmds(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 tmds = nv_ro08(bios, init->offset + 1);
u8 addr = nv_ro08(bios, init->offset + 2);
u8 mask = nv_ro08(bios, init->offset + 3);
u8 data = nv_ro08(bios, init->offset + 4);
u32 reg = init_tmds_reg(init, tmds);
trace("TMDS\tT[0x%02x][0x%02x] &= 0x%02x |= 0x%02x\n",
tmds, addr, mask, data);
init->offset += 5;
if (reg == 0)
return;
init_wr32(init, reg + 0, addr | 0x00010000);
init_wr32(init, reg + 4, data | (init_rd32(init, reg + 4) & mask));
init_wr32(init, reg + 0, addr);
}
/**
* INIT_ZM_TMDS_GROUP - opcode 0x50
*
*/
static void
init_zm_tmds_group(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 tmds = nv_ro08(bios, init->offset + 1);
u8 count = nv_ro08(bios, init->offset + 2);
u32 reg = init_tmds_reg(init, tmds);
trace("TMDS_ZM_GROUP\tT[0x%02x]\n", tmds);
init->offset += 3;
while (count--) {
u8 addr = nv_ro08(bios, init->offset + 0);
u8 data = nv_ro08(bios, init->offset + 1);
trace("\t[0x%02x] = 0x%02x\n", addr, data);
init->offset += 2;
init_wr32(init, reg + 4, data);
init_wr32(init, reg + 0, addr);
}
}
/**
* INIT_CR_INDEX_ADDRESS_LATCHED - opcode 0x51
*
*/
static void
init_cr_idx_adr_latch(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 addr0 = nv_ro08(bios, init->offset + 1);
u8 addr1 = nv_ro08(bios, init->offset + 2);
u8 base = nv_ro08(bios, init->offset + 3);
u8 count = nv_ro08(bios, init->offset + 4);
u8 save0;
trace("CR_INDEX_ADDR C[%02x] C[%02x]\n", addr0, addr1);
init->offset += 5;
save0 = init_rdvgai(init, 0x03d4, addr0);
while (count--) {
u8 data = nv_ro08(bios, init->offset);
trace("\t\t[0x%02x] = 0x%02x\n", base, data);
init->offset += 1;
init_wrvgai(init, 0x03d4, addr0, base++);
init_wrvgai(init, 0x03d4, addr1, data);
}
init_wrvgai(init, 0x03d4, addr0, save0);
}
/**
* INIT_CR - opcode 0x52
*
*/
static void
init_cr(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 addr = nv_ro08(bios, init->offset + 1);
u8 mask = nv_ro08(bios, init->offset + 2);
u8 data = nv_ro08(bios, init->offset + 3);
u8 val;
trace("CR\t\tC[0x%02x] &= 0x%02x |= 0x%02x\n", addr, mask, data);
init->offset += 4;
val = init_rdvgai(init, 0x03d4, addr) & mask;
init_wrvgai(init, 0x03d4, addr, val | data);
}
/**
* INIT_ZM_CR - opcode 0x53
*
*/
static void
init_zm_cr(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 addr = nv_ro08(bios, init->offset + 1);
u8 data = nv_ro08(bios, init->offset + 2);
trace("ZM_CR\tC[0x%02x] = 0x%02x\n", addr, data);
init->offset += 3;
init_wrvgai(init, 0x03d4, addr, data);
}
/**
* INIT_ZM_CR_GROUP - opcode 0x54
*
*/
static void
init_zm_cr_group(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 count = nv_ro08(bios, init->offset + 1);
trace("ZM_CR_GROUP\n");
init->offset += 2;
while (count--) {
u8 addr = nv_ro08(bios, init->offset + 0);
u8 data = nv_ro08(bios, init->offset + 1);
trace("\t\tC[0x%02x] = 0x%02x\n", addr, data);
init->offset += 2;
init_wrvgai(init, 0x03d4, addr, data);
}
}
/**
* INIT_CONDITION_TIME - opcode 0x56
*
*/
static void
init_condition_time(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 cond = nv_ro08(bios, init->offset + 1);
u8 retry = nv_ro08(bios, init->offset + 2);
u8 wait = min((u16)retry * 50, 100);
trace("CONDITION_TIME\t0x%02x 0x%02x\n", cond, retry);
init->offset += 3;
if (!init_exec(init))
return;
while (wait--) {
if (init_condition_met(init, cond))
return;
mdelay(20);
}
init_exec_set(init, false);
}
/**
* INIT_LTIME - opcode 0x57
*
*/
static void
init_ltime(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 msec = nv_ro16(bios, init->offset + 1);
trace("LTIME\t0x%04x\n", msec);
init->offset += 3;
if (init_exec(init))
mdelay(msec);
}
/**
* INIT_ZM_REG_SEQUENCE - opcode 0x58
*
*/
static void
init_zm_reg_sequence(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 base = nv_ro32(bios, init->offset + 1);
u8 count = nv_ro08(bios, init->offset + 5);
trace("ZM_REG_SEQUENCE\t0x%02x\n", count);
init->offset += 6;
while (count--) {
u32 data = nv_ro32(bios, init->offset);
trace("\t\tR[0x%06x] = 0x%08x\n", base, data);
init->offset += 4;
init_wr32(init, base, data);
base += 4;
}
}
/**
* INIT_SUB_DIRECT - opcode 0x5b
*
*/
static void
init_sub_direct(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 addr = nv_ro16(bios, init->offset + 1);
u16 save;
trace("SUB_DIRECT\t0x%04x\n", addr);
if (init_exec(init)) {
save = init->offset;
init->offset = addr;
if (nvbios_exec(init)) {
error("error parsing sub-table\n");
return;
}
init->offset = save;
}
init->offset += 3;
}
/**
* INIT_JUMP - opcode 0x5c
*
*/
static void
init_jump(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 offset = nv_ro16(bios, init->offset + 1);
trace("JUMP\t0x%04x\n", offset);
if (init_exec(init))
init->offset = offset;
else
init->offset += 3;
}
/**
* INIT_I2C_IF - opcode 0x5e
*
*/
static void
init_i2c_if(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 index = nv_ro08(bios, init->offset + 1);
u8 addr = nv_ro08(bios, init->offset + 2);
u8 reg = nv_ro08(bios, init->offset + 3);
u8 mask = nv_ro08(bios, init->offset + 4);
u8 data = nv_ro08(bios, init->offset + 5);
u8 value;
trace("I2C_IF\tI2C[0x%02x][0x%02x][0x%02x] & 0x%02x == 0x%02x\n",
index, addr, reg, mask, data);
init->offset += 6;
init_exec_force(init, true);
value = init_rdi2cr(init, index, addr, reg);
if ((value & mask) != data)
init_exec_set(init, false);
init_exec_force(init, false);
}
/**
* INIT_COPY_NV_REG - opcode 0x5f
*
*/
static void
init_copy_nv_reg(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 sreg = nv_ro32(bios, init->offset + 1);
u8 shift = nv_ro08(bios, init->offset + 5);
u32 smask = nv_ro32(bios, init->offset + 6);
u32 sxor = nv_ro32(bios, init->offset + 10);
u32 dreg = nv_ro32(bios, init->offset + 14);
u32 dmask = nv_ro32(bios, init->offset + 18);
u32 data;
trace("COPY_NV_REG\tR[0x%06x] &= 0x%08x |= "
"((R[0x%06x] %s 0x%02x) & 0x%08x ^ 0x%08x)\n",
dreg, dmask, sreg, (shift & 0x80) ? "<<" : ">>",
(shift & 0x80) ? (0x100 - shift) : shift, smask, sxor);
init->offset += 22;
data = init_shift(init_rd32(init, sreg), shift);
init_mask(init, dreg, ~dmask, (data & smask) ^ sxor);
}
/**
* INIT_ZM_INDEX_IO - opcode 0x62
*
*/
static void
init_zm_index_io(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 port = nv_ro16(bios, init->offset + 1);
u8 index = nv_ro08(bios, init->offset + 3);
u8 data = nv_ro08(bios, init->offset + 4);
trace("ZM_INDEX_IO\tI[0x%04x][0x%02x] = 0x%02x\n", port, index, data);
init->offset += 5;
init_wrvgai(init, port, index, data);
}
/**
* INIT_COMPUTE_MEM - opcode 0x63
*
*/
static void
init_compute_mem(struct nvbios_init *init)
{
struct nouveau_devinit *devinit = nouveau_devinit(init->bios);
trace("COMPUTE_MEM\n");
init->offset += 1;
init_exec_force(init, true);
if (init_exec(init) && devinit->meminit)
devinit->meminit(devinit);
init_exec_force(init, false);
}
/**
* INIT_RESET - opcode 0x65
*
*/
static void
init_reset(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 reg = nv_ro32(bios, init->offset + 1);
u32 data1 = nv_ro32(bios, init->offset + 5);
u32 data2 = nv_ro32(bios, init->offset + 9);
u32 savepci19;
trace("RESET\tR[0x%08x] = 0x%08x, 0x%08x", reg, data1, data2);
init->offset += 13;
init_exec_force(init, true);
savepci19 = init_mask(init, 0x00184c, 0x00000f00, 0x00000000);
init_wr32(init, reg, data1);
udelay(10);
init_wr32(init, reg, data2);
init_wr32(init, 0x00184c, savepci19);
init_mask(init, 0x001850, 0x00000001, 0x00000000);
init_exec_force(init, false);
}
/**
* INIT_CONFIGURE_MEM - opcode 0x66
*
*/
static u16
init_configure_mem_clk(struct nvbios_init *init)
{
u16 mdata = bmp_mem_init_table(init->bios);
if (mdata)
mdata += (init_rdvgai(init, 0x03d4, 0x3c) >> 4) * 66;
return mdata;
}
static void
init_configure_mem(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 mdata, sdata;
u32 addr, data;
trace("CONFIGURE_MEM\n");
init->offset += 1;
if (bios->version.major > 2) {
init_done(init);
return;
}
init_exec_force(init, true);
mdata = init_configure_mem_clk(init);
sdata = bmp_sdr_seq_table(bios);
if (nv_ro08(bios, mdata) & 0x01)
sdata = bmp_ddr_seq_table(bios);
mdata += 6; /* skip to data */
data = init_rdvgai(init, 0x03c4, 0x01);
init_wrvgai(init, 0x03c4, 0x01, data | 0x20);
while ((addr = nv_ro32(bios, sdata)) != 0xffffffff) {
switch (addr) {
case 0x10021c: /* CKE_NORMAL */
case 0x1002d0: /* CMD_REFRESH */
case 0x1002d4: /* CMD_PRECHARGE */
data = 0x00000001;
break;
default:
data = nv_ro32(bios, mdata);
mdata += 4;
if (data == 0xffffffff)
continue;
break;
}
init_wr32(init, addr, data);
}
init_exec_force(init, false);
}
/**
* INIT_CONFIGURE_CLK - opcode 0x67
*
*/
static void
init_configure_clk(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 mdata, clock;
trace("CONFIGURE_CLK\n");
init->offset += 1;
if (bios->version.major > 2) {
init_done(init);
return;
}
init_exec_force(init, true);
mdata = init_configure_mem_clk(init);
/* NVPLL */
clock = nv_ro16(bios, mdata + 4) * 10;
init_prog_pll(init, 0x680500, clock);
/* MPLL */
clock = nv_ro16(bios, mdata + 2) * 10;
if (nv_ro08(bios, mdata) & 0x01)
clock *= 2;
init_prog_pll(init, 0x680504, clock);
init_exec_force(init, false);
}
/**
* INIT_CONFIGURE_PREINIT - opcode 0x68
*
*/
static void
init_configure_preinit(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 strap;
trace("CONFIGURE_PREINIT\n");
init->offset += 1;
if (bios->version.major > 2) {
init_done(init);
return;
}
init_exec_force(init, true);
strap = init_rd32(init, 0x101000);
strap = ((strap << 2) & 0xf0) | ((strap & 0x40) >> 6);
init_wrvgai(init, 0x03d4, 0x3c, strap);
init_exec_force(init, false);
}
/**
* INIT_IO - opcode 0x69
*
*/
static void
init_io(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 port = nv_ro16(bios, init->offset + 1);
u8 mask = nv_ro16(bios, init->offset + 3);
u8 data = nv_ro16(bios, init->offset + 4);
u8 value;
trace("IO\t\tI[0x%04x] &= 0x%02x |= 0x%02x\n", port, mask, data);
init->offset += 5;
/* ummm.. yes.. should really figure out wtf this is and why it's
* needed some day.. it's almost certainly wrong, but, it also
* somehow makes things work...
*/
if (nv_device(init->bios)->card_type >= NV_50 &&
port == 0x03c3 && data == 0x01) {
init_mask(init, 0x614100, 0xf0800000, 0x00800000);
init_mask(init, 0x00e18c, 0x00020000, 0x00020000);
init_mask(init, 0x614900, 0xf0800000, 0x00800000);
init_mask(init, 0x000200, 0x40000000, 0x00000000);
mdelay(10);
init_mask(init, 0x00e18c, 0x00020000, 0x00000000);
init_mask(init, 0x000200, 0x40000000, 0x40000000);
init_wr32(init, 0x614100, 0x00800018);
init_wr32(init, 0x614900, 0x00800018);
mdelay(10);
init_wr32(init, 0x614100, 0x10000018);
init_wr32(init, 0x614900, 0x10000018);
}
value = init_rdport(init, port) & mask;
init_wrport(init, port, data | value);
}
/**
* INIT_SUB - opcode 0x6b
*
*/
static void
init_sub(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 index = nv_ro08(bios, init->offset + 1);
u16 addr, save;
trace("SUB\t0x%02x\n", index);
addr = init_script(bios, index);
if (addr && init_exec(init)) {
save = init->offset;
init->offset = addr;
if (nvbios_exec(init)) {
error("error parsing sub-table\n");
return;
}
init->offset = save;
}
init->offset += 2;
}
/**
* INIT_RAM_CONDITION - opcode 0x6d
*
*/
static void
init_ram_condition(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 mask = nv_ro08(bios, init->offset + 1);
u8 value = nv_ro08(bios, init->offset + 2);
trace("RAM_CONDITION\t"
"(R[0x100000] & 0x%02x) == 0x%02x\n", mask, value);
init->offset += 3;
if ((init_rd32(init, 0x100000) & mask) != value)
init_exec_set(init, false);
}
/**
* INIT_NV_REG - opcode 0x6e
*
*/
static void
init_nv_reg(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 reg = nv_ro32(bios, init->offset + 1);
u32 mask = nv_ro32(bios, init->offset + 5);
u32 data = nv_ro32(bios, init->offset + 9);
trace("NV_REG\tR[0x%06x] &= 0x%08x |= 0x%08x\n", reg, mask, data);
init->offset += 13;
init_mask(init, reg, ~mask, data);
}
/**
* INIT_MACRO - opcode 0x6f
*
*/
static void
init_macro(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 macro = nv_ro08(bios, init->offset + 1);
u16 table;
trace("MACRO\t0x%02x\n", macro);
table = init_macro_table(init);
if (table) {
u32 addr = nv_ro32(bios, table + (macro * 8) + 0);
u32 data = nv_ro32(bios, table + (macro * 8) + 4);
trace("\t\tR[0x%06x] = 0x%08x\n", addr, data);
init_wr32(init, addr, data);
}
init->offset += 2;
}
/**
* INIT_RESUME - opcode 0x72
*
*/
static void
init_resume(struct nvbios_init *init)
{
trace("RESUME\n");
init->offset += 1;
init_exec_set(init, true);
}
/**
* INIT_TIME - opcode 0x74
*
*/
static void
init_time(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 usec = nv_ro16(bios, init->offset + 1);
trace("TIME\t0x%04x\n", usec);
init->offset += 3;
if (init_exec(init)) {
if (usec < 1000)
udelay(usec);
else
mdelay((usec + 900) / 1000);
}
}
/**
* INIT_CONDITION - opcode 0x75
*
*/
static void
init_condition(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 cond = nv_ro08(bios, init->offset + 1);
trace("CONDITION\t0x%02x\n", cond);
init->offset += 2;
if (!init_condition_met(init, cond))
init_exec_set(init, false);
}
/**
* INIT_IO_CONDITION - opcode 0x76
*
*/
static void
init_io_condition(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 cond = nv_ro08(bios, init->offset + 1);
trace("IO_CONDITION\t0x%02x\n", cond);
init->offset += 2;
if (!init_io_condition_met(init, cond))
init_exec_set(init, false);
}
/**
* INIT_INDEX_IO - opcode 0x78
*
*/
static void
init_index_io(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 port = nv_ro16(bios, init->offset + 1);
u8 index = nv_ro16(bios, init->offset + 3);
u8 mask = nv_ro08(bios, init->offset + 4);
u8 data = nv_ro08(bios, init->offset + 5);
u8 value;
trace("INDEX_IO\tI[0x%04x][0x%02x] &= 0x%02x |= 0x%02x\n",
port, index, mask, data);
init->offset += 6;
value = init_rdvgai(init, port, index) & mask;
init_wrvgai(init, port, index, data | value);
}
/**
* INIT_PLL - opcode 0x79
*
*/
static void
init_pll(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 reg = nv_ro32(bios, init->offset + 1);
u32 freq = nv_ro16(bios, init->offset + 5) * 10;
trace("PLL\tR[0x%06x] =PLL= %dkHz\n", reg, freq);
init->offset += 7;
init_prog_pll(init, reg, freq);
}
/**
* INIT_ZM_REG - opcode 0x7a
*
*/
static void
init_zm_reg(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 addr = nv_ro32(bios, init->offset + 1);
u32 data = nv_ro32(bios, init->offset + 5);
trace("ZM_REG\tR[0x%06x] = 0x%08x\n", addr, data);
init->offset += 9;
if (addr == 0x000200)
data |= 0x00000001;
init_wr32(init, addr, data);
}
/**
* INIT_RAM_RESTRICT_PLL - opcde 0x87
*
*/
static void
init_ram_restrict_pll(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 type = nv_ro08(bios, init->offset + 1);
u8 count = init_ram_restrict_group_count(init);
u8 strap = init_ram_restrict(init);
u8 cconf;
trace("RAM_RESTRICT_PLL\t0x%02x\n", type);
init->offset += 2;
for (cconf = 0; cconf < count; cconf++) {
u32 freq = nv_ro32(bios, init->offset);
if (cconf == strap) {
trace("%dkHz *\n", freq);
init_prog_pll(init, type, freq);
} else {
trace("%dkHz\n", freq);
}
init->offset += 4;
}
}
/**
* INIT_GPIO - opcode 0x8e
*
*/
static void
init_gpio(struct nvbios_init *init)
{
struct nouveau_gpio *gpio = nouveau_gpio(init->bios);
trace("GPIO\n");
init->offset += 1;
if (init_exec(init) && gpio && gpio->reset)
gpio->reset(gpio, DCB_GPIO_UNUSED);
}
/**
* INIT_RAM_RESTRICT_ZM_GROUP - opcode 0x8f
*
*/
static void
init_ram_restrict_zm_reg_group(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 addr = nv_ro32(bios, init->offset + 1);
u8 incr = nv_ro08(bios, init->offset + 5);
u8 num = nv_ro08(bios, init->offset + 6);
u8 count = init_ram_restrict_group_count(init);
u8 index = init_ram_restrict(init);
u8 i, j;
trace("RAM_RESTRICT_ZM_REG_GROUP\t"
"R[0x%08x] 0x%02x 0x%02x\n", addr, incr, num);
init->offset += 7;
for (i = 0; i < num; i++) {
trace("\tR[0x%06x] = {\n", addr);
for (j = 0; j < count; j++) {
u32 data = nv_ro32(bios, init->offset);
if (j == index) {
trace("\t\t0x%08x *\n", data);
init_wr32(init, addr, data);
} else {
trace("\t\t0x%08x\n", data);
}
init->offset += 4;
}
trace("\t}\n");
addr += incr;
}
}
/**
* INIT_COPY_ZM_REG - opcode 0x90
*
*/
static void
init_copy_zm_reg(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 sreg = nv_ro32(bios, init->offset + 1);
u32 dreg = nv_ro32(bios, init->offset + 5);
trace("COPY_ZM_REG\tR[0x%06x] = R[0x%06x]\n", dreg, sreg);
init->offset += 9;
init_wr32(init, dreg, init_rd32(init, sreg));
}
/**
* INIT_ZM_REG_GROUP - opcode 0x91
*
*/
static void
init_zm_reg_group(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 addr = nv_ro32(bios, init->offset + 1);
u8 count = nv_ro08(bios, init->offset + 5);
trace("ZM_REG_GROUP\tR[0x%06x] =\n", addr);
init->offset += 6;
while (count--) {
u32 data = nv_ro32(bios, init->offset);
trace("\t0x%08x\n", data);
init_wr32(init, addr, data);
init->offset += 4;
}
}
/**
* INIT_XLAT - opcode 0x96
*
*/
static void
init_xlat(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 saddr = nv_ro32(bios, init->offset + 1);
u8 sshift = nv_ro08(bios, init->offset + 5);
u8 smask = nv_ro08(bios, init->offset + 6);
u8 index = nv_ro08(bios, init->offset + 7);
u32 daddr = nv_ro32(bios, init->offset + 8);
u32 dmask = nv_ro32(bios, init->offset + 12);
u8 shift = nv_ro08(bios, init->offset + 16);
u32 data;
trace("INIT_XLAT\tR[0x%06x] &= 0x%08x |= "
"(X%02x((R[0x%06x] %s 0x%02x) & 0x%02x) << 0x%02x)\n",
daddr, dmask, index, saddr, (sshift & 0x80) ? "<<" : ">>",
(sshift & 0x80) ? (0x100 - sshift) : sshift, smask, shift);
init->offset += 17;
data = init_shift(init_rd32(init, saddr), sshift) & smask;
data = init_xlat_(init, index, data) << shift;
init_mask(init, daddr, ~dmask, data);
}
/**
* INIT_ZM_MASK_ADD - opcode 0x97
*
*/
static void
init_zm_mask_add(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 addr = nv_ro32(bios, init->offset + 1);
u32 mask = nv_ro32(bios, init->offset + 5);
u32 add = nv_ro32(bios, init->offset + 9);
u32 data;
trace("ZM_MASK_ADD\tR[0x%06x] &= 0x%08x += 0x%08x\n", addr, mask, add);
init->offset += 13;
data = init_rd32(init, addr);
data = (data & mask) | ((data + add) & ~mask);
init_wr32(init, addr, data);
}
/**
* INIT_AUXCH - opcode 0x98
*
*/
static void
init_auxch(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 addr = nv_ro32(bios, init->offset + 1);
u8 count = nv_ro08(bios, init->offset + 5);
trace("AUXCH\tAUX[0x%08x] 0x%02x\n", addr, count);
init->offset += 6;
while (count--) {
u8 mask = nv_ro08(bios, init->offset + 0);
u8 data = nv_ro08(bios, init->offset + 1);
trace("\tAUX[0x%08x] &= 0x%02x |= 0x%02x\n", addr, mask, data);
mask = init_rdauxr(init, addr) & mask;
init_wrauxr(init, addr, mask | data);
init->offset += 2;
}
}
/**
* INIT_AUXCH - opcode 0x99
*
*/
static void
init_zm_auxch(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 addr = nv_ro32(bios, init->offset + 1);
u8 count = nv_ro08(bios, init->offset + 5);
trace("ZM_AUXCH\tAUX[0x%08x] 0x%02x\n", addr, count);
init->offset += 6;
while (count--) {
u8 data = nv_ro08(bios, init->offset + 0);
trace("\tAUX[0x%08x] = 0x%02x\n", addr, data);
init_wrauxr(init, addr, data);
init->offset += 1;
}
}
/**
* INIT_I2C_LONG_IF - opcode 0x9a
*
*/
static void
init_i2c_long_if(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 index = nv_ro08(bios, init->offset + 1);
u8 addr = nv_ro08(bios, init->offset + 2) >> 1;
u8 reglo = nv_ro08(bios, init->offset + 3);
u8 reghi = nv_ro08(bios, init->offset + 4);
u8 mask = nv_ro08(bios, init->offset + 5);
u8 data = nv_ro08(bios, init->offset + 6);
struct nouveau_i2c_port *port;
trace("I2C_LONG_IF\t"
"I2C[0x%02x][0x%02x][0x%02x%02x] & 0x%02x == 0x%02x\n",
index, addr, reglo, reghi, mask, data);
init->offset += 7;
port = init_i2c(init, index);
if (port) {
u8 i[2] = { reghi, reglo };
u8 o[1] = {};
struct i2c_msg msg[] = {
{ .addr = addr, .flags = 0, .len = 2, .buf = i },
{ .addr = addr, .flags = I2C_M_RD, .len = 1, .buf = o }
};
int ret;
ret = i2c_transfer(&port->adapter, msg, 2);
if (ret == 2 && ((o[0] & mask) == data))
return;
}
init_exec_set(init, false);
}
/**
* INIT_GPIO_NE - opcode 0xa9
*
*/
static void
init_gpio_ne(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
struct nouveau_gpio *gpio = nouveau_gpio(bios);
struct dcb_gpio_func func;
u8 count = nv_ro08(bios, init->offset + 1);
u8 idx = 0, ver, len;
u16 data, i;
trace("GPIO_NE\t");
init->offset += 2;
for (i = init->offset; i < init->offset + count; i++)
cont("0x%02x ", nv_ro08(bios, i));
cont("\n");
while ((data = dcb_gpio_parse(bios, 0, idx++, &ver, &len, &func))) {
if (func.func != DCB_GPIO_UNUSED) {
for (i = init->offset; i < init->offset + count; i++) {
if (func.func == nv_ro08(bios, i))
break;
}
trace("\tFUNC[0x%02x]", func.func);
if (i == (init->offset + count)) {
cont(" *");
if (init_exec(init) && gpio && gpio->reset)
gpio->reset(gpio, func.func);
}
cont("\n");
}
}
init->offset += count;
}
static struct nvbios_init_opcode {
void (*exec)(struct nvbios_init *);
} init_opcode[] = {
[0x32] = { init_io_restrict_prog },
[0x33] = { init_repeat },
[0x34] = { init_io_restrict_pll },
[0x36] = { init_end_repeat },
[0x37] = { init_copy },
[0x38] = { init_not },
[0x39] = { init_io_flag_condition },
[0x3a] = { init_dp_condition },
[0x3b] = { init_io_mask_or },
[0x3c] = { init_io_or },
[0x49] = { init_idx_addr_latched },
[0x4a] = { init_io_restrict_pll2 },
[0x4b] = { init_pll2 },
[0x4c] = { init_i2c_byte },
[0x4d] = { init_zm_i2c_byte },
[0x4e] = { init_zm_i2c },
[0x4f] = { init_tmds },
[0x50] = { init_zm_tmds_group },
[0x51] = { init_cr_idx_adr_latch },
[0x52] = { init_cr },
[0x53] = { init_zm_cr },
[0x54] = { init_zm_cr_group },
[0x56] = { init_condition_time },
[0x57] = { init_ltime },
[0x58] = { init_zm_reg_sequence },
[0x5b] = { init_sub_direct },
[0x5c] = { init_jump },
[0x5e] = { init_i2c_if },
[0x5f] = { init_copy_nv_reg },
[0x62] = { init_zm_index_io },
[0x63] = { init_compute_mem },
[0x65] = { init_reset },
[0x66] = { init_configure_mem },
[0x67] = { init_configure_clk },
[0x68] = { init_configure_preinit },
[0x69] = { init_io },
[0x6b] = { init_sub },
[0x6d] = { init_ram_condition },
[0x6e] = { init_nv_reg },
[0x6f] = { init_macro },
[0x71] = { init_done },
[0x72] = { init_resume },
[0x74] = { init_time },
[0x75] = { init_condition },
[0x76] = { init_io_condition },
[0x78] = { init_index_io },
[0x79] = { init_pll },
[0x7a] = { init_zm_reg },
[0x87] = { init_ram_restrict_pll },
[0x8c] = { init_reserved },
[0x8d] = { init_reserved },
[0x8e] = { init_gpio },
[0x8f] = { init_ram_restrict_zm_reg_group },
[0x90] = { init_copy_zm_reg },
[0x91] = { init_zm_reg_group },
[0x92] = { init_reserved },
[0x96] = { init_xlat },
[0x97] = { init_zm_mask_add },
[0x98] = { init_auxch },
[0x99] = { init_zm_auxch },
[0x9a] = { init_i2c_long_if },
[0xa9] = { init_gpio_ne },
[0xaa] = { init_reserved },
};
#define init_opcode_nr (sizeof(init_opcode) / sizeof(init_opcode[0]))
int
nvbios_exec(struct nvbios_init *init)
{
init->nested++;
while (init->offset) {
u8 opcode = nv_ro08(init->bios, init->offset);
if (opcode >= init_opcode_nr || !init_opcode[opcode].exec) {
error("unknown opcode 0x%02x\n", opcode);
return -EINVAL;
}
init_opcode[opcode].exec(init);
}
init->nested--;
return 0;
}
int
nvbios_init(struct nouveau_subdev *subdev, bool execute)
{
struct nouveau_bios *bios = nouveau_bios(subdev);
int ret = 0;
int i = -1;
u16 data;
if (execute)
nv_info(bios, "running init tables\n");
while (!ret && (data = (init_script(bios, ++i)))) {
struct nvbios_init init = {
.subdev = subdev,
.bios = bios,
.offset = data,
.outp = NULL,
.crtc = -1,
.execute = execute ? 1 : 0,
};
ret = nvbios_exec(&init);
}
/* the vbios parser will run this right after the normal init
* tables, whereas the binary driver appears to run it later.
*/
if (!ret && (data = init_unknown_script(bios))) {
struct nvbios_init init = {
.subdev = subdev,
.bios = bios,
.offset = data,
.outp = NULL,
.crtc = -1,
.execute = execute ? 1 : 0,
};
ret = nvbios_exec(&init);
}
return 0;
}
| gpl-2.0 |
javelinanddart/android_kernel_htc_msm8974 | sound/soc/soc-cache.c | 2401 | 8023 | /*
* soc-cache.c -- ASoC register cache helpers
*
* Copyright 2009 Wolfson Microelectronics PLC.
*
* Author: Mark Brown <broonie@opensource.wolfsonmicro.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/i2c.h>
#include <linux/spi/spi.h>
#include <sound/soc.h>
#include <linux/bitmap.h>
#include <linux/rbtree.h>
#include <linux/export.h>
#include <trace/events/asoc.h>
static bool snd_soc_set_cache_val(void *base, unsigned int idx,
unsigned int val, unsigned int word_size)
{
switch (word_size) {
case 1: {
u8 *cache = base;
if (cache[idx] == val)
return true;
cache[idx] = val;
break;
}
case 2: {
u16 *cache = base;
if (cache[idx] == val)
return true;
cache[idx] = val;
break;
}
default:
BUG();
}
return false;
}
static unsigned int snd_soc_get_cache_val(const void *base, unsigned int idx,
unsigned int word_size)
{
if (!base)
return -1;
switch (word_size) {
case 1: {
const u8 *cache = base;
return cache[idx];
}
case 2: {
const u16 *cache = base;
return cache[idx];
}
default:
BUG();
}
/* unreachable */
return -1;
}
static int snd_soc_flat_cache_sync(struct snd_soc_codec *codec)
{
int i;
int ret;
const struct snd_soc_codec_driver *codec_drv;
unsigned int val;
codec_drv = codec->driver;
for (i = 0; i < codec_drv->reg_cache_size; ++i) {
ret = snd_soc_cache_read(codec, i, &val);
if (ret)
return ret;
if (codec->reg_def_copy)
if (snd_soc_get_cache_val(codec->reg_def_copy,
i, codec_drv->reg_word_size) == val)
continue;
WARN_ON(!snd_soc_codec_writable_register(codec, i));
ret = snd_soc_write(codec, i, val);
if (ret)
return ret;
dev_dbg(codec->dev, "ASoC: Synced register %#x, value = %#x\n",
i, val);
}
return 0;
}
static int snd_soc_flat_cache_write(struct snd_soc_codec *codec,
unsigned int reg, unsigned int value)
{
snd_soc_set_cache_val(codec->reg_cache, reg, value,
codec->driver->reg_word_size);
return 0;
}
static int snd_soc_flat_cache_read(struct snd_soc_codec *codec,
unsigned int reg, unsigned int *value)
{
*value = snd_soc_get_cache_val(codec->reg_cache, reg,
codec->driver->reg_word_size);
return 0;
}
static int snd_soc_flat_cache_exit(struct snd_soc_codec *codec)
{
if (!codec->reg_cache)
return 0;
kfree(codec->reg_cache);
codec->reg_cache = NULL;
return 0;
}
static int snd_soc_flat_cache_init(struct snd_soc_codec *codec)
{
if (codec->reg_def_copy)
codec->reg_cache = kmemdup(codec->reg_def_copy,
codec->reg_size, GFP_KERNEL);
else
codec->reg_cache = kzalloc(codec->reg_size, GFP_KERNEL);
if (!codec->reg_cache)
return -ENOMEM;
return 0;
}
/* an array of all supported compression types */
static const struct snd_soc_cache_ops cache_types[] = {
/* Flat *must* be the first entry for fallback */
{
.id = SND_SOC_FLAT_COMPRESSION,
.name = "flat",
.init = snd_soc_flat_cache_init,
.exit = snd_soc_flat_cache_exit,
.read = snd_soc_flat_cache_read,
.write = snd_soc_flat_cache_write,
.sync = snd_soc_flat_cache_sync
},
};
int snd_soc_cache_init(struct snd_soc_codec *codec)
{
int i;
for (i = 0; i < ARRAY_SIZE(cache_types); ++i)
if (cache_types[i].id == codec->compress_type)
break;
/* Fall back to flat compression */
if (i == ARRAY_SIZE(cache_types)) {
dev_warn(codec->dev, "ASoC: Could not match compress type: %d\n",
codec->compress_type);
i = 0;
}
mutex_init(&codec->cache_rw_mutex);
codec->cache_ops = &cache_types[i];
if (codec->cache_ops->init) {
if (codec->cache_ops->name)
dev_dbg(codec->dev, "ASoC: Initializing %s cache for %s codec\n",
codec->cache_ops->name, codec->name);
return codec->cache_ops->init(codec);
}
return -ENOSYS;
}
/*
* NOTE: keep in mind that this function might be called
* multiple times.
*/
int snd_soc_cache_exit(struct snd_soc_codec *codec)
{
if (codec->cache_ops && codec->cache_ops->exit) {
if (codec->cache_ops->name)
dev_dbg(codec->dev, "ASoC: Destroying %s cache for %s codec\n",
codec->cache_ops->name, codec->name);
return codec->cache_ops->exit(codec);
}
return -ENOSYS;
}
/**
* snd_soc_cache_read: Fetch the value of a given register from the cache.
*
* @codec: CODEC to configure.
* @reg: The register index.
* @value: The value to be returned.
*/
int snd_soc_cache_read(struct snd_soc_codec *codec,
unsigned int reg, unsigned int *value)
{
int ret;
mutex_lock(&codec->cache_rw_mutex);
if (value && codec->cache_ops && codec->cache_ops->read) {
ret = codec->cache_ops->read(codec, reg, value);
mutex_unlock(&codec->cache_rw_mutex);
return ret;
}
mutex_unlock(&codec->cache_rw_mutex);
return -ENOSYS;
}
EXPORT_SYMBOL_GPL(snd_soc_cache_read);
/**
* snd_soc_cache_write: Set the value of a given register in the cache.
*
* @codec: CODEC to configure.
* @reg: The register index.
* @value: The new register value.
*/
int snd_soc_cache_write(struct snd_soc_codec *codec,
unsigned int reg, unsigned int value)
{
int ret;
mutex_lock(&codec->cache_rw_mutex);
if (codec->cache_ops && codec->cache_ops->write) {
ret = codec->cache_ops->write(codec, reg, value);
mutex_unlock(&codec->cache_rw_mutex);
return ret;
}
mutex_unlock(&codec->cache_rw_mutex);
return -ENOSYS;
}
EXPORT_SYMBOL_GPL(snd_soc_cache_write);
/**
* snd_soc_cache_sync: Sync the register cache with the hardware.
*
* @codec: CODEC to configure.
*
* Any registers that should not be synced should be marked as
* volatile. In general drivers can choose not to use the provided
* syncing functionality if they so require.
*/
int snd_soc_cache_sync(struct snd_soc_codec *codec)
{
int ret;
const char *name;
if (!codec->cache_sync) {
return 0;
}
if (!codec->cache_ops || !codec->cache_ops->sync)
return -ENOSYS;
if (codec->cache_ops->name)
name = codec->cache_ops->name;
else
name = "unknown";
if (codec->cache_ops->name)
dev_dbg(codec->dev, "ASoC: Syncing %s cache for %s codec\n",
codec->cache_ops->name, codec->name);
trace_snd_soc_cache_sync(codec, name, "start");
ret = codec->cache_ops->sync(codec);
if (!ret)
codec->cache_sync = 0;
trace_snd_soc_cache_sync(codec, name, "end");
return ret;
}
EXPORT_SYMBOL_GPL(snd_soc_cache_sync);
static int snd_soc_get_reg_access_index(struct snd_soc_codec *codec,
unsigned int reg)
{
const struct snd_soc_codec_driver *codec_drv;
unsigned int min, max, index;
codec_drv = codec->driver;
min = 0;
max = codec_drv->reg_access_size - 1;
do {
index = (min + max) / 2;
if (codec_drv->reg_access_default[index].reg == reg)
return index;
if (codec_drv->reg_access_default[index].reg < reg)
min = index + 1;
else
max = index;
} while (min <= max);
return -1;
}
int snd_soc_default_volatile_register(struct snd_soc_codec *codec,
unsigned int reg)
{
int index;
if (reg >= codec->driver->reg_cache_size)
return 1;
index = snd_soc_get_reg_access_index(codec, reg);
if (index < 0)
return 0;
return codec->driver->reg_access_default[index].vol;
}
EXPORT_SYMBOL_GPL(snd_soc_default_volatile_register);
int snd_soc_default_readable_register(struct snd_soc_codec *codec,
unsigned int reg)
{
int index;
if (reg >= codec->driver->reg_cache_size)
return 1;
index = snd_soc_get_reg_access_index(codec, reg);
if (index < 0)
return 0;
return codec->driver->reg_access_default[index].read;
}
EXPORT_SYMBOL_GPL(snd_soc_default_readable_register);
int snd_soc_default_writable_register(struct snd_soc_codec *codec,
unsigned int reg)
{
int index;
if (reg >= codec->driver->reg_cache_size)
return 1;
index = snd_soc_get_reg_access_index(codec, reg);
if (index < 0)
return 0;
return codec->driver->reg_access_default[index].write;
}
EXPORT_SYMBOL_GPL(snd_soc_default_writable_register);
| gpl-2.0 |
jbott/android_kernel_lge_hammerhead | net/ipv6/ip6_fib.c | 2657 | 36546 | /*
* Linux INET6 implementation
* Forwarding Information Database
*
* Authors:
* Pedro Roque <roque@di.fc.ul.pt>
*
* 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.
*/
/*
* Changes:
* Yuji SEKIYA @USAGI: Support default route on router node;
* remove ip6_null_entry from the top of
* routing table.
* Ville Nuorvala: Fixed routing subtrees.
*/
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/net.h>
#include <linux/route.h>
#include <linux/netdevice.h>
#include <linux/in6.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <net/ipv6.h>
#include <net/ndisc.h>
#include <net/addrconf.h>
#include <net/ip6_fib.h>
#include <net/ip6_route.h>
#define RT6_DEBUG 2
#if RT6_DEBUG >= 3
#define RT6_TRACE(x...) printk(KERN_DEBUG x)
#else
#define RT6_TRACE(x...) do { ; } while (0)
#endif
static struct kmem_cache * fib6_node_kmem __read_mostly;
enum fib_walk_state_t
{
#ifdef CONFIG_IPV6_SUBTREES
FWS_S,
#endif
FWS_L,
FWS_R,
FWS_C,
FWS_U
};
struct fib6_cleaner_t
{
struct fib6_walker_t w;
struct net *net;
int (*func)(struct rt6_info *, void *arg);
void *arg;
};
static DEFINE_RWLOCK(fib6_walker_lock);
#ifdef CONFIG_IPV6_SUBTREES
#define FWS_INIT FWS_S
#else
#define FWS_INIT FWS_L
#endif
static void fib6_prune_clones(struct net *net, struct fib6_node *fn,
struct rt6_info *rt);
static struct rt6_info *fib6_find_prefix(struct net *net, struct fib6_node *fn);
static struct fib6_node *fib6_repair_tree(struct net *net, struct fib6_node *fn);
static int fib6_walk(struct fib6_walker_t *w);
static int fib6_walk_continue(struct fib6_walker_t *w);
/*
* A routing update causes an increase of the serial number on the
* affected subtree. This allows for cached routes to be asynchronously
* tested when modifications are made to the destination cache as a
* result of redirects, path MTU changes, etc.
*/
static __u32 rt_sernum;
static void fib6_gc_timer_cb(unsigned long arg);
static LIST_HEAD(fib6_walkers);
#define FOR_WALKERS(w) list_for_each_entry(w, &fib6_walkers, lh)
static inline void fib6_walker_link(struct fib6_walker_t *w)
{
write_lock_bh(&fib6_walker_lock);
list_add(&w->lh, &fib6_walkers);
write_unlock_bh(&fib6_walker_lock);
}
static inline void fib6_walker_unlink(struct fib6_walker_t *w)
{
write_lock_bh(&fib6_walker_lock);
list_del(&w->lh);
write_unlock_bh(&fib6_walker_lock);
}
static __inline__ u32 fib6_new_sernum(void)
{
u32 n = ++rt_sernum;
if ((__s32)n <= 0)
rt_sernum = n = 1;
return n;
}
/*
* Auxiliary address test functions for the radix tree.
*
* These assume a 32bit processor (although it will work on
* 64bit processors)
*/
/*
* test bit
*/
#if defined(__LITTLE_ENDIAN)
# define BITOP_BE32_SWIZZLE (0x1F & ~7)
#else
# define BITOP_BE32_SWIZZLE 0
#endif
static __inline__ __be32 addr_bit_set(const void *token, int fn_bit)
{
const __be32 *addr = token;
/*
* Here,
* 1 << ((~fn_bit ^ BITOP_BE32_SWIZZLE) & 0x1f)
* is optimized version of
* htonl(1 << ((~fn_bit)&0x1F))
* See include/asm-generic/bitops/le.h.
*/
return (__force __be32)(1 << ((~fn_bit ^ BITOP_BE32_SWIZZLE) & 0x1f)) &
addr[fn_bit >> 5];
}
static __inline__ struct fib6_node * node_alloc(void)
{
struct fib6_node *fn;
fn = kmem_cache_zalloc(fib6_node_kmem, GFP_ATOMIC);
return fn;
}
static __inline__ void node_free(struct fib6_node * fn)
{
kmem_cache_free(fib6_node_kmem, fn);
}
static __inline__ void rt6_release(struct rt6_info *rt)
{
if (atomic_dec_and_test(&rt->rt6i_ref))
dst_free(&rt->dst);
}
static void fib6_link_table(struct net *net, struct fib6_table *tb)
{
unsigned int h;
/*
* Initialize table lock at a single place to give lockdep a key,
* tables aren't visible prior to being linked to the list.
*/
rwlock_init(&tb->tb6_lock);
h = tb->tb6_id & (FIB6_TABLE_HASHSZ - 1);
/*
* No protection necessary, this is the only list mutatation
* operation, tables never disappear once they exist.
*/
hlist_add_head_rcu(&tb->tb6_hlist, &net->ipv6.fib_table_hash[h]);
}
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
static struct fib6_table *fib6_alloc_table(struct net *net, u32 id)
{
struct fib6_table *table;
table = kzalloc(sizeof(*table), GFP_ATOMIC);
if (table) {
table->tb6_id = id;
table->tb6_root.leaf = net->ipv6.ip6_null_entry;
table->tb6_root.fn_flags = RTN_ROOT | RTN_TL_ROOT | RTN_RTINFO;
}
return table;
}
struct fib6_table *fib6_new_table(struct net *net, u32 id)
{
struct fib6_table *tb;
if (id == 0)
id = RT6_TABLE_MAIN;
tb = fib6_get_table(net, id);
if (tb)
return tb;
tb = fib6_alloc_table(net, id);
if (tb)
fib6_link_table(net, tb);
return tb;
}
struct fib6_table *fib6_get_table(struct net *net, u32 id)
{
struct fib6_table *tb;
struct hlist_head *head;
struct hlist_node *node;
unsigned int h;
if (id == 0)
id = RT6_TABLE_MAIN;
h = id & (FIB6_TABLE_HASHSZ - 1);
rcu_read_lock();
head = &net->ipv6.fib_table_hash[h];
hlist_for_each_entry_rcu(tb, node, head, tb6_hlist) {
if (tb->tb6_id == id) {
rcu_read_unlock();
return tb;
}
}
rcu_read_unlock();
return NULL;
}
static void __net_init fib6_tables_init(struct net *net)
{
fib6_link_table(net, net->ipv6.fib6_main_tbl);
fib6_link_table(net, net->ipv6.fib6_local_tbl);
}
#else
struct fib6_table *fib6_new_table(struct net *net, u32 id)
{
return fib6_get_table(net, id);
}
struct fib6_table *fib6_get_table(struct net *net, u32 id)
{
return net->ipv6.fib6_main_tbl;
}
struct dst_entry *fib6_rule_lookup(struct net *net, struct flowi6 *fl6,
int flags, pol_lookup_t lookup)
{
return (struct dst_entry *) lookup(net, net->ipv6.fib6_main_tbl, fl6, flags);
}
static void __net_init fib6_tables_init(struct net *net)
{
fib6_link_table(net, net->ipv6.fib6_main_tbl);
}
#endif
static int fib6_dump_node(struct fib6_walker_t *w)
{
int res;
struct rt6_info *rt;
for (rt = w->leaf; rt; rt = rt->dst.rt6_next) {
res = rt6_dump_route(rt, w->args);
if (res < 0) {
/* Frame is full, suspend walking */
w->leaf = rt;
return 1;
}
WARN_ON(res == 0);
}
w->leaf = NULL;
return 0;
}
static void fib6_dump_end(struct netlink_callback *cb)
{
struct fib6_walker_t *w = (void*)cb->args[2];
if (w) {
if (cb->args[4]) {
cb->args[4] = 0;
fib6_walker_unlink(w);
}
cb->args[2] = 0;
kfree(w);
}
cb->done = (void*)cb->args[3];
cb->args[1] = 3;
}
static int fib6_dump_done(struct netlink_callback *cb)
{
fib6_dump_end(cb);
return cb->done ? cb->done(cb) : 0;
}
static int fib6_dump_table(struct fib6_table *table, struct sk_buff *skb,
struct netlink_callback *cb)
{
struct fib6_walker_t *w;
int res;
w = (void *)cb->args[2];
w->root = &table->tb6_root;
if (cb->args[4] == 0) {
w->count = 0;
w->skip = 0;
read_lock_bh(&table->tb6_lock);
res = fib6_walk(w);
read_unlock_bh(&table->tb6_lock);
if (res > 0) {
cb->args[4] = 1;
cb->args[5] = w->root->fn_sernum;
}
} else {
if (cb->args[5] != w->root->fn_sernum) {
/* Begin at the root if the tree changed */
cb->args[5] = w->root->fn_sernum;
w->state = FWS_INIT;
w->node = w->root;
w->skip = w->count;
} else
w->skip = 0;
read_lock_bh(&table->tb6_lock);
res = fib6_walk_continue(w);
read_unlock_bh(&table->tb6_lock);
if (res <= 0) {
fib6_walker_unlink(w);
cb->args[4] = 0;
}
}
return res;
}
static int inet6_dump_fib(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
unsigned int h, s_h;
unsigned int e = 0, s_e;
struct rt6_rtnl_dump_arg arg;
struct fib6_walker_t *w;
struct fib6_table *tb;
struct hlist_node *node;
struct hlist_head *head;
int res = 0;
s_h = cb->args[0];
s_e = cb->args[1];
w = (void *)cb->args[2];
if (!w) {
/* New dump:
*
* 1. hook callback destructor.
*/
cb->args[3] = (long)cb->done;
cb->done = fib6_dump_done;
/*
* 2. allocate and initialize walker.
*/
w = kzalloc(sizeof(*w), GFP_ATOMIC);
if (!w)
return -ENOMEM;
w->func = fib6_dump_node;
cb->args[2] = (long)w;
}
arg.skb = skb;
arg.cb = cb;
arg.net = net;
w->args = &arg;
rcu_read_lock();
for (h = s_h; h < FIB6_TABLE_HASHSZ; h++, s_e = 0) {
e = 0;
head = &net->ipv6.fib_table_hash[h];
hlist_for_each_entry_rcu(tb, node, head, tb6_hlist) {
if (e < s_e)
goto next;
res = fib6_dump_table(tb, skb, cb);
if (res != 0)
goto out;
next:
e++;
}
}
out:
rcu_read_unlock();
cb->args[1] = e;
cb->args[0] = h;
res = res < 0 ? res : skb->len;
if (res <= 0)
fib6_dump_end(cb);
return res;
}
/*
* Routing Table
*
* return the appropriate node for a routing tree "add" operation
* by either creating and inserting or by returning an existing
* node.
*/
static struct fib6_node * fib6_add_1(struct fib6_node *root, void *addr,
int addrlen, int plen,
int offset, int allow_create,
int replace_required)
{
struct fib6_node *fn, *in, *ln;
struct fib6_node *pn = NULL;
struct rt6key *key;
int bit;
__be32 dir = 0;
__u32 sernum = fib6_new_sernum();
RT6_TRACE("fib6_add_1\n");
/* insert node in tree */
fn = root;
do {
key = (struct rt6key *)((u8 *)fn->leaf + offset);
/*
* Prefix match
*/
if (plen < fn->fn_bit ||
!ipv6_prefix_equal(&key->addr, addr, fn->fn_bit)) {
if (!allow_create) {
if (replace_required) {
pr_warn("IPv6: Can't replace route, "
"no match found\n");
return ERR_PTR(-ENOENT);
}
pr_warn("IPv6: NLM_F_CREATE should be set "
"when creating new route\n");
}
goto insert_above;
}
/*
* Exact match ?
*/
if (plen == fn->fn_bit) {
/* clean up an intermediate node */
if (!(fn->fn_flags & RTN_RTINFO)) {
rt6_release(fn->leaf);
fn->leaf = NULL;
}
fn->fn_sernum = sernum;
return fn;
}
/*
* We have more bits to go
*/
/* Try to walk down on tree. */
fn->fn_sernum = sernum;
dir = addr_bit_set(addr, fn->fn_bit);
pn = fn;
fn = dir ? fn->right: fn->left;
} while (fn);
if (!allow_create) {
/* We should not create new node because
* NLM_F_REPLACE was specified without NLM_F_CREATE
* I assume it is safe to require NLM_F_CREATE when
* REPLACE flag is used! Later we may want to remove the
* check for replace_required, because according
* to netlink specification, NLM_F_CREATE
* MUST be specified if new route is created.
* That would keep IPv6 consistent with IPv4
*/
if (replace_required) {
pr_warn("IPv6: Can't replace route, no match found\n");
return ERR_PTR(-ENOENT);
}
pr_warn("IPv6: NLM_F_CREATE should be set "
"when creating new route\n");
}
/*
* We walked to the bottom of tree.
* Create new leaf node without children.
*/
ln = node_alloc();
if (!ln)
return NULL;
ln->fn_bit = plen;
ln->parent = pn;
ln->fn_sernum = sernum;
if (dir)
pn->right = ln;
else
pn->left = ln;
return ln;
insert_above:
/*
* split since we don't have a common prefix anymore or
* we have a less significant route.
* we've to insert an intermediate node on the list
* this new node will point to the one we need to create
* and the current
*/
pn = fn->parent;
/* find 1st bit in difference between the 2 addrs.
See comment in __ipv6_addr_diff: bit may be an invalid value,
but if it is >= plen, the value is ignored in any case.
*/
bit = __ipv6_addr_diff(addr, &key->addr, addrlen);
/*
* (intermediate)[in]
* / \
* (new leaf node)[ln] (old node)[fn]
*/
if (plen > bit) {
in = node_alloc();
ln = node_alloc();
if (!in || !ln) {
if (in)
node_free(in);
if (ln)
node_free(ln);
return NULL;
}
/*
* new intermediate node.
* RTN_RTINFO will
* be off since that an address that chooses one of
* the branches would not match less specific routes
* in the other branch
*/
in->fn_bit = bit;
in->parent = pn;
in->leaf = fn->leaf;
atomic_inc(&in->leaf->rt6i_ref);
in->fn_sernum = sernum;
/* update parent pointer */
if (dir)
pn->right = in;
else
pn->left = in;
ln->fn_bit = plen;
ln->parent = in;
fn->parent = in;
ln->fn_sernum = sernum;
if (addr_bit_set(addr, bit)) {
in->right = ln;
in->left = fn;
} else {
in->left = ln;
in->right = fn;
}
} else { /* plen <= bit */
/*
* (new leaf node)[ln]
* / \
* (old node)[fn] NULL
*/
ln = node_alloc();
if (!ln)
return NULL;
ln->fn_bit = plen;
ln->parent = pn;
ln->fn_sernum = sernum;
if (dir)
pn->right = ln;
else
pn->left = ln;
if (addr_bit_set(&key->addr, plen))
ln->right = fn;
else
ln->left = fn;
fn->parent = ln;
}
return ln;
}
/*
* Insert routing information in a node.
*/
static int fib6_add_rt2node(struct fib6_node *fn, struct rt6_info *rt,
struct nl_info *info)
{
struct rt6_info *iter = NULL;
struct rt6_info **ins;
int replace = (info->nlh &&
(info->nlh->nlmsg_flags & NLM_F_REPLACE));
int add = (!info->nlh ||
(info->nlh->nlmsg_flags & NLM_F_CREATE));
int found = 0;
ins = &fn->leaf;
for (iter = fn->leaf; iter; iter = iter->dst.rt6_next) {
/*
* Search for duplicates
*/
if (iter->rt6i_metric == rt->rt6i_metric) {
/*
* Same priority level
*/
if (info->nlh &&
(info->nlh->nlmsg_flags & NLM_F_EXCL))
return -EEXIST;
if (replace) {
found++;
break;
}
if (iter->dst.dev == rt->dst.dev &&
iter->rt6i_idev == rt->rt6i_idev &&
ipv6_addr_equal(&iter->rt6i_gateway,
&rt->rt6i_gateway)) {
if (!(iter->rt6i_flags & RTF_EXPIRES))
return -EEXIST;
if (!(rt->rt6i_flags & RTF_EXPIRES))
rt6_clean_expires(iter);
else
rt6_set_expires(iter, rt->dst.expires);
return -EEXIST;
}
}
if (iter->rt6i_metric > rt->rt6i_metric)
break;
ins = &iter->dst.rt6_next;
}
/* Reset round-robin state, if necessary */
if (ins == &fn->leaf)
fn->rr_ptr = NULL;
/*
* insert node
*/
if (!replace) {
if (!add)
pr_warn("IPv6: NLM_F_CREATE should be set when creating new route\n");
add:
rt->dst.rt6_next = iter;
*ins = rt;
rt->rt6i_node = fn;
atomic_inc(&rt->rt6i_ref);
inet6_rt_notify(RTM_NEWROUTE, rt, info);
info->nl_net->ipv6.rt6_stats->fib_rt_entries++;
if (!(fn->fn_flags & RTN_RTINFO)) {
info->nl_net->ipv6.rt6_stats->fib_route_nodes++;
fn->fn_flags |= RTN_RTINFO;
}
} else {
if (!found) {
if (add)
goto add;
pr_warn("IPv6: NLM_F_REPLACE set, but no existing node found!\n");
return -ENOENT;
}
*ins = rt;
rt->rt6i_node = fn;
rt->dst.rt6_next = iter->dst.rt6_next;
atomic_inc(&rt->rt6i_ref);
inet6_rt_notify(RTM_NEWROUTE, rt, info);
rt6_release(iter);
if (!(fn->fn_flags & RTN_RTINFO)) {
info->nl_net->ipv6.rt6_stats->fib_route_nodes++;
fn->fn_flags |= RTN_RTINFO;
}
}
return 0;
}
static __inline__ void fib6_start_gc(struct net *net, struct rt6_info *rt)
{
if (!timer_pending(&net->ipv6.ip6_fib_timer) &&
(rt->rt6i_flags & (RTF_EXPIRES | RTF_CACHE)))
mod_timer(&net->ipv6.ip6_fib_timer,
jiffies + net->ipv6.sysctl.ip6_rt_gc_interval);
}
void fib6_force_start_gc(struct net *net)
{
if (!timer_pending(&net->ipv6.ip6_fib_timer))
mod_timer(&net->ipv6.ip6_fib_timer,
jiffies + net->ipv6.sysctl.ip6_rt_gc_interval);
}
/*
* Add routing information to the routing tree.
* <destination addr>/<source addr>
* with source addr info in sub-trees
*/
int fib6_add(struct fib6_node *root, struct rt6_info *rt, struct nl_info *info)
{
struct fib6_node *fn, *pn = NULL;
int err = -ENOMEM;
int allow_create = 1;
int replace_required = 0;
if (info->nlh) {
if (!(info->nlh->nlmsg_flags & NLM_F_CREATE))
allow_create = 0;
if (info->nlh->nlmsg_flags & NLM_F_REPLACE)
replace_required = 1;
}
if (!allow_create && !replace_required)
pr_warn("IPv6: RTM_NEWROUTE with no NLM_F_CREATE or NLM_F_REPLACE\n");
fn = fib6_add_1(root, &rt->rt6i_dst.addr, sizeof(struct in6_addr),
rt->rt6i_dst.plen, offsetof(struct rt6_info, rt6i_dst),
allow_create, replace_required);
if (IS_ERR(fn)) {
err = PTR_ERR(fn);
fn = NULL;
}
if (!fn)
goto out;
pn = fn;
#ifdef CONFIG_IPV6_SUBTREES
if (rt->rt6i_src.plen) {
struct fib6_node *sn;
if (!fn->subtree) {
struct fib6_node *sfn;
/*
* Create subtree.
*
* fn[main tree]
* |
* sfn[subtree root]
* \
* sn[new leaf node]
*/
/* Create subtree root node */
sfn = node_alloc();
if (!sfn)
goto st_failure;
sfn->leaf = info->nl_net->ipv6.ip6_null_entry;
atomic_inc(&info->nl_net->ipv6.ip6_null_entry->rt6i_ref);
sfn->fn_flags = RTN_ROOT;
sfn->fn_sernum = fib6_new_sernum();
/* Now add the first leaf node to new subtree */
sn = fib6_add_1(sfn, &rt->rt6i_src.addr,
sizeof(struct in6_addr), rt->rt6i_src.plen,
offsetof(struct rt6_info, rt6i_src),
allow_create, replace_required);
if (!sn) {
/* If it is failed, discard just allocated
root, and then (in st_failure) stale node
in main tree.
*/
node_free(sfn);
goto st_failure;
}
/* Now link new subtree to main tree */
sfn->parent = fn;
fn->subtree = sfn;
} else {
sn = fib6_add_1(fn->subtree, &rt->rt6i_src.addr,
sizeof(struct in6_addr), rt->rt6i_src.plen,
offsetof(struct rt6_info, rt6i_src),
allow_create, replace_required);
if (IS_ERR(sn)) {
err = PTR_ERR(sn);
sn = NULL;
}
if (!sn)
goto st_failure;
}
if (!fn->leaf) {
fn->leaf = rt;
atomic_inc(&rt->rt6i_ref);
}
fn = sn;
}
#endif
err = fib6_add_rt2node(fn, rt, info);
if (!err) {
fib6_start_gc(info->nl_net, rt);
if (!(rt->rt6i_flags & RTF_CACHE))
fib6_prune_clones(info->nl_net, pn, rt);
}
out:
if (err) {
#ifdef CONFIG_IPV6_SUBTREES
/*
* If fib6_add_1 has cleared the old leaf pointer in the
* super-tree leaf node we have to find a new one for it.
*/
if (pn != fn && pn->leaf == rt) {
pn->leaf = NULL;
atomic_dec(&rt->rt6i_ref);
}
if (pn != fn && !pn->leaf && !(pn->fn_flags & RTN_RTINFO)) {
pn->leaf = fib6_find_prefix(info->nl_net, pn);
#if RT6_DEBUG >= 2
if (!pn->leaf) {
WARN_ON(pn->leaf == NULL);
pn->leaf = info->nl_net->ipv6.ip6_null_entry;
}
#endif
atomic_inc(&pn->leaf->rt6i_ref);
}
#endif
dst_free(&rt->dst);
}
return err;
#ifdef CONFIG_IPV6_SUBTREES
/* Subtree creation failed, probably main tree node
is orphan. If it is, shoot it.
*/
st_failure:
if (fn && !(fn->fn_flags & (RTN_RTINFO|RTN_ROOT)))
fib6_repair_tree(info->nl_net, fn);
dst_free(&rt->dst);
return err;
#endif
}
/*
* Routing tree lookup
*
*/
struct lookup_args {
int offset; /* key offset on rt6_info */
const struct in6_addr *addr; /* search key */
};
static struct fib6_node * fib6_lookup_1(struct fib6_node *root,
struct lookup_args *args)
{
struct fib6_node *fn;
__be32 dir;
if (unlikely(args->offset == 0))
return NULL;
/*
* Descend on a tree
*/
fn = root;
for (;;) {
struct fib6_node *next;
dir = addr_bit_set(args->addr, fn->fn_bit);
next = dir ? fn->right : fn->left;
if (next) {
fn = next;
continue;
}
break;
}
while (fn) {
if (FIB6_SUBTREE(fn) || fn->fn_flags & RTN_RTINFO) {
struct rt6key *key;
key = (struct rt6key *) ((u8 *) fn->leaf +
args->offset);
if (ipv6_prefix_equal(&key->addr, args->addr, key->plen)) {
#ifdef CONFIG_IPV6_SUBTREES
if (fn->subtree)
fn = fib6_lookup_1(fn->subtree, args + 1);
#endif
if (!fn || fn->fn_flags & RTN_RTINFO)
return fn;
}
}
if (fn->fn_flags & RTN_ROOT)
break;
fn = fn->parent;
}
return NULL;
}
struct fib6_node * fib6_lookup(struct fib6_node *root, const struct in6_addr *daddr,
const struct in6_addr *saddr)
{
struct fib6_node *fn;
struct lookup_args args[] = {
{
.offset = offsetof(struct rt6_info, rt6i_dst),
.addr = daddr,
},
#ifdef CONFIG_IPV6_SUBTREES
{
.offset = offsetof(struct rt6_info, rt6i_src),
.addr = saddr,
},
#endif
{
.offset = 0, /* sentinel */
}
};
fn = fib6_lookup_1(root, daddr ? args : args + 1);
if (!fn || fn->fn_flags & RTN_TL_ROOT)
fn = root;
return fn;
}
/*
* Get node with specified destination prefix (and source prefix,
* if subtrees are used)
*/
static struct fib6_node * fib6_locate_1(struct fib6_node *root,
const struct in6_addr *addr,
int plen, int offset)
{
struct fib6_node *fn;
for (fn = root; fn ; ) {
struct rt6key *key = (struct rt6key *)((u8 *)fn->leaf + offset);
/*
* Prefix match
*/
if (plen < fn->fn_bit ||
!ipv6_prefix_equal(&key->addr, addr, fn->fn_bit))
return NULL;
if (plen == fn->fn_bit)
return fn;
/*
* We have more bits to go
*/
if (addr_bit_set(addr, fn->fn_bit))
fn = fn->right;
else
fn = fn->left;
}
return NULL;
}
struct fib6_node * fib6_locate(struct fib6_node *root,
const struct in6_addr *daddr, int dst_len,
const struct in6_addr *saddr, int src_len)
{
struct fib6_node *fn;
fn = fib6_locate_1(root, daddr, dst_len,
offsetof(struct rt6_info, rt6i_dst));
#ifdef CONFIG_IPV6_SUBTREES
if (src_len) {
WARN_ON(saddr == NULL);
if (fn && fn->subtree)
fn = fib6_locate_1(fn->subtree, saddr, src_len,
offsetof(struct rt6_info, rt6i_src));
}
#endif
if (fn && fn->fn_flags & RTN_RTINFO)
return fn;
return NULL;
}
/*
* Deletion
*
*/
static struct rt6_info *fib6_find_prefix(struct net *net, struct fib6_node *fn)
{
if (fn->fn_flags & RTN_ROOT)
return net->ipv6.ip6_null_entry;
while (fn) {
if (fn->left)
return fn->left->leaf;
if (fn->right)
return fn->right->leaf;
fn = FIB6_SUBTREE(fn);
}
return NULL;
}
/*
* Called to trim the tree of intermediate nodes when possible. "fn"
* is the node we want to try and remove.
*/
static struct fib6_node *fib6_repair_tree(struct net *net,
struct fib6_node *fn)
{
int children;
int nstate;
struct fib6_node *child, *pn;
struct fib6_walker_t *w;
int iter = 0;
for (;;) {
RT6_TRACE("fixing tree: plen=%d iter=%d\n", fn->fn_bit, iter);
iter++;
WARN_ON(fn->fn_flags & RTN_RTINFO);
WARN_ON(fn->fn_flags & RTN_TL_ROOT);
WARN_ON(fn->leaf != NULL);
children = 0;
child = NULL;
if (fn->right) child = fn->right, children |= 1;
if (fn->left) child = fn->left, children |= 2;
if (children == 3 || FIB6_SUBTREE(fn)
#ifdef CONFIG_IPV6_SUBTREES
/* Subtree root (i.e. fn) may have one child */
|| (children && fn->fn_flags & RTN_ROOT)
#endif
) {
fn->leaf = fib6_find_prefix(net, fn);
#if RT6_DEBUG >= 2
if (!fn->leaf) {
WARN_ON(!fn->leaf);
fn->leaf = net->ipv6.ip6_null_entry;
}
#endif
atomic_inc(&fn->leaf->rt6i_ref);
return fn->parent;
}
pn = fn->parent;
#ifdef CONFIG_IPV6_SUBTREES
if (FIB6_SUBTREE(pn) == fn) {
WARN_ON(!(fn->fn_flags & RTN_ROOT));
FIB6_SUBTREE(pn) = NULL;
nstate = FWS_L;
} else {
WARN_ON(fn->fn_flags & RTN_ROOT);
#endif
if (pn->right == fn) pn->right = child;
else if (pn->left == fn) pn->left = child;
#if RT6_DEBUG >= 2
else
WARN_ON(1);
#endif
if (child)
child->parent = pn;
nstate = FWS_R;
#ifdef CONFIG_IPV6_SUBTREES
}
#endif
read_lock(&fib6_walker_lock);
FOR_WALKERS(w) {
if (!child) {
if (w->root == fn) {
w->root = w->node = NULL;
RT6_TRACE("W %p adjusted by delroot 1\n", w);
} else if (w->node == fn) {
RT6_TRACE("W %p adjusted by delnode 1, s=%d/%d\n", w, w->state, nstate);
w->node = pn;
w->state = nstate;
}
} else {
if (w->root == fn) {
w->root = child;
RT6_TRACE("W %p adjusted by delroot 2\n", w);
}
if (w->node == fn) {
w->node = child;
if (children&2) {
RT6_TRACE("W %p adjusted by delnode 2, s=%d\n", w, w->state);
w->state = w->state>=FWS_R ? FWS_U : FWS_INIT;
} else {
RT6_TRACE("W %p adjusted by delnode 2, s=%d\n", w, w->state);
w->state = w->state>=FWS_C ? FWS_U : FWS_INIT;
}
}
}
}
read_unlock(&fib6_walker_lock);
node_free(fn);
if (pn->fn_flags & RTN_RTINFO || FIB6_SUBTREE(pn))
return pn;
rt6_release(pn->leaf);
pn->leaf = NULL;
fn = pn;
}
}
static void fib6_del_route(struct fib6_node *fn, struct rt6_info **rtp,
struct nl_info *info)
{
struct fib6_walker_t *w;
struct rt6_info *rt = *rtp;
struct net *net = info->nl_net;
RT6_TRACE("fib6_del_route\n");
/* Unlink it */
*rtp = rt->dst.rt6_next;
rt->rt6i_node = NULL;
net->ipv6.rt6_stats->fib_rt_entries--;
net->ipv6.rt6_stats->fib_discarded_routes++;
/* Reset round-robin state, if necessary */
if (fn->rr_ptr == rt)
fn->rr_ptr = NULL;
/* Adjust walkers */
read_lock(&fib6_walker_lock);
FOR_WALKERS(w) {
if (w->state == FWS_C && w->leaf == rt) {
RT6_TRACE("walker %p adjusted by delroute\n", w);
w->leaf = rt->dst.rt6_next;
if (!w->leaf)
w->state = FWS_U;
}
}
read_unlock(&fib6_walker_lock);
rt->dst.rt6_next = NULL;
/* If it was last route, expunge its radix tree node */
if (!fn->leaf) {
fn->fn_flags &= ~RTN_RTINFO;
net->ipv6.rt6_stats->fib_route_nodes--;
fn = fib6_repair_tree(net, fn);
}
if (atomic_read(&rt->rt6i_ref) != 1) {
/* This route is used as dummy address holder in some split
* nodes. It is not leaked, but it still holds other resources,
* which must be released in time. So, scan ascendant nodes
* and replace dummy references to this route with references
* to still alive ones.
*/
while (fn) {
if (!(fn->fn_flags & RTN_RTINFO) && fn->leaf == rt) {
fn->leaf = fib6_find_prefix(net, fn);
atomic_inc(&fn->leaf->rt6i_ref);
rt6_release(rt);
}
fn = fn->parent;
}
/* No more references are possible at this point. */
BUG_ON(atomic_read(&rt->rt6i_ref) != 1);
}
inet6_rt_notify(RTM_DELROUTE, rt, info);
rt6_release(rt);
}
int fib6_del(struct rt6_info *rt, struct nl_info *info)
{
struct net *net = info->nl_net;
struct fib6_node *fn = rt->rt6i_node;
struct rt6_info **rtp;
#if RT6_DEBUG >= 2
if (rt->dst.obsolete>0) {
WARN_ON(fn != NULL);
return -ENOENT;
}
#endif
if (!fn || rt == net->ipv6.ip6_null_entry)
return -ENOENT;
WARN_ON(!(fn->fn_flags & RTN_RTINFO));
if (!(rt->rt6i_flags & RTF_CACHE)) {
struct fib6_node *pn = fn;
#ifdef CONFIG_IPV6_SUBTREES
/* clones of this route might be in another subtree */
if (rt->rt6i_src.plen) {
while (!(pn->fn_flags & RTN_ROOT))
pn = pn->parent;
pn = pn->parent;
}
#endif
fib6_prune_clones(info->nl_net, pn, rt);
}
/*
* Walk the leaf entries looking for ourself
*/
for (rtp = &fn->leaf; *rtp; rtp = &(*rtp)->dst.rt6_next) {
if (*rtp == rt) {
fib6_del_route(fn, rtp, info);
return 0;
}
}
return -ENOENT;
}
/*
* Tree traversal function.
*
* Certainly, it is not interrupt safe.
* However, it is internally reenterable wrt itself and fib6_add/fib6_del.
* It means, that we can modify tree during walking
* and use this function for garbage collection, clone pruning,
* cleaning tree when a device goes down etc. etc.
*
* It guarantees that every node will be traversed,
* and that it will be traversed only once.
*
* Callback function w->func may return:
* 0 -> continue walking.
* positive value -> walking is suspended (used by tree dumps,
* and probably by gc, if it will be split to several slices)
* negative value -> terminate walking.
*
* The function itself returns:
* 0 -> walk is complete.
* >0 -> walk is incomplete (i.e. suspended)
* <0 -> walk is terminated by an error.
*/
static int fib6_walk_continue(struct fib6_walker_t *w)
{
struct fib6_node *fn, *pn;
for (;;) {
fn = w->node;
if (!fn)
return 0;
if (w->prune && fn != w->root &&
fn->fn_flags & RTN_RTINFO && w->state < FWS_C) {
w->state = FWS_C;
w->leaf = fn->leaf;
}
switch (w->state) {
#ifdef CONFIG_IPV6_SUBTREES
case FWS_S:
if (FIB6_SUBTREE(fn)) {
w->node = FIB6_SUBTREE(fn);
continue;
}
w->state = FWS_L;
#endif
case FWS_L:
if (fn->left) {
w->node = fn->left;
w->state = FWS_INIT;
continue;
}
w->state = FWS_R;
case FWS_R:
if (fn->right) {
w->node = fn->right;
w->state = FWS_INIT;
continue;
}
w->state = FWS_C;
w->leaf = fn->leaf;
case FWS_C:
if (w->leaf && fn->fn_flags & RTN_RTINFO) {
int err;
if (w->count < w->skip) {
w->count++;
continue;
}
err = w->func(w);
if (err)
return err;
w->count++;
continue;
}
w->state = FWS_U;
case FWS_U:
if (fn == w->root)
return 0;
pn = fn->parent;
w->node = pn;
#ifdef CONFIG_IPV6_SUBTREES
if (FIB6_SUBTREE(pn) == fn) {
WARN_ON(!(fn->fn_flags & RTN_ROOT));
w->state = FWS_L;
continue;
}
#endif
if (pn->left == fn) {
w->state = FWS_R;
continue;
}
if (pn->right == fn) {
w->state = FWS_C;
w->leaf = w->node->leaf;
continue;
}
#if RT6_DEBUG >= 2
WARN_ON(1);
#endif
}
}
}
static int fib6_walk(struct fib6_walker_t *w)
{
int res;
w->state = FWS_INIT;
w->node = w->root;
fib6_walker_link(w);
res = fib6_walk_continue(w);
if (res <= 0)
fib6_walker_unlink(w);
return res;
}
static int fib6_clean_node(struct fib6_walker_t *w)
{
int res;
struct rt6_info *rt;
struct fib6_cleaner_t *c = container_of(w, struct fib6_cleaner_t, w);
struct nl_info info = {
.nl_net = c->net,
};
for (rt = w->leaf; rt; rt = rt->dst.rt6_next) {
res = c->func(rt, c->arg);
if (res < 0) {
w->leaf = rt;
res = fib6_del(rt, &info);
if (res) {
#if RT6_DEBUG >= 2
printk(KERN_DEBUG "fib6_clean_node: del failed: rt=%p@%p err=%d\n", rt, rt->rt6i_node, res);
#endif
continue;
}
return 0;
}
WARN_ON(res != 0);
}
w->leaf = rt;
return 0;
}
/*
* Convenient frontend to tree walker.
*
* func is called on each route.
* It may return -1 -> delete this route.
* 0 -> continue walking
*
* prune==1 -> only immediate children of node (certainly,
* ignoring pure split nodes) will be scanned.
*/
static void fib6_clean_tree(struct net *net, struct fib6_node *root,
int (*func)(struct rt6_info *, void *arg),
int prune, void *arg)
{
struct fib6_cleaner_t c;
c.w.root = root;
c.w.func = fib6_clean_node;
c.w.prune = prune;
c.w.count = 0;
c.w.skip = 0;
c.func = func;
c.arg = arg;
c.net = net;
fib6_walk(&c.w);
}
void fib6_clean_all_ro(struct net *net, int (*func)(struct rt6_info *, void *arg),
int prune, void *arg)
{
struct fib6_table *table;
struct hlist_node *node;
struct hlist_head *head;
unsigned int h;
rcu_read_lock();
for (h = 0; h < FIB6_TABLE_HASHSZ; h++) {
head = &net->ipv6.fib_table_hash[h];
hlist_for_each_entry_rcu(table, node, head, tb6_hlist) {
read_lock_bh(&table->tb6_lock);
fib6_clean_tree(net, &table->tb6_root,
func, prune, arg);
read_unlock_bh(&table->tb6_lock);
}
}
rcu_read_unlock();
}
void fib6_clean_all(struct net *net, int (*func)(struct rt6_info *, void *arg),
int prune, void *arg)
{
struct fib6_table *table;
struct hlist_node *node;
struct hlist_head *head;
unsigned int h;
rcu_read_lock();
for (h = 0; h < FIB6_TABLE_HASHSZ; h++) {
head = &net->ipv6.fib_table_hash[h];
hlist_for_each_entry_rcu(table, node, head, tb6_hlist) {
write_lock_bh(&table->tb6_lock);
fib6_clean_tree(net, &table->tb6_root,
func, prune, arg);
write_unlock_bh(&table->tb6_lock);
}
}
rcu_read_unlock();
}
static int fib6_prune_clone(struct rt6_info *rt, void *arg)
{
if (rt->rt6i_flags & RTF_CACHE) {
RT6_TRACE("pruning clone %p\n", rt);
return -1;
}
return 0;
}
static void fib6_prune_clones(struct net *net, struct fib6_node *fn,
struct rt6_info *rt)
{
fib6_clean_tree(net, fn, fib6_prune_clone, 1, rt);
}
/*
* Garbage collection
*/
static struct fib6_gc_args
{
int timeout;
int more;
} gc_args;
static int fib6_age(struct rt6_info *rt, void *arg)
{
unsigned long now = jiffies;
/*
* check addrconf expiration here.
* Routes are expired even if they are in use.
*
* Also age clones. Note, that clones are aged out
* only if they are not in use now.
*/
if (rt->rt6i_flags & RTF_EXPIRES && rt->dst.expires) {
if (time_after(now, rt->dst.expires)) {
RT6_TRACE("expiring %p\n", rt);
return -1;
}
gc_args.more++;
} else if (rt->rt6i_flags & RTF_CACHE) {
if (atomic_read(&rt->dst.__refcnt) == 0 &&
time_after_eq(now, rt->dst.lastuse + gc_args.timeout)) {
RT6_TRACE("aging clone %p\n", rt);
return -1;
} else if (rt->rt6i_flags & RTF_GATEWAY) {
struct neighbour *neigh;
__u8 neigh_flags = 0;
neigh = dst_neigh_lookup(&rt->dst, &rt->rt6i_gateway);
if (neigh) {
neigh_flags = neigh->flags;
neigh_release(neigh);
}
if (neigh_flags & NTF_ROUTER) {
RT6_TRACE("purging route %p via non-router but gateway\n",
rt);
return -1;
}
}
gc_args.more++;
}
return 0;
}
static DEFINE_SPINLOCK(fib6_gc_lock);
void fib6_run_gc(unsigned long expires, struct net *net)
{
if (expires != ~0UL) {
spin_lock_bh(&fib6_gc_lock);
gc_args.timeout = expires ? (int)expires :
net->ipv6.sysctl.ip6_rt_gc_interval;
} else {
if (!spin_trylock_bh(&fib6_gc_lock)) {
mod_timer(&net->ipv6.ip6_fib_timer, jiffies + HZ);
return;
}
gc_args.timeout = net->ipv6.sysctl.ip6_rt_gc_interval;
}
gc_args.more = icmp6_dst_gc();
fib6_clean_all(net, fib6_age, 0, NULL);
if (gc_args.more)
mod_timer(&net->ipv6.ip6_fib_timer,
round_jiffies(jiffies
+ net->ipv6.sysctl.ip6_rt_gc_interval));
else
del_timer(&net->ipv6.ip6_fib_timer);
spin_unlock_bh(&fib6_gc_lock);
}
static void fib6_gc_timer_cb(unsigned long arg)
{
fib6_run_gc(0, (struct net *)arg);
}
static int __net_init fib6_net_init(struct net *net)
{
size_t size = sizeof(struct hlist_head) * FIB6_TABLE_HASHSZ;
setup_timer(&net->ipv6.ip6_fib_timer, fib6_gc_timer_cb, (unsigned long)net);
net->ipv6.rt6_stats = kzalloc(sizeof(*net->ipv6.rt6_stats), GFP_KERNEL);
if (!net->ipv6.rt6_stats)
goto out_timer;
/* Avoid false sharing : Use at least a full cache line */
size = max_t(size_t, size, L1_CACHE_BYTES);
net->ipv6.fib_table_hash = kzalloc(size, GFP_KERNEL);
if (!net->ipv6.fib_table_hash)
goto out_rt6_stats;
net->ipv6.fib6_main_tbl = kzalloc(sizeof(*net->ipv6.fib6_main_tbl),
GFP_KERNEL);
if (!net->ipv6.fib6_main_tbl)
goto out_fib_table_hash;
net->ipv6.fib6_main_tbl->tb6_id = RT6_TABLE_MAIN;
net->ipv6.fib6_main_tbl->tb6_root.leaf = net->ipv6.ip6_null_entry;
net->ipv6.fib6_main_tbl->tb6_root.fn_flags =
RTN_ROOT | RTN_TL_ROOT | RTN_RTINFO;
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
net->ipv6.fib6_local_tbl = kzalloc(sizeof(*net->ipv6.fib6_local_tbl),
GFP_KERNEL);
if (!net->ipv6.fib6_local_tbl)
goto out_fib6_main_tbl;
net->ipv6.fib6_local_tbl->tb6_id = RT6_TABLE_LOCAL;
net->ipv6.fib6_local_tbl->tb6_root.leaf = net->ipv6.ip6_null_entry;
net->ipv6.fib6_local_tbl->tb6_root.fn_flags =
RTN_ROOT | RTN_TL_ROOT | RTN_RTINFO;
#endif
fib6_tables_init(net);
return 0;
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
out_fib6_main_tbl:
kfree(net->ipv6.fib6_main_tbl);
#endif
out_fib_table_hash:
kfree(net->ipv6.fib_table_hash);
out_rt6_stats:
kfree(net->ipv6.rt6_stats);
out_timer:
return -ENOMEM;
}
static void fib6_net_exit(struct net *net)
{
rt6_ifdown(net, NULL);
del_timer_sync(&net->ipv6.ip6_fib_timer);
#ifdef CONFIG_IPV6_MULTIPLE_TABLES
kfree(net->ipv6.fib6_local_tbl);
#endif
kfree(net->ipv6.fib6_main_tbl);
kfree(net->ipv6.fib_table_hash);
kfree(net->ipv6.rt6_stats);
}
static struct pernet_operations fib6_net_ops = {
.init = fib6_net_init,
.exit = fib6_net_exit,
};
int __init fib6_init(void)
{
int ret = -ENOMEM;
fib6_node_kmem = kmem_cache_create("fib6_nodes",
sizeof(struct fib6_node),
0, SLAB_HWCACHE_ALIGN,
NULL);
if (!fib6_node_kmem)
goto out;
ret = register_pernet_subsys(&fib6_net_ops);
if (ret)
goto out_kmem_cache_create;
ret = __rtnl_register(PF_INET6, RTM_GETROUTE, NULL, inet6_dump_fib,
NULL);
if (ret)
goto out_unregister_subsys;
out:
return ret;
out_unregister_subsys:
unregister_pernet_subsys(&fib6_net_ops);
out_kmem_cache_create:
kmem_cache_destroy(fib6_node_kmem);
goto out;
}
void fib6_gc_cleanup(void)
{
unregister_pernet_subsys(&fib6_net_ops);
kmem_cache_destroy(fib6_node_kmem);
}
| gpl-2.0 |
scorp2kk/kernel_pyramid_3.0.16 | sound/arm/aaci.c | 2913 | 25780 | /*
* linux/sound/arm/aaci.c - ARM PrimeCell AACI PL041 driver
*
* Copyright (C) 2003 Deep Blue Solutions Ltd, All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Documentation: ARM DDI 0173B
*/
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/device.h>
#include <linux/spinlock.h>
#include <linux/interrupt.h>
#include <linux/err.h>
#include <linux/amba/bus.h>
#include <linux/io.h>
#include <sound/core.h>
#include <sound/initval.h>
#include <sound/ac97_codec.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include "aaci.h"
#define DRIVER_NAME "aaci-pl041"
#define FRAME_PERIOD_US 21
/*
* PM support is not complete. Turn it off.
*/
#undef CONFIG_PM
static void aaci_ac97_select_codec(struct aaci *aaci, struct snd_ac97 *ac97)
{
u32 v, maincr = aaci->maincr | MAINCR_SCRA(ac97->num);
/*
* Ensure that the slot 1/2 RX registers are empty.
*/
v = readl(aaci->base + AACI_SLFR);
if (v & SLFR_2RXV)
readl(aaci->base + AACI_SL2RX);
if (v & SLFR_1RXV)
readl(aaci->base + AACI_SL1RX);
if (maincr != readl(aaci->base + AACI_MAINCR)) {
writel(maincr, aaci->base + AACI_MAINCR);
readl(aaci->base + AACI_MAINCR);
udelay(1);
}
}
/*
* P29:
* The recommended use of programming the external codec through slot 1
* and slot 2 data is to use the channels during setup routines and the
* slot register at any other time. The data written into slot 1, slot 2
* and slot 12 registers is transmitted only when their corresponding
* SI1TxEn, SI2TxEn and SI12TxEn bits are set in the AACI_MAINCR
* register.
*/
static void aaci_ac97_write(struct snd_ac97 *ac97, unsigned short reg,
unsigned short val)
{
struct aaci *aaci = ac97->private_data;
int timeout;
u32 v;
if (ac97->num >= 4)
return;
mutex_lock(&aaci->ac97_sem);
aaci_ac97_select_codec(aaci, ac97);
/*
* P54: You must ensure that AACI_SL2TX is always written
* to, if required, before data is written to AACI_SL1TX.
*/
writel(val << 4, aaci->base + AACI_SL2TX);
writel(reg << 12, aaci->base + AACI_SL1TX);
/* Initially, wait one frame period */
udelay(FRAME_PERIOD_US);
/* And then wait an additional eight frame periods for it to be sent */
timeout = FRAME_PERIOD_US * 8;
do {
udelay(1);
v = readl(aaci->base + AACI_SLFR);
} while ((v & (SLFR_1TXB|SLFR_2TXB)) && --timeout);
if (v & (SLFR_1TXB|SLFR_2TXB))
dev_err(&aaci->dev->dev,
"timeout waiting for write to complete\n");
mutex_unlock(&aaci->ac97_sem);
}
/*
* Read an AC'97 register.
*/
static unsigned short aaci_ac97_read(struct snd_ac97 *ac97, unsigned short reg)
{
struct aaci *aaci = ac97->private_data;
int timeout, retries = 10;
u32 v;
if (ac97->num >= 4)
return ~0;
mutex_lock(&aaci->ac97_sem);
aaci_ac97_select_codec(aaci, ac97);
/*
* Write the register address to slot 1.
*/
writel((reg << 12) | (1 << 19), aaci->base + AACI_SL1TX);
/* Initially, wait one frame period */
udelay(FRAME_PERIOD_US);
/* And then wait an additional eight frame periods for it to be sent */
timeout = FRAME_PERIOD_US * 8;
do {
udelay(1);
v = readl(aaci->base + AACI_SLFR);
} while ((v & SLFR_1TXB) && --timeout);
if (v & SLFR_1TXB) {
dev_err(&aaci->dev->dev, "timeout on slot 1 TX busy\n");
v = ~0;
goto out;
}
/* Now wait for the response frame */
udelay(FRAME_PERIOD_US);
/* And then wait an additional eight frame periods for data */
timeout = FRAME_PERIOD_US * 8;
do {
udelay(1);
cond_resched();
v = readl(aaci->base + AACI_SLFR) & (SLFR_1RXV|SLFR_2RXV);
} while ((v != (SLFR_1RXV|SLFR_2RXV)) && --timeout);
if (v != (SLFR_1RXV|SLFR_2RXV)) {
dev_err(&aaci->dev->dev, "timeout on RX valid\n");
v = ~0;
goto out;
}
do {
v = readl(aaci->base + AACI_SL1RX) >> 12;
if (v == reg) {
v = readl(aaci->base + AACI_SL2RX) >> 4;
break;
} else if (--retries) {
dev_warn(&aaci->dev->dev,
"ac97 read back fail. retry\n");
continue;
} else {
dev_warn(&aaci->dev->dev,
"wrong ac97 register read back (%x != %x)\n",
v, reg);
v = ~0;
}
} while (retries);
out:
mutex_unlock(&aaci->ac97_sem);
return v;
}
static inline void
aaci_chan_wait_ready(struct aaci_runtime *aacirun, unsigned long mask)
{
u32 val;
int timeout = 5000;
do {
udelay(1);
val = readl(aacirun->base + AACI_SR);
} while (val & mask && timeout--);
}
/*
* Interrupt support.
*/
static void aaci_fifo_irq(struct aaci *aaci, int channel, u32 mask)
{
if (mask & ISR_ORINTR) {
dev_warn(&aaci->dev->dev, "RX overrun on chan %d\n", channel);
writel(ICLR_RXOEC1 << channel, aaci->base + AACI_INTCLR);
}
if (mask & ISR_RXTOINTR) {
dev_warn(&aaci->dev->dev, "RX timeout on chan %d\n", channel);
writel(ICLR_RXTOFEC1 << channel, aaci->base + AACI_INTCLR);
}
if (mask & ISR_RXINTR) {
struct aaci_runtime *aacirun = &aaci->capture;
bool period_elapsed = false;
void *ptr;
if (!aacirun->substream || !aacirun->start) {
dev_warn(&aaci->dev->dev, "RX interrupt???\n");
writel(0, aacirun->base + AACI_IE);
return;
}
spin_lock(&aacirun->lock);
ptr = aacirun->ptr;
do {
unsigned int len = aacirun->fifo_bytes;
u32 val;
if (aacirun->bytes <= 0) {
aacirun->bytes += aacirun->period;
period_elapsed = true;
}
if (!(aacirun->cr & CR_EN))
break;
val = readl(aacirun->base + AACI_SR);
if (!(val & SR_RXHF))
break;
if (!(val & SR_RXFF))
len >>= 1;
aacirun->bytes -= len;
/* reading 16 bytes at a time */
for( ; len > 0; len -= 16) {
asm(
"ldmia %1, {r0, r1, r2, r3}\n\t"
"stmia %0!, {r0, r1, r2, r3}"
: "+r" (ptr)
: "r" (aacirun->fifo)
: "r0", "r1", "r2", "r3", "cc");
if (ptr >= aacirun->end)
ptr = aacirun->start;
}
} while(1);
aacirun->ptr = ptr;
spin_unlock(&aacirun->lock);
if (period_elapsed)
snd_pcm_period_elapsed(aacirun->substream);
}
if (mask & ISR_URINTR) {
dev_dbg(&aaci->dev->dev, "TX underrun on chan %d\n", channel);
writel(ICLR_TXUEC1 << channel, aaci->base + AACI_INTCLR);
}
if (mask & ISR_TXINTR) {
struct aaci_runtime *aacirun = &aaci->playback;
bool period_elapsed = false;
void *ptr;
if (!aacirun->substream || !aacirun->start) {
dev_warn(&aaci->dev->dev, "TX interrupt???\n");
writel(0, aacirun->base + AACI_IE);
return;
}
spin_lock(&aacirun->lock);
ptr = aacirun->ptr;
do {
unsigned int len = aacirun->fifo_bytes;
u32 val;
if (aacirun->bytes <= 0) {
aacirun->bytes += aacirun->period;
period_elapsed = true;
}
if (!(aacirun->cr & CR_EN))
break;
val = readl(aacirun->base + AACI_SR);
if (!(val & SR_TXHE))
break;
if (!(val & SR_TXFE))
len >>= 1;
aacirun->bytes -= len;
/* writing 16 bytes at a time */
for ( ; len > 0; len -= 16) {
asm(
"ldmia %0!, {r0, r1, r2, r3}\n\t"
"stmia %1, {r0, r1, r2, r3}"
: "+r" (ptr)
: "r" (aacirun->fifo)
: "r0", "r1", "r2", "r3", "cc");
if (ptr >= aacirun->end)
ptr = aacirun->start;
}
} while (1);
aacirun->ptr = ptr;
spin_unlock(&aacirun->lock);
if (period_elapsed)
snd_pcm_period_elapsed(aacirun->substream);
}
}
static irqreturn_t aaci_irq(int irq, void *devid)
{
struct aaci *aaci = devid;
u32 mask;
int i;
mask = readl(aaci->base + AACI_ALLINTS);
if (mask) {
u32 m = mask;
for (i = 0; i < 4; i++, m >>= 7) {
if (m & 0x7f) {
aaci_fifo_irq(aaci, i, m);
}
}
}
return mask ? IRQ_HANDLED : IRQ_NONE;
}
/*
* ALSA support.
*/
static struct snd_pcm_hardware aaci_hw_info = {
.info = SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_RESUME,
/*
* ALSA doesn't support 18-bit or 20-bit packed into 32-bit
* words. It also doesn't support 12-bit at all.
*/
.formats = SNDRV_PCM_FMTBIT_S16_LE,
/* rates are setup from the AC'97 codec */
.channels_min = 2,
.channels_max = 2,
.buffer_bytes_max = 64 * 1024,
.period_bytes_min = 256,
.period_bytes_max = PAGE_SIZE,
.periods_min = 4,
.periods_max = PAGE_SIZE / 16,
};
/*
* We can support two and four channel audio. Unfortunately
* six channel audio requires a non-standard channel ordering:
* 2 -> FL(3), FR(4)
* 4 -> FL(3), FR(4), SL(7), SR(8)
* 6 -> FL(3), FR(4), SL(7), SR(8), C(6), LFE(9) (required)
* FL(3), FR(4), C(6), SL(7), SR(8), LFE(9) (actual)
* This requires an ALSA configuration file to correct.
*/
static int aaci_rule_channels(struct snd_pcm_hw_params *p,
struct snd_pcm_hw_rule *rule)
{
static unsigned int channel_list[] = { 2, 4, 6 };
struct aaci *aaci = rule->private;
unsigned int mask = 1 << 0, slots;
/* pcms[0] is the our 5.1 PCM instance. */
slots = aaci->ac97_bus->pcms[0].r[0].slots;
if (slots & (1 << AC97_SLOT_PCM_SLEFT)) {
mask |= 1 << 1;
if (slots & (1 << AC97_SLOT_LFE))
mask |= 1 << 2;
}
return snd_interval_list(hw_param_interval(p, rule->var),
ARRAY_SIZE(channel_list), channel_list, mask);
}
static int aaci_pcm_open(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct aaci *aaci = substream->private_data;
struct aaci_runtime *aacirun;
int ret = 0;
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
aacirun = &aaci->playback;
} else {
aacirun = &aaci->capture;
}
aacirun->substream = substream;
runtime->private_data = aacirun;
runtime->hw = aaci_hw_info;
runtime->hw.rates = aacirun->pcm->rates;
snd_pcm_limit_hw_rates(runtime);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
runtime->hw.channels_max = 6;
/* Add rule describing channel dependency. */
ret = snd_pcm_hw_rule_add(substream->runtime, 0,
SNDRV_PCM_HW_PARAM_CHANNELS,
aaci_rule_channels, aaci,
SNDRV_PCM_HW_PARAM_CHANNELS, -1);
if (ret)
return ret;
if (aacirun->pcm->r[1].slots)
snd_ac97_pcm_double_rate_rules(runtime);
}
/*
* ALSA wants the byte-size of the FIFOs. As we only support
* 16-bit samples, this is twice the FIFO depth irrespective
* of whether it's in compact mode or not.
*/
runtime->hw.fifo_size = aaci->fifo_depth * 2;
mutex_lock(&aaci->irq_lock);
if (!aaci->users++) {
ret = request_irq(aaci->dev->irq[0], aaci_irq,
IRQF_SHARED | IRQF_DISABLED, DRIVER_NAME, aaci);
if (ret != 0)
aaci->users--;
}
mutex_unlock(&aaci->irq_lock);
return ret;
}
/*
* Common ALSA stuff
*/
static int aaci_pcm_close(struct snd_pcm_substream *substream)
{
struct aaci *aaci = substream->private_data;
struct aaci_runtime *aacirun = substream->runtime->private_data;
WARN_ON(aacirun->cr & CR_EN);
aacirun->substream = NULL;
mutex_lock(&aaci->irq_lock);
if (!--aaci->users)
free_irq(aaci->dev->irq[0], aaci);
mutex_unlock(&aaci->irq_lock);
return 0;
}
static int aaci_pcm_hw_free(struct snd_pcm_substream *substream)
{
struct aaci_runtime *aacirun = substream->runtime->private_data;
/*
* This must not be called with the device enabled.
*/
WARN_ON(aacirun->cr & CR_EN);
if (aacirun->pcm_open)
snd_ac97_pcm_close(aacirun->pcm);
aacirun->pcm_open = 0;
/*
* Clear out the DMA and any allocated buffers.
*/
snd_pcm_lib_free_pages(substream);
return 0;
}
/* Channel to slot mask */
static const u32 channels_to_slotmask[] = {
[2] = CR_SL3 | CR_SL4,
[4] = CR_SL3 | CR_SL4 | CR_SL7 | CR_SL8,
[6] = CR_SL3 | CR_SL4 | CR_SL7 | CR_SL8 | CR_SL6 | CR_SL9,
};
static int aaci_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct aaci_runtime *aacirun = substream->runtime->private_data;
unsigned int channels = params_channels(params);
unsigned int rate = params_rate(params);
int dbl = rate > 48000;
int err;
aaci_pcm_hw_free(substream);
if (aacirun->pcm_open) {
snd_ac97_pcm_close(aacirun->pcm);
aacirun->pcm_open = 0;
}
/* channels is already limited to 2, 4, or 6 by aaci_rule_channels */
if (dbl && channels != 2)
return -EINVAL;
err = snd_pcm_lib_malloc_pages(substream,
params_buffer_bytes(params));
if (err >= 0) {
struct aaci *aaci = substream->private_data;
err = snd_ac97_pcm_open(aacirun->pcm, rate, channels,
aacirun->pcm->r[dbl].slots);
aacirun->pcm_open = err == 0;
aacirun->cr = CR_FEN | CR_COMPACT | CR_SZ16;
aacirun->cr |= channels_to_slotmask[channels + dbl * 2];
/*
* fifo_bytes is the number of bytes we transfer to/from
* the FIFO, including padding. So that's x4. As we're
* in compact mode, the FIFO is half the size.
*/
aacirun->fifo_bytes = aaci->fifo_depth * 4 / 2;
}
return err;
}
static int aaci_pcm_prepare(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct aaci_runtime *aacirun = runtime->private_data;
aacirun->period = snd_pcm_lib_period_bytes(substream);
aacirun->start = runtime->dma_area;
aacirun->end = aacirun->start + snd_pcm_lib_buffer_bytes(substream);
aacirun->ptr = aacirun->start;
aacirun->bytes = aacirun->period;
return 0;
}
static snd_pcm_uframes_t aaci_pcm_pointer(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct aaci_runtime *aacirun = runtime->private_data;
ssize_t bytes = aacirun->ptr - aacirun->start;
return bytes_to_frames(runtime, bytes);
}
/*
* Playback specific ALSA stuff
*/
static void aaci_pcm_playback_stop(struct aaci_runtime *aacirun)
{
u32 ie;
ie = readl(aacirun->base + AACI_IE);
ie &= ~(IE_URIE|IE_TXIE);
writel(ie, aacirun->base + AACI_IE);
aacirun->cr &= ~CR_EN;
aaci_chan_wait_ready(aacirun, SR_TXB);
writel(aacirun->cr, aacirun->base + AACI_TXCR);
}
static void aaci_pcm_playback_start(struct aaci_runtime *aacirun)
{
u32 ie;
aaci_chan_wait_ready(aacirun, SR_TXB);
aacirun->cr |= CR_EN;
ie = readl(aacirun->base + AACI_IE);
ie |= IE_URIE | IE_TXIE;
writel(ie, aacirun->base + AACI_IE);
writel(aacirun->cr, aacirun->base + AACI_TXCR);
}
static int aaci_pcm_playback_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct aaci_runtime *aacirun = substream->runtime->private_data;
unsigned long flags;
int ret = 0;
spin_lock_irqsave(&aacirun->lock, flags);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
aaci_pcm_playback_start(aacirun);
break;
case SNDRV_PCM_TRIGGER_RESUME:
aaci_pcm_playback_start(aacirun);
break;
case SNDRV_PCM_TRIGGER_STOP:
aaci_pcm_playback_stop(aacirun);
break;
case SNDRV_PCM_TRIGGER_SUSPEND:
aaci_pcm_playback_stop(aacirun);
break;
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
break;
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
break;
default:
ret = -EINVAL;
}
spin_unlock_irqrestore(&aacirun->lock, flags);
return ret;
}
static struct snd_pcm_ops aaci_playback_ops = {
.open = aaci_pcm_open,
.close = aaci_pcm_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = aaci_pcm_hw_params,
.hw_free = aaci_pcm_hw_free,
.prepare = aaci_pcm_prepare,
.trigger = aaci_pcm_playback_trigger,
.pointer = aaci_pcm_pointer,
};
static void aaci_pcm_capture_stop(struct aaci_runtime *aacirun)
{
u32 ie;
aaci_chan_wait_ready(aacirun, SR_RXB);
ie = readl(aacirun->base + AACI_IE);
ie &= ~(IE_ORIE | IE_RXIE);
writel(ie, aacirun->base+AACI_IE);
aacirun->cr &= ~CR_EN;
writel(aacirun->cr, aacirun->base + AACI_RXCR);
}
static void aaci_pcm_capture_start(struct aaci_runtime *aacirun)
{
u32 ie;
aaci_chan_wait_ready(aacirun, SR_RXB);
#ifdef DEBUG
/* RX Timeout value: bits 28:17 in RXCR */
aacirun->cr |= 0xf << 17;
#endif
aacirun->cr |= CR_EN;
writel(aacirun->cr, aacirun->base + AACI_RXCR);
ie = readl(aacirun->base + AACI_IE);
ie |= IE_ORIE |IE_RXIE; // overrun and rx interrupt -- half full
writel(ie, aacirun->base + AACI_IE);
}
static int aaci_pcm_capture_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct aaci_runtime *aacirun = substream->runtime->private_data;
unsigned long flags;
int ret = 0;
spin_lock_irqsave(&aacirun->lock, flags);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
aaci_pcm_capture_start(aacirun);
break;
case SNDRV_PCM_TRIGGER_RESUME:
aaci_pcm_capture_start(aacirun);
break;
case SNDRV_PCM_TRIGGER_STOP:
aaci_pcm_capture_stop(aacirun);
break;
case SNDRV_PCM_TRIGGER_SUSPEND:
aaci_pcm_capture_stop(aacirun);
break;
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
break;
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
break;
default:
ret = -EINVAL;
}
spin_unlock_irqrestore(&aacirun->lock, flags);
return ret;
}
static int aaci_pcm_capture_prepare(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct aaci *aaci = substream->private_data;
aaci_pcm_prepare(substream);
/* allow changing of sample rate */
aaci_ac97_write(aaci->ac97, AC97_EXTENDED_STATUS, 0x0001); /* VRA */
aaci_ac97_write(aaci->ac97, AC97_PCM_LR_ADC_RATE, runtime->rate);
aaci_ac97_write(aaci->ac97, AC97_PCM_MIC_ADC_RATE, runtime->rate);
/* Record select: Mic: 0, Aux: 3, Line: 4 */
aaci_ac97_write(aaci->ac97, AC97_REC_SEL, 0x0404);
return 0;
}
static struct snd_pcm_ops aaci_capture_ops = {
.open = aaci_pcm_open,
.close = aaci_pcm_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = aaci_pcm_hw_params,
.hw_free = aaci_pcm_hw_free,
.prepare = aaci_pcm_capture_prepare,
.trigger = aaci_pcm_capture_trigger,
.pointer = aaci_pcm_pointer,
};
/*
* Power Management.
*/
#ifdef CONFIG_PM
static int aaci_do_suspend(struct snd_card *card, unsigned int state)
{
struct aaci *aaci = card->private_data;
snd_power_change_state(card, SNDRV_CTL_POWER_D3cold);
snd_pcm_suspend_all(aaci->pcm);
return 0;
}
static int aaci_do_resume(struct snd_card *card, unsigned int state)
{
snd_power_change_state(card, SNDRV_CTL_POWER_D0);
return 0;
}
static int aaci_suspend(struct amba_device *dev, pm_message_t state)
{
struct snd_card *card = amba_get_drvdata(dev);
return card ? aaci_do_suspend(card) : 0;
}
static int aaci_resume(struct amba_device *dev)
{
struct snd_card *card = amba_get_drvdata(dev);
return card ? aaci_do_resume(card) : 0;
}
#else
#define aaci_do_suspend NULL
#define aaci_do_resume NULL
#define aaci_suspend NULL
#define aaci_resume NULL
#endif
static struct ac97_pcm ac97_defs[] __devinitdata = {
[0] = { /* Front PCM */
.exclusive = 1,
.r = {
[0] = {
.slots = (1 << AC97_SLOT_PCM_LEFT) |
(1 << AC97_SLOT_PCM_RIGHT) |
(1 << AC97_SLOT_PCM_CENTER) |
(1 << AC97_SLOT_PCM_SLEFT) |
(1 << AC97_SLOT_PCM_SRIGHT) |
(1 << AC97_SLOT_LFE),
},
[1] = {
.slots = (1 << AC97_SLOT_PCM_LEFT) |
(1 << AC97_SLOT_PCM_RIGHT) |
(1 << AC97_SLOT_PCM_LEFT_0) |
(1 << AC97_SLOT_PCM_RIGHT_0),
},
},
},
[1] = { /* PCM in */
.stream = 1,
.exclusive = 1,
.r = {
[0] = {
.slots = (1 << AC97_SLOT_PCM_LEFT) |
(1 << AC97_SLOT_PCM_RIGHT),
},
},
},
[2] = { /* Mic in */
.stream = 1,
.exclusive = 1,
.r = {
[0] = {
.slots = (1 << AC97_SLOT_MIC),
},
},
}
};
static struct snd_ac97_bus_ops aaci_bus_ops = {
.write = aaci_ac97_write,
.read = aaci_ac97_read,
};
static int __devinit aaci_probe_ac97(struct aaci *aaci)
{
struct snd_ac97_template ac97_template;
struct snd_ac97_bus *ac97_bus;
struct snd_ac97 *ac97;
int ret;
/*
* Assert AACIRESET for 2us
*/
writel(0, aaci->base + AACI_RESET);
udelay(2);
writel(RESET_NRST, aaci->base + AACI_RESET);
/*
* Give the AC'97 codec more than enough time
* to wake up. (42us = ~2 frames at 48kHz.)
*/
udelay(FRAME_PERIOD_US * 2);
ret = snd_ac97_bus(aaci->card, 0, &aaci_bus_ops, aaci, &ac97_bus);
if (ret)
goto out;
ac97_bus->clock = 48000;
aaci->ac97_bus = ac97_bus;
memset(&ac97_template, 0, sizeof(struct snd_ac97_template));
ac97_template.private_data = aaci;
ac97_template.num = 0;
ac97_template.scaps = AC97_SCAP_SKIP_MODEM;
ret = snd_ac97_mixer(ac97_bus, &ac97_template, &ac97);
if (ret)
goto out;
aaci->ac97 = ac97;
/*
* Disable AC97 PC Beep input on audio codecs.
*/
if (ac97_is_audio(ac97))
snd_ac97_write_cache(ac97, AC97_PC_BEEP, 0x801e);
ret = snd_ac97_pcm_assign(ac97_bus, ARRAY_SIZE(ac97_defs), ac97_defs);
if (ret)
goto out;
aaci->playback.pcm = &ac97_bus->pcms[0];
aaci->capture.pcm = &ac97_bus->pcms[1];
out:
return ret;
}
static void aaci_free_card(struct snd_card *card)
{
struct aaci *aaci = card->private_data;
if (aaci->base)
iounmap(aaci->base);
}
static struct aaci * __devinit aaci_init_card(struct amba_device *dev)
{
struct aaci *aaci;
struct snd_card *card;
int err;
err = snd_card_create(SNDRV_DEFAULT_IDX1, SNDRV_DEFAULT_STR1,
THIS_MODULE, sizeof(struct aaci), &card);
if (err < 0)
return NULL;
card->private_free = aaci_free_card;
strlcpy(card->driver, DRIVER_NAME, sizeof(card->driver));
strlcpy(card->shortname, "ARM AC'97 Interface", sizeof(card->shortname));
snprintf(card->longname, sizeof(card->longname),
"%s PL%03x rev%u at 0x%08llx, irq %d",
card->shortname, amba_part(dev), amba_rev(dev),
(unsigned long long)dev->res.start, dev->irq[0]);
aaci = card->private_data;
mutex_init(&aaci->ac97_sem);
mutex_init(&aaci->irq_lock);
aaci->card = card;
aaci->dev = dev;
/* Set MAINCR to allow slot 1 and 2 data IO */
aaci->maincr = MAINCR_IE | MAINCR_SL1RXEN | MAINCR_SL1TXEN |
MAINCR_SL2RXEN | MAINCR_SL2TXEN;
return aaci;
}
static int __devinit aaci_init_pcm(struct aaci *aaci)
{
struct snd_pcm *pcm;
int ret;
ret = snd_pcm_new(aaci->card, "AACI AC'97", 0, 1, 1, &pcm);
if (ret == 0) {
aaci->pcm = pcm;
pcm->private_data = aaci;
pcm->info_flags = 0;
strlcpy(pcm->name, DRIVER_NAME, sizeof(pcm->name));
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &aaci_playback_ops);
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &aaci_capture_ops);
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
NULL, 0, 64 * 1024);
}
return ret;
}
static unsigned int __devinit aaci_size_fifo(struct aaci *aaci)
{
struct aaci_runtime *aacirun = &aaci->playback;
int i;
/*
* Enable the channel, but don't assign it to any slots, so
* it won't empty onto the AC'97 link.
*/
writel(CR_FEN | CR_SZ16 | CR_EN, aacirun->base + AACI_TXCR);
for (i = 0; !(readl(aacirun->base + AACI_SR) & SR_TXFF) && i < 4096; i++)
writel(0, aacirun->fifo);
writel(0, aacirun->base + AACI_TXCR);
/*
* Re-initialise the AACI after the FIFO depth test, to
* ensure that the FIFOs are empty. Unfortunately, merely
* disabling the channel doesn't clear the FIFO.
*/
writel(aaci->maincr & ~MAINCR_IE, aaci->base + AACI_MAINCR);
readl(aaci->base + AACI_MAINCR);
udelay(1);
writel(aaci->maincr, aaci->base + AACI_MAINCR);
/*
* If we hit 4096 entries, we failed. Go back to the specified
* fifo depth.
*/
if (i == 4096)
i = 8;
return i;
}
static int __devinit aaci_probe(struct amba_device *dev,
const struct amba_id *id)
{
struct aaci *aaci;
int ret, i;
ret = amba_request_regions(dev, NULL);
if (ret)
return ret;
aaci = aaci_init_card(dev);
if (!aaci) {
ret = -ENOMEM;
goto out;
}
aaci->base = ioremap(dev->res.start, resource_size(&dev->res));
if (!aaci->base) {
ret = -ENOMEM;
goto out;
}
/*
* Playback uses AACI channel 0
*/
spin_lock_init(&aaci->playback.lock);
aaci->playback.base = aaci->base + AACI_CSCH1;
aaci->playback.fifo = aaci->base + AACI_DR1;
/*
* Capture uses AACI channel 0
*/
spin_lock_init(&aaci->capture.lock);
aaci->capture.base = aaci->base + AACI_CSCH1;
aaci->capture.fifo = aaci->base + AACI_DR1;
for (i = 0; i < 4; i++) {
void __iomem *base = aaci->base + i * 0x14;
writel(0, base + AACI_IE);
writel(0, base + AACI_TXCR);
writel(0, base + AACI_RXCR);
}
writel(0x1fff, aaci->base + AACI_INTCLR);
writel(aaci->maincr, aaci->base + AACI_MAINCR);
/*
* Fix: ac97 read back fail errors by reading
* from any arbitrary aaci register.
*/
readl(aaci->base + AACI_CSCH1);
ret = aaci_probe_ac97(aaci);
if (ret)
goto out;
/*
* Size the FIFOs (must be multiple of 16).
* This is the number of entries in the FIFO.
*/
aaci->fifo_depth = aaci_size_fifo(aaci);
if (aaci->fifo_depth & 15) {
printk(KERN_WARNING "AACI: FIFO depth %d not supported\n",
aaci->fifo_depth);
ret = -ENODEV;
goto out;
}
ret = aaci_init_pcm(aaci);
if (ret)
goto out;
snd_card_set_dev(aaci->card, &dev->dev);
ret = snd_card_register(aaci->card);
if (ret == 0) {
dev_info(&dev->dev, "%s\n", aaci->card->longname);
dev_info(&dev->dev, "FIFO %u entries\n", aaci->fifo_depth);
amba_set_drvdata(dev, aaci->card);
return ret;
}
out:
if (aaci)
snd_card_free(aaci->card);
amba_release_regions(dev);
return ret;
}
static int __devexit aaci_remove(struct amba_device *dev)
{
struct snd_card *card = amba_get_drvdata(dev);
amba_set_drvdata(dev, NULL);
if (card) {
struct aaci *aaci = card->private_data;
writel(0, aaci->base + AACI_MAINCR);
snd_card_free(card);
amba_release_regions(dev);
}
return 0;
}
static struct amba_id aaci_ids[] = {
{
.id = 0x00041041,
.mask = 0x000fffff,
},
{ 0, 0 },
};
static struct amba_driver aaci_driver = {
.drv = {
.name = DRIVER_NAME,
},
.probe = aaci_probe,
.remove = __devexit_p(aaci_remove),
.suspend = aaci_suspend,
.resume = aaci_resume,
.id_table = aaci_ids,
};
static int __init aaci_init(void)
{
return amba_driver_register(&aaci_driver);
}
static void __exit aaci_exit(void)
{
amba_driver_unregister(&aaci_driver);
}
module_init(aaci_init);
module_exit(aaci_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("ARM PrimeCell PL041 Advanced Audio CODEC Interface driver");
| gpl-2.0 |
vidoardes/Vivo-2.6.35 | arch/um/drivers/pcap_user.c | 4705 | 3025 | /*
* Copyright (C) 2002 - 2007 Jeff Dike (jdike@{addtoit,linux.intel}.com)
* Licensed under the GPL.
*/
#include <errno.h>
#include <pcap.h>
#include <string.h>
#include <asm/types.h>
#include "net_user.h"
#include "pcap_user.h"
#include "kern_constants.h"
#include "um_malloc.h"
#include "user.h"
#define PCAP_FD(p) (*(int *)(p))
static int pcap_user_init(void *data, void *dev)
{
struct pcap_data *pri = data;
pcap_t *p;
char errors[PCAP_ERRBUF_SIZE];
p = pcap_open_live(pri->host_if, ETH_MAX_PACKET + ETH_HEADER_OTHER,
pri->promisc, 0, errors);
if (p == NULL) {
printk(UM_KERN_ERR "pcap_user_init : pcap_open_live failed - "
"'%s'\n", errors);
return -EINVAL;
}
pri->dev = dev;
pri->pcap = p;
return 0;
}
static int pcap_open(void *data)
{
struct pcap_data *pri = data;
__u32 netmask;
int err;
if (pri->pcap == NULL)
return -ENODEV;
if (pri->filter != NULL) {
err = dev_netmask(pri->dev, &netmask);
if (err < 0) {
printk(UM_KERN_ERR "pcap_open : dev_netmask failed\n");
return -EIO;
}
pri->compiled = uml_kmalloc(sizeof(struct bpf_program),
UM_GFP_KERNEL);
if (pri->compiled == NULL) {
printk(UM_KERN_ERR "pcap_open : kmalloc failed\n");
return -ENOMEM;
}
err = pcap_compile(pri->pcap,
(struct bpf_program *) pri->compiled,
pri->filter, pri->optimize, netmask);
if (err < 0) {
printk(UM_KERN_ERR "pcap_open : pcap_compile failed - "
"'%s'\n", pcap_geterr(pri->pcap));
goto out;
}
err = pcap_setfilter(pri->pcap, pri->compiled);
if (err < 0) {
printk(UM_KERN_ERR "pcap_open : pcap_setfilter "
"failed - '%s'\n", pcap_geterr(pri->pcap));
goto out;
}
}
return PCAP_FD(pri->pcap);
out:
kfree(pri->compiled);
return -EIO;
}
static void pcap_remove(void *data)
{
struct pcap_data *pri = data;
if (pri->compiled != NULL)
pcap_freecode(pri->compiled);
if (pri->pcap != NULL)
pcap_close(pri->pcap);
}
struct pcap_handler_data {
char *buffer;
int len;
};
static void handler(u_char *data, const struct pcap_pkthdr *header,
const u_char *packet)
{
int len;
struct pcap_handler_data *hdata = (struct pcap_handler_data *) data;
len = hdata->len < header->caplen ? hdata->len : header->caplen;
memcpy(hdata->buffer, packet, len);
hdata->len = len;
}
int pcap_user_read(int fd, void *buffer, int len, struct pcap_data *pri)
{
struct pcap_handler_data hdata = ((struct pcap_handler_data)
{ .buffer = buffer,
.len = len });
int n;
n = pcap_dispatch(pri->pcap, 1, handler, (u_char *) &hdata);
if (n < 0) {
printk(UM_KERN_ERR "pcap_dispatch failed - %s\n",
pcap_geterr(pri->pcap));
return -EIO;
}
else if (n == 0)
return 0;
return hdata.len;
}
const struct net_user_info pcap_user_info = {
.init = pcap_user_init,
.open = pcap_open,
.close = NULL,
.remove = pcap_remove,
.add_address = NULL,
.delete_address = NULL,
.mtu = ETH_MAX_PACKET,
.max_packet = ETH_MAX_PACKET + ETH_HEADER_OTHER,
};
| gpl-2.0 |
choco81/x10_.32_kernel | arch/um/drivers/port_user.c | 4705 | 3774 | /*
* Copyright (C) 2001 - 2007 Jeff Dike (jdike@{linux.intel,addtoit}.com)
* Licensed under the GPL
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <termios.h>
#include <unistd.h>
#include <netinet/in.h>
#include "chan_user.h"
#include "kern_constants.h"
#include "os.h"
#include "port.h"
#include "um_malloc.h"
#include "user.h"
struct port_chan {
int raw;
struct termios tt;
void *kernel_data;
char dev[sizeof("32768\0")];
};
static void *port_init(char *str, int device, const struct chan_opts *opts)
{
struct port_chan *data;
void *kern_data;
char *end;
int port;
if (*str != ':') {
printk(UM_KERN_ERR "port_init : channel type 'port' must "
"specify a port number\n");
return NULL;
}
str++;
port = strtoul(str, &end, 0);
if ((*end != '\0') || (end == str)) {
printk(UM_KERN_ERR "port_init : couldn't parse port '%s'\n",
str);
return NULL;
}
kern_data = port_data(port);
if (kern_data == NULL)
return NULL;
data = uml_kmalloc(sizeof(*data), UM_GFP_KERNEL);
if (data == NULL)
goto err;
*data = ((struct port_chan) { .raw = opts->raw,
.kernel_data = kern_data });
sprintf(data->dev, "%d", port);
return data;
err:
port_kern_free(kern_data);
return NULL;
}
static void port_free(void *d)
{
struct port_chan *data = d;
port_kern_free(data->kernel_data);
kfree(data);
}
static int port_open(int input, int output, int primary, void *d,
char **dev_out)
{
struct port_chan *data = d;
int fd, err;
fd = port_wait(data->kernel_data);
if ((fd >= 0) && data->raw) {
CATCH_EINTR(err = tcgetattr(fd, &data->tt));
if (err)
return err;
err = raw(fd);
if (err)
return err;
}
*dev_out = data->dev;
return fd;
}
static void port_close(int fd, void *d)
{
struct port_chan *data = d;
port_remove_dev(data->kernel_data);
os_close_file(fd);
}
const struct chan_ops port_ops = {
.type = "port",
.init = port_init,
.open = port_open,
.close = port_close,
.read = generic_read,
.write = generic_write,
.console_write = generic_console_write,
.window_size = generic_window_size,
.free = port_free,
.winch = 1,
};
int port_listen_fd(int port)
{
struct sockaddr_in addr;
int fd, err, arg;
fd = socket(PF_INET, SOCK_STREAM, 0);
if (fd == -1)
return -errno;
arg = 1;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &arg, sizeof(arg)) < 0) {
err = -errno;
goto out;
}
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
err = -errno;
goto out;
}
if (listen(fd, 1) < 0) {
err = -errno;
goto out;
}
err = os_set_fd_block(fd, 0);
if (err < 0)
goto out;
return fd;
out:
close(fd);
return err;
}
struct port_pre_exec_data {
int sock_fd;
int pipe_fd;
};
static void port_pre_exec(void *arg)
{
struct port_pre_exec_data *data = arg;
dup2(data->sock_fd, 0);
dup2(data->sock_fd, 1);
dup2(data->sock_fd, 2);
close(data->sock_fd);
dup2(data->pipe_fd, 3);
shutdown(3, SHUT_RD);
close(data->pipe_fd);
}
int port_connection(int fd, int *socket, int *pid_out)
{
int new, err;
char *argv[] = { "/usr/sbin/in.telnetd", "-L",
"/usr/lib/uml/port-helper", NULL };
struct port_pre_exec_data data;
new = accept(fd, NULL, 0);
if (new < 0)
return -errno;
err = os_pipe(socket, 0, 0);
if (err < 0)
goto out_close;
data = ((struct port_pre_exec_data)
{ .sock_fd = new,
.pipe_fd = socket[1] });
err = run_helper(port_pre_exec, &data, argv);
if (err < 0)
goto out_shutdown;
*pid_out = err;
return new;
out_shutdown:
shutdown(socket[0], SHUT_RDWR);
close(socket[0]);
shutdown(socket[1], SHUT_RDWR);
close(socket[1]);
out_close:
close(new);
return err;
}
| gpl-2.0 |
CyanogenMod/android_kernel_samsung_hlte | arch/arm/mach-s3c24xx/mach-n30.c | 4961 | 15649 | /* Machine specific code for the Acer n30, Acer N35, Navman PiN 570,
* Yakumo AlphaX and Airis NC05 PDAs.
*
* Copyright (c) 2003-2005 Simtec Electronics
* Ben Dooks <ben@simtec.co.uk>
*
* Copyright (c) 2005-2008 Christer Weinigel <christer@weinigel.se>
*
* There is a wiki with more information about the n30 port at
* http://handhelds.org/moin/moin.cgi/AcerN30Documentation .
*
* 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/gpio_keys.h>
#include <linux/init.h>
#include <linux/gpio.h>
#include <linux/input.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/serial_core.h>
#include <linux/timer.h>
#include <linux/io.h>
#include <linux/mmc/host.h>
#include <mach/hardware.h>
#include <asm/irq.h>
#include <asm/mach-types.h>
#include <mach/fb.h>
#include <mach/leds-gpio.h>
#include <mach/regs-gpio.h>
#include <mach/regs-lcd.h>
#include <asm/mach/arch.h>
#include <asm/mach/irq.h>
#include <asm/mach/map.h>
#include <plat/iic.h>
#include <plat/regs-serial.h>
#include <plat/clock.h>
#include <plat/cpu.h>
#include <plat/devs.h>
#include <plat/mci.h>
#include <plat/s3c2410.h>
#include <plat/udc.h>
#include "common.h"
static struct map_desc n30_iodesc[] __initdata = {
/* nothing here yet */
};
static struct s3c2410_uartcfg n30_uartcfgs[] = {
/* Normal serial port */
[0] = {
.hwport = 0,
.flags = 0,
.ucon = 0x2c5,
.ulcon = 0x03,
.ufcon = 0x51,
},
/* IR port */
[1] = {
.hwport = 1,
.flags = 0,
.uart_flags = UPF_CONS_FLOW,
.ucon = 0x2c5,
.ulcon = 0x43,
.ufcon = 0x51,
},
/* On the N30 the bluetooth controller is connected here.
* On the N35 and variants the GPS receiver is connected here. */
[2] = {
.hwport = 2,
.flags = 0,
.ucon = 0x2c5,
.ulcon = 0x03,
.ufcon = 0x51,
},
};
static struct s3c2410_udc_mach_info n30_udc_cfg __initdata = {
.vbus_pin = S3C2410_GPG(1),
.vbus_pin_inverted = 0,
.pullup_pin = S3C2410_GPB(3),
};
static struct gpio_keys_button n30_buttons[] = {
{
.gpio = S3C2410_GPF(0),
.code = KEY_POWER,
.desc = "Power",
.active_low = 0,
},
{
.gpio = S3C2410_GPG(9),
.code = KEY_UP,
.desc = "Thumbwheel Up",
.active_low = 0,
},
{
.gpio = S3C2410_GPG(8),
.code = KEY_DOWN,
.desc = "Thumbwheel Down",
.active_low = 0,
},
{
.gpio = S3C2410_GPG(7),
.code = KEY_ENTER,
.desc = "Thumbwheel Press",
.active_low = 0,
},
{
.gpio = S3C2410_GPF(7),
.code = KEY_HOMEPAGE,
.desc = "Home",
.active_low = 0,
},
{
.gpio = S3C2410_GPF(6),
.code = KEY_CALENDAR,
.desc = "Calendar",
.active_low = 0,
},
{
.gpio = S3C2410_GPF(5),
.code = KEY_ADDRESSBOOK,
.desc = "Contacts",
.active_low = 0,
},
{
.gpio = S3C2410_GPF(4),
.code = KEY_MAIL,
.desc = "Mail",
.active_low = 0,
},
};
static struct gpio_keys_platform_data n30_button_data = {
.buttons = n30_buttons,
.nbuttons = ARRAY_SIZE(n30_buttons),
};
static struct platform_device n30_button_device = {
.name = "gpio-keys",
.id = -1,
.dev = {
.platform_data = &n30_button_data,
}
};
static struct gpio_keys_button n35_buttons[] = {
{
.gpio = S3C2410_GPF(0),
.code = KEY_POWER,
.type = EV_PWR,
.desc = "Power",
.active_low = 0,
.wakeup = 1,
},
{
.gpio = S3C2410_GPG(9),
.code = KEY_UP,
.desc = "Joystick Up",
.active_low = 0,
},
{
.gpio = S3C2410_GPG(8),
.code = KEY_DOWN,
.desc = "Joystick Down",
.active_low = 0,
},
{
.gpio = S3C2410_GPG(6),
.code = KEY_DOWN,
.desc = "Joystick Left",
.active_low = 0,
},
{
.gpio = S3C2410_GPG(5),
.code = KEY_DOWN,
.desc = "Joystick Right",
.active_low = 0,
},
{
.gpio = S3C2410_GPG(7),
.code = KEY_ENTER,
.desc = "Joystick Press",
.active_low = 0,
},
{
.gpio = S3C2410_GPF(7),
.code = KEY_HOMEPAGE,
.desc = "Home",
.active_low = 0,
},
{
.gpio = S3C2410_GPF(6),
.code = KEY_CALENDAR,
.desc = "Calendar",
.active_low = 0,
},
{
.gpio = S3C2410_GPF(5),
.code = KEY_ADDRESSBOOK,
.desc = "Contacts",
.active_low = 0,
},
{
.gpio = S3C2410_GPF(4),
.code = KEY_MAIL,
.desc = "Mail",
.active_low = 0,
},
{
.gpio = S3C2410_GPF(3),
.code = SW_RADIO,
.desc = "GPS Antenna",
.active_low = 0,
},
{
.gpio = S3C2410_GPG(2),
.code = SW_HEADPHONE_INSERT,
.desc = "Headphone",
.active_low = 0,
},
};
static struct gpio_keys_platform_data n35_button_data = {
.buttons = n35_buttons,
.nbuttons = ARRAY_SIZE(n35_buttons),
};
static struct platform_device n35_button_device = {
.name = "gpio-keys",
.id = -1,
.num_resources = 0,
.dev = {
.platform_data = &n35_button_data,
}
};
/* This is the bluetooth LED on the device. */
static struct s3c24xx_led_platdata n30_blue_led_pdata = {
.name = "blue_led",
.gpio = S3C2410_GPG(6),
.def_trigger = "",
};
/* This is the blue LED on the device. Originally used to indicate GPS activity
* by flashing. */
static struct s3c24xx_led_platdata n35_blue_led_pdata = {
.name = "blue_led",
.gpio = S3C2410_GPD(8),
.def_trigger = "",
};
/* This LED is driven by the battery microcontroller, and is blinking
* red, blinking green or solid green when the battery is low,
* charging or full respectively. By driving GPD9 low, it's possible
* to force the LED to blink red, so call that warning LED. */
static struct s3c24xx_led_platdata n30_warning_led_pdata = {
.name = "warning_led",
.flags = S3C24XX_LEDF_ACTLOW,
.gpio = S3C2410_GPD(9),
.def_trigger = "",
};
static struct s3c24xx_led_platdata n35_warning_led_pdata = {
.name = "warning_led",
.flags = S3C24XX_LEDF_ACTLOW | S3C24XX_LEDF_TRISTATE,
.gpio = S3C2410_GPD(9),
.def_trigger = "",
};
static struct platform_device n30_blue_led = {
.name = "s3c24xx_led",
.id = 1,
.dev = {
.platform_data = &n30_blue_led_pdata,
},
};
static struct platform_device n35_blue_led = {
.name = "s3c24xx_led",
.id = 1,
.dev = {
.platform_data = &n35_blue_led_pdata,
},
};
static struct platform_device n30_warning_led = {
.name = "s3c24xx_led",
.id = 2,
.dev = {
.platform_data = &n30_warning_led_pdata,
},
};
static struct platform_device n35_warning_led = {
.name = "s3c24xx_led",
.id = 2,
.dev = {
.platform_data = &n35_warning_led_pdata,
},
};
static struct s3c2410fb_display n30_display __initdata = {
.type = S3C2410_LCDCON1_TFT,
.width = 240,
.height = 320,
.pixclock = 170000,
.xres = 240,
.yres = 320,
.bpp = 16,
.left_margin = 3,
.right_margin = 40,
.hsync_len = 40,
.upper_margin = 2,
.lower_margin = 3,
.vsync_len = 2,
.lcdcon5 = S3C2410_LCDCON5_INVVLINE | S3C2410_LCDCON5_INVVFRAME,
};
static struct s3c2410fb_mach_info n30_fb_info __initdata = {
.displays = &n30_display,
.num_displays = 1,
.default_display = 0,
.lpcsel = 0x06,
};
static void n30_sdi_set_power(unsigned char power_mode, unsigned short vdd)
{
switch (power_mode) {
case MMC_POWER_ON:
case MMC_POWER_UP:
gpio_set_value(S3C2410_GPG(4), 1);
break;
case MMC_POWER_OFF:
default:
gpio_set_value(S3C2410_GPG(4), 0);
break;
}
}
static struct s3c24xx_mci_pdata n30_mci_cfg __initdata = {
.gpio_detect = S3C2410_GPF(1),
.gpio_wprotect = S3C2410_GPG(10),
.ocr_avail = MMC_VDD_32_33,
.set_power = n30_sdi_set_power,
};
static struct platform_device *n30_devices[] __initdata = {
&s3c_device_lcd,
&s3c_device_wdt,
&s3c_device_i2c0,
&s3c_device_iis,
&s3c_device_ohci,
&s3c_device_rtc,
&s3c_device_usbgadget,
&s3c_device_sdi,
&n30_button_device,
&n30_blue_led,
&n30_warning_led,
};
static struct platform_device *n35_devices[] __initdata = {
&s3c_device_lcd,
&s3c_device_wdt,
&s3c_device_i2c0,
&s3c_device_iis,
&s3c_device_rtc,
&s3c_device_usbgadget,
&s3c_device_sdi,
&n35_button_device,
&n35_blue_led,
&n35_warning_led,
};
static struct s3c2410_platform_i2c __initdata n30_i2ccfg = {
.flags = 0,
.slave_addr = 0x10,
.frequency = 10*1000,
};
/* Lots of hardcoded stuff, but it sets up the hardware in a useful
* state so that we can boot Linux directly from flash. */
static void __init n30_hwinit(void)
{
/* GPA0-11 special functions -- unknown what they do
* GPA12 N30 special function -- unknown what it does
* N35/PiN output -- unknown what it does
*
* A12 is nGCS1 on the N30 and an output on the N35/PiN. I
* don't think it does anything useful on the N30, so I ought
* to make it an output there too since it always driven to 0
* as far as I can tell. */
if (machine_is_n30())
__raw_writel(0x007fffff, S3C2410_GPACON);
if (machine_is_n35())
__raw_writel(0x007fefff, S3C2410_GPACON);
__raw_writel(0x00000000, S3C2410_GPADAT);
/* GPB0 TOUT0 backlight level
* GPB1 output 1=backlight on
* GPB2 output IrDA enable 0=transceiver enabled, 1=disabled
* GPB3 output USB D+ pull up 0=disabled, 1=enabled
* GPB4 N30 output -- unknown function
* N30/PiN GPS control 0=GPS enabled, 1=GPS disabled
* GPB5 output -- unknown function
* GPB6 input -- unknown function
* GPB7 output -- unknown function
* GPB8 output -- probably LCD driver enable
* GPB9 output -- probably LCD VSYNC driver enable
* GPB10 output -- probably LCD HSYNC driver enable
*/
__raw_writel(0x00154556, S3C2410_GPBCON);
__raw_writel(0x00000750, S3C2410_GPBDAT);
__raw_writel(0x00000073, S3C2410_GPBUP);
/* GPC0 input RS232 DCD/DSR/RI
* GPC1 LCD
* GPC2 output RS232 DTR?
* GPC3 input RS232 DCD/DSR/RI
* GPC4 LCD
* GPC5 output 0=NAND write enabled, 1=NAND write protect
* GPC6 input -- unknown function
* GPC7 input charger status 0=charger connected
* this input can be triggered by power on the USB device
* port too, but will go back to disconnected soon after.
* GPC8 N30/N35 output -- unknown function, always driven to 1
* PiN input -- unknown function, always read as 1
* Make it an input with a pull up for all models.
* GPC9-15 LCD
*/
__raw_writel(0xaaa80618, S3C2410_GPCCON);
__raw_writel(0x0000014c, S3C2410_GPCDAT);
__raw_writel(0x0000fef2, S3C2410_GPCUP);
/* GPD0 input -- unknown function
* GPD1-D7 LCD
* GPD8 N30 output -- unknown function
* N35/PiN output 1=GPS LED on
* GPD9 output 0=power led blinks red, 1=normal power led function
* GPD10 output -- unknown function
* GPD11-15 LCD drivers
*/
__raw_writel(0xaa95aaa4, S3C2410_GPDCON);
__raw_writel(0x00000601, S3C2410_GPDDAT);
__raw_writel(0x0000fbfe, S3C2410_GPDUP);
/* GPE0-4 I2S audio bus
* GPE5-10 SD/MMC bus
* E11-13 outputs -- unknown function, probably power management
* E14-15 I2C bus connected to the battery controller
*/
__raw_writel(0xa56aaaaa, S3C2410_GPECON);
__raw_writel(0x0000efc5, S3C2410_GPEDAT);
__raw_writel(0x0000f81f, S3C2410_GPEUP);
/* GPF0 input 0=power button pressed
* GPF1 input SD/MMC switch 0=card present
* GPF2 N30 1=reset button pressed (inverted compared to the rest)
* N35/PiN 0=reset button pressed
* GPF3 N30/PiN input -- unknown function
* N35 input GPS antenna position, 0=antenna closed, 1=open
* GPF4 input 0=button 4 pressed
* GPF5 input 0=button 3 pressed
* GPF6 input 0=button 2 pressed
* GPF7 input 0=button 1 pressed
*/
__raw_writel(0x0000aaaa, S3C2410_GPFCON);
__raw_writel(0x00000000, S3C2410_GPFDAT);
__raw_writel(0x000000ff, S3C2410_GPFUP);
/* GPG0 input RS232 DCD/DSR/RI
* GPG1 input 1=USB gadget port has power from a host
* GPG2 N30 input -- unknown function
* N35/PiN input 0=headphones plugged in, 1=not plugged in
* GPG3 N30 output -- unknown function
* N35/PiN input with unknown function
* GPG4 N30 output 0=MMC enabled, 1=MMC disabled
* GPG5 N30 output 0=BlueTooth chip disabled, 1=enabled
* N35/PiN input joystick right
* GPG6 N30 output 0=blue led on, 1=off
* N35/PiN input joystick left
* GPG7 input 0=thumbwheel pressed
* GPG8 input 0=thumbwheel down
* GPG9 input 0=thumbwheel up
* GPG10 input SD/MMC write protect switch
* GPG11 N30 input -- unknown function
* N35 output 0=GPS antenna powered, 1=not powered
* PiN output -- unknown function
* GPG12-15 touch screen functions
*
* The pullups differ between the models, so enable all
* pullups that are enabled on any of the models.
*/
if (machine_is_n30())
__raw_writel(0xff0a956a, S3C2410_GPGCON);
if (machine_is_n35())
__raw_writel(0xff4aa92a, S3C2410_GPGCON);
__raw_writel(0x0000e800, S3C2410_GPGDAT);
__raw_writel(0x0000f86f, S3C2410_GPGUP);
/* GPH0/1/2/3 RS232 serial port
* GPH4/5 IrDA serial port
* GPH6/7 N30 BlueTooth serial port
* N35/PiN GPS receiver
* GPH8 input -- unknown function
* GPH9 CLKOUT0 HCLK -- unknown use
* GPH10 CLKOUT1 FCLK -- unknown use
*
* The pull ups for H6/H7 are enabled on N30 but not on the
* N35/PiN. I suppose is useful for a budget model of the N30
* with no bluetooh. It doesn't hurt to have the pull ups
* enabled on the N35, so leave them enabled for all models.
*/
__raw_writel(0x0028aaaa, S3C2410_GPHCON);
__raw_writel(0x000005ef, S3C2410_GPHDAT);
__raw_writel(0x0000063f, S3C2410_GPHUP);
}
static void __init n30_map_io(void)
{
s3c24xx_init_io(n30_iodesc, ARRAY_SIZE(n30_iodesc));
n30_hwinit();
s3c24xx_init_clocks(0);
s3c24xx_init_uarts(n30_uartcfgs, ARRAY_SIZE(n30_uartcfgs));
}
/* GPB3 is the line that controls the pull-up for the USB D+ line */
static void __init n30_init(void)
{
WARN_ON(gpio_request(S3C2410_GPG(4), "mmc power"));
s3c24xx_fb_set_platdata(&n30_fb_info);
s3c24xx_udc_set_platdata(&n30_udc_cfg);
s3c24xx_mci_set_platdata(&n30_mci_cfg);
s3c_i2c0_set_platdata(&n30_i2ccfg);
/* Turn off suspend on both USB ports, and switch the
* selectable USB port to USB device mode. */
s3c2410_modify_misccr(S3C2410_MISCCR_USBHOST |
S3C2410_MISCCR_USBSUSPND0 |
S3C2410_MISCCR_USBSUSPND1, 0x0);
if (machine_is_n30()) {
/* Turn off suspend on both USB ports, and switch the
* selectable USB port to USB device mode. */
s3c2410_modify_misccr(S3C2410_MISCCR_USBHOST |
S3C2410_MISCCR_USBSUSPND0 |
S3C2410_MISCCR_USBSUSPND1, 0x0);
platform_add_devices(n30_devices, ARRAY_SIZE(n30_devices));
}
if (machine_is_n35()) {
/* Turn off suspend and switch the selectable USB port
* to USB device mode. Turn on suspend for the host
* port since it is not connected on the N35.
*
* Actually, the host port is available at some pads
* on the back of the device, so it would actually be
* possible to add a USB device inside the N35 if you
* are willing to do some hardware modifications. */
s3c2410_modify_misccr(S3C2410_MISCCR_USBHOST |
S3C2410_MISCCR_USBSUSPND0 |
S3C2410_MISCCR_USBSUSPND1,
S3C2410_MISCCR_USBSUSPND0);
platform_add_devices(n35_devices, ARRAY_SIZE(n35_devices));
}
}
MACHINE_START(N30, "Acer-N30")
/* Maintainer: Christer Weinigel <christer@weinigel.se>,
Ben Dooks <ben-linux@fluff.org>
*/
.atag_offset = 0x100,
.timer = &s3c24xx_timer,
.init_machine = n30_init,
.init_irq = s3c24xx_init_irq,
.map_io = n30_map_io,
.restart = s3c2410_restart,
MACHINE_END
MACHINE_START(N35, "Acer-N35")
/* Maintainer: Christer Weinigel <christer@weinigel.se>
*/
.atag_offset = 0x100,
.timer = &s3c24xx_timer,
.init_machine = n30_init,
.init_irq = s3c24xx_init_irq,
.map_io = n30_map_io,
.restart = s3c2410_restart,
MACHINE_END
| gpl-2.0 |
HashBang173/kernel_common | arch/arm/mach-s3c24xx/mach-jive.c | 4961 | 16879 | /* linux/arch/arm/mach-s3c2410/mach-jive.c
*
* Copyright 2007 Simtec Electronics
* Ben Dooks <ben@simtec.co.uk>
*
* http://armlinux.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.
*/
#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/syscore_ops.h>
#include <linux/serial_core.h>
#include <linux/platform_device.h>
#include <linux/i2c.h>
#include <video/ili9320.h>
#include <linux/spi/spi.h>
#include <linux/spi/spi_gpio.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <plat/regs-serial.h>
#include <plat/nand.h>
#include <plat/iic.h>
#include <mach/regs-power.h>
#include <mach/regs-gpio.h>
#include <mach/regs-mem.h>
#include <mach/regs-lcd.h>
#include <mach/fb.h>
#include <asm/mach-types.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/nand_ecc.h>
#include <linux/mtd/partitions.h>
#include <plat/s3c2412.h>
#include <plat/gpio-cfg.h>
#include <plat/clock.h>
#include <plat/devs.h>
#include <plat/cpu.h>
#include <plat/pm.h>
#include <plat/udc.h>
static struct map_desc jive_iodesc[] __initdata = {
};
#define UCON S3C2410_UCON_DEFAULT
#define ULCON S3C2410_LCON_CS8 | S3C2410_LCON_PNONE
#define UFCON S3C2410_UFCON_RXTRIG8 | S3C2410_UFCON_FIFOMODE
static struct s3c2410_uartcfg jive_uartcfgs[] = {
[0] = {
.hwport = 0,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
},
[1] = {
.hwport = 1,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
},
[2] = {
.hwport = 2,
.flags = 0,
.ucon = UCON,
.ulcon = ULCON,
.ufcon = UFCON,
}
};
/* Jive flash assignment
*
* 0x00000000-0x00028000 : uboot
* 0x00028000-0x0002c000 : uboot env
* 0x0002c000-0x00030000 : spare
* 0x00030000-0x00200000 : zimage A
* 0x00200000-0x01600000 : cramfs A
* 0x01600000-0x017d0000 : zimage B
* 0x017d0000-0x02bd0000 : cramfs B
* 0x02bd0000-0x03fd0000 : yaffs
*/
static struct mtd_partition __initdata jive_imageA_nand_part[] = {
#ifdef CONFIG_MACH_JIVE_SHOW_BOOTLOADER
/* Don't allow access to the bootloader from linux */
{
.name = "uboot",
.offset = 0,
.size = (160 * SZ_1K),
.mask_flags = MTD_WRITEABLE, /* force read-only */
},
/* spare */
{
.name = "spare",
.offset = (176 * SZ_1K),
.size = (16 * SZ_1K),
},
#endif
/* booted images */
{
.name = "kernel (ro)",
.offset = (192 * SZ_1K),
.size = (SZ_2M) - (192 * SZ_1K),
.mask_flags = MTD_WRITEABLE, /* force read-only */
}, {
.name = "root (ro)",
.offset = (SZ_2M),
.size = (20 * SZ_1M),
.mask_flags = MTD_WRITEABLE, /* force read-only */
},
/* yaffs */
{
.name = "yaffs",
.offset = (44 * SZ_1M),
.size = (20 * SZ_1M),
},
/* bootloader environment */
{
.name = "env",
.offset = (160 * SZ_1K),
.size = (16 * SZ_1K),
},
/* upgrade images */
{
.name = "zimage",
.offset = (22 * SZ_1M),
.size = (2 * SZ_1M) - (192 * SZ_1K),
}, {
.name = "cramfs",
.offset = (24 * SZ_1M) - (192*SZ_1K),
.size = (20 * SZ_1M),
},
};
static struct mtd_partition __initdata jive_imageB_nand_part[] = {
#ifdef CONFIG_MACH_JIVE_SHOW_BOOTLOADER
/* Don't allow access to the bootloader from linux */
{
.name = "uboot",
.offset = 0,
.size = (160 * SZ_1K),
.mask_flags = MTD_WRITEABLE, /* force read-only */
},
/* spare */
{
.name = "spare",
.offset = (176 * SZ_1K),
.size = (16 * SZ_1K),
},
#endif
/* booted images */
{
.name = "kernel (ro)",
.offset = (22 * SZ_1M),
.size = (2 * SZ_1M) - (192 * SZ_1K),
.mask_flags = MTD_WRITEABLE, /* force read-only */
},
{
.name = "root (ro)",
.offset = (24 * SZ_1M) - (192 * SZ_1K),
.size = (20 * SZ_1M),
.mask_flags = MTD_WRITEABLE, /* force read-only */
},
/* yaffs */
{
.name = "yaffs",
.offset = (44 * SZ_1M),
.size = (20 * SZ_1M),
},
/* bootloader environment */
{
.name = "env",
.offset = (160 * SZ_1K),
.size = (16 * SZ_1K),
},
/* upgrade images */
{
.name = "zimage",
.offset = (192 * SZ_1K),
.size = (2 * SZ_1M) - (192 * SZ_1K),
}, {
.name = "cramfs",
.offset = (2 * SZ_1M),
.size = (20 * SZ_1M),
},
};
static struct s3c2410_nand_set __initdata jive_nand_sets[] = {
[0] = {
.name = "flash",
.nr_chips = 1,
.nr_partitions = ARRAY_SIZE(jive_imageA_nand_part),
.partitions = jive_imageA_nand_part,
},
};
static struct s3c2410_platform_nand __initdata jive_nand_info = {
/* set taken from osiris nand timings, possibly still conservative */
.tacls = 30,
.twrph0 = 55,
.twrph1 = 40,
.sets = jive_nand_sets,
.nr_sets = ARRAY_SIZE(jive_nand_sets),
};
static int __init jive_mtdset(char *options)
{
struct s3c2410_nand_set *nand = &jive_nand_sets[0];
unsigned long set;
if (options == NULL || options[0] == '\0')
return 0;
if (strict_strtoul(options, 10, &set)) {
printk(KERN_ERR "failed to parse mtdset=%s\n", options);
return 0;
}
switch (set) {
case 1:
nand->nr_partitions = ARRAY_SIZE(jive_imageB_nand_part);
nand->partitions = jive_imageB_nand_part;
case 0:
/* this is already setup in the nand info */
break;
default:
printk(KERN_ERR "Unknown mtd set %ld specified,"
"using default.", set);
}
return 0;
}
/* parse the mtdset= option given to the kernel command line */
__setup("mtdset=", jive_mtdset);
/* LCD timing and setup */
#define LCD_XRES (240)
#define LCD_YRES (320)
#define LCD_LEFT_MARGIN (12)
#define LCD_RIGHT_MARGIN (12)
#define LCD_LOWER_MARGIN (12)
#define LCD_UPPER_MARGIN (12)
#define LCD_VSYNC (2)
#define LCD_HSYNC (2)
#define LCD_REFRESH (60)
#define LCD_HTOT (LCD_HSYNC + LCD_LEFT_MARGIN + LCD_XRES + LCD_RIGHT_MARGIN)
#define LCD_VTOT (LCD_VSYNC + LCD_LOWER_MARGIN + LCD_YRES + LCD_UPPER_MARGIN)
static struct s3c2410fb_display jive_vgg2432a4_display[] = {
[0] = {
.width = LCD_XRES,
.height = LCD_YRES,
.xres = LCD_XRES,
.yres = LCD_YRES,
.left_margin = LCD_LEFT_MARGIN,
.right_margin = LCD_RIGHT_MARGIN,
.upper_margin = LCD_UPPER_MARGIN,
.lower_margin = LCD_LOWER_MARGIN,
.hsync_len = LCD_HSYNC,
.vsync_len = LCD_VSYNC,
.pixclock = (1000000000000LL /
(LCD_REFRESH * LCD_HTOT * LCD_VTOT)),
.bpp = 16,
.type = (S3C2410_LCDCON1_TFT16BPP |
S3C2410_LCDCON1_TFT),
.lcdcon5 = (S3C2410_LCDCON5_FRM565 |
S3C2410_LCDCON5_INVVLINE |
S3C2410_LCDCON5_INVVFRAME |
S3C2410_LCDCON5_INVVDEN |
S3C2410_LCDCON5_PWREN),
},
};
/* todo - put into gpio header */
#define S3C2410_GPCCON_MASK(x) (3 << ((x) * 2))
#define S3C2410_GPDCON_MASK(x) (3 << ((x) * 2))
static struct s3c2410fb_mach_info jive_lcd_config = {
.displays = jive_vgg2432a4_display,
.num_displays = ARRAY_SIZE(jive_vgg2432a4_display),
.default_display = 0,
/* Enable VD[2..7], VD[10..15], VD[18..23] and VCLK, syncs, VDEN
* and disable the pull down resistors on pins we are using for LCD
* data. */
.gpcup = (0xf << 1) | (0x3f << 10),
.gpccon = (S3C2410_GPC1_VCLK | S3C2410_GPC2_VLINE |
S3C2410_GPC3_VFRAME | S3C2410_GPC4_VM |
S3C2410_GPC10_VD2 | S3C2410_GPC11_VD3 |
S3C2410_GPC12_VD4 | S3C2410_GPC13_VD5 |
S3C2410_GPC14_VD6 | S3C2410_GPC15_VD7),
.gpccon_mask = (S3C2410_GPCCON_MASK(1) | S3C2410_GPCCON_MASK(2) |
S3C2410_GPCCON_MASK(3) | S3C2410_GPCCON_MASK(4) |
S3C2410_GPCCON_MASK(10) | S3C2410_GPCCON_MASK(11) |
S3C2410_GPCCON_MASK(12) | S3C2410_GPCCON_MASK(13) |
S3C2410_GPCCON_MASK(14) | S3C2410_GPCCON_MASK(15)),
.gpdup = (0x3f << 2) | (0x3f << 10),
.gpdcon = (S3C2410_GPD2_VD10 | S3C2410_GPD3_VD11 |
S3C2410_GPD4_VD12 | S3C2410_GPD5_VD13 |
S3C2410_GPD6_VD14 | S3C2410_GPD7_VD15 |
S3C2410_GPD10_VD18 | S3C2410_GPD11_VD19 |
S3C2410_GPD12_VD20 | S3C2410_GPD13_VD21 |
S3C2410_GPD14_VD22 | S3C2410_GPD15_VD23),
.gpdcon_mask = (S3C2410_GPDCON_MASK(2) | S3C2410_GPDCON_MASK(3) |
S3C2410_GPDCON_MASK(4) | S3C2410_GPDCON_MASK(5) |
S3C2410_GPDCON_MASK(6) | S3C2410_GPDCON_MASK(7) |
S3C2410_GPDCON_MASK(10) | S3C2410_GPDCON_MASK(11)|
S3C2410_GPDCON_MASK(12) | S3C2410_GPDCON_MASK(13)|
S3C2410_GPDCON_MASK(14) | S3C2410_GPDCON_MASK(15)),
};
/* ILI9320 support. */
static void jive_lcm_reset(unsigned int set)
{
printk(KERN_DEBUG "%s(%d)\n", __func__, set);
gpio_set_value(S3C2410_GPG(13), set);
}
#undef LCD_UPPER_MARGIN
#define LCD_UPPER_MARGIN 2
static struct ili9320_platdata jive_lcm_config = {
.hsize = LCD_XRES,
.vsize = LCD_YRES,
.reset = jive_lcm_reset,
.suspend = ILI9320_SUSPEND_DEEP,
.entry_mode = ILI9320_ENTRYMODE_ID(3) | ILI9320_ENTRYMODE_BGR,
.display2 = (ILI9320_DISPLAY2_FP(LCD_UPPER_MARGIN) |
ILI9320_DISPLAY2_BP(LCD_LOWER_MARGIN)),
.display3 = 0x0,
.display4 = 0x0,
.rgb_if1 = (ILI9320_RGBIF1_RIM_RGB18 |
ILI9320_RGBIF1_RM | ILI9320_RGBIF1_CLK_RGBIF),
.rgb_if2 = ILI9320_RGBIF2_DPL,
.interface2 = 0x0,
.interface3 = 0x3,
.interface4 = (ILI9320_INTERFACE4_RTNE(16) |
ILI9320_INTERFACE4_DIVE(1)),
.interface5 = 0x0,
.interface6 = 0x0,
};
/* LCD SPI support */
static struct spi_gpio_platform_data jive_lcd_spi = {
.sck = S3C2410_GPG(8),
.mosi = S3C2410_GPB(8),
.miso = SPI_GPIO_NO_MISO,
};
static struct platform_device jive_device_lcdspi = {
.name = "spi-gpio",
.id = 1,
.dev.platform_data = &jive_lcd_spi,
};
/* WM8750 audio code SPI definition */
static struct spi_gpio_platform_data jive_wm8750_spi = {
.sck = S3C2410_GPB(4),
.mosi = S3C2410_GPB(9),
.miso = SPI_GPIO_NO_MISO,
};
static struct platform_device jive_device_wm8750 = {
.name = "spi-gpio",
.id = 2,
.dev.platform_data = &jive_wm8750_spi,
};
/* JIVE SPI devices. */
static struct spi_board_info __initdata jive_spi_devs[] = {
[0] = {
.modalias = "VGG2432A4",
.bus_num = 1,
.chip_select = 0,
.mode = SPI_MODE_3, /* CPOL=1, CPHA=1 */
.max_speed_hz = 100000,
.platform_data = &jive_lcm_config,
.controller_data = (void *)S3C2410_GPB(7),
}, {
.modalias = "WM8750",
.bus_num = 2,
.chip_select = 0,
.mode = SPI_MODE_0, /* CPOL=0, CPHA=0 */
.max_speed_hz = 100000,
.controller_data = (void *)S3C2410_GPH(10),
},
};
/* I2C bus and device configuration. */
static struct s3c2410_platform_i2c jive_i2c_cfg __initdata = {
.frequency = 80 * 1000,
.flags = S3C_IICFLG_FILTER,
.sda_delay = 2,
};
static struct i2c_board_info jive_i2c_devs[] __initdata = {
[0] = {
I2C_BOARD_INFO("lis302dl", 0x1c),
.irq = IRQ_EINT14,
},
};
/* The platform devices being used. */
static struct platform_device *jive_devices[] __initdata = {
&s3c_device_ohci,
&s3c_device_rtc,
&s3c_device_wdt,
&s3c_device_i2c0,
&s3c_device_lcd,
&jive_device_lcdspi,
&jive_device_wm8750,
&s3c_device_nand,
&s3c_device_usbgadget,
};
static struct s3c2410_udc_mach_info jive_udc_cfg __initdata = {
.vbus_pin = S3C2410_GPG(1), /* detect is on GPG1 */
};
/* Jive power management device */
#ifdef CONFIG_PM
static int jive_pm_suspend(void)
{
/* Write the magic value u-boot uses to check for resume into
* the INFORM0 register, and ensure INFORM1 is set to the
* correct address to resume from. */
__raw_writel(0x2BED, S3C2412_INFORM0);
__raw_writel(virt_to_phys(s3c_cpu_resume), S3C2412_INFORM1);
return 0;
}
static void jive_pm_resume(void)
{
__raw_writel(0x0, S3C2412_INFORM0);
}
#else
#define jive_pm_suspend NULL
#define jive_pm_resume NULL
#endif
static struct syscore_ops jive_pm_syscore_ops = {
.suspend = jive_pm_suspend,
.resume = jive_pm_resume,
};
static void __init jive_map_io(void)
{
s3c24xx_init_io(jive_iodesc, ARRAY_SIZE(jive_iodesc));
s3c24xx_init_clocks(12000000);
s3c24xx_init_uarts(jive_uartcfgs, ARRAY_SIZE(jive_uartcfgs));
}
static void jive_power_off(void)
{
printk(KERN_INFO "powering system down...\n");
s3c2410_gpio_setpin(S3C2410_GPC(5), 1);
s3c_gpio_cfgpin(S3C2410_GPC(5), S3C2410_GPIO_OUTPUT);
}
static void __init jive_machine_init(void)
{
/* register system core operations for managing low level suspend */
register_syscore_ops(&jive_pm_syscore_ops);
/* write our sleep configurations for the IO. Pull down all unused
* IO, ensure that we have turned off all peripherals we do not
* need, and configure the ones we do need. */
/* Port B sleep */
__raw_writel(S3C2412_SLPCON_IN(0) |
S3C2412_SLPCON_PULL(1) |
S3C2412_SLPCON_HIGH(2) |
S3C2412_SLPCON_PULL(3) |
S3C2412_SLPCON_PULL(4) |
S3C2412_SLPCON_PULL(5) |
S3C2412_SLPCON_PULL(6) |
S3C2412_SLPCON_HIGH(7) |
S3C2412_SLPCON_PULL(8) |
S3C2412_SLPCON_PULL(9) |
S3C2412_SLPCON_PULL(10), S3C2412_GPBSLPCON);
/* Port C sleep */
__raw_writel(S3C2412_SLPCON_PULL(0) |
S3C2412_SLPCON_PULL(1) |
S3C2412_SLPCON_PULL(2) |
S3C2412_SLPCON_PULL(3) |
S3C2412_SLPCON_PULL(4) |
S3C2412_SLPCON_PULL(5) |
S3C2412_SLPCON_LOW(6) |
S3C2412_SLPCON_PULL(6) |
S3C2412_SLPCON_PULL(7) |
S3C2412_SLPCON_PULL(8) |
S3C2412_SLPCON_PULL(9) |
S3C2412_SLPCON_PULL(10) |
S3C2412_SLPCON_PULL(11) |
S3C2412_SLPCON_PULL(12) |
S3C2412_SLPCON_PULL(13) |
S3C2412_SLPCON_PULL(14) |
S3C2412_SLPCON_PULL(15), S3C2412_GPCSLPCON);
/* Port D sleep */
__raw_writel(S3C2412_SLPCON_ALL_PULL, S3C2412_GPDSLPCON);
/* Port F sleep */
__raw_writel(S3C2412_SLPCON_LOW(0) |
S3C2412_SLPCON_LOW(1) |
S3C2412_SLPCON_LOW(2) |
S3C2412_SLPCON_EINT(3) |
S3C2412_SLPCON_EINT(4) |
S3C2412_SLPCON_EINT(5) |
S3C2412_SLPCON_EINT(6) |
S3C2412_SLPCON_EINT(7), S3C2412_GPFSLPCON);
/* Port G sleep */
__raw_writel(S3C2412_SLPCON_IN(0) |
S3C2412_SLPCON_IN(1) |
S3C2412_SLPCON_IN(2) |
S3C2412_SLPCON_IN(3) |
S3C2412_SLPCON_IN(4) |
S3C2412_SLPCON_IN(5) |
S3C2412_SLPCON_IN(6) |
S3C2412_SLPCON_IN(7) |
S3C2412_SLPCON_PULL(8) |
S3C2412_SLPCON_PULL(9) |
S3C2412_SLPCON_IN(10) |
S3C2412_SLPCON_PULL(11) |
S3C2412_SLPCON_PULL(12) |
S3C2412_SLPCON_PULL(13) |
S3C2412_SLPCON_IN(14) |
S3C2412_SLPCON_PULL(15), S3C2412_GPGSLPCON);
/* Port H sleep */
__raw_writel(S3C2412_SLPCON_PULL(0) |
S3C2412_SLPCON_PULL(1) |
S3C2412_SLPCON_PULL(2) |
S3C2412_SLPCON_PULL(3) |
S3C2412_SLPCON_PULL(4) |
S3C2412_SLPCON_PULL(5) |
S3C2412_SLPCON_PULL(6) |
S3C2412_SLPCON_IN(7) |
S3C2412_SLPCON_IN(8) |
S3C2412_SLPCON_PULL(9) |
S3C2412_SLPCON_IN(10), S3C2412_GPHSLPCON);
/* initialise the power management now we've setup everything. */
s3c_pm_init();
/** TODO - check that this is after the cmdline option! */
s3c_nand_set_platdata(&jive_nand_info);
/* initialise the spi */
gpio_request(S3C2410_GPG(13), "lcm reset");
gpio_direction_output(S3C2410_GPG(13), 0);
gpio_request(S3C2410_GPB(7), "jive spi");
gpio_direction_output(S3C2410_GPB(7), 1);
s3c2410_gpio_setpin(S3C2410_GPB(6), 0);
s3c_gpio_cfgpin(S3C2410_GPB(6), S3C2410_GPIO_OUTPUT);
s3c2410_gpio_setpin(S3C2410_GPG(8), 1);
s3c_gpio_cfgpin(S3C2410_GPG(8), S3C2410_GPIO_OUTPUT);
/* initialise the WM8750 spi */
gpio_request(S3C2410_GPH(10), "jive wm8750 spi");
gpio_direction_output(S3C2410_GPH(10), 1);
/* Turn off suspend on both USB ports, and switch the
* selectable USB port to USB device mode. */
s3c2410_modify_misccr(S3C2410_MISCCR_USBHOST |
S3C2410_MISCCR_USBSUSPND0 |
S3C2410_MISCCR_USBSUSPND1, 0x0);
s3c24xx_udc_set_platdata(&jive_udc_cfg);
s3c24xx_fb_set_platdata(&jive_lcd_config);
spi_register_board_info(jive_spi_devs, ARRAY_SIZE(jive_spi_devs));
s3c_i2c0_set_platdata(&jive_i2c_cfg);
i2c_register_board_info(0, jive_i2c_devs, ARRAY_SIZE(jive_i2c_devs));
pm_power_off = jive_power_off;
platform_add_devices(jive_devices, ARRAY_SIZE(jive_devices));
}
MACHINE_START(JIVE, "JIVE")
/* Maintainer: Ben Dooks <ben-linux@fluff.org> */
.atag_offset = 0x100,
.init_irq = s3c24xx_init_irq,
.map_io = jive_map_io,
.init_machine = jive_machine_init,
.timer = &s3c24xx_timer,
.restart = s3c2412_restart,
MACHINE_END
| gpl-2.0 |
friedrich420/S4-AEL-LP-FOR-LINUX-TESTING | arch/arm/mach-msm/idle.c | 4961 | 1498 | /* arch/arm/mach-msm/idle.c
*
* Idle processing for MSM7K - work around bugs with SWFI.
*
* Copyright (c) 2007 QUALCOMM Incorporated.
* Copyright (C) 2007 Google, Inc.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/init.h>
#include <asm/system.h>
static void msm_idle(void)
{
#ifdef CONFIG_MSM7X00A_IDLE
asm volatile (
"mrc p15, 0, r1, c1, c0, 0 /* read current CR */ \n\t"
"bic r0, r1, #(1 << 2) /* clear dcache bit */ \n\t"
"bic r0, r0, #(1 << 12) /* clear icache bit */ \n\t"
"mcr p15, 0, r0, c1, c0, 0 /* disable d/i cache */ \n\t"
"mov r0, #0 /* prepare wfi value */ \n\t"
"mcr p15, 0, r0, c7, c10, 0 /* flush the cache */ \n\t"
"mcr p15, 0, r0, c7, c10, 4 /* memory barrier */ \n\t"
"mcr p15, 0, r0, c7, c0, 4 /* wait for interrupt */ \n\t"
"mcr p15, 0, r1, c1, c0, 0 /* restore d/i cache */ \n\t"
: : : "r0","r1" );
#endif
}
static int __init msm_idle_init(void)
{
arm_pm_idle = msm_idle;
return 0;
}
arch_initcall(msm_idle_init);
| gpl-2.0 |
skeevy420/android_kernel_lge_d850 | arch/arm/mach-s3c24xx/mach-vstms.c | 4961 | 3528 | /* linux/arch/arm/mach-s3c2412/mach-vstms.c
*
* (C) 2006 Thomas Gleixner <tglx@linutronix.de>
*
* Derived from mach-smdk2413.c - (C) 2006 Simtec Electronics
*
* 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/serial_core.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/nand_ecc.h>
#include <linux/mtd/partitions.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <mach/hardware.h>
#include <asm/setup.h>
#include <asm/irq.h>
#include <asm/mach-types.h>
#include <plat/regs-serial.h>
#include <mach/regs-gpio.h>
#include <mach/regs-lcd.h>
#include <mach/idle.h>
#include <mach/fb.h>
#include <plat/iic.h>
#include <plat/nand.h>
#include <plat/s3c2410.h>
#include <plat/s3c2412.h>
#include <plat/clock.h>
#include <plat/devs.h>
#include <plat/cpu.h>
static struct map_desc vstms_iodesc[] __initdata = {
};
static struct s3c2410_uartcfg vstms_uartcfgs[] __initdata = {
[0] = {
.hwport = 0,
.flags = 0,
.ucon = 0x3c5,
.ulcon = 0x03,
.ufcon = 0x51,
},
[1] = {
.hwport = 1,
.flags = 0,
.ucon = 0x3c5,
.ulcon = 0x03,
.ufcon = 0x51,
},
[2] = {
.hwport = 2,
.flags = 0,
.ucon = 0x3c5,
.ulcon = 0x03,
.ufcon = 0x51,
}
};
static struct mtd_partition __initdata vstms_nand_part[] = {
[0] = {
.name = "Boot Agent",
.size = 0x7C000,
.offset = 0,
},
[1] = {
.name = "UBoot Config",
.offset = 0x7C000,
.size = 0x4000,
},
[2] = {
.name = "Kernel",
.offset = 0x80000,
.size = 0x200000,
},
[3] = {
.name = "RFS",
.offset = 0x280000,
.size = 0x3d80000,
},
};
static struct s3c2410_nand_set __initdata vstms_nand_sets[] = {
[0] = {
.name = "NAND",
.nr_chips = 1,
.nr_partitions = ARRAY_SIZE(vstms_nand_part),
.partitions = vstms_nand_part,
},
};
/* choose a set of timings which should suit most 512Mbit
* chips and beyond.
*/
static struct s3c2410_platform_nand __initdata vstms_nand_info = {
.tacls = 20,
.twrph0 = 60,
.twrph1 = 20,
.nr_sets = ARRAY_SIZE(vstms_nand_sets),
.sets = vstms_nand_sets,
};
static struct platform_device *vstms_devices[] __initdata = {
&s3c_device_ohci,
&s3c_device_wdt,
&s3c_device_i2c0,
&s3c_device_iis,
&s3c_device_rtc,
&s3c_device_nand,
};
static void __init vstms_fixup(struct tag *tags, char **cmdline,
struct meminfo *mi)
{
if (tags != phys_to_virt(S3C2410_SDRAM_PA + 0x100)) {
mi->nr_banks=1;
mi->bank[0].start = 0x30000000;
mi->bank[0].size = SZ_64M;
}
}
static void __init vstms_map_io(void)
{
s3c24xx_init_io(vstms_iodesc, ARRAY_SIZE(vstms_iodesc));
s3c24xx_init_clocks(12000000);
s3c24xx_init_uarts(vstms_uartcfgs, ARRAY_SIZE(vstms_uartcfgs));
}
static void __init vstms_init(void)
{
s3c_i2c0_set_platdata(NULL);
s3c_nand_set_platdata(&vstms_nand_info);
platform_add_devices(vstms_devices, ARRAY_SIZE(vstms_devices));
}
MACHINE_START(VSTMS, "VSTMS")
.atag_offset = 0x100,
.fixup = vstms_fixup,
.init_irq = s3c24xx_init_irq,
.init_machine = vstms_init,
.map_io = vstms_map_io,
.timer = &s3c24xx_timer,
.restart = s3c2412_restart,
MACHINE_END
| gpl-2.0 |
pronobis/linux_kernel_arm_N8000 | net/netfilter/nf_conntrack_netbios_ns.c | 12385 | 2254 | /*
* NetBIOS name service broadcast connection tracking helper
*
* (c) 2005 Patrick McHardy <kaber@trash.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 helper tracks locally originating NetBIOS name service
* requests by issuing permanent expectations (valid until
* timing out) matching all reply connections from the
* destination network. The only NetBIOS specific thing is
* actually the port number.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/in.h>
#include <net/netfilter/nf_conntrack.h>
#include <net/netfilter/nf_conntrack_helper.h>
#include <net/netfilter/nf_conntrack_expect.h>
#define NMBD_PORT 137
MODULE_AUTHOR("Patrick McHardy <kaber@trash.net>");
MODULE_DESCRIPTION("NetBIOS name service broadcast connection tracking helper");
MODULE_LICENSE("GPL");
MODULE_ALIAS("ip_conntrack_netbios_ns");
MODULE_ALIAS_NFCT_HELPER("netbios_ns");
static unsigned int timeout __read_mostly = 3;
module_param(timeout, uint, S_IRUSR);
MODULE_PARM_DESC(timeout, "timeout for master connection/replies in seconds");
static struct nf_conntrack_expect_policy exp_policy = {
.max_expected = 1,
};
static int netbios_ns_help(struct sk_buff *skb, unsigned int protoff,
struct nf_conn *ct, enum ip_conntrack_info ctinfo)
{
return nf_conntrack_broadcast_help(skb, protoff, ct, ctinfo, timeout);
}
static struct nf_conntrack_helper helper __read_mostly = {
.name = "netbios-ns",
.tuple.src.l3num = NFPROTO_IPV4,
.tuple.src.u.udp.port = cpu_to_be16(NMBD_PORT),
.tuple.dst.protonum = IPPROTO_UDP,
.me = THIS_MODULE,
.help = netbios_ns_help,
.expect_policy = &exp_policy,
};
static int __init nf_conntrack_netbios_ns_init(void)
{
exp_policy.timeout = timeout;
return nf_conntrack_helper_register(&helper);
}
static void __exit nf_conntrack_netbios_ns_fini(void)
{
nf_conntrack_helper_unregister(&helper);
}
module_init(nf_conntrack_netbios_ns_init);
module_exit(nf_conntrack_netbios_ns_fini);
| gpl-2.0 |
dianlujitao/android_kernel_zte_msm8994 | arch/parisc/math-emu/frnd.c | 14177 | 7173 | /*
* Linux/PA-RISC Project (http://www.parisc-linux.org/)
*
* Floating-point emulation code
* Copyright (C) 2001 Hewlett-Packard (Paul Bame) <bame@debian.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* BEGIN_DESC
*
* Purpose:
* Single Floating-point Round to Integer
* Double Floating-point Round to Integer
* Quad Floating-point Round to Integer (returns unimplemented)
*
* External Interfaces:
* dbl_frnd(srcptr,nullptr,dstptr,status)
* sgl_frnd(srcptr,nullptr,dstptr,status)
*
* END_DESC
*/
#include "float.h"
#include "sgl_float.h"
#include "dbl_float.h"
#include "cnv_float.h"
/*
* Single Floating-point Round to Integer
*/
/*ARGSUSED*/
int
sgl_frnd(sgl_floating_point *srcptr,
unsigned int *nullptr,
sgl_floating_point *dstptr,
unsigned int *status)
{
register unsigned int src, result;
register int src_exponent;
register boolean inexact = FALSE;
src = *srcptr;
/*
* check source operand for NaN or infinity
*/
if ((src_exponent = Sgl_exponent(src)) == SGL_INFINITY_EXPONENT) {
/*
* is signaling NaN?
*/
if (Sgl_isone_signaling(src)) {
/* trap if INVALIDTRAP enabled */
if (Is_invalidtrap_enabled()) return(INVALIDEXCEPTION);
/* make NaN quiet */
Set_invalidflag();
Sgl_set_quiet(src);
}
/*
* return quiet NaN or infinity
*/
*dstptr = src;
return(NOEXCEPTION);
}
/*
* Need to round?
*/
if ((src_exponent -= SGL_BIAS) >= SGL_P - 1) {
*dstptr = src;
return(NOEXCEPTION);
}
/*
* Generate result
*/
if (src_exponent >= 0) {
Sgl_clear_exponent_set_hidden(src);
result = src;
Sgl_rightshift(result,(SGL_P-1) - (src_exponent));
/* check for inexact */
if (Sgl_isinexact_to_fix(src,src_exponent)) {
inexact = TRUE;
/* round result */
switch (Rounding_mode()) {
case ROUNDPLUS:
if (Sgl_iszero_sign(src)) Sgl_increment(result);
break;
case ROUNDMINUS:
if (Sgl_isone_sign(src)) Sgl_increment(result);
break;
case ROUNDNEAREST:
if (Sgl_isone_roundbit(src,src_exponent))
if (Sgl_isone_stickybit(src,src_exponent)
|| (Sgl_isone_lowmantissa(result)))
Sgl_increment(result);
}
}
Sgl_leftshift(result,(SGL_P-1) - (src_exponent));
if (Sgl_isone_hiddenoverflow(result))
Sgl_set_exponent(result,src_exponent + (SGL_BIAS+1));
else Sgl_set_exponent(result,src_exponent + SGL_BIAS);
}
else {
result = src; /* set sign */
Sgl_setzero_exponentmantissa(result);
/* check for inexact */
if (Sgl_isnotzero_exponentmantissa(src)) {
inexact = TRUE;
/* round result */
switch (Rounding_mode()) {
case ROUNDPLUS:
if (Sgl_iszero_sign(src))
Sgl_set_exponent(result,SGL_BIAS);
break;
case ROUNDMINUS:
if (Sgl_isone_sign(src))
Sgl_set_exponent(result,SGL_BIAS);
break;
case ROUNDNEAREST:
if (src_exponent == -1)
if (Sgl_isnotzero_mantissa(src))
Sgl_set_exponent(result,SGL_BIAS);
}
}
}
*dstptr = result;
if (inexact) {
if (Is_inexacttrap_enabled()) return(INEXACTEXCEPTION);
else Set_inexactflag();
}
return(NOEXCEPTION);
}
/*
* Double Floating-point Round to Integer
*/
/*ARGSUSED*/
int
dbl_frnd(
dbl_floating_point *srcptr,
unsigned int *nullptr,
dbl_floating_point *dstptr,
unsigned int *status)
{
register unsigned int srcp1, srcp2, resultp1, resultp2;
register int src_exponent;
register boolean inexact = FALSE;
Dbl_copyfromptr(srcptr,srcp1,srcp2);
/*
* check source operand for NaN or infinity
*/
if ((src_exponent = Dbl_exponent(srcp1)) == DBL_INFINITY_EXPONENT) {
/*
* is signaling NaN?
*/
if (Dbl_isone_signaling(srcp1)) {
/* trap if INVALIDTRAP enabled */
if (Is_invalidtrap_enabled()) return(INVALIDEXCEPTION);
/* make NaN quiet */
Set_invalidflag();
Dbl_set_quiet(srcp1);
}
/*
* return quiet NaN or infinity
*/
Dbl_copytoptr(srcp1,srcp2,dstptr);
return(NOEXCEPTION);
}
/*
* Need to round?
*/
if ((src_exponent -= DBL_BIAS) >= DBL_P - 1) {
Dbl_copytoptr(srcp1,srcp2,dstptr);
return(NOEXCEPTION);
}
/*
* Generate result
*/
if (src_exponent >= 0) {
Dbl_clear_exponent_set_hidden(srcp1);
resultp1 = srcp1;
resultp2 = srcp2;
Dbl_rightshift(resultp1,resultp2,(DBL_P-1) - (src_exponent));
/* check for inexact */
if (Dbl_isinexact_to_fix(srcp1,srcp2,src_exponent)) {
inexact = TRUE;
/* round result */
switch (Rounding_mode()) {
case ROUNDPLUS:
if (Dbl_iszero_sign(srcp1))
Dbl_increment(resultp1,resultp2);
break;
case ROUNDMINUS:
if (Dbl_isone_sign(srcp1))
Dbl_increment(resultp1,resultp2);
break;
case ROUNDNEAREST:
if (Dbl_isone_roundbit(srcp1,srcp2,src_exponent))
if (Dbl_isone_stickybit(srcp1,srcp2,src_exponent)
|| (Dbl_isone_lowmantissap2(resultp2)))
Dbl_increment(resultp1,resultp2);
}
}
Dbl_leftshift(resultp1,resultp2,(DBL_P-1) - (src_exponent));
if (Dbl_isone_hiddenoverflow(resultp1))
Dbl_set_exponent(resultp1,src_exponent + (DBL_BIAS+1));
else Dbl_set_exponent(resultp1,src_exponent + DBL_BIAS);
}
else {
resultp1 = srcp1; /* set sign */
Dbl_setzero_exponentmantissa(resultp1,resultp2);
/* check for inexact */
if (Dbl_isnotzero_exponentmantissa(srcp1,srcp2)) {
inexact = TRUE;
/* round result */
switch (Rounding_mode()) {
case ROUNDPLUS:
if (Dbl_iszero_sign(srcp1))
Dbl_set_exponent(resultp1,DBL_BIAS);
break;
case ROUNDMINUS:
if (Dbl_isone_sign(srcp1))
Dbl_set_exponent(resultp1,DBL_BIAS);
break;
case ROUNDNEAREST:
if (src_exponent == -1)
if (Dbl_isnotzero_mantissa(srcp1,srcp2))
Dbl_set_exponent(resultp1,DBL_BIAS);
}
}
}
Dbl_copytoptr(resultp1,resultp2,dstptr);
if (inexact) {
if (Is_inexacttrap_enabled()) return(INEXACTEXCEPTION);
else Set_inexactflag();
}
return(NOEXCEPTION);
}
| gpl-2.0 |
tejaswanjari/SMR_FS-EXT4 | kernel/lib/fonts/font_pearl_8x8.c | 14689 | 55726 | /**********************************************/
/* */
/* Font file generated by cpi2fnt */
/* ------------------------------ */
/* Combined with the alpha-numeric */
/* portion of Greg Harp's old PEARL */
/* font (from earlier versions of */
/* linux-m86k) by John Shifflett */
/* */
/**********************************************/
#include <linux/font.h>
#define FONTDATAMAX 2048
static const unsigned char fontdata_pearl8x8[FONTDATAMAX] = {
/* 0 0x00 '^@' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 1 0x01 '^A' */
0x7e, /* 01111110 */
0x81, /* 10000001 */
0xa5, /* 10100101 */
0x81, /* 10000001 */
0xbd, /* 10111101 */
0x99, /* 10011001 */
0x81, /* 10000001 */
0x7e, /* 01111110 */
/* 2 0x02 '^B' */
0x7e, /* 01111110 */
0xff, /* 11111111 */
0xdb, /* 11011011 */
0xff, /* 11111111 */
0xc3, /* 11000011 */
0xe7, /* 11100111 */
0xff, /* 11111111 */
0x7e, /* 01111110 */
/* 3 0x03 '^C' */
0x6c, /* 01101100 */
0xfe, /* 11111110 */
0xfe, /* 11111110 */
0xfe, /* 11111110 */
0x7c, /* 01111100 */
0x38, /* 00111000 */
0x10, /* 00010000 */
0x00, /* 00000000 */
/* 4 0x04 '^D' */
0x10, /* 00010000 */
0x38, /* 00111000 */
0x7c, /* 01111100 */
0xfe, /* 11111110 */
0x7c, /* 01111100 */
0x38, /* 00111000 */
0x10, /* 00010000 */
0x00, /* 00000000 */
/* 5 0x05 '^E' */
0x38, /* 00111000 */
0x7c, /* 01111100 */
0x38, /* 00111000 */
0xfe, /* 11111110 */
0xfe, /* 11111110 */
0xd6, /* 11010110 */
0x10, /* 00010000 */
0x38, /* 00111000 */
/* 6 0x06 '^F' */
0x10, /* 00010000 */
0x38, /* 00111000 */
0x7c, /* 01111100 */
0xfe, /* 11111110 */
0xfe, /* 11111110 */
0x7c, /* 01111100 */
0x10, /* 00010000 */
0x38, /* 00111000 */
/* 7 0x07 '^G' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 8 0x08 '^H' */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xe7, /* 11100111 */
0xc3, /* 11000011 */
0xc3, /* 11000011 */
0xe7, /* 11100111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
/* 9 0x09 '^I' */
0x00, /* 00000000 */
0x3c, /* 00111100 */
0x66, /* 01100110 */
0x42, /* 01000010 */
0x42, /* 01000010 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 10 0x0a '^J' */
0xff, /* 11111111 */
0xc3, /* 11000011 */
0x99, /* 10011001 */
0xbd, /* 10111101 */
0xbd, /* 10111101 */
0x99, /* 10011001 */
0xc3, /* 11000011 */
0xff, /* 11111111 */
/* 11 0x0b '^K' */
0x0f, /* 00001111 */
0x07, /* 00000111 */
0x0f, /* 00001111 */
0x7d, /* 01111101 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0x78, /* 01111000 */
/* 12 0x0c '^L' */
0x3c, /* 00111100 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
/* 13 0x0d '^M' */
0x3f, /* 00111111 */
0x33, /* 00110011 */
0x3f, /* 00111111 */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x70, /* 01110000 */
0xf0, /* 11110000 */
0xe0, /* 11100000 */
/* 14 0x0e '^N' */
0x7f, /* 01111111 */
0x63, /* 01100011 */
0x7f, /* 01111111 */
0x63, /* 01100011 */
0x63, /* 01100011 */
0x67, /* 01100111 */
0xe6, /* 11100110 */
0xc0, /* 11000000 */
/* 15 0x0f '^O' */
0x18, /* 00011000 */
0xdb, /* 11011011 */
0x3c, /* 00111100 */
0xe7, /* 11100111 */
0xe7, /* 11100111 */
0x3c, /* 00111100 */
0xdb, /* 11011011 */
0x18, /* 00011000 */
/* 16 0x10 '^P' */
0x80, /* 10000000 */
0xe0, /* 11100000 */
0xf8, /* 11111000 */
0xfe, /* 11111110 */
0xf8, /* 11111000 */
0xe0, /* 11100000 */
0x80, /* 10000000 */
0x00, /* 00000000 */
/* 17 0x11 '^Q' */
0x02, /* 00000010 */
0x0e, /* 00001110 */
0x3e, /* 00111110 */
0xfe, /* 11111110 */
0x3e, /* 00111110 */
0x0e, /* 00001110 */
0x02, /* 00000010 */
0x00, /* 00000000 */
/* 18 0x12 '^R' */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
/* 19 0x13 '^S' */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x00, /* 00000000 */
0x66, /* 01100110 */
0x00, /* 00000000 */
/* 20 0x14 '^T' */
0x7f, /* 01111111 */
0xdb, /* 11011011 */
0xdb, /* 11011011 */
0x7b, /* 01111011 */
0x1b, /* 00011011 */
0x1b, /* 00011011 */
0x1b, /* 00011011 */
0x00, /* 00000000 */
/* 21 0x15 '^U' */
0x3e, /* 00111110 */
0x61, /* 01100001 */
0x3c, /* 00111100 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0x86, /* 10000110 */
0x7c, /* 01111100 */
/* 22 0x16 '^V' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x7e, /* 01111110 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
/* 23 0x17 '^W' */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0xff, /* 11111111 */
/* 24 0x18 '^X' */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 25 0x19 '^Y' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 26 0x1a '^Z' */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0xfe, /* 11111110 */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 27 0x1b '^[' */
0x00, /* 00000000 */
0x30, /* 00110000 */
0x60, /* 01100000 */
0xfe, /* 11111110 */
0x60, /* 01100000 */
0x30, /* 00110000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 28 0x1c '^\' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 29 0x1d '^]' */
0x00, /* 00000000 */
0x24, /* 00100100 */
0x66, /* 01100110 */
0xff, /* 11111111 */
0x66, /* 01100110 */
0x24, /* 00100100 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 30 0x1e '^^' */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x7e, /* 01111110 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 31 0x1f '^_' */
0x00, /* 00000000 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0x7e, /* 01111110 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 32 0x20 ' ' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 33 0x21 '!' */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x3c, /* 00111100 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 34 0x22 '"' */
0x6c, /* 01101100 */
0x6c, /* 01101100 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 35 0x23 '#' */
0x6c, /* 01101100 */
0x6c, /* 01101100 */
0xfe, /* 11111110 */
0x6c, /* 01101100 */
0xfe, /* 11111110 */
0x6c, /* 01101100 */
0x6c, /* 01101100 */
0x00, /* 00000000 */
/* 36 0x24 '$' */
0x18, /* 00011000 */
0x3e, /* 00111110 */
0x60, /* 01100000 */
0x3c, /* 00111100 */
0x06, /* 00000110 */
0x7c, /* 01111100 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 37 0x25 '%' */
0x00, /* 00000000 */
0xc6, /* 11000110 */
0xcc, /* 11001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x66, /* 01100110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 38 0x26 '&' */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0x68, /* 01101000 */
0x76, /* 01110110 */
0xdc, /* 11011100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 39 0x27 ''' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 40 0x28 '(' */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0x00, /* 00000000 */
/* 41 0x29 ')' */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0x0c, /* 00001100 */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x00, /* 00000000 */
/* 42 0x2a '*' */
0x00, /* 00000000 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0xff, /* 11111111 */
0x3c, /* 00111100 */
0x66, /* 01100110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 43 0x2b '+' */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 44 0x2c ',' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x30, /* 00110000 */
/* 45 0x2d '-' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 46 0x2e '.' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 47 0x2f '/' */
0x03, /* 00000011 */
0x06, /* 00000110 */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x60, /* 01100000 */
0xc0, /* 11000000 */
0x00, /* 00000000 */
/* 48 0x30 '0' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xde, /* 11011110 */
0xfe, /* 11111110 */
0xf6, /* 11110110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 49 0x31 '1' */
0x18, /* 00011000 */
0x78, /* 01111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 50 0x32 '2' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x60, /* 01100000 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
/* 51 0x33 '3' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0x06, /* 00000110 */
0x1c, /* 00011100 */
0x06, /* 00000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 52 0x34 '4' */
0x1c, /* 00011100 */
0x3c, /* 00111100 */
0x6c, /* 01101100 */
0xcc, /* 11001100 */
0xfe, /* 11111110 */
0x0c, /* 00001100 */
0x0c, /* 00001100 */
0x00, /* 00000000 */
/* 53 0x35 '5' */
0xfe, /* 11111110 */
0xc0, /* 11000000 */
0xfc, /* 11111100 */
0x06, /* 00000110 */
0x06, /* 00000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 54 0x36 '6' */
0x38, /* 00111000 */
0x60, /* 01100000 */
0xc0, /* 11000000 */
0xfc, /* 11111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 55 0x37 '7' */
0xfe, /* 11111110 */
0x06, /* 00000110 */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x60, /* 01100000 */
0x60, /* 01100000 */
0x00, /* 00000000 */
/* 56 0x38 '8' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 57 0x39 '9' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7e, /* 01111110 */
0x06, /* 00000110 */
0x0c, /* 00001100 */
0x38, /* 00111000 */
0x00, /* 00000000 */
/* 58 0x3a ':' */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 59 0x3b ';' */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x30, /* 00110000 */
/* 60 0x3c '<' */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x60, /* 01100000 */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0x00, /* 00000000 */
/* 61 0x3d '=' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 62 0x3e '>' */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0x06, /* 00000110 */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x00, /* 00000000 */
/* 63 0x3f '?' */
0x3c, /* 00111100 */
0x66, /* 01100110 */
0x06, /* 00000110 */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 64 0x40 '@' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xde, /* 11011110 */
0xde, /* 11011110 */
0xde, /* 11011110 */
0xc0, /* 11000000 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 65 0x41 'A' */
0x10, /* 00010000 */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 66 0x42 'B' */
0xfc, /* 11111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xfc, /* 11111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xfc, /* 11111100 */
0x00, /* 00000000 */
/* 67 0x43 'C' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 68 0x44 'D' */
0xfc, /* 11111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xfc, /* 11111100 */
0x00, /* 00000000 */
/* 69 0x45 'E' */
0xfe, /* 11111110 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xf8, /* 11111000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
/* 70 0x46 'F' */
0xfe, /* 11111110 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xf8, /* 11111000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0x00, /* 00000000 */
/* 71 0x47 'G' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc0, /* 11000000 */
0xce, /* 11001110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 72 0x48 'H' */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 73 0x49 'I' */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
/* 74 0x4a 'J' */
0x06, /* 00000110 */
0x06, /* 00000110 */
0x06, /* 00000110 */
0x06, /* 00000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 75 0x4b 'K' */
0xc6, /* 11000110 */
0xcc, /* 11001100 */
0xd8, /* 11011000 */
0xf0, /* 11110000 */
0xd8, /* 11011000 */
0xcc, /* 11001100 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 76 0x4c 'L' */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
/* 77 0x4d 'M' */
0x82, /* 10000010 */
0xc6, /* 11000110 */
0xee, /* 11101110 */
0xfe, /* 11111110 */
0xd6, /* 11010110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 78 0x4e 'N' */
0xc6, /* 11000110 */
0xe6, /* 11100110 */
0xf6, /* 11110110 */
0xde, /* 11011110 */
0xce, /* 11001110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 79 0x4f 'O' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 80 0x50 'P' */
0xfc, /* 11111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xfc, /* 11111100 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0x00, /* 00000000 */
/* 81 0x51 'Q' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xf6, /* 11110110 */
0xde, /* 11011110 */
0x7c, /* 01111100 */
0x06, /* 00000110 */
/* 82 0x52 'R' */
0xfc, /* 11111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xfc, /* 11111100 */
0xd8, /* 11011000 */
0xcc, /* 11001100 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 83 0x53 'S' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0x60, /* 01100000 */
0x38, /* 00111000 */
0x0c, /* 00001100 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 84 0x54 'T' */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 85 0x55 'U' */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 86 0x56 'V' */
0xc3, /* 11000011 */
0xc3, /* 11000011 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 87 0x57 'W' */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xd6, /* 11010110 */
0xfe, /* 11111110 */
0xee, /* 11101110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 88 0x58 'X' */
0xc3, /* 11000011 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x66, /* 01100110 */
0xc3, /* 11000011 */
0x00, /* 00000000 */
/* 89 0x59 'Y' */
0xc3, /* 11000011 */
0xc3, /* 11000011 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 90 0x5a 'Z' */
0xfe, /* 11111110 */
0x06, /* 00000110 */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x60, /* 01100000 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
/* 91 0x5b '[' */
0x3c, /* 00111100 */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 92 0x5c '\' */
0xc0, /* 11000000 */
0x60, /* 01100000 */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0x06, /* 00000110 */
0x03, /* 00000011 */
0x00, /* 00000000 */
/* 93 0x5d ']' */
0x3c, /* 00111100 */
0x0c, /* 00001100 */
0x0c, /* 00001100 */
0x0c, /* 00001100 */
0x0c, /* 00001100 */
0x0c, /* 00001100 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 94 0x5e '^' */
0x10, /* 00010000 */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 95 0x5f '_' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xfe, /* 11111110 */
/* 96 0x60 '`' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 97 0x61 'a' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7c, /* 01111100 */
0x06, /* 00000110 */
0x7e, /* 01111110 */
0xc6, /* 11000110 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
/* 98 0x62 'b' */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xfc, /* 11111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xfc, /* 11111100 */
0x00, /* 00000000 */
/* 99 0x63 'c' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc0, /* 11000000 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 100 0x64 'd' */
0x06, /* 00000110 */
0x06, /* 00000110 */
0x7e, /* 01111110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
/* 101 0x65 'e' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc0, /* 11000000 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 102 0x66 'f' */
0x3c, /* 00111100 */
0x66, /* 01100110 */
0x60, /* 01100000 */
0xf0, /* 11110000 */
0x60, /* 01100000 */
0x60, /* 01100000 */
0x60, /* 01100000 */
0x00, /* 00000000 */
/* 103 0x67 'g' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7e, /* 01111110 */
0x06, /* 00000110 */
0x7c, /* 01111100 */
/* 104 0x68 'h' */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xfc, /* 11111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 105 0x69 'i' */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x38, /* 00111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 106 0x6a 'j' */
0x06, /* 00000110 */
0x00, /* 00000000 */
0x06, /* 00000110 */
0x06, /* 00000110 */
0x06, /* 00000110 */
0x06, /* 00000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
/* 107 0x6b 'k' */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xcc, /* 11001100 */
0xd8, /* 11011000 */
0xf0, /* 11110000 */
0xd8, /* 11011000 */
0xcc, /* 11001100 */
0x00, /* 00000000 */
/* 108 0x6c 'l' */
0x38, /* 00111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 109 0x6d 'm' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xec, /* 11101100 */
0xfe, /* 11111110 */
0xd6, /* 11010110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 110 0x6e 'n' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xfc, /* 11111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 111 0x6f 'o' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 112 0x70 'p' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xfc, /* 11111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xfc, /* 11111100 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
/* 113 0x71 'q' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7e, /* 01111110 */
0x06, /* 00000110 */
0x06, /* 00000110 */
/* 114 0x72 'r' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xdc, /* 11011100 */
0xe6, /* 11100110 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0x00, /* 00000000 */
/* 115 0x73 's' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0xc0, /* 11000000 */
0x7c, /* 01111100 */
0x06, /* 00000110 */
0xfc, /* 11111100 */
0x00, /* 00000000 */
/* 116 0x74 't' */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x7c, /* 01111100 */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x36, /* 00110110 */
0x1c, /* 00011100 */
0x00, /* 00000000 */
/* 117 0x75 'u' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 118 0x76 'v' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x6c, /* 01101100 */
0x38, /* 00111000 */
0x00, /* 00000000 */
/* 119 0x77 'w' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xd6, /* 11010110 */
0xfe, /* 11111110 */
0x6c, /* 01101100 */
0x00, /* 00000000 */
/* 120 0x78 'x' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xc6, /* 11000110 */
0x6c, /* 01101100 */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 121 0x79 'y' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xc3, /* 11000011 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x60, /* 01100000 */
/* 122 0x7a 'z' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xfe, /* 11111110 */
0x0c, /* 00001100 */
0x38, /* 00111000 */
0x60, /* 01100000 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
/* 123 0x7b '{' */
0x0e, /* 00001110 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x70, /* 01110000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x0e, /* 00001110 */
0x00, /* 00000000 */
/* 124 0x7c '|' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 125 0x7d '}' */
0x70, /* 01110000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x0e, /* 00001110 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x70, /* 01110000 */
0x00, /* 00000000 */
/* 126 0x7e '~' */
0x72, /* 01110010 */
0x9c, /* 10011100 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 127 0x7f '' */
0x00, /* 00000000 */
0x10, /* 00010000 */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
/* 128 0x80 '' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x0c, /* 00001100 */
0x78, /* 01111000 */
/* 129 0x81 '' */
0xcc, /* 11001100 */
0x00, /* 00000000 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 130 0x82 '' */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc0, /* 11000000 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 131 0x83 '' */
0x7c, /* 01111100 */
0x82, /* 10000010 */
0x78, /* 01111000 */
0x0c, /* 00001100 */
0x7c, /* 01111100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 132 0x84 '' */
0xc6, /* 11000110 */
0x00, /* 00000000 */
0x78, /* 01111000 */
0x0c, /* 00001100 */
0x7c, /* 01111100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 133 0x85 '
' */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x78, /* 01111000 */
0x0c, /* 00001100 */
0x7c, /* 01111100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 134 0x86 '' */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x78, /* 01111000 */
0x0c, /* 00001100 */
0x7c, /* 01111100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 135 0x87 '' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0x7e, /* 01111110 */
0x0c, /* 00001100 */
0x38, /* 00111000 */
/* 136 0x88 '' */
0x7c, /* 01111100 */
0x82, /* 10000010 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc0, /* 11000000 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 137 0x89 '' */
0xc6, /* 11000110 */
0x00, /* 00000000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc0, /* 11000000 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 138 0x8a '' */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc0, /* 11000000 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 139 0x8b '' */
0x66, /* 01100110 */
0x00, /* 00000000 */
0x38, /* 00111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 140 0x8c '' */
0x7c, /* 01111100 */
0x82, /* 10000010 */
0x38, /* 00111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 141 0x8d '' */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x38, /* 00111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 142 0x8e '' */
0xc6, /* 11000110 */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 143 0x8f '' */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 144 0x90 '' */
0x18, /* 00011000 */
0x30, /* 00110000 */
0xfe, /* 11111110 */
0xc0, /* 11000000 */
0xf8, /* 11111000 */
0xc0, /* 11000000 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
/* 145 0x91 '' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0xd8, /* 11011000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
/* 146 0x92 '' */
0x3e, /* 00111110 */
0x6c, /* 01101100 */
0xcc, /* 11001100 */
0xfe, /* 11111110 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xce, /* 11001110 */
0x00, /* 00000000 */
/* 147 0x93 '' */
0x7c, /* 01111100 */
0x82, /* 10000010 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 148 0x94 '' */
0xc6, /* 11000110 */
0x00, /* 00000000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 149 0x95 '' */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 150 0x96 '' */
0x78, /* 01111000 */
0x84, /* 10000100 */
0x00, /* 00000000 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 151 0x97 '' */
0x60, /* 01100000 */
0x30, /* 00110000 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 152 0x98 '' */
0xc6, /* 11000110 */
0x00, /* 00000000 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7e, /* 01111110 */
0x06, /* 00000110 */
0xfc, /* 11111100 */
/* 153 0x99 '' */
0xc6, /* 11000110 */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x6c, /* 01101100 */
0x38, /* 00111000 */
0x00, /* 00000000 */
/* 154 0x9a '' */
0xc6, /* 11000110 */
0x00, /* 00000000 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 155 0x9b '' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 156 0x9c '' */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0x64, /* 01100100 */
0xf0, /* 11110000 */
0x60, /* 01100000 */
0x66, /* 01100110 */
0xfc, /* 11111100 */
0x00, /* 00000000 */
/* 157 0x9d '' */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 158 0x9e '' */
0xf8, /* 11111000 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xfa, /* 11111010 */
0xc6, /* 11000110 */
0xcf, /* 11001111 */
0xc6, /* 11000110 */
0xc7, /* 11000111 */
/* 159 0x9f '' */
0x0e, /* 00001110 */
0x1b, /* 00011011 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0xd8, /* 11011000 */
0x70, /* 01110000 */
0x00, /* 00000000 */
/* 160 0xa0 ' ' */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x78, /* 01111000 */
0x0c, /* 00001100 */
0x7c, /* 01111100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 161 0xa1 '¡' */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x38, /* 00111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 162 0xa2 '¢' */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 163 0xa3 '£' */
0x18, /* 00011000 */
0x30, /* 00110000 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 164 0xa4 '¤' */
0x76, /* 01110110 */
0xdc, /* 11011100 */
0x00, /* 00000000 */
0xdc, /* 11011100 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x00, /* 00000000 */
/* 165 0xa5 '¥' */
0x76, /* 01110110 */
0xdc, /* 11011100 */
0x00, /* 00000000 */
0xe6, /* 11100110 */
0xf6, /* 11110110 */
0xde, /* 11011110 */
0xce, /* 11001110 */
0x00, /* 00000000 */
/* 166 0xa6 '¦' */
0x3c, /* 00111100 */
0x6c, /* 01101100 */
0x6c, /* 01101100 */
0x3e, /* 00111110 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 167 0xa7 '§' */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0x6c, /* 01101100 */
0x38, /* 00111000 */
0x00, /* 00000000 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 168 0xa8 '¨' */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x63, /* 01100011 */
0x3e, /* 00111110 */
0x00, /* 00000000 */
/* 169 0xa9 '©' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xfe, /* 11111110 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 170 0xaa 'ª' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xfe, /* 11111110 */
0x06, /* 00000110 */
0x06, /* 00000110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 171 0xab '«' */
0x63, /* 01100011 */
0xe6, /* 11100110 */
0x6c, /* 01101100 */
0x7e, /* 01111110 */
0x33, /* 00110011 */
0x66, /* 01100110 */
0xcc, /* 11001100 */
0x0f, /* 00001111 */
/* 172 0xac '¬' */
0x63, /* 01100011 */
0xe6, /* 11100110 */
0x6c, /* 01101100 */
0x7a, /* 01111010 */
0x36, /* 00110110 */
0x6a, /* 01101010 */
0xdf, /* 11011111 */
0x06, /* 00000110 */
/* 173 0xad '' */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 174 0xae '®' */
0x00, /* 00000000 */
0x33, /* 00110011 */
0x66, /* 01100110 */
0xcc, /* 11001100 */
0x66, /* 01100110 */
0x33, /* 00110011 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 175 0xaf '¯' */
0x00, /* 00000000 */
0xcc, /* 11001100 */
0x66, /* 01100110 */
0x33, /* 00110011 */
0x66, /* 01100110 */
0xcc, /* 11001100 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 176 0xb0 '°' */
0x22, /* 00100010 */
0x88, /* 10001000 */
0x22, /* 00100010 */
0x88, /* 10001000 */
0x22, /* 00100010 */
0x88, /* 10001000 */
0x22, /* 00100010 */
0x88, /* 10001000 */
/* 177 0xb1 '±' */
0x55, /* 01010101 */
0xaa, /* 10101010 */
0x55, /* 01010101 */
0xaa, /* 10101010 */
0x55, /* 01010101 */
0xaa, /* 10101010 */
0x55, /* 01010101 */
0xaa, /* 10101010 */
/* 178 0xb2 '²' */
0x77, /* 01110111 */
0xdd, /* 11011101 */
0x77, /* 01110111 */
0xdd, /* 11011101 */
0x77, /* 01110111 */
0xdd, /* 11011101 */
0x77, /* 01110111 */
0xdd, /* 11011101 */
/* 179 0xb3 '³' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 180 0xb4 '´' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0xf8, /* 11111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 181 0xb5 'µ' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0xf8, /* 11111000 */
0x18, /* 00011000 */
0xf8, /* 11111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 182 0xb6 '¶' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0xf6, /* 11110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 183 0xb7 '·' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xfe, /* 11111110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 184 0xb8 '¸' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xf8, /* 11111000 */
0x18, /* 00011000 */
0xf8, /* 11111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 185 0xb9 '¹' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0xf6, /* 11110110 */
0x06, /* 00000110 */
0xf6, /* 11110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 186 0xba 'º' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 187 0xbb '»' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xfe, /* 11111110 */
0x06, /* 00000110 */
0xf6, /* 11110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 188 0xbc '¼' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0xf6, /* 11110110 */
0x06, /* 00000110 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 189 0xbd '½' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 190 0xbe '¾' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0xf8, /* 11111000 */
0x18, /* 00011000 */
0xf8, /* 11111000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 191 0xbf '¿' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xf8, /* 11111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 192 0xc0 'À' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x1f, /* 00011111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 193 0xc1 'Á' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 194 0xc2 'Â' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 195 0xc3 'Ã' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x1f, /* 00011111 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 196 0xc4 'Ä' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 197 0xc5 'Å' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0xff, /* 11111111 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 198 0xc6 'Æ' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x1f, /* 00011111 */
0x18, /* 00011000 */
0x1f, /* 00011111 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 199 0xc7 'Ç' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x37, /* 00110111 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 200 0xc8 'È' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x37, /* 00110111 */
0x30, /* 00110000 */
0x3f, /* 00111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 201 0xc9 'É' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x3f, /* 00111111 */
0x30, /* 00110000 */
0x37, /* 00110111 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 202 0xca 'Ê' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0xf7, /* 11110111 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 203 0xcb 'Ë' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0xf7, /* 11110111 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 204 0xcc 'Ì' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x37, /* 00110111 */
0x30, /* 00110000 */
0x37, /* 00110111 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 205 0xcd 'Í' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 206 0xce 'Î' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0xf7, /* 11110111 */
0x00, /* 00000000 */
0xf7, /* 11110111 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 207 0xcf 'Ï' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 208 0xd0 'Ð' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 209 0xd1 'Ñ' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 210 0xd2 'Ò' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 211 0xd3 'Ó' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x3f, /* 00111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 212 0xd4 'Ô' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x1f, /* 00011111 */
0x18, /* 00011000 */
0x1f, /* 00011111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 213 0xd5 'Õ' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x1f, /* 00011111 */
0x18, /* 00011000 */
0x1f, /* 00011111 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 214 0xd6 'Ö' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x3f, /* 00111111 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 215 0xd7 '×' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0xff, /* 11111111 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 216 0xd8 'Ø' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0xff, /* 11111111 */
0x18, /* 00011000 */
0xff, /* 11111111 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 217 0xd9 'Ù' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0xf8, /* 11111000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 218 0xda 'Ú' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x1f, /* 00011111 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 219 0xdb 'Û' */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
/* 220 0xdc 'Ü' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
/* 221 0xdd 'Ý' */
0xf0, /* 11110000 */
0xf0, /* 11110000 */
0xf0, /* 11110000 */
0xf0, /* 11110000 */
0xf0, /* 11110000 */
0xf0, /* 11110000 */
0xf0, /* 11110000 */
0xf0, /* 11110000 */
/* 222 0xde 'Þ' */
0x0f, /* 00001111 */
0x0f, /* 00001111 */
0x0f, /* 00001111 */
0x0f, /* 00001111 */
0x0f, /* 00001111 */
0x0f, /* 00001111 */
0x0f, /* 00001111 */
0x0f, /* 00001111 */
/* 223 0xdf 'ß' */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 224 0xe0 'à' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x76, /* 01110110 */
0xdc, /* 11011100 */
0xc8, /* 11001000 */
0xdc, /* 11011100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 225 0xe1 'á' */
0x78, /* 01111000 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xd8, /* 11011000 */
0xcc, /* 11001100 */
0xc6, /* 11000110 */
0xcc, /* 11001100 */
0x00, /* 00000000 */
/* 226 0xe2 'â' */
0xfe, /* 11111110 */
0xc6, /* 11000110 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0x00, /* 00000000 */
/* 227 0xe3 'ã' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xfe, /* 11111110 */
0x6c, /* 01101100 */
0x6c, /* 01101100 */
0x6c, /* 01101100 */
0x6c, /* 01101100 */
0x00, /* 00000000 */
/* 228 0xe4 'ä' */
0xfe, /* 11111110 */
0xc6, /* 11000110 */
0x60, /* 01100000 */
0x30, /* 00110000 */
0x60, /* 01100000 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
/* 229 0xe5 'å' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0xd8, /* 11011000 */
0xd8, /* 11011000 */
0xd8, /* 11011000 */
0x70, /* 01110000 */
0x00, /* 00000000 */
/* 230 0xe6 'æ' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x7c, /* 01111100 */
0xc0, /* 11000000 */
/* 231 0xe7 'ç' */
0x00, /* 00000000 */
0x76, /* 01110110 */
0xdc, /* 11011100 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 232 0xe8 'è' */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
/* 233 0xe9 'é' */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc6, /* 11000110 */
0x6c, /* 01101100 */
0x38, /* 00111000 */
0x00, /* 00000000 */
/* 234 0xea 'ê' */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x6c, /* 01101100 */
0x6c, /* 01101100 */
0xee, /* 11101110 */
0x00, /* 00000000 */
/* 235 0xeb 'ë' */
0x0e, /* 00001110 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0x3e, /* 00111110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 236 0xec 'ì' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0xdb, /* 11011011 */
0xdb, /* 11011011 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 237 0xed 'í' */
0x06, /* 00000110 */
0x0c, /* 00001100 */
0x7e, /* 01111110 */
0xdb, /* 11011011 */
0xdb, /* 11011011 */
0x7e, /* 01111110 */
0x60, /* 01100000 */
0xc0, /* 11000000 */
/* 238 0xee 'î' */
0x1e, /* 00011110 */
0x30, /* 00110000 */
0x60, /* 01100000 */
0x7e, /* 01111110 */
0x60, /* 01100000 */
0x30, /* 00110000 */
0x1e, /* 00011110 */
0x00, /* 00000000 */
/* 239 0xef 'ï' */
0x00, /* 00000000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 240 0xf0 'ð' */
0x00, /* 00000000 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 241 0xf1 'ñ' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
/* 242 0xf2 'ò' */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
/* 243 0xf3 'ó' */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
/* 244 0xf4 'ô' */
0x0e, /* 00001110 */
0x1b, /* 00011011 */
0x1b, /* 00011011 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 245 0xf5 'õ' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0xd8, /* 11011000 */
0xd8, /* 11011000 */
0x70, /* 01110000 */
/* 246 0xf6 'ö' */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 247 0xf7 '÷' */
0x00, /* 00000000 */
0x76, /* 01110110 */
0xdc, /* 11011100 */
0x00, /* 00000000 */
0x76, /* 01110110 */
0xdc, /* 11011100 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 248 0xf8 'ø' */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0x6c, /* 01101100 */
0x38, /* 00111000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 249 0xf9 'ù' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 250 0xfa 'ú' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 251 0xfb 'û' */
0x0f, /* 00001111 */
0x0c, /* 00001100 */
0x0c, /* 00001100 */
0x0c, /* 00001100 */
0xec, /* 11101100 */
0x6c, /* 01101100 */
0x3c, /* 00111100 */
0x1c, /* 00011100 */
/* 252 0xfc 'ü' */
0x6c, /* 01101100 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 253 0xfd 'ý' */
0x78, /* 01111000 */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 254 0xfe 'þ' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x3c, /* 00111100 */
0x3c, /* 00111100 */
0x3c, /* 00111100 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 255 0xff 'ÿ' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
};
const struct font_desc font_pearl_8x8 = {
.idx = PEARL8x8_IDX,
.name = "PEARL8x8",
.width = 8,
.height = 8,
.data = fontdata_pearl8x8,
.pref = 2,
};
| gpl-2.0 |
fabiant7t/qmk_firmware | keyboards/handwired/selene/keymaps/bpendragon/keymap.c | 98 | 1930 | /* Copyright 2020 Bpendragon
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include QMK_KEYBOARD_H
enum custom_keycodes {
DBL_0 = SAFE_RANGE,
};
bool process_record_user(uint16_t keycode, keyrecord_t *record) {
switch (keycode) {
case DBL_0:
if(record->event.pressed) {
SEND_STRING("00");
}
break;
}
return true;
};
const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = {
[0] = LAYOUT (
KC_ESC, KC_F1, KC_F2, KC_F3, KC_F4, KC_F5, KC_F6, KC_F7, KC_F8, KC_F9, KC_F10, KC_F11, KC_F12, KC_PSCR, KC_SLCK, KC_PAUS, KC_MUTE, KC_MPRV, KC_MNXT, KC_MPLY,
KC_GRV, KC_1, KC_2, KC_3, KC_4, KC_5, KC_6, KC_7, KC_8, KC_9, KC_0, KC_MINS, KC_EQL, KC_BSPC, KC_INS, KC_HOME, KC_PGUP, KC_NLCK, KC_PSLS, KC_PAST, KC_PMNS,
KC_TAB, KC_Q, KC_W, KC_E, KC_R, KC_T, KC_Y, KC_U, KC_I, KC_O, KC_P, KC_LBRC, KC_RBRC, KC_BSLS, KC_DEL, KC_END, KC_PGDN, KC_P7, KC_P8, KC_P9, KC_PPLS,
KC_CAPS, KC_A, KC_S, KC_D, KC_F, KC_G, KC_H, KC_J, KC_K, KC_L, KC_SCLN, KC_QUOT, KC_ENT, KC_P4, KC_P5, KC_P6,
KC_LSFT, KC_Z, KC_X, KC_C, KC_V, KC_B, KC_N, KC_M, KC_COMM, KC_DOT, KC_SLSH, KC_RSFT, KC_UP, KC_P1, KC_P2, KC_P3, KC_PENT,
KC_LCTL, KC_LGUI, KC_LALT, KC_SPC, KC_RALT, KC_RGUI, KC_APP, KC_RCTL, KC_LEFT, KC_DOWN, KC_RGHT, KC_P0, DBL_0, KC_PDOT
)
};
| gpl-2.0 |
j1nx/Amlogic-reff16-kernel | drivers/hwmon/adm1031.c | 98 | 32379 | /*
adm1031.c - Part of lm_sensors, Linux kernel modules for hardware
monitoring
Based on lm75.c and lm85.c
Supports adm1030 / adm1031
Copyright (C) 2004 Alexandre d'Alton <alex@alexdalton.org>
Reworked by Jean Delvare <khali@linux-fr.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/i2c.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/err.h>
#include <linux/mutex.h>
/* Following macros takes channel parameter starting from 0 to 2 */
#define ADM1031_REG_FAN_SPEED(nr) (0x08 + (nr))
#define ADM1031_REG_FAN_DIV(nr) (0x20 + (nr))
#define ADM1031_REG_PWM (0x22)
#define ADM1031_REG_FAN_MIN(nr) (0x10 + (nr))
#define ADM1031_REG_TEMP_OFFSET(nr) (0x0d + (nr))
#define ADM1031_REG_TEMP_MAX(nr) (0x14 + 4 * (nr))
#define ADM1031_REG_TEMP_MIN(nr) (0x15 + 4 * (nr))
#define ADM1031_REG_TEMP_CRIT(nr) (0x16 + 4 * (nr))
#define ADM1031_REG_TEMP(nr) (0x0a + (nr))
#define ADM1031_REG_AUTO_TEMP(nr) (0x24 + (nr))
#define ADM1031_REG_STATUS(nr) (0x2 + (nr))
#define ADM1031_REG_CONF1 0x00
#define ADM1031_REG_CONF2 0x01
#define ADM1031_REG_EXT_TEMP 0x06
#define ADM1031_CONF1_MONITOR_ENABLE 0x01 /* Monitoring enable */
#define ADM1031_CONF1_PWM_INVERT 0x08 /* PWM Invert */
#define ADM1031_CONF1_AUTO_MODE 0x80 /* Auto FAN */
#define ADM1031_CONF2_PWM1_ENABLE 0x01
#define ADM1031_CONF2_PWM2_ENABLE 0x02
#define ADM1031_CONF2_TACH1_ENABLE 0x04
#define ADM1031_CONF2_TACH2_ENABLE 0x08
#define ADM1031_CONF2_TEMP_ENABLE(chan) (0x10 << (chan))
/* Addresses to scan */
static const unsigned short normal_i2c[] = { 0x2c, 0x2d, 0x2e, I2C_CLIENT_END };
enum chips { adm1030, adm1031 };
typedef u8 auto_chan_table_t[8][2];
/* Each client has this additional data */
struct adm1031_data {
struct device *hwmon_dev;
struct mutex update_lock;
int chip_type;
char valid; /* !=0 if following fields are valid */
unsigned long last_updated; /* In jiffies */
/* The chan_select_table contains the possible configurations for
* auto fan control.
*/
const auto_chan_table_t *chan_select_table;
u16 alarm;
u8 conf1;
u8 conf2;
u8 fan[2];
u8 fan_div[2];
u8 fan_min[2];
u8 pwm[2];
u8 old_pwm[2];
s8 temp[3];
u8 ext_temp[3];
u8 auto_temp[3];
u8 auto_temp_min[3];
u8 auto_temp_off[3];
u8 auto_temp_max[3];
s8 temp_offset[3];
s8 temp_min[3];
s8 temp_max[3];
s8 temp_crit[3];
};
static int adm1031_probe(struct i2c_client *client,
const struct i2c_device_id *id);
static int adm1031_detect(struct i2c_client *client,
struct i2c_board_info *info);
static void adm1031_init_client(struct i2c_client *client);
static int adm1031_remove(struct i2c_client *client);
static struct adm1031_data *adm1031_update_device(struct device *dev);
static const struct i2c_device_id adm1031_id[] = {
{ "adm1030", adm1030 },
{ "adm1031", adm1031 },
{ }
};
MODULE_DEVICE_TABLE(i2c, adm1031_id);
/* This is the driver that will be inserted */
static struct i2c_driver adm1031_driver = {
.class = I2C_CLASS_HWMON,
.driver = {
.name = "adm1031",
},
.probe = adm1031_probe,
.remove = adm1031_remove,
.id_table = adm1031_id,
.detect = adm1031_detect,
.address_list = normal_i2c,
};
static inline u8 adm1031_read_value(struct i2c_client *client, u8 reg)
{
return i2c_smbus_read_byte_data(client, reg);
}
static inline int
adm1031_write_value(struct i2c_client *client, u8 reg, unsigned int value)
{
return i2c_smbus_write_byte_data(client, reg, value);
}
#define TEMP_TO_REG(val) (((val) < 0 ? ((val - 500) / 1000) : \
((val + 500) / 1000)))
#define TEMP_FROM_REG(val) ((val) * 1000)
#define TEMP_FROM_REG_EXT(val, ext) (TEMP_FROM_REG(val) + (ext) * 125)
#define TEMP_OFFSET_TO_REG(val) (TEMP_TO_REG(val) & 0x8f)
#define TEMP_OFFSET_FROM_REG(val) TEMP_FROM_REG((val) < 0 ? \
(val) | 0x70 : (val))
#define FAN_FROM_REG(reg, div) ((reg) ? (11250 * 60) / ((reg) * (div)) : 0)
static int FAN_TO_REG(int reg, int div)
{
int tmp;
tmp = FAN_FROM_REG(SENSORS_LIMIT(reg, 0, 65535), div);
return tmp > 255 ? 255 : tmp;
}
#define FAN_DIV_FROM_REG(reg) (1<<(((reg)&0xc0)>>6))
#define PWM_TO_REG(val) (SENSORS_LIMIT((val), 0, 255) >> 4)
#define PWM_FROM_REG(val) ((val) << 4)
#define FAN_CHAN_FROM_REG(reg) (((reg) >> 5) & 7)
#define FAN_CHAN_TO_REG(val, reg) \
(((reg) & 0x1F) | (((val) << 5) & 0xe0))
#define AUTO_TEMP_MIN_TO_REG(val, reg) \
((((val)/500) & 0xf8)|((reg) & 0x7))
#define AUTO_TEMP_RANGE_FROM_REG(reg) (5000 * (1<< ((reg)&0x7)))
#define AUTO_TEMP_MIN_FROM_REG(reg) (1000 * ((((reg) >> 3) & 0x1f) << 2))
#define AUTO_TEMP_MIN_FROM_REG_DEG(reg) ((((reg) >> 3) & 0x1f) << 2)
#define AUTO_TEMP_OFF_FROM_REG(reg) \
(AUTO_TEMP_MIN_FROM_REG(reg) - 5000)
#define AUTO_TEMP_MAX_FROM_REG(reg) \
(AUTO_TEMP_RANGE_FROM_REG(reg) + \
AUTO_TEMP_MIN_FROM_REG(reg))
static int AUTO_TEMP_MAX_TO_REG(int val, int reg, int pwm)
{
int ret;
int range = val - AUTO_TEMP_MIN_FROM_REG(reg);
range = ((val - AUTO_TEMP_MIN_FROM_REG(reg))*10)/(16 - pwm);
ret = ((reg & 0xf8) |
(range < 10000 ? 0 :
range < 20000 ? 1 :
range < 40000 ? 2 : range < 80000 ? 3 : 4));
return ret;
}
/* FAN auto control */
#define GET_FAN_AUTO_BITFIELD(data, idx) \
(*(data)->chan_select_table)[FAN_CHAN_FROM_REG((data)->conf1)][idx%2]
/* The tables below contains the possible values for the auto fan
* control bitfields. the index in the table is the register value.
* MSb is the auto fan control enable bit, so the four first entries
* in the table disables auto fan control when both bitfields are zero.
*/
static const auto_chan_table_t auto_channel_select_table_adm1031 = {
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 },
{ 2 /* 0b010 */ , 4 /* 0b100 */ },
{ 2 /* 0b010 */ , 2 /* 0b010 */ },
{ 4 /* 0b100 */ , 4 /* 0b100 */ },
{ 7 /* 0b111 */ , 7 /* 0b111 */ },
};
static const auto_chan_table_t auto_channel_select_table_adm1030 = {
{ 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 },
{ 2 /* 0b10 */ , 0 },
{ 0xff /* invalid */ , 0 },
{ 0xff /* invalid */ , 0 },
{ 3 /* 0b11 */ , 0 },
};
/* That function checks if a bitfield is valid and returns the other bitfield
* nearest match if no exact match where found.
*/
static int
get_fan_auto_nearest(struct adm1031_data *data,
int chan, u8 val, u8 reg, u8 * new_reg)
{
int i;
int first_match = -1, exact_match = -1;
u8 other_reg_val =
(*data->chan_select_table)[FAN_CHAN_FROM_REG(reg)][chan ? 0 : 1];
if (val == 0) {
*new_reg = 0;
return 0;
}
for (i = 0; i < 8; i++) {
if ((val == (*data->chan_select_table)[i][chan]) &&
((*data->chan_select_table)[i][chan ? 0 : 1] ==
other_reg_val)) {
/* We found an exact match */
exact_match = i;
break;
} else if (val == (*data->chan_select_table)[i][chan] &&
first_match == -1) {
/* Save the first match in case of an exact match has
* not been found
*/
first_match = i;
}
}
if (exact_match >= 0) {
*new_reg = exact_match;
} else if (first_match >= 0) {
*new_reg = first_match;
} else {
return -EINVAL;
}
return 0;
}
static ssize_t show_fan_auto_channel(struct device *dev,
struct device_attribute *attr, char *buf)
{
int nr = to_sensor_dev_attr(attr)->index;
struct adm1031_data *data = adm1031_update_device(dev);
return sprintf(buf, "%d\n", GET_FAN_AUTO_BITFIELD(data, nr));
}
static ssize_t
set_fan_auto_channel(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct adm1031_data *data = i2c_get_clientdata(client);
int nr = to_sensor_dev_attr(attr)->index;
int val = simple_strtol(buf, NULL, 10);
u8 reg;
int ret;
u8 old_fan_mode;
old_fan_mode = data->conf1;
mutex_lock(&data->update_lock);
if ((ret = get_fan_auto_nearest(data, nr, val, data->conf1, ®))) {
mutex_unlock(&data->update_lock);
return ret;
}
data->conf1 = FAN_CHAN_TO_REG(reg, data->conf1);
if ((data->conf1 & ADM1031_CONF1_AUTO_MODE) ^
(old_fan_mode & ADM1031_CONF1_AUTO_MODE)) {
if (data->conf1 & ADM1031_CONF1_AUTO_MODE){
/* Switch to Auto Fan Mode
* Save PWM registers
* Set PWM registers to 33% Both */
data->old_pwm[0] = data->pwm[0];
data->old_pwm[1] = data->pwm[1];
adm1031_write_value(client, ADM1031_REG_PWM, 0x55);
} else {
/* Switch to Manual Mode */
data->pwm[0] = data->old_pwm[0];
data->pwm[1] = data->old_pwm[1];
/* Restore PWM registers */
adm1031_write_value(client, ADM1031_REG_PWM,
data->pwm[0] | (data->pwm[1] << 4));
}
}
data->conf1 = FAN_CHAN_TO_REG(reg, data->conf1);
adm1031_write_value(client, ADM1031_REG_CONF1, data->conf1);
mutex_unlock(&data->update_lock);
return count;
}
static SENSOR_DEVICE_ATTR(auto_fan1_channel, S_IRUGO | S_IWUSR,
show_fan_auto_channel, set_fan_auto_channel, 0);
static SENSOR_DEVICE_ATTR(auto_fan2_channel, S_IRUGO | S_IWUSR,
show_fan_auto_channel, set_fan_auto_channel, 1);
/* Auto Temps */
static ssize_t show_auto_temp_off(struct device *dev,
struct device_attribute *attr, char *buf)
{
int nr = to_sensor_dev_attr(attr)->index;
struct adm1031_data *data = adm1031_update_device(dev);
return sprintf(buf, "%d\n",
AUTO_TEMP_OFF_FROM_REG(data->auto_temp[nr]));
}
static ssize_t show_auto_temp_min(struct device *dev,
struct device_attribute *attr, char *buf)
{
int nr = to_sensor_dev_attr(attr)->index;
struct adm1031_data *data = adm1031_update_device(dev);
return sprintf(buf, "%d\n",
AUTO_TEMP_MIN_FROM_REG(data->auto_temp[nr]));
}
static ssize_t
set_auto_temp_min(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct adm1031_data *data = i2c_get_clientdata(client);
int nr = to_sensor_dev_attr(attr)->index;
int val = simple_strtol(buf, NULL, 10);
mutex_lock(&data->update_lock);
data->auto_temp[nr] = AUTO_TEMP_MIN_TO_REG(val, data->auto_temp[nr]);
adm1031_write_value(client, ADM1031_REG_AUTO_TEMP(nr),
data->auto_temp[nr]);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_auto_temp_max(struct device *dev,
struct device_attribute *attr, char *buf)
{
int nr = to_sensor_dev_attr(attr)->index;
struct adm1031_data *data = adm1031_update_device(dev);
return sprintf(buf, "%d\n",
AUTO_TEMP_MAX_FROM_REG(data->auto_temp[nr]));
}
static ssize_t
set_auto_temp_max(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct adm1031_data *data = i2c_get_clientdata(client);
int nr = to_sensor_dev_attr(attr)->index;
int val = simple_strtol(buf, NULL, 10);
mutex_lock(&data->update_lock);
data->temp_max[nr] = AUTO_TEMP_MAX_TO_REG(val, data->auto_temp[nr], data->pwm[nr]);
adm1031_write_value(client, ADM1031_REG_AUTO_TEMP(nr),
data->temp_max[nr]);
mutex_unlock(&data->update_lock);
return count;
}
#define auto_temp_reg(offset) \
static SENSOR_DEVICE_ATTR(auto_temp##offset##_off, S_IRUGO, \
show_auto_temp_off, NULL, offset - 1); \
static SENSOR_DEVICE_ATTR(auto_temp##offset##_min, S_IRUGO | S_IWUSR, \
show_auto_temp_min, set_auto_temp_min, offset - 1); \
static SENSOR_DEVICE_ATTR(auto_temp##offset##_max, S_IRUGO | S_IWUSR, \
show_auto_temp_max, set_auto_temp_max, offset - 1)
auto_temp_reg(1);
auto_temp_reg(2);
auto_temp_reg(3);
/* pwm */
static ssize_t show_pwm(struct device *dev,
struct device_attribute *attr, char *buf)
{
int nr = to_sensor_dev_attr(attr)->index;
struct adm1031_data *data = adm1031_update_device(dev);
return sprintf(buf, "%d\n", PWM_FROM_REG(data->pwm[nr]));
}
static ssize_t set_pwm(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct adm1031_data *data = i2c_get_clientdata(client);
int nr = to_sensor_dev_attr(attr)->index;
int val = simple_strtol(buf, NULL, 10);
int reg;
mutex_lock(&data->update_lock);
if ((data->conf1 & ADM1031_CONF1_AUTO_MODE) &&
(((val>>4) & 0xf) != 5)) {
/* In automatic mode, the only PWM accepted is 33% */
mutex_unlock(&data->update_lock);
return -EINVAL;
}
data->pwm[nr] = PWM_TO_REG(val);
reg = adm1031_read_value(client, ADM1031_REG_PWM);
adm1031_write_value(client, ADM1031_REG_PWM,
nr ? ((data->pwm[nr] << 4) & 0xf0) | (reg & 0xf)
: (data->pwm[nr] & 0xf) | (reg & 0xf0));
mutex_unlock(&data->update_lock);
return count;
}
static SENSOR_DEVICE_ATTR(pwm1, S_IRUGO | S_IWUSR, show_pwm, set_pwm, 0);
static SENSOR_DEVICE_ATTR(pwm2, S_IRUGO | S_IWUSR, show_pwm, set_pwm, 1);
static SENSOR_DEVICE_ATTR(auto_fan1_min_pwm, S_IRUGO | S_IWUSR,
show_pwm, set_pwm, 0);
static SENSOR_DEVICE_ATTR(auto_fan2_min_pwm, S_IRUGO | S_IWUSR,
show_pwm, set_pwm, 1);
/* Fans */
/*
* That function checks the cases where the fan reading is not
* relevant. It is used to provide 0 as fan reading when the fan is
* not supposed to run
*/
static int trust_fan_readings(struct adm1031_data *data, int chan)
{
int res = 0;
if (data->conf1 & ADM1031_CONF1_AUTO_MODE) {
switch (data->conf1 & 0x60) {
case 0x00: /* remote temp1 controls fan1 remote temp2 controls fan2 */
res = data->temp[chan+1] >=
AUTO_TEMP_MIN_FROM_REG_DEG(data->auto_temp[chan+1]);
break;
case 0x20: /* remote temp1 controls both fans */
res =
data->temp[1] >=
AUTO_TEMP_MIN_FROM_REG_DEG(data->auto_temp[1]);
break;
case 0x40: /* remote temp2 controls both fans */
res =
data->temp[2] >=
AUTO_TEMP_MIN_FROM_REG_DEG(data->auto_temp[2]);
break;
case 0x60: /* max controls both fans */
res =
data->temp[0] >=
AUTO_TEMP_MIN_FROM_REG_DEG(data->auto_temp[0])
|| data->temp[1] >=
AUTO_TEMP_MIN_FROM_REG_DEG(data->auto_temp[1])
|| (data->chip_type == adm1031
&& data->temp[2] >=
AUTO_TEMP_MIN_FROM_REG_DEG(data->auto_temp[2]));
break;
}
} else {
res = data->pwm[chan] > 0;
}
return res;
}
static ssize_t show_fan(struct device *dev,
struct device_attribute *attr, char *buf)
{
int nr = to_sensor_dev_attr(attr)->index;
struct adm1031_data *data = adm1031_update_device(dev);
int value;
value = trust_fan_readings(data, nr) ? FAN_FROM_REG(data->fan[nr],
FAN_DIV_FROM_REG(data->fan_div[nr])) : 0;
return sprintf(buf, "%d\n", value);
}
static ssize_t show_fan_div(struct device *dev,
struct device_attribute *attr, char *buf)
{
int nr = to_sensor_dev_attr(attr)->index;
struct adm1031_data *data = adm1031_update_device(dev);
return sprintf(buf, "%d\n", FAN_DIV_FROM_REG(data->fan_div[nr]));
}
static ssize_t show_fan_min(struct device *dev,
struct device_attribute *attr, char *buf)
{
int nr = to_sensor_dev_attr(attr)->index;
struct adm1031_data *data = adm1031_update_device(dev);
return sprintf(buf, "%d\n",
FAN_FROM_REG(data->fan_min[nr],
FAN_DIV_FROM_REG(data->fan_div[nr])));
}
static ssize_t set_fan_min(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct adm1031_data *data = i2c_get_clientdata(client);
int nr = to_sensor_dev_attr(attr)->index;
int val = simple_strtol(buf, NULL, 10);
mutex_lock(&data->update_lock);
if (val) {
data->fan_min[nr] =
FAN_TO_REG(val, FAN_DIV_FROM_REG(data->fan_div[nr]));
} else {
data->fan_min[nr] = 0xff;
}
adm1031_write_value(client, ADM1031_REG_FAN_MIN(nr), data->fan_min[nr]);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t set_fan_div(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct adm1031_data *data = i2c_get_clientdata(client);
int nr = to_sensor_dev_attr(attr)->index;
int val = simple_strtol(buf, NULL, 10);
u8 tmp;
int old_div;
int new_min;
tmp = val == 8 ? 0xc0 :
val == 4 ? 0x80 :
val == 2 ? 0x40 :
val == 1 ? 0x00 :
0xff;
if (tmp == 0xff)
return -EINVAL;
mutex_lock(&data->update_lock);
/* Get fresh readings */
data->fan_div[nr] = adm1031_read_value(client,
ADM1031_REG_FAN_DIV(nr));
data->fan_min[nr] = adm1031_read_value(client,
ADM1031_REG_FAN_MIN(nr));
/* Write the new clock divider and fan min */
old_div = FAN_DIV_FROM_REG(data->fan_div[nr]);
data->fan_div[nr] = tmp | (0x3f & data->fan_div[nr]);
new_min = data->fan_min[nr] * old_div / val;
data->fan_min[nr] = new_min > 0xff ? 0xff : new_min;
adm1031_write_value(client, ADM1031_REG_FAN_DIV(nr),
data->fan_div[nr]);
adm1031_write_value(client, ADM1031_REG_FAN_MIN(nr),
data->fan_min[nr]);
/* Invalidate the cache: fan speed is no longer valid */
data->valid = 0;
mutex_unlock(&data->update_lock);
return count;
}
#define fan_offset(offset) \
static SENSOR_DEVICE_ATTR(fan##offset##_input, S_IRUGO, \
show_fan, NULL, offset - 1); \
static SENSOR_DEVICE_ATTR(fan##offset##_min, S_IRUGO | S_IWUSR, \
show_fan_min, set_fan_min, offset - 1); \
static SENSOR_DEVICE_ATTR(fan##offset##_div, S_IRUGO | S_IWUSR, \
show_fan_div, set_fan_div, offset - 1)
fan_offset(1);
fan_offset(2);
/* Temps */
static ssize_t show_temp(struct device *dev,
struct device_attribute *attr, char *buf)
{
int nr = to_sensor_dev_attr(attr)->index;
struct adm1031_data *data = adm1031_update_device(dev);
int ext;
ext = nr == 0 ?
((data->ext_temp[nr] >> 6) & 0x3) * 2 :
(((data->ext_temp[nr] >> ((nr - 1) * 3)) & 7));
return sprintf(buf, "%d\n", TEMP_FROM_REG_EXT(data->temp[nr], ext));
}
static ssize_t show_temp_offset(struct device *dev,
struct device_attribute *attr, char *buf)
{
int nr = to_sensor_dev_attr(attr)->index;
struct adm1031_data *data = adm1031_update_device(dev);
return sprintf(buf, "%d\n",
TEMP_OFFSET_FROM_REG(data->temp_offset[nr]));
}
static ssize_t show_temp_min(struct device *dev,
struct device_attribute *attr, char *buf)
{
int nr = to_sensor_dev_attr(attr)->index;
struct adm1031_data *data = adm1031_update_device(dev);
return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp_min[nr]));
}
static ssize_t show_temp_max(struct device *dev,
struct device_attribute *attr, char *buf)
{
int nr = to_sensor_dev_attr(attr)->index;
struct adm1031_data *data = adm1031_update_device(dev);
return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp_max[nr]));
}
static ssize_t show_temp_crit(struct device *dev,
struct device_attribute *attr, char *buf)
{
int nr = to_sensor_dev_attr(attr)->index;
struct adm1031_data *data = adm1031_update_device(dev);
return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp_crit[nr]));
}
static ssize_t set_temp_offset(struct device *dev,
struct device_attribute *attr, const char *buf,
size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct adm1031_data *data = i2c_get_clientdata(client);
int nr = to_sensor_dev_attr(attr)->index;
int val;
val = simple_strtol(buf, NULL, 10);
val = SENSORS_LIMIT(val, -15000, 15000);
mutex_lock(&data->update_lock);
data->temp_offset[nr] = TEMP_OFFSET_TO_REG(val);
adm1031_write_value(client, ADM1031_REG_TEMP_OFFSET(nr),
data->temp_offset[nr]);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t set_temp_min(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct adm1031_data *data = i2c_get_clientdata(client);
int nr = to_sensor_dev_attr(attr)->index;
int val;
val = simple_strtol(buf, NULL, 10);
val = SENSORS_LIMIT(val, -55000, nr == 0 ? 127750 : 127875);
mutex_lock(&data->update_lock);
data->temp_min[nr] = TEMP_TO_REG(val);
adm1031_write_value(client, ADM1031_REG_TEMP_MIN(nr),
data->temp_min[nr]);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t set_temp_max(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct adm1031_data *data = i2c_get_clientdata(client);
int nr = to_sensor_dev_attr(attr)->index;
int val;
val = simple_strtol(buf, NULL, 10);
val = SENSORS_LIMIT(val, -55000, nr == 0 ? 127750 : 127875);
mutex_lock(&data->update_lock);
data->temp_max[nr] = TEMP_TO_REG(val);
adm1031_write_value(client, ADM1031_REG_TEMP_MAX(nr),
data->temp_max[nr]);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t set_temp_crit(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct adm1031_data *data = i2c_get_clientdata(client);
int nr = to_sensor_dev_attr(attr)->index;
int val;
val = simple_strtol(buf, NULL, 10);
val = SENSORS_LIMIT(val, -55000, nr == 0 ? 127750 : 127875);
mutex_lock(&data->update_lock);
data->temp_crit[nr] = TEMP_TO_REG(val);
adm1031_write_value(client, ADM1031_REG_TEMP_CRIT(nr),
data->temp_crit[nr]);
mutex_unlock(&data->update_lock);
return count;
}
#define temp_reg(offset) \
static SENSOR_DEVICE_ATTR(temp##offset##_input, S_IRUGO, \
show_temp, NULL, offset - 1); \
static SENSOR_DEVICE_ATTR(temp##offset##_offset, S_IRUGO | S_IWUSR, \
show_temp_offset, set_temp_offset, offset - 1); \
static SENSOR_DEVICE_ATTR(temp##offset##_min, S_IRUGO | S_IWUSR, \
show_temp_min, set_temp_min, offset - 1); \
static SENSOR_DEVICE_ATTR(temp##offset##_max, S_IRUGO | S_IWUSR, \
show_temp_max, set_temp_max, offset - 1); \
static SENSOR_DEVICE_ATTR(temp##offset##_crit, S_IRUGO | S_IWUSR, \
show_temp_crit, set_temp_crit, offset - 1)
temp_reg(1);
temp_reg(2);
temp_reg(3);
/* Alarms */
static ssize_t show_alarms(struct device *dev, struct device_attribute *attr, char *buf)
{
struct adm1031_data *data = adm1031_update_device(dev);
return sprintf(buf, "%d\n", data->alarm);
}
static DEVICE_ATTR(alarms, S_IRUGO, show_alarms, NULL);
static ssize_t show_alarm(struct device *dev,
struct device_attribute *attr, char *buf)
{
int bitnr = to_sensor_dev_attr(attr)->index;
struct adm1031_data *data = adm1031_update_device(dev);
return sprintf(buf, "%d\n", (data->alarm >> bitnr) & 1);
}
static SENSOR_DEVICE_ATTR(fan1_alarm, S_IRUGO, show_alarm, NULL, 0);
static SENSOR_DEVICE_ATTR(fan1_fault, S_IRUGO, show_alarm, NULL, 1);
static SENSOR_DEVICE_ATTR(temp2_max_alarm, S_IRUGO, show_alarm, NULL, 2);
static SENSOR_DEVICE_ATTR(temp2_min_alarm, S_IRUGO, show_alarm, NULL, 3);
static SENSOR_DEVICE_ATTR(temp2_crit_alarm, S_IRUGO, show_alarm, NULL, 4);
static SENSOR_DEVICE_ATTR(temp2_fault, S_IRUGO, show_alarm, NULL, 5);
static SENSOR_DEVICE_ATTR(temp1_max_alarm, S_IRUGO, show_alarm, NULL, 6);
static SENSOR_DEVICE_ATTR(temp1_min_alarm, S_IRUGO, show_alarm, NULL, 7);
static SENSOR_DEVICE_ATTR(fan2_alarm, S_IRUGO, show_alarm, NULL, 8);
static SENSOR_DEVICE_ATTR(fan2_fault, S_IRUGO, show_alarm, NULL, 9);
static SENSOR_DEVICE_ATTR(temp3_max_alarm, S_IRUGO, show_alarm, NULL, 10);
static SENSOR_DEVICE_ATTR(temp3_min_alarm, S_IRUGO, show_alarm, NULL, 11);
static SENSOR_DEVICE_ATTR(temp3_crit_alarm, S_IRUGO, show_alarm, NULL, 12);
static SENSOR_DEVICE_ATTR(temp3_fault, S_IRUGO, show_alarm, NULL, 13);
static SENSOR_DEVICE_ATTR(temp1_crit_alarm, S_IRUGO, show_alarm, NULL, 14);
static struct attribute *adm1031_attributes[] = {
&sensor_dev_attr_fan1_input.dev_attr.attr,
&sensor_dev_attr_fan1_div.dev_attr.attr,
&sensor_dev_attr_fan1_min.dev_attr.attr,
&sensor_dev_attr_fan1_alarm.dev_attr.attr,
&sensor_dev_attr_fan1_fault.dev_attr.attr,
&sensor_dev_attr_pwm1.dev_attr.attr,
&sensor_dev_attr_auto_fan1_channel.dev_attr.attr,
&sensor_dev_attr_temp1_input.dev_attr.attr,
&sensor_dev_attr_temp1_offset.dev_attr.attr,
&sensor_dev_attr_temp1_min.dev_attr.attr,
&sensor_dev_attr_temp1_min_alarm.dev_attr.attr,
&sensor_dev_attr_temp1_max.dev_attr.attr,
&sensor_dev_attr_temp1_max_alarm.dev_attr.attr,
&sensor_dev_attr_temp1_crit.dev_attr.attr,
&sensor_dev_attr_temp1_crit_alarm.dev_attr.attr,
&sensor_dev_attr_temp2_input.dev_attr.attr,
&sensor_dev_attr_temp2_offset.dev_attr.attr,
&sensor_dev_attr_temp2_min.dev_attr.attr,
&sensor_dev_attr_temp2_min_alarm.dev_attr.attr,
&sensor_dev_attr_temp2_max.dev_attr.attr,
&sensor_dev_attr_temp2_max_alarm.dev_attr.attr,
&sensor_dev_attr_temp2_crit.dev_attr.attr,
&sensor_dev_attr_temp2_crit_alarm.dev_attr.attr,
&sensor_dev_attr_temp2_fault.dev_attr.attr,
&sensor_dev_attr_auto_temp1_off.dev_attr.attr,
&sensor_dev_attr_auto_temp1_min.dev_attr.attr,
&sensor_dev_attr_auto_temp1_max.dev_attr.attr,
&sensor_dev_attr_auto_temp2_off.dev_attr.attr,
&sensor_dev_attr_auto_temp2_min.dev_attr.attr,
&sensor_dev_attr_auto_temp2_max.dev_attr.attr,
&sensor_dev_attr_auto_fan1_min_pwm.dev_attr.attr,
&dev_attr_alarms.attr,
NULL
};
static const struct attribute_group adm1031_group = {
.attrs = adm1031_attributes,
};
static struct attribute *adm1031_attributes_opt[] = {
&sensor_dev_attr_fan2_input.dev_attr.attr,
&sensor_dev_attr_fan2_div.dev_attr.attr,
&sensor_dev_attr_fan2_min.dev_attr.attr,
&sensor_dev_attr_fan2_alarm.dev_attr.attr,
&sensor_dev_attr_fan2_fault.dev_attr.attr,
&sensor_dev_attr_pwm2.dev_attr.attr,
&sensor_dev_attr_auto_fan2_channel.dev_attr.attr,
&sensor_dev_attr_temp3_input.dev_attr.attr,
&sensor_dev_attr_temp3_offset.dev_attr.attr,
&sensor_dev_attr_temp3_min.dev_attr.attr,
&sensor_dev_attr_temp3_min_alarm.dev_attr.attr,
&sensor_dev_attr_temp3_max.dev_attr.attr,
&sensor_dev_attr_temp3_max_alarm.dev_attr.attr,
&sensor_dev_attr_temp3_crit.dev_attr.attr,
&sensor_dev_attr_temp3_crit_alarm.dev_attr.attr,
&sensor_dev_attr_temp3_fault.dev_attr.attr,
&sensor_dev_attr_auto_temp3_off.dev_attr.attr,
&sensor_dev_attr_auto_temp3_min.dev_attr.attr,
&sensor_dev_attr_auto_temp3_max.dev_attr.attr,
&sensor_dev_attr_auto_fan2_min_pwm.dev_attr.attr,
NULL
};
static const struct attribute_group adm1031_group_opt = {
.attrs = adm1031_attributes_opt,
};
/* Return 0 if detection is successful, -ENODEV otherwise */
static int adm1031_detect(struct i2c_client *client,
struct i2c_board_info *info)
{
struct i2c_adapter *adapter = client->adapter;
const char *name;
int id, co;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -ENODEV;
id = i2c_smbus_read_byte_data(client, 0x3d);
co = i2c_smbus_read_byte_data(client, 0x3e);
if (!((id == 0x31 || id == 0x30) && co == 0x41))
return -ENODEV;
name = (id == 0x30) ? "adm1030" : "adm1031";
strlcpy(info->type, name, I2C_NAME_SIZE);
return 0;
}
static int adm1031_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct adm1031_data *data;
int err;
data = kzalloc(sizeof(struct adm1031_data), GFP_KERNEL);
if (!data) {
err = -ENOMEM;
goto exit;
}
i2c_set_clientdata(client, data);
data->chip_type = id->driver_data;
mutex_init(&data->update_lock);
if (data->chip_type == adm1030)
data->chan_select_table = &auto_channel_select_table_adm1030;
else
data->chan_select_table = &auto_channel_select_table_adm1031;
/* Initialize the ADM1031 chip */
adm1031_init_client(client);
/* Register sysfs hooks */
if ((err = sysfs_create_group(&client->dev.kobj, &adm1031_group)))
goto exit_free;
if (data->chip_type == adm1031) {
if ((err = sysfs_create_group(&client->dev.kobj,
&adm1031_group_opt)))
goto exit_remove;
}
data->hwmon_dev = hwmon_device_register(&client->dev);
if (IS_ERR(data->hwmon_dev)) {
err = PTR_ERR(data->hwmon_dev);
goto exit_remove;
}
return 0;
exit_remove:
sysfs_remove_group(&client->dev.kobj, &adm1031_group);
sysfs_remove_group(&client->dev.kobj, &adm1031_group_opt);
exit_free:
kfree(data);
exit:
return err;
}
static int adm1031_remove(struct i2c_client *client)
{
struct adm1031_data *data = i2c_get_clientdata(client);
hwmon_device_unregister(data->hwmon_dev);
sysfs_remove_group(&client->dev.kobj, &adm1031_group);
sysfs_remove_group(&client->dev.kobj, &adm1031_group_opt);
kfree(data);
return 0;
}
static void adm1031_init_client(struct i2c_client *client)
{
unsigned int read_val;
unsigned int mask;
struct adm1031_data *data = i2c_get_clientdata(client);
mask = (ADM1031_CONF2_PWM1_ENABLE | ADM1031_CONF2_TACH1_ENABLE);
if (data->chip_type == adm1031) {
mask |= (ADM1031_CONF2_PWM2_ENABLE |
ADM1031_CONF2_TACH2_ENABLE);
}
/* Initialize the ADM1031 chip (enables fan speed reading ) */
read_val = adm1031_read_value(client, ADM1031_REG_CONF2);
if ((read_val | mask) != read_val) {
adm1031_write_value(client, ADM1031_REG_CONF2, read_val | mask);
}
read_val = adm1031_read_value(client, ADM1031_REG_CONF1);
if ((read_val | ADM1031_CONF1_MONITOR_ENABLE) != read_val) {
adm1031_write_value(client, ADM1031_REG_CONF1, read_val |
ADM1031_CONF1_MONITOR_ENABLE);
}
}
static struct adm1031_data *adm1031_update_device(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct adm1031_data *data = i2c_get_clientdata(client);
int chan;
mutex_lock(&data->update_lock);
if (time_after(jiffies, data->last_updated + HZ + HZ / 2)
|| !data->valid) {
dev_dbg(&client->dev, "Starting adm1031 update\n");
for (chan = 0;
chan < ((data->chip_type == adm1031) ? 3 : 2); chan++) {
u8 oldh, newh;
oldh =
adm1031_read_value(client, ADM1031_REG_TEMP(chan));
data->ext_temp[chan] =
adm1031_read_value(client, ADM1031_REG_EXT_TEMP);
newh =
adm1031_read_value(client, ADM1031_REG_TEMP(chan));
if (newh != oldh) {
data->ext_temp[chan] =
adm1031_read_value(client,
ADM1031_REG_EXT_TEMP);
#ifdef DEBUG
oldh =
adm1031_read_value(client,
ADM1031_REG_TEMP(chan));
/* oldh is actually newer */
if (newh != oldh)
dev_warn(&client->dev,
"Remote temperature may be "
"wrong.\n");
#endif
}
data->temp[chan] = newh;
data->temp_offset[chan] =
adm1031_read_value(client,
ADM1031_REG_TEMP_OFFSET(chan));
data->temp_min[chan] =
adm1031_read_value(client,
ADM1031_REG_TEMP_MIN(chan));
data->temp_max[chan] =
adm1031_read_value(client,
ADM1031_REG_TEMP_MAX(chan));
data->temp_crit[chan] =
adm1031_read_value(client,
ADM1031_REG_TEMP_CRIT(chan));
data->auto_temp[chan] =
adm1031_read_value(client,
ADM1031_REG_AUTO_TEMP(chan));
}
data->conf1 = adm1031_read_value(client, ADM1031_REG_CONF1);
data->conf2 = adm1031_read_value(client, ADM1031_REG_CONF2);
data->alarm = adm1031_read_value(client, ADM1031_REG_STATUS(0))
| (adm1031_read_value(client, ADM1031_REG_STATUS(1))
<< 8);
if (data->chip_type == adm1030) {
data->alarm &= 0xc0ff;
}
for (chan=0; chan<(data->chip_type == adm1030 ? 1 : 2); chan++) {
data->fan_div[chan] =
adm1031_read_value(client, ADM1031_REG_FAN_DIV(chan));
data->fan_min[chan] =
adm1031_read_value(client, ADM1031_REG_FAN_MIN(chan));
data->fan[chan] =
adm1031_read_value(client, ADM1031_REG_FAN_SPEED(chan));
data->pwm[chan] =
0xf & (adm1031_read_value(client, ADM1031_REG_PWM) >>
(4*chan));
}
data->last_updated = jiffies;
data->valid = 1;
}
mutex_unlock(&data->update_lock);
return data;
}
static int __init sensors_adm1031_init(void)
{
return i2c_add_driver(&adm1031_driver);
}
static void __exit sensors_adm1031_exit(void)
{
i2c_del_driver(&adm1031_driver);
}
MODULE_AUTHOR("Alexandre d'Alton <alex@alexdalton.org>");
MODULE_DESCRIPTION("ADM1031/ADM1030 driver");
MODULE_LICENSE("GPL");
module_init(sensors_adm1031_init);
module_exit(sensors_adm1031_exit);
| gpl-2.0 |
NeptunIDE/linux | drivers/usb/gadget/f_rndis.c | 98 | 24505 | /*
* f_rndis.c -- RNDIS link function driver
*
* 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/device.h>
#include <linux/etherdevice.h>
#include <asm/atomic.h>
#include "u_ether.h"
#include "rndis.h"
/*
* This function is an RNDIS Ethernet port -- a Microsoft protocol that's
* been promoted instead of the standard CDC Ethernet. The published RNDIS
* spec is ambiguous, incomplete, and needlessly complex. Variants such as
* ActiveSync have even worse status in terms of specification.
*
* In short: it's a protocol controlled by (and for) Microsoft, not for an
* Open ecosystem or markets. Linux supports it *only* because Microsoft
* doesn't support the CDC Ethernet standard.
*
* The RNDIS data transfer model is complex, with multiple Ethernet packets
* per USB message, and out of band data. The control model is built around
* what's essentially an "RNDIS RPC" protocol. It's all wrapped in a CDC ACM
* (modem, not Ethernet) veneer, with those ACM descriptors being entirely
* useless (they're ignored). RNDIS expects to be the only function in its
* configuration, so it's no real help if you need composite devices; and
* it expects to be the first configuration too.
*
* There is a single technical advantage of RNDIS over CDC Ethernet, if you
* discount the fluff that its RPC can be made to deliver: it doesn't need
* a NOP altsetting for the data interface. That lets it work on some of the
* "so smart it's stupid" hardware which takes over configuration changes
* from the software, and adds restrictions like "no altsettings".
*
* Unfortunately MSFT's RNDIS drivers are buggy. They hang or oops, and
* have all sorts of contrary-to-specification oddities that can prevent
* them from working sanely. Since bugfixes (or accurate specs, letting
* Linux work around those bugs) are unlikely to ever come from MSFT, you
* may want to avoid using RNDIS on purely operational grounds.
*
* Omissions from the RNDIS 1.0 specification include:
*
* - Power management ... references data that's scattered around lots
* of other documentation, which is incorrect/incomplete there too.
*
* - There are various undocumented protocol requirements, like the need
* to send garbage in some control-OUT messages.
*
* - MS-Windows drivers sometimes emit undocumented requests.
*/
struct rndis_ep_descs {
struct usb_endpoint_descriptor *in;
struct usb_endpoint_descriptor *out;
struct usb_endpoint_descriptor *notify;
};
struct f_rndis {
struct gether port;
u8 ctrl_id, data_id;
u8 ethaddr[ETH_ALEN];
int config;
struct rndis_ep_descs fs;
struct rndis_ep_descs hs;
struct usb_ep *notify;
struct usb_endpoint_descriptor *notify_desc;
struct usb_request *notify_req;
atomic_t notify_count;
};
static inline struct f_rndis *func_to_rndis(struct usb_function *f)
{
return container_of(f, struct f_rndis, port.func);
}
/* peak (theoretical) bulk transfer rate in bits-per-second */
static unsigned int bitrate(struct usb_gadget *g)
{
if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
return 13 * 512 * 8 * 1000 * 8;
else
return 19 * 64 * 1 * 1000 * 8;
}
/*-------------------------------------------------------------------------*/
/*
*/
#define LOG2_STATUS_INTERVAL_MSEC 5 /* 1 << 5 == 32 msec */
#define STATUS_BYTECOUNT 8 /* 8 bytes data */
/* interface descriptor: */
static struct usb_interface_descriptor rndis_control_intf __initdata = {
.bLength = sizeof rndis_control_intf,
.bDescriptorType = USB_DT_INTERFACE,
/* .bInterfaceNumber = DYNAMIC */
/* status endpoint is optional; this could be patched later */
.bNumEndpoints = 1,
.bInterfaceClass = USB_CLASS_COMM,
.bInterfaceSubClass = USB_CDC_SUBCLASS_ACM,
.bInterfaceProtocol = USB_CDC_ACM_PROTO_VENDOR,
/* .iInterface = DYNAMIC */
};
static struct usb_cdc_header_desc header_desc __initdata = {
.bLength = sizeof header_desc,
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_HEADER_TYPE,
.bcdCDC = cpu_to_le16(0x0110),
};
static struct usb_cdc_call_mgmt_descriptor call_mgmt_descriptor __initdata = {
.bLength = sizeof call_mgmt_descriptor,
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_CALL_MANAGEMENT_TYPE,
.bmCapabilities = 0x00,
.bDataInterface = 0x01,
};
static struct usb_cdc_acm_descriptor acm_descriptor __initdata = {
.bLength = sizeof acm_descriptor,
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_ACM_TYPE,
.bmCapabilities = 0x00,
};
static struct usb_cdc_union_desc rndis_union_desc __initdata = {
.bLength = sizeof(rndis_union_desc),
.bDescriptorType = USB_DT_CS_INTERFACE,
.bDescriptorSubType = USB_CDC_UNION_TYPE,
/* .bMasterInterface0 = DYNAMIC */
/* .bSlaveInterface0 = DYNAMIC */
};
/* the data interface has two bulk endpoints */
static struct usb_interface_descriptor rndis_data_intf __initdata = {
.bLength = sizeof rndis_data_intf,
.bDescriptorType = USB_DT_INTERFACE,
/* .bInterfaceNumber = DYNAMIC */
.bNumEndpoints = 2,
.bInterfaceClass = USB_CLASS_CDC_DATA,
.bInterfaceSubClass = 0,
.bInterfaceProtocol = 0,
/* .iInterface = DYNAMIC */
};
/* full speed support: */
static struct usb_endpoint_descriptor fs_notify_desc __initdata = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_INT,
.wMaxPacketSize = cpu_to_le16(STATUS_BYTECOUNT),
.bInterval = 1 << LOG2_STATUS_INTERVAL_MSEC,
};
static struct usb_endpoint_descriptor fs_in_desc __initdata = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
};
static struct usb_endpoint_descriptor fs_out_desc __initdata = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_OUT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
};
static struct usb_descriptor_header *eth_fs_function[] __initdata = {
/* control interface matches ACM, not Ethernet */
(struct usb_descriptor_header *) &rndis_control_intf,
(struct usb_descriptor_header *) &header_desc,
(struct usb_descriptor_header *) &call_mgmt_descriptor,
(struct usb_descriptor_header *) &acm_descriptor,
(struct usb_descriptor_header *) &rndis_union_desc,
(struct usb_descriptor_header *) &fs_notify_desc,
/* data interface has no altsetting */
(struct usb_descriptor_header *) &rndis_data_intf,
(struct usb_descriptor_header *) &fs_in_desc,
(struct usb_descriptor_header *) &fs_out_desc,
NULL,
};
/* high speed support: */
static struct usb_endpoint_descriptor hs_notify_desc __initdata = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_INT,
.wMaxPacketSize = cpu_to_le16(STATUS_BYTECOUNT),
.bInterval = LOG2_STATUS_INTERVAL_MSEC + 4,
};
static struct usb_endpoint_descriptor hs_in_desc __initdata = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_IN,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(512),
};
static struct usb_endpoint_descriptor hs_out_desc __initdata = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bEndpointAddress = USB_DIR_OUT,
.bmAttributes = USB_ENDPOINT_XFER_BULK,
.wMaxPacketSize = cpu_to_le16(512),
};
static struct usb_descriptor_header *eth_hs_function[] __initdata = {
/* control interface matches ACM, not Ethernet */
(struct usb_descriptor_header *) &rndis_control_intf,
(struct usb_descriptor_header *) &header_desc,
(struct usb_descriptor_header *) &call_mgmt_descriptor,
(struct usb_descriptor_header *) &acm_descriptor,
(struct usb_descriptor_header *) &rndis_union_desc,
(struct usb_descriptor_header *) &hs_notify_desc,
/* data interface has no altsetting */
(struct usb_descriptor_header *) &rndis_data_intf,
(struct usb_descriptor_header *) &hs_in_desc,
(struct usb_descriptor_header *) &hs_out_desc,
NULL,
};
/* string descriptors: */
static struct usb_string rndis_string_defs[] = {
[0].s = "RNDIS Communications Control",
[1].s = "RNDIS Ethernet Data",
{ } /* end of list */
};
static struct usb_gadget_strings rndis_string_table = {
.language = 0x0409, /* en-us */
.strings = rndis_string_defs,
};
static struct usb_gadget_strings *rndis_strings[] = {
&rndis_string_table,
NULL,
};
/*-------------------------------------------------------------------------*/
static struct sk_buff *rndis_add_header(struct gether *port,
struct sk_buff *skb)
{
struct sk_buff *skb2;
skb2 = skb_realloc_headroom(skb, sizeof(struct rndis_packet_msg_type));
if (skb2)
rndis_add_hdr(skb2);
dev_kfree_skb_any(skb);
return skb2;
}
static void rndis_response_available(void *_rndis)
{
struct f_rndis *rndis = _rndis;
struct usb_request *req = rndis->notify_req;
struct usb_composite_dev *cdev = rndis->port.func.config->cdev;
__le32 *data = req->buf;
int status;
if (atomic_inc_return(&rndis->notify_count) != 1)
return;
/* Send RNDIS RESPONSE_AVAILABLE notification; a
* USB_CDC_NOTIFY_RESPONSE_AVAILABLE "should" work too
*
* This is the only notification defined by RNDIS.
*/
data[0] = cpu_to_le32(1);
data[1] = cpu_to_le32(0);
status = usb_ep_queue(rndis->notify, req, GFP_ATOMIC);
if (status) {
atomic_dec(&rndis->notify_count);
DBG(cdev, "notify/0 --> %d\n", status);
}
}
static void rndis_response_complete(struct usb_ep *ep, struct usb_request *req)
{
struct f_rndis *rndis = req->context;
struct usb_composite_dev *cdev = rndis->port.func.config->cdev;
int status = req->status;
/* after TX:
* - USB_CDC_GET_ENCAPSULATED_RESPONSE (ep0/control)
* - RNDIS_RESPONSE_AVAILABLE (status/irq)
*/
switch (status) {
case -ECONNRESET:
case -ESHUTDOWN:
/* connection gone */
atomic_set(&rndis->notify_count, 0);
break;
default:
DBG(cdev, "RNDIS %s response error %d, %d/%d\n",
ep->name, status,
req->actual, req->length);
/* FALLTHROUGH */
case 0:
if (ep != rndis->notify)
break;
/* handle multiple pending RNDIS_RESPONSE_AVAILABLE
* notifications by resending until we're done
*/
if (atomic_dec_and_test(&rndis->notify_count))
break;
status = usb_ep_queue(rndis->notify, req, GFP_ATOMIC);
if (status) {
atomic_dec(&rndis->notify_count);
DBG(cdev, "notify/1 --> %d\n", status);
}
break;
}
}
static void rndis_command_complete(struct usb_ep *ep, struct usb_request *req)
{
struct f_rndis *rndis = req->context;
struct usb_composite_dev *cdev = rndis->port.func.config->cdev;
int status;
/* received RNDIS command from USB_CDC_SEND_ENCAPSULATED_COMMAND */
// spin_lock(&dev->lock);
status = rndis_msg_parser(rndis->config, (u8 *) req->buf);
if (status < 0)
ERROR(cdev, "RNDIS command error %d, %d/%d\n",
status, req->actual, req->length);
// spin_unlock(&dev->lock);
}
static int
rndis_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
{
struct f_rndis *rndis = func_to_rndis(f);
struct usb_composite_dev *cdev = f->config->cdev;
struct usb_request *req = cdev->req;
int value = -EOPNOTSUPP;
u16 w_index = le16_to_cpu(ctrl->wIndex);
u16 w_value = le16_to_cpu(ctrl->wValue);
u16 w_length = le16_to_cpu(ctrl->wLength);
/* composite driver infrastructure handles everything except
* CDC class messages; interface activation uses set_alt().
*/
switch ((ctrl->bRequestType << 8) | ctrl->bRequest) {
/* RNDIS uses the CDC command encapsulation mechanism to implement
* an RPC scheme, with much getting/setting of attributes by OID.
*/
case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
| USB_CDC_SEND_ENCAPSULATED_COMMAND:
if (w_length > req->length || w_value
|| w_index != rndis->ctrl_id)
goto invalid;
/* read the request; process it later */
value = w_length;
req->complete = rndis_command_complete;
req->context = rndis;
/* later, rndis_response_available() sends a notification */
break;
case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
| USB_CDC_GET_ENCAPSULATED_RESPONSE:
if (w_value || w_index != rndis->ctrl_id)
goto invalid;
else {
u8 *buf;
u32 n;
/* return the result */
buf = rndis_get_next_response(rndis->config, &n);
if (buf) {
memcpy(req->buf, buf, n);
req->complete = rndis_response_complete;
rndis_free_response(rndis->config, buf);
value = n;
}
/* else stalls ... spec says to avoid that */
}
break;
default:
invalid:
VDBG(cdev, "invalid control req%02x.%02x v%04x i%04x l%d\n",
ctrl->bRequestType, ctrl->bRequest,
w_value, w_index, w_length);
}
/* respond with data transfer or status phase? */
if (value >= 0) {
DBG(cdev, "rndis req%02x.%02x v%04x i%04x l%d\n",
ctrl->bRequestType, ctrl->bRequest,
w_value, w_index, w_length);
req->zero = (value < w_length);
req->length = value;
value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
if (value < 0)
ERROR(cdev, "rndis response on err %d\n", value);
}
/* device either stalls (value < 0) or reports success */
return value;
}
static int rndis_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
{
struct f_rndis *rndis = func_to_rndis(f);
struct usb_composite_dev *cdev = f->config->cdev;
/* we know alt == 0 */
if (intf == rndis->ctrl_id) {
if (rndis->notify->driver_data) {
VDBG(cdev, "reset rndis control %d\n", intf);
usb_ep_disable(rndis->notify);
} else {
VDBG(cdev, "init rndis ctrl %d\n", intf);
rndis->notify_desc = ep_choose(cdev->gadget,
rndis->hs.notify,
rndis->fs.notify);
}
usb_ep_enable(rndis->notify, rndis->notify_desc);
rndis->notify->driver_data = rndis;
} else if (intf == rndis->data_id) {
struct net_device *net;
if (rndis->port.in_ep->driver_data) {
DBG(cdev, "reset rndis\n");
gether_disconnect(&rndis->port);
}
if (!rndis->port.in) {
DBG(cdev, "init rndis\n");
rndis->port.in = ep_choose(cdev->gadget,
rndis->hs.in, rndis->fs.in);
rndis->port.out = ep_choose(cdev->gadget,
rndis->hs.out, rndis->fs.out);
}
/* Avoid ZLPs; they can be troublesome. */
rndis->port.is_zlp_ok = false;
/* RNDIS should be in the "RNDIS uninitialized" state,
* either never activated or after rndis_uninit().
*
* We don't want data to flow here until a nonzero packet
* filter is set, at which point it enters "RNDIS data
* initialized" state ... but we do want the endpoints
* to be activated. It's a strange little state.
*
* REVISIT the RNDIS gadget code has done this wrong for a
* very long time. We need another call to the link layer
* code -- gether_updown(...bool) maybe -- to do it right.
*/
rndis->port.cdc_filter = 0;
DBG(cdev, "RNDIS RX/TX early activation ... \n");
net = gether_connect(&rndis->port);
if (IS_ERR(net))
return PTR_ERR(net);
rndis_set_param_dev(rndis->config, net,
&rndis->port.cdc_filter);
} else
goto fail;
return 0;
fail:
return -EINVAL;
}
static void rndis_disable(struct usb_function *f)
{
struct f_rndis *rndis = func_to_rndis(f);
struct usb_composite_dev *cdev = f->config->cdev;
if (!rndis->notify->driver_data)
return;
DBG(cdev, "rndis deactivated\n");
rndis_uninit(rndis->config);
gether_disconnect(&rndis->port);
usb_ep_disable(rndis->notify);
rndis->notify->driver_data = NULL;
}
/*-------------------------------------------------------------------------*/
/*
* This isn't quite the same mechanism as CDC Ethernet, since the
* notification scheme passes less data, but the same set of link
* states must be tested. A key difference is that altsettings are
* not used to tell whether the link should send packets or not.
*/
static void rndis_open(struct gether *geth)
{
struct f_rndis *rndis = func_to_rndis(&geth->func);
struct usb_composite_dev *cdev = geth->func.config->cdev;
DBG(cdev, "%s\n", __func__);
rndis_set_param_medium(rndis->config, NDIS_MEDIUM_802_3,
bitrate(cdev->gadget) / 100);
rndis_signal_connect(rndis->config);
}
static void rndis_close(struct gether *geth)
{
struct f_rndis *rndis = func_to_rndis(&geth->func);
DBG(geth->func.config->cdev, "%s\n", __func__);
rndis_set_param_medium(rndis->config, NDIS_MEDIUM_802_3, 0);
rndis_signal_disconnect(rndis->config);
}
/*-------------------------------------------------------------------------*/
/* ethernet function driver setup/binding */
static int __init
rndis_bind(struct usb_configuration *c, struct usb_function *f)
{
struct usb_composite_dev *cdev = c->cdev;
struct f_rndis *rndis = func_to_rndis(f);
int status;
struct usb_ep *ep;
/* allocate instance-specific interface IDs */
status = usb_interface_id(c, f);
if (status < 0)
goto fail;
rndis->ctrl_id = status;
rndis_control_intf.bInterfaceNumber = status;
rndis_union_desc.bMasterInterface0 = status;
status = usb_interface_id(c, f);
if (status < 0)
goto fail;
rndis->data_id = status;
rndis_data_intf.bInterfaceNumber = status;
rndis_union_desc.bSlaveInterface0 = status;
status = -ENODEV;
/* allocate instance-specific endpoints */
ep = usb_ep_autoconfig(cdev->gadget, &fs_in_desc);
if (!ep)
goto fail;
rndis->port.in_ep = ep;
ep->driver_data = cdev; /* claim */
ep = usb_ep_autoconfig(cdev->gadget, &fs_out_desc);
if (!ep)
goto fail;
rndis->port.out_ep = ep;
ep->driver_data = cdev; /* claim */
/* NOTE: a status/notification endpoint is, strictly speaking,
* optional. We don't treat it that way though! It's simpler,
* and some newer profiles don't treat it as optional.
*/
ep = usb_ep_autoconfig(cdev->gadget, &fs_notify_desc);
if (!ep)
goto fail;
rndis->notify = ep;
ep->driver_data = cdev; /* claim */
status = -ENOMEM;
/* allocate notification request and buffer */
rndis->notify_req = usb_ep_alloc_request(ep, GFP_KERNEL);
if (!rndis->notify_req)
goto fail;
rndis->notify_req->buf = kmalloc(STATUS_BYTECOUNT, GFP_KERNEL);
if (!rndis->notify_req->buf)
goto fail;
rndis->notify_req->length = STATUS_BYTECOUNT;
rndis->notify_req->context = rndis;
rndis->notify_req->complete = rndis_response_complete;
/* copy descriptors, and track endpoint copies */
f->descriptors = usb_copy_descriptors(eth_fs_function);
if (!f->descriptors)
goto fail;
rndis->fs.in = usb_find_endpoint(eth_fs_function,
f->descriptors, &fs_in_desc);
rndis->fs.out = usb_find_endpoint(eth_fs_function,
f->descriptors, &fs_out_desc);
rndis->fs.notify = usb_find_endpoint(eth_fs_function,
f->descriptors, &fs_notify_desc);
/* support all relevant hardware speeds... we expect that when
* hardware is dual speed, all bulk-capable endpoints work at
* both speeds
*/
if (gadget_is_dualspeed(c->cdev->gadget)) {
hs_in_desc.bEndpointAddress =
fs_in_desc.bEndpointAddress;
hs_out_desc.bEndpointAddress =
fs_out_desc.bEndpointAddress;
hs_notify_desc.bEndpointAddress =
fs_notify_desc.bEndpointAddress;
/* copy descriptors, and track endpoint copies */
f->hs_descriptors = usb_copy_descriptors(eth_hs_function);
if (!f->hs_descriptors)
goto fail;
rndis->hs.in = usb_find_endpoint(eth_hs_function,
f->hs_descriptors, &hs_in_desc);
rndis->hs.out = usb_find_endpoint(eth_hs_function,
f->hs_descriptors, &hs_out_desc);
rndis->hs.notify = usb_find_endpoint(eth_hs_function,
f->hs_descriptors, &hs_notify_desc);
}
rndis->port.open = rndis_open;
rndis->port.close = rndis_close;
status = rndis_register(rndis_response_available, rndis);
if (status < 0)
goto fail;
rndis->config = status;
rndis_set_param_medium(rndis->config, NDIS_MEDIUM_802_3, 0);
rndis_set_host_mac(rndis->config, rndis->ethaddr);
#if 0
// FIXME
if (rndis_set_param_vendor(rndis->config, vendorID,
manufacturer))
goto fail0;
#endif
/* NOTE: all that is done without knowing or caring about
* the network link ... which is unavailable to this code
* until we're activated via set_alt().
*/
DBG(cdev, "RNDIS: %s speed IN/%s OUT/%s NOTIFY/%s\n",
gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full",
rndis->port.in_ep->name, rndis->port.out_ep->name,
rndis->notify->name);
return 0;
fail:
if (gadget_is_dualspeed(c->cdev->gadget) && f->hs_descriptors)
usb_free_descriptors(f->hs_descriptors);
if (f->descriptors)
usb_free_descriptors(f->descriptors);
if (rndis->notify_req) {
kfree(rndis->notify_req->buf);
usb_ep_free_request(rndis->notify, rndis->notify_req);
}
/* we might as well release our claims on endpoints */
if (rndis->notify)
rndis->notify->driver_data = NULL;
if (rndis->port.out)
rndis->port.out_ep->driver_data = NULL;
if (rndis->port.in)
rndis->port.in_ep->driver_data = NULL;
ERROR(cdev, "%s: can't bind, err %d\n", f->name, status);
return status;
}
static void
rndis_unbind(struct usb_configuration *c, struct usb_function *f)
{
struct f_rndis *rndis = func_to_rndis(f);
rndis_deregister(rndis->config);
rndis_exit();
if (gadget_is_dualspeed(c->cdev->gadget))
usb_free_descriptors(f->hs_descriptors);
usb_free_descriptors(f->descriptors);
kfree(rndis->notify_req->buf);
usb_ep_free_request(rndis->notify, rndis->notify_req);
kfree(rndis);
}
/* Some controllers can't support RNDIS ... */
static inline bool can_support_rndis(struct usb_configuration *c)
{
/* only two endpoints on sa1100 */
if (gadget_is_sa1100(c->cdev->gadget))
return false;
/* everything else is *presumably* fine */
return true;
}
/**
* rndis_bind_config - add RNDIS network link to a configuration
* @c: the configuration to support the network link
* @ethaddr: a buffer in which the ethernet address of the host side
* side of the link was recorded
* Context: single threaded during gadget setup
*
* Returns zero on success, else negative errno.
*
* Caller must have called @gether_setup(). Caller is also responsible
* for calling @gether_cleanup() before module unload.
*/
int __init rndis_bind_config(struct usb_configuration *c, u8 ethaddr[ETH_ALEN])
{
struct f_rndis *rndis;
int status;
if (!can_support_rndis(c) || !ethaddr)
return -EINVAL;
/* maybe allocate device-global string IDs */
if (rndis_string_defs[0].id == 0) {
/* ... and setup RNDIS itself */
status = rndis_init();
if (status < 0)
return status;
/* control interface label */
status = usb_string_id(c->cdev);
if (status < 0)
return status;
rndis_string_defs[0].id = status;
rndis_control_intf.iInterface = status;
/* data interface label */
status = usb_string_id(c->cdev);
if (status < 0)
return status;
rndis_string_defs[1].id = status;
rndis_data_intf.iInterface = status;
}
/* allocate and initialize one new instance */
status = -ENOMEM;
rndis = kzalloc(sizeof *rndis, GFP_KERNEL);
if (!rndis)
goto fail;
memcpy(rndis->ethaddr, ethaddr, ETH_ALEN);
/* RNDIS activates when the host changes this filter */
rndis->port.cdc_filter = 0;
/* RNDIS has special (and complex) framing */
rndis->port.header_len = sizeof(struct rndis_packet_msg_type);
rndis->port.wrap = rndis_add_header;
rndis->port.unwrap = rndis_rm_hdr;
rndis->port.func.name = "rndis";
rndis->port.func.strings = rndis_strings;
/* descriptors are per-instance copies */
rndis->port.func.bind = rndis_bind;
rndis->port.func.unbind = rndis_unbind;
rndis->port.func.set_alt = rndis_set_alt;
rndis->port.func.setup = rndis_setup;
rndis->port.func.disable = rndis_disable;
status = usb_add_function(c, &rndis->port.func);
if (status) {
kfree(rndis);
fail:
rndis_exit();
}
return status;
}
| gpl-2.0 |
GtrCraft/Optimus_Lux | drivers/tty/n_tty.c | 1122 | 56655 | /*
* n_tty.c --- implements the N_TTY line discipline.
*
* This code used to be in tty_io.c, but things are getting hairy
* enough that it made sense to split things off. (The N_TTY
* processing has changed so much that it's hardly recognizable,
* anyway...)
*
* Note that the open routine for N_TTY is guaranteed never to return
* an error. This is because Linux will fall back to setting a line
* to N_TTY if it can not switch to any other line discipline.
*
* Written by Theodore Ts'o, Copyright 1994.
*
* This file also contains code originally written by Linus Torvalds,
* Copyright 1991, 1992, 1993, and by Julian Cowley, Copyright 1994.
*
* This file may be redistributed under the terms of the GNU General Public
* License.
*
* Reduced memory usage for older ARM systems - Russell King.
*
* 2000/01/20 Fixed SMP locking on put_tty_queue using bits of
* the patch by Andrew J. Kroll <ag784@freenet.buffalo.edu>
* who actually finally proved there really was a race.
*
* 2002/03/18 Implemented n_tty_wakeup to send SIGIO POLL_OUTs to
* waiting writing processes-Sapan Bhatia <sapan@corewars.org>.
* Also fixed a bug in BLOCKING mode where n_tty_write returns
* EAGAIN
*/
#include <linux/types.h>
#include <linux/major.h>
#include <linux/errno.h>
#include <linux/signal.h>
#include <linux/fcntl.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include <linux/tty.h>
#include <linux/timer.h>
#include <linux/ctype.h>
#include <linux/mm.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/poll.h>
#include <linux/bitops.h>
#include <linux/audit.h>
#include <linux/file.h>
#include <linux/uaccess.h>
#include <linux/module.h>
#include <linux/ratelimit.h>
/* number of characters left in xmit buffer before select has we have room */
#define WAKEUP_CHARS 256
/*
* This defines the low- and high-watermarks for throttling and
* unthrottling the TTY driver. These watermarks are used for
* controlling the space in the read buffer.
*/
#define TTY_THRESHOLD_THROTTLE 128 /* now based on remaining room */
#define TTY_THRESHOLD_UNTHROTTLE 128
/*
* Special byte codes used in the echo buffer to represent operations
* or special handling of characters. Bytes in the echo buffer that
* are not part of such special blocks are treated as normal character
* codes.
*/
#define ECHO_OP_START 0xff
#define ECHO_OP_MOVE_BACK_COL 0x80
#define ECHO_OP_SET_CANON_COL 0x81
#define ECHO_OP_ERASE_TAB 0x82
struct n_tty_data {
unsigned int column;
unsigned long overrun_time;
int num_overrun;
unsigned char lnext:1, erasing:1, raw:1, real_raw:1, icanon:1;
unsigned char echo_overrun:1;
DECLARE_BITMAP(process_char_map, 256);
DECLARE_BITMAP(read_flags, N_TTY_BUF_SIZE);
char *read_buf;
int read_head;
int read_tail;
int read_cnt;
unsigned char *echo_buf;
unsigned int echo_pos;
unsigned int echo_cnt;
int canon_data;
unsigned long canon_head;
unsigned int canon_column;
struct mutex atomic_read_lock;
struct mutex output_lock;
struct mutex echo_lock;
raw_spinlock_t read_lock;
};
static inline int tty_put_user(struct tty_struct *tty, unsigned char x,
unsigned char __user *ptr)
{
struct n_tty_data *ldata = tty->disc_data;
tty_audit_add_data(tty, &x, 1, ldata->icanon);
return put_user(x, ptr);
}
/**
* n_tty_set_room - receive space
* @tty: terminal
*
* Sets tty->receive_room to reflect the currently available space
* in the input buffer, and re-schedules the flip buffer work if space
* just became available.
*
* Locks: Concurrent update is protected with read_lock
*/
static void n_tty_set_room(struct tty_struct *tty)
{
struct n_tty_data *ldata = tty->disc_data;
int left;
int old_left;
unsigned long flags;
raw_spin_lock_irqsave(&ldata->read_lock, flags);
if (I_PARMRK(tty)) {
/* Multiply read_cnt by 3, since each byte might take up to
* three times as many spaces when PARMRK is set (depending on
* its flags, e.g. parity error). */
left = N_TTY_BUF_SIZE - ldata->read_cnt * 3 - 1;
} else
left = N_TTY_BUF_SIZE - ldata->read_cnt - 1;
/*
* If we are doing input canonicalization, and there are no
* pending newlines, let characters through without limit, so
* that erase characters will be handled. Other excess
* characters will be beeped.
*/
if (left <= 0)
left = ldata->icanon && !ldata->canon_data;
old_left = tty->receive_room;
tty->receive_room = left;
raw_spin_unlock_irqrestore(&ldata->read_lock, flags);
/* Did this open up the receive buffer? We may need to flip */
if (left && !old_left) {
WARN_RATELIMIT(tty->port->itty == NULL,
"scheduling with invalid itty\n");
/* see if ldisc has been killed - if so, this means that
* even though the ldisc has been halted and ->buf.work
* cancelled, ->buf.work is about to be rescheduled
*/
WARN_RATELIMIT(test_bit(TTY_LDISC_HALTED, &tty->flags),
"scheduling buffer work for halted ldisc\n");
schedule_work(&tty->port->buf.work);
}
}
static void put_tty_queue_nolock(unsigned char c, struct n_tty_data *ldata)
{
if (ldata->read_cnt < N_TTY_BUF_SIZE) {
ldata->read_buf[ldata->read_head] = c;
ldata->read_head = (ldata->read_head + 1) & (N_TTY_BUF_SIZE-1);
ldata->read_cnt++;
}
}
/**
* put_tty_queue - add character to tty
* @c: character
* @ldata: n_tty data
*
* Add a character to the tty read_buf queue. This is done under the
* read_lock to serialize character addition and also to protect us
* against parallel reads or flushes
*/
static void put_tty_queue(unsigned char c, struct n_tty_data *ldata)
{
unsigned long flags;
/*
* The problem of stomping on the buffers ends here.
* Why didn't anyone see this one coming? --AJK
*/
raw_spin_lock_irqsave(&ldata->read_lock, flags);
put_tty_queue_nolock(c, ldata);
raw_spin_unlock_irqrestore(&ldata->read_lock, flags);
}
/**
* reset_buffer_flags - reset buffer state
* @tty: terminal to reset
*
* Reset the read buffer counters and clear the flags.
* Called from n_tty_open() and n_tty_flush_buffer().
*
* Locking: tty_read_lock for read fields.
*/
static void reset_buffer_flags(struct n_tty_data *ldata)
{
unsigned long flags;
raw_spin_lock_irqsave(&ldata->read_lock, flags);
ldata->read_head = ldata->read_tail = ldata->read_cnt = 0;
raw_spin_unlock_irqrestore(&ldata->read_lock, flags);
mutex_lock(&ldata->echo_lock);
ldata->echo_pos = ldata->echo_cnt = ldata->echo_overrun = 0;
mutex_unlock(&ldata->echo_lock);
ldata->canon_head = ldata->canon_data = ldata->erasing = 0;
bitmap_zero(ldata->read_flags, N_TTY_BUF_SIZE);
}
static void n_tty_packet_mode_flush(struct tty_struct *tty)
{
unsigned long flags;
spin_lock_irqsave(&tty->ctrl_lock, flags);
if (tty->link->packet) {
tty->ctrl_status |= TIOCPKT_FLUSHREAD;
wake_up_interruptible(&tty->link->read_wait);
}
spin_unlock_irqrestore(&tty->ctrl_lock, flags);
}
/**
* n_tty_flush_buffer - clean input queue
* @tty: terminal device
*
* Flush the input buffer. Called when the tty layer wants the
* buffer flushed (eg at hangup) or when the N_TTY line discipline
* internally has to clean the pending queue (for example some signals).
*
* Locking: ctrl_lock, read_lock.
*/
static void n_tty_flush_buffer(struct tty_struct *tty)
{
reset_buffer_flags(tty->disc_data);
n_tty_set_room(tty);
if (tty->link)
n_tty_packet_mode_flush(tty);
}
/**
* n_tty_chars_in_buffer - report available bytes
* @tty: tty device
*
* Report the number of characters buffered to be delivered to user
* at this instant in time.
*
* Locking: read_lock
*/
static ssize_t n_tty_chars_in_buffer(struct tty_struct *tty)
{
struct n_tty_data *ldata = tty->disc_data;
unsigned long flags;
ssize_t n = 0;
raw_spin_lock_irqsave(&ldata->read_lock, flags);
if (!ldata->icanon) {
n = ldata->read_cnt;
} else if (ldata->canon_data) {
n = (ldata->canon_head > ldata->read_tail) ?
ldata->canon_head - ldata->read_tail :
ldata->canon_head + (N_TTY_BUF_SIZE - ldata->read_tail);
}
raw_spin_unlock_irqrestore(&ldata->read_lock, flags);
return n;
}
/**
* is_utf8_continuation - utf8 multibyte check
* @c: byte to check
*
* Returns true if the utf8 character 'c' is a multibyte continuation
* character. We use this to correctly compute the on screen size
* of the character when printing
*/
static inline int is_utf8_continuation(unsigned char c)
{
return (c & 0xc0) == 0x80;
}
/**
* is_continuation - multibyte check
* @c: byte to check
*
* Returns true if the utf8 character 'c' is a multibyte continuation
* character and the terminal is in unicode mode.
*/
static inline int is_continuation(unsigned char c, struct tty_struct *tty)
{
return I_IUTF8(tty) && is_utf8_continuation(c);
}
/**
* do_output_char - output one character
* @c: character (or partial unicode symbol)
* @tty: terminal device
* @space: space available in tty driver write buffer
*
* This is a helper function that handles one output character
* (including special characters like TAB, CR, LF, etc.),
* doing OPOST processing and putting the results in the
* tty driver's write buffer.
*
* Note that Linux currently ignores TABDLY, CRDLY, VTDLY, FFDLY
* and NLDLY. They simply aren't relevant in the world today.
* If you ever need them, add them here.
*
* Returns the number of bytes of buffer space used or -1 if
* no space left.
*
* Locking: should be called under the output_lock to protect
* the column state and space left in the buffer
*/
static int do_output_char(unsigned char c, struct tty_struct *tty, int space)
{
struct n_tty_data *ldata = tty->disc_data;
int spaces;
if (!space)
return -1;
switch (c) {
case '\n':
if (O_ONLRET(tty))
ldata->column = 0;
if (O_ONLCR(tty)) {
if (space < 2)
return -1;
ldata->canon_column = ldata->column = 0;
tty->ops->write(tty, "\r\n", 2);
return 2;
}
ldata->canon_column = ldata->column;
break;
case '\r':
if (O_ONOCR(tty) && ldata->column == 0)
return 0;
if (O_OCRNL(tty)) {
c = '\n';
if (O_ONLRET(tty))
ldata->canon_column = ldata->column = 0;
break;
}
ldata->canon_column = ldata->column = 0;
break;
case '\t':
spaces = 8 - (ldata->column & 7);
if (O_TABDLY(tty) == XTABS) {
if (space < spaces)
return -1;
ldata->column += spaces;
tty->ops->write(tty, " ", spaces);
return spaces;
}
ldata->column += spaces;
break;
case '\b':
if (ldata->column > 0)
ldata->column--;
break;
default:
if (!iscntrl(c)) {
if (O_OLCUC(tty))
c = toupper(c);
if (!is_continuation(c, tty))
ldata->column++;
}
break;
}
tty_put_char(tty, c);
return 1;
}
/**
* process_output - output post processor
* @c: character (or partial unicode symbol)
* @tty: terminal device
*
* Output one character with OPOST processing.
* Returns -1 when the output device is full and the character
* must be retried.
*
* Locking: output_lock to protect column state and space left
* (also, this is called from n_tty_write under the
* tty layer write lock)
*/
static int process_output(unsigned char c, struct tty_struct *tty)
{
struct n_tty_data *ldata = tty->disc_data;
int space, retval;
mutex_lock(&ldata->output_lock);
space = tty_write_room(tty);
retval = do_output_char(c, tty, space);
mutex_unlock(&ldata->output_lock);
if (retval < 0)
return -1;
else
return 0;
}
/**
* process_output_block - block post processor
* @tty: terminal device
* @buf: character buffer
* @nr: number of bytes to output
*
* Output a block of characters with OPOST processing.
* Returns the number of characters output.
*
* This path is used to speed up block console writes, among other
* things when processing blocks of output data. It handles only
* the simple cases normally found and helps to generate blocks of
* symbols for the console driver and thus improve performance.
*
* Locking: output_lock to protect column state and space left
* (also, this is called from n_tty_write under the
* tty layer write lock)
*/
static ssize_t process_output_block(struct tty_struct *tty,
const unsigned char *buf, unsigned int nr)
{
struct n_tty_data *ldata = tty->disc_data;
int space;
int i;
const unsigned char *cp;
mutex_lock(&ldata->output_lock);
space = tty_write_room(tty);
if (!space) {
mutex_unlock(&ldata->output_lock);
return 0;
}
if (nr > space)
nr = space;
for (i = 0, cp = buf; i < nr; i++, cp++) {
unsigned char c = *cp;
switch (c) {
case '\n':
if (O_ONLRET(tty))
ldata->column = 0;
if (O_ONLCR(tty))
goto break_out;
ldata->canon_column = ldata->column;
break;
case '\r':
if (O_ONOCR(tty) && ldata->column == 0)
goto break_out;
if (O_OCRNL(tty))
goto break_out;
ldata->canon_column = ldata->column = 0;
break;
case '\t':
goto break_out;
case '\b':
if (ldata->column > 0)
ldata->column--;
break;
default:
if (!iscntrl(c)) {
if (O_OLCUC(tty))
goto break_out;
if (!is_continuation(c, tty))
ldata->column++;
}
break;
}
}
break_out:
i = tty->ops->write(tty, buf, i);
mutex_unlock(&ldata->output_lock);
return i;
}
/**
* process_echoes - write pending echo characters
* @tty: terminal device
*
* Write previously buffered echo (and other ldisc-generated)
* characters to the tty.
*
* Characters generated by the ldisc (including echoes) need to
* be buffered because the driver's write buffer can fill during
* heavy program output. Echoing straight to the driver will
* often fail under these conditions, causing lost characters and
* resulting mismatches of ldisc state information.
*
* Since the ldisc state must represent the characters actually sent
* to the driver at the time of the write, operations like certain
* changes in column state are also saved in the buffer and executed
* here.
*
* A circular fifo buffer is used so that the most recent characters
* are prioritized. Also, when control characters are echoed with a
* prefixed "^", the pair is treated atomically and thus not separated.
*
* Locking: output_lock to protect column state and space left,
* echo_lock to protect the echo buffer
*/
static void process_echoes(struct tty_struct *tty)
{
struct n_tty_data *ldata = tty->disc_data;
int space, nr;
unsigned char c;
unsigned char *cp, *buf_end;
if (!ldata->echo_cnt)
return;
mutex_lock(&ldata->output_lock);
mutex_lock(&ldata->echo_lock);
space = tty_write_room(tty);
buf_end = ldata->echo_buf + N_TTY_BUF_SIZE;
cp = ldata->echo_buf + ldata->echo_pos;
nr = ldata->echo_cnt;
while (nr > 0) {
c = *cp;
if (c == ECHO_OP_START) {
unsigned char op;
unsigned char *opp;
int no_space_left = 0;
/*
* If the buffer byte is the start of a multi-byte
* operation, get the next byte, which is either the
* op code or a control character value.
*/
opp = cp + 1;
if (opp == buf_end)
opp -= N_TTY_BUF_SIZE;
op = *opp;
switch (op) {
unsigned int num_chars, num_bs;
case ECHO_OP_ERASE_TAB:
if (++opp == buf_end)
opp -= N_TTY_BUF_SIZE;
num_chars = *opp;
/*
* Determine how many columns to go back
* in order to erase the tab.
* This depends on the number of columns
* used by other characters within the tab
* area. If this (modulo 8) count is from
* the start of input rather than from a
* previous tab, we offset by canon column.
* Otherwise, tab spacing is normal.
*/
if (!(num_chars & 0x80))
num_chars += ldata->canon_column;
num_bs = 8 - (num_chars & 7);
if (num_bs > space) {
no_space_left = 1;
break;
}
space -= num_bs;
while (num_bs--) {
tty_put_char(tty, '\b');
if (ldata->column > 0)
ldata->column--;
}
cp += 3;
nr -= 3;
break;
case ECHO_OP_SET_CANON_COL:
ldata->canon_column = ldata->column;
cp += 2;
nr -= 2;
break;
case ECHO_OP_MOVE_BACK_COL:
if (ldata->column > 0)
ldata->column--;
cp += 2;
nr -= 2;
break;
case ECHO_OP_START:
/* This is an escaped echo op start code */
if (!space) {
no_space_left = 1;
break;
}
tty_put_char(tty, ECHO_OP_START);
ldata->column++;
space--;
cp += 2;
nr -= 2;
break;
default:
/*
* If the op is not a special byte code,
* it is a ctrl char tagged to be echoed
* as "^X" (where X is the letter
* representing the control char).
* Note that we must ensure there is
* enough space for the whole ctrl pair.
*
*/
if (space < 2) {
no_space_left = 1;
break;
}
tty_put_char(tty, '^');
tty_put_char(tty, op ^ 0100);
ldata->column += 2;
space -= 2;
cp += 2;
nr -= 2;
}
if (no_space_left)
break;
} else {
if (O_OPOST(tty) &&
!(test_bit(TTY_HW_COOK_OUT, &tty->flags))) {
int retval = do_output_char(c, tty, space);
if (retval < 0)
break;
space -= retval;
} else {
if (!space)
break;
tty_put_char(tty, c);
space -= 1;
}
cp += 1;
nr -= 1;
}
/* When end of circular buffer reached, wrap around */
if (cp >= buf_end)
cp -= N_TTY_BUF_SIZE;
}
if (nr == 0) {
ldata->echo_pos = 0;
ldata->echo_cnt = 0;
ldata->echo_overrun = 0;
} else {
int num_processed = ldata->echo_cnt - nr;
ldata->echo_pos += num_processed;
ldata->echo_pos &= N_TTY_BUF_SIZE - 1;
ldata->echo_cnt = nr;
if (num_processed > 0)
ldata->echo_overrun = 0;
}
mutex_unlock(&ldata->echo_lock);
mutex_unlock(&ldata->output_lock);
if (tty->ops->flush_chars)
tty->ops->flush_chars(tty);
}
/**
* add_echo_byte - add a byte to the echo buffer
* @c: unicode byte to echo
* @ldata: n_tty data
*
* Add a character or operation byte to the echo buffer.
*
* Should be called under the echo lock to protect the echo buffer.
*/
static void add_echo_byte(unsigned char c, struct n_tty_data *ldata)
{
int new_byte_pos;
if (ldata->echo_cnt == N_TTY_BUF_SIZE) {
/* Circular buffer is already at capacity */
new_byte_pos = ldata->echo_pos;
/*
* Since the buffer start position needs to be advanced,
* be sure to step by a whole operation byte group.
*/
if (ldata->echo_buf[ldata->echo_pos] == ECHO_OP_START) {
if (ldata->echo_buf[(ldata->echo_pos + 1) &
(N_TTY_BUF_SIZE - 1)] ==
ECHO_OP_ERASE_TAB) {
ldata->echo_pos += 3;
ldata->echo_cnt -= 2;
} else {
ldata->echo_pos += 2;
ldata->echo_cnt -= 1;
}
} else {
ldata->echo_pos++;
}
ldata->echo_pos &= N_TTY_BUF_SIZE - 1;
ldata->echo_overrun = 1;
} else {
new_byte_pos = ldata->echo_pos + ldata->echo_cnt;
new_byte_pos &= N_TTY_BUF_SIZE - 1;
ldata->echo_cnt++;
}
ldata->echo_buf[new_byte_pos] = c;
}
/**
* echo_move_back_col - add operation to move back a column
* @ldata: n_tty data
*
* Add an operation to the echo buffer to move back one column.
*
* Locking: echo_lock to protect the echo buffer
*/
static void echo_move_back_col(struct n_tty_data *ldata)
{
mutex_lock(&ldata->echo_lock);
add_echo_byte(ECHO_OP_START, ldata);
add_echo_byte(ECHO_OP_MOVE_BACK_COL, ldata);
mutex_unlock(&ldata->echo_lock);
}
/**
* echo_set_canon_col - add operation to set the canon column
* @ldata: n_tty data
*
* Add an operation to the echo buffer to set the canon column
* to the current column.
*
* Locking: echo_lock to protect the echo buffer
*/
static void echo_set_canon_col(struct n_tty_data *ldata)
{
mutex_lock(&ldata->echo_lock);
add_echo_byte(ECHO_OP_START, ldata);
add_echo_byte(ECHO_OP_SET_CANON_COL, ldata);
mutex_unlock(&ldata->echo_lock);
}
/**
* echo_erase_tab - add operation to erase a tab
* @num_chars: number of character columns already used
* @after_tab: true if num_chars starts after a previous tab
* @ldata: n_tty data
*
* Add an operation to the echo buffer to erase a tab.
*
* Called by the eraser function, which knows how many character
* columns have been used since either a previous tab or the start
* of input. This information will be used later, along with
* canon column (if applicable), to go back the correct number
* of columns.
*
* Locking: echo_lock to protect the echo buffer
*/
static void echo_erase_tab(unsigned int num_chars, int after_tab,
struct n_tty_data *ldata)
{
mutex_lock(&ldata->echo_lock);
add_echo_byte(ECHO_OP_START, ldata);
add_echo_byte(ECHO_OP_ERASE_TAB, ldata);
/* We only need to know this modulo 8 (tab spacing) */
num_chars &= 7;
/* Set the high bit as a flag if num_chars is after a previous tab */
if (after_tab)
num_chars |= 0x80;
add_echo_byte(num_chars, ldata);
mutex_unlock(&ldata->echo_lock);
}
/**
* echo_char_raw - echo a character raw
* @c: unicode byte to echo
* @tty: terminal device
*
* Echo user input back onto the screen. This must be called only when
* L_ECHO(tty) is true. Called from the driver receive_buf path.
*
* This variant does not treat control characters specially.
*
* Locking: echo_lock to protect the echo buffer
*/
static void echo_char_raw(unsigned char c, struct n_tty_data *ldata)
{
mutex_lock(&ldata->echo_lock);
if (c == ECHO_OP_START) {
add_echo_byte(ECHO_OP_START, ldata);
add_echo_byte(ECHO_OP_START, ldata);
} else {
add_echo_byte(c, ldata);
}
mutex_unlock(&ldata->echo_lock);
}
/**
* echo_char - echo a character
* @c: unicode byte to echo
* @tty: terminal device
*
* Echo user input back onto the screen. This must be called only when
* L_ECHO(tty) is true. Called from the driver receive_buf path.
*
* This variant tags control characters to be echoed as "^X"
* (where X is the letter representing the control char).
*
* Locking: echo_lock to protect the echo buffer
*/
static void echo_char(unsigned char c, struct tty_struct *tty)
{
struct n_tty_data *ldata = tty->disc_data;
mutex_lock(&ldata->echo_lock);
if (c == ECHO_OP_START) {
add_echo_byte(ECHO_OP_START, ldata);
add_echo_byte(ECHO_OP_START, ldata);
} else {
if (L_ECHOCTL(tty) && iscntrl(c) && c != '\t')
add_echo_byte(ECHO_OP_START, ldata);
add_echo_byte(c, ldata);
}
mutex_unlock(&ldata->echo_lock);
}
/**
* finish_erasing - complete erase
* @ldata: n_tty data
*/
static inline void finish_erasing(struct n_tty_data *ldata)
{
if (ldata->erasing) {
echo_char_raw('/', ldata);
ldata->erasing = 0;
}
}
/**
* eraser - handle erase function
* @c: character input
* @tty: terminal device
*
* Perform erase and necessary output when an erase character is
* present in the stream from the driver layer. Handles the complexities
* of UTF-8 multibyte symbols.
*
* Locking: read_lock for tty buffers
*/
static void eraser(unsigned char c, struct tty_struct *tty)
{
struct n_tty_data *ldata = tty->disc_data;
enum { ERASE, WERASE, KILL } kill_type;
int head, seen_alnums, cnt;
unsigned long flags;
/* FIXME: locking needed ? */
if (ldata->read_head == ldata->canon_head) {
/* process_output('\a', tty); */ /* what do you think? */
return;
}
if (c == ERASE_CHAR(tty))
kill_type = ERASE;
else if (c == WERASE_CHAR(tty))
kill_type = WERASE;
else {
if (!L_ECHO(tty)) {
raw_spin_lock_irqsave(&ldata->read_lock, flags);
ldata->read_cnt -= ((ldata->read_head - ldata->canon_head) &
(N_TTY_BUF_SIZE - 1));
ldata->read_head = ldata->canon_head;
raw_spin_unlock_irqrestore(&ldata->read_lock, flags);
return;
}
if (!L_ECHOK(tty) || !L_ECHOKE(tty) || !L_ECHOE(tty)) {
raw_spin_lock_irqsave(&ldata->read_lock, flags);
ldata->read_cnt -= ((ldata->read_head - ldata->canon_head) &
(N_TTY_BUF_SIZE - 1));
ldata->read_head = ldata->canon_head;
raw_spin_unlock_irqrestore(&ldata->read_lock, flags);
finish_erasing(ldata);
echo_char(KILL_CHAR(tty), tty);
/* Add a newline if ECHOK is on and ECHOKE is off. */
if (L_ECHOK(tty))
echo_char_raw('\n', ldata);
return;
}
kill_type = KILL;
}
seen_alnums = 0;
/* FIXME: Locking ?? */
while (ldata->read_head != ldata->canon_head) {
head = ldata->read_head;
/* erase a single possibly multibyte character */
do {
head = (head - 1) & (N_TTY_BUF_SIZE-1);
c = ldata->read_buf[head];
} while (is_continuation(c, tty) && head != ldata->canon_head);
/* do not partially erase */
if (is_continuation(c, tty))
break;
if (kill_type == WERASE) {
/* Equivalent to BSD's ALTWERASE. */
if (isalnum(c) || c == '_')
seen_alnums++;
else if (seen_alnums)
break;
}
cnt = (ldata->read_head - head) & (N_TTY_BUF_SIZE-1);
raw_spin_lock_irqsave(&ldata->read_lock, flags);
ldata->read_head = head;
ldata->read_cnt -= cnt;
raw_spin_unlock_irqrestore(&ldata->read_lock, flags);
if (L_ECHO(tty)) {
if (L_ECHOPRT(tty)) {
if (!ldata->erasing) {
echo_char_raw('\\', ldata);
ldata->erasing = 1;
}
/* if cnt > 1, output a multi-byte character */
echo_char(c, tty);
while (--cnt > 0) {
head = (head+1) & (N_TTY_BUF_SIZE-1);
echo_char_raw(ldata->read_buf[head],
ldata);
echo_move_back_col(ldata);
}
} else if (kill_type == ERASE && !L_ECHOE(tty)) {
echo_char(ERASE_CHAR(tty), tty);
} else if (c == '\t') {
unsigned int num_chars = 0;
int after_tab = 0;
unsigned long tail = ldata->read_head;
/*
* Count the columns used for characters
* since the start of input or after a
* previous tab.
* This info is used to go back the correct
* number of columns.
*/
while (tail != ldata->canon_head) {
tail = (tail-1) & (N_TTY_BUF_SIZE-1);
c = ldata->read_buf[tail];
if (c == '\t') {
after_tab = 1;
break;
} else if (iscntrl(c)) {
if (L_ECHOCTL(tty))
num_chars += 2;
} else if (!is_continuation(c, tty)) {
num_chars++;
}
}
echo_erase_tab(num_chars, after_tab, ldata);
} else {
if (iscntrl(c) && L_ECHOCTL(tty)) {
echo_char_raw('\b', ldata);
echo_char_raw(' ', ldata);
echo_char_raw('\b', ldata);
}
if (!iscntrl(c) || L_ECHOCTL(tty)) {
echo_char_raw('\b', ldata);
echo_char_raw(' ', ldata);
echo_char_raw('\b', ldata);
}
}
}
if (kill_type == ERASE)
break;
}
if (ldata->read_head == ldata->canon_head && L_ECHO(tty))
finish_erasing(ldata);
}
/**
* isig - handle the ISIG optio
* @sig: signal
* @tty: terminal
*
* Called when a signal is being sent due to terminal input.
* Called from the driver receive_buf path so serialized.
*
* Locking: ctrl_lock
*/
static inline void isig(int sig, struct tty_struct *tty)
{
struct pid *tty_pgrp = tty_get_pgrp(tty);
if (tty_pgrp) {
kill_pgrp(tty_pgrp, sig, 1);
put_pid(tty_pgrp);
}
}
/**
* n_tty_receive_break - handle break
* @tty: terminal
*
* An RS232 break event has been hit in the incoming bitstream. This
* can cause a variety of events depending upon the termios settings.
*
* Called from the receive_buf path so single threaded.
*/
static inline void n_tty_receive_break(struct tty_struct *tty)
{
struct n_tty_data *ldata = tty->disc_data;
if (I_IGNBRK(tty))
return;
if (I_BRKINT(tty)) {
isig(SIGINT, tty);
if (!L_NOFLSH(tty)) {
n_tty_flush_buffer(tty);
tty_driver_flush_buffer(tty);
}
return;
}
if (I_PARMRK(tty)) {
put_tty_queue('\377', ldata);
put_tty_queue('\0', ldata);
}
put_tty_queue('\0', ldata);
wake_up_interruptible(&tty->read_wait);
}
/**
* n_tty_receive_overrun - handle overrun reporting
* @tty: terminal
*
* Data arrived faster than we could process it. While the tty
* driver has flagged this the bits that were missed are gone
* forever.
*
* Called from the receive_buf path so single threaded. Does not
* need locking as num_overrun and overrun_time are function
* private.
*/
static inline void n_tty_receive_overrun(struct tty_struct *tty)
{
struct n_tty_data *ldata = tty->disc_data;
char buf[64];
ldata->num_overrun++;
if (time_after(jiffies, ldata->overrun_time + HZ) ||
time_after(ldata->overrun_time, jiffies)) {
printk(KERN_WARNING "%s: %d input overrun(s)\n",
tty_name(tty, buf),
ldata->num_overrun);
ldata->overrun_time = jiffies;
ldata->num_overrun = 0;
}
}
/**
* n_tty_receive_parity_error - error notifier
* @tty: terminal device
* @c: character
*
* Process a parity error and queue the right data to indicate
* the error case if necessary. Locking as per n_tty_receive_buf.
*/
static inline void n_tty_receive_parity_error(struct tty_struct *tty,
unsigned char c)
{
struct n_tty_data *ldata = tty->disc_data;
if (I_IGNPAR(tty))
return;
if (I_PARMRK(tty)) {
put_tty_queue('\377', ldata);
put_tty_queue('\0', ldata);
put_tty_queue(c, ldata);
} else if (I_INPCK(tty))
put_tty_queue('\0', ldata);
else
put_tty_queue(c, ldata);
wake_up_interruptible(&tty->read_wait);
}
/**
* n_tty_receive_char - perform processing
* @tty: terminal device
* @c: character
*
* Process an individual character of input received from the driver.
* This is serialized with respect to itself by the rules for the
* driver above.
*/
static inline void n_tty_receive_char(struct tty_struct *tty, unsigned char c)
{
struct n_tty_data *ldata = tty->disc_data;
unsigned long flags;
int parmrk;
if (ldata->raw) {
put_tty_queue(c, ldata);
return;
}
if (I_ISTRIP(tty))
c &= 0x7f;
if (I_IUCLC(tty) && L_IEXTEN(tty))
c = tolower(c);
if (L_EXTPROC(tty)) {
put_tty_queue(c, ldata);
return;
}
if (tty->stopped && !tty->flow_stopped && I_IXON(tty) &&
I_IXANY(tty) && c != START_CHAR(tty) && c != STOP_CHAR(tty) &&
c != INTR_CHAR(tty) && c != QUIT_CHAR(tty) && c != SUSP_CHAR(tty)) {
start_tty(tty);
process_echoes(tty);
}
if (tty->closing) {
if (I_IXON(tty)) {
if (c == START_CHAR(tty)) {
start_tty(tty);
process_echoes(tty);
} else if (c == STOP_CHAR(tty))
stop_tty(tty);
}
return;
}
/*
* If the previous character was LNEXT, or we know that this
* character is not one of the characters that we'll have to
* handle specially, do shortcut processing to speed things
* up.
*/
if (!test_bit(c, ldata->process_char_map) || ldata->lnext) {
ldata->lnext = 0;
parmrk = (c == (unsigned char) '\377' && I_PARMRK(tty)) ? 1 : 0;
if (ldata->read_cnt >= (N_TTY_BUF_SIZE - parmrk - 1)) {
/* beep if no space */
if (L_ECHO(tty))
process_output('\a', tty);
return;
}
if (L_ECHO(tty)) {
finish_erasing(ldata);
/* Record the column of first canon char. */
if (ldata->canon_head == ldata->read_head)
echo_set_canon_col(ldata);
echo_char(c, tty);
process_echoes(tty);
}
if (parmrk)
put_tty_queue(c, ldata);
put_tty_queue(c, ldata);
return;
}
if (I_IXON(tty)) {
if (c == START_CHAR(tty)) {
start_tty(tty);
process_echoes(tty);
return;
}
if (c == STOP_CHAR(tty)) {
stop_tty(tty);
return;
}
}
if (L_ISIG(tty)) {
int signal;
signal = SIGINT;
if (c == INTR_CHAR(tty))
goto send_signal;
signal = SIGQUIT;
if (c == QUIT_CHAR(tty))
goto send_signal;
signal = SIGTSTP;
if (c == SUSP_CHAR(tty)) {
send_signal:
if (!L_NOFLSH(tty)) {
n_tty_flush_buffer(tty);
tty_driver_flush_buffer(tty);
}
if (I_IXON(tty))
start_tty(tty);
if (L_ECHO(tty)) {
echo_char(c, tty);
process_echoes(tty);
}
isig(signal, tty);
return;
}
}
if (c == '\r') {
if (I_IGNCR(tty))
return;
if (I_ICRNL(tty))
c = '\n';
} else if (c == '\n' && I_INLCR(tty))
c = '\r';
if (ldata->icanon) {
if (c == ERASE_CHAR(tty) || c == KILL_CHAR(tty) ||
(c == WERASE_CHAR(tty) && L_IEXTEN(tty))) {
eraser(c, tty);
process_echoes(tty);
return;
}
if (c == LNEXT_CHAR(tty) && L_IEXTEN(tty)) {
ldata->lnext = 1;
if (L_ECHO(tty)) {
finish_erasing(ldata);
if (L_ECHOCTL(tty)) {
echo_char_raw('^', ldata);
echo_char_raw('\b', ldata);
process_echoes(tty);
}
}
return;
}
if (c == REPRINT_CHAR(tty) && L_ECHO(tty) &&
L_IEXTEN(tty)) {
unsigned long tail = ldata->canon_head;
finish_erasing(ldata);
echo_char(c, tty);
echo_char_raw('\n', ldata);
while (tail != ldata->read_head) {
echo_char(ldata->read_buf[tail], tty);
tail = (tail+1) & (N_TTY_BUF_SIZE-1);
}
process_echoes(tty);
return;
}
if (c == '\n') {
if (ldata->read_cnt >= N_TTY_BUF_SIZE) {
if (L_ECHO(tty))
process_output('\a', tty);
return;
}
if (L_ECHO(tty) || L_ECHONL(tty)) {
echo_char_raw('\n', ldata);
process_echoes(tty);
}
goto handle_newline;
}
if (c == EOF_CHAR(tty)) {
if (ldata->read_cnt >= N_TTY_BUF_SIZE)
return;
if (ldata->canon_head != ldata->read_head)
set_bit(TTY_PUSH, &tty->flags);
c = __DISABLED_CHAR;
goto handle_newline;
}
if ((c == EOL_CHAR(tty)) ||
(c == EOL2_CHAR(tty) && L_IEXTEN(tty))) {
parmrk = (c == (unsigned char) '\377' && I_PARMRK(tty))
? 1 : 0;
if (ldata->read_cnt >= (N_TTY_BUF_SIZE - parmrk)) {
if (L_ECHO(tty))
process_output('\a', tty);
return;
}
/*
* XXX are EOL_CHAR and EOL2_CHAR echoed?!?
*/
if (L_ECHO(tty)) {
/* Record the column of first canon char. */
if (ldata->canon_head == ldata->read_head)
echo_set_canon_col(ldata);
echo_char(c, tty);
process_echoes(tty);
}
/*
* XXX does PARMRK doubling happen for
* EOL_CHAR and EOL2_CHAR?
*/
if (parmrk)
put_tty_queue(c, ldata);
handle_newline:
raw_spin_lock_irqsave(&ldata->read_lock, flags);
set_bit(ldata->read_head, ldata->read_flags);
put_tty_queue_nolock(c, ldata);
ldata->canon_head = ldata->read_head;
ldata->canon_data++;
raw_spin_unlock_irqrestore(&ldata->read_lock, flags);
kill_fasync(&tty->fasync, SIGIO, POLL_IN);
if (waitqueue_active(&tty->read_wait))
wake_up_interruptible(&tty->read_wait);
return;
}
}
parmrk = (c == (unsigned char) '\377' && I_PARMRK(tty)) ? 1 : 0;
if (ldata->read_cnt >= (N_TTY_BUF_SIZE - parmrk - 1)) {
/* beep if no space */
if (L_ECHO(tty))
process_output('\a', tty);
return;
}
if (L_ECHO(tty)) {
finish_erasing(ldata);
if (c == '\n')
echo_char_raw('\n', ldata);
else {
/* Record the column of first canon char. */
if (ldata->canon_head == ldata->read_head)
echo_set_canon_col(ldata);
echo_char(c, tty);
}
process_echoes(tty);
}
if (parmrk)
put_tty_queue(c, ldata);
put_tty_queue(c, ldata);
}
/**
* n_tty_write_wakeup - asynchronous I/O notifier
* @tty: tty device
*
* Required for the ptys, serial driver etc. since processes
* that attach themselves to the master and rely on ASYNC
* IO must be woken up
*/
static void n_tty_write_wakeup(struct tty_struct *tty)
{
if (tty->fasync && test_and_clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags))
kill_fasync(&tty->fasync, SIGIO, POLL_OUT);
}
/**
* n_tty_receive_buf - data receive
* @tty: terminal device
* @cp: buffer
* @fp: flag buffer
* @count: characters
*
* Called by the terminal driver when a block of characters has
* been received. This function must be called from soft contexts
* not from interrupt context. The driver is responsible for making
* calls one at a time and in order (or using flush_to_ldisc)
*/
static void n_tty_receive_buf(struct tty_struct *tty, const unsigned char *cp,
char *fp, int count)
{
struct n_tty_data *ldata = tty->disc_data;
const unsigned char *p;
char *f, flags = TTY_NORMAL;
int i;
char buf[64];
unsigned long cpuflags;
if (ldata->real_raw) {
raw_spin_lock_irqsave(&ldata->read_lock, cpuflags);
i = min(N_TTY_BUF_SIZE - ldata->read_cnt,
N_TTY_BUF_SIZE - ldata->read_head);
i = min(count, i);
memcpy(ldata->read_buf + ldata->read_head, cp, i);
ldata->read_head = (ldata->read_head + i) & (N_TTY_BUF_SIZE-1);
ldata->read_cnt += i;
cp += i;
count -= i;
i = min(N_TTY_BUF_SIZE - ldata->read_cnt,
N_TTY_BUF_SIZE - ldata->read_head);
i = min(count, i);
memcpy(ldata->read_buf + ldata->read_head, cp, i);
ldata->read_head = (ldata->read_head + i) & (N_TTY_BUF_SIZE-1);
ldata->read_cnt += i;
raw_spin_unlock_irqrestore(&ldata->read_lock, cpuflags);
} else {
for (i = count, p = cp, f = fp; i; i--, p++) {
if (f)
flags = *f++;
switch (flags) {
case TTY_NORMAL:
n_tty_receive_char(tty, *p);
break;
case TTY_BREAK:
n_tty_receive_break(tty);
break;
case TTY_PARITY:
case TTY_FRAME:
n_tty_receive_parity_error(tty, *p);
break;
case TTY_OVERRUN:
n_tty_receive_overrun(tty);
break;
default:
printk(KERN_ERR "%s: unknown flag %d\n",
tty_name(tty, buf), flags);
break;
}
}
if (tty->ops->flush_chars)
tty->ops->flush_chars(tty);
}
n_tty_set_room(tty);
if ((!ldata->icanon && (ldata->read_cnt >= tty->minimum_to_wake)) ||
L_EXTPROC(tty)) {
kill_fasync(&tty->fasync, SIGIO, POLL_IN);
if (waitqueue_active(&tty->read_wait))
wake_up_interruptible(&tty->read_wait);
}
/*
* Check the remaining room for the input canonicalization
* mode. We don't want to throttle the driver if we're in
* canonical mode and don't have a newline yet!
*/
while (1) {
tty_set_flow_change(tty, TTY_THROTTLE_SAFE);
if (tty->receive_room >= TTY_THRESHOLD_THROTTLE)
break;
if (!tty_throttle_safe(tty))
break;
}
__tty_set_flow_change(tty, 0);
}
int is_ignored(int sig)
{
return (sigismember(¤t->blocked, sig) ||
current->sighand->action[sig-1].sa.sa_handler == SIG_IGN);
}
/**
* n_tty_set_termios - termios data changed
* @tty: terminal
* @old: previous data
*
* Called by the tty layer when the user changes termios flags so
* that the line discipline can plan ahead. This function cannot sleep
* and is protected from re-entry by the tty layer. The user is
* guaranteed that this function will not be re-entered or in progress
* when the ldisc is closed.
*
* Locking: Caller holds tty->termios_mutex
*/
static void n_tty_set_termios(struct tty_struct *tty, struct ktermios *old)
{
struct n_tty_data *ldata = tty->disc_data;
int canon_change = 1;
if (old)
canon_change = (old->c_lflag ^ tty->termios.c_lflag) & ICANON;
if (canon_change) {
bitmap_zero(ldata->read_flags, N_TTY_BUF_SIZE);
ldata->canon_head = ldata->read_tail;
ldata->canon_data = 0;
ldata->erasing = 0;
}
if (canon_change && !L_ICANON(tty) && ldata->read_cnt)
wake_up_interruptible(&tty->read_wait);
ldata->icanon = (L_ICANON(tty) != 0);
if (test_bit(TTY_HW_COOK_IN, &tty->flags)) {
ldata->raw = 1;
ldata->real_raw = 1;
n_tty_set_room(tty);
return;
}
if (I_ISTRIP(tty) || I_IUCLC(tty) || I_IGNCR(tty) ||
I_ICRNL(tty) || I_INLCR(tty) || L_ICANON(tty) ||
I_IXON(tty) || L_ISIG(tty) || L_ECHO(tty) ||
I_PARMRK(tty)) {
bitmap_zero(ldata->process_char_map, 256);
if (I_IGNCR(tty) || I_ICRNL(tty))
set_bit('\r', ldata->process_char_map);
if (I_INLCR(tty))
set_bit('\n', ldata->process_char_map);
if (L_ICANON(tty)) {
set_bit(ERASE_CHAR(tty), ldata->process_char_map);
set_bit(KILL_CHAR(tty), ldata->process_char_map);
set_bit(EOF_CHAR(tty), ldata->process_char_map);
set_bit('\n', ldata->process_char_map);
set_bit(EOL_CHAR(tty), ldata->process_char_map);
if (L_IEXTEN(tty)) {
set_bit(WERASE_CHAR(tty),
ldata->process_char_map);
set_bit(LNEXT_CHAR(tty),
ldata->process_char_map);
set_bit(EOL2_CHAR(tty),
ldata->process_char_map);
if (L_ECHO(tty))
set_bit(REPRINT_CHAR(tty),
ldata->process_char_map);
}
}
if (I_IXON(tty)) {
set_bit(START_CHAR(tty), ldata->process_char_map);
set_bit(STOP_CHAR(tty), ldata->process_char_map);
}
if (L_ISIG(tty)) {
set_bit(INTR_CHAR(tty), ldata->process_char_map);
set_bit(QUIT_CHAR(tty), ldata->process_char_map);
set_bit(SUSP_CHAR(tty), ldata->process_char_map);
}
clear_bit(__DISABLED_CHAR, ldata->process_char_map);
ldata->raw = 0;
ldata->real_raw = 0;
} else {
ldata->raw = 1;
if ((I_IGNBRK(tty) || (!I_BRKINT(tty) && !I_PARMRK(tty))) &&
(I_IGNPAR(tty) || !I_INPCK(tty)) &&
(tty->driver->flags & TTY_DRIVER_REAL_RAW))
ldata->real_raw = 1;
else
ldata->real_raw = 0;
}
n_tty_set_room(tty);
/*
* Fix tty hang when I_IXON(tty) is cleared, but the tty
* been stopped by STOP_CHAR(tty) before it.
*/
if (!I_IXON(tty) && old && (old->c_iflag & IXON) && !tty->flow_stopped) {
start_tty(tty);
}
/* The termios change make the tty ready for I/O */
wake_up_interruptible(&tty->write_wait);
wake_up_interruptible(&tty->read_wait);
}
/**
* n_tty_close - close the ldisc for this tty
* @tty: device
*
* Called from the terminal layer when this line discipline is
* being shut down, either because of a close or becsuse of a
* discipline change. The function will not be called while other
* ldisc methods are in progress.
*/
static void n_tty_close(struct tty_struct *tty)
{
struct n_tty_data *ldata = tty->disc_data;
if (tty->link)
n_tty_packet_mode_flush(tty);
kfree(ldata->read_buf);
kfree(ldata->echo_buf);
kfree(ldata);
tty->disc_data = NULL;
}
/**
* n_tty_open - open an ldisc
* @tty: terminal to open
*
* Called when this line discipline is being attached to the
* terminal device. Can sleep. Called serialized so that no
* other events will occur in parallel. No further open will occur
* until a close.
*/
static int n_tty_open(struct tty_struct *tty)
{
struct n_tty_data *ldata;
ldata = kzalloc(sizeof(*ldata), GFP_KERNEL);
if (!ldata)
goto err;
ldata->overrun_time = jiffies;
mutex_init(&ldata->atomic_read_lock);
mutex_init(&ldata->output_lock);
mutex_init(&ldata->echo_lock);
raw_spin_lock_init(&ldata->read_lock);
/* These are ugly. Currently a malloc failure here can panic */
ldata->read_buf = kzalloc(N_TTY_BUF_SIZE, GFP_KERNEL);
ldata->echo_buf = kzalloc(N_TTY_BUF_SIZE, GFP_KERNEL);
if (!ldata->read_buf || !ldata->echo_buf)
goto err_free_bufs;
tty->disc_data = ldata;
reset_buffer_flags(tty->disc_data);
ldata->column = 0;
tty->minimum_to_wake = 1;
tty->closing = 0;
/* indicate buffer work may resume */
clear_bit(TTY_LDISC_HALTED, &tty->flags);
n_tty_set_termios(tty, NULL);
tty_unthrottle(tty);
return 0;
err_free_bufs:
kfree(ldata->read_buf);
kfree(ldata->echo_buf);
kfree(ldata);
err:
return -ENOMEM;
}
static inline int input_available_p(struct tty_struct *tty, int amt)
{
struct n_tty_data *ldata = tty->disc_data;
tty_flush_to_ldisc(tty);
if (ldata->icanon && !L_EXTPROC(tty)) {
if (ldata->canon_data)
return 1;
} else if (ldata->read_cnt >= (amt ? amt : 1))
return 1;
return 0;
}
/**
* copy_from_read_buf - copy read data directly
* @tty: terminal device
* @b: user data
* @nr: size of data
*
* Helper function to speed up n_tty_read. It is only called when
* ICANON is off; it copies characters straight from the tty queue to
* user space directly. It can be profitably called twice; once to
* drain the space from the tail pointer to the (physical) end of the
* buffer, and once to drain the space from the (physical) beginning of
* the buffer to head pointer.
*
* Called under the ldata->atomic_read_lock sem
*
*/
static int copy_from_read_buf(struct tty_struct *tty,
unsigned char __user **b,
size_t *nr)
{
struct n_tty_data *ldata = tty->disc_data;
int retval;
size_t n;
unsigned long flags;
bool is_eof;
retval = 0;
raw_spin_lock_irqsave(&ldata->read_lock, flags);
n = min(ldata->read_cnt, N_TTY_BUF_SIZE - ldata->read_tail);
n = min(*nr, n);
raw_spin_unlock_irqrestore(&ldata->read_lock, flags);
if (n) {
retval = copy_to_user(*b, &ldata->read_buf[ldata->read_tail], n);
n -= retval;
is_eof = n == 1 &&
ldata->read_buf[ldata->read_tail] == EOF_CHAR(tty);
tty_audit_add_data(tty, &ldata->read_buf[ldata->read_tail], n,
ldata->icanon);
raw_spin_lock_irqsave(&ldata->read_lock, flags);
ldata->read_tail = (ldata->read_tail + n) & (N_TTY_BUF_SIZE-1);
ldata->read_cnt -= n;
/* Turn single EOF into zero-length read */
if (L_EXTPROC(tty) && ldata->icanon && is_eof && !ldata->read_cnt)
n = 0;
raw_spin_unlock_irqrestore(&ldata->read_lock, flags);
*b += n;
*nr -= n;
}
return retval;
}
extern ssize_t redirected_tty_write(struct file *, const char __user *,
size_t, loff_t *);
/**
* job_control - check job control
* @tty: tty
* @file: file handle
*
* Perform job control management checks on this file/tty descriptor
* and if appropriate send any needed signals and return a negative
* error code if action should be taken.
*
* Locking: redirected write test is safe
* current->signal->tty check is safe
* ctrl_lock to safely reference tty->pgrp
*/
static int job_control(struct tty_struct *tty, struct file *file)
{
/* Job control check -- must be done at start and after
every sleep (POSIX.1 7.1.1.4). */
/* NOTE: not yet done after every sleep pending a thorough
check of the logic of this change. -- jlc */
/* don't stop on /dev/console */
if (file->f_op->write == redirected_tty_write ||
current->signal->tty != tty)
return 0;
spin_lock_irq(&tty->ctrl_lock);
if (!tty->pgrp)
printk(KERN_ERR "n_tty_read: no tty->pgrp!\n");
else if (task_pgrp(current) != tty->pgrp) {
spin_unlock_irq(&tty->ctrl_lock);
if (is_ignored(SIGTTIN) || is_current_pgrp_orphaned())
return -EIO;
kill_pgrp(task_pgrp(current), SIGTTIN, 1);
set_thread_flag(TIF_SIGPENDING);
return -ERESTARTSYS;
}
spin_unlock_irq(&tty->ctrl_lock);
return 0;
}
/**
* n_tty_read - read function for tty
* @tty: tty device
* @file: file object
* @buf: userspace buffer pointer
* @nr: size of I/O
*
* Perform reads for the line discipline. We are guaranteed that the
* line discipline will not be closed under us but we may get multiple
* parallel readers and must handle this ourselves. We may also get
* a hangup. Always called in user context, may sleep.
*
* This code must be sure never to sleep through a hangup.
*/
static ssize_t n_tty_read(struct tty_struct *tty, struct file *file,
unsigned char __user *buf, size_t nr)
{
struct n_tty_data *ldata = tty->disc_data;
unsigned char __user *b = buf;
DECLARE_WAITQUEUE(wait, current);
int c;
int minimum, time;
ssize_t retval = 0;
ssize_t size;
long timeout;
unsigned long flags;
int packet;
do_it_again:
c = job_control(tty, file);
if (c < 0)
return c;
minimum = time = 0;
timeout = MAX_SCHEDULE_TIMEOUT;
if (!ldata->icanon) {
time = (HZ / 10) * TIME_CHAR(tty);
minimum = MIN_CHAR(tty);
if (minimum) {
if (time)
tty->minimum_to_wake = 1;
else if (!waitqueue_active(&tty->read_wait) ||
(tty->minimum_to_wake > minimum))
tty->minimum_to_wake = minimum;
} else {
timeout = 0;
if (time) {
timeout = time;
time = 0;
}
tty->minimum_to_wake = minimum = 1;
}
}
/*
* Internal serialization of reads.
*/
if (file->f_flags & O_NONBLOCK) {
if (!mutex_trylock(&ldata->atomic_read_lock))
return -EAGAIN;
} else {
if (mutex_lock_interruptible(&ldata->atomic_read_lock))
return -ERESTARTSYS;
}
packet = tty->packet;
add_wait_queue(&tty->read_wait, &wait);
while (nr) {
/* First test for status change. */
if (packet && tty->link->ctrl_status) {
unsigned char cs;
if (b != buf)
break;
spin_lock_irqsave(&tty->link->ctrl_lock, flags);
cs = tty->link->ctrl_status;
tty->link->ctrl_status = 0;
spin_unlock_irqrestore(&tty->link->ctrl_lock, flags);
if (tty_put_user(tty, cs, b++)) {
retval = -EFAULT;
b--;
break;
}
nr--;
break;
}
/* This statement must be first before checking for input
so that any interrupt will set the state back to
TASK_RUNNING. */
set_current_state(TASK_INTERRUPTIBLE);
if (((minimum - (b - buf)) < tty->minimum_to_wake) &&
((minimum - (b - buf)) >= 1))
tty->minimum_to_wake = (minimum - (b - buf));
if (!input_available_p(tty, 0)) {
if (test_bit(TTY_OTHER_CLOSED, &tty->flags)) {
retval = -EIO;
break;
}
if (tty_hung_up_p(file))
break;
if (!timeout)
break;
if (file->f_flags & O_NONBLOCK) {
retval = -EAGAIN;
break;
}
if (signal_pending(current)) {
retval = -ERESTARTSYS;
break;
}
n_tty_set_room(tty);
timeout = schedule_timeout(timeout);
continue;
}
__set_current_state(TASK_RUNNING);
/* Deal with packet mode. */
if (packet && b == buf) {
if (tty_put_user(tty, TIOCPKT_DATA, b++)) {
retval = -EFAULT;
b--;
break;
}
nr--;
}
if (ldata->icanon && !L_EXTPROC(tty)) {
/* N.B. avoid overrun if nr == 0 */
raw_spin_lock_irqsave(&ldata->read_lock, flags);
while (nr && ldata->read_cnt) {
int eol;
eol = test_and_clear_bit(ldata->read_tail,
ldata->read_flags);
c = ldata->read_buf[ldata->read_tail];
ldata->read_tail = ((ldata->read_tail+1) &
(N_TTY_BUF_SIZE-1));
ldata->read_cnt--;
if (eol) {
/* this test should be redundant:
* we shouldn't be reading data if
* canon_data is 0
*/
if (--ldata->canon_data < 0)
ldata->canon_data = 0;
}
raw_spin_unlock_irqrestore(&ldata->read_lock, flags);
if (!eol || (c != __DISABLED_CHAR)) {
if (tty_put_user(tty, c, b++)) {
retval = -EFAULT;
b--;
raw_spin_lock_irqsave(&ldata->read_lock, flags);
break;
}
nr--;
}
if (eol) {
tty_audit_push(tty);
raw_spin_lock_irqsave(&ldata->read_lock, flags);
break;
}
raw_spin_lock_irqsave(&ldata->read_lock, flags);
}
raw_spin_unlock_irqrestore(&ldata->read_lock, flags);
if (retval)
break;
} else {
int uncopied;
/* The copy function takes the read lock and handles
locking internally for this case */
uncopied = copy_from_read_buf(tty, &b, &nr);
uncopied += copy_from_read_buf(tty, &b, &nr);
if (uncopied) {
retval = -EFAULT;
break;
}
}
/* If there is enough space in the read buffer now, let the
* low-level driver know. We use n_tty_chars_in_buffer() to
* check the buffer, as it now knows about canonical mode.
* Otherwise, if the driver is throttled and the line is
* longer than TTY_THRESHOLD_UNTHROTTLE in canonical mode,
* we won't get any more characters.
*/
while (1) {
tty_set_flow_change(tty, TTY_UNTHROTTLE_SAFE);
if (n_tty_chars_in_buffer(tty) > TTY_THRESHOLD_UNTHROTTLE)
break;
if (!tty->count)
break;
n_tty_set_room(tty);
if (!tty_unthrottle_safe(tty))
break;
}
__tty_set_flow_change(tty, 0);
if (b - buf >= minimum)
break;
if (time)
timeout = time;
}
mutex_unlock(&ldata->atomic_read_lock);
remove_wait_queue(&tty->read_wait, &wait);
if (!waitqueue_active(&tty->read_wait))
tty->minimum_to_wake = minimum;
__set_current_state(TASK_RUNNING);
size = b - buf;
if (size) {
retval = size;
if (nr)
clear_bit(TTY_PUSH, &tty->flags);
} else if (test_and_clear_bit(TTY_PUSH, &tty->flags))
goto do_it_again;
n_tty_set_room(tty);
return retval;
}
/**
* n_tty_write - write function for tty
* @tty: tty device
* @file: file object
* @buf: userspace buffer pointer
* @nr: size of I/O
*
* Write function of the terminal device. This is serialized with
* respect to other write callers but not to termios changes, reads
* and other such events. Since the receive code will echo characters,
* thus calling driver write methods, the output_lock is used in
* the output processing functions called here as well as in the
* echo processing function to protect the column state and space
* left in the buffer.
*
* This code must be sure never to sleep through a hangup.
*
* Locking: output_lock to protect column state and space left
* (note that the process_output*() functions take this
* lock themselves)
*/
static ssize_t n_tty_write(struct tty_struct *tty, struct file *file,
const unsigned char *buf, size_t nr)
{
const unsigned char *b = buf;
DECLARE_WAITQUEUE(wait, current);
int c;
ssize_t retval = 0;
/* Job control check -- must be done at start (POSIX.1 7.1.1.4). */
if (L_TOSTOP(tty) && file->f_op->write != redirected_tty_write) {
retval = tty_check_change(tty);
if (retval)
return retval;
}
/* Write out any echoed characters that are still pending */
process_echoes(tty);
add_wait_queue(&tty->write_wait, &wait);
while (1) {
set_current_state(TASK_INTERRUPTIBLE);
if (signal_pending(current)) {
retval = -ERESTARTSYS;
break;
}
if (tty_hung_up_p(file) || (tty->link && !tty->link->count)) {
retval = -EIO;
break;
}
if (O_OPOST(tty) && !(test_bit(TTY_HW_COOK_OUT, &tty->flags))) {
while (nr > 0) {
ssize_t num = process_output_block(tty, b, nr);
if (num < 0) {
if (num == -EAGAIN)
break;
retval = num;
goto break_out;
}
b += num;
nr -= num;
if (nr == 0)
break;
c = *b;
if (process_output(c, tty) < 0)
break;
b++; nr--;
}
if (tty->ops->flush_chars)
tty->ops->flush_chars(tty);
} else {
struct n_tty_data *ldata = tty->disc_data;
while (nr > 0) {
mutex_lock(&ldata->output_lock);
c = tty->ops->write(tty, b, nr);
mutex_unlock(&ldata->output_lock);
if (c < 0) {
retval = c;
goto break_out;
}
if (!c)
break;
b += c;
nr -= c;
}
}
if (!nr)
break;
if (file->f_flags & O_NONBLOCK) {
retval = -EAGAIN;
break;
}
schedule();
}
break_out:
__set_current_state(TASK_RUNNING);
remove_wait_queue(&tty->write_wait, &wait);
if (b - buf != nr && tty->fasync)
set_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
return (b - buf) ? b - buf : retval;
}
/**
* n_tty_poll - poll method for N_TTY
* @tty: terminal device
* @file: file accessing it
* @wait: poll table
*
* Called when the line discipline is asked to poll() for data or
* for special events. This code is not serialized with respect to
* other events save open/close.
*
* This code must be sure never to sleep through a hangup.
* Called without the kernel lock held - fine
*/
static unsigned int n_tty_poll(struct tty_struct *tty, struct file *file,
poll_table *wait)
{
unsigned int mask = 0;
poll_wait(file, &tty->read_wait, wait);
poll_wait(file, &tty->write_wait, wait);
if (input_available_p(tty, TIME_CHAR(tty) ? 0 : MIN_CHAR(tty)))
mask |= POLLIN | POLLRDNORM;
if (tty->packet && tty->link->ctrl_status)
mask |= POLLPRI | POLLIN | POLLRDNORM;
if (test_bit(TTY_OTHER_CLOSED, &tty->flags))
mask |= POLLHUP;
if (tty_hung_up_p(file))
mask |= POLLHUP;
if (!(mask & (POLLHUP | POLLIN | POLLRDNORM))) {
if (MIN_CHAR(tty) && !TIME_CHAR(tty))
tty->minimum_to_wake = MIN_CHAR(tty);
else
tty->minimum_to_wake = 1;
}
if (tty->ops->write && !tty_is_writelocked(tty) &&
tty_chars_in_buffer(tty) < WAKEUP_CHARS &&
tty_write_room(tty) > 0)
mask |= POLLOUT | POLLWRNORM;
return mask;
}
static unsigned long inq_canon(struct n_tty_data *ldata)
{
int nr, head, tail;
if (!ldata->canon_data)
return 0;
head = ldata->canon_head;
tail = ldata->read_tail;
nr = (head - tail) & (N_TTY_BUF_SIZE-1);
/* Skip EOF-chars.. */
while (head != tail) {
if (test_bit(tail, ldata->read_flags) &&
ldata->read_buf[tail] == __DISABLED_CHAR)
nr--;
tail = (tail+1) & (N_TTY_BUF_SIZE-1);
}
return nr;
}
static int n_tty_ioctl(struct tty_struct *tty, struct file *file,
unsigned int cmd, unsigned long arg)
{
struct n_tty_data *ldata = tty->disc_data;
int retval;
switch (cmd) {
case TIOCOUTQ:
return put_user(tty_chars_in_buffer(tty), (int __user *) arg);
case TIOCINQ:
/* FIXME: Locking */
retval = ldata->read_cnt;
if (L_ICANON(tty))
retval = inq_canon(ldata);
return put_user(retval, (unsigned int __user *) arg);
default:
return n_tty_ioctl_helper(tty, file, cmd, arg);
}
}
struct tty_ldisc_ops tty_ldisc_N_TTY = {
.magic = TTY_LDISC_MAGIC,
.name = "n_tty",
.open = n_tty_open,
.close = n_tty_close,
.flush_buffer = n_tty_flush_buffer,
.chars_in_buffer = n_tty_chars_in_buffer,
.read = n_tty_read,
.write = n_tty_write,
.ioctl = n_tty_ioctl,
.set_termios = n_tty_set_termios,
.poll = n_tty_poll,
.receive_buf = n_tty_receive_buf,
.write_wakeup = n_tty_write_wakeup
};
/**
* n_tty_inherit_ops - inherit N_TTY methods
* @ops: struct tty_ldisc_ops where to save N_TTY methods
*
* Enables a 'subclass' line discipline to 'inherit' N_TTY
* methods.
*/
void n_tty_inherit_ops(struct tty_ldisc_ops *ops)
{
*ops = tty_ldisc_N_TTY;
ops->owner = NULL;
ops->refcount = ops->flags = 0;
}
EXPORT_SYMBOL_GPL(n_tty_inherit_ops);
| gpl-2.0 |
cyjia/linux | drivers/scsi/qla4xxx/ql4_mbx.c | 1634 | 73729 | /*
* QLogic iSCSI HBA Driver
* Copyright (c) 2003-2013 QLogic Corporation
*
* See LICENSE.qla4xxx for copyright and licensing details.
*/
#include <linux/ctype.h>
#include "ql4_def.h"
#include "ql4_glbl.h"
#include "ql4_dbg.h"
#include "ql4_inline.h"
#include "ql4_version.h"
void qla4xxx_queue_mbox_cmd(struct scsi_qla_host *ha, uint32_t *mbx_cmd,
int in_count)
{
int i;
/* Load all mailbox registers, except mailbox 0. */
for (i = 1; i < in_count; i++)
writel(mbx_cmd[i], &ha->reg->mailbox[i]);
/* Wakeup firmware */
writel(mbx_cmd[0], &ha->reg->mailbox[0]);
readl(&ha->reg->mailbox[0]);
writel(set_rmask(CSR_INTR_RISC), &ha->reg->ctrl_status);
readl(&ha->reg->ctrl_status);
}
void qla4xxx_process_mbox_intr(struct scsi_qla_host *ha, int out_count)
{
int intr_status;
intr_status = readl(&ha->reg->ctrl_status);
if (intr_status & INTR_PENDING) {
/*
* Service the interrupt.
* The ISR will save the mailbox status registers
* to a temporary storage location in the adapter structure.
*/
ha->mbox_status_count = out_count;
ha->isp_ops->interrupt_service_routine(ha, intr_status);
}
}
/**
* qla4xxx_is_intr_poll_mode – Are we allowed to poll for interrupts?
* @ha: Pointer to host adapter structure.
* @ret: 1=polling mode, 0=non-polling mode
**/
static int qla4xxx_is_intr_poll_mode(struct scsi_qla_host *ha)
{
int rval = 1;
if (is_qla8032(ha) || is_qla8042(ha)) {
if (test_bit(AF_IRQ_ATTACHED, &ha->flags) &&
test_bit(AF_83XX_MBOX_INTR_ON, &ha->flags))
rval = 0;
} else {
if (test_bit(AF_IRQ_ATTACHED, &ha->flags) &&
test_bit(AF_INTERRUPTS_ON, &ha->flags) &&
test_bit(AF_ONLINE, &ha->flags) &&
!test_bit(AF_HA_REMOVAL, &ha->flags))
rval = 0;
}
return rval;
}
/**
* qla4xxx_mailbox_command - issues mailbox commands
* @ha: Pointer to host adapter structure.
* @inCount: number of mailbox registers to load.
* @outCount: number of mailbox registers to return.
* @mbx_cmd: data pointer for mailbox in registers.
* @mbx_sts: data pointer for mailbox out registers.
*
* This routine issue mailbox commands and waits for completion.
* If outCount is 0, this routine completes successfully WITHOUT waiting
* for the mailbox command to complete.
**/
int qla4xxx_mailbox_command(struct scsi_qla_host *ha, uint8_t inCount,
uint8_t outCount, uint32_t *mbx_cmd,
uint32_t *mbx_sts)
{
int status = QLA_ERROR;
uint8_t i;
u_long wait_count;
unsigned long flags = 0;
uint32_t dev_state;
/* Make sure that pointers are valid */
if (!mbx_cmd || !mbx_sts) {
DEBUG2(printk("scsi%ld: %s: Invalid mbx_cmd or mbx_sts "
"pointer\n", ha->host_no, __func__));
return status;
}
if (is_qla40XX(ha)) {
if (test_bit(AF_HA_REMOVAL, &ha->flags)) {
DEBUG2(ql4_printk(KERN_WARNING, ha, "scsi%ld: %s: "
"prematurely completing mbx cmd as "
"adapter removal detected\n",
ha->host_no, __func__));
return status;
}
}
if ((is_aer_supported(ha)) &&
(test_bit(AF_PCI_CHANNEL_IO_PERM_FAILURE, &ha->flags))) {
DEBUG2(printk(KERN_WARNING "scsi%ld: %s: Perm failure on EEH, "
"timeout MBX Exiting.\n", ha->host_no, __func__));
return status;
}
/* Mailbox code active */
wait_count = MBOX_TOV * 100;
while (wait_count--) {
mutex_lock(&ha->mbox_sem);
if (!test_bit(AF_MBOX_COMMAND, &ha->flags)) {
set_bit(AF_MBOX_COMMAND, &ha->flags);
mutex_unlock(&ha->mbox_sem);
break;
}
mutex_unlock(&ha->mbox_sem);
if (!wait_count) {
DEBUG2(printk("scsi%ld: %s: mbox_sem failed\n",
ha->host_no, __func__));
return status;
}
msleep(10);
}
if (is_qla80XX(ha)) {
if (test_bit(AF_FW_RECOVERY, &ha->flags)) {
DEBUG2(ql4_printk(KERN_WARNING, ha,
"scsi%ld: %s: prematurely completing mbx cmd as firmware recovery detected\n",
ha->host_no, __func__));
goto mbox_exit;
}
/* Do not send any mbx cmd if h/w is in failed state*/
ha->isp_ops->idc_lock(ha);
dev_state = qla4_8xxx_rd_direct(ha, QLA8XXX_CRB_DEV_STATE);
ha->isp_ops->idc_unlock(ha);
if (dev_state == QLA8XXX_DEV_FAILED) {
ql4_printk(KERN_WARNING, ha,
"scsi%ld: %s: H/W is in failed state, do not send any mailbox commands\n",
ha->host_no, __func__);
goto mbox_exit;
}
}
spin_lock_irqsave(&ha->hardware_lock, flags);
ha->mbox_status_count = outCount;
for (i = 0; i < outCount; i++)
ha->mbox_status[i] = 0;
/* Queue the mailbox command to the firmware */
ha->isp_ops->queue_mailbox_command(ha, mbx_cmd, inCount);
spin_unlock_irqrestore(&ha->hardware_lock, flags);
/* Wait for completion */
/*
* If we don't want status, don't wait for the mailbox command to
* complete. For example, MBOX_CMD_RESET_FW doesn't return status,
* you must poll the inbound Interrupt Mask for completion.
*/
if (outCount == 0) {
status = QLA_SUCCESS;
goto mbox_exit;
}
/*
* Wait for completion: Poll or completion queue
*/
if (qla4xxx_is_intr_poll_mode(ha)) {
/* Poll for command to complete */
wait_count = jiffies + MBOX_TOV * HZ;
while (test_bit(AF_MBOX_COMMAND_DONE, &ha->flags) == 0) {
if (time_after_eq(jiffies, wait_count))
break;
/*
* Service the interrupt.
* The ISR will save the mailbox status registers
* to a temporary storage location in the adapter
* structure.
*/
spin_lock_irqsave(&ha->hardware_lock, flags);
ha->isp_ops->process_mailbox_interrupt(ha, outCount);
spin_unlock_irqrestore(&ha->hardware_lock, flags);
msleep(10);
}
} else {
/* Do not poll for completion. Use completion queue */
set_bit(AF_MBOX_COMMAND_NOPOLL, &ha->flags);
wait_for_completion_timeout(&ha->mbx_intr_comp, MBOX_TOV * HZ);
clear_bit(AF_MBOX_COMMAND_NOPOLL, &ha->flags);
}
/* Check for mailbox timeout. */
if (!test_bit(AF_MBOX_COMMAND_DONE, &ha->flags)) {
if (is_qla80XX(ha) &&
test_bit(AF_FW_RECOVERY, &ha->flags)) {
DEBUG2(ql4_printk(KERN_INFO, ha,
"scsi%ld: %s: prematurely completing mbx cmd as "
"firmware recovery detected\n",
ha->host_no, __func__));
goto mbox_exit;
}
ql4_printk(KERN_WARNING, ha, "scsi%ld: Mailbox Cmd 0x%08X timed out, Scheduling Adapter Reset\n",
ha->host_no, mbx_cmd[0]);
ha->mailbox_timeout_count++;
mbx_sts[0] = (-1);
set_bit(DPC_RESET_HA, &ha->dpc_flags);
if (is_qla8022(ha)) {
ql4_printk(KERN_INFO, ha,
"disabling pause transmit on port 0 & 1.\n");
qla4_82xx_wr_32(ha, QLA82XX_CRB_NIU + 0x98,
CRB_NIU_XG_PAUSE_CTL_P0 |
CRB_NIU_XG_PAUSE_CTL_P1);
} else if (is_qla8032(ha) || is_qla8042(ha)) {
ql4_printk(KERN_INFO, ha, " %s: disabling pause transmit on port 0 & 1.\n",
__func__);
qla4_83xx_disable_pause(ha);
}
goto mbox_exit;
}
/*
* Copy the mailbox out registers to the caller's mailbox in/out
* structure.
*/
spin_lock_irqsave(&ha->hardware_lock, flags);
for (i = 0; i < outCount; i++)
mbx_sts[i] = ha->mbox_status[i];
/* Set return status and error flags (if applicable). */
switch (ha->mbox_status[0]) {
case MBOX_STS_COMMAND_COMPLETE:
status = QLA_SUCCESS;
break;
case MBOX_STS_INTERMEDIATE_COMPLETION:
status = QLA_SUCCESS;
break;
case MBOX_STS_BUSY:
ql4_printk(KERN_WARNING, ha, "scsi%ld: %s: Cmd = %08X, ISP BUSY\n",
ha->host_no, __func__, mbx_cmd[0]);
ha->mailbox_timeout_count++;
break;
default:
ql4_printk(KERN_WARNING, ha, "scsi%ld: %s: FAILED, MBOX CMD = %08X, MBOX STS = %08X %08X %08X %08X %08X %08X %08X %08X\n",
ha->host_no, __func__, mbx_cmd[0], mbx_sts[0],
mbx_sts[1], mbx_sts[2], mbx_sts[3], mbx_sts[4],
mbx_sts[5], mbx_sts[6], mbx_sts[7]);
break;
}
spin_unlock_irqrestore(&ha->hardware_lock, flags);
mbox_exit:
mutex_lock(&ha->mbox_sem);
clear_bit(AF_MBOX_COMMAND, &ha->flags);
mutex_unlock(&ha->mbox_sem);
clear_bit(AF_MBOX_COMMAND_DONE, &ha->flags);
return status;
}
/**
* qla4xxx_get_minidump_template - Get the firmware template
* @ha: Pointer to host adapter structure.
* @phys_addr: dma address for template
*
* Obtain the minidump template from firmware during initialization
* as it may not be available when minidump is desired.
**/
int qla4xxx_get_minidump_template(struct scsi_qla_host *ha,
dma_addr_t phys_addr)
{
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
int status;
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
mbox_cmd[0] = MBOX_CMD_MINIDUMP;
mbox_cmd[1] = MINIDUMP_GET_TMPLT_SUBCOMMAND;
mbox_cmd[2] = LSDW(phys_addr);
mbox_cmd[3] = MSDW(phys_addr);
mbox_cmd[4] = ha->fw_dump_tmplt_size;
mbox_cmd[5] = 0;
status = qla4xxx_mailbox_command(ha, MBOX_REG_COUNT, 2, &mbox_cmd[0],
&mbox_sts[0]);
if (status != QLA_SUCCESS) {
DEBUG2(ql4_printk(KERN_INFO, ha,
"scsi%ld: %s: Cmd = %08X, mbx[0] = 0x%04x, mbx[1] = 0x%04x\n",
ha->host_no, __func__, mbox_cmd[0],
mbox_sts[0], mbox_sts[1]));
}
return status;
}
/**
* qla4xxx_req_template_size - Get minidump template size from firmware.
* @ha: Pointer to host adapter structure.
**/
int qla4xxx_req_template_size(struct scsi_qla_host *ha)
{
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
int status;
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
mbox_cmd[0] = MBOX_CMD_MINIDUMP;
mbox_cmd[1] = MINIDUMP_GET_SIZE_SUBCOMMAND;
status = qla4xxx_mailbox_command(ha, MBOX_REG_COUNT, 8, &mbox_cmd[0],
&mbox_sts[0]);
if (status == QLA_SUCCESS) {
ha->fw_dump_tmplt_size = mbox_sts[1];
DEBUG2(ql4_printk(KERN_INFO, ha,
"%s: sts[0]=0x%04x, template size=0x%04x, size_cm_02=0x%04x, size_cm_04=0x%04x, size_cm_08=0x%04x, size_cm_10=0x%04x, size_cm_FF=0x%04x, version=0x%04x\n",
__func__, mbox_sts[0], mbox_sts[1],
mbox_sts[2], mbox_sts[3], mbox_sts[4],
mbox_sts[5], mbox_sts[6], mbox_sts[7]));
if (ha->fw_dump_tmplt_size == 0)
status = QLA_ERROR;
} else {
ql4_printk(KERN_WARNING, ha,
"%s: Error sts[0]=0x%04x, mbx[1]=0x%04x\n",
__func__, mbox_sts[0], mbox_sts[1]);
status = QLA_ERROR;
}
return status;
}
void qla4xxx_mailbox_premature_completion(struct scsi_qla_host *ha)
{
set_bit(AF_FW_RECOVERY, &ha->flags);
ql4_printk(KERN_INFO, ha, "scsi%ld: %s: set FW RECOVERY!\n",
ha->host_no, __func__);
if (test_bit(AF_MBOX_COMMAND, &ha->flags)) {
if (test_bit(AF_MBOX_COMMAND_NOPOLL, &ha->flags)) {
complete(&ha->mbx_intr_comp);
ql4_printk(KERN_INFO, ha, "scsi%ld: %s: Due to fw "
"recovery, doing premature completion of "
"mbx cmd\n", ha->host_no, __func__);
} else {
set_bit(AF_MBOX_COMMAND_DONE, &ha->flags);
ql4_printk(KERN_INFO, ha, "scsi%ld: %s: Due to fw "
"recovery, doing premature completion of "
"polling mbx cmd\n", ha->host_no, __func__);
}
}
}
static uint8_t
qla4xxx_set_ifcb(struct scsi_qla_host *ha, uint32_t *mbox_cmd,
uint32_t *mbox_sts, dma_addr_t init_fw_cb_dma)
{
memset(mbox_cmd, 0, sizeof(mbox_cmd[0]) * MBOX_REG_COUNT);
memset(mbox_sts, 0, sizeof(mbox_sts[0]) * MBOX_REG_COUNT);
if (is_qla8022(ha))
qla4_82xx_wr_32(ha, ha->nx_db_wr_ptr, 0);
mbox_cmd[0] = MBOX_CMD_INITIALIZE_FIRMWARE;
mbox_cmd[1] = 0;
mbox_cmd[2] = LSDW(init_fw_cb_dma);
mbox_cmd[3] = MSDW(init_fw_cb_dma);
mbox_cmd[4] = sizeof(struct addr_ctrl_blk);
if (qla4xxx_mailbox_command(ha, 6, 6, mbox_cmd, mbox_sts) !=
QLA_SUCCESS) {
DEBUG2(printk(KERN_WARNING "scsi%ld: %s: "
"MBOX_CMD_INITIALIZE_FIRMWARE"
" failed w/ status %04X\n",
ha->host_no, __func__, mbox_sts[0]));
return QLA_ERROR;
}
return QLA_SUCCESS;
}
uint8_t
qla4xxx_get_ifcb(struct scsi_qla_host *ha, uint32_t *mbox_cmd,
uint32_t *mbox_sts, dma_addr_t init_fw_cb_dma)
{
memset(mbox_cmd, 0, sizeof(mbox_cmd[0]) * MBOX_REG_COUNT);
memset(mbox_sts, 0, sizeof(mbox_sts[0]) * MBOX_REG_COUNT);
mbox_cmd[0] = MBOX_CMD_GET_INIT_FW_CTRL_BLOCK;
mbox_cmd[2] = LSDW(init_fw_cb_dma);
mbox_cmd[3] = MSDW(init_fw_cb_dma);
mbox_cmd[4] = sizeof(struct addr_ctrl_blk);
if (qla4xxx_mailbox_command(ha, 5, 5, mbox_cmd, mbox_sts) !=
QLA_SUCCESS) {
DEBUG2(printk(KERN_WARNING "scsi%ld: %s: "
"MBOX_CMD_GET_INIT_FW_CTRL_BLOCK"
" failed w/ status %04X\n",
ha->host_no, __func__, mbox_sts[0]));
return QLA_ERROR;
}
return QLA_SUCCESS;
}
uint8_t qla4xxx_set_ipaddr_state(uint8_t fw_ipaddr_state)
{
uint8_t ipaddr_state;
switch (fw_ipaddr_state) {
case IP_ADDRSTATE_UNCONFIGURED:
ipaddr_state = ISCSI_IPDDRESS_STATE_UNCONFIGURED;
break;
case IP_ADDRSTATE_INVALID:
ipaddr_state = ISCSI_IPDDRESS_STATE_INVALID;
break;
case IP_ADDRSTATE_ACQUIRING:
ipaddr_state = ISCSI_IPDDRESS_STATE_ACQUIRING;
break;
case IP_ADDRSTATE_TENTATIVE:
ipaddr_state = ISCSI_IPDDRESS_STATE_TENTATIVE;
break;
case IP_ADDRSTATE_DEPRICATED:
ipaddr_state = ISCSI_IPDDRESS_STATE_DEPRECATED;
break;
case IP_ADDRSTATE_PREFERRED:
ipaddr_state = ISCSI_IPDDRESS_STATE_VALID;
break;
case IP_ADDRSTATE_DISABLING:
ipaddr_state = ISCSI_IPDDRESS_STATE_DISABLING;
break;
default:
ipaddr_state = ISCSI_IPDDRESS_STATE_UNCONFIGURED;
}
return ipaddr_state;
}
static void
qla4xxx_update_local_ip(struct scsi_qla_host *ha,
struct addr_ctrl_blk *init_fw_cb)
{
ha->ip_config.tcp_options = le16_to_cpu(init_fw_cb->ipv4_tcp_opts);
ha->ip_config.ipv4_options = le16_to_cpu(init_fw_cb->ipv4_ip_opts);
ha->ip_config.ipv4_addr_state =
qla4xxx_set_ipaddr_state(init_fw_cb->ipv4_addr_state);
ha->ip_config.eth_mtu_size =
le16_to_cpu(init_fw_cb->eth_mtu_size);
ha->ip_config.ipv4_port = le16_to_cpu(init_fw_cb->ipv4_port);
if (ha->acb_version == ACB_SUPPORTED) {
ha->ip_config.ipv6_options = le16_to_cpu(init_fw_cb->ipv6_opts);
ha->ip_config.ipv6_addl_options =
le16_to_cpu(init_fw_cb->ipv6_addtl_opts);
ha->ip_config.ipv6_tcp_options =
le16_to_cpu(init_fw_cb->ipv6_tcp_opts);
}
/* Save IPv4 Address Info */
memcpy(ha->ip_config.ip_address, init_fw_cb->ipv4_addr,
min(sizeof(ha->ip_config.ip_address),
sizeof(init_fw_cb->ipv4_addr)));
memcpy(ha->ip_config.subnet_mask, init_fw_cb->ipv4_subnet,
min(sizeof(ha->ip_config.subnet_mask),
sizeof(init_fw_cb->ipv4_subnet)));
memcpy(ha->ip_config.gateway, init_fw_cb->ipv4_gw_addr,
min(sizeof(ha->ip_config.gateway),
sizeof(init_fw_cb->ipv4_gw_addr)));
ha->ip_config.ipv4_vlan_tag = be16_to_cpu(init_fw_cb->ipv4_vlan_tag);
ha->ip_config.control = init_fw_cb->control;
ha->ip_config.tcp_wsf = init_fw_cb->ipv4_tcp_wsf;
ha->ip_config.ipv4_tos = init_fw_cb->ipv4_tos;
ha->ip_config.ipv4_cache_id = init_fw_cb->ipv4_cacheid;
ha->ip_config.ipv4_alt_cid_len = init_fw_cb->ipv4_dhcp_alt_cid_len;
memcpy(ha->ip_config.ipv4_alt_cid, init_fw_cb->ipv4_dhcp_alt_cid,
min(sizeof(ha->ip_config.ipv4_alt_cid),
sizeof(init_fw_cb->ipv4_dhcp_alt_cid)));
ha->ip_config.ipv4_vid_len = init_fw_cb->ipv4_dhcp_vid_len;
memcpy(ha->ip_config.ipv4_vid, init_fw_cb->ipv4_dhcp_vid,
min(sizeof(ha->ip_config.ipv4_vid),
sizeof(init_fw_cb->ipv4_dhcp_vid)));
ha->ip_config.ipv4_ttl = init_fw_cb->ipv4_ttl;
ha->ip_config.def_timeout = le16_to_cpu(init_fw_cb->def_timeout);
ha->ip_config.abort_timer = init_fw_cb->abort_timer;
ha->ip_config.iscsi_options = le16_to_cpu(init_fw_cb->iscsi_opts);
ha->ip_config.iscsi_max_pdu_size =
le16_to_cpu(init_fw_cb->iscsi_max_pdu_size);
ha->ip_config.iscsi_first_burst_len =
le16_to_cpu(init_fw_cb->iscsi_fburst_len);
ha->ip_config.iscsi_max_outstnd_r2t =
le16_to_cpu(init_fw_cb->iscsi_max_outstnd_r2t);
ha->ip_config.iscsi_max_burst_len =
le16_to_cpu(init_fw_cb->iscsi_max_burst_len);
memcpy(ha->ip_config.iscsi_name, init_fw_cb->iscsi_name,
min(sizeof(ha->ip_config.iscsi_name),
sizeof(init_fw_cb->iscsi_name)));
if (is_ipv6_enabled(ha)) {
/* Save IPv6 Address */
ha->ip_config.ipv6_link_local_state =
qla4xxx_set_ipaddr_state(init_fw_cb->ipv6_lnk_lcl_addr_state);
ha->ip_config.ipv6_addr0_state =
qla4xxx_set_ipaddr_state(init_fw_cb->ipv6_addr0_state);
ha->ip_config.ipv6_addr1_state =
qla4xxx_set_ipaddr_state(init_fw_cb->ipv6_addr1_state);
switch (le16_to_cpu(init_fw_cb->ipv6_dflt_rtr_state)) {
case IPV6_RTRSTATE_UNKNOWN:
ha->ip_config.ipv6_default_router_state =
ISCSI_ROUTER_STATE_UNKNOWN;
break;
case IPV6_RTRSTATE_MANUAL:
ha->ip_config.ipv6_default_router_state =
ISCSI_ROUTER_STATE_MANUAL;
break;
case IPV6_RTRSTATE_ADVERTISED:
ha->ip_config.ipv6_default_router_state =
ISCSI_ROUTER_STATE_ADVERTISED;
break;
case IPV6_RTRSTATE_STALE:
ha->ip_config.ipv6_default_router_state =
ISCSI_ROUTER_STATE_STALE;
break;
default:
ha->ip_config.ipv6_default_router_state =
ISCSI_ROUTER_STATE_UNKNOWN;
}
ha->ip_config.ipv6_link_local_addr.in6_u.u6_addr8[0] = 0xFE;
ha->ip_config.ipv6_link_local_addr.in6_u.u6_addr8[1] = 0x80;
memcpy(&ha->ip_config.ipv6_link_local_addr.in6_u.u6_addr8[8],
init_fw_cb->ipv6_if_id,
min(sizeof(ha->ip_config.ipv6_link_local_addr)/2,
sizeof(init_fw_cb->ipv6_if_id)));
memcpy(&ha->ip_config.ipv6_addr0, init_fw_cb->ipv6_addr0,
min(sizeof(ha->ip_config.ipv6_addr0),
sizeof(init_fw_cb->ipv6_addr0)));
memcpy(&ha->ip_config.ipv6_addr1, init_fw_cb->ipv6_addr1,
min(sizeof(ha->ip_config.ipv6_addr1),
sizeof(init_fw_cb->ipv6_addr1)));
memcpy(&ha->ip_config.ipv6_default_router_addr,
init_fw_cb->ipv6_dflt_rtr_addr,
min(sizeof(ha->ip_config.ipv6_default_router_addr),
sizeof(init_fw_cb->ipv6_dflt_rtr_addr)));
ha->ip_config.ipv6_vlan_tag =
be16_to_cpu(init_fw_cb->ipv6_vlan_tag);
ha->ip_config.ipv6_port = le16_to_cpu(init_fw_cb->ipv6_port);
ha->ip_config.ipv6_cache_id = init_fw_cb->ipv6_cache_id;
ha->ip_config.ipv6_flow_lbl =
le16_to_cpu(init_fw_cb->ipv6_flow_lbl);
ha->ip_config.ipv6_traffic_class =
init_fw_cb->ipv6_traffic_class;
ha->ip_config.ipv6_hop_limit = init_fw_cb->ipv6_hop_limit;
ha->ip_config.ipv6_nd_reach_time =
le32_to_cpu(init_fw_cb->ipv6_nd_reach_time);
ha->ip_config.ipv6_nd_rexmit_timer =
le32_to_cpu(init_fw_cb->ipv6_nd_rexmit_timer);
ha->ip_config.ipv6_nd_stale_timeout =
le32_to_cpu(init_fw_cb->ipv6_nd_stale_timeout);
ha->ip_config.ipv6_dup_addr_detect_count =
init_fw_cb->ipv6_dup_addr_detect_count;
ha->ip_config.ipv6_gw_advrt_mtu =
le32_to_cpu(init_fw_cb->ipv6_gw_advrt_mtu);
ha->ip_config.ipv6_tcp_wsf = init_fw_cb->ipv6_tcp_wsf;
}
}
uint8_t
qla4xxx_update_local_ifcb(struct scsi_qla_host *ha,
uint32_t *mbox_cmd,
uint32_t *mbox_sts,
struct addr_ctrl_blk *init_fw_cb,
dma_addr_t init_fw_cb_dma)
{
if (qla4xxx_get_ifcb(ha, mbox_cmd, mbox_sts, init_fw_cb_dma)
!= QLA_SUCCESS) {
DEBUG2(printk(KERN_WARNING
"scsi%ld: %s: Failed to get init_fw_ctrl_blk\n",
ha->host_no, __func__));
return QLA_ERROR;
}
DEBUG2(qla4xxx_dump_buffer(init_fw_cb, sizeof(struct addr_ctrl_blk)));
/* Save some info in adapter structure. */
ha->acb_version = init_fw_cb->acb_version;
ha->firmware_options = le16_to_cpu(init_fw_cb->fw_options);
ha->heartbeat_interval = init_fw_cb->hb_interval;
memcpy(ha->name_string, init_fw_cb->iscsi_name,
min(sizeof(ha->name_string),
sizeof(init_fw_cb->iscsi_name)));
ha->def_timeout = le16_to_cpu(init_fw_cb->def_timeout);
/*memcpy(ha->alias, init_fw_cb->Alias,
min(sizeof(ha->alias), sizeof(init_fw_cb->Alias)));*/
qla4xxx_update_local_ip(ha, init_fw_cb);
return QLA_SUCCESS;
}
/**
* qla4xxx_initialize_fw_cb - initializes firmware control block.
* @ha: Pointer to host adapter structure.
**/
int qla4xxx_initialize_fw_cb(struct scsi_qla_host * ha)
{
struct addr_ctrl_blk *init_fw_cb;
dma_addr_t init_fw_cb_dma;
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
int status = QLA_ERROR;
init_fw_cb = dma_alloc_coherent(&ha->pdev->dev,
sizeof(struct addr_ctrl_blk),
&init_fw_cb_dma, GFP_KERNEL);
if (init_fw_cb == NULL) {
DEBUG2(printk("scsi%ld: %s: Unable to alloc init_cb\n",
ha->host_no, __func__));
goto exit_init_fw_cb_no_free;
}
memset(init_fw_cb, 0, sizeof(struct addr_ctrl_blk));
/* Get Initialize Firmware Control Block. */
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
if (qla4xxx_get_ifcb(ha, &mbox_cmd[0], &mbox_sts[0], init_fw_cb_dma) !=
QLA_SUCCESS) {
dma_free_coherent(&ha->pdev->dev,
sizeof(struct addr_ctrl_blk),
init_fw_cb, init_fw_cb_dma);
goto exit_init_fw_cb;
}
/* Fill in the request and response queue information. */
init_fw_cb->rqq_consumer_idx = cpu_to_le16(ha->request_out);
init_fw_cb->compq_producer_idx = cpu_to_le16(ha->response_in);
init_fw_cb->rqq_len = __constant_cpu_to_le16(REQUEST_QUEUE_DEPTH);
init_fw_cb->compq_len = __constant_cpu_to_le16(RESPONSE_QUEUE_DEPTH);
init_fw_cb->rqq_addr_lo = cpu_to_le32(LSDW(ha->request_dma));
init_fw_cb->rqq_addr_hi = cpu_to_le32(MSDW(ha->request_dma));
init_fw_cb->compq_addr_lo = cpu_to_le32(LSDW(ha->response_dma));
init_fw_cb->compq_addr_hi = cpu_to_le32(MSDW(ha->response_dma));
init_fw_cb->shdwreg_addr_lo = cpu_to_le32(LSDW(ha->shadow_regs_dma));
init_fw_cb->shdwreg_addr_hi = cpu_to_le32(MSDW(ha->shadow_regs_dma));
/* Set up required options. */
init_fw_cb->fw_options |=
__constant_cpu_to_le16(FWOPT_SESSION_MODE |
FWOPT_INITIATOR_MODE);
if (is_qla80XX(ha))
init_fw_cb->fw_options |=
__constant_cpu_to_le16(FWOPT_ENABLE_CRBDB);
init_fw_cb->fw_options &= __constant_cpu_to_le16(~FWOPT_TARGET_MODE);
init_fw_cb->add_fw_options = 0;
init_fw_cb->add_fw_options |=
__constant_cpu_to_le16(ADFWOPT_SERIALIZE_TASK_MGMT);
init_fw_cb->add_fw_options |=
__constant_cpu_to_le16(ADFWOPT_AUTOCONN_DISABLE);
if (qla4xxx_set_ifcb(ha, &mbox_cmd[0], &mbox_sts[0], init_fw_cb_dma)
!= QLA_SUCCESS) {
DEBUG2(printk(KERN_WARNING
"scsi%ld: %s: Failed to set init_fw_ctrl_blk\n",
ha->host_no, __func__));
goto exit_init_fw_cb;
}
if (qla4xxx_update_local_ifcb(ha, &mbox_cmd[0], &mbox_sts[0],
init_fw_cb, init_fw_cb_dma) != QLA_SUCCESS) {
DEBUG2(printk("scsi%ld: %s: Failed to update local ifcb\n",
ha->host_no, __func__));
goto exit_init_fw_cb;
}
status = QLA_SUCCESS;
exit_init_fw_cb:
dma_free_coherent(&ha->pdev->dev, sizeof(struct addr_ctrl_blk),
init_fw_cb, init_fw_cb_dma);
exit_init_fw_cb_no_free:
return status;
}
/**
* qla4xxx_get_dhcp_ip_address - gets HBA ip address via DHCP
* @ha: Pointer to host adapter structure.
**/
int qla4xxx_get_dhcp_ip_address(struct scsi_qla_host * ha)
{
struct addr_ctrl_blk *init_fw_cb;
dma_addr_t init_fw_cb_dma;
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
init_fw_cb = dma_alloc_coherent(&ha->pdev->dev,
sizeof(struct addr_ctrl_blk),
&init_fw_cb_dma, GFP_KERNEL);
if (init_fw_cb == NULL) {
printk("scsi%ld: %s: Unable to alloc init_cb\n", ha->host_no,
__func__);
return QLA_ERROR;
}
/* Get Initialize Firmware Control Block. */
memset(init_fw_cb, 0, sizeof(struct addr_ctrl_blk));
if (qla4xxx_get_ifcb(ha, &mbox_cmd[0], &mbox_sts[0], init_fw_cb_dma) !=
QLA_SUCCESS) {
DEBUG2(printk("scsi%ld: %s: Failed to get init_fw_ctrl_blk\n",
ha->host_no, __func__));
dma_free_coherent(&ha->pdev->dev,
sizeof(struct addr_ctrl_blk),
init_fw_cb, init_fw_cb_dma);
return QLA_ERROR;
}
/* Save IP Address. */
qla4xxx_update_local_ip(ha, init_fw_cb);
dma_free_coherent(&ha->pdev->dev, sizeof(struct addr_ctrl_blk),
init_fw_cb, init_fw_cb_dma);
return QLA_SUCCESS;
}
/**
* qla4xxx_get_firmware_state - gets firmware state of HBA
* @ha: Pointer to host adapter structure.
**/
int qla4xxx_get_firmware_state(struct scsi_qla_host * ha)
{
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
/* Get firmware version */
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
mbox_cmd[0] = MBOX_CMD_GET_FW_STATE;
if (qla4xxx_mailbox_command(ha, MBOX_REG_COUNT, 4, &mbox_cmd[0], &mbox_sts[0]) !=
QLA_SUCCESS) {
DEBUG2(printk("scsi%ld: %s: MBOX_CMD_GET_FW_STATE failed w/ "
"status %04X\n", ha->host_no, __func__,
mbox_sts[0]));
return QLA_ERROR;
}
ha->firmware_state = mbox_sts[1];
ha->board_id = mbox_sts[2];
ha->addl_fw_state = mbox_sts[3];
DEBUG2(printk("scsi%ld: %s firmware_state=0x%x\n",
ha->host_no, __func__, ha->firmware_state);)
return QLA_SUCCESS;
}
/**
* qla4xxx_get_firmware_status - retrieves firmware status
* @ha: Pointer to host adapter structure.
**/
int qla4xxx_get_firmware_status(struct scsi_qla_host * ha)
{
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
/* Get firmware version */
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
mbox_cmd[0] = MBOX_CMD_GET_FW_STATUS;
if (qla4xxx_mailbox_command(ha, MBOX_REG_COUNT, 3, &mbox_cmd[0], &mbox_sts[0]) !=
QLA_SUCCESS) {
DEBUG2(printk("scsi%ld: %s: MBOX_CMD_GET_FW_STATUS failed w/ "
"status %04X\n", ha->host_no, __func__,
mbox_sts[0]));
return QLA_ERROR;
}
/* High-water mark of IOCBs */
ha->iocb_hiwat = mbox_sts[2];
DEBUG2(ql4_printk(KERN_INFO, ha,
"%s: firmware IOCBs available = %d\n", __func__,
ha->iocb_hiwat));
if (ha->iocb_hiwat > IOCB_HIWAT_CUSHION)
ha->iocb_hiwat -= IOCB_HIWAT_CUSHION;
/* Ideally, we should not enter this code, as the # of firmware
* IOCBs is hard-coded in the firmware. We set a default
* iocb_hiwat here just in case */
if (ha->iocb_hiwat == 0) {
ha->iocb_hiwat = REQUEST_QUEUE_DEPTH / 4;
DEBUG2(ql4_printk(KERN_WARNING, ha,
"%s: Setting IOCB's to = %d\n", __func__,
ha->iocb_hiwat));
}
return QLA_SUCCESS;
}
/**
* qla4xxx_get_fwddb_entry - retrieves firmware ddb entry
* @ha: Pointer to host adapter structure.
* @fw_ddb_index: Firmware's device database index
* @fw_ddb_entry: Pointer to firmware's device database entry structure
* @num_valid_ddb_entries: Pointer to number of valid ddb entries
* @next_ddb_index: Pointer to next valid device database index
* @fw_ddb_device_state: Pointer to device state
**/
int qla4xxx_get_fwddb_entry(struct scsi_qla_host *ha,
uint16_t fw_ddb_index,
struct dev_db_entry *fw_ddb_entry,
dma_addr_t fw_ddb_entry_dma,
uint32_t *num_valid_ddb_entries,
uint32_t *next_ddb_index,
uint32_t *fw_ddb_device_state,
uint32_t *conn_err_detail,
uint16_t *tcp_source_port_num,
uint16_t *connection_id)
{
int status = QLA_ERROR;
uint16_t options;
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
/* Make sure the device index is valid */
if (fw_ddb_index >= MAX_DDB_ENTRIES) {
DEBUG2(printk("scsi%ld: %s: ddb [%d] out of range.\n",
ha->host_no, __func__, fw_ddb_index));
goto exit_get_fwddb;
}
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
if (fw_ddb_entry)
memset(fw_ddb_entry, 0, sizeof(struct dev_db_entry));
mbox_cmd[0] = MBOX_CMD_GET_DATABASE_ENTRY;
mbox_cmd[1] = (uint32_t) fw_ddb_index;
mbox_cmd[2] = LSDW(fw_ddb_entry_dma);
mbox_cmd[3] = MSDW(fw_ddb_entry_dma);
mbox_cmd[4] = sizeof(struct dev_db_entry);
if (qla4xxx_mailbox_command(ha, MBOX_REG_COUNT, 7, &mbox_cmd[0], &mbox_sts[0]) ==
QLA_ERROR) {
DEBUG2(printk("scsi%ld: %s: MBOX_CMD_GET_DATABASE_ENTRY failed"
" with status 0x%04X\n", ha->host_no, __func__,
mbox_sts[0]));
goto exit_get_fwddb;
}
if (fw_ddb_index != mbox_sts[1]) {
DEBUG2(printk("scsi%ld: %s: ddb mismatch [%d] != [%d].\n",
ha->host_no, __func__, fw_ddb_index,
mbox_sts[1]));
goto exit_get_fwddb;
}
if (fw_ddb_entry) {
options = le16_to_cpu(fw_ddb_entry->options);
if (options & DDB_OPT_IPV6_DEVICE) {
ql4_printk(KERN_INFO, ha, "%s: DDB[%d] MB0 %04x Tot %d "
"Next %d State %04x ConnErr %08x %pI6 "
":%04d \"%s\"\n", __func__, fw_ddb_index,
mbox_sts[0], mbox_sts[2], mbox_sts[3],
mbox_sts[4], mbox_sts[5],
fw_ddb_entry->ip_addr,
le16_to_cpu(fw_ddb_entry->port),
fw_ddb_entry->iscsi_name);
} else {
ql4_printk(KERN_INFO, ha, "%s: DDB[%d] MB0 %04x Tot %d "
"Next %d State %04x ConnErr %08x %pI4 "
":%04d \"%s\"\n", __func__, fw_ddb_index,
mbox_sts[0], mbox_sts[2], mbox_sts[3],
mbox_sts[4], mbox_sts[5],
fw_ddb_entry->ip_addr,
le16_to_cpu(fw_ddb_entry->port),
fw_ddb_entry->iscsi_name);
}
}
if (num_valid_ddb_entries)
*num_valid_ddb_entries = mbox_sts[2];
if (next_ddb_index)
*next_ddb_index = mbox_sts[3];
if (fw_ddb_device_state)
*fw_ddb_device_state = mbox_sts[4];
/*
* RA: This mailbox has been changed to pass connection error and
* details. Its true for ISP4010 as per Version E - Not sure when it
* was changed. Get the time2wait from the fw_dd_entry field :
* default_time2wait which we call it as minTime2Wait DEV_DB_ENTRY
* struct.
*/
if (conn_err_detail)
*conn_err_detail = mbox_sts[5];
if (tcp_source_port_num)
*tcp_source_port_num = (uint16_t) (mbox_sts[6] >> 16);
if (connection_id)
*connection_id = (uint16_t) mbox_sts[6] & 0x00FF;
status = QLA_SUCCESS;
exit_get_fwddb:
return status;
}
int qla4xxx_conn_open(struct scsi_qla_host *ha, uint16_t fw_ddb_index)
{
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
int status;
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
mbox_cmd[0] = MBOX_CMD_CONN_OPEN;
mbox_cmd[1] = fw_ddb_index;
status = qla4xxx_mailbox_command(ha, MBOX_REG_COUNT, 2, &mbox_cmd[0],
&mbox_sts[0]);
DEBUG2(ql4_printk(KERN_INFO, ha,
"%s: status = %d mbx0 = 0x%x mbx1 = 0x%x\n",
__func__, status, mbox_sts[0], mbox_sts[1]));
return status;
}
/**
* qla4xxx_set_fwddb_entry - sets a ddb entry.
* @ha: Pointer to host adapter structure.
* @fw_ddb_index: Firmware's device database index
* @fw_ddb_entry_dma: dma address of ddb entry
* @mbx_sts: mailbox 0 to be returned or NULL
*
* This routine initializes or updates the adapter's device database
* entry for the specified device.
**/
int qla4xxx_set_ddb_entry(struct scsi_qla_host * ha, uint16_t fw_ddb_index,
dma_addr_t fw_ddb_entry_dma, uint32_t *mbx_sts)
{
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
int status;
/* Do not wait for completion. The firmware will send us an
* ASTS_DATABASE_CHANGED (0x8014) to notify us of the login status.
*/
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
mbox_cmd[0] = MBOX_CMD_SET_DATABASE_ENTRY;
mbox_cmd[1] = (uint32_t) fw_ddb_index;
mbox_cmd[2] = LSDW(fw_ddb_entry_dma);
mbox_cmd[3] = MSDW(fw_ddb_entry_dma);
mbox_cmd[4] = sizeof(struct dev_db_entry);
status = qla4xxx_mailbox_command(ha, MBOX_REG_COUNT, 5, &mbox_cmd[0],
&mbox_sts[0]);
if (mbx_sts)
*mbx_sts = mbox_sts[0];
DEBUG2(printk("scsi%ld: %s: status=%d mbx0=0x%x mbx4=0x%x\n",
ha->host_no, __func__, status, mbox_sts[0], mbox_sts[4]);)
return status;
}
int qla4xxx_session_logout_ddb(struct scsi_qla_host *ha,
struct ddb_entry *ddb_entry, int options)
{
int status;
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
mbox_cmd[0] = MBOX_CMD_CONN_CLOSE_SESS_LOGOUT;
mbox_cmd[1] = ddb_entry->fw_ddb_index;
mbox_cmd[3] = options;
status = qla4xxx_mailbox_command(ha, MBOX_REG_COUNT, 2, &mbox_cmd[0],
&mbox_sts[0]);
if (status != QLA_SUCCESS) {
DEBUG2(ql4_printk(KERN_INFO, ha,
"%s: MBOX_CMD_CONN_CLOSE_SESS_LOGOUT "
"failed sts %04X %04X", __func__,
mbox_sts[0], mbox_sts[1]));
if ((mbox_sts[0] == MBOX_STS_COMMAND_ERROR) &&
(mbox_sts[1] == DDB_NOT_LOGGED_IN)) {
set_bit(DDB_CONN_CLOSE_FAILURE, &ddb_entry->flags);
}
}
return status;
}
/**
* qla4xxx_get_crash_record - retrieves crash record.
* @ha: Pointer to host adapter structure.
*
* This routine retrieves a crash record from the QLA4010 after an 8002h aen.
**/
void qla4xxx_get_crash_record(struct scsi_qla_host * ha)
{
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
struct crash_record *crash_record = NULL;
dma_addr_t crash_record_dma = 0;
uint32_t crash_record_size = 0;
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_cmd));
/* Get size of crash record. */
mbox_cmd[0] = MBOX_CMD_GET_CRASH_RECORD;
if (qla4xxx_mailbox_command(ha, MBOX_REG_COUNT, 5, &mbox_cmd[0], &mbox_sts[0]) !=
QLA_SUCCESS) {
DEBUG2(printk("scsi%ld: %s: ERROR: Unable to retrieve size!\n",
ha->host_no, __func__));
goto exit_get_crash_record;
}
crash_record_size = mbox_sts[4];
if (crash_record_size == 0) {
DEBUG2(printk("scsi%ld: %s: ERROR: Crash record size is 0!\n",
ha->host_no, __func__));
goto exit_get_crash_record;
}
/* Alloc Memory for Crash Record. */
crash_record = dma_alloc_coherent(&ha->pdev->dev, crash_record_size,
&crash_record_dma, GFP_KERNEL);
if (crash_record == NULL)
goto exit_get_crash_record;
/* Get Crash Record. */
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_cmd));
mbox_cmd[0] = MBOX_CMD_GET_CRASH_RECORD;
mbox_cmd[2] = LSDW(crash_record_dma);
mbox_cmd[3] = MSDW(crash_record_dma);
mbox_cmd[4] = crash_record_size;
if (qla4xxx_mailbox_command(ha, MBOX_REG_COUNT, 5, &mbox_cmd[0], &mbox_sts[0]) !=
QLA_SUCCESS)
goto exit_get_crash_record;
/* Dump Crash Record. */
exit_get_crash_record:
if (crash_record)
dma_free_coherent(&ha->pdev->dev, crash_record_size,
crash_record, crash_record_dma);
}
/**
* qla4xxx_get_conn_event_log - retrieves connection event log
* @ha: Pointer to host adapter structure.
**/
void qla4xxx_get_conn_event_log(struct scsi_qla_host * ha)
{
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
struct conn_event_log_entry *event_log = NULL;
dma_addr_t event_log_dma = 0;
uint32_t event_log_size = 0;
uint32_t num_valid_entries;
uint32_t oldest_entry = 0;
uint32_t max_event_log_entries;
uint8_t i;
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_cmd));
/* Get size of crash record. */
mbox_cmd[0] = MBOX_CMD_GET_CONN_EVENT_LOG;
if (qla4xxx_mailbox_command(ha, MBOX_REG_COUNT, 5, &mbox_cmd[0], &mbox_sts[0]) !=
QLA_SUCCESS)
goto exit_get_event_log;
event_log_size = mbox_sts[4];
if (event_log_size == 0)
goto exit_get_event_log;
/* Alloc Memory for Crash Record. */
event_log = dma_alloc_coherent(&ha->pdev->dev, event_log_size,
&event_log_dma, GFP_KERNEL);
if (event_log == NULL)
goto exit_get_event_log;
/* Get Crash Record. */
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_cmd));
mbox_cmd[0] = MBOX_CMD_GET_CONN_EVENT_LOG;
mbox_cmd[2] = LSDW(event_log_dma);
mbox_cmd[3] = MSDW(event_log_dma);
if (qla4xxx_mailbox_command(ha, MBOX_REG_COUNT, 5, &mbox_cmd[0], &mbox_sts[0]) !=
QLA_SUCCESS) {
DEBUG2(printk("scsi%ld: %s: ERROR: Unable to retrieve event "
"log!\n", ha->host_no, __func__));
goto exit_get_event_log;
}
/* Dump Event Log. */
num_valid_entries = mbox_sts[1];
max_event_log_entries = event_log_size /
sizeof(struct conn_event_log_entry);
if (num_valid_entries > max_event_log_entries)
oldest_entry = num_valid_entries % max_event_log_entries;
DEBUG3(printk("scsi%ld: Connection Event Log Dump (%d entries):\n",
ha->host_no, num_valid_entries));
if (ql4xextended_error_logging == 3) {
if (oldest_entry == 0) {
/* Circular Buffer has not wrapped around */
for (i=0; i < num_valid_entries; i++) {
qla4xxx_dump_buffer((uint8_t *)event_log+
(i*sizeof(*event_log)),
sizeof(*event_log));
}
}
else {
/* Circular Buffer has wrapped around -
* display accordingly*/
for (i=oldest_entry; i < max_event_log_entries; i++) {
qla4xxx_dump_buffer((uint8_t *)event_log+
(i*sizeof(*event_log)),
sizeof(*event_log));
}
for (i=0; i < oldest_entry; i++) {
qla4xxx_dump_buffer((uint8_t *)event_log+
(i*sizeof(*event_log)),
sizeof(*event_log));
}
}
}
exit_get_event_log:
if (event_log)
dma_free_coherent(&ha->pdev->dev, event_log_size, event_log,
event_log_dma);
}
/**
* qla4xxx_abort_task - issues Abort Task
* @ha: Pointer to host adapter structure.
* @srb: Pointer to srb entry
*
* This routine performs a LUN RESET on the specified target/lun.
* The caller must ensure that the ddb_entry and lun_entry pointers
* are valid before calling this routine.
**/
int qla4xxx_abort_task(struct scsi_qla_host *ha, struct srb *srb)
{
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
struct scsi_cmnd *cmd = srb->cmd;
int status = QLA_SUCCESS;
unsigned long flags = 0;
uint32_t index;
/*
* Send abort task command to ISP, so that the ISP will return
* request with ABORT status
*/
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
spin_lock_irqsave(&ha->hardware_lock, flags);
index = (unsigned long)(unsigned char *)cmd->host_scribble;
spin_unlock_irqrestore(&ha->hardware_lock, flags);
/* Firmware already posted completion on response queue */
if (index == MAX_SRBS)
return status;
mbox_cmd[0] = MBOX_CMD_ABORT_TASK;
mbox_cmd[1] = srb->ddb->fw_ddb_index;
mbox_cmd[2] = index;
/* Immediate Command Enable */
mbox_cmd[5] = 0x01;
qla4xxx_mailbox_command(ha, MBOX_REG_COUNT, 5, &mbox_cmd[0],
&mbox_sts[0]);
if (mbox_sts[0] != MBOX_STS_COMMAND_COMPLETE) {
status = QLA_ERROR;
DEBUG2(printk(KERN_WARNING "scsi%ld:%d:%llu: abort task FAILED: "
"mbx0=%04X, mb1=%04X, mb2=%04X, mb3=%04X, mb4=%04X\n",
ha->host_no, cmd->device->id, cmd->device->lun, mbox_sts[0],
mbox_sts[1], mbox_sts[2], mbox_sts[3], mbox_sts[4]));
}
return status;
}
/**
* qla4xxx_reset_lun - issues LUN Reset
* @ha: Pointer to host adapter structure.
* @ddb_entry: Pointer to device database entry
* @lun: lun number
*
* This routine performs a LUN RESET on the specified target/lun.
* The caller must ensure that the ddb_entry and lun_entry pointers
* are valid before calling this routine.
**/
int qla4xxx_reset_lun(struct scsi_qla_host * ha, struct ddb_entry * ddb_entry,
uint64_t lun)
{
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
uint32_t scsi_lun[2];
int status = QLA_SUCCESS;
DEBUG2(printk("scsi%ld:%d:%llu: lun reset issued\n", ha->host_no,
ddb_entry->fw_ddb_index, lun));
/*
* Send lun reset command to ISP, so that the ISP will return all
* outstanding requests with RESET status
*/
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
int_to_scsilun(lun, (struct scsi_lun *) scsi_lun);
mbox_cmd[0] = MBOX_CMD_LUN_RESET;
mbox_cmd[1] = ddb_entry->fw_ddb_index;
/* FW expects LUN bytes 0-3 in Incoming Mailbox 2
* (LUN byte 0 is LSByte, byte 3 is MSByte) */
mbox_cmd[2] = cpu_to_le32(scsi_lun[0]);
/* FW expects LUN bytes 4-7 in Incoming Mailbox 3
* (LUN byte 4 is LSByte, byte 7 is MSByte) */
mbox_cmd[3] = cpu_to_le32(scsi_lun[1]);
mbox_cmd[5] = 0x01; /* Immediate Command Enable */
qla4xxx_mailbox_command(ha, MBOX_REG_COUNT, 1, &mbox_cmd[0], &mbox_sts[0]);
if (mbox_sts[0] != MBOX_STS_COMMAND_COMPLETE &&
mbox_sts[0] != MBOX_STS_COMMAND_ERROR)
status = QLA_ERROR;
return status;
}
/**
* qla4xxx_reset_target - issues target Reset
* @ha: Pointer to host adapter structure.
* @db_entry: Pointer to device database entry
* @un_entry: Pointer to lun entry structure
*
* This routine performs a TARGET RESET on the specified target.
* The caller must ensure that the ddb_entry pointers
* are valid before calling this routine.
**/
int qla4xxx_reset_target(struct scsi_qla_host *ha,
struct ddb_entry *ddb_entry)
{
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
int status = QLA_SUCCESS;
DEBUG2(printk("scsi%ld:%d: target reset issued\n", ha->host_no,
ddb_entry->fw_ddb_index));
/*
* Send target reset command to ISP, so that the ISP will return all
* outstanding requests with RESET status
*/
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
mbox_cmd[0] = MBOX_CMD_TARGET_WARM_RESET;
mbox_cmd[1] = ddb_entry->fw_ddb_index;
mbox_cmd[5] = 0x01; /* Immediate Command Enable */
qla4xxx_mailbox_command(ha, MBOX_REG_COUNT, 1, &mbox_cmd[0],
&mbox_sts[0]);
if (mbox_sts[0] != MBOX_STS_COMMAND_COMPLETE &&
mbox_sts[0] != MBOX_STS_COMMAND_ERROR)
status = QLA_ERROR;
return status;
}
int qla4xxx_get_flash(struct scsi_qla_host * ha, dma_addr_t dma_addr,
uint32_t offset, uint32_t len)
{
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
mbox_cmd[0] = MBOX_CMD_READ_FLASH;
mbox_cmd[1] = LSDW(dma_addr);
mbox_cmd[2] = MSDW(dma_addr);
mbox_cmd[3] = offset;
mbox_cmd[4] = len;
if (qla4xxx_mailbox_command(ha, MBOX_REG_COUNT, 2, &mbox_cmd[0], &mbox_sts[0]) !=
QLA_SUCCESS) {
DEBUG2(printk("scsi%ld: %s: MBOX_CMD_READ_FLASH, failed w/ "
"status %04X %04X, offset %08x, len %08x\n", ha->host_no,
__func__, mbox_sts[0], mbox_sts[1], offset, len));
return QLA_ERROR;
}
return QLA_SUCCESS;
}
/**
* qla4xxx_about_firmware - gets FW, iscsi draft and boot loader version
* @ha: Pointer to host adapter structure.
*
* Retrieves the FW version, iSCSI draft version & bootloader version of HBA.
* Mailboxes 2 & 3 may hold an address for data. Make sure that we write 0 to
* those mailboxes, if unused.
**/
int qla4xxx_about_firmware(struct scsi_qla_host *ha)
{
struct about_fw_info *about_fw = NULL;
dma_addr_t about_fw_dma;
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
int status = QLA_ERROR;
about_fw = dma_alloc_coherent(&ha->pdev->dev,
sizeof(struct about_fw_info),
&about_fw_dma, GFP_KERNEL);
if (!about_fw) {
DEBUG2(ql4_printk(KERN_ERR, ha, "%s: Unable to alloc memory "
"for about_fw\n", __func__));
return status;
}
memset(about_fw, 0, sizeof(struct about_fw_info));
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
mbox_cmd[0] = MBOX_CMD_ABOUT_FW;
mbox_cmd[2] = LSDW(about_fw_dma);
mbox_cmd[3] = MSDW(about_fw_dma);
mbox_cmd[4] = sizeof(struct about_fw_info);
status = qla4xxx_mailbox_command(ha, MBOX_REG_COUNT, MBOX_REG_COUNT,
&mbox_cmd[0], &mbox_sts[0]);
if (status != QLA_SUCCESS) {
DEBUG2(ql4_printk(KERN_WARNING, ha, "%s: MBOX_CMD_ABOUT_FW "
"failed w/ status %04X\n", __func__,
mbox_sts[0]));
goto exit_about_fw;
}
/* Save version information. */
ha->fw_info.fw_major = le16_to_cpu(about_fw->fw_major);
ha->fw_info.fw_minor = le16_to_cpu(about_fw->fw_minor);
ha->fw_info.fw_patch = le16_to_cpu(about_fw->fw_patch);
ha->fw_info.fw_build = le16_to_cpu(about_fw->fw_build);
memcpy(ha->fw_info.fw_build_date, about_fw->fw_build_date,
sizeof(about_fw->fw_build_date));
memcpy(ha->fw_info.fw_build_time, about_fw->fw_build_time,
sizeof(about_fw->fw_build_time));
strcpy((char *)ha->fw_info.fw_build_user,
skip_spaces((char *)about_fw->fw_build_user));
ha->fw_info.fw_load_source = le16_to_cpu(about_fw->fw_load_source);
ha->fw_info.iscsi_major = le16_to_cpu(about_fw->iscsi_major);
ha->fw_info.iscsi_minor = le16_to_cpu(about_fw->iscsi_minor);
ha->fw_info.bootload_major = le16_to_cpu(about_fw->bootload_major);
ha->fw_info.bootload_minor = le16_to_cpu(about_fw->bootload_minor);
ha->fw_info.bootload_patch = le16_to_cpu(about_fw->bootload_patch);
ha->fw_info.bootload_build = le16_to_cpu(about_fw->bootload_build);
strcpy((char *)ha->fw_info.extended_timestamp,
skip_spaces((char *)about_fw->extended_timestamp));
ha->fw_uptime_secs = le32_to_cpu(mbox_sts[5]);
ha->fw_uptime_msecs = le32_to_cpu(mbox_sts[6]);
status = QLA_SUCCESS;
exit_about_fw:
dma_free_coherent(&ha->pdev->dev, sizeof(struct about_fw_info),
about_fw, about_fw_dma);
return status;
}
int qla4xxx_get_default_ddb(struct scsi_qla_host *ha, uint32_t options,
dma_addr_t dma_addr)
{
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
mbox_cmd[0] = MBOX_CMD_GET_DATABASE_ENTRY_DEFAULTS;
mbox_cmd[1] = options;
mbox_cmd[2] = LSDW(dma_addr);
mbox_cmd[3] = MSDW(dma_addr);
if (qla4xxx_mailbox_command(ha, MBOX_REG_COUNT, 1, &mbox_cmd[0], &mbox_sts[0]) !=
QLA_SUCCESS) {
DEBUG2(printk("scsi%ld: %s: failed status %04X\n",
ha->host_no, __func__, mbox_sts[0]));
return QLA_ERROR;
}
return QLA_SUCCESS;
}
int qla4xxx_req_ddb_entry(struct scsi_qla_host *ha, uint32_t ddb_index,
uint32_t *mbx_sts)
{
int status;
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
mbox_cmd[0] = MBOX_CMD_REQUEST_DATABASE_ENTRY;
mbox_cmd[1] = ddb_index;
status = qla4xxx_mailbox_command(ha, MBOX_REG_COUNT, 1, &mbox_cmd[0],
&mbox_sts[0]);
if (status != QLA_SUCCESS) {
DEBUG2(ql4_printk(KERN_ERR, ha, "%s: failed status %04X\n",
__func__, mbox_sts[0]));
}
*mbx_sts = mbox_sts[0];
return status;
}
int qla4xxx_clear_ddb_entry(struct scsi_qla_host *ha, uint32_t ddb_index)
{
int status;
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
mbox_cmd[0] = MBOX_CMD_CLEAR_DATABASE_ENTRY;
mbox_cmd[1] = ddb_index;
status = qla4xxx_mailbox_command(ha, 2, 1, &mbox_cmd[0],
&mbox_sts[0]);
if (status != QLA_SUCCESS) {
DEBUG2(ql4_printk(KERN_ERR, ha, "%s: failed status %04X\n",
__func__, mbox_sts[0]));
}
return status;
}
int qla4xxx_set_flash(struct scsi_qla_host *ha, dma_addr_t dma_addr,
uint32_t offset, uint32_t length, uint32_t options)
{
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
int status = QLA_SUCCESS;
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
mbox_cmd[0] = MBOX_CMD_WRITE_FLASH;
mbox_cmd[1] = LSDW(dma_addr);
mbox_cmd[2] = MSDW(dma_addr);
mbox_cmd[3] = offset;
mbox_cmd[4] = length;
mbox_cmd[5] = options;
status = qla4xxx_mailbox_command(ha, 6, 2, &mbox_cmd[0], &mbox_sts[0]);
if (status != QLA_SUCCESS) {
DEBUG2(ql4_printk(KERN_WARNING, ha, "%s: MBOX_CMD_WRITE_FLASH "
"failed w/ status %04X, mbx1 %04X\n",
__func__, mbox_sts[0], mbox_sts[1]));
}
return status;
}
int qla4xxx_bootdb_by_index(struct scsi_qla_host *ha,
struct dev_db_entry *fw_ddb_entry,
dma_addr_t fw_ddb_entry_dma, uint16_t ddb_index)
{
uint32_t dev_db_start_offset = FLASH_OFFSET_DB_INFO;
uint32_t dev_db_end_offset;
int status = QLA_ERROR;
memset(fw_ddb_entry, 0, sizeof(*fw_ddb_entry));
dev_db_start_offset += (ddb_index * sizeof(*fw_ddb_entry));
dev_db_end_offset = FLASH_OFFSET_DB_END;
if (dev_db_start_offset > dev_db_end_offset) {
DEBUG2(ql4_printk(KERN_ERR, ha,
"%s:Invalid DDB index %d", __func__,
ddb_index));
goto exit_bootdb_failed;
}
if (qla4xxx_get_flash(ha, fw_ddb_entry_dma, dev_db_start_offset,
sizeof(*fw_ddb_entry)) != QLA_SUCCESS) {
ql4_printk(KERN_ERR, ha, "scsi%ld: %s: Get Flash"
"failed\n", ha->host_no, __func__);
goto exit_bootdb_failed;
}
if (fw_ddb_entry->cookie == DDB_VALID_COOKIE)
status = QLA_SUCCESS;
exit_bootdb_failed:
return status;
}
int qla4xxx_flashdb_by_index(struct scsi_qla_host *ha,
struct dev_db_entry *fw_ddb_entry,
dma_addr_t fw_ddb_entry_dma, uint16_t ddb_index)
{
uint32_t dev_db_start_offset;
uint32_t dev_db_end_offset;
int status = QLA_ERROR;
memset(fw_ddb_entry, 0, sizeof(*fw_ddb_entry));
if (is_qla40XX(ha)) {
dev_db_start_offset = FLASH_OFFSET_DB_INFO;
dev_db_end_offset = FLASH_OFFSET_DB_END;
} else {
dev_db_start_offset = FLASH_RAW_ACCESS_ADDR +
(ha->hw.flt_region_ddb << 2);
/* flt_ddb_size is DDB table size for both ports
* so divide it by 2 to calculate the offset for second port
*/
if (ha->port_num == 1)
dev_db_start_offset += (ha->hw.flt_ddb_size / 2);
dev_db_end_offset = dev_db_start_offset +
(ha->hw.flt_ddb_size / 2);
}
dev_db_start_offset += (ddb_index * sizeof(*fw_ddb_entry));
if (dev_db_start_offset > dev_db_end_offset) {
DEBUG2(ql4_printk(KERN_ERR, ha,
"%s:Invalid DDB index %d", __func__,
ddb_index));
goto exit_fdb_failed;
}
if (qla4xxx_get_flash(ha, fw_ddb_entry_dma, dev_db_start_offset,
sizeof(*fw_ddb_entry)) != QLA_SUCCESS) {
ql4_printk(KERN_ERR, ha, "scsi%ld: %s: Get Flash failed\n",
ha->host_no, __func__);
goto exit_fdb_failed;
}
if (fw_ddb_entry->cookie == DDB_VALID_COOKIE)
status = QLA_SUCCESS;
exit_fdb_failed:
return status;
}
int qla4xxx_get_chap(struct scsi_qla_host *ha, char *username, char *password,
uint16_t idx)
{
int ret = 0;
int rval = QLA_ERROR;
uint32_t offset = 0, chap_size;
struct ql4_chap_table *chap_table;
dma_addr_t chap_dma;
chap_table = dma_pool_alloc(ha->chap_dma_pool, GFP_KERNEL, &chap_dma);
if (chap_table == NULL)
return -ENOMEM;
chap_size = sizeof(struct ql4_chap_table);
memset(chap_table, 0, chap_size);
if (is_qla40XX(ha))
offset = FLASH_CHAP_OFFSET | (idx * chap_size);
else {
offset = FLASH_RAW_ACCESS_ADDR + (ha->hw.flt_region_chap << 2);
/* flt_chap_size is CHAP table size for both ports
* so divide it by 2 to calculate the offset for second port
*/
if (ha->port_num == 1)
offset += (ha->hw.flt_chap_size / 2);
offset += (idx * chap_size);
}
rval = qla4xxx_get_flash(ha, chap_dma, offset, chap_size);
if (rval != QLA_SUCCESS) {
ret = -EINVAL;
goto exit_get_chap;
}
DEBUG2(ql4_printk(KERN_INFO, ha, "Chap Cookie: x%x\n",
__le16_to_cpu(chap_table->cookie)));
if (__le16_to_cpu(chap_table->cookie) != CHAP_VALID_COOKIE) {
ql4_printk(KERN_ERR, ha, "No valid chap entry found\n");
goto exit_get_chap;
}
strlcpy(password, chap_table->secret, QL4_CHAP_MAX_SECRET_LEN);
strlcpy(username, chap_table->name, QL4_CHAP_MAX_NAME_LEN);
chap_table->cookie = __constant_cpu_to_le16(CHAP_VALID_COOKIE);
exit_get_chap:
dma_pool_free(ha->chap_dma_pool, chap_table, chap_dma);
return ret;
}
/**
* qla4xxx_set_chap - Make a chap entry at the given index
* @ha: pointer to adapter structure
* @username: CHAP username to set
* @password: CHAP password to set
* @idx: CHAP index at which to make the entry
* @bidi: type of chap entry (chap_in or chap_out)
*
* Create chap entry at the given index with the information provided.
*
* Note: Caller should acquire the chap lock before getting here.
**/
int qla4xxx_set_chap(struct scsi_qla_host *ha, char *username, char *password,
uint16_t idx, int bidi)
{
int ret = 0;
int rval = QLA_ERROR;
uint32_t offset = 0;
struct ql4_chap_table *chap_table;
uint32_t chap_size = 0;
dma_addr_t chap_dma;
chap_table = dma_pool_alloc(ha->chap_dma_pool, GFP_KERNEL, &chap_dma);
if (chap_table == NULL) {
ret = -ENOMEM;
goto exit_set_chap;
}
memset(chap_table, 0, sizeof(struct ql4_chap_table));
if (bidi)
chap_table->flags |= BIT_6; /* peer */
else
chap_table->flags |= BIT_7; /* local */
chap_table->secret_len = strlen(password);
strncpy(chap_table->secret, password, MAX_CHAP_SECRET_LEN - 1);
strncpy(chap_table->name, username, MAX_CHAP_NAME_LEN - 1);
chap_table->cookie = __constant_cpu_to_le16(CHAP_VALID_COOKIE);
if (is_qla40XX(ha)) {
chap_size = MAX_CHAP_ENTRIES_40XX * sizeof(*chap_table);
offset = FLASH_CHAP_OFFSET;
} else { /* Single region contains CHAP info for both ports which is
* divided into half for each port.
*/
chap_size = ha->hw.flt_chap_size / 2;
offset = FLASH_RAW_ACCESS_ADDR + (ha->hw.flt_region_chap << 2);
if (ha->port_num == 1)
offset += chap_size;
}
offset += (idx * sizeof(struct ql4_chap_table));
rval = qla4xxx_set_flash(ha, chap_dma, offset,
sizeof(struct ql4_chap_table),
FLASH_OPT_RMW_COMMIT);
if (rval == QLA_SUCCESS && ha->chap_list) {
/* Update ha chap_list cache */
memcpy((struct ql4_chap_table *)ha->chap_list + idx,
chap_table, sizeof(struct ql4_chap_table));
}
dma_pool_free(ha->chap_dma_pool, chap_table, chap_dma);
if (rval != QLA_SUCCESS)
ret = -EINVAL;
exit_set_chap:
return ret;
}
int qla4xxx_get_uni_chap_at_index(struct scsi_qla_host *ha, char *username,
char *password, uint16_t chap_index)
{
int rval = QLA_ERROR;
struct ql4_chap_table *chap_table = NULL;
int max_chap_entries;
if (!ha->chap_list) {
ql4_printk(KERN_ERR, ha, "Do not have CHAP table cache\n");
rval = QLA_ERROR;
goto exit_uni_chap;
}
if (!username || !password) {
ql4_printk(KERN_ERR, ha, "No memory for username & secret\n");
rval = QLA_ERROR;
goto exit_uni_chap;
}
if (is_qla80XX(ha))
max_chap_entries = (ha->hw.flt_chap_size / 2) /
sizeof(struct ql4_chap_table);
else
max_chap_entries = MAX_CHAP_ENTRIES_40XX;
if (chap_index > max_chap_entries) {
ql4_printk(KERN_ERR, ha, "Invalid Chap index\n");
rval = QLA_ERROR;
goto exit_uni_chap;
}
mutex_lock(&ha->chap_sem);
chap_table = (struct ql4_chap_table *)ha->chap_list + chap_index;
if (chap_table->cookie != __constant_cpu_to_le16(CHAP_VALID_COOKIE)) {
rval = QLA_ERROR;
goto exit_unlock_uni_chap;
}
if (!(chap_table->flags & BIT_7)) {
ql4_printk(KERN_ERR, ha, "Unidirectional entry not set\n");
rval = QLA_ERROR;
goto exit_unlock_uni_chap;
}
strlcpy(password, chap_table->secret, MAX_CHAP_SECRET_LEN);
strlcpy(username, chap_table->name, MAX_CHAP_NAME_LEN);
rval = QLA_SUCCESS;
exit_unlock_uni_chap:
mutex_unlock(&ha->chap_sem);
exit_uni_chap:
return rval;
}
/**
* qla4xxx_get_chap_index - Get chap index given username and secret
* @ha: pointer to adapter structure
* @username: CHAP username to be searched
* @password: CHAP password to be searched
* @bidi: Is this a BIDI CHAP
* @chap_index: CHAP index to be returned
*
* Match the username and password in the chap_list, return the index if a
* match is found. If a match is not found then add the entry in FLASH and
* return the index at which entry is written in the FLASH.
**/
int qla4xxx_get_chap_index(struct scsi_qla_host *ha, char *username,
char *password, int bidi, uint16_t *chap_index)
{
int i, rval;
int free_index = -1;
int found_index = 0;
int max_chap_entries = 0;
struct ql4_chap_table *chap_table;
if (is_qla80XX(ha))
max_chap_entries = (ha->hw.flt_chap_size / 2) /
sizeof(struct ql4_chap_table);
else
max_chap_entries = MAX_CHAP_ENTRIES_40XX;
if (!ha->chap_list) {
ql4_printk(KERN_ERR, ha, "Do not have CHAP table cache\n");
return QLA_ERROR;
}
if (!username || !password) {
ql4_printk(KERN_ERR, ha, "Do not have username and psw\n");
return QLA_ERROR;
}
mutex_lock(&ha->chap_sem);
for (i = 0; i < max_chap_entries; i++) {
chap_table = (struct ql4_chap_table *)ha->chap_list + i;
if (chap_table->cookie !=
__constant_cpu_to_le16(CHAP_VALID_COOKIE)) {
if (i > MAX_RESRV_CHAP_IDX && free_index == -1)
free_index = i;
continue;
}
if (bidi) {
if (chap_table->flags & BIT_7)
continue;
} else {
if (chap_table->flags & BIT_6)
continue;
}
if (!strncmp(chap_table->secret, password,
MAX_CHAP_SECRET_LEN) &&
!strncmp(chap_table->name, username,
MAX_CHAP_NAME_LEN)) {
*chap_index = i;
found_index = 1;
break;
}
}
/* If chap entry is not present and a free index is available then
* write the entry in flash
*/
if (!found_index && free_index != -1) {
rval = qla4xxx_set_chap(ha, username, password,
free_index, bidi);
if (!rval) {
*chap_index = free_index;
found_index = 1;
}
}
mutex_unlock(&ha->chap_sem);
if (found_index)
return QLA_SUCCESS;
return QLA_ERROR;
}
int qla4xxx_conn_close_sess_logout(struct scsi_qla_host *ha,
uint16_t fw_ddb_index,
uint16_t connection_id,
uint16_t option)
{
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
int status = QLA_SUCCESS;
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
mbox_cmd[0] = MBOX_CMD_CONN_CLOSE_SESS_LOGOUT;
mbox_cmd[1] = fw_ddb_index;
mbox_cmd[2] = connection_id;
mbox_cmd[3] = option;
status = qla4xxx_mailbox_command(ha, 4, 2, &mbox_cmd[0], &mbox_sts[0]);
if (status != QLA_SUCCESS) {
DEBUG2(ql4_printk(KERN_WARNING, ha, "%s: MBOX_CMD_CONN_CLOSE "
"option %04x failed w/ status %04X %04X\n",
__func__, option, mbox_sts[0], mbox_sts[1]));
}
return status;
}
/**
* qla4_84xx_extend_idc_tmo - Extend IDC Timeout.
* @ha: Pointer to host adapter structure.
* @ext_tmo: idc timeout value
*
* Requests firmware to extend the idc timeout value.
**/
static int qla4_84xx_extend_idc_tmo(struct scsi_qla_host *ha, uint32_t ext_tmo)
{
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
int status;
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
ext_tmo &= 0xf;
mbox_cmd[0] = MBOX_CMD_IDC_TIME_EXTEND;
mbox_cmd[1] = ((ha->idc_info.request_desc & 0xfffff0ff) |
(ext_tmo << 8)); /* new timeout */
mbox_cmd[2] = ha->idc_info.info1;
mbox_cmd[3] = ha->idc_info.info2;
mbox_cmd[4] = ha->idc_info.info3;
status = qla4xxx_mailbox_command(ha, MBOX_REG_COUNT, MBOX_REG_COUNT,
mbox_cmd, mbox_sts);
if (status != QLA_SUCCESS) {
DEBUG2(ql4_printk(KERN_INFO, ha,
"scsi%ld: %s: failed status %04X\n",
ha->host_no, __func__, mbox_sts[0]));
return QLA_ERROR;
} else {
ql4_printk(KERN_INFO, ha, "%s: IDC timeout extended by %d secs\n",
__func__, ext_tmo);
}
return QLA_SUCCESS;
}
int qla4xxx_disable_acb(struct scsi_qla_host *ha)
{
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
int status = QLA_SUCCESS;
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
mbox_cmd[0] = MBOX_CMD_DISABLE_ACB;
status = qla4xxx_mailbox_command(ha, 8, 5, &mbox_cmd[0], &mbox_sts[0]);
if (status != QLA_SUCCESS) {
DEBUG2(ql4_printk(KERN_WARNING, ha, "%s: MBOX_CMD_DISABLE_ACB "
"failed w/ status %04X %04X %04X", __func__,
mbox_sts[0], mbox_sts[1], mbox_sts[2]));
} else {
if (is_qla8042(ha) &&
test_bit(DPC_POST_IDC_ACK, &ha->dpc_flags) &&
(mbox_sts[0] != MBOX_STS_COMMAND_COMPLETE)) {
/*
* Disable ACB mailbox command takes time to complete
* based on the total number of targets connected.
* For 512 targets, it took approximately 5 secs to
* complete. Setting the timeout value to 8, with the 3
* secs buffer.
*/
qla4_84xx_extend_idc_tmo(ha, IDC_EXTEND_TOV);
if (!wait_for_completion_timeout(&ha->disable_acb_comp,
IDC_EXTEND_TOV * HZ)) {
ql4_printk(KERN_WARNING, ha, "%s: Disable ACB Completion not received\n",
__func__);
}
}
}
return status;
}
int qla4xxx_get_acb(struct scsi_qla_host *ha, dma_addr_t acb_dma,
uint32_t acb_type, uint32_t len)
{
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
int status = QLA_SUCCESS;
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
mbox_cmd[0] = MBOX_CMD_GET_ACB;
mbox_cmd[1] = acb_type;
mbox_cmd[2] = LSDW(acb_dma);
mbox_cmd[3] = MSDW(acb_dma);
mbox_cmd[4] = len;
status = qla4xxx_mailbox_command(ha, 5, 5, &mbox_cmd[0], &mbox_sts[0]);
if (status != QLA_SUCCESS) {
DEBUG2(ql4_printk(KERN_WARNING, ha, "%s: MBOX_CMD_GET_ACB "
"failed w/ status %04X\n", __func__,
mbox_sts[0]));
}
return status;
}
int qla4xxx_set_acb(struct scsi_qla_host *ha, uint32_t *mbox_cmd,
uint32_t *mbox_sts, dma_addr_t acb_dma)
{
int status = QLA_SUCCESS;
memset(mbox_cmd, 0, sizeof(mbox_cmd[0]) * MBOX_REG_COUNT);
memset(mbox_sts, 0, sizeof(mbox_sts[0]) * MBOX_REG_COUNT);
mbox_cmd[0] = MBOX_CMD_SET_ACB;
mbox_cmd[1] = 0; /* Primary ACB */
mbox_cmd[2] = LSDW(acb_dma);
mbox_cmd[3] = MSDW(acb_dma);
mbox_cmd[4] = sizeof(struct addr_ctrl_blk);
status = qla4xxx_mailbox_command(ha, 5, 5, &mbox_cmd[0], &mbox_sts[0]);
if (status != QLA_SUCCESS) {
DEBUG2(ql4_printk(KERN_WARNING, ha, "%s: MBOX_CMD_SET_ACB "
"failed w/ status %04X\n", __func__,
mbox_sts[0]));
}
return status;
}
int qla4xxx_set_param_ddbentry(struct scsi_qla_host *ha,
struct ddb_entry *ddb_entry,
struct iscsi_cls_conn *cls_conn,
uint32_t *mbx_sts)
{
struct dev_db_entry *fw_ddb_entry;
struct iscsi_conn *conn;
struct iscsi_session *sess;
struct qla_conn *qla_conn;
struct sockaddr *dst_addr;
dma_addr_t fw_ddb_entry_dma;
int status = QLA_SUCCESS;
int rval = 0;
struct sockaddr_in *addr;
struct sockaddr_in6 *addr6;
char *ip;
uint16_t iscsi_opts = 0;
uint32_t options = 0;
uint16_t idx, *ptid;
fw_ddb_entry = dma_alloc_coherent(&ha->pdev->dev, sizeof(*fw_ddb_entry),
&fw_ddb_entry_dma, GFP_KERNEL);
if (!fw_ddb_entry) {
DEBUG2(ql4_printk(KERN_ERR, ha,
"%s: Unable to allocate dma buffer.\n",
__func__));
rval = -ENOMEM;
goto exit_set_param_no_free;
}
conn = cls_conn->dd_data;
qla_conn = conn->dd_data;
sess = conn->session;
dst_addr = (struct sockaddr *)&qla_conn->qla_ep->dst_addr;
if (dst_addr->sa_family == AF_INET6)
options |= IPV6_DEFAULT_DDB_ENTRY;
status = qla4xxx_get_default_ddb(ha, options, fw_ddb_entry_dma);
if (status == QLA_ERROR) {
rval = -EINVAL;
goto exit_set_param;
}
ptid = (uint16_t *)&fw_ddb_entry->isid[1];
*ptid = cpu_to_le16((uint16_t)ddb_entry->sess->target_id);
DEBUG2(ql4_printk(KERN_INFO, ha, "ISID [%02x%02x%02x%02x%02x%02x]\n",
fw_ddb_entry->isid[5], fw_ddb_entry->isid[4],
fw_ddb_entry->isid[3], fw_ddb_entry->isid[2],
fw_ddb_entry->isid[1], fw_ddb_entry->isid[0]));
iscsi_opts = le16_to_cpu(fw_ddb_entry->iscsi_options);
memset(fw_ddb_entry->iscsi_alias, 0, sizeof(fw_ddb_entry->iscsi_alias));
memset(fw_ddb_entry->iscsi_name, 0, sizeof(fw_ddb_entry->iscsi_name));
if (sess->targetname != NULL) {
memcpy(fw_ddb_entry->iscsi_name, sess->targetname,
min(strlen(sess->targetname),
sizeof(fw_ddb_entry->iscsi_name)));
}
memset(fw_ddb_entry->ip_addr, 0, sizeof(fw_ddb_entry->ip_addr));
memset(fw_ddb_entry->tgt_addr, 0, sizeof(fw_ddb_entry->tgt_addr));
fw_ddb_entry->options = DDB_OPT_TARGET | DDB_OPT_AUTO_SENDTGTS_DISABLE;
if (dst_addr->sa_family == AF_INET) {
addr = (struct sockaddr_in *)dst_addr;
ip = (char *)&addr->sin_addr;
memcpy(fw_ddb_entry->ip_addr, ip, IP_ADDR_LEN);
fw_ddb_entry->port = cpu_to_le16(ntohs(addr->sin_port));
DEBUG2(ql4_printk(KERN_INFO, ha,
"%s: Destination Address [%pI4]: index [%d]\n",
__func__, fw_ddb_entry->ip_addr,
ddb_entry->fw_ddb_index));
} else if (dst_addr->sa_family == AF_INET6) {
addr6 = (struct sockaddr_in6 *)dst_addr;
ip = (char *)&addr6->sin6_addr;
memcpy(fw_ddb_entry->ip_addr, ip, IPv6_ADDR_LEN);
fw_ddb_entry->port = cpu_to_le16(ntohs(addr6->sin6_port));
fw_ddb_entry->options |= DDB_OPT_IPV6_DEVICE;
DEBUG2(ql4_printk(KERN_INFO, ha,
"%s: Destination Address [%pI6]: index [%d]\n",
__func__, fw_ddb_entry->ip_addr,
ddb_entry->fw_ddb_index));
} else {
ql4_printk(KERN_ERR, ha,
"%s: Failed to get IP Address\n",
__func__);
rval = -EINVAL;
goto exit_set_param;
}
/* CHAP */
if (sess->username != NULL && sess->password != NULL) {
if (strlen(sess->username) && strlen(sess->password)) {
iscsi_opts |= BIT_7;
rval = qla4xxx_get_chap_index(ha, sess->username,
sess->password,
LOCAL_CHAP, &idx);
if (rval)
goto exit_set_param;
fw_ddb_entry->chap_tbl_idx = cpu_to_le16(idx);
}
}
if (sess->username_in != NULL && sess->password_in != NULL) {
/* Check if BIDI CHAP */
if (strlen(sess->username_in) && strlen(sess->password_in)) {
iscsi_opts |= BIT_4;
rval = qla4xxx_get_chap_index(ha, sess->username_in,
sess->password_in,
BIDI_CHAP, &idx);
if (rval)
goto exit_set_param;
}
}
if (sess->initial_r2t_en)
iscsi_opts |= BIT_10;
if (sess->imm_data_en)
iscsi_opts |= BIT_11;
fw_ddb_entry->iscsi_options = cpu_to_le16(iscsi_opts);
if (conn->max_recv_dlength)
fw_ddb_entry->iscsi_max_rcv_data_seg_len =
__constant_cpu_to_le16((conn->max_recv_dlength / BYTE_UNITS));
if (sess->max_r2t)
fw_ddb_entry->iscsi_max_outsnd_r2t = cpu_to_le16(sess->max_r2t);
if (sess->first_burst)
fw_ddb_entry->iscsi_first_burst_len =
__constant_cpu_to_le16((sess->first_burst / BYTE_UNITS));
if (sess->max_burst)
fw_ddb_entry->iscsi_max_burst_len =
__constant_cpu_to_le16((sess->max_burst / BYTE_UNITS));
if (sess->time2wait)
fw_ddb_entry->iscsi_def_time2wait =
cpu_to_le16(sess->time2wait);
if (sess->time2retain)
fw_ddb_entry->iscsi_def_time2retain =
cpu_to_le16(sess->time2retain);
status = qla4xxx_set_ddb_entry(ha, ddb_entry->fw_ddb_index,
fw_ddb_entry_dma, mbx_sts);
if (status != QLA_SUCCESS)
rval = -EINVAL;
exit_set_param:
dma_free_coherent(&ha->pdev->dev, sizeof(*fw_ddb_entry),
fw_ddb_entry, fw_ddb_entry_dma);
exit_set_param_no_free:
return rval;
}
int qla4xxx_get_mgmt_data(struct scsi_qla_host *ha, uint16_t fw_ddb_index,
uint16_t stats_size, dma_addr_t stats_dma)
{
int status = QLA_SUCCESS;
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
memset(mbox_cmd, 0, sizeof(mbox_cmd[0]) * MBOX_REG_COUNT);
memset(mbox_sts, 0, sizeof(mbox_sts[0]) * MBOX_REG_COUNT);
mbox_cmd[0] = MBOX_CMD_GET_MANAGEMENT_DATA;
mbox_cmd[1] = fw_ddb_index;
mbox_cmd[2] = LSDW(stats_dma);
mbox_cmd[3] = MSDW(stats_dma);
mbox_cmd[4] = stats_size;
status = qla4xxx_mailbox_command(ha, 5, 1, &mbox_cmd[0], &mbox_sts[0]);
if (status != QLA_SUCCESS) {
DEBUG2(ql4_printk(KERN_WARNING, ha,
"%s: MBOX_CMD_GET_MANAGEMENT_DATA "
"failed w/ status %04X\n", __func__,
mbox_sts[0]));
}
return status;
}
int qla4xxx_get_ip_state(struct scsi_qla_host *ha, uint32_t acb_idx,
uint32_t ip_idx, uint32_t *sts)
{
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
int status = QLA_SUCCESS;
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
mbox_cmd[0] = MBOX_CMD_GET_IP_ADDR_STATE;
mbox_cmd[1] = acb_idx;
mbox_cmd[2] = ip_idx;
status = qla4xxx_mailbox_command(ha, 3, 8, &mbox_cmd[0], &mbox_sts[0]);
if (status != QLA_SUCCESS) {
DEBUG2(ql4_printk(KERN_WARNING, ha, "%s: "
"MBOX_CMD_GET_IP_ADDR_STATE failed w/ "
"status %04X\n", __func__, mbox_sts[0]));
}
memcpy(sts, mbox_sts, sizeof(mbox_sts));
return status;
}
int qla4xxx_get_nvram(struct scsi_qla_host *ha, dma_addr_t nvram_dma,
uint32_t offset, uint32_t size)
{
int status = QLA_SUCCESS;
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
mbox_cmd[0] = MBOX_CMD_GET_NVRAM;
mbox_cmd[1] = LSDW(nvram_dma);
mbox_cmd[2] = MSDW(nvram_dma);
mbox_cmd[3] = offset;
mbox_cmd[4] = size;
status = qla4xxx_mailbox_command(ha, MBOX_REG_COUNT, 1, &mbox_cmd[0],
&mbox_sts[0]);
if (status != QLA_SUCCESS) {
DEBUG2(ql4_printk(KERN_ERR, ha, "scsi%ld: %s: failed "
"status %04X\n", ha->host_no, __func__,
mbox_sts[0]));
}
return status;
}
int qla4xxx_set_nvram(struct scsi_qla_host *ha, dma_addr_t nvram_dma,
uint32_t offset, uint32_t size)
{
int status = QLA_SUCCESS;
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
mbox_cmd[0] = MBOX_CMD_SET_NVRAM;
mbox_cmd[1] = LSDW(nvram_dma);
mbox_cmd[2] = MSDW(nvram_dma);
mbox_cmd[3] = offset;
mbox_cmd[4] = size;
status = qla4xxx_mailbox_command(ha, MBOX_REG_COUNT, 1, &mbox_cmd[0],
&mbox_sts[0]);
if (status != QLA_SUCCESS) {
DEBUG2(ql4_printk(KERN_ERR, ha, "scsi%ld: %s: failed "
"status %04X\n", ha->host_no, __func__,
mbox_sts[0]));
}
return status;
}
int qla4xxx_restore_factory_defaults(struct scsi_qla_host *ha,
uint32_t region, uint32_t field0,
uint32_t field1)
{
int status = QLA_SUCCESS;
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
mbox_cmd[0] = MBOX_CMD_RESTORE_FACTORY_DEFAULTS;
mbox_cmd[3] = region;
mbox_cmd[4] = field0;
mbox_cmd[5] = field1;
status = qla4xxx_mailbox_command(ha, MBOX_REG_COUNT, 3, &mbox_cmd[0],
&mbox_sts[0]);
if (status != QLA_SUCCESS) {
DEBUG2(ql4_printk(KERN_ERR, ha, "scsi%ld: %s: failed "
"status %04X\n", ha->host_no, __func__,
mbox_sts[0]));
}
return status;
}
/**
* qla4_8xxx_set_param - set driver version in firmware.
* @ha: Pointer to host adapter structure.
* @param: Parameter to set i.e driver version
**/
int qla4_8xxx_set_param(struct scsi_qla_host *ha, int param)
{
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
uint32_t status;
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
mbox_cmd[0] = MBOX_CMD_SET_PARAM;
if (param == SET_DRVR_VERSION) {
mbox_cmd[1] = SET_DRVR_VERSION;
strncpy((char *)&mbox_cmd[2], QLA4XXX_DRIVER_VERSION,
MAX_DRVR_VER_LEN - 1);
} else {
ql4_printk(KERN_ERR, ha, "%s: invalid parameter 0x%x\n",
__func__, param);
status = QLA_ERROR;
goto exit_set_param;
}
status = qla4xxx_mailbox_command(ha, MBOX_REG_COUNT, 2, mbox_cmd,
mbox_sts);
if (status == QLA_ERROR)
ql4_printk(KERN_ERR, ha, "%s: failed status %04X\n",
__func__, mbox_sts[0]);
exit_set_param:
return status;
}
/**
* qla4_83xx_post_idc_ack - post IDC ACK
* @ha: Pointer to host adapter structure.
*
* Posts IDC ACK for IDC Request Notification AEN.
**/
int qla4_83xx_post_idc_ack(struct scsi_qla_host *ha)
{
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
int status;
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
mbox_cmd[0] = MBOX_CMD_IDC_ACK;
mbox_cmd[1] = ha->idc_info.request_desc;
mbox_cmd[2] = ha->idc_info.info1;
mbox_cmd[3] = ha->idc_info.info2;
mbox_cmd[4] = ha->idc_info.info3;
status = qla4xxx_mailbox_command(ha, MBOX_REG_COUNT, MBOX_REG_COUNT,
mbox_cmd, mbox_sts);
if (status == QLA_ERROR)
ql4_printk(KERN_ERR, ha, "%s: failed status %04X\n", __func__,
mbox_sts[0]);
else
ql4_printk(KERN_INFO, ha, "%s: IDC ACK posted\n", __func__);
return status;
}
int qla4_84xx_config_acb(struct scsi_qla_host *ha, int acb_config)
{
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
struct addr_ctrl_blk *acb = NULL;
uint32_t acb_len = sizeof(struct addr_ctrl_blk);
int rval = QLA_SUCCESS;
dma_addr_t acb_dma;
acb = dma_alloc_coherent(&ha->pdev->dev,
sizeof(struct addr_ctrl_blk),
&acb_dma, GFP_KERNEL);
if (!acb) {
ql4_printk(KERN_ERR, ha, "%s: Unable to alloc acb\n", __func__);
rval = QLA_ERROR;
goto exit_config_acb;
}
memset(acb, 0, acb_len);
switch (acb_config) {
case ACB_CONFIG_DISABLE:
rval = qla4xxx_get_acb(ha, acb_dma, 0, acb_len);
if (rval != QLA_SUCCESS)
goto exit_free_acb;
rval = qla4xxx_disable_acb(ha);
if (rval != QLA_SUCCESS)
goto exit_free_acb;
if (!ha->saved_acb)
ha->saved_acb = kzalloc(acb_len, GFP_KERNEL);
if (!ha->saved_acb) {
ql4_printk(KERN_ERR, ha, "%s: Unable to alloc acb\n",
__func__);
rval = QLA_ERROR;
goto exit_free_acb;
}
memcpy(ha->saved_acb, acb, acb_len);
break;
case ACB_CONFIG_SET:
if (!ha->saved_acb) {
ql4_printk(KERN_ERR, ha, "%s: Can't set ACB, Saved ACB not available\n",
__func__);
rval = QLA_ERROR;
goto exit_free_acb;
}
memcpy(acb, ha->saved_acb, acb_len);
rval = qla4xxx_set_acb(ha, &mbox_cmd[0], &mbox_sts[0], acb_dma);
if (rval != QLA_SUCCESS)
goto exit_free_acb;
break;
default:
ql4_printk(KERN_ERR, ha, "%s: Invalid ACB Configuration\n",
__func__);
}
exit_free_acb:
dma_free_coherent(&ha->pdev->dev, sizeof(struct addr_ctrl_blk), acb,
acb_dma);
exit_config_acb:
if ((acb_config == ACB_CONFIG_SET) && ha->saved_acb) {
kfree(ha->saved_acb);
ha->saved_acb = NULL;
}
DEBUG2(ql4_printk(KERN_INFO, ha,
"%s %s\n", __func__,
rval == QLA_SUCCESS ? "SUCCEEDED" : "FAILED"));
return rval;
}
int qla4_83xx_get_port_config(struct scsi_qla_host *ha, uint32_t *config)
{
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
int status;
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
mbox_cmd[0] = MBOX_CMD_GET_PORT_CONFIG;
status = qla4xxx_mailbox_command(ha, MBOX_REG_COUNT, MBOX_REG_COUNT,
mbox_cmd, mbox_sts);
if (status == QLA_SUCCESS)
*config = mbox_sts[1];
else
ql4_printk(KERN_ERR, ha, "%s: failed status %04X\n", __func__,
mbox_sts[0]);
return status;
}
int qla4_83xx_set_port_config(struct scsi_qla_host *ha, uint32_t *config)
{
uint32_t mbox_cmd[MBOX_REG_COUNT];
uint32_t mbox_sts[MBOX_REG_COUNT];
int status;
memset(&mbox_cmd, 0, sizeof(mbox_cmd));
memset(&mbox_sts, 0, sizeof(mbox_sts));
mbox_cmd[0] = MBOX_CMD_SET_PORT_CONFIG;
mbox_cmd[1] = *config;
status = qla4xxx_mailbox_command(ha, MBOX_REG_COUNT, MBOX_REG_COUNT,
mbox_cmd, mbox_sts);
if (status != QLA_SUCCESS)
ql4_printk(KERN_ERR, ha, "%s: failed status %04X\n", __func__,
mbox_sts[0]);
return status;
}
| gpl-2.0 |
AndroidDevelopersTeam/android_kernel_samsung_j2xlte_dd | arch/s390/kvm/diag.c | 1634 | 4091 | /*
* handling diagnose instructions
*
* Copyright IBM Corp. 2008, 2011
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License (version 2 only)
* as published by the Free Software Foundation.
*
* Author(s): Carsten Otte <cotte@de.ibm.com>
* Christian Borntraeger <borntraeger@de.ibm.com>
*/
#include <linux/kvm.h>
#include <linux/kvm_host.h>
#include <asm/virtio-ccw.h>
#include "kvm-s390.h"
#include "trace.h"
#include "trace-s390.h"
static int diag_release_pages(struct kvm_vcpu *vcpu)
{
unsigned long start, end;
unsigned long prefix = vcpu->arch.sie_block->prefix;
start = vcpu->run->s.regs.gprs[(vcpu->arch.sie_block->ipa & 0xf0) >> 4];
end = vcpu->run->s.regs.gprs[vcpu->arch.sie_block->ipa & 0xf] + 4096;
if (start & ~PAGE_MASK || end & ~PAGE_MASK || start > end
|| start < 2 * PAGE_SIZE)
return kvm_s390_inject_program_int(vcpu, PGM_SPECIFICATION);
VCPU_EVENT(vcpu, 5, "diag release pages %lX %lX", start, end);
vcpu->stat.diagnose_10++;
/* we checked for start > end above */
if (end < prefix || start >= prefix + 2 * PAGE_SIZE) {
gmap_discard(start, end, vcpu->arch.gmap);
} else {
if (start < prefix)
gmap_discard(start, prefix, vcpu->arch.gmap);
if (end >= prefix)
gmap_discard(prefix + 2 * PAGE_SIZE,
end, vcpu->arch.gmap);
}
return 0;
}
static int __diag_time_slice_end(struct kvm_vcpu *vcpu)
{
VCPU_EVENT(vcpu, 5, "%s", "diag time slice end");
vcpu->stat.diagnose_44++;
kvm_vcpu_on_spin(vcpu);
return 0;
}
static int __diag_time_slice_end_directed(struct kvm_vcpu *vcpu)
{
struct kvm *kvm = vcpu->kvm;
struct kvm_vcpu *tcpu;
int tid;
int i;
tid = vcpu->run->s.regs.gprs[(vcpu->arch.sie_block->ipa & 0xf0) >> 4];
vcpu->stat.diagnose_9c++;
VCPU_EVENT(vcpu, 5, "diag time slice end directed to %d", tid);
if (tid == vcpu->vcpu_id)
return 0;
kvm_for_each_vcpu(i, tcpu, kvm)
if (tcpu->vcpu_id == tid) {
kvm_vcpu_yield_to(tcpu);
break;
}
return 0;
}
static int __diag_ipl_functions(struct kvm_vcpu *vcpu)
{
unsigned int reg = vcpu->arch.sie_block->ipa & 0xf;
unsigned long subcode = vcpu->run->s.regs.gprs[reg] & 0xffff;
VCPU_EVENT(vcpu, 5, "diag ipl functions, subcode %lx", subcode);
switch (subcode) {
case 3:
vcpu->run->s390_reset_flags = KVM_S390_RESET_CLEAR;
break;
case 4:
vcpu->run->s390_reset_flags = 0;
break;
default:
return -EOPNOTSUPP;
}
atomic_set_mask(CPUSTAT_STOPPED, &vcpu->arch.sie_block->cpuflags);
vcpu->run->s390_reset_flags |= KVM_S390_RESET_SUBSYSTEM;
vcpu->run->s390_reset_flags |= KVM_S390_RESET_IPL;
vcpu->run->s390_reset_flags |= KVM_S390_RESET_CPU_INIT;
vcpu->run->exit_reason = KVM_EXIT_S390_RESET;
VCPU_EVENT(vcpu, 3, "requesting userspace resets %llx",
vcpu->run->s390_reset_flags);
trace_kvm_s390_request_resets(vcpu->run->s390_reset_flags);
return -EREMOTE;
}
static int __diag_virtio_hypercall(struct kvm_vcpu *vcpu)
{
int ret, idx;
/* No virtio-ccw notification? Get out quickly. */
if (!vcpu->kvm->arch.css_support ||
(vcpu->run->s.regs.gprs[1] != KVM_S390_VIRTIO_CCW_NOTIFY))
return -EOPNOTSUPP;
idx = srcu_read_lock(&vcpu->kvm->srcu);
/*
* The layout is as follows:
* - gpr 2 contains the subchannel id (passed as addr)
* - gpr 3 contains the virtqueue index (passed as datamatch)
*/
ret = kvm_io_bus_write(vcpu->kvm, KVM_VIRTIO_CCW_NOTIFY_BUS,
vcpu->run->s.regs.gprs[2],
8, &vcpu->run->s.regs.gprs[3]);
srcu_read_unlock(&vcpu->kvm->srcu, idx);
/* kvm_io_bus_write returns -EOPNOTSUPP if it found no match. */
return ret < 0 ? ret : 0;
}
int kvm_s390_handle_diag(struct kvm_vcpu *vcpu)
{
int code = kvm_s390_get_base_disp_rs(vcpu) & 0xffff;
trace_kvm_s390_handle_diag(vcpu, code);
switch (code) {
case 0x10:
return diag_release_pages(vcpu);
case 0x44:
return __diag_time_slice_end(vcpu);
case 0x9c:
return __diag_time_slice_end_directed(vcpu);
case 0x308:
return __diag_ipl_functions(vcpu);
case 0x500:
return __diag_virtio_hypercall(vcpu);
default:
return -EOPNOTSUPP;
}
}
| gpl-2.0 |
XePeleato/ALE-L21_ESAL | drivers/net/wireless/ath/ath9k/htc_drv_txrx.c | 1890 | 31421 | /*
* Copyright (c) 2010-2011 Atheros Communications Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "htc.h"
/******/
/* TX */
/******/
static const int subtype_txq_to_hwq[] = {
[IEEE80211_AC_BE] = ATH_TXQ_AC_BE,
[IEEE80211_AC_BK] = ATH_TXQ_AC_BK,
[IEEE80211_AC_VI] = ATH_TXQ_AC_VI,
[IEEE80211_AC_VO] = ATH_TXQ_AC_VO,
};
#define ATH9K_HTC_INIT_TXQ(subtype) do { \
qi.tqi_subtype = subtype_txq_to_hwq[subtype]; \
qi.tqi_aifs = ATH9K_TXQ_USEDEFAULT; \
qi.tqi_cwmin = ATH9K_TXQ_USEDEFAULT; \
qi.tqi_cwmax = ATH9K_TXQ_USEDEFAULT; \
qi.tqi_physCompBuf = 0; \
qi.tqi_qflags = TXQ_FLAG_TXEOLINT_ENABLE | \
TXQ_FLAG_TXDESCINT_ENABLE; \
} while (0)
int get_hw_qnum(u16 queue, int *hwq_map)
{
switch (queue) {
case 0:
return hwq_map[IEEE80211_AC_VO];
case 1:
return hwq_map[IEEE80211_AC_VI];
case 2:
return hwq_map[IEEE80211_AC_BE];
case 3:
return hwq_map[IEEE80211_AC_BK];
default:
return hwq_map[IEEE80211_AC_BE];
}
}
void ath9k_htc_check_stop_queues(struct ath9k_htc_priv *priv)
{
spin_lock_bh(&priv->tx.tx_lock);
priv->tx.queued_cnt++;
if ((priv->tx.queued_cnt >= ATH9K_HTC_TX_THRESHOLD) &&
!(priv->tx.flags & ATH9K_HTC_OP_TX_QUEUES_STOP)) {
priv->tx.flags |= ATH9K_HTC_OP_TX_QUEUES_STOP;
ieee80211_stop_queues(priv->hw);
}
spin_unlock_bh(&priv->tx.tx_lock);
}
void ath9k_htc_check_wake_queues(struct ath9k_htc_priv *priv)
{
spin_lock_bh(&priv->tx.tx_lock);
if ((priv->tx.queued_cnt < ATH9K_HTC_TX_THRESHOLD) &&
(priv->tx.flags & ATH9K_HTC_OP_TX_QUEUES_STOP)) {
priv->tx.flags &= ~ATH9K_HTC_OP_TX_QUEUES_STOP;
ieee80211_wake_queues(priv->hw);
}
spin_unlock_bh(&priv->tx.tx_lock);
}
int ath9k_htc_tx_get_slot(struct ath9k_htc_priv *priv)
{
int slot;
spin_lock_bh(&priv->tx.tx_lock);
slot = find_first_zero_bit(priv->tx.tx_slot, MAX_TX_BUF_NUM);
if (slot >= MAX_TX_BUF_NUM) {
spin_unlock_bh(&priv->tx.tx_lock);
return -ENOBUFS;
}
__set_bit(slot, priv->tx.tx_slot);
spin_unlock_bh(&priv->tx.tx_lock);
return slot;
}
void ath9k_htc_tx_clear_slot(struct ath9k_htc_priv *priv, int slot)
{
spin_lock_bh(&priv->tx.tx_lock);
__clear_bit(slot, priv->tx.tx_slot);
spin_unlock_bh(&priv->tx.tx_lock);
}
static inline enum htc_endpoint_id get_htc_epid(struct ath9k_htc_priv *priv,
u16 qnum)
{
enum htc_endpoint_id epid;
switch (qnum) {
case 0:
TX_QSTAT_INC(IEEE80211_AC_VO);
epid = priv->data_vo_ep;
break;
case 1:
TX_QSTAT_INC(IEEE80211_AC_VI);
epid = priv->data_vi_ep;
break;
case 2:
TX_QSTAT_INC(IEEE80211_AC_BE);
epid = priv->data_be_ep;
break;
case 3:
default:
TX_QSTAT_INC(IEEE80211_AC_BK);
epid = priv->data_bk_ep;
break;
}
return epid;
}
static inline struct sk_buff_head*
get_htc_epid_queue(struct ath9k_htc_priv *priv, u8 epid)
{
struct ath_common *common = ath9k_hw_common(priv->ah);
struct sk_buff_head *epid_queue = NULL;
if (epid == priv->mgmt_ep)
epid_queue = &priv->tx.mgmt_ep_queue;
else if (epid == priv->cab_ep)
epid_queue = &priv->tx.cab_ep_queue;
else if (epid == priv->data_be_ep)
epid_queue = &priv->tx.data_be_queue;
else if (epid == priv->data_bk_ep)
epid_queue = &priv->tx.data_bk_queue;
else if (epid == priv->data_vi_ep)
epid_queue = &priv->tx.data_vi_queue;
else if (epid == priv->data_vo_ep)
epid_queue = &priv->tx.data_vo_queue;
else
ath_err(common, "Invalid EPID: %d\n", epid);
return epid_queue;
}
/*
* Removes the driver header and returns the TX slot number
*/
static inline int strip_drv_header(struct ath9k_htc_priv *priv,
struct sk_buff *skb)
{
struct ath_common *common = ath9k_hw_common(priv->ah);
struct ath9k_htc_tx_ctl *tx_ctl;
int slot;
tx_ctl = HTC_SKB_CB(skb);
if (tx_ctl->epid == priv->mgmt_ep) {
struct tx_mgmt_hdr *tx_mhdr =
(struct tx_mgmt_hdr *)skb->data;
slot = tx_mhdr->cookie;
skb_pull(skb, sizeof(struct tx_mgmt_hdr));
} else if ((tx_ctl->epid == priv->data_bk_ep) ||
(tx_ctl->epid == priv->data_be_ep) ||
(tx_ctl->epid == priv->data_vi_ep) ||
(tx_ctl->epid == priv->data_vo_ep) ||
(tx_ctl->epid == priv->cab_ep)) {
struct tx_frame_hdr *tx_fhdr =
(struct tx_frame_hdr *)skb->data;
slot = tx_fhdr->cookie;
skb_pull(skb, sizeof(struct tx_frame_hdr));
} else {
ath_err(common, "Unsupported EPID: %d\n", tx_ctl->epid);
slot = -EINVAL;
}
return slot;
}
int ath_htc_txq_update(struct ath9k_htc_priv *priv, int qnum,
struct ath9k_tx_queue_info *qinfo)
{
struct ath_hw *ah = priv->ah;
int error = 0;
struct ath9k_tx_queue_info qi;
ath9k_hw_get_txq_props(ah, qnum, &qi);
qi.tqi_aifs = qinfo->tqi_aifs;
qi.tqi_cwmin = qinfo->tqi_cwmin / 2; /* XXX */
qi.tqi_cwmax = qinfo->tqi_cwmax;
qi.tqi_burstTime = qinfo->tqi_burstTime;
qi.tqi_readyTime = qinfo->tqi_readyTime;
if (!ath9k_hw_set_txq_props(ah, qnum, &qi)) {
ath_err(ath9k_hw_common(ah),
"Unable to update hardware queue %u!\n", qnum);
error = -EIO;
} else {
ath9k_hw_resettxqueue(ah, qnum);
}
return error;
}
static void ath9k_htc_tx_mgmt(struct ath9k_htc_priv *priv,
struct ath9k_htc_vif *avp,
struct sk_buff *skb,
u8 sta_idx, u8 vif_idx, u8 slot)
{
struct ieee80211_tx_info *tx_info = IEEE80211_SKB_CB(skb);
struct ieee80211_mgmt *mgmt;
struct ieee80211_hdr *hdr;
struct tx_mgmt_hdr mgmt_hdr;
struct ath9k_htc_tx_ctl *tx_ctl;
u8 *tx_fhdr;
tx_ctl = HTC_SKB_CB(skb);
hdr = (struct ieee80211_hdr *) skb->data;
memset(tx_ctl, 0, sizeof(*tx_ctl));
memset(&mgmt_hdr, 0, sizeof(struct tx_mgmt_hdr));
/*
* Set the TSF adjust value for probe response
* frame also.
*/
if (avp && unlikely(ieee80211_is_probe_resp(hdr->frame_control))) {
mgmt = (struct ieee80211_mgmt *)skb->data;
mgmt->u.probe_resp.timestamp = avp->tsfadjust;
}
tx_ctl->type = ATH9K_HTC_MGMT;
mgmt_hdr.node_idx = sta_idx;
mgmt_hdr.vif_idx = vif_idx;
mgmt_hdr.tidno = 0;
mgmt_hdr.flags = 0;
mgmt_hdr.cookie = slot;
mgmt_hdr.key_type = ath9k_cmn_get_hw_crypto_keytype(skb);
if (mgmt_hdr.key_type == ATH9K_KEY_TYPE_CLEAR)
mgmt_hdr.keyix = (u8) ATH9K_TXKEYIX_INVALID;
else
mgmt_hdr.keyix = tx_info->control.hw_key->hw_key_idx;
tx_fhdr = skb_push(skb, sizeof(mgmt_hdr));
memcpy(tx_fhdr, (u8 *) &mgmt_hdr, sizeof(mgmt_hdr));
tx_ctl->epid = priv->mgmt_ep;
}
static void ath9k_htc_tx_data(struct ath9k_htc_priv *priv,
struct ieee80211_vif *vif,
struct sk_buff *skb,
u8 sta_idx, u8 vif_idx, u8 slot,
bool is_cab)
{
struct ieee80211_tx_info *tx_info = IEEE80211_SKB_CB(skb);
struct ieee80211_hdr *hdr;
struct ath9k_htc_tx_ctl *tx_ctl;
struct tx_frame_hdr tx_hdr;
u32 flags = 0;
u8 *qc, *tx_fhdr;
u16 qnum;
tx_ctl = HTC_SKB_CB(skb);
hdr = (struct ieee80211_hdr *) skb->data;
memset(tx_ctl, 0, sizeof(*tx_ctl));
memset(&tx_hdr, 0, sizeof(struct tx_frame_hdr));
tx_hdr.node_idx = sta_idx;
tx_hdr.vif_idx = vif_idx;
tx_hdr.cookie = slot;
/*
* This is a bit redundant but it helps to get
* the per-packet index quickly when draining the
* TX queue in the HIF layer. Otherwise we would
* have to parse the packet contents ...
*/
tx_ctl->sta_idx = sta_idx;
if (tx_info->flags & IEEE80211_TX_CTL_AMPDU) {
tx_ctl->type = ATH9K_HTC_AMPDU;
tx_hdr.data_type = ATH9K_HTC_AMPDU;
} else {
tx_ctl->type = ATH9K_HTC_NORMAL;
tx_hdr.data_type = ATH9K_HTC_NORMAL;
}
if (ieee80211_is_data_qos(hdr->frame_control)) {
qc = ieee80211_get_qos_ctl(hdr);
tx_hdr.tidno = qc[0] & IEEE80211_QOS_CTL_TID_MASK;
}
/* Check for RTS protection */
if (priv->hw->wiphy->rts_threshold != (u32) -1)
if (skb->len > priv->hw->wiphy->rts_threshold)
flags |= ATH9K_HTC_TX_RTSCTS;
/* CTS-to-self */
if (!(flags & ATH9K_HTC_TX_RTSCTS) &&
(vif && vif->bss_conf.use_cts_prot))
flags |= ATH9K_HTC_TX_CTSONLY;
tx_hdr.flags = cpu_to_be32(flags);
tx_hdr.key_type = ath9k_cmn_get_hw_crypto_keytype(skb);
if (tx_hdr.key_type == ATH9K_KEY_TYPE_CLEAR)
tx_hdr.keyix = (u8) ATH9K_TXKEYIX_INVALID;
else
tx_hdr.keyix = tx_info->control.hw_key->hw_key_idx;
tx_fhdr = skb_push(skb, sizeof(tx_hdr));
memcpy(tx_fhdr, (u8 *) &tx_hdr, sizeof(tx_hdr));
if (is_cab) {
CAB_STAT_INC;
tx_ctl->epid = priv->cab_ep;
return;
}
qnum = skb_get_queue_mapping(skb);
tx_ctl->epid = get_htc_epid(priv, qnum);
}
int ath9k_htc_tx_start(struct ath9k_htc_priv *priv,
struct ieee80211_sta *sta,
struct sk_buff *skb,
u8 slot, bool is_cab)
{
struct ieee80211_hdr *hdr;
struct ieee80211_tx_info *tx_info = IEEE80211_SKB_CB(skb);
struct ieee80211_vif *vif = tx_info->control.vif;
struct ath9k_htc_sta *ista;
struct ath9k_htc_vif *avp = NULL;
u8 sta_idx, vif_idx;
hdr = (struct ieee80211_hdr *) skb->data;
/*
* Find out on which interface this packet has to be
* sent out.
*/
if (vif) {
avp = (struct ath9k_htc_vif *) vif->drv_priv;
vif_idx = avp->index;
} else {
if (!priv->ah->is_monitoring) {
ath_dbg(ath9k_hw_common(priv->ah), XMIT,
"VIF is null, but no monitor interface !\n");
return -EINVAL;
}
vif_idx = priv->mon_vif_idx;
}
/*
* Find out which station this packet is destined for.
*/
if (sta) {
ista = (struct ath9k_htc_sta *) sta->drv_priv;
sta_idx = ista->index;
} else {
sta_idx = priv->vif_sta_pos[vif_idx];
}
if (ieee80211_is_data(hdr->frame_control))
ath9k_htc_tx_data(priv, vif, skb,
sta_idx, vif_idx, slot, is_cab);
else
ath9k_htc_tx_mgmt(priv, avp, skb,
sta_idx, vif_idx, slot);
return htc_send(priv->htc, skb);
}
static inline bool __ath9k_htc_check_tx_aggr(struct ath9k_htc_priv *priv,
struct ath9k_htc_sta *ista, u8 tid)
{
bool ret = false;
spin_lock_bh(&priv->tx.tx_lock);
if ((tid < ATH9K_HTC_MAX_TID) && (ista->tid_state[tid] == AGGR_STOP))
ret = true;
spin_unlock_bh(&priv->tx.tx_lock);
return ret;
}
static void ath9k_htc_check_tx_aggr(struct ath9k_htc_priv *priv,
struct ieee80211_vif *vif,
struct sk_buff *skb)
{
struct ieee80211_sta *sta;
struct ieee80211_hdr *hdr;
__le16 fc;
hdr = (struct ieee80211_hdr *) skb->data;
fc = hdr->frame_control;
rcu_read_lock();
sta = ieee80211_find_sta(vif, hdr->addr1);
if (!sta) {
rcu_read_unlock();
return;
}
if (sta && conf_is_ht(&priv->hw->conf) &&
!(skb->protocol == cpu_to_be16(ETH_P_PAE))) {
if (ieee80211_is_data_qos(fc)) {
u8 *qc, tid;
struct ath9k_htc_sta *ista;
qc = ieee80211_get_qos_ctl(hdr);
tid = qc[0] & 0xf;
ista = (struct ath9k_htc_sta *)sta->drv_priv;
if (__ath9k_htc_check_tx_aggr(priv, ista, tid)) {
ieee80211_start_tx_ba_session(sta, tid, 0);
spin_lock_bh(&priv->tx.tx_lock);
ista->tid_state[tid] = AGGR_PROGRESS;
spin_unlock_bh(&priv->tx.tx_lock);
}
}
}
rcu_read_unlock();
}
static void ath9k_htc_tx_process(struct ath9k_htc_priv *priv,
struct sk_buff *skb,
struct __wmi_event_txstatus *txs)
{
struct ieee80211_vif *vif;
struct ath9k_htc_tx_ctl *tx_ctl;
struct ieee80211_tx_info *tx_info;
struct ieee80211_tx_rate *rate;
struct ieee80211_conf *cur_conf = &priv->hw->conf;
bool txok;
int slot;
int hdrlen, padsize;
slot = strip_drv_header(priv, skb);
if (slot < 0) {
dev_kfree_skb_any(skb);
return;
}
tx_ctl = HTC_SKB_CB(skb);
txok = tx_ctl->txok;
tx_info = IEEE80211_SKB_CB(skb);
vif = tx_info->control.vif;
rate = &tx_info->status.rates[0];
memset(&tx_info->status, 0, sizeof(tx_info->status));
/*
* URB submission failed for this frame, it never reached
* the target.
*/
if (!txok || !vif || !txs)
goto send_mac80211;
if (txs->ts_flags & ATH9K_HTC_TXSTAT_ACK)
tx_info->flags |= IEEE80211_TX_STAT_ACK;
if (txs->ts_flags & ATH9K_HTC_TXSTAT_FILT)
tx_info->flags |= IEEE80211_TX_STAT_TX_FILTERED;
if (txs->ts_flags & ATH9K_HTC_TXSTAT_RTC_CTS)
rate->flags |= IEEE80211_TX_RC_USE_RTS_CTS;
rate->count = 1;
rate->idx = MS(txs->ts_rate, ATH9K_HTC_TXSTAT_RATE);
if (txs->ts_flags & ATH9K_HTC_TXSTAT_MCS) {
rate->flags |= IEEE80211_TX_RC_MCS;
if (txs->ts_flags & ATH9K_HTC_TXSTAT_CW40)
rate->flags |= IEEE80211_TX_RC_40_MHZ_WIDTH;
if (txs->ts_flags & ATH9K_HTC_TXSTAT_SGI)
rate->flags |= IEEE80211_TX_RC_SHORT_GI;
} else {
if (cur_conf->chandef.chan->band == IEEE80211_BAND_5GHZ)
rate->idx += 4; /* No CCK rates */
}
ath9k_htc_check_tx_aggr(priv, vif, skb);
send_mac80211:
spin_lock_bh(&priv->tx.tx_lock);
if (WARN_ON(--priv->tx.queued_cnt < 0))
priv->tx.queued_cnt = 0;
spin_unlock_bh(&priv->tx.tx_lock);
ath9k_htc_tx_clear_slot(priv, slot);
/* Remove padding before handing frame back to mac80211 */
hdrlen = ieee80211_get_hdrlen_from_skb(skb);
padsize = hdrlen & 3;
if (padsize && skb->len > hdrlen + padsize) {
memmove(skb->data + padsize, skb->data, hdrlen);
skb_pull(skb, padsize);
}
/* Send status to mac80211 */
ieee80211_tx_status(priv->hw, skb);
}
static inline void ath9k_htc_tx_drainq(struct ath9k_htc_priv *priv,
struct sk_buff_head *queue)
{
struct sk_buff *skb;
while ((skb = skb_dequeue(queue)) != NULL) {
ath9k_htc_tx_process(priv, skb, NULL);
}
}
void ath9k_htc_tx_drain(struct ath9k_htc_priv *priv)
{
struct ath9k_htc_tx_event *event, *tmp;
spin_lock_bh(&priv->tx.tx_lock);
priv->tx.flags |= ATH9K_HTC_OP_TX_DRAIN;
spin_unlock_bh(&priv->tx.tx_lock);
/*
* Ensure that all pending TX frames are flushed,
* and that the TX completion/failed tasklets is killed.
*/
htc_stop(priv->htc);
tasklet_kill(&priv->wmi->wmi_event_tasklet);
tasklet_kill(&priv->tx_failed_tasklet);
ath9k_htc_tx_drainq(priv, &priv->tx.mgmt_ep_queue);
ath9k_htc_tx_drainq(priv, &priv->tx.cab_ep_queue);
ath9k_htc_tx_drainq(priv, &priv->tx.data_be_queue);
ath9k_htc_tx_drainq(priv, &priv->tx.data_bk_queue);
ath9k_htc_tx_drainq(priv, &priv->tx.data_vi_queue);
ath9k_htc_tx_drainq(priv, &priv->tx.data_vo_queue);
ath9k_htc_tx_drainq(priv, &priv->tx.tx_failed);
/*
* The TX cleanup timer has already been killed.
*/
spin_lock_bh(&priv->wmi->event_lock);
list_for_each_entry_safe(event, tmp, &priv->wmi->pending_tx_events, list) {
list_del(&event->list);
kfree(event);
}
spin_unlock_bh(&priv->wmi->event_lock);
spin_lock_bh(&priv->tx.tx_lock);
priv->tx.flags &= ~ATH9K_HTC_OP_TX_DRAIN;
spin_unlock_bh(&priv->tx.tx_lock);
}
void ath9k_tx_failed_tasklet(unsigned long data)
{
struct ath9k_htc_priv *priv = (struct ath9k_htc_priv *)data;
spin_lock_bh(&priv->tx.tx_lock);
if (priv->tx.flags & ATH9K_HTC_OP_TX_DRAIN) {
spin_unlock_bh(&priv->tx.tx_lock);
return;
}
spin_unlock_bh(&priv->tx.tx_lock);
ath9k_htc_tx_drainq(priv, &priv->tx.tx_failed);
}
static inline bool check_cookie(struct ath9k_htc_priv *priv,
struct sk_buff *skb,
u8 cookie, u8 epid)
{
u8 fcookie = 0;
if (epid == priv->mgmt_ep) {
struct tx_mgmt_hdr *hdr;
hdr = (struct tx_mgmt_hdr *) skb->data;
fcookie = hdr->cookie;
} else if ((epid == priv->data_bk_ep) ||
(epid == priv->data_be_ep) ||
(epid == priv->data_vi_ep) ||
(epid == priv->data_vo_ep) ||
(epid == priv->cab_ep)) {
struct tx_frame_hdr *hdr;
hdr = (struct tx_frame_hdr *) skb->data;
fcookie = hdr->cookie;
}
if (fcookie == cookie)
return true;
return false;
}
static struct sk_buff* ath9k_htc_tx_get_packet(struct ath9k_htc_priv *priv,
struct __wmi_event_txstatus *txs)
{
struct ath_common *common = ath9k_hw_common(priv->ah);
struct sk_buff_head *epid_queue;
struct sk_buff *skb, *tmp;
unsigned long flags;
u8 epid = MS(txs->ts_rate, ATH9K_HTC_TXSTAT_EPID);
epid_queue = get_htc_epid_queue(priv, epid);
if (!epid_queue)
return NULL;
spin_lock_irqsave(&epid_queue->lock, flags);
skb_queue_walk_safe(epid_queue, skb, tmp) {
if (check_cookie(priv, skb, txs->cookie, epid)) {
__skb_unlink(skb, epid_queue);
spin_unlock_irqrestore(&epid_queue->lock, flags);
return skb;
}
}
spin_unlock_irqrestore(&epid_queue->lock, flags);
ath_dbg(common, XMIT, "No matching packet for cookie: %d, epid: %d\n",
txs->cookie, epid);
return NULL;
}
void ath9k_htc_txstatus(struct ath9k_htc_priv *priv, void *wmi_event)
{
struct wmi_event_txstatus *txs = (struct wmi_event_txstatus *)wmi_event;
struct __wmi_event_txstatus *__txs;
struct sk_buff *skb;
struct ath9k_htc_tx_event *tx_pend;
int i;
for (i = 0; i < txs->cnt; i++) {
WARN_ON(txs->cnt > HTC_MAX_TX_STATUS);
__txs = &txs->txstatus[i];
skb = ath9k_htc_tx_get_packet(priv, __txs);
if (!skb) {
/*
* Store this event, so that the TX cleanup
* routine can check later for the needed packet.
*/
tx_pend = kzalloc(sizeof(struct ath9k_htc_tx_event),
GFP_ATOMIC);
if (!tx_pend)
continue;
memcpy(&tx_pend->txs, __txs,
sizeof(struct __wmi_event_txstatus));
spin_lock(&priv->wmi->event_lock);
list_add_tail(&tx_pend->list,
&priv->wmi->pending_tx_events);
spin_unlock(&priv->wmi->event_lock);
continue;
}
ath9k_htc_tx_process(priv, skb, __txs);
}
/* Wake TX queues if needed */
ath9k_htc_check_wake_queues(priv);
}
void ath9k_htc_txep(void *drv_priv, struct sk_buff *skb,
enum htc_endpoint_id ep_id, bool txok)
{
struct ath9k_htc_priv *priv = (struct ath9k_htc_priv *) drv_priv;
struct ath9k_htc_tx_ctl *tx_ctl;
struct sk_buff_head *epid_queue;
tx_ctl = HTC_SKB_CB(skb);
tx_ctl->txok = txok;
tx_ctl->timestamp = jiffies;
if (!txok) {
skb_queue_tail(&priv->tx.tx_failed, skb);
tasklet_schedule(&priv->tx_failed_tasklet);
return;
}
epid_queue = get_htc_epid_queue(priv, ep_id);
if (!epid_queue) {
dev_kfree_skb_any(skb);
return;
}
skb_queue_tail(epid_queue, skb);
}
static inline bool check_packet(struct ath9k_htc_priv *priv, struct sk_buff *skb)
{
struct ath_common *common = ath9k_hw_common(priv->ah);
struct ath9k_htc_tx_ctl *tx_ctl;
tx_ctl = HTC_SKB_CB(skb);
if (time_after(jiffies,
tx_ctl->timestamp +
msecs_to_jiffies(ATH9K_HTC_TX_TIMEOUT_INTERVAL))) {
ath_dbg(common, XMIT, "Dropping a packet due to TX timeout\n");
return true;
}
return false;
}
static void ath9k_htc_tx_cleanup_queue(struct ath9k_htc_priv *priv,
struct sk_buff_head *epid_queue)
{
bool process = false;
unsigned long flags;
struct sk_buff *skb, *tmp;
struct sk_buff_head queue;
skb_queue_head_init(&queue);
spin_lock_irqsave(&epid_queue->lock, flags);
skb_queue_walk_safe(epid_queue, skb, tmp) {
if (check_packet(priv, skb)) {
__skb_unlink(skb, epid_queue);
__skb_queue_tail(&queue, skb);
process = true;
}
}
spin_unlock_irqrestore(&epid_queue->lock, flags);
if (process) {
skb_queue_walk_safe(&queue, skb, tmp) {
__skb_unlink(skb, &queue);
ath9k_htc_tx_process(priv, skb, NULL);
}
}
}
void ath9k_htc_tx_cleanup_timer(unsigned long data)
{
struct ath9k_htc_priv *priv = (struct ath9k_htc_priv *) data;
struct ath_common *common = ath9k_hw_common(priv->ah);
struct ath9k_htc_tx_event *event, *tmp;
struct sk_buff *skb;
spin_lock(&priv->wmi->event_lock);
list_for_each_entry_safe(event, tmp, &priv->wmi->pending_tx_events, list) {
skb = ath9k_htc_tx_get_packet(priv, &event->txs);
if (skb) {
ath_dbg(common, XMIT,
"Found packet for cookie: %d, epid: %d\n",
event->txs.cookie,
MS(event->txs.ts_rate, ATH9K_HTC_TXSTAT_EPID));
ath9k_htc_tx_process(priv, skb, &event->txs);
list_del(&event->list);
kfree(event);
continue;
}
if (++event->count >= ATH9K_HTC_TX_TIMEOUT_COUNT) {
list_del(&event->list);
kfree(event);
}
}
spin_unlock(&priv->wmi->event_lock);
/*
* Check if status-pending packets have to be cleaned up.
*/
ath9k_htc_tx_cleanup_queue(priv, &priv->tx.mgmt_ep_queue);
ath9k_htc_tx_cleanup_queue(priv, &priv->tx.cab_ep_queue);
ath9k_htc_tx_cleanup_queue(priv, &priv->tx.data_be_queue);
ath9k_htc_tx_cleanup_queue(priv, &priv->tx.data_bk_queue);
ath9k_htc_tx_cleanup_queue(priv, &priv->tx.data_vi_queue);
ath9k_htc_tx_cleanup_queue(priv, &priv->tx.data_vo_queue);
/* Wake TX queues if needed */
ath9k_htc_check_wake_queues(priv);
mod_timer(&priv->tx.cleanup_timer,
jiffies + msecs_to_jiffies(ATH9K_HTC_TX_CLEANUP_INTERVAL));
}
int ath9k_tx_init(struct ath9k_htc_priv *priv)
{
skb_queue_head_init(&priv->tx.mgmt_ep_queue);
skb_queue_head_init(&priv->tx.cab_ep_queue);
skb_queue_head_init(&priv->tx.data_be_queue);
skb_queue_head_init(&priv->tx.data_bk_queue);
skb_queue_head_init(&priv->tx.data_vi_queue);
skb_queue_head_init(&priv->tx.data_vo_queue);
skb_queue_head_init(&priv->tx.tx_failed);
return 0;
}
void ath9k_tx_cleanup(struct ath9k_htc_priv *priv)
{
}
bool ath9k_htc_txq_setup(struct ath9k_htc_priv *priv, int subtype)
{
struct ath_hw *ah = priv->ah;
struct ath_common *common = ath9k_hw_common(ah);
struct ath9k_tx_queue_info qi;
int qnum;
memset(&qi, 0, sizeof(qi));
ATH9K_HTC_INIT_TXQ(subtype);
qnum = ath9k_hw_setuptxqueue(priv->ah, ATH9K_TX_QUEUE_DATA, &qi);
if (qnum == -1)
return false;
if (qnum >= ARRAY_SIZE(priv->hwq_map)) {
ath_err(common, "qnum %u out of range, max %zu!\n",
qnum, ARRAY_SIZE(priv->hwq_map));
ath9k_hw_releasetxqueue(ah, qnum);
return false;
}
priv->hwq_map[subtype] = qnum;
return true;
}
int ath9k_htc_cabq_setup(struct ath9k_htc_priv *priv)
{
struct ath9k_tx_queue_info qi;
memset(&qi, 0, sizeof(qi));
ATH9K_HTC_INIT_TXQ(0);
return ath9k_hw_setuptxqueue(priv->ah, ATH9K_TX_QUEUE_CAB, &qi);
}
/******/
/* RX */
/******/
/*
* Calculate the RX filter to be set in the HW.
*/
u32 ath9k_htc_calcrxfilter(struct ath9k_htc_priv *priv)
{
#define RX_FILTER_PRESERVE (ATH9K_RX_FILTER_PHYERR | ATH9K_RX_FILTER_PHYRADAR)
struct ath_hw *ah = priv->ah;
u32 rfilt;
rfilt = (ath9k_hw_getrxfilter(ah) & RX_FILTER_PRESERVE)
| ATH9K_RX_FILTER_UCAST | ATH9K_RX_FILTER_BCAST
| ATH9K_RX_FILTER_MCAST;
if (priv->rxfilter & FIF_PROBE_REQ)
rfilt |= ATH9K_RX_FILTER_PROBEREQ;
/*
* Set promiscuous mode when FIF_PROMISC_IN_BSS is enabled for station
* mode interface or when in monitor mode. AP mode does not need this
* since it receives all in-BSS frames anyway.
*/
if (((ah->opmode != NL80211_IFTYPE_AP) &&
(priv->rxfilter & FIF_PROMISC_IN_BSS)) ||
ah->is_monitoring)
rfilt |= ATH9K_RX_FILTER_PROM;
if (priv->rxfilter & FIF_CONTROL)
rfilt |= ATH9K_RX_FILTER_CONTROL;
if ((ah->opmode == NL80211_IFTYPE_STATION) &&
(priv->nvifs <= 1) &&
!(priv->rxfilter & FIF_BCN_PRBRESP_PROMISC))
rfilt |= ATH9K_RX_FILTER_MYBEACON;
else
rfilt |= ATH9K_RX_FILTER_BEACON;
if (conf_is_ht(&priv->hw->conf)) {
rfilt |= ATH9K_RX_FILTER_COMP_BAR;
rfilt |= ATH9K_RX_FILTER_UNCOMP_BA_BAR;
}
if (priv->rxfilter & FIF_PSPOLL)
rfilt |= ATH9K_RX_FILTER_PSPOLL;
if (priv->nvifs > 1)
rfilt |= ATH9K_RX_FILTER_MCAST_BCAST_ALL;
return rfilt;
#undef RX_FILTER_PRESERVE
}
/*
* Recv initialization for opmode change.
*/
static void ath9k_htc_opmode_init(struct ath9k_htc_priv *priv)
{
struct ath_hw *ah = priv->ah;
u32 rfilt, mfilt[2];
/* configure rx filter */
rfilt = ath9k_htc_calcrxfilter(priv);
ath9k_hw_setrxfilter(ah, rfilt);
/* calculate and install multicast filter */
mfilt[0] = mfilt[1] = ~0;
ath9k_hw_setmcastfilter(ah, mfilt[0], mfilt[1]);
}
void ath9k_host_rx_init(struct ath9k_htc_priv *priv)
{
ath9k_hw_rxena(priv->ah);
ath9k_htc_opmode_init(priv);
ath9k_hw_startpcureceive(priv->ah, test_bit(OP_SCANNING, &priv->op_flags));
priv->rx.last_rssi = ATH_RSSI_DUMMY_MARKER;
}
static void ath9k_process_rate(struct ieee80211_hw *hw,
struct ieee80211_rx_status *rxs,
u8 rx_rate, u8 rs_flags)
{
struct ieee80211_supported_band *sband;
enum ieee80211_band band;
unsigned int i = 0;
if (rx_rate & 0x80) {
/* HT rate */
rxs->flag |= RX_FLAG_HT;
if (rs_flags & ATH9K_RX_2040)
rxs->flag |= RX_FLAG_40MHZ;
if (rs_flags & ATH9K_RX_GI)
rxs->flag |= RX_FLAG_SHORT_GI;
rxs->rate_idx = rx_rate & 0x7f;
return;
}
band = hw->conf.chandef.chan->band;
sband = hw->wiphy->bands[band];
for (i = 0; i < sband->n_bitrates; i++) {
if (sband->bitrates[i].hw_value == rx_rate) {
rxs->rate_idx = i;
return;
}
if (sband->bitrates[i].hw_value_short == rx_rate) {
rxs->rate_idx = i;
rxs->flag |= RX_FLAG_SHORTPRE;
return;
}
}
}
static bool ath9k_rx_prepare(struct ath9k_htc_priv *priv,
struct ath9k_htc_rxbuf *rxbuf,
struct ieee80211_rx_status *rx_status)
{
struct ieee80211_hdr *hdr;
struct ieee80211_hw *hw = priv->hw;
struct sk_buff *skb = rxbuf->skb;
struct ath_common *common = ath9k_hw_common(priv->ah);
struct ath_htc_rx_status *rxstatus;
int hdrlen, padsize;
int last_rssi = ATH_RSSI_DUMMY_MARKER;
__le16 fc;
if (skb->len < HTC_RX_FRAME_HEADER_SIZE) {
ath_err(common, "Corrupted RX frame, dropping (len: %d)\n",
skb->len);
goto rx_next;
}
rxstatus = (struct ath_htc_rx_status *)skb->data;
if (be16_to_cpu(rxstatus->rs_datalen) -
(skb->len - HTC_RX_FRAME_HEADER_SIZE) != 0) {
ath_err(common,
"Corrupted RX data len, dropping (dlen: %d, skblen: %d)\n",
rxstatus->rs_datalen, skb->len);
goto rx_next;
}
ath9k_htc_err_stat_rx(priv, rxstatus);
/* Get the RX status information */
memcpy(&rxbuf->rxstatus, rxstatus, HTC_RX_FRAME_HEADER_SIZE);
skb_pull(skb, HTC_RX_FRAME_HEADER_SIZE);
hdr = (struct ieee80211_hdr *)skb->data;
fc = hdr->frame_control;
hdrlen = ieee80211_get_hdrlen_from_skb(skb);
padsize = hdrlen & 3;
if (padsize && skb->len >= hdrlen+padsize+FCS_LEN) {
memmove(skb->data + padsize, skb->data, hdrlen);
skb_pull(skb, padsize);
}
memset(rx_status, 0, sizeof(struct ieee80211_rx_status));
if (rxbuf->rxstatus.rs_status != 0) {
if (rxbuf->rxstatus.rs_status & ATH9K_RXERR_CRC)
rx_status->flag |= RX_FLAG_FAILED_FCS_CRC;
if (rxbuf->rxstatus.rs_status & ATH9K_RXERR_PHY)
goto rx_next;
if (rxbuf->rxstatus.rs_status & ATH9K_RXERR_DECRYPT) {
/* FIXME */
} else if (rxbuf->rxstatus.rs_status & ATH9K_RXERR_MIC) {
if (ieee80211_is_ctl(fc))
/*
* Sometimes, we get invalid
* MIC failures on valid control frames.
* Remove these mic errors.
*/
rxbuf->rxstatus.rs_status &= ~ATH9K_RXERR_MIC;
else
rx_status->flag |= RX_FLAG_MMIC_ERROR;
}
/*
* Reject error frames with the exception of
* decryption and MIC failures. For monitor mode,
* we also ignore the CRC error.
*/
if (priv->ah->opmode == NL80211_IFTYPE_MONITOR) {
if (rxbuf->rxstatus.rs_status &
~(ATH9K_RXERR_DECRYPT | ATH9K_RXERR_MIC |
ATH9K_RXERR_CRC))
goto rx_next;
} else {
if (rxbuf->rxstatus.rs_status &
~(ATH9K_RXERR_DECRYPT | ATH9K_RXERR_MIC)) {
goto rx_next;
}
}
}
if (!(rxbuf->rxstatus.rs_status & ATH9K_RXERR_DECRYPT)) {
u8 keyix;
keyix = rxbuf->rxstatus.rs_keyix;
if (keyix != ATH9K_RXKEYIX_INVALID) {
rx_status->flag |= RX_FLAG_DECRYPTED;
} else if (ieee80211_has_protected(fc) &&
skb->len >= hdrlen + 4) {
keyix = skb->data[hdrlen + 3] >> 6;
if (test_bit(keyix, common->keymap))
rx_status->flag |= RX_FLAG_DECRYPTED;
}
}
ath9k_process_rate(hw, rx_status, rxbuf->rxstatus.rs_rate,
rxbuf->rxstatus.rs_flags);
if (rxbuf->rxstatus.rs_rssi != ATH9K_RSSI_BAD &&
!rxbuf->rxstatus.rs_moreaggr)
ATH_RSSI_LPF(priv->rx.last_rssi,
rxbuf->rxstatus.rs_rssi);
last_rssi = priv->rx.last_rssi;
if (ieee80211_is_beacon(hdr->frame_control) &&
!is_zero_ether_addr(common->curbssid) &&
ether_addr_equal(hdr->addr3, common->curbssid)) {
s8 rssi = rxbuf->rxstatus.rs_rssi;
if (likely(last_rssi != ATH_RSSI_DUMMY_MARKER))
rssi = ATH_EP_RND(last_rssi, ATH_RSSI_EP_MULTIPLIER);
if (rssi < 0)
rssi = 0;
priv->ah->stats.avgbrssi = rssi;
}
rx_status->mactime = be64_to_cpu(rxbuf->rxstatus.rs_tstamp);
rx_status->band = hw->conf.chandef.chan->band;
rx_status->freq = hw->conf.chandef.chan->center_freq;
rx_status->signal = rxbuf->rxstatus.rs_rssi + ATH_DEFAULT_NOISE_FLOOR;
rx_status->antenna = rxbuf->rxstatus.rs_antenna;
rx_status->flag |= RX_FLAG_MACTIME_END;
return true;
rx_next:
return false;
}
/*
* FIXME: Handle FLUSH later on.
*/
void ath9k_rx_tasklet(unsigned long data)
{
struct ath9k_htc_priv *priv = (struct ath9k_htc_priv *)data;
struct ath9k_htc_rxbuf *rxbuf = NULL, *tmp_buf = NULL;
struct ieee80211_rx_status rx_status;
struct sk_buff *skb;
unsigned long flags;
struct ieee80211_hdr *hdr;
do {
spin_lock_irqsave(&priv->rx.rxbuflock, flags);
list_for_each_entry(tmp_buf, &priv->rx.rxbuf, list) {
if (tmp_buf->in_process) {
rxbuf = tmp_buf;
break;
}
}
if (rxbuf == NULL) {
spin_unlock_irqrestore(&priv->rx.rxbuflock, flags);
break;
}
if (!rxbuf->skb)
goto requeue;
if (!ath9k_rx_prepare(priv, rxbuf, &rx_status)) {
dev_kfree_skb_any(rxbuf->skb);
goto requeue;
}
memcpy(IEEE80211_SKB_RXCB(rxbuf->skb), &rx_status,
sizeof(struct ieee80211_rx_status));
skb = rxbuf->skb;
hdr = (struct ieee80211_hdr *) skb->data;
if (ieee80211_is_beacon(hdr->frame_control) && priv->ps_enabled)
ieee80211_queue_work(priv->hw, &priv->ps_work);
spin_unlock_irqrestore(&priv->rx.rxbuflock, flags);
ieee80211_rx(priv->hw, skb);
spin_lock_irqsave(&priv->rx.rxbuflock, flags);
requeue:
rxbuf->in_process = false;
rxbuf->skb = NULL;
list_move_tail(&rxbuf->list, &priv->rx.rxbuf);
rxbuf = NULL;
spin_unlock_irqrestore(&priv->rx.rxbuflock, flags);
} while (1);
}
void ath9k_htc_rxep(void *drv_priv, struct sk_buff *skb,
enum htc_endpoint_id ep_id)
{
struct ath9k_htc_priv *priv = (struct ath9k_htc_priv *)drv_priv;
struct ath_hw *ah = priv->ah;
struct ath_common *common = ath9k_hw_common(ah);
struct ath9k_htc_rxbuf *rxbuf = NULL, *tmp_buf = NULL;
spin_lock(&priv->rx.rxbuflock);
list_for_each_entry(tmp_buf, &priv->rx.rxbuf, list) {
if (!tmp_buf->in_process) {
rxbuf = tmp_buf;
break;
}
}
spin_unlock(&priv->rx.rxbuflock);
if (rxbuf == NULL) {
ath_dbg(common, ANY, "No free RX buffer\n");
goto err;
}
spin_lock(&priv->rx.rxbuflock);
rxbuf->skb = skb;
rxbuf->in_process = true;
spin_unlock(&priv->rx.rxbuflock);
tasklet_schedule(&priv->rx_tasklet);
return;
err:
dev_kfree_skb_any(skb);
}
/* FIXME: Locking for cleanup/init */
void ath9k_rx_cleanup(struct ath9k_htc_priv *priv)
{
struct ath9k_htc_rxbuf *rxbuf, *tbuf;
list_for_each_entry_safe(rxbuf, tbuf, &priv->rx.rxbuf, list) {
list_del(&rxbuf->list);
if (rxbuf->skb)
dev_kfree_skb_any(rxbuf->skb);
kfree(rxbuf);
}
}
int ath9k_rx_init(struct ath9k_htc_priv *priv)
{
int i = 0;
INIT_LIST_HEAD(&priv->rx.rxbuf);
spin_lock_init(&priv->rx.rxbuflock);
for (i = 0; i < ATH9K_HTC_RXBUF; i++) {
struct ath9k_htc_rxbuf *rxbuf =
kzalloc(sizeof(struct ath9k_htc_rxbuf), GFP_KERNEL);
if (rxbuf == NULL)
goto err;
list_add_tail(&rxbuf->list, &priv->rx.rxbuf);
}
return 0;
err:
ath9k_rx_cleanup(priv);
return -ENOMEM;
}
| gpl-2.0 |
tim-yang/linux-3.8 | fs/nls/mac-iceland.c | 2658 | 31288 | /*
* linux/fs/nls/mac-iceland.c
*
* Charset maciceland translation tables.
* Generated automatically from the Unicode and charset
* tables from the Unicode Organization (www.unicode.org).
* The Unicode to charset table has only exact mappings.
*/
/*
* COPYRIGHT AND PERMISSION NOTICE
*
* Copyright 1991-2012 Unicode, Inc. All rights reserved. Distributed under
* the Terms of Use in http://www.unicode.org/copyright.html.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of the Unicode data files and any associated documentation (the "Data
* Files") or Unicode software and any associated documentation (the
* "Software") to deal in the Data Files or Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, and/or sell copies of the Data Files or Software, and
* to permit persons to whom the Data Files or Software are furnished to do
* so, provided that (a) the above copyright notice(s) and this permission
* notice appear with all copies of the Data Files or Software, (b) both the
* above copyright notice(s) and this permission notice appear in associated
* documentation, and (c) there is clear notice in each modified Data File or
* in the Software as well as in the documentation associated with the Data
* File(s) or Software that the data or software has been modified.
*
* THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
* KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
* THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
* INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT
* OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
* USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THE DATA FILES OR SOFTWARE.
*
* Except as contained in this notice, the name of a copyright holder shall
* not be used in advertising or otherwise to promote the sale, use or other
* dealings in these Data Files or Software without prior written
* authorization of the copyright holder.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/nls.h>
#include <linux/errno.h>
static const wchar_t charset2uni[256] = {
/* 0x00 */
0x0000, 0x0001, 0x0002, 0x0003,
0x0004, 0x0005, 0x0006, 0x0007,
0x0008, 0x0009, 0x000a, 0x000b,
0x000c, 0x000d, 0x000e, 0x000f,
/* 0x10 */
0x0010, 0x0011, 0x0012, 0x0013,
0x0014, 0x0015, 0x0016, 0x0017,
0x0018, 0x0019, 0x001a, 0x001b,
0x001c, 0x001d, 0x001e, 0x001f,
/* 0x20 */
0x0020, 0x0021, 0x0022, 0x0023,
0x0024, 0x0025, 0x0026, 0x0027,
0x0028, 0x0029, 0x002a, 0x002b,
0x002c, 0x002d, 0x002e, 0x002f,
/* 0x30 */
0x0030, 0x0031, 0x0032, 0x0033,
0x0034, 0x0035, 0x0036, 0x0037,
0x0038, 0x0039, 0x003a, 0x003b,
0x003c, 0x003d, 0x003e, 0x003f,
/* 0x40 */
0x0040, 0x0041, 0x0042, 0x0043,
0x0044, 0x0045, 0x0046, 0x0047,
0x0048, 0x0049, 0x004a, 0x004b,
0x004c, 0x004d, 0x004e, 0x004f,
/* 0x50 */
0x0050, 0x0051, 0x0052, 0x0053,
0x0054, 0x0055, 0x0056, 0x0057,
0x0058, 0x0059, 0x005a, 0x005b,
0x005c, 0x005d, 0x005e, 0x005f,
/* 0x60 */
0x0060, 0x0061, 0x0062, 0x0063,
0x0064, 0x0065, 0x0066, 0x0067,
0x0068, 0x0069, 0x006a, 0x006b,
0x006c, 0x006d, 0x006e, 0x006f,
/* 0x70 */
0x0070, 0x0071, 0x0072, 0x0073,
0x0074, 0x0075, 0x0076, 0x0077,
0x0078, 0x0079, 0x007a, 0x007b,
0x007c, 0x007d, 0x007e, 0x007f,
/* 0x80 */
0x00c4, 0x00c5, 0x00c7, 0x00c9,
0x00d1, 0x00d6, 0x00dc, 0x00e1,
0x00e0, 0x00e2, 0x00e4, 0x00e3,
0x00e5, 0x00e7, 0x00e9, 0x00e8,
/* 0x90 */
0x00ea, 0x00eb, 0x00ed, 0x00ec,
0x00ee, 0x00ef, 0x00f1, 0x00f3,
0x00f2, 0x00f4, 0x00f6, 0x00f5,
0x00fa, 0x00f9, 0x00fb, 0x00fc,
/* 0xa0 */
0x00dd, 0x00b0, 0x00a2, 0x00a3,
0x00a7, 0x2022, 0x00b6, 0x00df,
0x00ae, 0x00a9, 0x2122, 0x00b4,
0x00a8, 0x2260, 0x00c6, 0x00d8,
/* 0xb0 */
0x221e, 0x00b1, 0x2264, 0x2265,
0x00a5, 0x00b5, 0x2202, 0x2211,
0x220f, 0x03c0, 0x222b, 0x00aa,
0x00ba, 0x03a9, 0x00e6, 0x00f8,
/* 0xc0 */
0x00bf, 0x00a1, 0x00ac, 0x221a,
0x0192, 0x2248, 0x2206, 0x00ab,
0x00bb, 0x2026, 0x00a0, 0x00c0,
0x00c3, 0x00d5, 0x0152, 0x0153,
/* 0xd0 */
0x2013, 0x2014, 0x201c, 0x201d,
0x2018, 0x2019, 0x00f7, 0x25ca,
0x00ff, 0x0178, 0x2044, 0x20ac,
0x00d0, 0x00f0, 0x00de, 0x00fe,
/* 0xe0 */
0x00fd, 0x00b7, 0x201a, 0x201e,
0x2030, 0x00c2, 0x00ca, 0x00c1,
0x00cb, 0x00c8, 0x00cd, 0x00ce,
0x00cf, 0x00cc, 0x00d3, 0x00d4,
/* 0xf0 */
0xf8ff, 0x00d2, 0x00da, 0x00db,
0x00d9, 0x0131, 0x02c6, 0x02dc,
0x00af, 0x02d8, 0x02d9, 0x02da,
0x00b8, 0x02dd, 0x02db, 0x02c7,
};
static const unsigned char page00[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */
0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0xca, 0xc1, 0xa2, 0xa3, 0x00, 0xb4, 0x00, 0xa4, /* 0xa0-0xa7 */
0xac, 0xa9, 0xbb, 0xc7, 0xc2, 0x00, 0xa8, 0xf8, /* 0xa8-0xaf */
0xa1, 0xb1, 0x00, 0x00, 0xab, 0xb5, 0xa6, 0xe1, /* 0xb0-0xb7 */
0xfc, 0x00, 0xbc, 0xc8, 0x00, 0x00, 0x00, 0xc0, /* 0xb8-0xbf */
0xcb, 0xe7, 0xe5, 0xcc, 0x80, 0x81, 0xae, 0x82, /* 0xc0-0xc7 */
0xe9, 0x83, 0xe6, 0xe8, 0xed, 0xea, 0xeb, 0xec, /* 0xc8-0xcf */
0xdc, 0x84, 0xf1, 0xee, 0xef, 0xcd, 0x85, 0x00, /* 0xd0-0xd7 */
0xaf, 0xf4, 0xf2, 0xf3, 0x86, 0xa0, 0xde, 0xa7, /* 0xd8-0xdf */
0x88, 0x87, 0x89, 0x8b, 0x8a, 0x8c, 0xbe, 0x8d, /* 0xe0-0xe7 */
0x8f, 0x8e, 0x90, 0x91, 0x93, 0x92, 0x94, 0x95, /* 0xe8-0xef */
0xdd, 0x96, 0x98, 0x97, 0x99, 0x9b, 0x9a, 0xd6, /* 0xf0-0xf7 */
0xbf, 0x9d, 0x9c, 0x9e, 0x9f, 0xe0, 0xdf, 0xd8, /* 0xf8-0xff */
};
static const unsigned char page01[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x00, 0xf5, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0x00, 0x00, 0xce, 0xcf, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */
0xd9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0x00, 0xc4, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa8-0xaf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xb0-0xb7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xb8-0xbf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xc0-0xc7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xc8-0xcf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xd0-0xd7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xd8-0xdf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xe0-0xe7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xe8-0xef */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xf0-0xf7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xf8-0xff */
};
static const unsigned char page02[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa8-0xaf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xb0-0xb7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xb8-0xbf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0xff, /* 0xc0-0xc7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xc8-0xcf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xd0-0xd7 */
0xf9, 0xfa, 0xfb, 0xfe, 0xf7, 0xfd, 0x00, 0x00, /* 0xd8-0xdf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xe0-0xe7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xe8-0xef */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xf0-0xf7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xf8-0xff */
};
static const unsigned char page03[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */
0x00, 0xbd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa8-0xaf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xb0-0xb7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xb8-0xbf */
0xb9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xc0-0xc7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xc8-0xcf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xd0-0xd7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xd8-0xdf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xe0-0xe7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xe8-0xef */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xf0-0xf7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xf8-0xff */
};
static const unsigned char page20[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0xd0, 0xd1, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0xd4, 0xd5, 0xe2, 0x00, 0xd2, 0xd3, 0xe3, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0xa5, 0x00, 0x00, 0x00, 0xc9, 0x00, /* 0x20-0x27 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0xe4, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0xda, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */
0x00, 0x00, 0x00, 0x00, 0xdb, 0x00, 0x00, 0x00, /* 0xa8-0xaf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xb0-0xb7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xb8-0xbf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xc0-0xc7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xc8-0xcf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xd0-0xd7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xd8-0xdf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xe0-0xe7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xe8-0xef */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xf0-0xf7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xf8-0xff */
};
static const unsigned char page21[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0xaa, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa8-0xaf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xb0-0xb7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xb8-0xbf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xc0-0xc7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xc8-0xcf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xd0-0xd7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xd8-0xdf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xe0-0xe7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xe8-0xef */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xf0-0xf7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xf8-0xff */
};
static const unsigned char page22[256] = {
0x00, 0x00, 0xb6, 0x00, 0x00, 0x00, 0xc6, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xb8, /* 0x08-0x0f */
0x00, 0xb7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0x00, 0x00, 0xc3, 0x00, 0x00, 0x00, 0xb0, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */
0x00, 0x00, 0x00, 0xba, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0xc5, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */
0xad, 0x00, 0x00, 0x00, 0xb2, 0xb3, 0x00, 0x00, /* 0x60-0x67 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa8-0xaf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xb0-0xb7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xb8-0xbf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xc0-0xc7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xc8-0xcf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xd0-0xd7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xd8-0xdf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xe0-0xe7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xe8-0xef */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xf0-0xf7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xf8-0xff */
};
static const unsigned char page25[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa8-0xaf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xb0-0xb7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xb8-0xbf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xc0-0xc7 */
0x00, 0x00, 0xd7, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xc8-0xcf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xd0-0xd7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xd8-0xdf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xe0-0xe7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xe8-0xef */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xf0-0xf7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xf8-0xff */
};
static const unsigned char pagef8[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa8-0xaf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xb0-0xb7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xb8-0xbf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xc0-0xc7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xc8-0xcf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xd0-0xd7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xd8-0xdf */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xe0-0xe7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xe8-0xef */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xf0-0xf7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, /* 0xf8-0xff */
};
static const unsigned char *const page_uni2charset[256] = {
page00, page01, page02, page03, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
page20, page21, page22, NULL, NULL, page25, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
pagef8, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
};
static const unsigned char charset2lower[256] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x00-0x07 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x08-0x0f */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x10-0x17 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x18-0x1f */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x20-0x27 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x28-0x2f */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x30-0x37 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x38-0x3f */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x40-0x47 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x48-0x4f */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x50-0x57 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x58-0x5f */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x60-0x67 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x68-0x6f */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x70-0x77 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x78-0x7f */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x80-0x87 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x88-0x8f */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x90-0x97 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x98-0x9f */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0xa0-0xa7 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0xa8-0xaf */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0xb0-0xb7 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0xb8-0xbf */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0xc0-0xc7 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0xc8-0xcf */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0xd0-0xd7 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0xd8-0xdf */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0xe0-0xe7 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0xe8-0xef */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0xf0-0xf7 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0xf8-0xff */
};
static const unsigned char charset2upper[256] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x00-0x07 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x08-0x0f */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x10-0x17 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x18-0x1f */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x20-0x27 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x28-0x2f */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x30-0x37 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x38-0x3f */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x40-0x47 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x48-0x4f */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x50-0x57 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x58-0x5f */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x60-0x67 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x68-0x6f */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x70-0x77 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x78-0x7f */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x80-0x87 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x88-0x8f */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x90-0x97 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0x98-0x9f */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0xa0-0xa7 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0xa8-0xaf */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0xb0-0xb7 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0xb8-0xbf */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0xc0-0xc7 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0xc8-0xcf */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0xd0-0xd7 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0xd8-0xdf */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0xe0-0xe7 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0xe8-0xef */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0xf0-0xf7 */
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, /* 0xf8-0xff */
};
static int uni2char(wchar_t uni, unsigned char *out, int boundlen)
{
const unsigned char *uni2charset;
unsigned char cl = uni & 0x00ff;
unsigned char ch = (uni & 0xff00) >> 8;
if (boundlen <= 0)
return -ENAMETOOLONG;
uni2charset = page_uni2charset[ch];
if (uni2charset && uni2charset[cl])
out[0] = uni2charset[cl];
else
return -EINVAL;
return 1;
}
static int char2uni(const unsigned char *rawstring, int boundlen, wchar_t *uni)
{
*uni = charset2uni[*rawstring];
if (*uni == 0x0000)
return -EINVAL;
return 1;
}
static struct nls_table table = {
.charset = "maciceland",
.uni2char = uni2char,
.char2uni = char2uni,
.charset2lower = charset2lower,
.charset2upper = charset2upper,
.owner = THIS_MODULE,
};
static int __init init_nls_maciceland(void)
{
return register_nls(&table);
}
static void __exit exit_nls_maciceland(void)
{
unregister_nls(&table);
}
module_init(init_nls_maciceland)
module_exit(exit_nls_maciceland)
MODULE_LICENSE("Dual BSD/GPL");
| gpl-2.0 |
Evil-Green/boeffla-kernel-jb-u10-s3 | drivers/net/tokenring/lanstreamer.c | 2914 | 64483 | /*
* lanstreamer.c -- driver for the IBM Auto LANStreamer PCI Adapter
*
* Written By: Mike Sullivan, IBM Corporation
*
* Copyright (C) 1999 IBM Corporation
*
* Linux driver for IBM PCI tokenring cards based on the LanStreamer MPC
* chipset.
*
* This driver is based on the olympic driver for IBM PCI TokenRing cards (Pit/Pit-Phy/Olympic
* chipsets) written by:
* 1999 Peter De Schrijver All Rights Reserved
* 1999 Mike Phillips (phillim@amtrak.com)
*
* Base Driver Skeleton:
* Written 1993-94 by Donald Becker.
*
* Copyright 1993 United States Government as represented by the
* Director, National Security Agency.
*
* 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.
*
* NO WARRANTY
* THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT
* LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is
* solely responsible for determining the appropriateness of using and
* distributing the Program and assumes all risks associated with its
* exercise of rights under this Agreement, including but not limited to
* the risks and costs of program errors, damage to or loss of data,
* programs or equipment, and unavailability or interruption of operations.
*
* DISCLAIMER OF LIABILITY
* NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), 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 OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
* HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES
*
* 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
*
*
* 12/10/99 - Alpha Release 0.1.0
* First release to the public
* 03/03/00 - Merged to kernel, indented -kr -i8 -bri0, fixed some missing
* malloc free checks, reviewed code. <alan@redhat.com>
* 03/13/00 - Added spinlocks for smp
* 03/08/01 - Added support for module_init() and module_exit()
* 08/15/01 - Added ioctl() functionality for debugging, changed netif_*_queue
* calls and other incorrectness - Kent Yoder <yoder1@us.ibm.com>
* 11/05/01 - Restructured the interrupt function, added delays, reduced the
* the number of TX descriptors to 1, which together can prevent
* the card from locking up the box - <yoder1@us.ibm.com>
* 09/27/02 - New PCI interface + bug fix. - <yoder1@us.ibm.com>
* 11/13/02 - Removed free_irq calls which could cause a hang, added
* netif_carrier_{on|off} - <yoder1@us.ibm.com>
*
* To Do:
*
*
* If Problems do Occur
* Most problems can be rectified by either closing and opening the interface
* (ifconfig down and up) or rmmod and insmod'ing the driver (a bit difficult
* if compiled into the kernel).
*/
/* Change STREAMER_DEBUG to 1 to get verbose, and I mean really verbose, messages */
#define STREAMER_DEBUG 0
#define STREAMER_DEBUG_PACKETS 0
/* Change STREAMER_NETWORK_MONITOR to receive mac frames through the arb channel.
* Will also create a /proc/net/streamer_tr entry if proc_fs is compiled into the
* kernel.
* Intended to be used to create a ring-error reporting network module
* i.e. it will give you the source address of beaconers on the ring
*/
#define STREAMER_NETWORK_MONITOR 0
/* #define CONFIG_PROC_FS */
/*
* Allow or disallow ioctl's for debugging
*/
#define STREAMER_IOCTL 0
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/timer.h>
#include <linux/in.h>
#include <linux/ioport.h>
#include <linux/string.h>
#include <linux/proc_fs.h>
#include <linux/ptrace.h>
#include <linux/skbuff.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/netdevice.h>
#include <linux/trdevice.h>
#include <linux/stddef.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/dma-mapping.h>
#include <linux/spinlock.h>
#include <linux/bitops.h>
#include <linux/jiffies.h>
#include <linux/slab.h>
#include <net/net_namespace.h>
#include <net/checksum.h>
#include <asm/io.h>
#include <asm/system.h>
#include "lanstreamer.h"
#if (BITS_PER_LONG == 64)
#error broken on 64-bit: stores pointer to rx_ring->buffer in 32-bit int
#endif
/* I've got to put some intelligence into the version number so that Peter and I know
* which version of the code somebody has got.
* Version Number = a.b.c.d where a.b.c is the level of code and d is the latest author.
* So 0.0.1.pds = Peter, 0.0.1.mlp = Mike
*
* Official releases will only have an a.b.c version number format.
*/
static char version[] = "LanStreamer.c v0.4.0 03/08/01 - Mike Sullivan\n"
" v0.5.3 11/13/02 - Kent Yoder";
static DEFINE_PCI_DEVICE_TABLE(streamer_pci_tbl) = {
{ PCI_VENDOR_ID_IBM, PCI_DEVICE_ID_IBM_TR, PCI_ANY_ID, PCI_ANY_ID,},
{} /* terminating entry */
};
MODULE_DEVICE_TABLE(pci,streamer_pci_tbl);
static char *open_maj_error[] = {
"No error", "Lobe Media Test", "Physical Insertion",
"Address Verification", "Neighbor Notification (Ring Poll)",
"Request Parameters", "FDX Registration Request",
"FDX Lobe Media Test", "FDX Duplicate Address Check",
"Unknown stage"
};
static char *open_min_error[] = {
"No error", "Function Failure", "Signal Lost", "Wire Fault",
"Ring Speed Mismatch", "Timeout", "Ring Failure", "Ring Beaconing",
"Duplicate Node Address", "Request Parameters", "Remove Received",
"Reserved", "Reserved", "No Monitor Detected for RPL",
"Monitor Contention failer for RPL", "FDX Protocol Error"
};
/* Module parameters */
/* Ring Speed 0,4,16
* 0 = Autosense
* 4,16 = Selected speed only, no autosense
* This allows the card to be the first on the ring
* and become the active monitor.
*
* WARNING: Some hubs will allow you to insert
* at the wrong speed
*/
static int ringspeed[STREAMER_MAX_ADAPTERS] = { 0, };
module_param_array(ringspeed, int, NULL, 0);
/* Packet buffer size */
static int pkt_buf_sz[STREAMER_MAX_ADAPTERS] = { 0, };
module_param_array(pkt_buf_sz, int, NULL, 0);
/* Message Level */
static int message_level[STREAMER_MAX_ADAPTERS] = { 1, };
module_param_array(message_level, int, NULL, 0);
#if STREAMER_IOCTL
static int streamer_ioctl(struct net_device *, struct ifreq *, int);
#endif
static int streamer_reset(struct net_device *dev);
static int streamer_open(struct net_device *dev);
static netdev_tx_t streamer_xmit(struct sk_buff *skb,
struct net_device *dev);
static int streamer_close(struct net_device *dev);
static void streamer_set_rx_mode(struct net_device *dev);
static irqreturn_t streamer_interrupt(int irq, void *dev_id);
static int streamer_set_mac_address(struct net_device *dev, void *addr);
static void streamer_arb_cmd(struct net_device *dev);
static int streamer_change_mtu(struct net_device *dev, int mtu);
static void streamer_srb_bh(struct net_device *dev);
static void streamer_asb_bh(struct net_device *dev);
#if STREAMER_NETWORK_MONITOR
#ifdef CONFIG_PROC_FS
static int streamer_proc_info(char *buffer, char **start, off_t offset,
int length, int *eof, void *data);
static int sprintf_info(char *buffer, struct net_device *dev);
struct streamer_private *dev_streamer=NULL;
#endif
#endif
static const struct net_device_ops streamer_netdev_ops = {
.ndo_open = streamer_open,
.ndo_stop = streamer_close,
.ndo_start_xmit = streamer_xmit,
.ndo_change_mtu = streamer_change_mtu,
#if STREAMER_IOCTL
.ndo_do_ioctl = streamer_ioctl,
#endif
.ndo_set_multicast_list = streamer_set_rx_mode,
.ndo_set_mac_address = streamer_set_mac_address,
};
static int __devinit streamer_init_one(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct net_device *dev;
struct streamer_private *streamer_priv;
unsigned long pio_start, pio_end, pio_flags, pio_len;
unsigned long mmio_start, mmio_end, mmio_flags, mmio_len;
int rc = 0;
static int card_no=-1;
u16 pcr;
#if STREAMER_DEBUG
printk("lanstreamer::streamer_init_one, entry pdev %p\n",pdev);
#endif
card_no++;
dev = alloc_trdev(sizeof(*streamer_priv));
if (dev==NULL) {
printk(KERN_ERR "lanstreamer: out of memory.\n");
return -ENOMEM;
}
streamer_priv = netdev_priv(dev);
#if STREAMER_NETWORK_MONITOR
#ifdef CONFIG_PROC_FS
if (!dev_streamer)
create_proc_read_entry("streamer_tr", 0, init_net.proc_net,
streamer_proc_info, NULL);
streamer_priv->next = dev_streamer;
dev_streamer = streamer_priv;
#endif
#endif
rc = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (rc) {
printk(KERN_ERR "%s: No suitable PCI mapping available.\n",
dev->name);
rc = -ENODEV;
goto err_out;
}
rc = pci_enable_device(pdev);
if (rc) {
printk(KERN_ERR "lanstreamer: unable to enable pci device\n");
rc=-EIO;
goto err_out;
}
pci_set_master(pdev);
rc = pci_set_mwi(pdev);
if (rc) {
printk(KERN_ERR "lanstreamer: unable to enable MWI on pci device\n");
goto err_out_disable;
}
pio_start = pci_resource_start(pdev, 0);
pio_end = pci_resource_end(pdev, 0);
pio_flags = pci_resource_flags(pdev, 0);
pio_len = pci_resource_len(pdev, 0);
mmio_start = pci_resource_start(pdev, 1);
mmio_end = pci_resource_end(pdev, 1);
mmio_flags = pci_resource_flags(pdev, 1);
mmio_len = pci_resource_len(pdev, 1);
#if STREAMER_DEBUG
printk("lanstreamer: pio_start %x pio_end %x pio_len %x pio_flags %x\n",
pio_start, pio_end, pio_len, pio_flags);
printk("lanstreamer: mmio_start %x mmio_end %x mmio_len %x mmio_flags %x\n",
mmio_start, mmio_end, mmio_flags, mmio_len);
#endif
if (!request_region(pio_start, pio_len, "lanstreamer")) {
printk(KERN_ERR "lanstreamer: unable to get pci io addr %lx\n",
pio_start);
rc= -EBUSY;
goto err_out_mwi;
}
if (!request_mem_region(mmio_start, mmio_len, "lanstreamer")) {
printk(KERN_ERR "lanstreamer: unable to get pci mmio addr %lx\n",
mmio_start);
rc= -EBUSY;
goto err_out_free_pio;
}
streamer_priv->streamer_mmio=ioremap(mmio_start, mmio_len);
if (streamer_priv->streamer_mmio == NULL) {
printk(KERN_ERR "lanstreamer: unable to remap MMIO %lx\n",
mmio_start);
rc= -EIO;
goto err_out_free_mmio;
}
init_waitqueue_head(&streamer_priv->srb_wait);
init_waitqueue_head(&streamer_priv->trb_wait);
dev->netdev_ops = &streamer_netdev_ops;
dev->irq = pdev->irq;
dev->base_addr=pio_start;
SET_NETDEV_DEV(dev, &pdev->dev);
streamer_priv->streamer_card_name = (char *)pdev->resource[0].name;
streamer_priv->pci_dev = pdev;
if ((pkt_buf_sz[card_no] < 100) || (pkt_buf_sz[card_no] > 18000))
streamer_priv->pkt_buf_sz = PKT_BUF_SZ;
else
streamer_priv->pkt_buf_sz = pkt_buf_sz[card_no];
streamer_priv->streamer_ring_speed = ringspeed[card_no];
streamer_priv->streamer_message_level = message_level[card_no];
pci_set_drvdata(pdev, dev);
spin_lock_init(&streamer_priv->streamer_lock);
pci_read_config_word (pdev, PCI_COMMAND, &pcr);
pcr |= PCI_COMMAND_SERR;
pci_write_config_word (pdev, PCI_COMMAND, pcr);
printk("%s\n", version);
printk("%s: %s. I/O at %hx, MMIO at %p, using irq %d\n",dev->name,
streamer_priv->streamer_card_name,
(unsigned int) dev->base_addr,
streamer_priv->streamer_mmio,
dev->irq);
if (streamer_reset(dev))
goto err_out_unmap;
rc = register_netdev(dev);
if (rc)
goto err_out_unmap;
return 0;
err_out_unmap:
iounmap(streamer_priv->streamer_mmio);
err_out_free_mmio:
release_mem_region(mmio_start, mmio_len);
err_out_free_pio:
release_region(pio_start, pio_len);
err_out_mwi:
pci_clear_mwi(pdev);
err_out_disable:
pci_disable_device(pdev);
err_out:
free_netdev(dev);
#if STREAMER_DEBUG
printk("lanstreamer: Exit error %x\n",rc);
#endif
return rc;
}
static void __devexit streamer_remove_one(struct pci_dev *pdev)
{
struct net_device *dev=pci_get_drvdata(pdev);
struct streamer_private *streamer_priv;
#if STREAMER_DEBUG
printk("lanstreamer::streamer_remove_one entry pdev %p\n",pdev);
#endif
if (dev == NULL) {
printk(KERN_ERR "lanstreamer::streamer_remove_one, ERROR dev is NULL\n");
return;
}
streamer_priv=netdev_priv(dev);
if (streamer_priv == NULL) {
printk(KERN_ERR "lanstreamer::streamer_remove_one, ERROR dev->priv is NULL\n");
return;
}
#if STREAMER_NETWORK_MONITOR
#ifdef CONFIG_PROC_FS
{
struct streamer_private **p, **next;
for (p = &dev_streamer; *p; p = next) {
next = &(*p)->next;
if (*p == streamer_priv) {
*p = *next;
break;
}
}
if (!dev_streamer)
remove_proc_entry("streamer_tr", init_net.proc_net);
}
#endif
#endif
unregister_netdev(dev);
iounmap(streamer_priv->streamer_mmio);
release_mem_region(pci_resource_start(pdev, 1), pci_resource_len(pdev,1));
release_region(pci_resource_start(pdev, 0), pci_resource_len(pdev,0));
pci_clear_mwi(pdev);
pci_disable_device(pdev);
free_netdev(dev);
pci_set_drvdata(pdev, NULL);
}
static int streamer_reset(struct net_device *dev)
{
struct streamer_private *streamer_priv;
__u8 __iomem *streamer_mmio;
unsigned long t;
unsigned int uaa_addr;
struct sk_buff *skb = NULL;
__u16 misr;
streamer_priv = netdev_priv(dev);
streamer_mmio = streamer_priv->streamer_mmio;
writew(readw(streamer_mmio + BCTL) | BCTL_SOFTRESET, streamer_mmio + BCTL);
t = jiffies;
/* Hold soft reset bit for a while */
ssleep(1);
writew(readw(streamer_mmio + BCTL) & ~BCTL_SOFTRESET,
streamer_mmio + BCTL);
#if STREAMER_DEBUG
printk("BCTL: %x\n", readw(streamer_mmio + BCTL));
printk("GPR: %x\n", readw(streamer_mmio + GPR));
printk("SISRMASK: %x\n", readw(streamer_mmio + SISR_MASK));
#endif
writew(readw(streamer_mmio + BCTL) | (BCTL_RX_FIFO_8 | BCTL_TX_FIFO_8), streamer_mmio + BCTL );
if (streamer_priv->streamer_ring_speed == 0) { /* Autosense */
writew(readw(streamer_mmio + GPR) | GPR_AUTOSENSE,
streamer_mmio + GPR);
if (streamer_priv->streamer_message_level)
printk(KERN_INFO "%s: Ringspeed autosense mode on\n",
dev->name);
} else if (streamer_priv->streamer_ring_speed == 16) {
if (streamer_priv->streamer_message_level)
printk(KERN_INFO "%s: Trying to open at 16 Mbps as requested\n",
dev->name);
writew(GPR_16MBPS, streamer_mmio + GPR);
} else if (streamer_priv->streamer_ring_speed == 4) {
if (streamer_priv->streamer_message_level)
printk(KERN_INFO "%s: Trying to open at 4 Mbps as requested\n",
dev->name);
writew(0, streamer_mmio + GPR);
}
skb = dev_alloc_skb(streamer_priv->pkt_buf_sz);
if (!skb) {
printk(KERN_INFO "%s: skb allocation for diagnostics failed...proceeding\n",
dev->name);
} else {
struct streamer_rx_desc *rx_ring;
u8 *data;
rx_ring=(struct streamer_rx_desc *)skb->data;
data=((u8 *)skb->data)+sizeof(struct streamer_rx_desc);
rx_ring->forward=0;
rx_ring->status=0;
rx_ring->buffer=cpu_to_le32(pci_map_single(streamer_priv->pci_dev, data,
512, PCI_DMA_FROMDEVICE));
rx_ring->framelen_buflen=512;
writel(cpu_to_le32(pci_map_single(streamer_priv->pci_dev, rx_ring, 512, PCI_DMA_FROMDEVICE)),
streamer_mmio+RXBDA);
}
#if STREAMER_DEBUG
printk("GPR = %x\n", readw(streamer_mmio + GPR));
#endif
/* start solo init */
writew(SISR_MI, streamer_mmio + SISR_MASK_SUM);
while (!((readw(streamer_mmio + SISR)) & SISR_SRB_REPLY)) {
msleep_interruptible(100);
if (time_after(jiffies, t + 40 * HZ)) {
printk(KERN_ERR
"IBM PCI tokenring card not responding\n");
release_region(dev->base_addr, STREAMER_IO_SPACE);
if (skb)
dev_kfree_skb(skb);
return -1;
}
}
writew(~SISR_SRB_REPLY, streamer_mmio + SISR_RUM);
misr = readw(streamer_mmio + MISR_RUM);
writew(~misr, streamer_mmio + MISR_RUM);
if (skb)
dev_kfree_skb(skb); /* release skb used for diagnostics */
#if STREAMER_DEBUG
printk("LAPWWO: %x, LAPA: %x LAPE: %x\n",
readw(streamer_mmio + LAPWWO), readw(streamer_mmio + LAPA),
readw(streamer_mmio + LAPE));
#endif
#if STREAMER_DEBUG
{
int i;
writew(readw(streamer_mmio + LAPWWO),
streamer_mmio + LAPA);
printk("initialization response srb dump: ");
for (i = 0; i < 10; i++)
printk("%x:",
ntohs(readw(streamer_mmio + LAPDINC)));
printk("\n");
}
#endif
writew(readw(streamer_mmio + LAPWWO) + 6, streamer_mmio + LAPA);
if (readw(streamer_mmio + LAPD)) {
printk(KERN_INFO "tokenring card initialization failed. errorcode : %x\n",
ntohs(readw(streamer_mmio + LAPD)));
release_region(dev->base_addr, STREAMER_IO_SPACE);
return -1;
}
writew(readw(streamer_mmio + LAPWWO) + 8, streamer_mmio + LAPA);
uaa_addr = ntohs(readw(streamer_mmio + LAPDINC));
readw(streamer_mmio + LAPDINC); /* skip over Level.Addr field */
streamer_priv->streamer_addr_table_addr = ntohs(readw(streamer_mmio + LAPDINC));
streamer_priv->streamer_parms_addr = ntohs(readw(streamer_mmio + LAPDINC));
#if STREAMER_DEBUG
printk("UAA resides at %x\n", uaa_addr);
#endif
/* setup uaa area for access with LAPD */
{
int i;
__u16 addr;
writew(uaa_addr, streamer_mmio + LAPA);
for (i = 0; i < 6; i += 2) {
addr=ntohs(readw(streamer_mmio+LAPDINC));
dev->dev_addr[i]= (addr >> 8) & 0xff;
dev->dev_addr[i+1]= addr & 0xff;
}
#if STREAMER_DEBUG
printk("Adapter address: %pM\n", dev->dev_addr);
#endif
}
return 0;
}
static int streamer_open(struct net_device *dev)
{
struct streamer_private *streamer_priv = netdev_priv(dev);
__u8 __iomem *streamer_mmio = streamer_priv->streamer_mmio;
unsigned long flags;
char open_error[255];
int i, open_finished = 1;
__u16 srb_word;
__u16 srb_open;
int rc;
if (readw(streamer_mmio+BMCTL_SUM) & BMCTL_RX_ENABLED) {
rc=streamer_reset(dev);
}
if (request_irq(dev->irq, streamer_interrupt, IRQF_SHARED, "lanstreamer", dev)) {
return -EAGAIN;
}
#if STREAMER_DEBUG
printk("BMCTL: %x\n", readw(streamer_mmio + BMCTL_SUM));
printk("pending ints: %x\n", readw(streamer_mmio + SISR));
#endif
writew(SISR_MI | SISR_SRB_REPLY, streamer_mmio + SISR_MASK); /* more ints later, doesn't stop arb cmd interrupt */
writew(LISR_LIE, streamer_mmio + LISR); /* more ints later */
/* adapter is closed, so SRB is pointed to by LAPWWO */
writew(readw(streamer_mmio + LAPWWO), streamer_mmio + LAPA);
#if STREAMER_DEBUG
printk("LAPWWO: %x, LAPA: %x\n", readw(streamer_mmio + LAPWWO),
readw(streamer_mmio + LAPA));
printk("LAPE: %x\n", readw(streamer_mmio + LAPE));
printk("SISR Mask = %04x\n", readw(streamer_mmio + SISR_MASK));
#endif
do {
for (i = 0; i < SRB_COMMAND_SIZE; i += 2) {
writew(0, streamer_mmio + LAPDINC);
}
writew(readw(streamer_mmio+LAPWWO),streamer_mmio+LAPA);
writew(htons(SRB_OPEN_ADAPTER<<8),streamer_mmio+LAPDINC) ; /* open */
writew(htons(STREAMER_CLEAR_RET_CODE<<8),streamer_mmio+LAPDINC);
writew(STREAMER_CLEAR_RET_CODE, streamer_mmio + LAPDINC);
writew(readw(streamer_mmio + LAPWWO) + 8, streamer_mmio + LAPA);
#if STREAMER_NETWORK_MONITOR
/* If Network Monitor, instruct card to copy MAC frames through the ARB */
writew(htons(OPEN_ADAPTER_ENABLE_FDX | OPEN_ADAPTER_PASS_ADC_MAC | OPEN_ADAPTER_PASS_ATT_MAC | OPEN_ADAPTER_PASS_BEACON), streamer_mmio + LAPDINC); /* offset 8 word contains open options */
#else
writew(htons(OPEN_ADAPTER_ENABLE_FDX), streamer_mmio + LAPDINC); /* Offset 8 word contains Open.Options */
#endif
if (streamer_priv->streamer_laa[0]) {
writew(readw(streamer_mmio + LAPWWO) + 12, streamer_mmio + LAPA);
writew(htons((streamer_priv->streamer_laa[0] << 8) |
streamer_priv->streamer_laa[1]),streamer_mmio+LAPDINC);
writew(htons((streamer_priv->streamer_laa[2] << 8) |
streamer_priv->streamer_laa[3]),streamer_mmio+LAPDINC);
writew(htons((streamer_priv->streamer_laa[4] << 8) |
streamer_priv->streamer_laa[5]),streamer_mmio+LAPDINC);
memcpy(dev->dev_addr, streamer_priv->streamer_laa, dev->addr_len);
}
/* save off srb open offset */
srb_open = readw(streamer_mmio + LAPWWO);
#if STREAMER_DEBUG
writew(readw(streamer_mmio + LAPWWO),
streamer_mmio + LAPA);
printk("srb open request:\n");
for (i = 0; i < 16; i++) {
printk("%x:", ntohs(readw(streamer_mmio + LAPDINC)));
}
printk("\n");
#endif
spin_lock_irqsave(&streamer_priv->streamer_lock, flags);
streamer_priv->srb_queued = 1;
/* signal solo that SRB command has been issued */
writew(LISR_SRB_CMD, streamer_mmio + LISR_SUM);
spin_unlock_irqrestore(&streamer_priv->streamer_lock, flags);
while (streamer_priv->srb_queued) {
interruptible_sleep_on_timeout(&streamer_priv->srb_wait, 5 * HZ);
if (signal_pending(current)) {
printk(KERN_WARNING "%s: SRB timed out.\n", dev->name);
printk(KERN_WARNING "SISR=%x MISR=%x, LISR=%x\n",
readw(streamer_mmio + SISR),
readw(streamer_mmio + MISR_RUM),
readw(streamer_mmio + LISR));
streamer_priv->srb_queued = 0;
break;
}
}
#if STREAMER_DEBUG
printk("SISR_MASK: %x\n", readw(streamer_mmio + SISR_MASK));
printk("srb open response:\n");
writew(srb_open, streamer_mmio + LAPA);
for (i = 0; i < 10; i++) {
printk("%x:",
ntohs(readw(streamer_mmio + LAPDINC)));
}
#endif
/* If we get the same return response as we set, the interrupt wasn't raised and the open
* timed out.
*/
writew(srb_open + 2, streamer_mmio + LAPA);
srb_word = ntohs(readw(streamer_mmio + LAPD)) >> 8;
if (srb_word == STREAMER_CLEAR_RET_CODE) {
printk(KERN_WARNING "%s: Adapter Open time out or error.\n",
dev->name);
return -EIO;
}
if (srb_word != 0) {
if (srb_word == 0x07) {
if (!streamer_priv->streamer_ring_speed && open_finished) { /* Autosense , first time around */
printk(KERN_WARNING "%s: Retrying at different ring speed\n",
dev->name);
open_finished = 0;
} else {
__u16 error_code;
writew(srb_open + 6, streamer_mmio + LAPA);
error_code = ntohs(readw(streamer_mmio + LAPD));
strcpy(open_error, open_maj_error[(error_code & 0xf0) >> 4]);
strcat(open_error, " - ");
strcat(open_error, open_min_error[(error_code & 0x0f)]);
if (!streamer_priv->streamer_ring_speed &&
((error_code & 0x0f) == 0x0d))
{
printk(KERN_WARNING "%s: Tried to autosense ring speed with no monitors present\n", dev->name);
printk(KERN_WARNING "%s: Please try again with a specified ring speed\n", dev->name);
free_irq(dev->irq, dev);
return -EIO;
}
printk(KERN_WARNING "%s: %s\n",
dev->name, open_error);
free_irq(dev->irq, dev);
return -EIO;
} /* if autosense && open_finished */
} else {
printk(KERN_WARNING "%s: Bad OPEN response: %x\n",
dev->name, srb_word);
free_irq(dev->irq, dev);
return -EIO;
}
} else
open_finished = 1;
} while (!(open_finished)); /* Will only loop if ring speed mismatch re-open attempted && autosense is on */
writew(srb_open + 18, streamer_mmio + LAPA);
srb_word=ntohs(readw(streamer_mmio+LAPD)) >> 8;
if (srb_word & (1 << 3))
if (streamer_priv->streamer_message_level)
printk(KERN_INFO "%s: Opened in FDX Mode\n", dev->name);
if (srb_word & 1)
streamer_priv->streamer_ring_speed = 16;
else
streamer_priv->streamer_ring_speed = 4;
if (streamer_priv->streamer_message_level)
printk(KERN_INFO "%s: Opened in %d Mbps mode\n",
dev->name,
streamer_priv->streamer_ring_speed);
writew(srb_open + 8, streamer_mmio + LAPA);
streamer_priv->asb = ntohs(readw(streamer_mmio + LAPDINC));
streamer_priv->srb = ntohs(readw(streamer_mmio + LAPDINC));
streamer_priv->arb = ntohs(readw(streamer_mmio + LAPDINC));
readw(streamer_mmio + LAPDINC); /* offset 14 word is rsvd */
streamer_priv->trb = ntohs(readw(streamer_mmio + LAPDINC));
streamer_priv->streamer_receive_options = 0x00;
streamer_priv->streamer_copy_all_options = 0;
/* setup rx ring */
/* enable rx channel */
writew(~BMCTL_RX_DIS, streamer_mmio + BMCTL_RUM);
/* setup rx descriptors */
streamer_priv->streamer_rx_ring=
kmalloc( sizeof(struct streamer_rx_desc)*
STREAMER_RX_RING_SIZE,GFP_KERNEL);
if (!streamer_priv->streamer_rx_ring) {
printk(KERN_WARNING "%s ALLOC of streamer rx ring FAILED!!\n",dev->name);
return -EIO;
}
for (i = 0; i < STREAMER_RX_RING_SIZE; i++) {
struct sk_buff *skb;
skb = dev_alloc_skb(streamer_priv->pkt_buf_sz);
if (skb == NULL)
break;
skb->dev = dev;
streamer_priv->streamer_rx_ring[i].forward =
cpu_to_le32(pci_map_single(streamer_priv->pci_dev, &streamer_priv->streamer_rx_ring[i + 1],
sizeof(struct streamer_rx_desc), PCI_DMA_FROMDEVICE));
streamer_priv->streamer_rx_ring[i].status = 0;
streamer_priv->streamer_rx_ring[i].buffer =
cpu_to_le32(pci_map_single(streamer_priv->pci_dev, skb->data,
streamer_priv->pkt_buf_sz, PCI_DMA_FROMDEVICE));
streamer_priv->streamer_rx_ring[i].framelen_buflen = streamer_priv->pkt_buf_sz;
streamer_priv->rx_ring_skb[i] = skb;
}
streamer_priv->streamer_rx_ring[STREAMER_RX_RING_SIZE - 1].forward =
cpu_to_le32(pci_map_single(streamer_priv->pci_dev, &streamer_priv->streamer_rx_ring[0],
sizeof(struct streamer_rx_desc), PCI_DMA_FROMDEVICE));
if (i == 0) {
printk(KERN_WARNING "%s: Not enough memory to allocate rx buffers. Adapter disabled\n", dev->name);
free_irq(dev->irq, dev);
return -EIO;
}
streamer_priv->rx_ring_last_received = STREAMER_RX_RING_SIZE - 1; /* last processed rx status */
writel(cpu_to_le32(pci_map_single(streamer_priv->pci_dev, &streamer_priv->streamer_rx_ring[0],
sizeof(struct streamer_rx_desc), PCI_DMA_TODEVICE)),
streamer_mmio + RXBDA);
writel(cpu_to_le32(pci_map_single(streamer_priv->pci_dev, &streamer_priv->streamer_rx_ring[STREAMER_RX_RING_SIZE - 1],
sizeof(struct streamer_rx_desc), PCI_DMA_TODEVICE)),
streamer_mmio + RXLBDA);
/* set bus master interrupt event mask */
writew(MISR_RX_NOBUF | MISR_RX_EOF, streamer_mmio + MISR_MASK);
/* setup tx ring */
streamer_priv->streamer_tx_ring=kmalloc(sizeof(struct streamer_tx_desc)*
STREAMER_TX_RING_SIZE,GFP_KERNEL);
if (!streamer_priv->streamer_tx_ring) {
printk(KERN_WARNING "%s ALLOC of streamer_tx_ring FAILED\n",dev->name);
return -EIO;
}
writew(~BMCTL_TX2_DIS, streamer_mmio + BMCTL_RUM); /* Enables TX channel 2 */
for (i = 0; i < STREAMER_TX_RING_SIZE; i++) {
streamer_priv->streamer_tx_ring[i].forward = cpu_to_le32(pci_map_single(streamer_priv->pci_dev,
&streamer_priv->streamer_tx_ring[i + 1],
sizeof(struct streamer_tx_desc),
PCI_DMA_TODEVICE));
streamer_priv->streamer_tx_ring[i].status = 0;
streamer_priv->streamer_tx_ring[i].bufcnt_framelen = 0;
streamer_priv->streamer_tx_ring[i].buffer = 0;
streamer_priv->streamer_tx_ring[i].buflen = 0;
streamer_priv->streamer_tx_ring[i].rsvd1 = 0;
streamer_priv->streamer_tx_ring[i].rsvd2 = 0;
streamer_priv->streamer_tx_ring[i].rsvd3 = 0;
}
streamer_priv->streamer_tx_ring[STREAMER_TX_RING_SIZE - 1].forward =
cpu_to_le32(pci_map_single(streamer_priv->pci_dev, &streamer_priv->streamer_tx_ring[0],
sizeof(struct streamer_tx_desc), PCI_DMA_TODEVICE));
streamer_priv->free_tx_ring_entries = STREAMER_TX_RING_SIZE;
streamer_priv->tx_ring_free = 0; /* next entry in tx ring to use */
streamer_priv->tx_ring_last_status = STREAMER_TX_RING_SIZE - 1;
/* set Busmaster interrupt event mask (handle receives on interrupt only */
writew(MISR_TX2_EOF | MISR_RX_NOBUF | MISR_RX_EOF, streamer_mmio + MISR_MASK);
/* set system event interrupt mask */
writew(SISR_ADAPTER_CHECK | SISR_ARB_CMD | SISR_TRB_REPLY | SISR_ASB_FREE, streamer_mmio + SISR_MASK_SUM);
#if STREAMER_DEBUG
printk("BMCTL: %x\n", readw(streamer_mmio + BMCTL_SUM));
printk("SISR MASK: %x\n", readw(streamer_mmio + SISR_MASK));
#endif
#if STREAMER_NETWORK_MONITOR
writew(streamer_priv->streamer_addr_table_addr, streamer_mmio + LAPA);
printk("%s: Node Address: %04x:%04x:%04x\n", dev->name,
ntohs(readw(streamer_mmio + LAPDINC)),
ntohs(readw(streamer_mmio + LAPDINC)),
ntohs(readw(streamer_mmio + LAPDINC)));
readw(streamer_mmio + LAPDINC);
readw(streamer_mmio + LAPDINC);
printk("%s: Functional Address: %04x:%04x\n", dev->name,
ntohs(readw(streamer_mmio + LAPDINC)),
ntohs(readw(streamer_mmio + LAPDINC)));
writew(streamer_priv->streamer_parms_addr + 4,
streamer_mmio + LAPA);
printk("%s: NAUN Address: %04x:%04x:%04x\n", dev->name,
ntohs(readw(streamer_mmio + LAPDINC)),
ntohs(readw(streamer_mmio + LAPDINC)),
ntohs(readw(streamer_mmio + LAPDINC)));
#endif
netif_start_queue(dev);
netif_carrier_on(dev);
return 0;
}
/*
* When we enter the rx routine we do not know how many frames have been
* queued on the rx channel. Therefore we start at the next rx status
* position and travel around the receive ring until we have completed
* all the frames.
*
* This means that we may process the frame before we receive the end
* of frame interrupt. This is why we always test the status instead
* of blindly processing the next frame.
*
*/
static void streamer_rx(struct net_device *dev)
{
struct streamer_private *streamer_priv =
netdev_priv(dev);
__u8 __iomem *streamer_mmio = streamer_priv->streamer_mmio;
struct streamer_rx_desc *rx_desc;
int rx_ring_last_received, length, frame_length, buffer_cnt = 0;
struct sk_buff *skb, *skb2;
/* setup the next rx descriptor to be received */
rx_desc = &streamer_priv->streamer_rx_ring[(streamer_priv->rx_ring_last_received + 1) & (STREAMER_RX_RING_SIZE - 1)];
rx_ring_last_received = streamer_priv->rx_ring_last_received;
while (rx_desc->status & 0x01000000) { /* While processed descriptors are available */
if (rx_ring_last_received != streamer_priv->rx_ring_last_received)
{
printk(KERN_WARNING "RX Error 1 rx_ring_last_received not the same %x %x\n",
rx_ring_last_received, streamer_priv->rx_ring_last_received);
}
streamer_priv->rx_ring_last_received = (streamer_priv->rx_ring_last_received + 1) & (STREAMER_RX_RING_SIZE - 1);
rx_ring_last_received = streamer_priv->rx_ring_last_received;
length = rx_desc->framelen_buflen & 0xffff; /* buffer length */
frame_length = (rx_desc->framelen_buflen >> 16) & 0xffff;
if (rx_desc->status & 0x7E830000) { /* errors */
if (streamer_priv->streamer_message_level) {
printk(KERN_WARNING "%s: Rx Error %x\n",
dev->name, rx_desc->status);
}
} else { /* received without errors */
if (rx_desc->status & 0x80000000) { /* frame complete */
buffer_cnt = 1;
skb = dev_alloc_skb(streamer_priv->pkt_buf_sz);
} else {
skb = dev_alloc_skb(frame_length);
}
if (skb == NULL)
{
printk(KERN_WARNING "%s: Not enough memory to copy packet to upper layers.\n", dev->name);
dev->stats.rx_dropped++;
} else { /* we allocated an skb OK */
if (buffer_cnt == 1) {
/* release the DMA mapping */
pci_unmap_single(streamer_priv->pci_dev,
le32_to_cpu(streamer_priv->streamer_rx_ring[rx_ring_last_received].buffer),
streamer_priv->pkt_buf_sz,
PCI_DMA_FROMDEVICE);
skb2 = streamer_priv->rx_ring_skb[rx_ring_last_received];
#if STREAMER_DEBUG_PACKETS
{
int i;
printk("streamer_rx packet print: skb->data2 %p skb->head %p\n", skb2->data, skb2->head);
for (i = 0; i < frame_length; i++)
{
printk("%x:", skb2->data[i]);
if (((i + 1) % 16) == 0)
printk("\n");
}
printk("\n");
}
#endif
skb_put(skb2, length);
skb2->protocol = tr_type_trans(skb2, dev);
/* recycle this descriptor */
streamer_priv->streamer_rx_ring[rx_ring_last_received].status = 0;
streamer_priv->streamer_rx_ring[rx_ring_last_received].framelen_buflen = streamer_priv->pkt_buf_sz;
streamer_priv->streamer_rx_ring[rx_ring_last_received].buffer =
cpu_to_le32(pci_map_single(streamer_priv->pci_dev, skb->data, streamer_priv->pkt_buf_sz,
PCI_DMA_FROMDEVICE));
streamer_priv->rx_ring_skb[rx_ring_last_received] = skb;
/* place recycled descriptor back on the adapter */
writel(cpu_to_le32(pci_map_single(streamer_priv->pci_dev,
&streamer_priv->streamer_rx_ring[rx_ring_last_received],
sizeof(struct streamer_rx_desc), PCI_DMA_FROMDEVICE)),
streamer_mmio + RXLBDA);
/* pass the received skb up to the protocol */
netif_rx(skb2);
} else {
do { /* Walk the buffers */
pci_unmap_single(streamer_priv->pci_dev, le32_to_cpu(rx_desc->buffer), length, PCI_DMA_FROMDEVICE),
memcpy(skb_put(skb, length), (void *)rx_desc->buffer, length); /* copy this fragment */
streamer_priv->streamer_rx_ring[rx_ring_last_received].status = 0;
streamer_priv->streamer_rx_ring[rx_ring_last_received].framelen_buflen = streamer_priv->pkt_buf_sz;
/* give descriptor back to the adapter */
writel(cpu_to_le32(pci_map_single(streamer_priv->pci_dev,
&streamer_priv->streamer_rx_ring[rx_ring_last_received],
length, PCI_DMA_FROMDEVICE)),
streamer_mmio + RXLBDA);
if (rx_desc->status & 0x80000000)
break; /* this descriptor completes the frame */
/* else get the next pending descriptor */
if (rx_ring_last_received!= streamer_priv->rx_ring_last_received)
{
printk("RX Error rx_ring_last_received not the same %x %x\n",
rx_ring_last_received,
streamer_priv->rx_ring_last_received);
}
rx_desc = &streamer_priv->streamer_rx_ring[(streamer_priv->rx_ring_last_received+1) & (STREAMER_RX_RING_SIZE-1)];
length = rx_desc->framelen_buflen & 0xffff; /* buffer length */
streamer_priv->rx_ring_last_received = (streamer_priv->rx_ring_last_received+1) & (STREAMER_RX_RING_SIZE - 1);
rx_ring_last_received = streamer_priv->rx_ring_last_received;
} while (1);
skb->protocol = tr_type_trans(skb, dev);
/* send up to the protocol */
netif_rx(skb);
}
dev->stats.rx_packets++;
dev->stats.rx_bytes += length;
} /* if skb == null */
} /* end received without errors */
/* try the next one */
rx_desc = &streamer_priv->streamer_rx_ring[(rx_ring_last_received + 1) & (STREAMER_RX_RING_SIZE - 1)];
} /* end for all completed rx descriptors */
}
static irqreturn_t streamer_interrupt(int irq, void *dev_id)
{
struct net_device *dev = (struct net_device *) dev_id;
struct streamer_private *streamer_priv =
netdev_priv(dev);
__u8 __iomem *streamer_mmio = streamer_priv->streamer_mmio;
__u16 sisr;
__u16 misr;
u8 max_intr = MAX_INTR;
spin_lock(&streamer_priv->streamer_lock);
sisr = readw(streamer_mmio + SISR);
while((sisr & (SISR_MI | SISR_SRB_REPLY | SISR_ADAPTER_CHECK | SISR_ASB_FREE |
SISR_ARB_CMD | SISR_TRB_REPLY | SISR_PAR_ERR | SISR_SERR_ERR)) &&
(max_intr > 0)) {
if(sisr & SISR_PAR_ERR) {
writew(~SISR_PAR_ERR, streamer_mmio + SISR_RUM);
(void)readw(streamer_mmio + SISR_RUM);
}
else if(sisr & SISR_SERR_ERR) {
writew(~SISR_SERR_ERR, streamer_mmio + SISR_RUM);
(void)readw(streamer_mmio + SISR_RUM);
}
else if(sisr & SISR_MI) {
misr = readw(streamer_mmio + MISR_RUM);
if (misr & MISR_TX2_EOF) {
while(streamer_priv->streamer_tx_ring[(streamer_priv->tx_ring_last_status + 1) & (STREAMER_TX_RING_SIZE - 1)].status) {
streamer_priv->tx_ring_last_status = (streamer_priv->tx_ring_last_status + 1) & (STREAMER_TX_RING_SIZE - 1);
streamer_priv->free_tx_ring_entries++;
dev->stats.tx_bytes += streamer_priv->tx_ring_skb[streamer_priv->tx_ring_last_status]->len;
dev->stats.tx_packets++;
dev_kfree_skb_irq(streamer_priv->tx_ring_skb[streamer_priv->tx_ring_last_status]);
streamer_priv->streamer_tx_ring[streamer_priv->tx_ring_last_status].buffer = 0xdeadbeef;
streamer_priv->streamer_tx_ring[streamer_priv->tx_ring_last_status].status = 0;
streamer_priv->streamer_tx_ring[streamer_priv->tx_ring_last_status].bufcnt_framelen = 0;
streamer_priv->streamer_tx_ring[streamer_priv->tx_ring_last_status].buflen = 0;
streamer_priv->streamer_tx_ring[streamer_priv->tx_ring_last_status].rsvd1 = 0;
streamer_priv->streamer_tx_ring[streamer_priv->tx_ring_last_status].rsvd2 = 0;
streamer_priv->streamer_tx_ring[streamer_priv->tx_ring_last_status].rsvd3 = 0;
}
netif_wake_queue(dev);
}
if (misr & MISR_RX_EOF) {
streamer_rx(dev);
}
/* MISR_RX_EOF */
if (misr & MISR_RX_NOBUF) {
/* According to the documentation, we don't have to do anything,
* but trapping it keeps it out of /var/log/messages.
*/
} /* SISR_RX_NOBUF */
writew(~misr, streamer_mmio + MISR_RUM);
(void)readw(streamer_mmio + MISR_RUM);
}
else if (sisr & SISR_SRB_REPLY) {
if (streamer_priv->srb_queued == 1) {
wake_up_interruptible(&streamer_priv->srb_wait);
} else if (streamer_priv->srb_queued == 2) {
streamer_srb_bh(dev);
}
streamer_priv->srb_queued = 0;
writew(~SISR_SRB_REPLY, streamer_mmio + SISR_RUM);
(void)readw(streamer_mmio + SISR_RUM);
}
else if (sisr & SISR_ADAPTER_CHECK) {
printk(KERN_WARNING "%s: Adapter Check Interrupt Raised, 8 bytes of information follow:\n", dev->name);
writel(readl(streamer_mmio + LAPWWO), streamer_mmio + LAPA);
printk(KERN_WARNING "%s: Words %x:%x:%x:%x:\n",
dev->name, readw(streamer_mmio + LAPDINC),
ntohs(readw(streamer_mmio + LAPDINC)),
ntohs(readw(streamer_mmio + LAPDINC)),
ntohs(readw(streamer_mmio + LAPDINC)));
netif_stop_queue(dev);
netif_carrier_off(dev);
printk(KERN_WARNING "%s: Adapter must be manually reset.\n", dev->name);
}
/* SISR_ADAPTER_CHECK */
else if (sisr & SISR_ASB_FREE) {
/* Wake up anything that is waiting for the asb response */
if (streamer_priv->asb_queued) {
streamer_asb_bh(dev);
}
writew(~SISR_ASB_FREE, streamer_mmio + SISR_RUM);
(void)readw(streamer_mmio + SISR_RUM);
}
/* SISR_ASB_FREE */
else if (sisr & SISR_ARB_CMD) {
streamer_arb_cmd(dev);
writew(~SISR_ARB_CMD, streamer_mmio + SISR_RUM);
(void)readw(streamer_mmio + SISR_RUM);
}
/* SISR_ARB_CMD */
else if (sisr & SISR_TRB_REPLY) {
/* Wake up anything that is waiting for the trb response */
if (streamer_priv->trb_queued) {
wake_up_interruptible(&streamer_priv->
trb_wait);
}
streamer_priv->trb_queued = 0;
writew(~SISR_TRB_REPLY, streamer_mmio + SISR_RUM);
(void)readw(streamer_mmio + SISR_RUM);
}
/* SISR_TRB_REPLY */
sisr = readw(streamer_mmio + SISR);
max_intr--;
} /* while() */
spin_unlock(&streamer_priv->streamer_lock) ;
return IRQ_HANDLED;
}
static netdev_tx_t streamer_xmit(struct sk_buff *skb,
struct net_device *dev)
{
struct streamer_private *streamer_priv =
netdev_priv(dev);
__u8 __iomem *streamer_mmio = streamer_priv->streamer_mmio;
unsigned long flags ;
spin_lock_irqsave(&streamer_priv->streamer_lock, flags);
if (streamer_priv->free_tx_ring_entries) {
streamer_priv->streamer_tx_ring[streamer_priv->tx_ring_free].status = 0;
streamer_priv->streamer_tx_ring[streamer_priv->tx_ring_free].bufcnt_framelen = 0x00020000 | skb->len;
streamer_priv->streamer_tx_ring[streamer_priv->tx_ring_free].buffer =
cpu_to_le32(pci_map_single(streamer_priv->pci_dev, skb->data, skb->len, PCI_DMA_TODEVICE));
streamer_priv->streamer_tx_ring[streamer_priv->tx_ring_free].rsvd1 = skb->len;
streamer_priv->streamer_tx_ring[streamer_priv->tx_ring_free].rsvd2 = 0;
streamer_priv->streamer_tx_ring[streamer_priv->tx_ring_free].rsvd3 = 0;
streamer_priv->streamer_tx_ring[streamer_priv->tx_ring_free].buflen = skb->len;
streamer_priv->tx_ring_skb[streamer_priv->tx_ring_free] = skb;
streamer_priv->free_tx_ring_entries--;
#if STREAMER_DEBUG_PACKETS
{
int i;
printk("streamer_xmit packet print:\n");
for (i = 0; i < skb->len; i++) {
printk("%x:", skb->data[i]);
if (((i + 1) % 16) == 0)
printk("\n");
}
printk("\n");
}
#endif
writel(cpu_to_le32(pci_map_single(streamer_priv->pci_dev,
&streamer_priv->streamer_tx_ring[streamer_priv->tx_ring_free],
sizeof(struct streamer_tx_desc), PCI_DMA_TODEVICE)),
streamer_mmio + TX2LFDA);
(void)readl(streamer_mmio + TX2LFDA);
streamer_priv->tx_ring_free = (streamer_priv->tx_ring_free + 1) & (STREAMER_TX_RING_SIZE - 1);
spin_unlock_irqrestore(&streamer_priv->streamer_lock,flags);
return NETDEV_TX_OK;
} else {
netif_stop_queue(dev);
spin_unlock_irqrestore(&streamer_priv->streamer_lock,flags);
return NETDEV_TX_BUSY;
}
}
static int streamer_close(struct net_device *dev)
{
struct streamer_private *streamer_priv =
netdev_priv(dev);
__u8 __iomem *streamer_mmio = streamer_priv->streamer_mmio;
unsigned long flags;
int i;
netif_stop_queue(dev);
netif_carrier_off(dev);
writew(streamer_priv->srb, streamer_mmio + LAPA);
writew(htons(SRB_CLOSE_ADAPTER << 8),streamer_mmio+LAPDINC);
writew(htons(STREAMER_CLEAR_RET_CODE << 8), streamer_mmio+LAPDINC);
spin_lock_irqsave(&streamer_priv->streamer_lock, flags);
streamer_priv->srb_queued = 1;
writew(LISR_SRB_CMD, streamer_mmio + LISR_SUM);
spin_unlock_irqrestore(&streamer_priv->streamer_lock, flags);
while (streamer_priv->srb_queued)
{
interruptible_sleep_on_timeout(&streamer_priv->srb_wait,
jiffies + 60 * HZ);
if (signal_pending(current))
{
printk(KERN_WARNING "%s: SRB timed out.\n", dev->name);
printk(KERN_WARNING "SISR=%x MISR=%x LISR=%x\n",
readw(streamer_mmio + SISR),
readw(streamer_mmio + MISR_RUM),
readw(streamer_mmio + LISR));
streamer_priv->srb_queued = 0;
break;
}
}
streamer_priv->rx_ring_last_received = (streamer_priv->rx_ring_last_received + 1) & (STREAMER_RX_RING_SIZE - 1);
for (i = 0; i < STREAMER_RX_RING_SIZE; i++) {
if (streamer_priv->rx_ring_skb[streamer_priv->rx_ring_last_received]) {
dev_kfree_skb(streamer_priv->rx_ring_skb[streamer_priv->rx_ring_last_received]);
}
streamer_priv->rx_ring_last_received = (streamer_priv->rx_ring_last_received + 1) & (STREAMER_RX_RING_SIZE - 1);
}
/* reset tx/rx fifo's and busmaster logic */
/* TBD. Add graceful way to reset the LLC channel without doing a soft reset.
writel(readl(streamer_mmio+BCTL)|(3<<13),streamer_mmio+BCTL);
udelay(1);
writel(readl(streamer_mmio+BCTL)&~(3<<13),streamer_mmio+BCTL);
*/
#if STREAMER_DEBUG
writew(streamer_priv->srb, streamer_mmio + LAPA);
printk("srb): ");
for (i = 0; i < 2; i++) {
printk("%x ", ntohs(readw(streamer_mmio + LAPDINC)));
}
printk("\n");
#endif
free_irq(dev->irq, dev);
return 0;
}
static void streamer_set_rx_mode(struct net_device *dev)
{
struct streamer_private *streamer_priv =
netdev_priv(dev);
__u8 __iomem *streamer_mmio = streamer_priv->streamer_mmio;
__u8 options = 0;
struct netdev_hw_addr *ha;
unsigned char dev_mc_address[5];
writel(streamer_priv->srb, streamer_mmio + LAPA);
options = streamer_priv->streamer_copy_all_options;
if (dev->flags & IFF_PROMISC)
options |= (3 << 5); /* All LLC and MAC frames, all through the main rx channel */
else
options &= ~(3 << 5);
/* Only issue the srb if there is a change in options */
if ((options ^ streamer_priv->streamer_copy_all_options))
{
/* Now to issue the srb command to alter the copy.all.options */
writew(htons(SRB_MODIFY_RECEIVE_OPTIONS << 8), streamer_mmio+LAPDINC);
writew(htons(STREAMER_CLEAR_RET_CODE << 8), streamer_mmio+LAPDINC);
writew(htons((streamer_priv->streamer_receive_options << 8) | options),streamer_mmio+LAPDINC);
writew(htons(0x4a41),streamer_mmio+LAPDINC);
writew(htons(0x4d45),streamer_mmio+LAPDINC);
writew(htons(0x5320),streamer_mmio+LAPDINC);
writew(0x2020, streamer_mmio + LAPDINC);
streamer_priv->srb_queued = 2; /* Can't sleep, use srb_bh */
writel(LISR_SRB_CMD, streamer_mmio + LISR_SUM);
streamer_priv->streamer_copy_all_options = options;
return;
}
/* Set the functional addresses we need for multicast */
writel(streamer_priv->srb,streamer_mmio+LAPA);
dev_mc_address[0] = dev_mc_address[1] = dev_mc_address[2] = dev_mc_address[3] = 0 ;
netdev_for_each_mc_addr(ha, dev) {
dev_mc_address[0] |= ha->addr[2];
dev_mc_address[1] |= ha->addr[3];
dev_mc_address[2] |= ha->addr[4];
dev_mc_address[3] |= ha->addr[5];
}
writew(htons(SRB_SET_FUNC_ADDRESS << 8),streamer_mmio+LAPDINC);
writew(htons(STREAMER_CLEAR_RET_CODE << 8), streamer_mmio+LAPDINC);
writew(0,streamer_mmio+LAPDINC);
writew(htons( (dev_mc_address[0] << 8) | dev_mc_address[1]),streamer_mmio+LAPDINC);
writew(htons( (dev_mc_address[2] << 8) | dev_mc_address[3]),streamer_mmio+LAPDINC);
streamer_priv->srb_queued = 2 ;
writel(LISR_SRB_CMD,streamer_mmio+LISR_SUM);
}
static void streamer_srb_bh(struct net_device *dev)
{
struct streamer_private *streamer_priv = netdev_priv(dev);
__u8 __iomem *streamer_mmio = streamer_priv->streamer_mmio;
__u16 srb_word;
writew(streamer_priv->srb, streamer_mmio + LAPA);
srb_word=ntohs(readw(streamer_mmio+LAPDINC)) >> 8;
switch (srb_word) {
/* SRB_MODIFY_RECEIVE_OPTIONS i.e. set_multicast_list options (promiscuous)
* At some point we should do something if we get an error, such as
* resetting the IFF_PROMISC flag in dev
*/
case SRB_MODIFY_RECEIVE_OPTIONS:
srb_word=ntohs(readw(streamer_mmio+LAPDINC)) >> 8;
switch (srb_word) {
case 0x01:
printk(KERN_WARNING "%s: Unrecognized srb command\n", dev->name);
break;
case 0x04:
printk(KERN_WARNING "%s: Adapter must be open for this operation, doh!!\n", dev->name);
break;
default:
if (streamer_priv->streamer_message_level)
printk(KERN_WARNING "%s: Receive Options Modified to %x,%x\n",
dev->name,
streamer_priv->streamer_copy_all_options,
streamer_priv->streamer_receive_options);
break;
} /* switch srb[2] */
break;
/* SRB_SET_GROUP_ADDRESS - Multicast group setting
*/
case SRB_SET_GROUP_ADDRESS:
srb_word=ntohs(readw(streamer_mmio+LAPDINC)) >> 8;
switch (srb_word) {
case 0x00:
break;
case 0x01:
printk(KERN_WARNING "%s: Unrecognized srb command\n",dev->name);
break;
case 0x04:
printk(KERN_WARNING "%s: Adapter must be open for this operation, doh!!\n", dev->name);
break;
case 0x3c:
printk(KERN_WARNING "%s: Group/Functional address indicator bits not set correctly\n", dev->name);
break;
case 0x3e: /* If we ever implement individual multicast addresses, will need to deal with this */
printk(KERN_WARNING "%s: Group address registers full\n", dev->name);
break;
case 0x55:
printk(KERN_INFO "%s: Group Address already set.\n", dev->name);
break;
default:
break;
} /* switch srb[2] */
break;
/* SRB_RESET_GROUP_ADDRESS - Remove a multicast address from group list
*/
case SRB_RESET_GROUP_ADDRESS:
srb_word=ntohs(readw(streamer_mmio+LAPDINC)) >> 8;
switch (srb_word) {
case 0x00:
break;
case 0x01:
printk(KERN_WARNING "%s: Unrecognized srb command\n", dev->name);
break;
case 0x04:
printk(KERN_WARNING "%s: Adapter must be open for this operation, doh!!\n", dev->name);
break;
case 0x39: /* Must deal with this if individual multicast addresses used */
printk(KERN_INFO "%s: Group address not found\n", dev->name);
break;
default:
break;
} /* switch srb[2] */
break;
/* SRB_SET_FUNC_ADDRESS - Called by the set_rx_mode
*/
case SRB_SET_FUNC_ADDRESS:
srb_word=ntohs(readw(streamer_mmio+LAPDINC)) >> 8;
switch (srb_word) {
case 0x00:
if (streamer_priv->streamer_message_level)
printk(KERN_INFO "%s: Functional Address Mask Set\n", dev->name);
break;
case 0x01:
printk(KERN_WARNING "%s: Unrecognized srb command\n", dev->name);
break;
case 0x04:
printk(KERN_WARNING "%s: Adapter must be open for this operation, doh!!\n", dev->name);
break;
default:
break;
} /* switch srb[2] */
break;
/* SRB_READ_LOG - Read and reset the adapter error counters
*/
case SRB_READ_LOG:
srb_word=ntohs(readw(streamer_mmio+LAPDINC)) >> 8;
switch (srb_word) {
case 0x00:
{
int i;
if (streamer_priv->streamer_message_level)
printk(KERN_INFO "%s: Read Log command complete\n", dev->name);
printk("Read Log statistics: ");
writew(streamer_priv->srb + 6,
streamer_mmio + LAPA);
for (i = 0; i < 5; i++) {
printk("%x:", ntohs(readw(streamer_mmio + LAPDINC)));
}
printk("\n");
}
break;
case 0x01:
printk(KERN_WARNING "%s: Unrecognized srb command\n", dev->name);
break;
case 0x04:
printk(KERN_WARNING "%s: Adapter must be open for this operation, doh!!\n", dev->name);
break;
} /* switch srb[2] */
break;
/* SRB_READ_SR_COUNTERS - Read and reset the source routing bridge related counters */
case SRB_READ_SR_COUNTERS:
srb_word=ntohs(readw(streamer_mmio+LAPDINC)) >> 8;
switch (srb_word) {
case 0x00:
if (streamer_priv->streamer_message_level)
printk(KERN_INFO "%s: Read Source Routing Counters issued\n", dev->name);
break;
case 0x01:
printk(KERN_WARNING "%s: Unrecognized srb command\n", dev->name);
break;
case 0x04:
printk(KERN_WARNING "%s: Adapter must be open for this operation, doh!!\n", dev->name);
break;
default:
break;
} /* switch srb[2] */
break;
default:
printk(KERN_WARNING "%s: Unrecognized srb bh return value.\n", dev->name);
break;
} /* switch srb[0] */
}
static int streamer_set_mac_address(struct net_device *dev, void *addr)
{
struct sockaddr *saddr = addr;
struct streamer_private *streamer_priv = netdev_priv(dev);
if (netif_running(dev))
{
printk(KERN_WARNING "%s: Cannot set mac/laa address while card is open\n", dev->name);
return -EIO;
}
memcpy(streamer_priv->streamer_laa, saddr->sa_data, dev->addr_len);
if (streamer_priv->streamer_message_level) {
printk(KERN_INFO "%s: MAC/LAA Set to = %x.%x.%x.%x.%x.%x\n",
dev->name, streamer_priv->streamer_laa[0],
streamer_priv->streamer_laa[1],
streamer_priv->streamer_laa[2],
streamer_priv->streamer_laa[3],
streamer_priv->streamer_laa[4],
streamer_priv->streamer_laa[5]);
}
return 0;
}
static void streamer_arb_cmd(struct net_device *dev)
{
struct streamer_private *streamer_priv =
netdev_priv(dev);
__u8 __iomem *streamer_mmio = streamer_priv->streamer_mmio;
__u8 header_len;
__u16 frame_len, buffer_len;
struct sk_buff *mac_frame;
__u8 frame_data[256];
__u16 buff_off;
__u16 lan_status = 0, lan_status_diff; /* Initialize to stop compiler warning */
__u8 fdx_prot_error;
__u16 next_ptr;
__u16 arb_word;
#if STREAMER_NETWORK_MONITOR
struct trh_hdr *mac_hdr;
#endif
writew(streamer_priv->arb, streamer_mmio + LAPA);
arb_word=ntohs(readw(streamer_mmio+LAPD)) >> 8;
if (arb_word == ARB_RECEIVE_DATA) { /* Receive.data, MAC frames */
writew(streamer_priv->arb + 6, streamer_mmio + LAPA);
streamer_priv->mac_rx_buffer = buff_off = ntohs(readw(streamer_mmio + LAPDINC));
header_len=ntohs(readw(streamer_mmio+LAPDINC)) >> 8; /* 802.5 Token-Ring Header Length */
frame_len = ntohs(readw(streamer_mmio + LAPDINC));
#if STREAMER_DEBUG
{
int i;
__u16 next;
__u8 status;
__u16 len;
writew(ntohs(buff_off), streamer_mmio + LAPA); /*setup window to frame data */
next = htons(readw(streamer_mmio + LAPDINC));
status =
ntohs(readw(streamer_mmio + LAPDINC)) & 0xff;
len = ntohs(readw(streamer_mmio + LAPDINC));
/* print out 1st 14 bytes of frame data */
for (i = 0; i < 7; i++) {
printk("Loc %d = %04x\n", i,
ntohs(readw
(streamer_mmio + LAPDINC)));
}
printk("next %04x, fs %02x, len %04x\n", next,
status, len);
}
#endif
if (!(mac_frame = dev_alloc_skb(frame_len))) {
printk(KERN_WARNING "%s: Memory squeeze, dropping frame.\n",
dev->name);
goto drop_frame;
}
/* Walk the buffer chain, creating the frame */
do {
int i;
__u16 rx_word;
writew(htons(buff_off), streamer_mmio + LAPA); /* setup window to frame data */
next_ptr = ntohs(readw(streamer_mmio + LAPDINC));
readw(streamer_mmio + LAPDINC); /* read thru status word */
buffer_len = ntohs(readw(streamer_mmio + LAPDINC));
if (buffer_len > 256)
break;
i = 0;
while (i < buffer_len) {
rx_word=ntohs(readw(streamer_mmio+LAPDINC));
frame_data[i]=rx_word >> 8;
frame_data[i+1]=rx_word & 0xff;
i += 2;
}
memcpy(skb_put(mac_frame, buffer_len),
frame_data, buffer_len);
} while (next_ptr && (buff_off = next_ptr));
mac_frame->protocol = tr_type_trans(mac_frame, dev);
#if STREAMER_NETWORK_MONITOR
printk(KERN_WARNING "%s: Received MAC Frame, details:\n",
dev->name);
mac_hdr = tr_hdr(mac_frame);
printk(KERN_WARNING
"%s: MAC Frame Dest. Addr: %pM\n",
dev->name, mac_hdr->daddr);
printk(KERN_WARNING
"%s: MAC Frame Srce. Addr: %pM\n",
dev->name, mac_hdr->saddr);
#endif
netif_rx(mac_frame);
/* Now tell the card we have dealt with the received frame */
drop_frame:
/* Set LISR Bit 1 */
writel(LISR_ARB_FREE, streamer_priv->streamer_mmio + LISR_SUM);
/* Is the ASB free ? */
if (!(readl(streamer_priv->streamer_mmio + SISR) & SISR_ASB_FREE))
{
streamer_priv->asb_queued = 1;
writel(LISR_ASB_FREE_REQ, streamer_priv->streamer_mmio + LISR_SUM);
return;
/* Drop out and wait for the bottom half to be run */
}
writew(streamer_priv->asb, streamer_mmio + LAPA);
writew(htons(ASB_RECEIVE_DATA << 8), streamer_mmio+LAPDINC);
writew(htons(STREAMER_CLEAR_RET_CODE << 8), streamer_mmio+LAPDINC);
writew(0, streamer_mmio + LAPDINC);
writew(htons(streamer_priv->mac_rx_buffer), streamer_mmio + LAPD);
writel(LISR_ASB_REPLY | LISR_ASB_FREE_REQ, streamer_priv->streamer_mmio + LISR_SUM);
streamer_priv->asb_queued = 2;
return;
} else if (arb_word == ARB_LAN_CHANGE_STATUS) { /* Lan.change.status */
writew(streamer_priv->arb + 6, streamer_mmio + LAPA);
lan_status = ntohs(readw(streamer_mmio + LAPDINC));
fdx_prot_error = ntohs(readw(streamer_mmio+LAPD)) >> 8;
/* Issue ARB Free */
writew(LISR_ARB_FREE, streamer_priv->streamer_mmio + LISR_SUM);
lan_status_diff = (streamer_priv->streamer_lan_status ^ lan_status) &
lan_status;
if (lan_status_diff & (LSC_LWF | LSC_ARW | LSC_FPE | LSC_RR))
{
if (lan_status_diff & LSC_LWF)
printk(KERN_WARNING "%s: Short circuit detected on the lobe\n", dev->name);
if (lan_status_diff & LSC_ARW)
printk(KERN_WARNING "%s: Auto removal error\n", dev->name);
if (lan_status_diff & LSC_FPE)
printk(KERN_WARNING "%s: FDX Protocol Error\n", dev->name);
if (lan_status_diff & LSC_RR)
printk(KERN_WARNING "%s: Force remove MAC frame received\n", dev->name);
/* Adapter has been closed by the hardware */
/* reset tx/rx fifo's and busmaster logic */
/* @TBD. no llc reset on autostreamer writel(readl(streamer_mmio+BCTL)|(3<<13),streamer_mmio+BCTL);
udelay(1);
writel(readl(streamer_mmio+BCTL)&~(3<<13),streamer_mmio+BCTL); */
netif_stop_queue(dev);
netif_carrier_off(dev);
printk(KERN_WARNING "%s: Adapter must be manually reset.\n", dev->name);
}
/* If serious error */
if (streamer_priv->streamer_message_level) {
if (lan_status_diff & LSC_SIG_LOSS)
printk(KERN_WARNING "%s: No receive signal detected\n", dev->name);
if (lan_status_diff & LSC_HARD_ERR)
printk(KERN_INFO "%s: Beaconing\n", dev->name);
if (lan_status_diff & LSC_SOFT_ERR)
printk(KERN_WARNING "%s: Adapter transmitted Soft Error Report Mac Frame\n", dev->name);
if (lan_status_diff & LSC_TRAN_BCN)
printk(KERN_INFO "%s: We are transmitting the beacon, aaah\n", dev->name);
if (lan_status_diff & LSC_SS)
printk(KERN_INFO "%s: Single Station on the ring\n", dev->name);
if (lan_status_diff & LSC_RING_REC)
printk(KERN_INFO "%s: Ring recovery ongoing\n", dev->name);
if (lan_status_diff & LSC_FDX_MODE)
printk(KERN_INFO "%s: Operating in FDX mode\n", dev->name);
}
if (lan_status_diff & LSC_CO) {
if (streamer_priv->streamer_message_level)
printk(KERN_INFO "%s: Counter Overflow\n", dev->name);
/* Issue READ.LOG command */
writew(streamer_priv->srb, streamer_mmio + LAPA);
writew(htons(SRB_READ_LOG << 8),streamer_mmio+LAPDINC);
writew(htons(STREAMER_CLEAR_RET_CODE << 8), streamer_mmio+LAPDINC);
writew(0, streamer_mmio + LAPDINC);
streamer_priv->srb_queued = 2; /* Can't sleep, use srb_bh */
writew(LISR_SRB_CMD, streamer_mmio + LISR_SUM);
}
if (lan_status_diff & LSC_SR_CO) {
if (streamer_priv->streamer_message_level)
printk(KERN_INFO "%s: Source routing counters overflow\n", dev->name);
/* Issue a READ.SR.COUNTERS */
writew(streamer_priv->srb, streamer_mmio + LAPA);
writew(htons(SRB_READ_SR_COUNTERS << 8),
streamer_mmio+LAPDINC);
writew(htons(STREAMER_CLEAR_RET_CODE << 8),
streamer_mmio+LAPDINC);
streamer_priv->srb_queued = 2; /* Can't sleep, use srb_bh */
writew(LISR_SRB_CMD, streamer_mmio + LISR_SUM);
}
streamer_priv->streamer_lan_status = lan_status;
} /* Lan.change.status */
else
printk(KERN_WARNING "%s: Unknown arb command\n", dev->name);
}
static void streamer_asb_bh(struct net_device *dev)
{
struct streamer_private *streamer_priv =
netdev_priv(dev);
__u8 __iomem *streamer_mmio = streamer_priv->streamer_mmio;
if (streamer_priv->asb_queued == 1)
{
/* Dropped through the first time */
writew(streamer_priv->asb, streamer_mmio + LAPA);
writew(htons(ASB_RECEIVE_DATA << 8),streamer_mmio+LAPDINC);
writew(htons(STREAMER_CLEAR_RET_CODE << 8), streamer_mmio+LAPDINC);
writew(0, streamer_mmio + LAPDINC);
writew(htons(streamer_priv->mac_rx_buffer), streamer_mmio + LAPD);
writel(LISR_ASB_REPLY | LISR_ASB_FREE_REQ, streamer_priv->streamer_mmio + LISR_SUM);
streamer_priv->asb_queued = 2;
return;
}
if (streamer_priv->asb_queued == 2) {
__u8 rc;
writew(streamer_priv->asb + 2, streamer_mmio + LAPA);
rc=ntohs(readw(streamer_mmio+LAPD)) >> 8;
switch (rc) {
case 0x01:
printk(KERN_WARNING "%s: Unrecognized command code\n", dev->name);
break;
case 0x26:
printk(KERN_WARNING "%s: Unrecognized buffer address\n", dev->name);
break;
case 0xFF:
/* Valid response, everything should be ok again */
break;
default:
printk(KERN_WARNING "%s: Invalid return code in asb\n", dev->name);
break;
}
}
streamer_priv->asb_queued = 0;
}
static int streamer_change_mtu(struct net_device *dev, int mtu)
{
struct streamer_private *streamer_priv =
netdev_priv(dev);
__u16 max_mtu;
if (streamer_priv->streamer_ring_speed == 4)
max_mtu = 4500;
else
max_mtu = 18000;
if (mtu > max_mtu)
return -EINVAL;
if (mtu < 100)
return -EINVAL;
dev->mtu = mtu;
streamer_priv->pkt_buf_sz = mtu + TR_HLEN;
return 0;
}
#if STREAMER_NETWORK_MONITOR
#ifdef CONFIG_PROC_FS
static int streamer_proc_info(char *buffer, char **start, off_t offset,
int length, int *eof, void *data)
{
struct streamer_private *sdev=NULL;
struct pci_dev *pci_device = NULL;
int len = 0;
off_t begin = 0;
off_t pos = 0;
int size;
struct net_device *dev;
size = sprintf(buffer, "IBM LanStreamer/MPC Chipset Token Ring Adapters\n");
pos += size;
len += size;
for(sdev=dev_streamer; sdev; sdev=sdev->next) {
pci_device=sdev->pci_dev;
dev=pci_get_drvdata(pci_device);
size = sprintf_info(buffer + len, dev);
len += size;
pos = begin + len;
if (pos < offset) {
len = 0;
begin = pos;
}
if (pos > offset + length)
break;
} /* for */
*start = buffer + (offset - begin); /* Start of wanted data */
len -= (offset - begin); /* Start slop */
if (len > length)
len = length; /* Ending slop */
return len;
}
static int sprintf_info(char *buffer, struct net_device *dev)
{
struct streamer_private *streamer_priv =
netdev_priv(dev);
__u8 __iomem *streamer_mmio = streamer_priv->streamer_mmio;
struct streamer_adapter_addr_table sat;
struct streamer_parameters_table spt;
int size = 0;
int i;
writew(streamer_priv->streamer_addr_table_addr, streamer_mmio + LAPA);
for (i = 0; i < 14; i += 2) {
__u16 io_word;
__u8 *datap = (__u8 *) & sat;
io_word=ntohs(readw(streamer_mmio+LAPDINC));
datap[size]=io_word >> 8;
datap[size+1]=io_word & 0xff;
}
writew(streamer_priv->streamer_parms_addr, streamer_mmio + LAPA);
for (i = 0; i < 68; i += 2) {
__u16 io_word;
__u8 *datap = (__u8 *) & spt;
io_word=ntohs(readw(streamer_mmio+LAPDINC));
datap[size]=io_word >> 8;
datap[size+1]=io_word & 0xff;
}
size = sprintf(buffer, "\n%6s: Adapter Address : Node Address : Functional Addr\n", dev->name);
size += sprintf(buffer + size,
"%6s: %pM : %pM : %02x:%02x:%02x:%02x\n",
dev->name, dev->dev_addr, sat.node_addr,
sat.func_addr[0], sat.func_addr[1],
sat.func_addr[2], sat.func_addr[3]);
size += sprintf(buffer + size, "\n%6s: Token Ring Parameters Table:\n", dev->name);
size += sprintf(buffer + size, "%6s: Physical Addr : Up Node Address : Poll Address : AccPri : Auth Src : Att Code :\n", dev->name);
size += sprintf(buffer + size,
"%6s: %02x:%02x:%02x:%02x : %pM : %pM : %04x : %04x : %04x :\n",
dev->name, spt.phys_addr[0], spt.phys_addr[1],
spt.phys_addr[2], spt.phys_addr[3],
spt.up_node_addr, spt.poll_addr,
ntohs(spt.acc_priority), ntohs(spt.auth_source_class),
ntohs(spt.att_code));
size += sprintf(buffer + size, "%6s: Source Address : Bcn T : Maj. V : Lan St : Lcl Rg : Mon Err : Frame Correl : \n", dev->name);
size += sprintf(buffer + size,
"%6s: %pM : %04x : %04x : %04x : %04x : %04x : %04x : \n",
dev->name, spt.source_addr,
ntohs(spt.beacon_type), ntohs(spt.major_vector),
ntohs(spt.lan_status), ntohs(spt.local_ring),
ntohs(spt.mon_error), ntohs(spt.frame_correl));
size += sprintf(buffer + size, "%6s: Beacon Details : Tx : Rx : NAUN Node Address : NAUN Node Phys : \n",
dev->name);
size += sprintf(buffer + size,
"%6s: : %02x : %02x : %pM : %02x:%02x:%02x:%02x : \n",
dev->name, ntohs(spt.beacon_transmit),
ntohs(spt.beacon_receive),
spt.beacon_naun,
spt.beacon_phys[0], spt.beacon_phys[1],
spt.beacon_phys[2], spt.beacon_phys[3]);
return size;
}
#endif
#endif
static struct pci_driver streamer_pci_driver = {
.name = "lanstreamer",
.id_table = streamer_pci_tbl,
.probe = streamer_init_one,
.remove = __devexit_p(streamer_remove_one),
};
static int __init streamer_init_module(void) {
return pci_register_driver(&streamer_pci_driver);
}
static void __exit streamer_cleanup_module(void) {
pci_unregister_driver(&streamer_pci_driver);
}
module_init(streamer_init_module);
module_exit(streamer_cleanup_module);
MODULE_LICENSE("GPL");
| gpl-2.0 |
nycbjr/android_kernel_asus_tf700 | drivers/net/tokenring/smctr.c | 2914 | 189193 | /*
* smctr.c: A network driver for the SMC Token Ring Adapters.
*
* Written by Jay Schulist <jschlst@samba.org>
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
* This device driver works with the following SMC adapters:
* - SMC TokenCard Elite (8115T, chips 825/584)
* - SMC TokenCard Elite/A MCA (8115T/A, chips 825/594)
*
* Source(s):
* - SMC TokenCard SDK.
*
* Maintainer(s):
* JS Jay Schulist <jschlst@samba.org>
*
* Changes:
* 07102000 JS Fixed a timing problem in smctr_wait_cmd();
* Also added a bit more discriptive error msgs.
* 07122000 JS Fixed problem with detecting a card with
* module io/irq/mem specified.
*
* To do:
* 1. Multicast support.
*
* Initial 2.5 cleanup Alan Cox <alan@lxorguk.ukuu.org.uk> 2002/10/28
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/fcntl.h>
#include <linux/interrupt.h>
#include <linux/ptrace.h>
#include <linux/ioport.h>
#include <linux/in.h>
#include <linux/string.h>
#include <linux/time.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/mca-legacy.h>
#include <linux/delay.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/trdevice.h>
#include <linux/bitops.h>
#include <linux/firmware.h>
#include <asm/system.h>
#include <asm/io.h>
#include <asm/dma.h>
#include <asm/irq.h>
#if BITS_PER_LONG == 64
#error FIXME: driver does not support 64-bit platforms
#endif
#include "smctr.h" /* Our Stuff */
static const char version[] __initdata =
KERN_INFO "smctr.c: v1.4 7/12/00 by jschlst@samba.org\n";
static const char cardname[] = "smctr";
#define SMCTR_IO_EXTENT 20
#ifdef CONFIG_MCA_LEGACY
static unsigned int smctr_posid = 0x6ec6;
#endif
static int ringspeed;
/* SMC Name of the Adapter. */
static char smctr_name[] = "SMC TokenCard";
static char *smctr_model = "Unknown";
/* Use 0 for production, 1 for verification, 2 for debug, and
* 3 for very verbose debug.
*/
#ifndef SMCTR_DEBUG
#define SMCTR_DEBUG 1
#endif
static unsigned int smctr_debug = SMCTR_DEBUG;
/* smctr.c prototypes and functions are arranged alphabeticly
* for clearity, maintainability and pure old fashion fun.
*/
/* A */
static int smctr_alloc_shared_memory(struct net_device *dev);
/* B */
static int smctr_bypass_state(struct net_device *dev);
/* C */
static int smctr_checksum_firmware(struct net_device *dev);
static int __init smctr_chk_isa(struct net_device *dev);
static int smctr_chg_rx_mask(struct net_device *dev);
static int smctr_clear_int(struct net_device *dev);
static int smctr_clear_trc_reset(int ioaddr);
static int smctr_close(struct net_device *dev);
/* D */
static int smctr_decode_firmware(struct net_device *dev,
const struct firmware *fw);
static int smctr_disable_16bit(struct net_device *dev);
static int smctr_disable_adapter_ctrl_store(struct net_device *dev);
static int smctr_disable_bic_int(struct net_device *dev);
/* E */
static int smctr_enable_16bit(struct net_device *dev);
static int smctr_enable_adapter_ctrl_store(struct net_device *dev);
static int smctr_enable_adapter_ram(struct net_device *dev);
static int smctr_enable_bic_int(struct net_device *dev);
/* G */
static int __init smctr_get_boardid(struct net_device *dev, int mca);
static int smctr_get_group_address(struct net_device *dev);
static int smctr_get_functional_address(struct net_device *dev);
static unsigned int smctr_get_num_rx_bdbs(struct net_device *dev);
static int smctr_get_physical_drop_number(struct net_device *dev);
static __u8 *smctr_get_rx_pointer(struct net_device *dev, short queue);
static int smctr_get_station_id(struct net_device *dev);
static FCBlock *smctr_get_tx_fcb(struct net_device *dev, __u16 queue,
__u16 bytes_count);
static int smctr_get_upstream_neighbor_addr(struct net_device *dev);
/* H */
static int smctr_hardware_send_packet(struct net_device *dev,
struct net_local *tp);
/* I */
static int smctr_init_acbs(struct net_device *dev);
static int smctr_init_adapter(struct net_device *dev);
static int smctr_init_card_real(struct net_device *dev);
static int smctr_init_rx_bdbs(struct net_device *dev);
static int smctr_init_rx_fcbs(struct net_device *dev);
static int smctr_init_shared_memory(struct net_device *dev);
static int smctr_init_tx_bdbs(struct net_device *dev);
static int smctr_init_tx_fcbs(struct net_device *dev);
static int smctr_internal_self_test(struct net_device *dev);
static irqreturn_t smctr_interrupt(int irq, void *dev_id);
static int smctr_issue_enable_int_cmd(struct net_device *dev,
__u16 interrupt_enable_mask);
static int smctr_issue_int_ack(struct net_device *dev, __u16 iack_code,
__u16 ibits);
static int smctr_issue_init_timers_cmd(struct net_device *dev);
static int smctr_issue_init_txrx_cmd(struct net_device *dev);
static int smctr_issue_insert_cmd(struct net_device *dev);
static int smctr_issue_read_ring_status_cmd(struct net_device *dev);
static int smctr_issue_read_word_cmd(struct net_device *dev, __u16 aword_cnt);
static int smctr_issue_remove_cmd(struct net_device *dev);
static int smctr_issue_resume_acb_cmd(struct net_device *dev);
static int smctr_issue_resume_rx_bdb_cmd(struct net_device *dev, __u16 queue);
static int smctr_issue_resume_rx_fcb_cmd(struct net_device *dev, __u16 queue);
static int smctr_issue_resume_tx_fcb_cmd(struct net_device *dev, __u16 queue);
static int smctr_issue_test_internal_rom_cmd(struct net_device *dev);
static int smctr_issue_test_hic_cmd(struct net_device *dev);
static int smctr_issue_test_mac_reg_cmd(struct net_device *dev);
static int smctr_issue_trc_loopback_cmd(struct net_device *dev);
static int smctr_issue_tri_loopback_cmd(struct net_device *dev);
static int smctr_issue_write_byte_cmd(struct net_device *dev,
short aword_cnt, void *byte);
static int smctr_issue_write_word_cmd(struct net_device *dev,
short aword_cnt, void *word);
/* J */
static int smctr_join_complete_state(struct net_device *dev);
/* L */
static int smctr_link_tx_fcbs_to_bdbs(struct net_device *dev);
static int smctr_load_firmware(struct net_device *dev);
static int smctr_load_node_addr(struct net_device *dev);
static int smctr_lobe_media_test(struct net_device *dev);
static int smctr_lobe_media_test_cmd(struct net_device *dev);
static int smctr_lobe_media_test_state(struct net_device *dev);
/* M */
static int smctr_make_8025_hdr(struct net_device *dev,
MAC_HEADER *rmf, MAC_HEADER *tmf, __u16 ac_fc);
static int smctr_make_access_pri(struct net_device *dev,
MAC_SUB_VECTOR *tsv);
static int smctr_make_addr_mod(struct net_device *dev, MAC_SUB_VECTOR *tsv);
static int smctr_make_auth_funct_class(struct net_device *dev,
MAC_SUB_VECTOR *tsv);
static int smctr_make_corr(struct net_device *dev,
MAC_SUB_VECTOR *tsv, __u16 correlator);
static int smctr_make_funct_addr(struct net_device *dev,
MAC_SUB_VECTOR *tsv);
static int smctr_make_group_addr(struct net_device *dev,
MAC_SUB_VECTOR *tsv);
static int smctr_make_phy_drop_num(struct net_device *dev,
MAC_SUB_VECTOR *tsv);
static int smctr_make_product_id(struct net_device *dev, MAC_SUB_VECTOR *tsv);
static int smctr_make_station_id(struct net_device *dev, MAC_SUB_VECTOR *tsv);
static int smctr_make_ring_station_status(struct net_device *dev,
MAC_SUB_VECTOR *tsv);
static int smctr_make_ring_station_version(struct net_device *dev,
MAC_SUB_VECTOR *tsv);
static int smctr_make_tx_status_code(struct net_device *dev,
MAC_SUB_VECTOR *tsv, __u16 tx_fstatus);
static int smctr_make_upstream_neighbor_addr(struct net_device *dev,
MAC_SUB_VECTOR *tsv);
static int smctr_make_wrap_data(struct net_device *dev,
MAC_SUB_VECTOR *tsv);
/* O */
static int smctr_open(struct net_device *dev);
static int smctr_open_tr(struct net_device *dev);
/* P */
struct net_device *smctr_probe(int unit);
static int __init smctr_probe1(struct net_device *dev, int ioaddr);
static int smctr_process_rx_packet(MAC_HEADER *rmf, __u16 size,
struct net_device *dev, __u16 rx_status);
/* R */
static int smctr_ram_memory_test(struct net_device *dev);
static int smctr_rcv_chg_param(struct net_device *dev, MAC_HEADER *rmf,
__u16 *correlator);
static int smctr_rcv_init(struct net_device *dev, MAC_HEADER *rmf,
__u16 *correlator);
static int smctr_rcv_tx_forward(struct net_device *dev, MAC_HEADER *rmf);
static int smctr_rcv_rq_addr_state_attch(struct net_device *dev,
MAC_HEADER *rmf, __u16 *correlator);
static int smctr_rcv_unknown(struct net_device *dev, MAC_HEADER *rmf,
__u16 *correlator);
static int smctr_reset_adapter(struct net_device *dev);
static int smctr_restart_tx_chain(struct net_device *dev, short queue);
static int smctr_ring_status_chg(struct net_device *dev);
static int smctr_rx_frame(struct net_device *dev);
/* S */
static int smctr_send_dat(struct net_device *dev);
static netdev_tx_t smctr_send_packet(struct sk_buff *skb,
struct net_device *dev);
static int smctr_send_lobe_media_test(struct net_device *dev);
static int smctr_send_rpt_addr(struct net_device *dev, MAC_HEADER *rmf,
__u16 correlator);
static int smctr_send_rpt_attch(struct net_device *dev, MAC_HEADER *rmf,
__u16 correlator);
static int smctr_send_rpt_state(struct net_device *dev, MAC_HEADER *rmf,
__u16 correlator);
static int smctr_send_rpt_tx_forward(struct net_device *dev,
MAC_HEADER *rmf, __u16 tx_fstatus);
static int smctr_send_rsp(struct net_device *dev, MAC_HEADER *rmf,
__u16 rcode, __u16 correlator);
static int smctr_send_rq_init(struct net_device *dev);
static int smctr_send_tx_forward(struct net_device *dev, MAC_HEADER *rmf,
__u16 *tx_fstatus);
static int smctr_set_auth_access_pri(struct net_device *dev,
MAC_SUB_VECTOR *rsv);
static int smctr_set_auth_funct_class(struct net_device *dev,
MAC_SUB_VECTOR *rsv);
static int smctr_set_corr(struct net_device *dev, MAC_SUB_VECTOR *rsv,
__u16 *correlator);
static int smctr_set_error_timer_value(struct net_device *dev,
MAC_SUB_VECTOR *rsv);
static int smctr_set_frame_forward(struct net_device *dev,
MAC_SUB_VECTOR *rsv, __u8 dc_sc);
static int smctr_set_local_ring_num(struct net_device *dev,
MAC_SUB_VECTOR *rsv);
static unsigned short smctr_set_ctrl_attention(struct net_device *dev);
static void smctr_set_multicast_list(struct net_device *dev);
static int smctr_set_page(struct net_device *dev, __u8 *buf);
static int smctr_set_phy_drop(struct net_device *dev,
MAC_SUB_VECTOR *rsv);
static int smctr_set_ring_speed(struct net_device *dev);
static int smctr_set_rx_look_ahead(struct net_device *dev);
static int smctr_set_trc_reset(int ioaddr);
static int smctr_setup_single_cmd(struct net_device *dev,
__u16 command, __u16 subcommand);
static int smctr_setup_single_cmd_w_data(struct net_device *dev,
__u16 command, __u16 subcommand);
static char *smctr_malloc(struct net_device *dev, __u16 size);
static int smctr_status_chg(struct net_device *dev);
/* T */
static void smctr_timeout(struct net_device *dev);
static int smctr_trc_send_packet(struct net_device *dev, FCBlock *fcb,
__u16 queue);
static __u16 smctr_tx_complete(struct net_device *dev, __u16 queue);
static unsigned short smctr_tx_move_frame(struct net_device *dev,
struct sk_buff *skb, __u8 *pbuff, unsigned int bytes);
/* U */
static int smctr_update_err_stats(struct net_device *dev);
static int smctr_update_rx_chain(struct net_device *dev, __u16 queue);
static int smctr_update_tx_chain(struct net_device *dev, FCBlock *fcb,
__u16 queue);
/* W */
static int smctr_wait_cmd(struct net_device *dev);
static int smctr_wait_while_cbusy(struct net_device *dev);
#define TO_256_BYTE_BOUNDRY(X) (((X + 0xff) & 0xff00) - X)
#define TO_PARAGRAPH_BOUNDRY(X) (((X + 0x0f) & 0xfff0) - X)
#define PARAGRAPH_BOUNDRY(X) smctr_malloc(dev, TO_PARAGRAPH_BOUNDRY(X))
/* Allocate Adapter Shared Memory.
* IMPORTANT NOTE: Any changes to this function MUST be mirrored in the
* function "get_num_rx_bdbs" below!!!
*
* Order of memory allocation:
*
* 0. Initial System Configuration Block Pointer
* 1. System Configuration Block
* 2. System Control Block
* 3. Action Command Block
* 4. Interrupt Status Block
*
* 5. MAC TX FCB'S
* 6. NON-MAC TX FCB'S
* 7. MAC TX BDB'S
* 8. NON-MAC TX BDB'S
* 9. MAC RX FCB'S
* 10. NON-MAC RX FCB'S
* 11. MAC RX BDB'S
* 12. NON-MAC RX BDB'S
* 13. MAC TX Data Buffer( 1, 256 byte buffer)
* 14. MAC RX Data Buffer( 1, 256 byte buffer)
*
* 15. NON-MAC TX Data Buffer
* 16. NON-MAC RX Data Buffer
*/
static int smctr_alloc_shared_memory(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_alloc_shared_memory\n", dev->name);
/* Allocate initial System Control Block pointer.
* This pointer is located in the last page, last offset - 4.
*/
tp->iscpb_ptr = (ISCPBlock *)(tp->ram_access + ((__u32)64 * 0x400)
- (long)ISCP_BLOCK_SIZE);
/* Allocate System Control Blocks. */
tp->scgb_ptr = (SCGBlock *)smctr_malloc(dev, sizeof(SCGBlock));
PARAGRAPH_BOUNDRY(tp->sh_mem_used);
tp->sclb_ptr = (SCLBlock *)smctr_malloc(dev, sizeof(SCLBlock));
PARAGRAPH_BOUNDRY(tp->sh_mem_used);
tp->acb_head = (ACBlock *)smctr_malloc(dev,
sizeof(ACBlock)*tp->num_acbs);
PARAGRAPH_BOUNDRY(tp->sh_mem_used);
tp->isb_ptr = (ISBlock *)smctr_malloc(dev, sizeof(ISBlock));
PARAGRAPH_BOUNDRY(tp->sh_mem_used);
tp->misc_command_data = (__u16 *)smctr_malloc(dev, MISC_DATA_SIZE);
PARAGRAPH_BOUNDRY(tp->sh_mem_used);
/* Allocate transmit FCBs. */
tp->tx_fcb_head[MAC_QUEUE] = (FCBlock *)smctr_malloc(dev,
sizeof(FCBlock) * tp->num_tx_fcbs[MAC_QUEUE]);
tp->tx_fcb_head[NON_MAC_QUEUE] = (FCBlock *)smctr_malloc(dev,
sizeof(FCBlock) * tp->num_tx_fcbs[NON_MAC_QUEUE]);
tp->tx_fcb_head[BUG_QUEUE] = (FCBlock *)smctr_malloc(dev,
sizeof(FCBlock) * tp->num_tx_fcbs[BUG_QUEUE]);
/* Allocate transmit BDBs. */
tp->tx_bdb_head[MAC_QUEUE] = (BDBlock *)smctr_malloc(dev,
sizeof(BDBlock) * tp->num_tx_bdbs[MAC_QUEUE]);
tp->tx_bdb_head[NON_MAC_QUEUE] = (BDBlock *)smctr_malloc(dev,
sizeof(BDBlock) * tp->num_tx_bdbs[NON_MAC_QUEUE]);
tp->tx_bdb_head[BUG_QUEUE] = (BDBlock *)smctr_malloc(dev,
sizeof(BDBlock) * tp->num_tx_bdbs[BUG_QUEUE]);
/* Allocate receive FCBs. */
tp->rx_fcb_head[MAC_QUEUE] = (FCBlock *)smctr_malloc(dev,
sizeof(FCBlock) * tp->num_rx_fcbs[MAC_QUEUE]);
tp->rx_fcb_head[NON_MAC_QUEUE] = (FCBlock *)smctr_malloc(dev,
sizeof(FCBlock) * tp->num_rx_fcbs[NON_MAC_QUEUE]);
/* Allocate receive BDBs. */
tp->rx_bdb_head[MAC_QUEUE] = (BDBlock *)smctr_malloc(dev,
sizeof(BDBlock) * tp->num_rx_bdbs[MAC_QUEUE]);
tp->rx_bdb_end[MAC_QUEUE] = (BDBlock *)smctr_malloc(dev, 0);
tp->rx_bdb_head[NON_MAC_QUEUE] = (BDBlock *)smctr_malloc(dev,
sizeof(BDBlock) * tp->num_rx_bdbs[NON_MAC_QUEUE]);
tp->rx_bdb_end[NON_MAC_QUEUE] = (BDBlock *)smctr_malloc(dev, 0);
/* Allocate MAC transmit buffers.
* MAC Tx Buffers doen't have to be on an ODD Boundary.
*/
tp->tx_buff_head[MAC_QUEUE]
= (__u16 *)smctr_malloc(dev, tp->tx_buff_size[MAC_QUEUE]);
tp->tx_buff_curr[MAC_QUEUE] = tp->tx_buff_head[MAC_QUEUE];
tp->tx_buff_end [MAC_QUEUE] = (__u16 *)smctr_malloc(dev, 0);
/* Allocate BUG transmit buffers. */
tp->tx_buff_head[BUG_QUEUE]
= (__u16 *)smctr_malloc(dev, tp->tx_buff_size[BUG_QUEUE]);
tp->tx_buff_curr[BUG_QUEUE] = tp->tx_buff_head[BUG_QUEUE];
tp->tx_buff_end[BUG_QUEUE] = (__u16 *)smctr_malloc(dev, 0);
/* Allocate MAC receive data buffers.
* MAC Rx buffer doesn't have to be on a 256 byte boundary.
*/
tp->rx_buff_head[MAC_QUEUE] = (__u16 *)smctr_malloc(dev,
RX_DATA_BUFFER_SIZE * tp->num_rx_bdbs[MAC_QUEUE]);
tp->rx_buff_end[MAC_QUEUE] = (__u16 *)smctr_malloc(dev, 0);
/* Allocate Non-MAC transmit buffers.
* ?? For maximum Netware performance, put Tx Buffers on
* ODD Boundary and then restore malloc to Even Boundrys.
*/
smctr_malloc(dev, 1L);
tp->tx_buff_head[NON_MAC_QUEUE]
= (__u16 *)smctr_malloc(dev, tp->tx_buff_size[NON_MAC_QUEUE]);
tp->tx_buff_curr[NON_MAC_QUEUE] = tp->tx_buff_head[NON_MAC_QUEUE];
tp->tx_buff_end [NON_MAC_QUEUE] = (__u16 *)smctr_malloc(dev, 0);
smctr_malloc(dev, 1L);
/* Allocate Non-MAC receive data buffers.
* To guarantee a minimum of 256 contiguous memory to
* UM_Receive_Packet's lookahead pointer, before a page
* change or ring end is encountered, place each rx buffer on
* a 256 byte boundary.
*/
smctr_malloc(dev, TO_256_BYTE_BOUNDRY(tp->sh_mem_used));
tp->rx_buff_head[NON_MAC_QUEUE] = (__u16 *)smctr_malloc(dev,
RX_DATA_BUFFER_SIZE * tp->num_rx_bdbs[NON_MAC_QUEUE]);
tp->rx_buff_end[NON_MAC_QUEUE] = (__u16 *)smctr_malloc(dev, 0);
return 0;
}
/* Enter Bypass state. */
static int smctr_bypass_state(struct net_device *dev)
{
int err;
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_bypass_state\n", dev->name);
err = smctr_setup_single_cmd(dev, ACB_CMD_CHANGE_JOIN_STATE, JS_BYPASS_STATE);
return err;
}
static int smctr_checksum_firmware(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
__u16 i, checksum = 0;
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_checksum_firmware\n", dev->name);
smctr_enable_adapter_ctrl_store(dev);
for(i = 0; i < CS_RAM_SIZE; i += 2)
checksum += *((__u16 *)(tp->ram_access + i));
tp->microcode_version = *(__u16 *)(tp->ram_access
+ CS_RAM_VERSION_OFFSET);
tp->microcode_version >>= 8;
smctr_disable_adapter_ctrl_store(dev);
if(checksum)
return checksum;
return 0;
}
static int __init smctr_chk_mca(struct net_device *dev)
{
#ifdef CONFIG_MCA_LEGACY
struct net_local *tp = netdev_priv(dev);
int current_slot;
__u8 r1, r2, r3, r4, r5;
current_slot = mca_find_unused_adapter(smctr_posid, 0);
if(current_slot == MCA_NOTFOUND)
return -ENODEV;
mca_set_adapter_name(current_slot, smctr_name);
mca_mark_as_used(current_slot);
tp->slot_num = current_slot;
r1 = mca_read_stored_pos(tp->slot_num, 2);
r2 = mca_read_stored_pos(tp->slot_num, 3);
if(tp->slot_num)
outb(CNFG_POS_CONTROL_REG, (__u8)((tp->slot_num - 1) | CNFG_SLOT_ENABLE_BIT));
else
outb(CNFG_POS_CONTROL_REG, (__u8)((tp->slot_num) | CNFG_SLOT_ENABLE_BIT));
r1 = inb(CNFG_POS_REG1);
r2 = inb(CNFG_POS_REG0);
tp->bic_type = BIC_594_CHIP;
/* IO */
r2 = mca_read_stored_pos(tp->slot_num, 2);
r2 &= 0xF0;
dev->base_addr = ((__u16)r2 << 8) + (__u16)0x800;
request_region(dev->base_addr, SMCTR_IO_EXTENT, smctr_name);
/* IRQ */
r5 = mca_read_stored_pos(tp->slot_num, 5);
r5 &= 0xC;
switch(r5)
{
case 0:
dev->irq = 3;
break;
case 0x4:
dev->irq = 4;
break;
case 0x8:
dev->irq = 10;
break;
default:
dev->irq = 15;
break;
}
if (request_irq(dev->irq, smctr_interrupt, IRQF_SHARED, smctr_name, dev)) {
release_region(dev->base_addr, SMCTR_IO_EXTENT);
return -ENODEV;
}
/* Get RAM base */
r3 = mca_read_stored_pos(tp->slot_num, 3);
tp->ram_base = ((__u32)(r3 & 0x7) << 13) + 0x0C0000;
if (r3 & 0x8)
tp->ram_base += 0x010000;
if (r3 & 0x80)
tp->ram_base += 0xF00000;
/* Get Ram Size */
r3 &= 0x30;
r3 >>= 4;
tp->ram_usable = (__u16)CNFG_SIZE_8KB << r3;
tp->ram_size = (__u16)CNFG_SIZE_64KB;
tp->board_id |= TOKEN_MEDIA;
r4 = mca_read_stored_pos(tp->slot_num, 4);
tp->rom_base = ((__u32)(r4 & 0x7) << 13) + 0x0C0000;
if (r4 & 0x8)
tp->rom_base += 0x010000;
/* Get ROM size. */
r4 >>= 4;
switch (r4) {
case 0:
tp->rom_size = CNFG_SIZE_8KB;
break;
case 1:
tp->rom_size = CNFG_SIZE_16KB;
break;
case 2:
tp->rom_size = CNFG_SIZE_32KB;
break;
default:
tp->rom_size = ROM_DISABLE;
}
/* Get Media Type. */
r5 = mca_read_stored_pos(tp->slot_num, 5);
r5 &= CNFG_MEDIA_TYPE_MASK;
switch(r5)
{
case (0):
tp->media_type = MEDIA_STP_4;
break;
case (1):
tp->media_type = MEDIA_STP_16;
break;
case (3):
tp->media_type = MEDIA_UTP_16;
break;
default:
tp->media_type = MEDIA_UTP_4;
break;
}
tp->media_menu = 14;
r2 = mca_read_stored_pos(tp->slot_num, 2);
if(!(r2 & 0x02))
tp->mode_bits |= EARLY_TOKEN_REL;
/* Disable slot */
outb(CNFG_POS_CONTROL_REG, 0);
tp->board_id = smctr_get_boardid(dev, 1);
switch(tp->board_id & 0xffff)
{
case WD8115TA:
smctr_model = "8115T/A";
break;
case WD8115T:
if(tp->extra_info & CHIP_REV_MASK)
smctr_model = "8115T rev XE";
else
smctr_model = "8115T rev XD";
break;
default:
smctr_model = "Unknown";
break;
}
return 0;
#else
return -1;
#endif /* CONFIG_MCA_LEGACY */
}
static int smctr_chg_rx_mask(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
int err = 0;
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_chg_rx_mask\n", dev->name);
smctr_enable_16bit(dev);
smctr_set_page(dev, (__u8 *)tp->ram_access);
if(tp->mode_bits & LOOPING_MODE_MASK)
tp->config_word0 |= RX_OWN_BIT;
else
tp->config_word0 &= ~RX_OWN_BIT;
if(tp->receive_mask & PROMISCUOUS_MODE)
tp->config_word0 |= PROMISCUOUS_BIT;
else
tp->config_word0 &= ~PROMISCUOUS_BIT;
if(tp->receive_mask & ACCEPT_ERR_PACKETS)
tp->config_word0 |= SAVBAD_BIT;
else
tp->config_word0 &= ~SAVBAD_BIT;
if(tp->receive_mask & ACCEPT_ATT_MAC_FRAMES)
tp->config_word0 |= RXATMAC;
else
tp->config_word0 &= ~RXATMAC;
if(tp->receive_mask & ACCEPT_MULTI_PROM)
tp->config_word1 |= MULTICAST_ADDRESS_BIT;
else
tp->config_word1 &= ~MULTICAST_ADDRESS_BIT;
if(tp->receive_mask & ACCEPT_SOURCE_ROUTING_SPANNING)
tp->config_word1 |= SOURCE_ROUTING_SPANNING_BITS;
else
{
if(tp->receive_mask & ACCEPT_SOURCE_ROUTING)
tp->config_word1 |= SOURCE_ROUTING_EXPLORER_BIT;
else
tp->config_word1 &= ~SOURCE_ROUTING_SPANNING_BITS;
}
if((err = smctr_issue_write_word_cmd(dev, RW_CONFIG_REGISTER_0,
&tp->config_word0)))
{
return err;
}
if((err = smctr_issue_write_word_cmd(dev, RW_CONFIG_REGISTER_1,
&tp->config_word1)))
{
return err;
}
smctr_disable_16bit(dev);
return 0;
}
static int smctr_clear_int(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
outb((tp->trc_mask | CSR_CLRTINT), dev->base_addr + CSR);
return 0;
}
static int smctr_clear_trc_reset(int ioaddr)
{
__u8 r;
r = inb(ioaddr + MSR);
outb(~MSR_RST & r, ioaddr + MSR);
return 0;
}
/*
* The inverse routine to smctr_open().
*/
static int smctr_close(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
struct sk_buff *skb;
int err;
netif_stop_queue(dev);
tp->cleanup = 1;
/* Check to see if adapter is already in a closed state. */
if(tp->status != OPEN)
return 0;
smctr_enable_16bit(dev);
smctr_set_page(dev, (__u8 *)tp->ram_access);
if((err = smctr_issue_remove_cmd(dev)))
{
smctr_disable_16bit(dev);
return err;
}
for(;;)
{
skb = skb_dequeue(&tp->SendSkbQueue);
if(skb == NULL)
break;
tp->QueueSkb++;
dev_kfree_skb(skb);
}
return 0;
}
static int smctr_decode_firmware(struct net_device *dev,
const struct firmware *fw)
{
struct net_local *tp = netdev_priv(dev);
short bit = 0x80, shift = 12;
DECODE_TREE_NODE *tree;
short branch, tsize;
__u16 buff = 0;
long weight;
__u8 *ucode;
__u16 *mem;
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_decode_firmware\n", dev->name);
weight = *(long *)(fw->data + WEIGHT_OFFSET);
tsize = *(__u8 *)(fw->data + TREE_SIZE_OFFSET);
tree = (DECODE_TREE_NODE *)(fw->data + TREE_OFFSET);
ucode = (__u8 *)(fw->data + TREE_OFFSET
+ (tsize * sizeof(DECODE_TREE_NODE)));
mem = (__u16 *)(tp->ram_access);
while(weight)
{
branch = ROOT;
while((tree + branch)->tag != LEAF && weight)
{
branch = *ucode & bit ? (tree + branch)->llink
: (tree + branch)->rlink;
bit >>= 1;
weight--;
if(bit == 0)
{
bit = 0x80;
ucode++;
}
}
buff |= (tree + branch)->info << shift;
shift -= 4;
if(shift < 0)
{
*(mem++) = SWAP_BYTES(buff);
buff = 0;
shift = 12;
}
}
/* The following assumes the Control Store Memory has
* been initialized to zero. If the last partial word
* is zero, it will not be written.
*/
if(buff)
*(mem++) = SWAP_BYTES(buff);
return 0;
}
static int smctr_disable_16bit(struct net_device *dev)
{
return 0;
}
/*
* On Exit, Adapter is:
* 1. TRC is in a reset state and un-initialized.
* 2. Adapter memory is enabled.
* 3. Control Store memory is out of context (-WCSS is 1).
*/
static int smctr_disable_adapter_ctrl_store(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
int ioaddr = dev->base_addr;
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_disable_adapter_ctrl_store\n", dev->name);
tp->trc_mask |= CSR_WCSS;
outb(tp->trc_mask, ioaddr + CSR);
return 0;
}
static int smctr_disable_bic_int(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
int ioaddr = dev->base_addr;
tp->trc_mask = CSR_MSK_ALL | CSR_MSKCBUSY
| CSR_MSKTINT | CSR_WCSS;
outb(tp->trc_mask, ioaddr + CSR);
return 0;
}
static int smctr_enable_16bit(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
__u8 r;
if(tp->adapter_bus == BUS_ISA16_TYPE)
{
r = inb(dev->base_addr + LAAR);
outb((r | LAAR_MEM16ENB), dev->base_addr + LAAR);
}
return 0;
}
/*
* To enable the adapter control store memory:
* 1. Adapter must be in a RESET state.
* 2. Adapter memory must be enabled.
* 3. Control Store Memory is in context (-WCSS is 0).
*/
static int smctr_enable_adapter_ctrl_store(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
int ioaddr = dev->base_addr;
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_enable_adapter_ctrl_store\n", dev->name);
smctr_set_trc_reset(ioaddr);
smctr_enable_adapter_ram(dev);
tp->trc_mask &= ~CSR_WCSS;
outb(tp->trc_mask, ioaddr + CSR);
return 0;
}
static int smctr_enable_adapter_ram(struct net_device *dev)
{
int ioaddr = dev->base_addr;
__u8 r;
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_enable_adapter_ram\n", dev->name);
r = inb(ioaddr + MSR);
outb(MSR_MEMB | r, ioaddr + MSR);
return 0;
}
static int smctr_enable_bic_int(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
int ioaddr = dev->base_addr;
__u8 r;
switch(tp->bic_type)
{
case (BIC_584_CHIP):
tp->trc_mask = CSR_MSKCBUSY | CSR_WCSS;
outb(tp->trc_mask, ioaddr + CSR);
r = inb(ioaddr + IRR);
outb(r | IRR_IEN, ioaddr + IRR);
break;
case (BIC_594_CHIP):
tp->trc_mask = CSR_MSKCBUSY | CSR_WCSS;
outb(tp->trc_mask, ioaddr + CSR);
r = inb(ioaddr + IMCCR);
outb(r | IMCCR_EIL, ioaddr + IMCCR);
break;
}
return 0;
}
static int __init smctr_chk_isa(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
int ioaddr = dev->base_addr;
__u8 r1, r2, b, chksum = 0;
__u16 r;
int i;
int err = -ENODEV;
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_chk_isa %#4x\n", dev->name, ioaddr);
if((ioaddr & 0x1F) != 0)
goto out;
/* Grab the region so that no one else tries to probe our ioports. */
if (!request_region(ioaddr, SMCTR_IO_EXTENT, smctr_name)) {
err = -EBUSY;
goto out;
}
/* Checksum SMC node address */
for(i = 0; i < 8; i++)
{
b = inb(ioaddr + LAR0 + i);
chksum += b;
}
if (chksum != NODE_ADDR_CKSUM)
goto out2;
b = inb(ioaddr + BDID);
if(b != BRD_ID_8115T)
{
printk(KERN_ERR "%s: The adapter found is not supported\n", dev->name);
goto out2;
}
/* Check for 8115T Board ID */
r2 = 0;
for(r = 0; r < 8; r++)
{
r1 = inb(ioaddr + 0x8 + r);
r2 += r1;
}
/* value of RegF adds up the sum to 0xFF */
if((r2 != 0xFF) && (r2 != 0xEE))
goto out2;
/* Get adapter ID */
tp->board_id = smctr_get_boardid(dev, 0);
switch(tp->board_id & 0xffff)
{
case WD8115TA:
smctr_model = "8115T/A";
break;
case WD8115T:
if(tp->extra_info & CHIP_REV_MASK)
smctr_model = "8115T rev XE";
else
smctr_model = "8115T rev XD";
break;
default:
smctr_model = "Unknown";
break;
}
/* Store BIC type. */
tp->bic_type = BIC_584_CHIP;
tp->nic_type = NIC_825_CHIP;
/* Copy Ram Size */
tp->ram_usable = CNFG_SIZE_16KB;
tp->ram_size = CNFG_SIZE_64KB;
/* Get 58x Ram Base */
r1 = inb(ioaddr);
r1 &= 0x3F;
r2 = inb(ioaddr + CNFG_LAAR_584);
r2 &= CNFG_LAAR_MASK;
r2 <<= 3;
r2 |= ((r1 & 0x38) >> 3);
tp->ram_base = ((__u32)r2 << 16) + (((__u32)(r1 & 0x7)) << 13);
/* Get 584 Irq */
r1 = 0;
r1 = inb(ioaddr + CNFG_ICR_583);
r1 &= CNFG_ICR_IR2_584;
r2 = inb(ioaddr + CNFG_IRR_583);
r2 &= CNFG_IRR_IRQS; /* 0x60 */
r2 >>= 5;
switch(r2)
{
case 0:
if(r1 == 0)
dev->irq = 2;
else
dev->irq = 10;
break;
case 1:
if(r1 == 0)
dev->irq = 3;
else
dev->irq = 11;
break;
case 2:
if(r1 == 0)
{
if(tp->extra_info & ALTERNATE_IRQ_BIT)
dev->irq = 5;
else
dev->irq = 4;
}
else
dev->irq = 15;
break;
case 3:
if(r1 == 0)
dev->irq = 7;
else
dev->irq = 4;
break;
default:
printk(KERN_ERR "%s: No IRQ found aborting\n", dev->name);
goto out2;
}
if (request_irq(dev->irq, smctr_interrupt, IRQF_SHARED, smctr_name, dev))
goto out2;
/* Get 58x Rom Base */
r1 = inb(ioaddr + CNFG_BIO_583);
r1 &= 0x3E;
r1 |= 0x40;
tp->rom_base = (__u32)r1 << 13;
/* Get 58x Rom Size */
r1 = inb(ioaddr + CNFG_BIO_583);
r1 &= 0xC0;
if(r1 == 0)
tp->rom_size = ROM_DISABLE;
else
{
r1 >>= 6;
tp->rom_size = (__u16)CNFG_SIZE_8KB << r1;
}
/* Get 58x Boot Status */
r1 = inb(ioaddr + CNFG_GP2);
tp->mode_bits &= (~BOOT_STATUS_MASK);
if(r1 & CNFG_GP2_BOOT_NIBBLE)
tp->mode_bits |= BOOT_TYPE_1;
/* Get 58x Zero Wait State */
tp->mode_bits &= (~ZERO_WAIT_STATE_MASK);
r1 = inb(ioaddr + CNFG_IRR_583);
if(r1 & CNFG_IRR_ZWS)
tp->mode_bits |= ZERO_WAIT_STATE_8_BIT;
if(tp->board_id & BOARD_16BIT)
{
r1 = inb(ioaddr + CNFG_LAAR_584);
if(r1 & CNFG_LAAR_ZWS)
tp->mode_bits |= ZERO_WAIT_STATE_16_BIT;
}
/* Get 584 Media Menu */
tp->media_menu = 14;
r1 = inb(ioaddr + CNFG_IRR_583);
tp->mode_bits &= 0xf8ff; /* (~CNFG_INTERFACE_TYPE_MASK) */
if((tp->board_id & TOKEN_MEDIA) == TOKEN_MEDIA)
{
/* Get Advanced Features */
if(((r1 & 0x6) >> 1) == 0x3)
tp->media_type |= MEDIA_UTP_16;
else
{
if(((r1 & 0x6) >> 1) == 0x2)
tp->media_type |= MEDIA_STP_16;
else
{
if(((r1 & 0x6) >> 1) == 0x1)
tp->media_type |= MEDIA_UTP_4;
else
tp->media_type |= MEDIA_STP_4;
}
}
r1 = inb(ioaddr + CNFG_GP2);
if(!(r1 & 0x2) ) /* GP2_ETRD */
tp->mode_bits |= EARLY_TOKEN_REL;
/* see if the chip is corrupted
if(smctr_read_584_chksum(ioaddr))
{
printk(KERN_ERR "%s: EEPROM Checksum Failure\n", dev->name);
free_irq(dev->irq, dev);
goto out2;
}
*/
}
return 0;
out2:
release_region(ioaddr, SMCTR_IO_EXTENT);
out:
return err;
}
static int __init smctr_get_boardid(struct net_device *dev, int mca)
{
struct net_local *tp = netdev_priv(dev);
int ioaddr = dev->base_addr;
__u8 r, r1, IdByte;
__u16 BoardIdMask;
tp->board_id = BoardIdMask = 0;
if(mca)
{
BoardIdMask |= (MICROCHANNEL+INTERFACE_CHIP+TOKEN_MEDIA+PAGED_RAM+BOARD_16BIT);
tp->extra_info |= (INTERFACE_594_CHIP+RAM_SIZE_64K+NIC_825_BIT+ALTERNATE_IRQ_BIT+SLOT_16BIT);
}
else
{
BoardIdMask|=(INTERFACE_CHIP+TOKEN_MEDIA+PAGED_RAM+BOARD_16BIT);
tp->extra_info |= (INTERFACE_584_CHIP + RAM_SIZE_64K
+ NIC_825_BIT + ALTERNATE_IRQ_BIT);
}
if(!mca)
{
r = inb(ioaddr + BID_REG_1);
r &= 0x0c;
outb(r, ioaddr + BID_REG_1);
r = inb(ioaddr + BID_REG_1);
if(r & BID_SIXTEEN_BIT_BIT)
{
tp->extra_info |= SLOT_16BIT;
tp->adapter_bus = BUS_ISA16_TYPE;
}
else
tp->adapter_bus = BUS_ISA8_TYPE;
}
else
tp->adapter_bus = BUS_MCA_TYPE;
/* Get Board Id Byte */
IdByte = inb(ioaddr + BID_BOARD_ID_BYTE);
/* if Major version > 1.0 then
* return;
*/
if(IdByte & 0xF8)
return -1;
r1 = inb(ioaddr + BID_REG_1);
r1 &= BID_ICR_MASK;
r1 |= BID_OTHER_BIT;
outb(r1, ioaddr + BID_REG_1);
r1 = inb(ioaddr + BID_REG_3);
r1 &= BID_EAR_MASK;
r1 |= BID_ENGR_PAGE;
outb(r1, ioaddr + BID_REG_3);
r1 = inb(ioaddr + BID_REG_1);
r1 &= BID_ICR_MASK;
r1 |= (BID_RLA | BID_OTHER_BIT);
outb(r1, ioaddr + BID_REG_1);
r1 = inb(ioaddr + BID_REG_1);
while(r1 & BID_RECALL_DONE_MASK)
r1 = inb(ioaddr + BID_REG_1);
r = inb(ioaddr + BID_LAR_0 + BID_REG_6);
/* clear chip rev bits */
tp->extra_info &= ~CHIP_REV_MASK;
tp->extra_info |= ((r & BID_EEPROM_CHIP_REV_MASK) << 6);
r1 = inb(ioaddr + BID_REG_1);
r1 &= BID_ICR_MASK;
r1 |= BID_OTHER_BIT;
outb(r1, ioaddr + BID_REG_1);
r1 = inb(ioaddr + BID_REG_3);
r1 &= BID_EAR_MASK;
r1 |= BID_EA6;
outb(r1, ioaddr + BID_REG_3);
r1 = inb(ioaddr + BID_REG_1);
r1 &= BID_ICR_MASK;
r1 |= BID_RLA;
outb(r1, ioaddr + BID_REG_1);
r1 = inb(ioaddr + BID_REG_1);
while(r1 & BID_RECALL_DONE_MASK)
r1 = inb(ioaddr + BID_REG_1);
return BoardIdMask;
}
static int smctr_get_group_address(struct net_device *dev)
{
smctr_issue_read_word_cmd(dev, RW_INDIVIDUAL_GROUP_ADDR);
return smctr_wait_cmd(dev);
}
static int smctr_get_functional_address(struct net_device *dev)
{
smctr_issue_read_word_cmd(dev, RW_FUNCTIONAL_ADDR);
return smctr_wait_cmd(dev);
}
/* Calculate number of Non-MAC receive BDB's and data buffers.
* This function must simulate allocateing shared memory exactly
* as the allocate_shared_memory function above.
*/
static unsigned int smctr_get_num_rx_bdbs(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
unsigned int mem_used = 0;
/* Allocate System Control Blocks. */
mem_used += sizeof(SCGBlock);
mem_used += TO_PARAGRAPH_BOUNDRY(mem_used);
mem_used += sizeof(SCLBlock);
mem_used += TO_PARAGRAPH_BOUNDRY(mem_used);
mem_used += sizeof(ACBlock) * tp->num_acbs;
mem_used += TO_PARAGRAPH_BOUNDRY(mem_used);
mem_used += sizeof(ISBlock);
mem_used += TO_PARAGRAPH_BOUNDRY(mem_used);
mem_used += MISC_DATA_SIZE;
/* Allocate transmit FCB's. */
mem_used += TO_PARAGRAPH_BOUNDRY(mem_used);
mem_used += sizeof(FCBlock) * tp->num_tx_fcbs[MAC_QUEUE];
mem_used += sizeof(FCBlock) * tp->num_tx_fcbs[NON_MAC_QUEUE];
mem_used += sizeof(FCBlock) * tp->num_tx_fcbs[BUG_QUEUE];
/* Allocate transmit BDBs. */
mem_used += sizeof(BDBlock) * tp->num_tx_bdbs[MAC_QUEUE];
mem_used += sizeof(BDBlock) * tp->num_tx_bdbs[NON_MAC_QUEUE];
mem_used += sizeof(BDBlock) * tp->num_tx_bdbs[BUG_QUEUE];
/* Allocate receive FCBs. */
mem_used += sizeof(FCBlock) * tp->num_rx_fcbs[MAC_QUEUE];
mem_used += sizeof(FCBlock) * tp->num_rx_fcbs[NON_MAC_QUEUE];
/* Allocate receive BDBs. */
mem_used += sizeof(BDBlock) * tp->num_rx_bdbs[MAC_QUEUE];
/* Allocate MAC transmit buffers.
* MAC transmit buffers don't have to be on an ODD Boundary.
*/
mem_used += tp->tx_buff_size[MAC_QUEUE];
/* Allocate BUG transmit buffers. */
mem_used += tp->tx_buff_size[BUG_QUEUE];
/* Allocate MAC receive data buffers.
* MAC receive buffers don't have to be on a 256 byte boundary.
*/
mem_used += RX_DATA_BUFFER_SIZE * tp->num_rx_bdbs[MAC_QUEUE];
/* Allocate Non-MAC transmit buffers.
* For maximum Netware performance, put Tx Buffers on
* ODD Boundary,and then restore malloc to Even Boundrys.
*/
mem_used += 1L;
mem_used += tp->tx_buff_size[NON_MAC_QUEUE];
mem_used += 1L;
/* CALCULATE NUMBER OF NON-MAC RX BDB'S
* AND NON-MAC RX DATA BUFFERS
*
* Make sure the mem_used offset at this point is the
* same as in allocate_shared memory or the following
* boundary adjustment will be incorrect (i.e. not allocating
* the non-mac receive buffers above cannot change the 256
* byte offset).
*
* Since this cannot be guaranteed, adding the full 256 bytes
* to the amount of shared memory used at this point will guaranteed
* that the rx data buffers do not overflow shared memory.
*/
mem_used += 0x100;
return (0xffff - mem_used) / (RX_DATA_BUFFER_SIZE + sizeof(BDBlock));
}
static int smctr_get_physical_drop_number(struct net_device *dev)
{
smctr_issue_read_word_cmd(dev, RW_PHYSICAL_DROP_NUMBER);
return smctr_wait_cmd(dev);
}
static __u8 * smctr_get_rx_pointer(struct net_device *dev, short queue)
{
struct net_local *tp = netdev_priv(dev);
BDBlock *bdb;
bdb = (BDBlock *)((__u32)tp->ram_access
+ (__u32)(tp->rx_fcb_curr[queue]->trc_bdb_ptr));
tp->rx_fcb_curr[queue]->bdb_ptr = bdb;
return (__u8 *)bdb->data_block_ptr;
}
static int smctr_get_station_id(struct net_device *dev)
{
smctr_issue_read_word_cmd(dev, RW_INDIVIDUAL_MAC_ADDRESS);
return smctr_wait_cmd(dev);
}
/*
* Get the current statistics. This may be called with the card open
* or closed.
*/
static struct net_device_stats *smctr_get_stats(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
return (struct net_device_stats *)&tp->MacStat;
}
static FCBlock *smctr_get_tx_fcb(struct net_device *dev, __u16 queue,
__u16 bytes_count)
{
struct net_local *tp = netdev_priv(dev);
FCBlock *pFCB;
BDBlock *pbdb;
unsigned short alloc_size;
unsigned short *temp;
if(smctr_debug > 20)
printk(KERN_DEBUG "smctr_get_tx_fcb\n");
/* check if there is enough FCB blocks */
if(tp->num_tx_fcbs_used[queue] >= tp->num_tx_fcbs[queue])
return (FCBlock *)(-1L);
/* round off the input pkt size to the nearest even number */
alloc_size = (bytes_count + 1) & 0xfffe;
/* check if enough mem */
if((tp->tx_buff_used[queue] + alloc_size) > tp->tx_buff_size[queue])
return (FCBlock *)(-1L);
/* check if past the end ;
* if exactly enough mem to end of ring, alloc from front.
* this avoids update of curr when curr = end
*/
if(((unsigned long)(tp->tx_buff_curr[queue]) + alloc_size)
>= (unsigned long)(tp->tx_buff_end[queue]))
{
/* check if enough memory from ring head */
alloc_size = alloc_size +
(__u16)((__u32)tp->tx_buff_end[queue]
- (__u32)tp->tx_buff_curr[queue]);
if((tp->tx_buff_used[queue] + alloc_size)
> tp->tx_buff_size[queue])
{
return (FCBlock *)(-1L);
}
/* ring wrap */
tp->tx_buff_curr[queue] = tp->tx_buff_head[queue];
}
tp->tx_buff_used[queue] += alloc_size;
tp->num_tx_fcbs_used[queue]++;
tp->tx_fcb_curr[queue]->frame_length = bytes_count;
tp->tx_fcb_curr[queue]->memory_alloc = alloc_size;
temp = tp->tx_buff_curr[queue];
tp->tx_buff_curr[queue]
= (__u16 *)((__u32)temp + (__u32)((bytes_count + 1) & 0xfffe));
pbdb = tp->tx_fcb_curr[queue]->bdb_ptr;
pbdb->buffer_length = bytes_count;
pbdb->data_block_ptr = temp;
pbdb->trc_data_block_ptr = TRC_POINTER(temp);
pFCB = tp->tx_fcb_curr[queue];
tp->tx_fcb_curr[queue] = tp->tx_fcb_curr[queue]->next_ptr;
return pFCB;
}
static int smctr_get_upstream_neighbor_addr(struct net_device *dev)
{
smctr_issue_read_word_cmd(dev, RW_UPSTREAM_NEIGHBOR_ADDRESS);
return smctr_wait_cmd(dev);
}
static int smctr_hardware_send_packet(struct net_device *dev,
struct net_local *tp)
{
struct tr_statistics *tstat = &tp->MacStat;
struct sk_buff *skb;
FCBlock *fcb;
if(smctr_debug > 10)
printk(KERN_DEBUG"%s: smctr_hardware_send_packet\n", dev->name);
if(tp->status != OPEN)
return -1;
if(tp->monitor_state_ready != 1)
return -1;
for(;;)
{
/* Send first buffer from queue */
skb = skb_dequeue(&tp->SendSkbQueue);
if(skb == NULL)
return -1;
tp->QueueSkb++;
if(skb->len < SMC_HEADER_SIZE || skb->len > tp->max_packet_size)
return -1;
smctr_enable_16bit(dev);
smctr_set_page(dev, (__u8 *)tp->ram_access);
if((fcb = smctr_get_tx_fcb(dev, NON_MAC_QUEUE, skb->len))
== (FCBlock *)(-1L))
{
smctr_disable_16bit(dev);
return -1;
}
smctr_tx_move_frame(dev, skb,
(__u8 *)fcb->bdb_ptr->data_block_ptr, skb->len);
smctr_set_page(dev, (__u8 *)fcb);
smctr_trc_send_packet(dev, fcb, NON_MAC_QUEUE);
dev_kfree_skb(skb);
tstat->tx_packets++;
smctr_disable_16bit(dev);
}
return 0;
}
static int smctr_init_acbs(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
unsigned int i;
ACBlock *acb;
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_init_acbs\n", dev->name);
acb = tp->acb_head;
acb->cmd_done_status = (ACB_COMMAND_DONE | ACB_COMMAND_SUCCESSFUL);
acb->cmd_info = ACB_CHAIN_END;
acb->cmd = 0;
acb->subcmd = 0;
acb->data_offset_lo = 0;
acb->data_offset_hi = 0;
acb->next_ptr
= (ACBlock *)(((char *)acb) + sizeof(ACBlock));
acb->trc_next_ptr = TRC_POINTER(acb->next_ptr);
for(i = 1; i < tp->num_acbs; i++)
{
acb = acb->next_ptr;
acb->cmd_done_status
= (ACB_COMMAND_DONE | ACB_COMMAND_SUCCESSFUL);
acb->cmd_info = ACB_CHAIN_END;
acb->cmd = 0;
acb->subcmd = 0;
acb->data_offset_lo = 0;
acb->data_offset_hi = 0;
acb->next_ptr
= (ACBlock *)(((char *)acb) + sizeof(ACBlock));
acb->trc_next_ptr = TRC_POINTER(acb->next_ptr);
}
acb->next_ptr = tp->acb_head;
acb->trc_next_ptr = TRC_POINTER(tp->acb_head);
tp->acb_next = tp->acb_head->next_ptr;
tp->acb_curr = tp->acb_head->next_ptr;
tp->num_acbs_used = 0;
return 0;
}
static int smctr_init_adapter(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
int err;
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_init_adapter\n", dev->name);
tp->status = CLOSED;
tp->page_offset_mask = (tp->ram_usable * 1024) - 1;
skb_queue_head_init(&tp->SendSkbQueue);
tp->QueueSkb = MAX_TX_QUEUE;
if(!(tp->group_address_0 & 0x0080))
tp->group_address_0 |= 0x00C0;
if(!(tp->functional_address_0 & 0x00C0))
tp->functional_address_0 |= 0x00C0;
tp->functional_address[0] &= 0xFF7F;
if(tp->authorized_function_classes == 0)
tp->authorized_function_classes = 0x7FFF;
if(tp->authorized_access_priority == 0)
tp->authorized_access_priority = 0x06;
smctr_disable_bic_int(dev);
smctr_set_trc_reset(dev->base_addr);
smctr_enable_16bit(dev);
smctr_set_page(dev, (__u8 *)tp->ram_access);
if(smctr_checksum_firmware(dev))
{
printk(KERN_ERR "%s: Previously loaded firmware is missing\n",dev->name);
return -ENOENT;
}
if((err = smctr_ram_memory_test(dev)))
{
printk(KERN_ERR "%s: RAM memory test failed.\n", dev->name);
return -EIO;
}
smctr_set_rx_look_ahead(dev);
smctr_load_node_addr(dev);
/* Initialize adapter for Internal Self Test. */
smctr_reset_adapter(dev);
if((err = smctr_init_card_real(dev)))
{
printk(KERN_ERR "%s: Initialization of card failed (%d)\n",
dev->name, err);
return -EINVAL;
}
/* This routine clobbers the TRC's internal registers. */
if((err = smctr_internal_self_test(dev)))
{
printk(KERN_ERR "%s: Card failed internal self test (%d)\n",
dev->name, err);
return -EINVAL;
}
/* Re-Initialize adapter's internal registers */
smctr_reset_adapter(dev);
if((err = smctr_init_card_real(dev)))
{
printk(KERN_ERR "%s: Initialization of card failed (%d)\n",
dev->name, err);
return -EINVAL;
}
smctr_enable_bic_int(dev);
if((err = smctr_issue_enable_int_cmd(dev, TRC_INTERRUPT_ENABLE_MASK)))
return err;
smctr_disable_16bit(dev);
return 0;
}
static int smctr_init_card_real(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
int err = 0;
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_init_card_real\n", dev->name);
tp->sh_mem_used = 0;
tp->num_acbs = NUM_OF_ACBS;
/* Range Check Max Packet Size */
if(tp->max_packet_size < 256)
tp->max_packet_size = 256;
else
{
if(tp->max_packet_size > NON_MAC_TX_BUFFER_MEMORY)
tp->max_packet_size = NON_MAC_TX_BUFFER_MEMORY;
}
tp->num_of_tx_buffs = (NON_MAC_TX_BUFFER_MEMORY
/ tp->max_packet_size) - 1;
if(tp->num_of_tx_buffs > NUM_NON_MAC_TX_FCBS)
tp->num_of_tx_buffs = NUM_NON_MAC_TX_FCBS;
else
{
if(tp->num_of_tx_buffs == 0)
tp->num_of_tx_buffs = 1;
}
/* Tx queue constants */
tp->num_tx_fcbs [BUG_QUEUE] = NUM_BUG_TX_FCBS;
tp->num_tx_bdbs [BUG_QUEUE] = NUM_BUG_TX_BDBS;
tp->tx_buff_size [BUG_QUEUE] = BUG_TX_BUFFER_MEMORY;
tp->tx_buff_used [BUG_QUEUE] = 0;
tp->tx_queue_status [BUG_QUEUE] = NOT_TRANSMITING;
tp->num_tx_fcbs [MAC_QUEUE] = NUM_MAC_TX_FCBS;
tp->num_tx_bdbs [MAC_QUEUE] = NUM_MAC_TX_BDBS;
tp->tx_buff_size [MAC_QUEUE] = MAC_TX_BUFFER_MEMORY;
tp->tx_buff_used [MAC_QUEUE] = 0;
tp->tx_queue_status [MAC_QUEUE] = NOT_TRANSMITING;
tp->num_tx_fcbs [NON_MAC_QUEUE] = NUM_NON_MAC_TX_FCBS;
tp->num_tx_bdbs [NON_MAC_QUEUE] = NUM_NON_MAC_TX_BDBS;
tp->tx_buff_size [NON_MAC_QUEUE] = NON_MAC_TX_BUFFER_MEMORY;
tp->tx_buff_used [NON_MAC_QUEUE] = 0;
tp->tx_queue_status [NON_MAC_QUEUE] = NOT_TRANSMITING;
/* Receive Queue Constants */
tp->num_rx_fcbs[MAC_QUEUE] = NUM_MAC_RX_FCBS;
tp->num_rx_bdbs[MAC_QUEUE] = NUM_MAC_RX_BDBS;
if(tp->extra_info & CHIP_REV_MASK)
tp->num_rx_fcbs[NON_MAC_QUEUE] = 78; /* 825 Rev. XE */
else
tp->num_rx_fcbs[NON_MAC_QUEUE] = 7; /* 825 Rev. XD */
tp->num_rx_bdbs[NON_MAC_QUEUE] = smctr_get_num_rx_bdbs(dev);
smctr_alloc_shared_memory(dev);
smctr_init_shared_memory(dev);
if((err = smctr_issue_init_timers_cmd(dev)))
return err;
if((err = smctr_issue_init_txrx_cmd(dev)))
{
printk(KERN_ERR "%s: Hardware failure\n", dev->name);
return err;
}
return 0;
}
static int smctr_init_rx_bdbs(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
unsigned int i, j;
BDBlock *bdb;
__u16 *buf;
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_init_rx_bdbs\n", dev->name);
for(i = 0; i < NUM_RX_QS_USED; i++)
{
bdb = tp->rx_bdb_head[i];
buf = tp->rx_buff_head[i];
bdb->info = (BDB_CHAIN_END | BDB_NO_WARNING);
bdb->buffer_length = RX_DATA_BUFFER_SIZE;
bdb->next_ptr = (BDBlock *)(((char *)bdb) + sizeof(BDBlock));
bdb->data_block_ptr = buf;
bdb->trc_next_ptr = TRC_POINTER(bdb->next_ptr);
if(i == NON_MAC_QUEUE)
bdb->trc_data_block_ptr = RX_BUFF_TRC_POINTER(buf);
else
bdb->trc_data_block_ptr = TRC_POINTER(buf);
for(j = 1; j < tp->num_rx_bdbs[i]; j++)
{
bdb->next_ptr->back_ptr = bdb;
bdb = bdb->next_ptr;
buf = (__u16 *)((char *)buf + RX_DATA_BUFFER_SIZE);
bdb->info = (BDB_NOT_CHAIN_END | BDB_NO_WARNING);
bdb->buffer_length = RX_DATA_BUFFER_SIZE;
bdb->next_ptr = (BDBlock *)(((char *)bdb) + sizeof(BDBlock));
bdb->data_block_ptr = buf;
bdb->trc_next_ptr = TRC_POINTER(bdb->next_ptr);
if(i == NON_MAC_QUEUE)
bdb->trc_data_block_ptr = RX_BUFF_TRC_POINTER(buf);
else
bdb->trc_data_block_ptr = TRC_POINTER(buf);
}
bdb->next_ptr = tp->rx_bdb_head[i];
bdb->trc_next_ptr = TRC_POINTER(tp->rx_bdb_head[i]);
tp->rx_bdb_head[i]->back_ptr = bdb;
tp->rx_bdb_curr[i] = tp->rx_bdb_head[i]->next_ptr;
}
return 0;
}
static int smctr_init_rx_fcbs(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
unsigned int i, j;
FCBlock *fcb;
for(i = 0; i < NUM_RX_QS_USED; i++)
{
fcb = tp->rx_fcb_head[i];
fcb->frame_status = 0;
fcb->frame_length = 0;
fcb->info = FCB_CHAIN_END;
fcb->next_ptr = (FCBlock *)(((char*)fcb) + sizeof(FCBlock));
if(i == NON_MAC_QUEUE)
fcb->trc_next_ptr = RX_FCB_TRC_POINTER(fcb->next_ptr);
else
fcb->trc_next_ptr = TRC_POINTER(fcb->next_ptr);
for(j = 1; j < tp->num_rx_fcbs[i]; j++)
{
fcb->next_ptr->back_ptr = fcb;
fcb = fcb->next_ptr;
fcb->frame_status = 0;
fcb->frame_length = 0;
fcb->info = FCB_WARNING;
fcb->next_ptr
= (FCBlock *)(((char *)fcb) + sizeof(FCBlock));
if(i == NON_MAC_QUEUE)
fcb->trc_next_ptr
= RX_FCB_TRC_POINTER(fcb->next_ptr);
else
fcb->trc_next_ptr
= TRC_POINTER(fcb->next_ptr);
}
fcb->next_ptr = tp->rx_fcb_head[i];
if(i == NON_MAC_QUEUE)
fcb->trc_next_ptr = RX_FCB_TRC_POINTER(fcb->next_ptr);
else
fcb->trc_next_ptr = TRC_POINTER(fcb->next_ptr);
tp->rx_fcb_head[i]->back_ptr = fcb;
tp->rx_fcb_curr[i] = tp->rx_fcb_head[i]->next_ptr;
}
return 0;
}
static int smctr_init_shared_memory(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
unsigned int i;
__u32 *iscpb;
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_init_shared_memory\n", dev->name);
smctr_set_page(dev, (__u8 *)(unsigned int)tp->iscpb_ptr);
/* Initialize Initial System Configuration Point. (ISCP) */
iscpb = (__u32 *)PAGE_POINTER(&tp->iscpb_ptr->trc_scgb_ptr);
*iscpb = (__u32)(SWAP_WORDS(TRC_POINTER(tp->scgb_ptr)));
smctr_set_page(dev, (__u8 *)tp->ram_access);
/* Initialize System Configuration Pointers. (SCP) */
tp->scgb_ptr->config = (SCGB_ADDRESS_POINTER_FORMAT
| SCGB_MULTI_WORD_CONTROL | SCGB_DATA_FORMAT
| SCGB_BURST_LENGTH);
tp->scgb_ptr->trc_sclb_ptr = TRC_POINTER(tp->sclb_ptr);
tp->scgb_ptr->trc_acb_ptr = TRC_POINTER(tp->acb_head);
tp->scgb_ptr->trc_isb_ptr = TRC_POINTER(tp->isb_ptr);
tp->scgb_ptr->isbsiz = (sizeof(ISBlock)) - 2;
/* Initialize System Control Block. (SCB) */
tp->sclb_ptr->valid_command = SCLB_VALID | SCLB_CMD_NOP;
tp->sclb_ptr->iack_code = 0;
tp->sclb_ptr->resume_control = 0;
tp->sclb_ptr->int_mask_control = 0;
tp->sclb_ptr->int_mask_state = 0;
/* Initialize Interrupt Status Block. (ISB) */
for(i = 0; i < NUM_OF_INTERRUPTS; i++)
{
tp->isb_ptr->IStatus[i].IType = 0xf0;
tp->isb_ptr->IStatus[i].ISubtype = 0;
}
tp->current_isb_index = 0;
/* Initialize Action Command Block. (ACB) */
smctr_init_acbs(dev);
/* Initialize transmit FCB's and BDB's. */
smctr_link_tx_fcbs_to_bdbs(dev);
smctr_init_tx_bdbs(dev);
smctr_init_tx_fcbs(dev);
/* Initialize receive FCB's and BDB's. */
smctr_init_rx_bdbs(dev);
smctr_init_rx_fcbs(dev);
return 0;
}
static int smctr_init_tx_bdbs(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
unsigned int i, j;
BDBlock *bdb;
for(i = 0; i < NUM_TX_QS_USED; i++)
{
bdb = tp->tx_bdb_head[i];
bdb->info = (BDB_NOT_CHAIN_END | BDB_NO_WARNING);
bdb->next_ptr = (BDBlock *)(((char *)bdb) + sizeof(BDBlock));
bdb->trc_next_ptr = TRC_POINTER(bdb->next_ptr);
for(j = 1; j < tp->num_tx_bdbs[i]; j++)
{
bdb->next_ptr->back_ptr = bdb;
bdb = bdb->next_ptr;
bdb->info = (BDB_NOT_CHAIN_END | BDB_NO_WARNING);
bdb->next_ptr
= (BDBlock *)(((char *)bdb) + sizeof( BDBlock)); bdb->trc_next_ptr = TRC_POINTER(bdb->next_ptr);
}
bdb->next_ptr = tp->tx_bdb_head[i];
bdb->trc_next_ptr = TRC_POINTER(tp->tx_bdb_head[i]);
tp->tx_bdb_head[i]->back_ptr = bdb;
}
return 0;
}
static int smctr_init_tx_fcbs(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
unsigned int i, j;
FCBlock *fcb;
for(i = 0; i < NUM_TX_QS_USED; i++)
{
fcb = tp->tx_fcb_head[i];
fcb->frame_status = 0;
fcb->frame_length = 0;
fcb->info = FCB_CHAIN_END;
fcb->next_ptr = (FCBlock *)(((char *)fcb) + sizeof(FCBlock));
fcb->trc_next_ptr = TRC_POINTER(fcb->next_ptr);
for(j = 1; j < tp->num_tx_fcbs[i]; j++)
{
fcb->next_ptr->back_ptr = fcb;
fcb = fcb->next_ptr;
fcb->frame_status = 0;
fcb->frame_length = 0;
fcb->info = FCB_CHAIN_END;
fcb->next_ptr
= (FCBlock *)(((char *)fcb) + sizeof(FCBlock));
fcb->trc_next_ptr = TRC_POINTER(fcb->next_ptr);
}
fcb->next_ptr = tp->tx_fcb_head[i];
fcb->trc_next_ptr = TRC_POINTER(tp->tx_fcb_head[i]);
tp->tx_fcb_head[i]->back_ptr = fcb;
tp->tx_fcb_end[i] = tp->tx_fcb_head[i]->next_ptr;
tp->tx_fcb_curr[i] = tp->tx_fcb_head[i]->next_ptr;
tp->num_tx_fcbs_used[i] = 0;
}
return 0;
}
static int smctr_internal_self_test(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
int err;
if((err = smctr_issue_test_internal_rom_cmd(dev)))
return err;
if((err = smctr_wait_cmd(dev)))
return err;
if(tp->acb_head->cmd_done_status & 0xff)
return -1;
if((err = smctr_issue_test_hic_cmd(dev)))
return err;
if((err = smctr_wait_cmd(dev)))
return err;
if(tp->acb_head->cmd_done_status & 0xff)
return -1;
if((err = smctr_issue_test_mac_reg_cmd(dev)))
return err;
if((err = smctr_wait_cmd(dev)))
return err;
if(tp->acb_head->cmd_done_status & 0xff)
return -1;
return 0;
}
/*
* The typical workload of the driver: Handle the network interface interrupts.
*/
static irqreturn_t smctr_interrupt(int irq, void *dev_id)
{
struct net_device *dev = dev_id;
struct net_local *tp;
int ioaddr;
__u16 interrupt_unmask_bits = 0, interrupt_ack_code = 0xff00;
__u16 err1, err = NOT_MY_INTERRUPT;
__u8 isb_type, isb_subtype;
__u16 isb_index;
ioaddr = dev->base_addr;
tp = netdev_priv(dev);
if(tp->status == NOT_INITIALIZED)
return IRQ_NONE;
spin_lock(&tp->lock);
smctr_disable_bic_int(dev);
smctr_enable_16bit(dev);
smctr_clear_int(dev);
/* First read the LSB */
while((tp->isb_ptr->IStatus[tp->current_isb_index].IType & 0xf0) == 0)
{
isb_index = tp->current_isb_index;
isb_type = tp->isb_ptr->IStatus[isb_index].IType;
isb_subtype = tp->isb_ptr->IStatus[isb_index].ISubtype;
(tp->current_isb_index)++;
if(tp->current_isb_index == NUM_OF_INTERRUPTS)
tp->current_isb_index = 0;
if(isb_type >= 0x10)
{
smctr_disable_16bit(dev);
spin_unlock(&tp->lock);
return IRQ_HANDLED;
}
err = HARDWARE_FAILED;
interrupt_ack_code = isb_index;
tp->isb_ptr->IStatus[isb_index].IType |= 0xf0;
interrupt_unmask_bits |= (1 << (__u16)isb_type);
switch(isb_type)
{
case ISB_IMC_MAC_TYPE_3:
smctr_disable_16bit(dev);
switch(isb_subtype)
{
case 0:
tp->monitor_state = MS_MONITOR_FSM_INACTIVE;
break;
case 1:
tp->monitor_state = MS_REPEAT_BEACON_STATE;
break;
case 2:
tp->monitor_state = MS_REPEAT_CLAIM_TOKEN_STATE;
break;
case 3:
tp->monitor_state = MS_TRANSMIT_CLAIM_TOKEN_STATE; break;
case 4:
tp->monitor_state = MS_STANDBY_MONITOR_STATE;
break;
case 5:
tp->monitor_state = MS_TRANSMIT_BEACON_STATE;
break;
case 6:
tp->monitor_state = MS_ACTIVE_MONITOR_STATE;
break;
case 7:
tp->monitor_state = MS_TRANSMIT_RING_PURGE_STATE;
break;
case 8: /* diagnostic state */
break;
case 9:
tp->monitor_state = MS_BEACON_TEST_STATE;
if(smctr_lobe_media_test(dev))
{
tp->ring_status_flags = RING_STATUS_CHANGED;
tp->ring_status = AUTO_REMOVAL_ERROR;
smctr_ring_status_chg(dev);
smctr_bypass_state(dev);
}
else
smctr_issue_insert_cmd(dev);
break;
/* case 0x0a-0xff, illegal states */
default:
break;
}
tp->ring_status_flags = MONITOR_STATE_CHANGED;
err = smctr_ring_status_chg(dev);
smctr_enable_16bit(dev);
break;
/* Type 0x02 - MAC Error Counters Interrupt
* One or more MAC Error Counter is half full
* MAC Error Counters
* Lost_FR_Error_Counter
* RCV_Congestion_Counter
* FR_copied_Error_Counter
* FREQ_Error_Counter
* Token_Error_Counter
* Line_Error_Counter
* Internal_Error_Count
*/
case ISB_IMC_MAC_ERROR_COUNTERS:
/* Read 802.5 Error Counters */
err = smctr_issue_read_ring_status_cmd(dev);
break;
/* Type 0x04 - MAC Type 2 Interrupt
* HOST needs to enqueue MAC Frame for transmission
* SubType Bit 15 - RQ_INIT_PDU( Request Initialization) * Changed from RQ_INIT_PDU to
* TRC_Status_Changed_Indicate
*/
case ISB_IMC_MAC_TYPE_2:
err = smctr_issue_read_ring_status_cmd(dev);
break;
/* Type 0x05 - TX Frame Interrupt (FI). */
case ISB_IMC_TX_FRAME:
/* BUG QUEUE for TRC stuck receive BUG */
if(isb_subtype & TX_PENDING_PRIORITY_2)
{
if((err = smctr_tx_complete(dev, BUG_QUEUE)) != SUCCESS)
break;
}
/* NON-MAC frames only */
if(isb_subtype & TX_PENDING_PRIORITY_1)
{
if((err = smctr_tx_complete(dev, NON_MAC_QUEUE)) != SUCCESS)
break;
}
/* MAC frames only */
if(isb_subtype & TX_PENDING_PRIORITY_0)
err = smctr_tx_complete(dev, MAC_QUEUE); break;
/* Type 0x06 - TX END OF QUEUE (FE) */
case ISB_IMC_END_OF_TX_QUEUE:
/* BUG queue */
if(isb_subtype & TX_PENDING_PRIORITY_2)
{
/* ok to clear Receive FIFO overrun
* imask send_BUG now completes.
*/
interrupt_unmask_bits |= 0x800;
tp->tx_queue_status[BUG_QUEUE] = NOT_TRANSMITING;
if((err = smctr_tx_complete(dev, BUG_QUEUE)) != SUCCESS)
break;
if((err = smctr_restart_tx_chain(dev, BUG_QUEUE)) != SUCCESS)
break;
}
/* NON-MAC queue only */
if(isb_subtype & TX_PENDING_PRIORITY_1)
{
tp->tx_queue_status[NON_MAC_QUEUE] = NOT_TRANSMITING;
if((err = smctr_tx_complete(dev, NON_MAC_QUEUE)) != SUCCESS)
break;
if((err = smctr_restart_tx_chain(dev, NON_MAC_QUEUE)) != SUCCESS)
break;
}
/* MAC queue only */
if(isb_subtype & TX_PENDING_PRIORITY_0)
{
tp->tx_queue_status[MAC_QUEUE] = NOT_TRANSMITING;
if((err = smctr_tx_complete(dev, MAC_QUEUE)) != SUCCESS)
break;
err = smctr_restart_tx_chain(dev, MAC_QUEUE);
}
break;
/* Type 0x07 - NON-MAC RX Resource Interrupt
* Subtype bit 12 - (BW) BDB warning
* Subtype bit 13 - (FW) FCB warning
* Subtype bit 14 - (BE) BDB End of chain
* Subtype bit 15 - (FE) FCB End of chain
*/
case ISB_IMC_NON_MAC_RX_RESOURCE:
tp->rx_fifo_overrun_count = 0;
tp->receive_queue_number = NON_MAC_QUEUE;
err1 = smctr_rx_frame(dev);
if(isb_subtype & NON_MAC_RX_RESOURCE_FE)
{
if((err = smctr_issue_resume_rx_fcb_cmd( dev, NON_MAC_QUEUE)) != SUCCESS) break;
if(tp->ptr_rx_fcb_overruns)
(*tp->ptr_rx_fcb_overruns)++;
}
if(isb_subtype & NON_MAC_RX_RESOURCE_BE)
{
if((err = smctr_issue_resume_rx_bdb_cmd( dev, NON_MAC_QUEUE)) != SUCCESS) break;
if(tp->ptr_rx_bdb_overruns)
(*tp->ptr_rx_bdb_overruns)++;
}
err = err1;
break;
/* Type 0x08 - MAC RX Resource Interrupt
* Subtype bit 12 - (BW) BDB warning
* Subtype bit 13 - (FW) FCB warning
* Subtype bit 14 - (BE) BDB End of chain
* Subtype bit 15 - (FE) FCB End of chain
*/
case ISB_IMC_MAC_RX_RESOURCE:
tp->receive_queue_number = MAC_QUEUE;
err1 = smctr_rx_frame(dev);
if(isb_subtype & MAC_RX_RESOURCE_FE)
{
if((err = smctr_issue_resume_rx_fcb_cmd( dev, MAC_QUEUE)) != SUCCESS)
break;
if(tp->ptr_rx_fcb_overruns)
(*tp->ptr_rx_fcb_overruns)++;
}
if(isb_subtype & MAC_RX_RESOURCE_BE)
{
if((err = smctr_issue_resume_rx_bdb_cmd( dev, MAC_QUEUE)) != SUCCESS)
break;
if(tp->ptr_rx_bdb_overruns)
(*tp->ptr_rx_bdb_overruns)++;
}
err = err1;
break;
/* Type 0x09 - NON_MAC RX Frame Interrupt */
case ISB_IMC_NON_MAC_RX_FRAME:
tp->rx_fifo_overrun_count = 0;
tp->receive_queue_number = NON_MAC_QUEUE;
err = smctr_rx_frame(dev);
break;
/* Type 0x0A - MAC RX Frame Interrupt */
case ISB_IMC_MAC_RX_FRAME:
tp->receive_queue_number = MAC_QUEUE;
err = smctr_rx_frame(dev);
break;
/* Type 0x0B - TRC status
* TRC has encountered an error condition
* subtype bit 14 - transmit FIFO underrun
* subtype bit 15 - receive FIFO overrun
*/
case ISB_IMC_TRC_FIFO_STATUS:
if(isb_subtype & TRC_FIFO_STATUS_TX_UNDERRUN)
{
if(tp->ptr_tx_fifo_underruns)
(*tp->ptr_tx_fifo_underruns)++;
}
if(isb_subtype & TRC_FIFO_STATUS_RX_OVERRUN)
{
/* update overrun stuck receive counter
* if >= 3, has to clear it by sending
* back to back frames. We pick
* DAT(duplicate address MAC frame)
*/
tp->rx_fifo_overrun_count++;
if(tp->rx_fifo_overrun_count >= 3)
{
tp->rx_fifo_overrun_count = 0;
/* delay clearing fifo overrun
* imask till send_BUG tx
* complete posted
*/
interrupt_unmask_bits &= (~0x800);
printk(KERN_CRIT "Jay please send bug\n");// smctr_send_bug(dev);
}
if(tp->ptr_rx_fifo_overruns)
(*tp->ptr_rx_fifo_overruns)++;
}
err = SUCCESS;
break;
/* Type 0x0C - Action Command Status Interrupt
* Subtype bit 14 - CB end of command chain (CE)
* Subtype bit 15 - CB command interrupt (CI)
*/
case ISB_IMC_COMMAND_STATUS:
err = SUCCESS;
if(tp->acb_head->cmd == ACB_CMD_HIC_NOP)
{
printk(KERN_ERR "i1\n");
smctr_disable_16bit(dev);
/* XXXXXXXXXXXXXXXXX */
/* err = UM_Interrupt(dev); */
smctr_enable_16bit(dev);
}
else
{
if((tp->acb_head->cmd
== ACB_CMD_READ_TRC_STATUS) &&
(tp->acb_head->subcmd
== RW_TRC_STATUS_BLOCK))
{
if(tp->ptr_bcn_type)
{
*(tp->ptr_bcn_type)
= (__u32)((SBlock *)tp->misc_command_data)->BCN_Type;
}
if(((SBlock *)tp->misc_command_data)->Status_CHG_Indicate & ERROR_COUNTERS_CHANGED)
{
smctr_update_err_stats(dev);
}
if(((SBlock *)tp->misc_command_data)->Status_CHG_Indicate & TI_NDIS_RING_STATUS_CHANGED)
{
tp->ring_status
= ((SBlock*)tp->misc_command_data)->TI_NDIS_Ring_Status;
smctr_disable_16bit(dev);
err = smctr_ring_status_chg(dev);
smctr_enable_16bit(dev);
if((tp->ring_status & REMOVE_RECEIVED) &&
(tp->config_word0 & NO_AUTOREMOVE))
{
smctr_issue_remove_cmd(dev);
}
if(err != SUCCESS)
{
tp->acb_pending = 0;
break;
}
}
if(((SBlock *)tp->misc_command_data)->Status_CHG_Indicate & UNA_CHANGED)
{
if(tp->ptr_una)
{
tp->ptr_una[0] = SWAP_BYTES(((SBlock *)tp->misc_command_data)->UNA[0]);
tp->ptr_una[1] = SWAP_BYTES(((SBlock *)tp->misc_command_data)->UNA[1]);
tp->ptr_una[2] = SWAP_BYTES(((SBlock *)tp->misc_command_data)->UNA[2]);
}
}
if(((SBlock *)tp->misc_command_data)->Status_CHG_Indicate & READY_TO_SEND_RQ_INIT) {
err = smctr_send_rq_init(dev);
}
}
}
tp->acb_pending = 0;
break;
/* Type 0x0D - MAC Type 1 interrupt
* Subtype -- 00 FR_BCN received at S12
* 01 FR_BCN received at S21
* 02 FR_DAT(DA=MA, A<>0) received at S21
* 03 TSM_EXP at S21
* 04 FR_REMOVE received at S42
* 05 TBR_EXP, BR_FLAG_SET at S42
* 06 TBT_EXP at S53
*/
case ISB_IMC_MAC_TYPE_1:
if(isb_subtype > 8)
{
err = HARDWARE_FAILED;
break;
}
err = SUCCESS;
switch(isb_subtype)
{
case 0:
tp->join_state = JS_BYPASS_STATE;
if(tp->status != CLOSED)
{
tp->status = CLOSED;
err = smctr_status_chg(dev);
}
break;
case 1:
tp->join_state = JS_LOBE_TEST_STATE;
break;
case 2:
tp->join_state = JS_DETECT_MONITOR_PRESENT_STATE;
break;
case 3:
tp->join_state = JS_AWAIT_NEW_MONITOR_STATE;
break;
case 4:
tp->join_state = JS_DUPLICATE_ADDRESS_TEST_STATE;
break;
case 5:
tp->join_state = JS_NEIGHBOR_NOTIFICATION_STATE;
break;
case 6:
tp->join_state = JS_REQUEST_INITIALIZATION_STATE;
break;
case 7:
tp->join_state = JS_JOIN_COMPLETE_STATE;
tp->status = OPEN;
err = smctr_status_chg(dev);
break;
case 8:
tp->join_state = JS_BYPASS_WAIT_STATE;
break;
}
break ;
/* Type 0x0E - TRC Initialization Sequence Interrupt
* Subtype -- 00-FF Initializatin sequence complete
*/
case ISB_IMC_TRC_INTRNL_TST_STATUS:
tp->status = INITIALIZED;
smctr_disable_16bit(dev);
err = smctr_status_chg(dev);
smctr_enable_16bit(dev);
break;
/* other interrupt types, illegal */
default:
break;
}
if(err != SUCCESS)
break;
}
/* Checking the ack code instead of the unmask bits here is because :
* while fixing the stuck receive, DAT frame are sent and mask off
* FIFO overrun interrupt temporarily (interrupt_unmask_bits = 0)
* but we still want to issue ack to ISB
*/
if(!(interrupt_ack_code & 0xff00))
smctr_issue_int_ack(dev, interrupt_ack_code, interrupt_unmask_bits);
smctr_disable_16bit(dev);
smctr_enable_bic_int(dev);
spin_unlock(&tp->lock);
return IRQ_HANDLED;
}
static int smctr_issue_enable_int_cmd(struct net_device *dev,
__u16 interrupt_enable_mask)
{
struct net_local *tp = netdev_priv(dev);
int err;
if((err = smctr_wait_while_cbusy(dev)))
return err;
tp->sclb_ptr->int_mask_control = interrupt_enable_mask;
tp->sclb_ptr->valid_command = SCLB_VALID | SCLB_CMD_CLEAR_INTERRUPT_MASK;
smctr_set_ctrl_attention(dev);
return 0;
}
static int smctr_issue_int_ack(struct net_device *dev, __u16 iack_code, __u16 ibits)
{
struct net_local *tp = netdev_priv(dev);
if(smctr_wait_while_cbusy(dev))
return -1;
tp->sclb_ptr->int_mask_control = ibits;
tp->sclb_ptr->iack_code = iack_code << 1; /* use the offset from base */ tp->sclb_ptr->resume_control = 0;
tp->sclb_ptr->valid_command = SCLB_VALID | SCLB_IACK_CODE_VALID | SCLB_CMD_CLEAR_INTERRUPT_MASK;
smctr_set_ctrl_attention(dev);
return 0;
}
static int smctr_issue_init_timers_cmd(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
unsigned int i;
int err;
__u16 *pTimer_Struc = (__u16 *)tp->misc_command_data;
if((err = smctr_wait_while_cbusy(dev)))
return err;
if((err = smctr_wait_cmd(dev)))
return err;
tp->config_word0 = THDREN | DMA_TRIGGER | USETPT | NO_AUTOREMOVE;
tp->config_word1 = 0;
if((tp->media_type == MEDIA_STP_16) ||
(tp->media_type == MEDIA_UTP_16) ||
(tp->media_type == MEDIA_STP_16_UTP_16))
{
tp->config_word0 |= FREQ_16MB_BIT;
}
if(tp->mode_bits & EARLY_TOKEN_REL)
tp->config_word0 |= ETREN;
if(tp->mode_bits & LOOPING_MODE_MASK)
tp->config_word0 |= RX_OWN_BIT;
else
tp->config_word0 &= ~RX_OWN_BIT;
if(tp->receive_mask & PROMISCUOUS_MODE)
tp->config_word0 |= PROMISCUOUS_BIT;
else
tp->config_word0 &= ~PROMISCUOUS_BIT;
if(tp->receive_mask & ACCEPT_ERR_PACKETS)
tp->config_word0 |= SAVBAD_BIT;
else
tp->config_word0 &= ~SAVBAD_BIT;
if(tp->receive_mask & ACCEPT_ATT_MAC_FRAMES)
tp->config_word0 |= RXATMAC;
else
tp->config_word0 &= ~RXATMAC;
if(tp->receive_mask & ACCEPT_MULTI_PROM)
tp->config_word1 |= MULTICAST_ADDRESS_BIT;
else
tp->config_word1 &= ~MULTICAST_ADDRESS_BIT;
if(tp->receive_mask & ACCEPT_SOURCE_ROUTING_SPANNING)
tp->config_word1 |= SOURCE_ROUTING_SPANNING_BITS;
else
{
if(tp->receive_mask & ACCEPT_SOURCE_ROUTING)
tp->config_word1 |= SOURCE_ROUTING_EXPLORER_BIT;
else
tp->config_word1 &= ~SOURCE_ROUTING_SPANNING_BITS;
}
if((tp->media_type == MEDIA_STP_16) ||
(tp->media_type == MEDIA_UTP_16) ||
(tp->media_type == MEDIA_STP_16_UTP_16))
{
tp->config_word1 |= INTERFRAME_SPACING_16;
}
else
tp->config_word1 |= INTERFRAME_SPACING_4;
*pTimer_Struc++ = tp->config_word0;
*pTimer_Struc++ = tp->config_word1;
if((tp->media_type == MEDIA_STP_4) ||
(tp->media_type == MEDIA_UTP_4) ||
(tp->media_type == MEDIA_STP_4_UTP_4))
{
*pTimer_Struc++ = 0x00FA; /* prescale */
*pTimer_Struc++ = 0x2710; /* TPT_limit */
*pTimer_Struc++ = 0x2710; /* TQP_limit */
*pTimer_Struc++ = 0x0A28; /* TNT_limit */
*pTimer_Struc++ = 0x3E80; /* TBT_limit */
*pTimer_Struc++ = 0x3A98; /* TSM_limit */
*pTimer_Struc++ = 0x1B58; /* TAM_limit */
*pTimer_Struc++ = 0x00C8; /* TBR_limit */
*pTimer_Struc++ = 0x07D0; /* TER_limit */
*pTimer_Struc++ = 0x000A; /* TGT_limit */
*pTimer_Struc++ = 0x1162; /* THT_limit */
*pTimer_Struc++ = 0x07D0; /* TRR_limit */
*pTimer_Struc++ = 0x1388; /* TVX_limit */
*pTimer_Struc++ = 0x0000; /* reserved */
}
else
{
*pTimer_Struc++ = 0x03E8; /* prescale */
*pTimer_Struc++ = 0x9C40; /* TPT_limit */
*pTimer_Struc++ = 0x9C40; /* TQP_limit */
*pTimer_Struc++ = 0x0A28; /* TNT_limit */
*pTimer_Struc++ = 0x3E80; /* TBT_limit */
*pTimer_Struc++ = 0x3A98; /* TSM_limit */
*pTimer_Struc++ = 0x1B58; /* TAM_limit */
*pTimer_Struc++ = 0x00C8; /* TBR_limit */
*pTimer_Struc++ = 0x07D0; /* TER_limit */
*pTimer_Struc++ = 0x000A; /* TGT_limit */
*pTimer_Struc++ = 0x4588; /* THT_limit */
*pTimer_Struc++ = 0x1F40; /* TRR_limit */
*pTimer_Struc++ = 0x4E20; /* TVX_limit */
*pTimer_Struc++ = 0x0000; /* reserved */
}
/* Set node address. */
*pTimer_Struc++ = dev->dev_addr[0] << 8
| (dev->dev_addr[1] & 0xFF);
*pTimer_Struc++ = dev->dev_addr[2] << 8
| (dev->dev_addr[3] & 0xFF);
*pTimer_Struc++ = dev->dev_addr[4] << 8
| (dev->dev_addr[5] & 0xFF);
/* Set group address. */
*pTimer_Struc++ = tp->group_address_0 << 8
| tp->group_address_0 >> 8;
*pTimer_Struc++ = tp->group_address[0] << 8
| tp->group_address[0] >> 8;
*pTimer_Struc++ = tp->group_address[1] << 8
| tp->group_address[1] >> 8;
/* Set functional address. */
*pTimer_Struc++ = tp->functional_address_0 << 8
| tp->functional_address_0 >> 8;
*pTimer_Struc++ = tp->functional_address[0] << 8
| tp->functional_address[0] >> 8;
*pTimer_Struc++ = tp->functional_address[1] << 8
| tp->functional_address[1] >> 8;
/* Set Bit-Wise group address. */
*pTimer_Struc++ = tp->bitwise_group_address[0] << 8
| tp->bitwise_group_address[0] >> 8;
*pTimer_Struc++ = tp->bitwise_group_address[1] << 8
| tp->bitwise_group_address[1] >> 8;
/* Set ring number address. */
*pTimer_Struc++ = tp->source_ring_number;
*pTimer_Struc++ = tp->target_ring_number;
/* Physical drop number. */
*pTimer_Struc++ = (unsigned short)0;
*pTimer_Struc++ = (unsigned short)0;
/* Product instance ID. */
for(i = 0; i < 9; i++)
*pTimer_Struc++ = (unsigned short)0;
err = smctr_setup_single_cmd_w_data(dev, ACB_CMD_INIT_TRC_TIMERS, 0);
return err;
}
static int smctr_issue_init_txrx_cmd(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
unsigned int i;
int err;
void **txrx_ptrs = (void *)tp->misc_command_data;
if((err = smctr_wait_while_cbusy(dev)))
return err;
if((err = smctr_wait_cmd(dev)))
{
printk(KERN_ERR "%s: Hardware failure\n", dev->name);
return err;
}
/* Initialize Transmit Queue Pointers that are used, to point to
* a single FCB.
*/
for(i = 0; i < NUM_TX_QS_USED; i++)
*txrx_ptrs++ = (void *)TRC_POINTER(tp->tx_fcb_head[i]);
/* Initialize Transmit Queue Pointers that are NOT used to ZERO. */
for(; i < MAX_TX_QS; i++)
*txrx_ptrs++ = (void *)0;
/* Initialize Receive Queue Pointers (MAC and Non-MAC) that are
* used, to point to a single FCB and a BDB chain of buffers.
*/
for(i = 0; i < NUM_RX_QS_USED; i++)
{
*txrx_ptrs++ = (void *)TRC_POINTER(tp->rx_fcb_head[i]);
*txrx_ptrs++ = (void *)TRC_POINTER(tp->rx_bdb_head[i]);
}
/* Initialize Receive Queue Pointers that are NOT used to ZERO. */
for(; i < MAX_RX_QS; i++)
{
*txrx_ptrs++ = (void *)0;
*txrx_ptrs++ = (void *)0;
}
err = smctr_setup_single_cmd_w_data(dev, ACB_CMD_INIT_TX_RX, 0);
return err;
}
static int smctr_issue_insert_cmd(struct net_device *dev)
{
int err;
err = smctr_setup_single_cmd(dev, ACB_CMD_INSERT, ACB_SUB_CMD_NOP);
return err;
}
static int smctr_issue_read_ring_status_cmd(struct net_device *dev)
{
int err;
if((err = smctr_wait_while_cbusy(dev)))
return err;
if((err = smctr_wait_cmd(dev)))
return err;
err = smctr_setup_single_cmd_w_data(dev, ACB_CMD_READ_TRC_STATUS,
RW_TRC_STATUS_BLOCK);
return err;
}
static int smctr_issue_read_word_cmd(struct net_device *dev, __u16 aword_cnt)
{
int err;
if((err = smctr_wait_while_cbusy(dev)))
return err;
if((err = smctr_wait_cmd(dev)))
return err;
err = smctr_setup_single_cmd_w_data(dev, ACB_CMD_MCT_READ_VALUE,
aword_cnt);
return err;
}
static int smctr_issue_remove_cmd(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
int err;
if((err = smctr_wait_while_cbusy(dev)))
return err;
tp->sclb_ptr->resume_control = 0;
tp->sclb_ptr->valid_command = SCLB_VALID | SCLB_CMD_REMOVE;
smctr_set_ctrl_attention(dev);
return 0;
}
static int smctr_issue_resume_acb_cmd(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
int err;
if((err = smctr_wait_while_cbusy(dev)))
return err;
tp->sclb_ptr->resume_control = SCLB_RC_ACB;
tp->sclb_ptr->valid_command = SCLB_VALID | SCLB_RESUME_CONTROL_VALID;
tp->acb_pending = 1;
smctr_set_ctrl_attention(dev);
return 0;
}
static int smctr_issue_resume_rx_bdb_cmd(struct net_device *dev, __u16 queue)
{
struct net_local *tp = netdev_priv(dev);
int err;
if((err = smctr_wait_while_cbusy(dev)))
return err;
if(queue == MAC_QUEUE)
tp->sclb_ptr->resume_control = SCLB_RC_RX_MAC_BDB;
else
tp->sclb_ptr->resume_control = SCLB_RC_RX_NON_MAC_BDB;
tp->sclb_ptr->valid_command = SCLB_VALID | SCLB_RESUME_CONTROL_VALID;
smctr_set_ctrl_attention(dev);
return 0;
}
static int smctr_issue_resume_rx_fcb_cmd(struct net_device *dev, __u16 queue)
{
struct net_local *tp = netdev_priv(dev);
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_issue_resume_rx_fcb_cmd\n", dev->name);
if(smctr_wait_while_cbusy(dev))
return -1;
if(queue == MAC_QUEUE)
tp->sclb_ptr->resume_control = SCLB_RC_RX_MAC_FCB;
else
tp->sclb_ptr->resume_control = SCLB_RC_RX_NON_MAC_FCB;
tp->sclb_ptr->valid_command = SCLB_VALID | SCLB_RESUME_CONTROL_VALID;
smctr_set_ctrl_attention(dev);
return 0;
}
static int smctr_issue_resume_tx_fcb_cmd(struct net_device *dev, __u16 queue)
{
struct net_local *tp = netdev_priv(dev);
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_issue_resume_tx_fcb_cmd\n", dev->name);
if(smctr_wait_while_cbusy(dev))
return -1;
tp->sclb_ptr->resume_control = (SCLB_RC_TFCB0 << queue);
tp->sclb_ptr->valid_command = SCLB_RESUME_CONTROL_VALID | SCLB_VALID;
smctr_set_ctrl_attention(dev);
return 0;
}
static int smctr_issue_test_internal_rom_cmd(struct net_device *dev)
{
int err;
err = smctr_setup_single_cmd(dev, ACB_CMD_MCT_TEST,
TRC_INTERNAL_ROM_TEST);
return err;
}
static int smctr_issue_test_hic_cmd(struct net_device *dev)
{
int err;
err = smctr_setup_single_cmd(dev, ACB_CMD_HIC_TEST,
TRC_HOST_INTERFACE_REG_TEST);
return err;
}
static int smctr_issue_test_mac_reg_cmd(struct net_device *dev)
{
int err;
err = smctr_setup_single_cmd(dev, ACB_CMD_MCT_TEST,
TRC_MAC_REGISTERS_TEST);
return err;
}
static int smctr_issue_trc_loopback_cmd(struct net_device *dev)
{
int err;
err = smctr_setup_single_cmd(dev, ACB_CMD_MCT_TEST,
TRC_INTERNAL_LOOPBACK);
return err;
}
static int smctr_issue_tri_loopback_cmd(struct net_device *dev)
{
int err;
err = smctr_setup_single_cmd(dev, ACB_CMD_MCT_TEST,
TRC_TRI_LOOPBACK);
return err;
}
static int smctr_issue_write_byte_cmd(struct net_device *dev,
short aword_cnt, void *byte)
{
struct net_local *tp = netdev_priv(dev);
unsigned int iword, ibyte;
int err;
if((err = smctr_wait_while_cbusy(dev)))
return err;
if((err = smctr_wait_cmd(dev)))
return err;
for(iword = 0, ibyte = 0; iword < (unsigned int)(aword_cnt & 0xff);
iword++, ibyte += 2)
{
tp->misc_command_data[iword] = (*((__u8 *)byte + ibyte) << 8)
| (*((__u8 *)byte + ibyte + 1));
}
return smctr_setup_single_cmd_w_data(dev, ACB_CMD_MCT_WRITE_VALUE,
aword_cnt);
}
static int smctr_issue_write_word_cmd(struct net_device *dev,
short aword_cnt, void *word)
{
struct net_local *tp = netdev_priv(dev);
unsigned int i, err;
if((err = smctr_wait_while_cbusy(dev)))
return err;
if((err = smctr_wait_cmd(dev)))
return err;
for(i = 0; i < (unsigned int)(aword_cnt & 0xff); i++)
tp->misc_command_data[i] = *((__u16 *)word + i);
err = smctr_setup_single_cmd_w_data(dev, ACB_CMD_MCT_WRITE_VALUE,
aword_cnt);
return err;
}
static int smctr_join_complete_state(struct net_device *dev)
{
int err;
err = smctr_setup_single_cmd(dev, ACB_CMD_CHANGE_JOIN_STATE,
JS_JOIN_COMPLETE_STATE);
return err;
}
static int smctr_link_tx_fcbs_to_bdbs(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
unsigned int i, j;
FCBlock *fcb;
BDBlock *bdb;
for(i = 0; i < NUM_TX_QS_USED; i++)
{
fcb = tp->tx_fcb_head[i];
bdb = tp->tx_bdb_head[i];
for(j = 0; j < tp->num_tx_fcbs[i]; j++)
{
fcb->bdb_ptr = bdb;
fcb->trc_bdb_ptr = TRC_POINTER(bdb);
fcb = (FCBlock *)((char *)fcb + sizeof(FCBlock));
bdb = (BDBlock *)((char *)bdb + sizeof(BDBlock));
}
}
return 0;
}
static int smctr_load_firmware(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
const struct firmware *fw;
__u16 i, checksum = 0;
int err = 0;
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_load_firmware\n", dev->name);
if (request_firmware(&fw, "tr_smctr.bin", &dev->dev)) {
printk(KERN_ERR "%s: firmware not found\n", dev->name);
return UCODE_NOT_PRESENT;
}
tp->num_of_tx_buffs = 4;
tp->mode_bits |= UMAC;
tp->receive_mask = 0;
tp->max_packet_size = 4177;
/* Can only upload the firmware once per adapter reset. */
if (tp->microcode_version != 0) {
err = (UCODE_PRESENT);
goto out;
}
/* Verify the firmware exists and is there in the right amount. */
if (!fw->data ||
(*(fw->data + UCODE_VERSION_OFFSET) < UCODE_VERSION))
{
err = (UCODE_NOT_PRESENT);
goto out;
}
/* UCODE_SIZE is not included in Checksum. */
for(i = 0; i < *((__u16 *)(fw->data + UCODE_SIZE_OFFSET)); i += 2)
checksum += *((__u16 *)(fw->data + 2 + i));
if (checksum) {
err = (UCODE_NOT_PRESENT);
goto out;
}
/* At this point we have a valid firmware image, lets kick it on up. */
smctr_enable_adapter_ram(dev);
smctr_enable_16bit(dev);
smctr_set_page(dev, (__u8 *)tp->ram_access);
if((smctr_checksum_firmware(dev)) ||
(*(fw->data + UCODE_VERSION_OFFSET) > tp->microcode_version))
{
smctr_enable_adapter_ctrl_store(dev);
/* Zero out ram space for firmware. */
for(i = 0; i < CS_RAM_SIZE; i += 2)
*((__u16 *)(tp->ram_access + i)) = 0;
smctr_decode_firmware(dev, fw);
tp->microcode_version = *(fw->data + UCODE_VERSION_OFFSET); *((__u16 *)(tp->ram_access + CS_RAM_VERSION_OFFSET))
= (tp->microcode_version << 8);
*((__u16 *)(tp->ram_access + CS_RAM_CHECKSUM_OFFSET))
= ~(tp->microcode_version << 8) + 1;
smctr_disable_adapter_ctrl_store(dev);
if(smctr_checksum_firmware(dev))
err = HARDWARE_FAILED;
}
else
err = UCODE_PRESENT;
smctr_disable_16bit(dev);
out:
release_firmware(fw);
return err;
}
static int smctr_load_node_addr(struct net_device *dev)
{
int ioaddr = dev->base_addr;
unsigned int i;
__u8 r;
for(i = 0; i < 6; i++)
{
r = inb(ioaddr + LAR0 + i);
dev->dev_addr[i] = (char)r;
}
dev->addr_len = 6;
return 0;
}
/* Lobe Media Test.
* During the transmission of the initial 1500 lobe media MAC frames,
* the phase lock loop in the 805 chip may lock, and then un-lock, causing
* the 825 to go into a PURGE state. When performing a PURGE, the MCT
* microcode will not transmit any frames given to it by the host, and
* will consequently cause a timeout.
*
* NOTE 1: If the monitor_state is MS_BEACON_TEST_STATE, all transmit
* queues other than the one used for the lobe_media_test should be
* disabled.!?
*
* NOTE 2: If the monitor_state is MS_BEACON_TEST_STATE and the receive_mask
* has any multi-cast or promiscuous bits set, the receive_mask needs to
* be changed to clear the multi-cast or promiscuous mode bits, the lobe_test
* run, and then the receive mask set back to its original value if the test
* is successful.
*/
static int smctr_lobe_media_test(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
unsigned int i, perror = 0;
unsigned short saved_rcv_mask;
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_lobe_media_test\n", dev->name);
/* Clear receive mask for lobe test. */
saved_rcv_mask = tp->receive_mask;
tp->receive_mask = 0;
smctr_chg_rx_mask(dev);
/* Setup the lobe media test. */
smctr_lobe_media_test_cmd(dev);
if(smctr_wait_cmd(dev))
goto err;
/* Tx lobe media test frames. */
for(i = 0; i < 1500; ++i)
{
if(smctr_send_lobe_media_test(dev))
{
if(perror)
goto err;
else
{
perror = 1;
if(smctr_lobe_media_test_cmd(dev))
goto err;
}
}
}
if(smctr_send_dat(dev))
{
if(smctr_send_dat(dev))
goto err;
}
/* Check if any frames received during test. */
if((tp->rx_fcb_curr[MAC_QUEUE]->frame_status) ||
(tp->rx_fcb_curr[NON_MAC_QUEUE]->frame_status))
goto err;
/* Set receive mask to "Promisc" mode. */
tp->receive_mask = saved_rcv_mask;
smctr_chg_rx_mask(dev);
return 0;
err:
smctr_reset_adapter(dev);
tp->status = CLOSED;
return LOBE_MEDIA_TEST_FAILED;
}
static int smctr_lobe_media_test_cmd(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
int err;
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_lobe_media_test_cmd\n", dev->name);
/* Change to lobe media test state. */
if(tp->monitor_state != MS_BEACON_TEST_STATE)
{
smctr_lobe_media_test_state(dev);
if(smctr_wait_cmd(dev))
{
printk(KERN_ERR "Lobe Failed test state\n");
return LOBE_MEDIA_TEST_FAILED;
}
}
err = smctr_setup_single_cmd(dev, ACB_CMD_MCT_TEST,
TRC_LOBE_MEDIA_TEST);
return err;
}
static int smctr_lobe_media_test_state(struct net_device *dev)
{
int err;
err = smctr_setup_single_cmd(dev, ACB_CMD_CHANGE_JOIN_STATE,
JS_LOBE_TEST_STATE);
return err;
}
static int smctr_make_8025_hdr(struct net_device *dev,
MAC_HEADER *rmf, MAC_HEADER *tmf, __u16 ac_fc)
{
tmf->ac = MSB(ac_fc); /* msb is access control */
tmf->fc = LSB(ac_fc); /* lsb is frame control */
tmf->sa[0] = dev->dev_addr[0];
tmf->sa[1] = dev->dev_addr[1];
tmf->sa[2] = dev->dev_addr[2];
tmf->sa[3] = dev->dev_addr[3];
tmf->sa[4] = dev->dev_addr[4];
tmf->sa[5] = dev->dev_addr[5];
switch(tmf->vc)
{
/* Send RQ_INIT to RPS */
case RQ_INIT:
tmf->da[0] = 0xc0;
tmf->da[1] = 0x00;
tmf->da[2] = 0x00;
tmf->da[3] = 0x00;
tmf->da[4] = 0x00;
tmf->da[5] = 0x02;
break;
/* Send RPT_TX_FORWARD to CRS */
case RPT_TX_FORWARD:
tmf->da[0] = 0xc0;
tmf->da[1] = 0x00;
tmf->da[2] = 0x00;
tmf->da[3] = 0x00;
tmf->da[4] = 0x00;
tmf->da[5] = 0x10;
break;
/* Everything else goes to sender */
default:
tmf->da[0] = rmf->sa[0];
tmf->da[1] = rmf->sa[1];
tmf->da[2] = rmf->sa[2];
tmf->da[3] = rmf->sa[3];
tmf->da[4] = rmf->sa[4];
tmf->da[5] = rmf->sa[5];
break;
}
return 0;
}
static int smctr_make_access_pri(struct net_device *dev, MAC_SUB_VECTOR *tsv)
{
struct net_local *tp = netdev_priv(dev);
tsv->svi = AUTHORIZED_ACCESS_PRIORITY;
tsv->svl = S_AUTHORIZED_ACCESS_PRIORITY;
tsv->svv[0] = MSB(tp->authorized_access_priority);
tsv->svv[1] = LSB(tp->authorized_access_priority);
return 0;
}
static int smctr_make_addr_mod(struct net_device *dev, MAC_SUB_VECTOR *tsv)
{
tsv->svi = ADDRESS_MODIFER;
tsv->svl = S_ADDRESS_MODIFER;
tsv->svv[0] = 0;
tsv->svv[1] = 0;
return 0;
}
static int smctr_make_auth_funct_class(struct net_device *dev,
MAC_SUB_VECTOR *tsv)
{
struct net_local *tp = netdev_priv(dev);
tsv->svi = AUTHORIZED_FUNCTION_CLASS;
tsv->svl = S_AUTHORIZED_FUNCTION_CLASS;
tsv->svv[0] = MSB(tp->authorized_function_classes);
tsv->svv[1] = LSB(tp->authorized_function_classes);
return 0;
}
static int smctr_make_corr(struct net_device *dev,
MAC_SUB_VECTOR *tsv, __u16 correlator)
{
tsv->svi = CORRELATOR;
tsv->svl = S_CORRELATOR;
tsv->svv[0] = MSB(correlator);
tsv->svv[1] = LSB(correlator);
return 0;
}
static int smctr_make_funct_addr(struct net_device *dev, MAC_SUB_VECTOR *tsv)
{
struct net_local *tp = netdev_priv(dev);
smctr_get_functional_address(dev);
tsv->svi = FUNCTIONAL_ADDRESS;
tsv->svl = S_FUNCTIONAL_ADDRESS;
tsv->svv[0] = MSB(tp->misc_command_data[0]);
tsv->svv[1] = LSB(tp->misc_command_data[0]);
tsv->svv[2] = MSB(tp->misc_command_data[1]);
tsv->svv[3] = LSB(tp->misc_command_data[1]);
return 0;
}
static int smctr_make_group_addr(struct net_device *dev, MAC_SUB_VECTOR *tsv)
{
struct net_local *tp = netdev_priv(dev);
smctr_get_group_address(dev);
tsv->svi = GROUP_ADDRESS;
tsv->svl = S_GROUP_ADDRESS;
tsv->svv[0] = MSB(tp->misc_command_data[0]);
tsv->svv[1] = LSB(tp->misc_command_data[0]);
tsv->svv[2] = MSB(tp->misc_command_data[1]);
tsv->svv[3] = LSB(tp->misc_command_data[1]);
/* Set Group Address Sub-vector to all zeros if only the
* Group Address/Functional Address Indicator is set.
*/
if(tsv->svv[0] == 0x80 && tsv->svv[1] == 0x00 &&
tsv->svv[2] == 0x00 && tsv->svv[3] == 0x00)
tsv->svv[0] = 0x00;
return 0;
}
static int smctr_make_phy_drop_num(struct net_device *dev,
MAC_SUB_VECTOR *tsv)
{
struct net_local *tp = netdev_priv(dev);
smctr_get_physical_drop_number(dev);
tsv->svi = PHYSICAL_DROP;
tsv->svl = S_PHYSICAL_DROP;
tsv->svv[0] = MSB(tp->misc_command_data[0]);
tsv->svv[1] = LSB(tp->misc_command_data[0]);
tsv->svv[2] = MSB(tp->misc_command_data[1]);
tsv->svv[3] = LSB(tp->misc_command_data[1]);
return 0;
}
static int smctr_make_product_id(struct net_device *dev, MAC_SUB_VECTOR *tsv)
{
int i;
tsv->svi = PRODUCT_INSTANCE_ID;
tsv->svl = S_PRODUCT_INSTANCE_ID;
for(i = 0; i < 18; i++)
tsv->svv[i] = 0xF0;
return 0;
}
static int smctr_make_station_id(struct net_device *dev, MAC_SUB_VECTOR *tsv)
{
struct net_local *tp = netdev_priv(dev);
smctr_get_station_id(dev);
tsv->svi = STATION_IDENTIFER;
tsv->svl = S_STATION_IDENTIFER;
tsv->svv[0] = MSB(tp->misc_command_data[0]);
tsv->svv[1] = LSB(tp->misc_command_data[0]);
tsv->svv[2] = MSB(tp->misc_command_data[1]);
tsv->svv[3] = LSB(tp->misc_command_data[1]);
tsv->svv[4] = MSB(tp->misc_command_data[2]);
tsv->svv[5] = LSB(tp->misc_command_data[2]);
return 0;
}
static int smctr_make_ring_station_status(struct net_device *dev,
MAC_SUB_VECTOR * tsv)
{
tsv->svi = RING_STATION_STATUS;
tsv->svl = S_RING_STATION_STATUS;
tsv->svv[0] = 0;
tsv->svv[1] = 0;
tsv->svv[2] = 0;
tsv->svv[3] = 0;
tsv->svv[4] = 0;
tsv->svv[5] = 0;
return 0;
}
static int smctr_make_ring_station_version(struct net_device *dev,
MAC_SUB_VECTOR *tsv)
{
struct net_local *tp = netdev_priv(dev);
tsv->svi = RING_STATION_VERSION_NUMBER;
tsv->svl = S_RING_STATION_VERSION_NUMBER;
tsv->svv[0] = 0xe2; /* EBCDIC - S */
tsv->svv[1] = 0xd4; /* EBCDIC - M */
tsv->svv[2] = 0xc3; /* EBCDIC - C */
tsv->svv[3] = 0x40; /* EBCDIC - */
tsv->svv[4] = 0xe5; /* EBCDIC - V */
tsv->svv[5] = 0xF0 + (tp->microcode_version >> 4);
tsv->svv[6] = 0xF0 + (tp->microcode_version & 0x0f);
tsv->svv[7] = 0x40; /* EBCDIC - */
tsv->svv[8] = 0xe7; /* EBCDIC - X */
if(tp->extra_info & CHIP_REV_MASK)
tsv->svv[9] = 0xc5; /* EBCDIC - E */
else
tsv->svv[9] = 0xc4; /* EBCDIC - D */
return 0;
}
static int smctr_make_tx_status_code(struct net_device *dev,
MAC_SUB_VECTOR *tsv, __u16 tx_fstatus)
{
tsv->svi = TRANSMIT_STATUS_CODE;
tsv->svl = S_TRANSMIT_STATUS_CODE;
tsv->svv[0] = ((tx_fstatus & 0x0100 >> 6) | IBM_PASS_SOURCE_ADDR);
/* Stripped frame status of Transmitted Frame */
tsv->svv[1] = tx_fstatus & 0xff;
return 0;
}
static int smctr_make_upstream_neighbor_addr(struct net_device *dev,
MAC_SUB_VECTOR *tsv)
{
struct net_local *tp = netdev_priv(dev);
smctr_get_upstream_neighbor_addr(dev);
tsv->svi = UPSTREAM_NEIGHBOR_ADDRESS;
tsv->svl = S_UPSTREAM_NEIGHBOR_ADDRESS;
tsv->svv[0] = MSB(tp->misc_command_data[0]);
tsv->svv[1] = LSB(tp->misc_command_data[0]);
tsv->svv[2] = MSB(tp->misc_command_data[1]);
tsv->svv[3] = LSB(tp->misc_command_data[1]);
tsv->svv[4] = MSB(tp->misc_command_data[2]);
tsv->svv[5] = LSB(tp->misc_command_data[2]);
return 0;
}
static int smctr_make_wrap_data(struct net_device *dev, MAC_SUB_VECTOR *tsv)
{
tsv->svi = WRAP_DATA;
tsv->svl = S_WRAP_DATA;
return 0;
}
/*
* Open/initialize the board. This is called sometime after
* booting when the 'ifconfig' program is run.
*
* This routine should set everything up anew at each open, even
* registers that "should" only need to be set once at boot, so that
* there is non-reboot way to recover if something goes wrong.
*/
static int smctr_open(struct net_device *dev)
{
int err;
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_open\n", dev->name);
err = smctr_init_adapter(dev);
if(err < 0)
return err;
return err;
}
/* Interrupt driven open of Token card. */
static int smctr_open_tr(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
unsigned long flags;
int err;
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_open_tr\n", dev->name);
/* Now we can actually open the adapter. */
if(tp->status == OPEN)
return 0;
if(tp->status != INITIALIZED)
return -1;
/* FIXME: it would work a lot better if we masked the irq sources
on the card here, then we could skip the locking and poll nicely */
spin_lock_irqsave(&tp->lock, flags);
smctr_set_page(dev, (__u8 *)tp->ram_access);
if((err = smctr_issue_resume_rx_fcb_cmd(dev, (short)MAC_QUEUE)))
goto out;
if((err = smctr_issue_resume_rx_bdb_cmd(dev, (short)MAC_QUEUE)))
goto out;
if((err = smctr_issue_resume_rx_fcb_cmd(dev, (short)NON_MAC_QUEUE)))
goto out;
if((err = smctr_issue_resume_rx_bdb_cmd(dev, (short)NON_MAC_QUEUE)))
goto out;
tp->status = CLOSED;
/* Insert into the Ring or Enter Loopback Mode. */
if((tp->mode_bits & LOOPING_MODE_MASK) == LOOPBACK_MODE_1)
{
tp->status = CLOSED;
if(!(err = smctr_issue_trc_loopback_cmd(dev)))
{
if(!(err = smctr_wait_cmd(dev)))
tp->status = OPEN;
}
smctr_status_chg(dev);
}
else
{
if((tp->mode_bits & LOOPING_MODE_MASK) == LOOPBACK_MODE_2)
{
tp->status = CLOSED;
if(!(err = smctr_issue_tri_loopback_cmd(dev)))
{
if(!(err = smctr_wait_cmd(dev)))
tp->status = OPEN;
}
smctr_status_chg(dev);
}
else
{
if((tp->mode_bits & LOOPING_MODE_MASK)
== LOOPBACK_MODE_3)
{
tp->status = CLOSED;
if(!(err = smctr_lobe_media_test_cmd(dev)))
{
if(!(err = smctr_wait_cmd(dev)))
tp->status = OPEN;
}
smctr_status_chg(dev);
}
else
{
if(!(err = smctr_lobe_media_test(dev)))
err = smctr_issue_insert_cmd(dev);
else
{
if(err == LOBE_MEDIA_TEST_FAILED)
printk(KERN_WARNING "%s: Lobe Media Test Failure - Check cable?\n", dev->name);
}
}
}
}
out:
spin_unlock_irqrestore(&tp->lock, flags);
return err;
}
/* Check for a network adapter of this type,
* and return device structure if one exists.
*/
struct net_device __init *smctr_probe(int unit)
{
struct net_device *dev = alloc_trdev(sizeof(struct net_local));
static const unsigned ports[] = {
0x200, 0x220, 0x240, 0x260, 0x280, 0x2A0, 0x2C0, 0x2E0, 0x300,
0x320, 0x340, 0x360, 0x380, 0
};
const unsigned *port;
int err = 0;
if (!dev)
return ERR_PTR(-ENOMEM);
if (unit >= 0) {
sprintf(dev->name, "tr%d", unit);
netdev_boot_setup_check(dev);
}
if (dev->base_addr > 0x1ff) /* Check a single specified location. */
err = smctr_probe1(dev, dev->base_addr);
else if(dev->base_addr != 0) /* Don't probe at all. */
err =-ENXIO;
else {
for (port = ports; *port; port++) {
err = smctr_probe1(dev, *port);
if (!err)
break;
}
}
if (err)
goto out;
err = register_netdev(dev);
if (err)
goto out1;
return dev;
out1:
#ifdef CONFIG_MCA_LEGACY
{ struct net_local *tp = netdev_priv(dev);
if (tp->slot_num)
mca_mark_as_unused(tp->slot_num);
}
#endif
release_region(dev->base_addr, SMCTR_IO_EXTENT);
free_irq(dev->irq, dev);
out:
free_netdev(dev);
return ERR_PTR(err);
}
static const struct net_device_ops smctr_netdev_ops = {
.ndo_open = smctr_open,
.ndo_stop = smctr_close,
.ndo_start_xmit = smctr_send_packet,
.ndo_tx_timeout = smctr_timeout,
.ndo_get_stats = smctr_get_stats,
.ndo_set_multicast_list = smctr_set_multicast_list,
};
static int __init smctr_probe1(struct net_device *dev, int ioaddr)
{
static unsigned version_printed;
struct net_local *tp = netdev_priv(dev);
int err;
__u32 *ram;
if(smctr_debug && version_printed++ == 0)
printk(version);
spin_lock_init(&tp->lock);
dev->base_addr = ioaddr;
/* Actually detect an adapter now. */
err = smctr_chk_isa(dev);
if(err < 0)
{
if ((err = smctr_chk_mca(dev)) < 0) {
err = -ENODEV;
goto out;
}
}
tp = netdev_priv(dev);
dev->mem_start = tp->ram_base;
dev->mem_end = dev->mem_start + 0x10000;
ram = (__u32 *)phys_to_virt(dev->mem_start);
tp->ram_access = *(__u32 *)&ram;
tp->status = NOT_INITIALIZED;
err = smctr_load_firmware(dev);
if(err != UCODE_PRESENT && err != SUCCESS)
{
printk(KERN_ERR "%s: Firmware load failed (%d)\n", dev->name, err);
err = -EIO;
goto out;
}
/* Allow user to specify ring speed on module insert. */
if(ringspeed == 4)
tp->media_type = MEDIA_UTP_4;
else
tp->media_type = MEDIA_UTP_16;
printk(KERN_INFO "%s: %s %s at Io %#4x, Irq %d, Rom %#4x, Ram %#4x.\n",
dev->name, smctr_name, smctr_model,
(unsigned int)dev->base_addr,
dev->irq, tp->rom_base, tp->ram_base);
dev->netdev_ops = &smctr_netdev_ops;
dev->watchdog_timeo = HZ;
return 0;
out:
return err;
}
static int smctr_process_rx_packet(MAC_HEADER *rmf, __u16 size,
struct net_device *dev, __u16 rx_status)
{
struct net_local *tp = netdev_priv(dev);
struct sk_buff *skb;
__u16 rcode, correlator;
int err = 0;
__u8 xframe = 1;
rmf->vl = SWAP_BYTES(rmf->vl);
if(rx_status & FCB_RX_STATUS_DA_MATCHED)
{
switch(rmf->vc)
{
/* Received MAC Frames Processed by RS. */
case INIT:
if((rcode = smctr_rcv_init(dev, rmf, &correlator)) == HARDWARE_FAILED)
{
return rcode;
}
if((err = smctr_send_rsp(dev, rmf, rcode,
correlator)))
{
return err;
}
break;
case CHG_PARM:
if((rcode = smctr_rcv_chg_param(dev, rmf,
&correlator)) ==HARDWARE_FAILED)
{
return rcode;
}
if((err = smctr_send_rsp(dev, rmf, rcode,
correlator)))
{
return err;
}
break;
case RQ_ADDR:
if((rcode = smctr_rcv_rq_addr_state_attch(dev,
rmf, &correlator)) != POSITIVE_ACK)
{
if(rcode == HARDWARE_FAILED)
return rcode;
else
return smctr_send_rsp(dev, rmf,
rcode, correlator);
}
if((err = smctr_send_rpt_addr(dev, rmf,
correlator)))
{
return err;
}
break;
case RQ_ATTCH:
if((rcode = smctr_rcv_rq_addr_state_attch(dev,
rmf, &correlator)) != POSITIVE_ACK)
{
if(rcode == HARDWARE_FAILED)
return rcode;
else
return smctr_send_rsp(dev, rmf,
rcode,
correlator);
}
if((err = smctr_send_rpt_attch(dev, rmf,
correlator)))
{
return err;
}
break;
case RQ_STATE:
if((rcode = smctr_rcv_rq_addr_state_attch(dev,
rmf, &correlator)) != POSITIVE_ACK)
{
if(rcode == HARDWARE_FAILED)
return rcode;
else
return smctr_send_rsp(dev, rmf,
rcode,
correlator);
}
if((err = smctr_send_rpt_state(dev, rmf,
correlator)))
{
return err;
}
break;
case TX_FORWARD: {
__u16 uninitialized_var(tx_fstatus);
if((rcode = smctr_rcv_tx_forward(dev, rmf))
!= POSITIVE_ACK)
{
if(rcode == HARDWARE_FAILED)
return rcode;
else
return smctr_send_rsp(dev, rmf,
rcode,
correlator);
}
if((err = smctr_send_tx_forward(dev, rmf,
&tx_fstatus)) == HARDWARE_FAILED)
{
return err;
}
if(err == A_FRAME_WAS_FORWARDED)
{
if((err = smctr_send_rpt_tx_forward(dev,
rmf, tx_fstatus))
== HARDWARE_FAILED)
{
return err;
}
}
break;
}
/* Received MAC Frames Processed by CRS/REM/RPS. */
case RSP:
case RQ_INIT:
case RPT_NEW_MON:
case RPT_SUA_CHG:
case RPT_ACTIVE_ERR:
case RPT_NN_INCMP:
case RPT_ERROR:
case RPT_ATTCH:
case RPT_STATE:
case RPT_ADDR:
break;
/* Rcvd Att. MAC Frame (if RXATMAC set) or UNKNOWN */
default:
xframe = 0;
if(!(tp->receive_mask & ACCEPT_ATT_MAC_FRAMES))
{
rcode = smctr_rcv_unknown(dev, rmf,
&correlator);
if((err = smctr_send_rsp(dev, rmf,rcode,
correlator)))
{
return err;
}
}
break;
}
}
else
{
/* 1. DA doesn't match (Promiscuous Mode).
* 2. Parse for Extended MAC Frame Type.
*/
switch(rmf->vc)
{
case RSP:
case INIT:
case RQ_INIT:
case RQ_ADDR:
case RQ_ATTCH:
case RQ_STATE:
case CHG_PARM:
case RPT_ADDR:
case RPT_ERROR:
case RPT_ATTCH:
case RPT_STATE:
case RPT_NEW_MON:
case RPT_SUA_CHG:
case RPT_NN_INCMP:
case RPT_ACTIVE_ERR:
break;
default:
xframe = 0;
break;
}
}
/* NOTE: UNKNOWN MAC frames will NOT be passed up unless
* ACCEPT_ATT_MAC_FRAMES is set.
*/
if(((tp->receive_mask & ACCEPT_ATT_MAC_FRAMES) &&
(xframe == (__u8)0)) ||
((tp->receive_mask & ACCEPT_EXT_MAC_FRAMES) &&
(xframe == (__u8)1)))
{
rmf->vl = SWAP_BYTES(rmf->vl);
if (!(skb = dev_alloc_skb(size)))
return -ENOMEM;
skb->len = size;
/* Slide data into a sleek skb. */
skb_put(skb, skb->len);
skb_copy_to_linear_data(skb, rmf, skb->len);
/* Update Counters */
tp->MacStat.rx_packets++;
tp->MacStat.rx_bytes += skb->len;
/* Kick the packet on up. */
skb->protocol = tr_type_trans(skb, dev);
netif_rx(skb);
err = 0;
}
return err;
}
/* Adapter RAM test. Incremental word ODD boundary data test. */
static int smctr_ram_memory_test(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
__u16 page, pages_of_ram, start_pattern = 0, word_pattern = 0,
word_read = 0, err_word = 0, err_pattern = 0;
unsigned int err_offset;
__u32 j, pword;
__u8 err = 0;
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_ram_memory_test\n", dev->name);
start_pattern = 0x0001;
pages_of_ram = tp->ram_size / tp->ram_usable;
pword = tp->ram_access;
/* Incremental word ODD boundary test. */
for(page = 0; (page < pages_of_ram) && (~err);
page++, start_pattern += 0x8000)
{
smctr_set_page(dev, (__u8 *)(tp->ram_access
+ (page * tp->ram_usable * 1024) + 1));
word_pattern = start_pattern;
for(j = 1; j < (__u32)(tp->ram_usable * 1024) - 1; j += 2)
*(__u16 *)(pword + j) = word_pattern++;
word_pattern = start_pattern;
for(j = 1; j < (__u32)(tp->ram_usable * 1024) - 1 && (~err);
j += 2, word_pattern++)
{
word_read = *(__u16 *)(pword + j);
if(word_read != word_pattern)
{
err = (__u8)1;
err_offset = j;
err_word = word_read;
err_pattern = word_pattern;
return RAM_TEST_FAILED;
}
}
}
/* Zero out memory. */
for(page = 0; page < pages_of_ram && (~err); page++)
{
smctr_set_page(dev, (__u8 *)(tp->ram_access
+ (page * tp->ram_usable * 1024)));
word_pattern = 0;
for(j = 0; j < (__u32)tp->ram_usable * 1024; j +=2)
*(__u16 *)(pword + j) = word_pattern;
for(j =0; j < (__u32)tp->ram_usable * 1024 && (~err); j += 2)
{
word_read = *(__u16 *)(pword + j);
if(word_read != word_pattern)
{
err = (__u8)1;
err_offset = j;
err_word = word_read;
err_pattern = word_pattern;
return RAM_TEST_FAILED;
}
}
}
smctr_set_page(dev, (__u8 *)tp->ram_access);
return 0;
}
static int smctr_rcv_chg_param(struct net_device *dev, MAC_HEADER *rmf,
__u16 *correlator)
{
MAC_SUB_VECTOR *rsv;
signed short vlen;
__u16 rcode = POSITIVE_ACK;
unsigned int svectors = F_NO_SUB_VECTORS_FOUND;
/* This Frame can only come from a CRS */
if((rmf->dc_sc & SC_MASK) != SC_CRS)
return E_INAPPROPRIATE_SOURCE_CLASS;
/* Remove MVID Length from total length. */
vlen = (signed short)rmf->vl - 4;
/* Point to First SVID */
rsv = (MAC_SUB_VECTOR *)((__u32)rmf + sizeof(MAC_HEADER));
/* Search for Appropriate SVID's. */
while((vlen > 0) && (rcode == POSITIVE_ACK))
{
switch(rsv->svi)
{
case CORRELATOR:
svectors |= F_CORRELATOR;
rcode = smctr_set_corr(dev, rsv, correlator);
break;
case LOCAL_RING_NUMBER:
svectors |= F_LOCAL_RING_NUMBER;
rcode = smctr_set_local_ring_num(dev, rsv);
break;
case ASSIGN_PHYSICAL_DROP:
svectors |= F_ASSIGN_PHYSICAL_DROP;
rcode = smctr_set_phy_drop(dev, rsv);
break;
case ERROR_TIMER_VALUE:
svectors |= F_ERROR_TIMER_VALUE;
rcode = smctr_set_error_timer_value(dev, rsv);
break;
case AUTHORIZED_FUNCTION_CLASS:
svectors |= F_AUTHORIZED_FUNCTION_CLASS;
rcode = smctr_set_auth_funct_class(dev, rsv);
break;
case AUTHORIZED_ACCESS_PRIORITY:
svectors |= F_AUTHORIZED_ACCESS_PRIORITY;
rcode = smctr_set_auth_access_pri(dev, rsv);
break;
default:
rcode = E_SUB_VECTOR_UNKNOWN;
break;
}
/* Let Sender Know if SUM of SV length's is
* larger then length in MVID length field
*/
if((vlen -= rsv->svl) < 0)
rcode = E_VECTOR_LENGTH_ERROR;
rsv = (MAC_SUB_VECTOR *)((__u32)rsv + rsv->svl);
}
if(rcode == POSITIVE_ACK)
{
/* Let Sender Know if MVID length field
* is larger then SUM of SV length's
*/
if(vlen != 0)
rcode = E_VECTOR_LENGTH_ERROR;
else
{
/* Let Sender Know if Expected SVID Missing */
if((svectors & R_CHG_PARM) ^ R_CHG_PARM)
rcode = E_MISSING_SUB_VECTOR;
}
}
return rcode;
}
static int smctr_rcv_init(struct net_device *dev, MAC_HEADER *rmf,
__u16 *correlator)
{
MAC_SUB_VECTOR *rsv;
signed short vlen;
__u16 rcode = POSITIVE_ACK;
unsigned int svectors = F_NO_SUB_VECTORS_FOUND;
/* This Frame can only come from a RPS */
if((rmf->dc_sc & SC_MASK) != SC_RPS)
return E_INAPPROPRIATE_SOURCE_CLASS;
/* Remove MVID Length from total length. */
vlen = (signed short)rmf->vl - 4;
/* Point to First SVID */
rsv = (MAC_SUB_VECTOR *)((__u32)rmf + sizeof(MAC_HEADER));
/* Search for Appropriate SVID's */
while((vlen > 0) && (rcode == POSITIVE_ACK))
{
switch(rsv->svi)
{
case CORRELATOR:
svectors |= F_CORRELATOR;
rcode = smctr_set_corr(dev, rsv, correlator);
break;
case LOCAL_RING_NUMBER:
svectors |= F_LOCAL_RING_NUMBER;
rcode = smctr_set_local_ring_num(dev, rsv);
break;
case ASSIGN_PHYSICAL_DROP:
svectors |= F_ASSIGN_PHYSICAL_DROP;
rcode = smctr_set_phy_drop(dev, rsv);
break;
case ERROR_TIMER_VALUE:
svectors |= F_ERROR_TIMER_VALUE;
rcode = smctr_set_error_timer_value(dev, rsv);
break;
default:
rcode = E_SUB_VECTOR_UNKNOWN;
break;
}
/* Let Sender Know if SUM of SV length's is
* larger then length in MVID length field
*/
if((vlen -= rsv->svl) < 0)
rcode = E_VECTOR_LENGTH_ERROR;
rsv = (MAC_SUB_VECTOR *)((__u32)rsv + rsv->svl);
}
if(rcode == POSITIVE_ACK)
{
/* Let Sender Know if MVID length field
* is larger then SUM of SV length's
*/
if(vlen != 0)
rcode = E_VECTOR_LENGTH_ERROR;
else
{
/* Let Sender Know if Expected SV Missing */
if((svectors & R_INIT) ^ R_INIT)
rcode = E_MISSING_SUB_VECTOR;
}
}
return rcode;
}
static int smctr_rcv_tx_forward(struct net_device *dev, MAC_HEADER *rmf)
{
MAC_SUB_VECTOR *rsv;
signed short vlen;
__u16 rcode = POSITIVE_ACK;
unsigned int svectors = F_NO_SUB_VECTORS_FOUND;
/* This Frame can only come from a CRS */
if((rmf->dc_sc & SC_MASK) != SC_CRS)
return E_INAPPROPRIATE_SOURCE_CLASS;
/* Remove MVID Length from total length */
vlen = (signed short)rmf->vl - 4;
/* Point to First SVID */
rsv = (MAC_SUB_VECTOR *)((__u32)rmf + sizeof(MAC_HEADER));
/* Search for Appropriate SVID's */
while((vlen > 0) && (rcode == POSITIVE_ACK))
{
switch(rsv->svi)
{
case FRAME_FORWARD:
svectors |= F_FRAME_FORWARD;
rcode = smctr_set_frame_forward(dev, rsv,
rmf->dc_sc);
break;
default:
rcode = E_SUB_VECTOR_UNKNOWN;
break;
}
/* Let Sender Know if SUM of SV length's is
* larger then length in MVID length field
*/
if((vlen -= rsv->svl) < 0)
rcode = E_VECTOR_LENGTH_ERROR;
rsv = (MAC_SUB_VECTOR *)((__u32)rsv + rsv->svl);
}
if(rcode == POSITIVE_ACK)
{
/* Let Sender Know if MVID length field
* is larger then SUM of SV length's
*/
if(vlen != 0)
rcode = E_VECTOR_LENGTH_ERROR;
else
{
/* Let Sender Know if Expected SV Missing */
if((svectors & R_TX_FORWARD) ^ R_TX_FORWARD)
rcode = E_MISSING_SUB_VECTOR;
}
}
return rcode;
}
static int smctr_rcv_rq_addr_state_attch(struct net_device *dev,
MAC_HEADER *rmf, __u16 *correlator)
{
MAC_SUB_VECTOR *rsv;
signed short vlen;
__u16 rcode = POSITIVE_ACK;
unsigned int svectors = F_NO_SUB_VECTORS_FOUND;
/* Remove MVID Length from total length */
vlen = (signed short)rmf->vl - 4;
/* Point to First SVID */
rsv = (MAC_SUB_VECTOR *)((__u32)rmf + sizeof(MAC_HEADER));
/* Search for Appropriate SVID's */
while((vlen > 0) && (rcode == POSITIVE_ACK))
{
switch(rsv->svi)
{
case CORRELATOR:
svectors |= F_CORRELATOR;
rcode = smctr_set_corr(dev, rsv, correlator);
break;
default:
rcode = E_SUB_VECTOR_UNKNOWN;
break;
}
/* Let Sender Know if SUM of SV length's is
* larger then length in MVID length field
*/
if((vlen -= rsv->svl) < 0)
rcode = E_VECTOR_LENGTH_ERROR;
rsv = (MAC_SUB_VECTOR *)((__u32)rsv + rsv->svl);
}
if(rcode == POSITIVE_ACK)
{
/* Let Sender Know if MVID length field
* is larger then SUM of SV length's
*/
if(vlen != 0)
rcode = E_VECTOR_LENGTH_ERROR;
else
{
/* Let Sender Know if Expected SVID Missing */
if((svectors & R_RQ_ATTCH_STATE_ADDR)
^ R_RQ_ATTCH_STATE_ADDR)
rcode = E_MISSING_SUB_VECTOR;
}
}
return rcode;
}
static int smctr_rcv_unknown(struct net_device *dev, MAC_HEADER *rmf,
__u16 *correlator)
{
MAC_SUB_VECTOR *rsv;
signed short vlen;
*correlator = 0;
/* Remove MVID Length from total length */
vlen = (signed short)rmf->vl - 4;
/* Point to First SVID */
rsv = (MAC_SUB_VECTOR *)((__u32)rmf + sizeof(MAC_HEADER));
/* Search for CORRELATOR for RSP to UNKNOWN */
while((vlen > 0) && (*correlator == 0))
{
switch(rsv->svi)
{
case CORRELATOR:
smctr_set_corr(dev, rsv, correlator);
break;
default:
break;
}
vlen -= rsv->svl;
rsv = (MAC_SUB_VECTOR *)((__u32)rsv + rsv->svl);
}
return E_UNRECOGNIZED_VECTOR_ID;
}
/*
* Reset the 825 NIC and exit w:
* 1. The NIC reset cleared (non-reset state), halted and un-initialized.
* 2. TINT masked.
* 3. CBUSY masked.
* 4. TINT clear.
* 5. CBUSY clear.
*/
static int smctr_reset_adapter(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
int ioaddr = dev->base_addr;
/* Reseting the NIC will put it in a halted and un-initialized state. */ smctr_set_trc_reset(ioaddr);
mdelay(200); /* ~2 ms */
smctr_clear_trc_reset(ioaddr);
mdelay(200); /* ~2 ms */
/* Remove any latched interrupts that occurred prior to reseting the
* adapter or possibily caused by line glitches due to the reset.
*/
outb(tp->trc_mask | CSR_CLRTINT | CSR_CLRCBUSY, ioaddr + CSR);
return 0;
}
static int smctr_restart_tx_chain(struct net_device *dev, short queue)
{
struct net_local *tp = netdev_priv(dev);
int err = 0;
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_restart_tx_chain\n", dev->name);
if(tp->num_tx_fcbs_used[queue] != 0 &&
tp->tx_queue_status[queue] == NOT_TRANSMITING)
{
tp->tx_queue_status[queue] = TRANSMITING;
err = smctr_issue_resume_tx_fcb_cmd(dev, queue);
}
return err;
}
static int smctr_ring_status_chg(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_ring_status_chg\n", dev->name);
/* Check for ring_status_flag: whenever MONITOR_STATE_BIT
* Bit is set, check value of monitor_state, only then we
* enable and start transmit/receive timeout (if and only
* if it is MS_ACTIVE_MONITOR_STATE or MS_STANDBY_MONITOR_STATE)
*/
if(tp->ring_status_flags == MONITOR_STATE_CHANGED)
{
if((tp->monitor_state == MS_ACTIVE_MONITOR_STATE) ||
(tp->monitor_state == MS_STANDBY_MONITOR_STATE))
{
tp->monitor_state_ready = 1;
}
else
{
/* if adapter is NOT in either active monitor
* or standby monitor state => Disable
* transmit/receive timeout.
*/
tp->monitor_state_ready = 0;
/* Ring speed problem, switching to auto mode. */
if(tp->monitor_state == MS_MONITOR_FSM_INACTIVE &&
!tp->cleanup)
{
printk(KERN_INFO "%s: Incorrect ring speed switching.\n",
dev->name);
smctr_set_ring_speed(dev);
}
}
}
if(!(tp->ring_status_flags & RING_STATUS_CHANGED))
return 0;
switch(tp->ring_status)
{
case RING_RECOVERY:
printk(KERN_INFO "%s: Ring Recovery\n", dev->name);
break;
case SINGLE_STATION:
printk(KERN_INFO "%s: Single Statinon\n", dev->name);
break;
case COUNTER_OVERFLOW:
printk(KERN_INFO "%s: Counter Overflow\n", dev->name);
break;
case REMOVE_RECEIVED:
printk(KERN_INFO "%s: Remove Received\n", dev->name);
break;
case AUTO_REMOVAL_ERROR:
printk(KERN_INFO "%s: Auto Remove Error\n", dev->name);
break;
case LOBE_WIRE_FAULT:
printk(KERN_INFO "%s: Lobe Wire Fault\n", dev->name);
break;
case TRANSMIT_BEACON:
printk(KERN_INFO "%s: Transmit Beacon\n", dev->name);
break;
case SOFT_ERROR:
printk(KERN_INFO "%s: Soft Error\n", dev->name);
break;
case HARD_ERROR:
printk(KERN_INFO "%s: Hard Error\n", dev->name);
break;
case SIGNAL_LOSS:
printk(KERN_INFO "%s: Signal Loss\n", dev->name);
break;
default:
printk(KERN_INFO "%s: Unknown ring status change\n",
dev->name);
break;
}
return 0;
}
static int smctr_rx_frame(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
__u16 queue, status, rx_size, err = 0;
__u8 *pbuff;
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_rx_frame\n", dev->name);
queue = tp->receive_queue_number;
while((status = tp->rx_fcb_curr[queue]->frame_status) != SUCCESS)
{
err = HARDWARE_FAILED;
if(((status & 0x007f) == 0) ||
((tp->receive_mask & ACCEPT_ERR_PACKETS) != 0))
{
/* frame length less the CRC (4 bytes) + FS (1 byte) */
rx_size = tp->rx_fcb_curr[queue]->frame_length - 5;
pbuff = smctr_get_rx_pointer(dev, queue);
smctr_set_page(dev, pbuff);
smctr_disable_16bit(dev);
/* pbuff points to addr within one page */
pbuff = (__u8 *)PAGE_POINTER(pbuff);
if(queue == NON_MAC_QUEUE)
{
struct sk_buff *skb;
skb = dev_alloc_skb(rx_size);
if (skb) {
skb_put(skb, rx_size);
skb_copy_to_linear_data(skb, pbuff, rx_size);
/* Update Counters */
tp->MacStat.rx_packets++;
tp->MacStat.rx_bytes += skb->len;
/* Kick the packet on up. */
skb->protocol = tr_type_trans(skb, dev);
netif_rx(skb);
} else {
}
}
else
smctr_process_rx_packet((MAC_HEADER *)pbuff,
rx_size, dev, status);
}
smctr_enable_16bit(dev);
smctr_set_page(dev, (__u8 *)tp->ram_access);
smctr_update_rx_chain(dev, queue);
if(err != SUCCESS)
break;
}
return err;
}
static int smctr_send_dat(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
unsigned int i, err;
MAC_HEADER *tmf;
FCBlock *fcb;
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_send_dat\n", dev->name);
if((fcb = smctr_get_tx_fcb(dev, MAC_QUEUE,
sizeof(MAC_HEADER))) == (FCBlock *)(-1L))
{
return OUT_OF_RESOURCES;
}
/* Initialize DAT Data Fields. */
tmf = (MAC_HEADER *)fcb->bdb_ptr->data_block_ptr;
tmf->ac = MSB(AC_FC_DAT);
tmf->fc = LSB(AC_FC_DAT);
for(i = 0; i < 6; i++)
{
tmf->sa[i] = dev->dev_addr[i];
tmf->da[i] = dev->dev_addr[i];
}
tmf->vc = DAT;
tmf->dc_sc = DC_RS | SC_RS;
tmf->vl = 4;
tmf->vl = SWAP_BYTES(tmf->vl);
/* Start Transmit. */
if((err = smctr_trc_send_packet(dev, fcb, MAC_QUEUE)))
return err;
/* Wait for Transmit to Complete */
for(i = 0; i < 10000; i++)
{
if(fcb->frame_status & FCB_COMMAND_DONE)
break;
mdelay(1);
}
/* Check if GOOD frame Tx'ed. */
if(!(fcb->frame_status & FCB_COMMAND_DONE) ||
fcb->frame_status & (FCB_TX_STATUS_E | FCB_TX_AC_BITS))
{
return INITIALIZE_FAILED;
}
/* De-allocated Tx FCB and Frame Buffer
* The FCB must be de-allocated manually if executing with
* interrupts disabled, other wise the ISR (LM_Service_Events)
* will de-allocate it when the interrupt occurs.
*/
tp->tx_queue_status[MAC_QUEUE] = NOT_TRANSMITING;
smctr_update_tx_chain(dev, fcb, MAC_QUEUE);
return 0;
}
static void smctr_timeout(struct net_device *dev)
{
/*
* If we get here, some higher level has decided we are broken.
* There should really be a "kick me" function call instead.
*
* Resetting the token ring adapter takes a long time so just
* fake transmission time and go on trying. Our own timeout
* routine is in sktr_timer_chk()
*/
dev->trans_start = jiffies; /* prevent tx timeout */
netif_wake_queue(dev);
}
/*
* Gets skb from system, queues it and checks if it can be sent
*/
static netdev_tx_t smctr_send_packet(struct sk_buff *skb,
struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_send_packet\n", dev->name);
/*
* Block a transmit overlap
*/
netif_stop_queue(dev);
if(tp->QueueSkb == 0)
return NETDEV_TX_BUSY; /* Return with tbusy set: queue full */
tp->QueueSkb--;
skb_queue_tail(&tp->SendSkbQueue, skb);
smctr_hardware_send_packet(dev, tp);
if(tp->QueueSkb > 0)
netif_wake_queue(dev);
return NETDEV_TX_OK;
}
static int smctr_send_lobe_media_test(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
MAC_SUB_VECTOR *tsv;
MAC_HEADER *tmf;
FCBlock *fcb;
__u32 i;
int err;
if(smctr_debug > 15)
printk(KERN_DEBUG "%s: smctr_send_lobe_media_test\n", dev->name);
if((fcb = smctr_get_tx_fcb(dev, MAC_QUEUE, sizeof(struct trh_hdr)
+ S_WRAP_DATA + S_WRAP_DATA)) == (FCBlock *)(-1L))
{
return OUT_OF_RESOURCES;
}
/* Initialize DAT Data Fields. */
tmf = (MAC_HEADER *)fcb->bdb_ptr->data_block_ptr;
tmf->ac = MSB(AC_FC_LOBE_MEDIA_TEST);
tmf->fc = LSB(AC_FC_LOBE_MEDIA_TEST);
for(i = 0; i < 6; i++)
{
tmf->da[i] = 0;
tmf->sa[i] = dev->dev_addr[i];
}
tmf->vc = LOBE_MEDIA_TEST;
tmf->dc_sc = DC_RS | SC_RS;
tmf->vl = 4;
tsv = (MAC_SUB_VECTOR *)((__u32)tmf + sizeof(MAC_HEADER));
smctr_make_wrap_data(dev, tsv);
tmf->vl += tsv->svl;
tsv = (MAC_SUB_VECTOR *)((__u32)tsv + tsv->svl);
smctr_make_wrap_data(dev, tsv);
tmf->vl += tsv->svl;
/* Start Transmit. */
tmf->vl = SWAP_BYTES(tmf->vl);
if((err = smctr_trc_send_packet(dev, fcb, MAC_QUEUE)))
return err;
/* Wait for Transmit to Complete. (10 ms). */
for(i=0; i < 10000; i++)
{
if(fcb->frame_status & FCB_COMMAND_DONE)
break;
mdelay(1);
}
/* Check if GOOD frame Tx'ed */
if(!(fcb->frame_status & FCB_COMMAND_DONE) ||
fcb->frame_status & (FCB_TX_STATUS_E | FCB_TX_AC_BITS))
{
return LOBE_MEDIA_TEST_FAILED;
}
/* De-allocated Tx FCB and Frame Buffer
* The FCB must be de-allocated manually if executing with
* interrupts disabled, other wise the ISR (LM_Service_Events)
* will de-allocate it when the interrupt occurs.
*/
tp->tx_queue_status[MAC_QUEUE] = NOT_TRANSMITING;
smctr_update_tx_chain(dev, fcb, MAC_QUEUE);
return 0;
}
static int smctr_send_rpt_addr(struct net_device *dev, MAC_HEADER *rmf,
__u16 correlator)
{
MAC_HEADER *tmf;
MAC_SUB_VECTOR *tsv;
FCBlock *fcb;
if((fcb = smctr_get_tx_fcb(dev, MAC_QUEUE, sizeof(MAC_HEADER)
+ S_CORRELATOR + S_PHYSICAL_DROP + S_UPSTREAM_NEIGHBOR_ADDRESS
+ S_ADDRESS_MODIFER + S_GROUP_ADDRESS + S_FUNCTIONAL_ADDRESS))
== (FCBlock *)(-1L))
{
return 0;
}
tmf = (MAC_HEADER *)fcb->bdb_ptr->data_block_ptr;
tmf->vc = RPT_ADDR;
tmf->dc_sc = (rmf->dc_sc & SC_MASK) << 4;
tmf->vl = 4;
smctr_make_8025_hdr(dev, rmf, tmf, AC_FC_RPT_ADDR);
tsv = (MAC_SUB_VECTOR *)((__u32)tmf + sizeof(MAC_HEADER));
smctr_make_corr(dev, tsv, correlator);
tmf->vl += tsv->svl;
tsv = (MAC_SUB_VECTOR *)((__u32)tsv + tsv->svl);
smctr_make_phy_drop_num(dev, tsv);
tmf->vl += tsv->svl;
tsv = (MAC_SUB_VECTOR *)((__u32)tsv + tsv->svl);
smctr_make_upstream_neighbor_addr(dev, tsv);
tmf->vl += tsv->svl;
tsv = (MAC_SUB_VECTOR *)((__u32)tsv + tsv->svl);
smctr_make_addr_mod(dev, tsv);
tmf->vl += tsv->svl;
tsv = (MAC_SUB_VECTOR *)((__u32)tsv + tsv->svl);
smctr_make_group_addr(dev, tsv);
tmf->vl += tsv->svl;
tsv = (MAC_SUB_VECTOR *)((__u32)tsv + tsv->svl);
smctr_make_funct_addr(dev, tsv);
tmf->vl += tsv->svl;
/* Subtract out MVID and MVL which is
* include in both vl and MAC_HEADER
*/
/* fcb->frame_length = tmf->vl + sizeof(MAC_HEADER) - 4;
fcb->bdb_ptr->buffer_length = tmf->vl + sizeof(MAC_HEADER) - 4;
*/
tmf->vl = SWAP_BYTES(tmf->vl);
return smctr_trc_send_packet(dev, fcb, MAC_QUEUE);
}
static int smctr_send_rpt_attch(struct net_device *dev, MAC_HEADER *rmf,
__u16 correlator)
{
MAC_HEADER *tmf;
MAC_SUB_VECTOR *tsv;
FCBlock *fcb;
if((fcb = smctr_get_tx_fcb(dev, MAC_QUEUE, sizeof(MAC_HEADER)
+ S_CORRELATOR + S_PRODUCT_INSTANCE_ID + S_FUNCTIONAL_ADDRESS
+ S_AUTHORIZED_FUNCTION_CLASS + S_AUTHORIZED_ACCESS_PRIORITY))
== (FCBlock *)(-1L))
{
return 0;
}
tmf = (MAC_HEADER *)fcb->bdb_ptr->data_block_ptr;
tmf->vc = RPT_ATTCH;
tmf->dc_sc = (rmf->dc_sc & SC_MASK) << 4;
tmf->vl = 4;
smctr_make_8025_hdr(dev, rmf, tmf, AC_FC_RPT_ATTCH);
tsv = (MAC_SUB_VECTOR *)((__u32)tmf + sizeof(MAC_HEADER));
smctr_make_corr(dev, tsv, correlator);
tmf->vl += tsv->svl;
tsv = (MAC_SUB_VECTOR *)((__u32)tsv + tsv->svl);
smctr_make_product_id(dev, tsv);
tmf->vl += tsv->svl;
tsv = (MAC_SUB_VECTOR *)((__u32)tsv + tsv->svl);
smctr_make_funct_addr(dev, tsv);
tmf->vl += tsv->svl;
tsv = (MAC_SUB_VECTOR *)((__u32)tsv + tsv->svl);
smctr_make_auth_funct_class(dev, tsv);
tmf->vl += tsv->svl;
tsv = (MAC_SUB_VECTOR *)((__u32)tsv + tsv->svl);
smctr_make_access_pri(dev, tsv);
tmf->vl += tsv->svl;
/* Subtract out MVID and MVL which is
* include in both vl and MAC_HEADER
*/
/* fcb->frame_length = tmf->vl + sizeof(MAC_HEADER) - 4;
fcb->bdb_ptr->buffer_length = tmf->vl + sizeof(MAC_HEADER) - 4;
*/
tmf->vl = SWAP_BYTES(tmf->vl);
return smctr_trc_send_packet(dev, fcb, MAC_QUEUE);
}
static int smctr_send_rpt_state(struct net_device *dev, MAC_HEADER *rmf,
__u16 correlator)
{
MAC_HEADER *tmf;
MAC_SUB_VECTOR *tsv;
FCBlock *fcb;
if((fcb = smctr_get_tx_fcb(dev, MAC_QUEUE, sizeof(MAC_HEADER)
+ S_CORRELATOR + S_RING_STATION_VERSION_NUMBER
+ S_RING_STATION_STATUS + S_STATION_IDENTIFER))
== (FCBlock *)(-1L))
{
return 0;
}
tmf = (MAC_HEADER *)fcb->bdb_ptr->data_block_ptr;
tmf->vc = RPT_STATE;
tmf->dc_sc = (rmf->dc_sc & SC_MASK) << 4;
tmf->vl = 4;
smctr_make_8025_hdr(dev, rmf, tmf, AC_FC_RPT_STATE);
tsv = (MAC_SUB_VECTOR *)((__u32)tmf + sizeof(MAC_HEADER));
smctr_make_corr(dev, tsv, correlator);
tmf->vl += tsv->svl;
tsv = (MAC_SUB_VECTOR *)((__u32)tsv + tsv->svl);
smctr_make_ring_station_version(dev, tsv);
tmf->vl += tsv->svl;
tsv = (MAC_SUB_VECTOR *)((__u32)tsv + tsv->svl);
smctr_make_ring_station_status(dev, tsv);
tmf->vl += tsv->svl;
tsv = (MAC_SUB_VECTOR *)((__u32)tsv + tsv->svl);
smctr_make_station_id(dev, tsv);
tmf->vl += tsv->svl;
/* Subtract out MVID and MVL which is
* include in both vl and MAC_HEADER
*/
/* fcb->frame_length = tmf->vl + sizeof(MAC_HEADER) - 4;
fcb->bdb_ptr->buffer_length = tmf->vl + sizeof(MAC_HEADER) - 4;
*/
tmf->vl = SWAP_BYTES(tmf->vl);
return smctr_trc_send_packet(dev, fcb, MAC_QUEUE);
}
static int smctr_send_rpt_tx_forward(struct net_device *dev,
MAC_HEADER *rmf, __u16 tx_fstatus)
{
MAC_HEADER *tmf;
MAC_SUB_VECTOR *tsv;
FCBlock *fcb;
if((fcb = smctr_get_tx_fcb(dev, MAC_QUEUE, sizeof(MAC_HEADER)
+ S_TRANSMIT_STATUS_CODE)) == (FCBlock *)(-1L))
{
return 0;
}
tmf = (MAC_HEADER *)fcb->bdb_ptr->data_block_ptr;
tmf->vc = RPT_TX_FORWARD;
tmf->dc_sc = (rmf->dc_sc & SC_MASK) << 4;
tmf->vl = 4;
smctr_make_8025_hdr(dev, rmf, tmf, AC_FC_RPT_TX_FORWARD);
tsv = (MAC_SUB_VECTOR *)((__u32)tmf + sizeof(MAC_HEADER));
smctr_make_tx_status_code(dev, tsv, tx_fstatus);
tmf->vl += tsv->svl;
/* Subtract out MVID and MVL which is
* include in both vl and MAC_HEADER
*/
/* fcb->frame_length = tmf->vl + sizeof(MAC_HEADER) - 4;
fcb->bdb_ptr->buffer_length = tmf->vl + sizeof(MAC_HEADER) - 4;
*/
tmf->vl = SWAP_BYTES(tmf->vl);
return smctr_trc_send_packet(dev, fcb, MAC_QUEUE);
}
static int smctr_send_rsp(struct net_device *dev, MAC_HEADER *rmf,
__u16 rcode, __u16 correlator)
{
MAC_HEADER *tmf;
MAC_SUB_VECTOR *tsv;
FCBlock *fcb;
if((fcb = smctr_get_tx_fcb(dev, MAC_QUEUE, sizeof(MAC_HEADER)
+ S_CORRELATOR + S_RESPONSE_CODE)) == (FCBlock *)(-1L))
{
return 0;
}
tmf = (MAC_HEADER *)fcb->bdb_ptr->data_block_ptr;
tmf->vc = RSP;
tmf->dc_sc = (rmf->dc_sc & SC_MASK) << 4;
tmf->vl = 4;
smctr_make_8025_hdr(dev, rmf, tmf, AC_FC_RSP);
tsv = (MAC_SUB_VECTOR *)((__u32)tmf + sizeof(MAC_HEADER));
smctr_make_corr(dev, tsv, correlator);
return 0;
}
static int smctr_send_rq_init(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
MAC_HEADER *tmf;
MAC_SUB_VECTOR *tsv;
FCBlock *fcb;
unsigned int i, count = 0;
__u16 fstatus;
int err;
do {
if(((fcb = smctr_get_tx_fcb(dev, MAC_QUEUE, sizeof(MAC_HEADER)
+ S_PRODUCT_INSTANCE_ID + S_UPSTREAM_NEIGHBOR_ADDRESS
+ S_RING_STATION_VERSION_NUMBER + S_ADDRESS_MODIFER))
== (FCBlock *)(-1L)))
{
return 0;
}
tmf = (MAC_HEADER *)fcb->bdb_ptr->data_block_ptr;
tmf->vc = RQ_INIT;
tmf->dc_sc = DC_RPS | SC_RS;
tmf->vl = 4;
smctr_make_8025_hdr(dev, NULL, tmf, AC_FC_RQ_INIT);
tsv = (MAC_SUB_VECTOR *)((__u32)tmf + sizeof(MAC_HEADER));
smctr_make_product_id(dev, tsv);
tmf->vl += tsv->svl;
tsv = (MAC_SUB_VECTOR *)((__u32)tsv + tsv->svl);
smctr_make_upstream_neighbor_addr(dev, tsv);
tmf->vl += tsv->svl;
tsv = (MAC_SUB_VECTOR *)((__u32)tsv + tsv->svl);
smctr_make_ring_station_version(dev, tsv);
tmf->vl += tsv->svl;
tsv = (MAC_SUB_VECTOR *)((__u32)tsv + tsv->svl);
smctr_make_addr_mod(dev, tsv);
tmf->vl += tsv->svl;
/* Subtract out MVID and MVL which is
* include in both vl and MAC_HEADER
*/
/* fcb->frame_length = tmf->vl + sizeof(MAC_HEADER) - 4;
fcb->bdb_ptr->buffer_length = tmf->vl + sizeof(MAC_HEADER) - 4;
*/
tmf->vl = SWAP_BYTES(tmf->vl);
if((err = smctr_trc_send_packet(dev, fcb, MAC_QUEUE)))
return err;
/* Wait for Transmit to Complete */
for(i = 0; i < 10000; i++)
{
if(fcb->frame_status & FCB_COMMAND_DONE)
break;
mdelay(1);
}
/* Check if GOOD frame Tx'ed */
fstatus = fcb->frame_status;
if(!(fstatus & FCB_COMMAND_DONE))
return HARDWARE_FAILED;
if(!(fstatus & FCB_TX_STATUS_E))
count++;
/* De-allocated Tx FCB and Frame Buffer
* The FCB must be de-allocated manually if executing with
* interrupts disabled, other wise the ISR (LM_Service_Events)
* will de-allocate it when the interrupt occurs.
*/
tp->tx_queue_status[MAC_QUEUE] = NOT_TRANSMITING;
smctr_update_tx_chain(dev, fcb, MAC_QUEUE);
} while(count < 4 && ((fstatus & FCB_TX_AC_BITS) ^ FCB_TX_AC_BITS));
return smctr_join_complete_state(dev);
}
static int smctr_send_tx_forward(struct net_device *dev, MAC_HEADER *rmf,
__u16 *tx_fstatus)
{
struct net_local *tp = netdev_priv(dev);
FCBlock *fcb;
unsigned int i;
int err;
/* Check if this is the END POINT of the Transmit Forward Chain. */
if(rmf->vl <= 18)
return 0;
/* Allocate Transmit FCB only by requesting 0 bytes
* of data buffer.
*/
if((fcb = smctr_get_tx_fcb(dev, MAC_QUEUE, 0)) == (FCBlock *)(-1L))
return 0;
/* Set pointer to Transmit Frame Buffer to the data
* portion of the received TX Forward frame, making
* sure to skip over the Vector Code (vc) and Vector
* length (vl).
*/
fcb->bdb_ptr->trc_data_block_ptr = TRC_POINTER((__u32)rmf
+ sizeof(MAC_HEADER) + 2);
fcb->bdb_ptr->data_block_ptr = (__u16 *)((__u32)rmf
+ sizeof(MAC_HEADER) + 2);
fcb->frame_length = rmf->vl - 4 - 2;
fcb->bdb_ptr->buffer_length = rmf->vl - 4 - 2;
if((err = smctr_trc_send_packet(dev, fcb, MAC_QUEUE)))
return err;
/* Wait for Transmit to Complete */
for(i = 0; i < 10000; i++)
{
if(fcb->frame_status & FCB_COMMAND_DONE)
break;
mdelay(1);
}
/* Check if GOOD frame Tx'ed */
if(!(fcb->frame_status & FCB_COMMAND_DONE))
{
if((err = smctr_issue_resume_tx_fcb_cmd(dev, MAC_QUEUE)))
return err;
for(i = 0; i < 10000; i++)
{
if(fcb->frame_status & FCB_COMMAND_DONE)
break;
mdelay(1);
}
if(!(fcb->frame_status & FCB_COMMAND_DONE))
return HARDWARE_FAILED;
}
*tx_fstatus = fcb->frame_status;
return A_FRAME_WAS_FORWARDED;
}
static int smctr_set_auth_access_pri(struct net_device *dev,
MAC_SUB_VECTOR *rsv)
{
struct net_local *tp = netdev_priv(dev);
if(rsv->svl != S_AUTHORIZED_ACCESS_PRIORITY)
return E_SUB_VECTOR_LENGTH_ERROR;
tp->authorized_access_priority = (rsv->svv[0] << 8 | rsv->svv[1]);
return POSITIVE_ACK;
}
static int smctr_set_auth_funct_class(struct net_device *dev,
MAC_SUB_VECTOR *rsv)
{
struct net_local *tp = netdev_priv(dev);
if(rsv->svl != S_AUTHORIZED_FUNCTION_CLASS)
return E_SUB_VECTOR_LENGTH_ERROR;
tp->authorized_function_classes = (rsv->svv[0] << 8 | rsv->svv[1]);
return POSITIVE_ACK;
}
static int smctr_set_corr(struct net_device *dev, MAC_SUB_VECTOR *rsv,
__u16 *correlator)
{
if(rsv->svl != S_CORRELATOR)
return E_SUB_VECTOR_LENGTH_ERROR;
*correlator = (rsv->svv[0] << 8 | rsv->svv[1]);
return POSITIVE_ACK;
}
static int smctr_set_error_timer_value(struct net_device *dev,
MAC_SUB_VECTOR *rsv)
{
__u16 err_tval;
int err;
if(rsv->svl != S_ERROR_TIMER_VALUE)
return E_SUB_VECTOR_LENGTH_ERROR;
err_tval = (rsv->svv[0] << 8 | rsv->svv[1])*10;
smctr_issue_write_word_cmd(dev, RW_TER_THRESHOLD, &err_tval);
if((err = smctr_wait_cmd(dev)))
return err;
return POSITIVE_ACK;
}
static int smctr_set_frame_forward(struct net_device *dev,
MAC_SUB_VECTOR *rsv, __u8 dc_sc)
{
if((rsv->svl < 2) || (rsv->svl > S_FRAME_FORWARD))
return E_SUB_VECTOR_LENGTH_ERROR;
if((dc_sc & DC_MASK) != DC_CRS)
{
if(rsv->svl >= 2 && rsv->svl < 20)
return E_TRANSMIT_FORWARD_INVALID;
if((rsv->svv[0] != 0) || (rsv->svv[1] != 0))
return E_TRANSMIT_FORWARD_INVALID;
}
return POSITIVE_ACK;
}
static int smctr_set_local_ring_num(struct net_device *dev,
MAC_SUB_VECTOR *rsv)
{
struct net_local *tp = netdev_priv(dev);
if(rsv->svl != S_LOCAL_RING_NUMBER)
return E_SUB_VECTOR_LENGTH_ERROR;
if(tp->ptr_local_ring_num)
*(__u16 *)(tp->ptr_local_ring_num)
= (rsv->svv[0] << 8 | rsv->svv[1]);
return POSITIVE_ACK;
}
static unsigned short smctr_set_ctrl_attention(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
int ioaddr = dev->base_addr;
if(tp->bic_type == BIC_585_CHIP)
outb((tp->trc_mask | HWR_CA), ioaddr + HWR);
else
{
outb((tp->trc_mask | CSR_CA), ioaddr + CSR);
outb(tp->trc_mask, ioaddr + CSR);
}
return 0;
}
static void smctr_set_multicast_list(struct net_device *dev)
{
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_set_multicast_list\n", dev->name);
}
static int smctr_set_page(struct net_device *dev, __u8 *buf)
{
struct net_local *tp = netdev_priv(dev);
__u8 amask;
__u32 tptr;
tptr = (__u32)buf - (__u32)tp->ram_access;
amask = (__u8)((tptr & PR_PAGE_MASK) >> 8);
outb(amask, dev->base_addr + PR);
return 0;
}
static int smctr_set_phy_drop(struct net_device *dev, MAC_SUB_VECTOR *rsv)
{
int err;
if(rsv->svl != S_PHYSICAL_DROP)
return E_SUB_VECTOR_LENGTH_ERROR;
smctr_issue_write_byte_cmd(dev, RW_PHYSICAL_DROP_NUMBER, &rsv->svv[0]);
if((err = smctr_wait_cmd(dev)))
return err;
return POSITIVE_ACK;
}
/* Reset the ring speed to the opposite of what it was. This auto-pilot
* mode requires a complete reset and re-init of the adapter.
*/
static int smctr_set_ring_speed(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
int err;
if(tp->media_type == MEDIA_UTP_16)
tp->media_type = MEDIA_UTP_4;
else
tp->media_type = MEDIA_UTP_16;
smctr_enable_16bit(dev);
/* Re-Initialize adapter's internal registers */
smctr_reset_adapter(dev);
if((err = smctr_init_card_real(dev)))
return err;
smctr_enable_bic_int(dev);
if((err = smctr_issue_enable_int_cmd(dev, TRC_INTERRUPT_ENABLE_MASK)))
return err;
smctr_disable_16bit(dev);
return 0;
}
static int smctr_set_rx_look_ahead(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
__u16 sword, rword;
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_set_rx_look_ahead_flag\n", dev->name);
tp->adapter_flags &= ~(FORCED_16BIT_MODE);
tp->adapter_flags |= RX_VALID_LOOKAHEAD;
if(tp->adapter_bus == BUS_ISA16_TYPE)
{
sword = *((__u16 *)(tp->ram_access));
*((__u16 *)(tp->ram_access)) = 0x1234;
smctr_disable_16bit(dev);
rword = *((__u16 *)(tp->ram_access));
smctr_enable_16bit(dev);
if(rword != 0x1234)
tp->adapter_flags |= FORCED_16BIT_MODE;
*((__u16 *)(tp->ram_access)) = sword;
}
return 0;
}
static int smctr_set_trc_reset(int ioaddr)
{
__u8 r;
r = inb(ioaddr + MSR);
outb(MSR_RST | r, ioaddr + MSR);
return 0;
}
/*
* This function can be called if the adapter is busy or not.
*/
static int smctr_setup_single_cmd(struct net_device *dev,
__u16 command, __u16 subcommand)
{
struct net_local *tp = netdev_priv(dev);
unsigned int err;
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_setup_single_cmd\n", dev->name);
if((err = smctr_wait_while_cbusy(dev)))
return err;
if((err = (unsigned int)smctr_wait_cmd(dev)))
return err;
tp->acb_head->cmd_done_status = 0;
tp->acb_head->cmd = command;
tp->acb_head->subcmd = subcommand;
err = smctr_issue_resume_acb_cmd(dev);
return err;
}
/*
* This function can not be called with the adapter busy.
*/
static int smctr_setup_single_cmd_w_data(struct net_device *dev,
__u16 command, __u16 subcommand)
{
struct net_local *tp = netdev_priv(dev);
tp->acb_head->cmd_done_status = ACB_COMMAND_NOT_DONE;
tp->acb_head->cmd = command;
tp->acb_head->subcmd = subcommand;
tp->acb_head->data_offset_lo
= (__u16)TRC_POINTER(tp->misc_command_data);
return smctr_issue_resume_acb_cmd(dev);
}
static char *smctr_malloc(struct net_device *dev, __u16 size)
{
struct net_local *tp = netdev_priv(dev);
char *m;
m = (char *)(tp->ram_access + tp->sh_mem_used);
tp->sh_mem_used += (__u32)size;
return m;
}
static int smctr_status_chg(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_status_chg\n", dev->name);
switch(tp->status)
{
case OPEN:
break;
case CLOSED:
break;
/* Interrupt driven open() completion. XXX */
case INITIALIZED:
tp->group_address_0 = 0;
tp->group_address[0] = 0;
tp->group_address[1] = 0;
tp->functional_address_0 = 0;
tp->functional_address[0] = 0;
tp->functional_address[1] = 0;
smctr_open_tr(dev);
break;
default:
printk(KERN_INFO "%s: status change unknown %x\n",
dev->name, tp->status);
break;
}
return 0;
}
static int smctr_trc_send_packet(struct net_device *dev, FCBlock *fcb,
__u16 queue)
{
struct net_local *tp = netdev_priv(dev);
int err = 0;
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_trc_send_packet\n", dev->name);
fcb->info = FCB_CHAIN_END | FCB_ENABLE_TFS;
if(tp->num_tx_fcbs[queue] != 1)
fcb->back_ptr->info = FCB_INTERRUPT_ENABLE | FCB_ENABLE_TFS;
if(tp->tx_queue_status[queue] == NOT_TRANSMITING)
{
tp->tx_queue_status[queue] = TRANSMITING;
err = smctr_issue_resume_tx_fcb_cmd(dev, queue);
}
return err;
}
static __u16 smctr_tx_complete(struct net_device *dev, __u16 queue)
{
struct net_local *tp = netdev_priv(dev);
__u16 status, err = 0;
int cstatus;
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_tx_complete\n", dev->name);
while((status = tp->tx_fcb_end[queue]->frame_status) != SUCCESS)
{
if(status & 0x7e00 )
{
err = HARDWARE_FAILED;
break;
}
if((err = smctr_update_tx_chain(dev, tp->tx_fcb_end[queue],
queue)) != SUCCESS)
break;
smctr_disable_16bit(dev);
if(tp->mode_bits & UMAC)
{
if(!(status & (FCB_TX_STATUS_AR1 | FCB_TX_STATUS_AR2)))
cstatus = NO_SUCH_DESTINATION;
else
{
if(!(status & (FCB_TX_STATUS_CR1 | FCB_TX_STATUS_CR2)))
cstatus = DEST_OUT_OF_RESOURCES;
else
{
if(status & FCB_TX_STATUS_E)
cstatus = MAX_COLLISIONS;
else
cstatus = SUCCESS;
}
}
}
else
cstatus = SUCCESS;
if(queue == BUG_QUEUE)
err = SUCCESS;
smctr_enable_16bit(dev);
if(err != SUCCESS)
break;
}
return err;
}
static unsigned short smctr_tx_move_frame(struct net_device *dev,
struct sk_buff *skb, __u8 *pbuff, unsigned int bytes)
{
struct net_local *tp = netdev_priv(dev);
unsigned int ram_usable;
__u32 flen, len, offset = 0;
__u8 *frag, *page;
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_tx_move_frame\n", dev->name);
ram_usable = ((unsigned int)tp->ram_usable) << 10;
frag = skb->data;
flen = skb->len;
while(flen > 0 && bytes > 0)
{
smctr_set_page(dev, pbuff);
offset = SMC_PAGE_OFFSET(pbuff);
if(offset + flen > ram_usable)
len = ram_usable - offset;
else
len = flen;
if(len > bytes)
len = bytes;
page = (char *) (offset + tp->ram_access);
memcpy(page, frag, len);
flen -=len;
bytes -= len;
frag += len;
pbuff += len;
}
return 0;
}
/* Update the error statistic counters for this adapter. */
static int smctr_update_err_stats(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
struct tr_statistics *tstat = &tp->MacStat;
if(tstat->internal_errors)
tstat->internal_errors
+= *(tp->misc_command_data + 0) & 0x00ff;
if(tstat->line_errors)
tstat->line_errors += *(tp->misc_command_data + 0) >> 8;
if(tstat->A_C_errors)
tstat->A_C_errors += *(tp->misc_command_data + 1) & 0x00ff;
if(tstat->burst_errors)
tstat->burst_errors += *(tp->misc_command_data + 1) >> 8;
if(tstat->abort_delimiters)
tstat->abort_delimiters += *(tp->misc_command_data + 2) >> 8;
if(tstat->recv_congest_count)
tstat->recv_congest_count
+= *(tp->misc_command_data + 3) & 0x00ff;
if(tstat->lost_frames)
tstat->lost_frames
+= *(tp->misc_command_data + 3) >> 8;
if(tstat->frequency_errors)
tstat->frequency_errors += *(tp->misc_command_data + 4) & 0x00ff;
if(tstat->frame_copied_errors)
tstat->frame_copied_errors
+= *(tp->misc_command_data + 4) >> 8;
if(tstat->token_errors)
tstat->token_errors += *(tp->misc_command_data + 5) >> 8;
return 0;
}
static int smctr_update_rx_chain(struct net_device *dev, __u16 queue)
{
struct net_local *tp = netdev_priv(dev);
FCBlock *fcb;
BDBlock *bdb;
__u16 size, len;
fcb = tp->rx_fcb_curr[queue];
len = fcb->frame_length;
fcb->frame_status = 0;
fcb->info = FCB_CHAIN_END;
fcb->back_ptr->info = FCB_WARNING;
tp->rx_fcb_curr[queue] = tp->rx_fcb_curr[queue]->next_ptr;
/* update RX BDBs */
size = (len >> RX_BDB_SIZE_SHIFT);
if(len & RX_DATA_BUFFER_SIZE_MASK)
size += sizeof(BDBlock);
size &= (~RX_BDB_SIZE_MASK);
/* check if wrap around */
bdb = (BDBlock *)((__u32)(tp->rx_bdb_curr[queue]) + (__u32)(size));
if((__u32)bdb >= (__u32)tp->rx_bdb_end[queue])
{
bdb = (BDBlock *)((__u32)(tp->rx_bdb_head[queue])
+ (__u32)(bdb) - (__u32)(tp->rx_bdb_end[queue]));
}
bdb->back_ptr->info = BDB_CHAIN_END;
tp->rx_bdb_curr[queue]->back_ptr->info = BDB_NOT_CHAIN_END;
tp->rx_bdb_curr[queue] = bdb;
return 0;
}
static int smctr_update_tx_chain(struct net_device *dev, FCBlock *fcb,
__u16 queue)
{
struct net_local *tp = netdev_priv(dev);
if(smctr_debug > 20)
printk(KERN_DEBUG "smctr_update_tx_chain\n");
if(tp->num_tx_fcbs_used[queue] <= 0)
return HARDWARE_FAILED;
else
{
if(tp->tx_buff_used[queue] < fcb->memory_alloc)
{
tp->tx_buff_used[queue] = 0;
return HARDWARE_FAILED;
}
tp->tx_buff_used[queue] -= fcb->memory_alloc;
/* if all transmit buffer are cleared
* need to set the tx_buff_curr[] to tx_buff_head[]
* otherwise, tx buffer will be segregate and cannot
* accommodate and buffer greater than (curr - head) and
* (end - curr) since we do not allow wrap around allocation.
*/
if(tp->tx_buff_used[queue] == 0)
tp->tx_buff_curr[queue] = tp->tx_buff_head[queue];
tp->num_tx_fcbs_used[queue]--;
fcb->frame_status = 0;
tp->tx_fcb_end[queue] = fcb->next_ptr;
netif_wake_queue(dev);
return 0;
}
}
static int smctr_wait_cmd(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
unsigned int loop_count = 0x20000;
if(smctr_debug > 10)
printk(KERN_DEBUG "%s: smctr_wait_cmd\n", dev->name);
while(loop_count)
{
if(tp->acb_head->cmd_done_status & ACB_COMMAND_DONE)
break;
udelay(1);
loop_count--;
}
if(loop_count == 0)
return HARDWARE_FAILED;
if(tp->acb_head->cmd_done_status & 0xff)
return HARDWARE_FAILED;
return 0;
}
static int smctr_wait_while_cbusy(struct net_device *dev)
{
struct net_local *tp = netdev_priv(dev);
unsigned int timeout = 0x20000;
int ioaddr = dev->base_addr;
__u8 r;
if(tp->bic_type == BIC_585_CHIP)
{
while(timeout)
{
r = inb(ioaddr + HWR);
if((r & HWR_CBUSY) == 0)
break;
timeout--;
}
}
else
{
while(timeout)
{
r = inb(ioaddr + CSR);
if((r & CSR_CBUSY) == 0)
break;
timeout--;
}
}
if(timeout)
return 0;
else
return HARDWARE_FAILED;
}
#ifdef MODULE
static struct net_device* dev_smctr[SMCTR_MAX_ADAPTERS];
static int io[SMCTR_MAX_ADAPTERS];
static int irq[SMCTR_MAX_ADAPTERS];
MODULE_LICENSE("GPL");
MODULE_FIRMWARE("tr_smctr.bin");
module_param_array(io, int, NULL, 0);
module_param_array(irq, int, NULL, 0);
module_param(ringspeed, int, 0);
static struct net_device * __init setup_card(int n)
{
struct net_device *dev = alloc_trdev(sizeof(struct net_local));
int err;
if (!dev)
return ERR_PTR(-ENOMEM);
dev->irq = irq[n];
err = smctr_probe1(dev, io[n]);
if (err)
goto out;
err = register_netdev(dev);
if (err)
goto out1;
return dev;
out1:
#ifdef CONFIG_MCA_LEGACY
{ struct net_local *tp = netdev_priv(dev);
if (tp->slot_num)
mca_mark_as_unused(tp->slot_num);
}
#endif
release_region(dev->base_addr, SMCTR_IO_EXTENT);
free_irq(dev->irq, dev);
out:
free_netdev(dev);
return ERR_PTR(err);
}
int __init init_module(void)
{
int i, found = 0;
struct net_device *dev;
for(i = 0; i < SMCTR_MAX_ADAPTERS; i++) {
dev = io[0]? setup_card(i) : smctr_probe(-1);
if (!IS_ERR(dev)) {
++found;
dev_smctr[i] = dev;
}
}
return found ? 0 : -ENODEV;
}
void __exit cleanup_module(void)
{
int i;
for(i = 0; i < SMCTR_MAX_ADAPTERS; i++) {
struct net_device *dev = dev_smctr[i];
if (dev) {
unregister_netdev(dev);
#ifdef CONFIG_MCA_LEGACY
{ struct net_local *tp = netdev_priv(dev);
if (tp->slot_num)
mca_mark_as_unused(tp->slot_num);
}
#endif
release_region(dev->base_addr, SMCTR_IO_EXTENT);
if (dev->irq)
free_irq(dev->irq, dev);
free_netdev(dev);
}
}
}
#endif /* MODULE */
| gpl-2.0 |
q1b/mut_linux | drivers/pnp/isapnp/core.c | 4194 | 26129 | /*
* ISA Plug & Play support
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Changelog:
* 2000-01-01 Added quirks handling for buggy hardware
* Peter Denison <peterd@pnd-pc.demon.co.uk>
* 2000-06-14 Added isapnp_probe_devs() and isapnp_activate_dev()
* Christoph Hellwig <hch@infradead.org>
* 2001-06-03 Added release_region calls to correspond with
* request_region calls when a failure occurs. Also
* added KERN_* constants to printk() calls.
* 2001-11-07 Added isapnp_{,un}register_driver calls along the lines
* of the pci driver interface
* Kai Germaschewski <kai.germaschewski@gmx.de>
* 2002-06-06 Made the use of dma channel 0 configurable
* Gerald Teschl <gerald.teschl@univie.ac.at>
* 2002-10-06 Ported to PnP Layer - Adam Belay <ambx1@neo.rr.com>
* 2003-08-11 Resource Management Updates - Adam Belay <ambx1@neo.rr.com>
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/isapnp.h>
#include <linux/mutex.h>
#include <asm/io.h>
#include "../base.h"
#if 0
#define ISAPNP_REGION_OK
#endif
int isapnp_disable; /* Disable ISA PnP */
static int isapnp_rdp; /* Read Data Port */
static int isapnp_reset = 1; /* reset all PnP cards (deactivate) */
static int isapnp_verbose = 1; /* verbose mode */
MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>");
MODULE_DESCRIPTION("Generic ISA Plug & Play support");
module_param(isapnp_disable, int, 0);
MODULE_PARM_DESC(isapnp_disable, "ISA Plug & Play disable");
module_param(isapnp_rdp, int, 0);
MODULE_PARM_DESC(isapnp_rdp, "ISA Plug & Play read data port");
module_param(isapnp_reset, int, 0);
MODULE_PARM_DESC(isapnp_reset, "ISA Plug & Play reset all cards");
module_param(isapnp_verbose, int, 0);
MODULE_PARM_DESC(isapnp_verbose, "ISA Plug & Play verbose mode");
MODULE_LICENSE("GPL");
#define _PIDXR 0x279
#define _PNPWRP 0xa79
/* short tags */
#define _STAG_PNPVERNO 0x01
#define _STAG_LOGDEVID 0x02
#define _STAG_COMPATDEVID 0x03
#define _STAG_IRQ 0x04
#define _STAG_DMA 0x05
#define _STAG_STARTDEP 0x06
#define _STAG_ENDDEP 0x07
#define _STAG_IOPORT 0x08
#define _STAG_FIXEDIO 0x09
#define _STAG_VENDOR 0x0e
#define _STAG_END 0x0f
/* long tags */
#define _LTAG_MEMRANGE 0x81
#define _LTAG_ANSISTR 0x82
#define _LTAG_UNICODESTR 0x83
#define _LTAG_VENDOR 0x84
#define _LTAG_MEM32RANGE 0x85
#define _LTAG_FIXEDMEM32RANGE 0x86
/* Logical device control and configuration registers */
#define ISAPNP_CFG_ACTIVATE 0x30 /* byte */
#define ISAPNP_CFG_MEM 0x40 /* 4 * dword */
#define ISAPNP_CFG_PORT 0x60 /* 8 * word */
#define ISAPNP_CFG_IRQ 0x70 /* 2 * word */
#define ISAPNP_CFG_DMA 0x74 /* 2 * byte */
/*
* Sizes of ISAPNP logical device configuration register sets.
* See PNP-ISA-v1.0a.pdf, Appendix A.
*/
#define ISAPNP_MAX_MEM 4
#define ISAPNP_MAX_PORT 8
#define ISAPNP_MAX_IRQ 2
#define ISAPNP_MAX_DMA 2
static unsigned char isapnp_checksum_value;
static DEFINE_MUTEX(isapnp_cfg_mutex);
static int isapnp_csn_count;
/* some prototypes */
static inline void write_data(unsigned char x)
{
outb(x, _PNPWRP);
}
static inline void write_address(unsigned char x)
{
outb(x, _PIDXR);
udelay(20);
}
static inline unsigned char read_data(void)
{
unsigned char val = inb(isapnp_rdp);
return val;
}
unsigned char isapnp_read_byte(unsigned char idx)
{
write_address(idx);
return read_data();
}
static unsigned short isapnp_read_word(unsigned char idx)
{
unsigned short val;
val = isapnp_read_byte(idx);
val = (val << 8) + isapnp_read_byte(idx + 1);
return val;
}
void isapnp_write_byte(unsigned char idx, unsigned char val)
{
write_address(idx);
write_data(val);
}
static void isapnp_write_word(unsigned char idx, unsigned short val)
{
isapnp_write_byte(idx, val >> 8);
isapnp_write_byte(idx + 1, val);
}
static void isapnp_key(void)
{
unsigned char code = 0x6a, msb;
int i;
mdelay(1);
write_address(0x00);
write_address(0x00);
write_address(code);
for (i = 1; i < 32; i++) {
msb = ((code & 0x01) ^ ((code & 0x02) >> 1)) << 7;
code = (code >> 1) | msb;
write_address(code);
}
}
/* place all pnp cards in wait-for-key state */
static void isapnp_wait(void)
{
isapnp_write_byte(0x02, 0x02);
}
static void isapnp_wake(unsigned char csn)
{
isapnp_write_byte(0x03, csn);
}
static void isapnp_device(unsigned char logdev)
{
isapnp_write_byte(0x07, logdev);
}
static void isapnp_activate(unsigned char logdev)
{
isapnp_device(logdev);
isapnp_write_byte(ISAPNP_CFG_ACTIVATE, 1);
udelay(250);
}
static void isapnp_deactivate(unsigned char logdev)
{
isapnp_device(logdev);
isapnp_write_byte(ISAPNP_CFG_ACTIVATE, 0);
udelay(500);
}
static void __init isapnp_peek(unsigned char *data, int bytes)
{
int i, j;
unsigned char d = 0;
for (i = 1; i <= bytes; i++) {
for (j = 0; j < 20; j++) {
d = isapnp_read_byte(0x05);
if (d & 1)
break;
udelay(100);
}
if (!(d & 1)) {
if (data != NULL)
*data++ = 0xff;
continue;
}
d = isapnp_read_byte(0x04); /* PRESDI */
isapnp_checksum_value += d;
if (data != NULL)
*data++ = d;
}
}
#define RDP_STEP 32 /* minimum is 4 */
static int isapnp_next_rdp(void)
{
int rdp = isapnp_rdp;
static int old_rdp = 0;
if (old_rdp) {
release_region(old_rdp, 1);
old_rdp = 0;
}
while (rdp <= 0x3ff) {
/*
* We cannot use NE2000 probe spaces for ISAPnP or we
* will lock up machines.
*/
if ((rdp < 0x280 || rdp > 0x380)
&& request_region(rdp, 1, "ISAPnP")) {
isapnp_rdp = rdp;
old_rdp = rdp;
return 0;
}
rdp += RDP_STEP;
}
return -1;
}
/* Set read port address */
static inline void isapnp_set_rdp(void)
{
isapnp_write_byte(0x00, isapnp_rdp >> 2);
udelay(100);
}
/*
* Perform an isolation. The port selection code now tries to avoid
* "dangerous to read" ports.
*/
static int __init isapnp_isolate_rdp_select(void)
{
isapnp_wait();
isapnp_key();
/* Control: reset CSN and conditionally everything else too */
isapnp_write_byte(0x02, isapnp_reset ? 0x05 : 0x04);
mdelay(2);
isapnp_wait();
isapnp_key();
isapnp_wake(0x00);
if (isapnp_next_rdp() < 0) {
isapnp_wait();
return -1;
}
isapnp_set_rdp();
udelay(1000);
write_address(0x01);
udelay(1000);
return 0;
}
/*
* Isolate (assign uniqued CSN) to all ISA PnP devices.
*/
static int __init isapnp_isolate(void)
{
unsigned char checksum = 0x6a;
unsigned char chksum = 0x00;
unsigned char bit = 0x00;
int data;
int csn = 0;
int i;
int iteration = 1;
isapnp_rdp = 0x213;
if (isapnp_isolate_rdp_select() < 0)
return -1;
while (1) {
for (i = 1; i <= 64; i++) {
data = read_data() << 8;
udelay(250);
data = data | read_data();
udelay(250);
if (data == 0x55aa)
bit = 0x01;
checksum =
((((checksum ^ (checksum >> 1)) & 0x01) ^ bit) << 7)
| (checksum >> 1);
bit = 0x00;
}
for (i = 65; i <= 72; i++) {
data = read_data() << 8;
udelay(250);
data = data | read_data();
udelay(250);
if (data == 0x55aa)
chksum |= (1 << (i - 65));
}
if (checksum != 0x00 && checksum == chksum) {
csn++;
isapnp_write_byte(0x06, csn);
udelay(250);
iteration++;
isapnp_wake(0x00);
isapnp_set_rdp();
udelay(1000);
write_address(0x01);
udelay(1000);
goto __next;
}
if (iteration == 1) {
isapnp_rdp += RDP_STEP;
if (isapnp_isolate_rdp_select() < 0)
return -1;
} else if (iteration > 1) {
break;
}
__next:
if (csn == 255)
break;
checksum = 0x6a;
chksum = 0x00;
bit = 0x00;
}
isapnp_wait();
isapnp_csn_count = csn;
return csn;
}
/*
* Read one tag from stream.
*/
static int __init isapnp_read_tag(unsigned char *type, unsigned short *size)
{
unsigned char tag, tmp[2];
isapnp_peek(&tag, 1);
if (tag == 0) /* invalid tag */
return -1;
if (tag & 0x80) { /* large item */
*type = tag;
isapnp_peek(tmp, 2);
*size = (tmp[1] << 8) | tmp[0];
} else {
*type = (tag >> 3) & 0x0f;
*size = tag & 0x07;
}
if (*type == 0xff && *size == 0xffff) /* probably invalid data */
return -1;
return 0;
}
/*
* Skip specified number of bytes from stream.
*/
static void __init isapnp_skip_bytes(int count)
{
isapnp_peek(NULL, count);
}
/*
* Parse logical device tag.
*/
static struct pnp_dev *__init isapnp_parse_device(struct pnp_card *card,
int size, int number)
{
unsigned char tmp[6];
struct pnp_dev *dev;
u32 eisa_id;
char id[8];
isapnp_peek(tmp, size);
eisa_id = tmp[0] | tmp[1] << 8 | tmp[2] << 16 | tmp[3] << 24;
pnp_eisa_id_to_string(eisa_id, id);
dev = pnp_alloc_dev(&isapnp_protocol, number, id);
if (!dev)
return NULL;
dev->card = card;
dev->capabilities |= PNP_CONFIGURABLE;
dev->capabilities |= PNP_READ;
dev->capabilities |= PNP_WRITE;
dev->capabilities |= PNP_DISABLE;
pnp_init_resources(dev);
return dev;
}
/*
* Add IRQ resource to resources list.
*/
static void __init isapnp_parse_irq_resource(struct pnp_dev *dev,
unsigned int option_flags,
int size)
{
unsigned char tmp[3];
unsigned long bits;
pnp_irq_mask_t map;
unsigned char flags = IORESOURCE_IRQ_HIGHEDGE;
isapnp_peek(tmp, size);
bits = (tmp[1] << 8) | tmp[0];
bitmap_zero(map.bits, PNP_IRQ_NR);
bitmap_copy(map.bits, &bits, 16);
if (size > 2)
flags = tmp[2];
pnp_register_irq_resource(dev, option_flags, &map, flags);
}
/*
* Add DMA resource to resources list.
*/
static void __init isapnp_parse_dma_resource(struct pnp_dev *dev,
unsigned int option_flags,
int size)
{
unsigned char tmp[2];
isapnp_peek(tmp, size);
pnp_register_dma_resource(dev, option_flags, tmp[0], tmp[1]);
}
/*
* Add port resource to resources list.
*/
static void __init isapnp_parse_port_resource(struct pnp_dev *dev,
unsigned int option_flags,
int size)
{
unsigned char tmp[7];
resource_size_t min, max, align, len;
unsigned char flags;
isapnp_peek(tmp, size);
min = (tmp[2] << 8) | tmp[1];
max = (tmp[4] << 8) | tmp[3];
align = tmp[5];
len = tmp[6];
flags = tmp[0] ? IORESOURCE_IO_16BIT_ADDR : 0;
pnp_register_port_resource(dev, option_flags,
min, max, align, len, flags);
}
/*
* Add fixed port resource to resources list.
*/
static void __init isapnp_parse_fixed_port_resource(struct pnp_dev *dev,
unsigned int option_flags,
int size)
{
unsigned char tmp[3];
resource_size_t base, len;
isapnp_peek(tmp, size);
base = (tmp[1] << 8) | tmp[0];
len = tmp[2];
pnp_register_port_resource(dev, option_flags, base, base, 0, len,
IORESOURCE_IO_FIXED);
}
/*
* Add memory resource to resources list.
*/
static void __init isapnp_parse_mem_resource(struct pnp_dev *dev,
unsigned int option_flags,
int size)
{
unsigned char tmp[9];
resource_size_t min, max, align, len;
unsigned char flags;
isapnp_peek(tmp, size);
min = ((tmp[2] << 8) | tmp[1]) << 8;
max = ((tmp[4] << 8) | tmp[3]) << 8;
align = (tmp[6] << 8) | tmp[5];
len = ((tmp[8] << 8) | tmp[7]) << 8;
flags = tmp[0];
pnp_register_mem_resource(dev, option_flags,
min, max, align, len, flags);
}
/*
* Add 32-bit memory resource to resources list.
*/
static void __init isapnp_parse_mem32_resource(struct pnp_dev *dev,
unsigned int option_flags,
int size)
{
unsigned char tmp[17];
resource_size_t min, max, align, len;
unsigned char flags;
isapnp_peek(tmp, size);
min = (tmp[4] << 24) | (tmp[3] << 16) | (tmp[2] << 8) | tmp[1];
max = (tmp[8] << 24) | (tmp[7] << 16) | (tmp[6] << 8) | tmp[5];
align = (tmp[12] << 24) | (tmp[11] << 16) | (tmp[10] << 8) | tmp[9];
len = (tmp[16] << 24) | (tmp[15] << 16) | (tmp[14] << 8) | tmp[13];
flags = tmp[0];
pnp_register_mem_resource(dev, option_flags,
min, max, align, len, flags);
}
/*
* Add 32-bit fixed memory resource to resources list.
*/
static void __init isapnp_parse_fixed_mem32_resource(struct pnp_dev *dev,
unsigned int option_flags,
int size)
{
unsigned char tmp[9];
resource_size_t base, len;
unsigned char flags;
isapnp_peek(tmp, size);
base = (tmp[4] << 24) | (tmp[3] << 16) | (tmp[2] << 8) | tmp[1];
len = (tmp[8] << 24) | (tmp[7] << 16) | (tmp[6] << 8) | tmp[5];
flags = tmp[0];
pnp_register_mem_resource(dev, option_flags, base, base, 0, len, flags);
}
/*
* Parse card name for ISA PnP device.
*/
static void __init
isapnp_parse_name(char *name, unsigned int name_max, unsigned short *size)
{
if (name[0] == '\0') {
unsigned short size1 =
*size >= name_max ? (name_max - 1) : *size;
isapnp_peek(name, size1);
name[size1] = '\0';
*size -= size1;
/* clean whitespace from end of string */
while (size1 > 0 && name[--size1] == ' ')
name[size1] = '\0';
}
}
/*
* Parse resource map for logical device.
*/
static int __init isapnp_create_device(struct pnp_card *card,
unsigned short size)
{
int number = 0, skip = 0, priority, compat = 0;
unsigned char type, tmp[17];
unsigned int option_flags;
struct pnp_dev *dev;
u32 eisa_id;
char id[8];
if ((dev = isapnp_parse_device(card, size, number++)) == NULL)
return 1;
option_flags = 0;
pnp_add_card_device(card, dev);
while (1) {
if (isapnp_read_tag(&type, &size) < 0)
return 1;
if (skip && type != _STAG_LOGDEVID && type != _STAG_END)
goto __skip;
switch (type) {
case _STAG_LOGDEVID:
if (size >= 5 && size <= 6) {
if ((dev =
isapnp_parse_device(card, size,
number++)) == NULL)
return 1;
size = 0;
skip = 0;
option_flags = 0;
pnp_add_card_device(card, dev);
} else {
skip = 1;
}
compat = 0;
break;
case _STAG_COMPATDEVID:
if (size == 4 && compat < DEVICE_COUNT_COMPATIBLE) {
isapnp_peek(tmp, 4);
eisa_id = tmp[0] | tmp[1] << 8 |
tmp[2] << 16 | tmp[3] << 24;
pnp_eisa_id_to_string(eisa_id, id);
pnp_add_id(dev, id);
compat++;
size = 0;
}
break;
case _STAG_IRQ:
if (size < 2 || size > 3)
goto __skip;
isapnp_parse_irq_resource(dev, option_flags, size);
size = 0;
break;
case _STAG_DMA:
if (size != 2)
goto __skip;
isapnp_parse_dma_resource(dev, option_flags, size);
size = 0;
break;
case _STAG_STARTDEP:
if (size > 1)
goto __skip;
priority = PNP_RES_PRIORITY_ACCEPTABLE;
if (size > 0) {
isapnp_peek(tmp, size);
priority = tmp[0];
size = 0;
}
option_flags = pnp_new_dependent_set(dev, priority);
break;
case _STAG_ENDDEP:
if (size != 0)
goto __skip;
option_flags = 0;
break;
case _STAG_IOPORT:
if (size != 7)
goto __skip;
isapnp_parse_port_resource(dev, option_flags, size);
size = 0;
break;
case _STAG_FIXEDIO:
if (size != 3)
goto __skip;
isapnp_parse_fixed_port_resource(dev, option_flags,
size);
size = 0;
break;
case _STAG_VENDOR:
break;
case _LTAG_MEMRANGE:
if (size != 9)
goto __skip;
isapnp_parse_mem_resource(dev, option_flags, size);
size = 0;
break;
case _LTAG_ANSISTR:
isapnp_parse_name(dev->name, sizeof(dev->name), &size);
break;
case _LTAG_UNICODESTR:
/* silently ignore */
/* who use unicode for hardware identification? */
break;
case _LTAG_VENDOR:
break;
case _LTAG_MEM32RANGE:
if (size != 17)
goto __skip;
isapnp_parse_mem32_resource(dev, option_flags, size);
size = 0;
break;
case _LTAG_FIXEDMEM32RANGE:
if (size != 9)
goto __skip;
isapnp_parse_fixed_mem32_resource(dev, option_flags,
size);
size = 0;
break;
case _STAG_END:
if (size > 0)
isapnp_skip_bytes(size);
return 1;
default:
dev_err(&dev->dev, "unknown tag %#x (card %i), "
"ignored\n", type, card->number);
}
__skip:
if (size > 0)
isapnp_skip_bytes(size);
}
return 0;
}
/*
* Parse resource map for ISA PnP card.
*/
static void __init isapnp_parse_resource_map(struct pnp_card *card)
{
unsigned char type, tmp[17];
unsigned short size;
while (1) {
if (isapnp_read_tag(&type, &size) < 0)
return;
switch (type) {
case _STAG_PNPVERNO:
if (size != 2)
goto __skip;
isapnp_peek(tmp, 2);
card->pnpver = tmp[0];
card->productver = tmp[1];
size = 0;
break;
case _STAG_LOGDEVID:
if (size >= 5 && size <= 6) {
if (isapnp_create_device(card, size) == 1)
return;
size = 0;
}
break;
case _STAG_VENDOR:
break;
case _LTAG_ANSISTR:
isapnp_parse_name(card->name, sizeof(card->name),
&size);
break;
case _LTAG_UNICODESTR:
/* silently ignore */
/* who use unicode for hardware identification? */
break;
case _LTAG_VENDOR:
break;
case _STAG_END:
if (size > 0)
isapnp_skip_bytes(size);
return;
default:
dev_err(&card->dev, "unknown tag %#x, ignored\n",
type);
}
__skip:
if (size > 0)
isapnp_skip_bytes(size);
}
}
/*
* Compute ISA PnP checksum for first eight bytes.
*/
static unsigned char __init isapnp_checksum(unsigned char *data)
{
int i, j;
unsigned char checksum = 0x6a, bit, b;
for (i = 0; i < 8; i++) {
b = data[i];
for (j = 0; j < 8; j++) {
bit = 0;
if (b & (1 << j))
bit = 1;
checksum =
((((checksum ^ (checksum >> 1)) & 0x01) ^ bit) << 7)
| (checksum >> 1);
}
}
return checksum;
}
/*
* Build device list for all present ISA PnP devices.
*/
static int __init isapnp_build_device_list(void)
{
int csn;
unsigned char header[9], checksum;
struct pnp_card *card;
u32 eisa_id;
char id[8];
isapnp_wait();
isapnp_key();
for (csn = 1; csn <= isapnp_csn_count; csn++) {
isapnp_wake(csn);
isapnp_peek(header, 9);
checksum = isapnp_checksum(header);
eisa_id = header[0] | header[1] << 8 |
header[2] << 16 | header[3] << 24;
pnp_eisa_id_to_string(eisa_id, id);
card = pnp_alloc_card(&isapnp_protocol, csn, id);
if (!card)
continue;
INIT_LIST_HEAD(&card->devices);
card->serial =
(header[7] << 24) | (header[6] << 16) | (header[5] << 8) |
header[4];
isapnp_checksum_value = 0x00;
isapnp_parse_resource_map(card);
if (isapnp_checksum_value != 0x00)
dev_err(&card->dev, "invalid checksum %#x\n",
isapnp_checksum_value);
card->checksum = isapnp_checksum_value;
pnp_add_card(card);
}
isapnp_wait();
return 0;
}
/*
* Basic configuration routines.
*/
int isapnp_present(void)
{
struct pnp_card *card;
pnp_for_each_card(card) {
if (card->protocol == &isapnp_protocol)
return 1;
}
return 0;
}
int isapnp_cfg_begin(int csn, int logdev)
{
if (csn < 1 || csn > isapnp_csn_count || logdev > 10)
return -EINVAL;
mutex_lock(&isapnp_cfg_mutex);
isapnp_wait();
isapnp_key();
isapnp_wake(csn);
#if 0
/* to avoid malfunction when the isapnptools package is used */
/* we must set RDP to our value again */
/* it is possible to set RDP only in the isolation phase */
/* Jens Thoms Toerring <Jens.Toerring@physik.fu-berlin.de> */
isapnp_write_byte(0x02, 0x04); /* clear CSN of card */
mdelay(2); /* is this necessary? */
isapnp_wake(csn); /* bring card into sleep state */
isapnp_wake(0); /* bring card into isolation state */
isapnp_set_rdp(); /* reset the RDP port */
udelay(1000); /* delay 1000us */
isapnp_write_byte(0x06, csn); /* reset CSN to previous value */
udelay(250); /* is this necessary? */
#endif
if (logdev >= 0)
isapnp_device(logdev);
return 0;
}
int isapnp_cfg_end(void)
{
isapnp_wait();
mutex_unlock(&isapnp_cfg_mutex);
return 0;
}
/*
* Initialization.
*/
EXPORT_SYMBOL(isapnp_protocol);
EXPORT_SYMBOL(isapnp_present);
EXPORT_SYMBOL(isapnp_cfg_begin);
EXPORT_SYMBOL(isapnp_cfg_end);
EXPORT_SYMBOL(isapnp_write_byte);
static int isapnp_get_resources(struct pnp_dev *dev)
{
int i, ret;
pnp_dbg(&dev->dev, "get resources\n");
pnp_init_resources(dev);
isapnp_cfg_begin(dev->card->number, dev->number);
dev->active = isapnp_read_byte(ISAPNP_CFG_ACTIVATE);
if (!dev->active)
goto __end;
for (i = 0; i < ISAPNP_MAX_PORT; i++) {
ret = isapnp_read_word(ISAPNP_CFG_PORT + (i << 1));
pnp_add_io_resource(dev, ret, ret,
ret == 0 ? IORESOURCE_DISABLED : 0);
}
for (i = 0; i < ISAPNP_MAX_MEM; i++) {
ret = isapnp_read_word(ISAPNP_CFG_MEM + (i << 3)) << 8;
pnp_add_mem_resource(dev, ret, ret,
ret == 0 ? IORESOURCE_DISABLED : 0);
}
for (i = 0; i < ISAPNP_MAX_IRQ; i++) {
ret = isapnp_read_word(ISAPNP_CFG_IRQ + (i << 1)) >> 8;
pnp_add_irq_resource(dev, ret,
ret == 0 ? IORESOURCE_DISABLED : 0);
}
for (i = 0; i < ISAPNP_MAX_DMA; i++) {
ret = isapnp_read_byte(ISAPNP_CFG_DMA + i);
pnp_add_dma_resource(dev, ret,
ret == 4 ? IORESOURCE_DISABLED : 0);
}
__end:
isapnp_cfg_end();
return 0;
}
static int isapnp_set_resources(struct pnp_dev *dev)
{
struct resource *res;
int tmp;
pnp_dbg(&dev->dev, "set resources\n");
isapnp_cfg_begin(dev->card->number, dev->number);
dev->active = 1;
for (tmp = 0; tmp < ISAPNP_MAX_PORT; tmp++) {
res = pnp_get_resource(dev, IORESOURCE_IO, tmp);
if (pnp_resource_enabled(res)) {
pnp_dbg(&dev->dev, " set io %d to %#llx\n",
tmp, (unsigned long long) res->start);
isapnp_write_word(ISAPNP_CFG_PORT + (tmp << 1),
res->start);
}
}
for (tmp = 0; tmp < ISAPNP_MAX_IRQ; tmp++) {
res = pnp_get_resource(dev, IORESOURCE_IRQ, tmp);
if (pnp_resource_enabled(res)) {
int irq = res->start;
if (irq == 2)
irq = 9;
pnp_dbg(&dev->dev, " set irq %d to %d\n", tmp, irq);
isapnp_write_byte(ISAPNP_CFG_IRQ + (tmp << 1), irq);
}
}
for (tmp = 0; tmp < ISAPNP_MAX_DMA; tmp++) {
res = pnp_get_resource(dev, IORESOURCE_DMA, tmp);
if (pnp_resource_enabled(res)) {
pnp_dbg(&dev->dev, " set dma %d to %lld\n",
tmp, (unsigned long long) res->start);
isapnp_write_byte(ISAPNP_CFG_DMA + tmp, res->start);
}
}
for (tmp = 0; tmp < ISAPNP_MAX_MEM; tmp++) {
res = pnp_get_resource(dev, IORESOURCE_MEM, tmp);
if (pnp_resource_enabled(res)) {
pnp_dbg(&dev->dev, " set mem %d to %#llx\n",
tmp, (unsigned long long) res->start);
isapnp_write_word(ISAPNP_CFG_MEM + (tmp << 3),
(res->start >> 8) & 0xffff);
}
}
/* FIXME: We aren't handling 32bit mems properly here */
isapnp_activate(dev->number);
isapnp_cfg_end();
return 0;
}
static int isapnp_disable_resources(struct pnp_dev *dev)
{
if (!dev->active)
return -EINVAL;
isapnp_cfg_begin(dev->card->number, dev->number);
isapnp_deactivate(dev->number);
dev->active = 0;
isapnp_cfg_end();
return 0;
}
struct pnp_protocol isapnp_protocol = {
.name = "ISA Plug and Play",
.get = isapnp_get_resources,
.set = isapnp_set_resources,
.disable = isapnp_disable_resources,
};
static int __init isapnp_init(void)
{
int cards;
struct pnp_card *card;
struct pnp_dev *dev;
if (isapnp_disable) {
printk(KERN_INFO "isapnp: ISA Plug & Play support disabled\n");
return 0;
}
#ifdef CONFIG_PPC
if (check_legacy_ioport(_PIDXR) || check_legacy_ioport(_PNPWRP))
return -EINVAL;
#endif
#ifdef ISAPNP_REGION_OK
if (!request_region(_PIDXR, 1, "isapnp index")) {
printk(KERN_ERR "isapnp: Index Register 0x%x already used\n",
_PIDXR);
return -EBUSY;
}
#endif
if (!request_region(_PNPWRP, 1, "isapnp write")) {
printk(KERN_ERR
"isapnp: Write Data Register 0x%x already used\n",
_PNPWRP);
#ifdef ISAPNP_REGION_OK
release_region(_PIDXR, 1);
#endif
return -EBUSY;
}
if (pnp_register_protocol(&isapnp_protocol) < 0)
return -EBUSY;
/*
* Print a message. The existing ISAPnP code is hanging machines
* so let the user know where.
*/
printk(KERN_INFO "isapnp: Scanning for PnP cards...\n");
if (isapnp_rdp >= 0x203 && isapnp_rdp <= 0x3ff) {
isapnp_rdp |= 3;
if (!request_region(isapnp_rdp, 1, "isapnp read")) {
printk(KERN_ERR
"isapnp: Read Data Register 0x%x already used\n",
isapnp_rdp);
#ifdef ISAPNP_REGION_OK
release_region(_PIDXR, 1);
#endif
release_region(_PNPWRP, 1);
return -EBUSY;
}
isapnp_set_rdp();
}
if (isapnp_rdp < 0x203 || isapnp_rdp > 0x3ff) {
cards = isapnp_isolate();
if (cards < 0 || (isapnp_rdp < 0x203 || isapnp_rdp > 0x3ff)) {
#ifdef ISAPNP_REGION_OK
release_region(_PIDXR, 1);
#endif
release_region(_PNPWRP, 1);
printk(KERN_INFO
"isapnp: No Plug & Play device found\n");
return 0;
}
request_region(isapnp_rdp, 1, "isapnp read");
}
isapnp_build_device_list();
cards = 0;
protocol_for_each_card(&isapnp_protocol, card) {
cards++;
if (isapnp_verbose) {
dev_info(&card->dev, "card '%s'\n",
card->name[0] ? card->name : "unknown");
if (isapnp_verbose < 2)
continue;
card_for_each_dev(card, dev) {
dev_info(&card->dev, "device '%s'\n",
dev->name[0] ? dev->name : "unknown");
}
}
}
if (cards)
printk(KERN_INFO
"isapnp: %i Plug & Play card%s detected total\n", cards,
cards > 1 ? "s" : "");
else
printk(KERN_INFO "isapnp: No Plug & Play card found\n");
isapnp_proc_init();
return 0;
}
device_initcall(isapnp_init);
/* format is: noisapnp */
static int __init isapnp_setup_disable(char *str)
{
isapnp_disable = 1;
return 1;
}
__setup("noisapnp", isapnp_setup_disable);
/* format is: isapnp=rdp,reset,skip_pci_scan,verbose */
static int __init isapnp_setup_isapnp(char *str)
{
(void)((get_option(&str, &isapnp_rdp) == 2) &&
(get_option(&str, &isapnp_reset) == 2) &&
(get_option(&str, &isapnp_verbose) == 2));
return 1;
}
__setup("isapnp=", isapnp_setup_isapnp);
| gpl-2.0 |
Tekcafe/Kernel-LTE3-KK | arch/arm/mach-kirkwood/ts41x-setup.c | 4962 | 4602 | /*
*
* QNAP TS-410, TS-410U, TS-419P and TS-419U Turbo NAS Board Setup
*
* Copyright (C) 2009-2010 Martin Michlmayr <tbm@cyrius.com>
* Copyright (C) 2008 Byron Bradley <byron.bbradley@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/i2c.h>
#include <linux/mv643xx_eth.h>
#include <linux/ata_platform.h>
#include <linux/gpio.h>
#include <linux/gpio_keys.h>
#include <linux/input.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <mach/kirkwood.h>
#include "common.h"
#include "mpp.h"
#include "tsx1x-common.h"
/* for the PCIe reset workaround */
#include <plat/pcie.h>
#define QNAP_TS41X_JUMPER_JP1 45
static struct i2c_board_info __initdata qnap_ts41x_i2c_rtc = {
I2C_BOARD_INFO("s35390a", 0x30),
};
static struct mv643xx_eth_platform_data qnap_ts41x_ge00_data = {
.phy_addr = MV643XX_ETH_PHY_ADDR(8),
};
static struct mv643xx_eth_platform_data qnap_ts41x_ge01_data = {
.phy_addr = MV643XX_ETH_PHY_ADDR(0),
};
static struct mv_sata_platform_data qnap_ts41x_sata_data = {
.n_ports = 2,
};
static struct gpio_keys_button qnap_ts41x_buttons[] = {
{
.code = KEY_COPY,
.gpio = 43,
.desc = "USB Copy",
.active_low = 1,
},
{
.code = KEY_RESTART,
.gpio = 37,
.desc = "Reset",
.active_low = 1,
},
};
static struct gpio_keys_platform_data qnap_ts41x_button_data = {
.buttons = qnap_ts41x_buttons,
.nbuttons = ARRAY_SIZE(qnap_ts41x_buttons),
};
static struct platform_device qnap_ts41x_button_device = {
.name = "gpio-keys",
.id = -1,
.num_resources = 0,
.dev = {
.platform_data = &qnap_ts41x_button_data,
}
};
static unsigned int qnap_ts41x_mpp_config[] __initdata = {
MPP0_SPI_SCn,
MPP1_SPI_MOSI,
MPP2_SPI_SCK,
MPP3_SPI_MISO,
MPP6_SYSRST_OUTn,
MPP7_PEX_RST_OUTn,
MPP8_TW0_SDA,
MPP9_TW0_SCK,
MPP10_UART0_TXD,
MPP11_UART0_RXD,
MPP13_UART1_TXD, /* PIC controller */
MPP14_UART1_RXD, /* PIC controller */
MPP15_SATA0_ACTn,
MPP16_SATA1_ACTn,
MPP20_GE1_TXD0,
MPP21_GE1_TXD1,
MPP22_GE1_TXD2,
MPP23_GE1_TXD3,
MPP24_GE1_RXD0,
MPP25_GE1_RXD1,
MPP26_GE1_RXD2,
MPP27_GE1_RXD3,
MPP30_GE1_RXCTL,
MPP31_GE1_RXCLK,
MPP32_GE1_TCLKOUT,
MPP33_GE1_TXCTL,
MPP36_GPIO, /* RAM: 0: 256 MB, 1: 512 MB */
MPP37_GPIO, /* Reset button */
MPP43_GPIO, /* USB Copy button */
MPP44_GPIO, /* Board ID: 0: TS-419U, 1: TS-419 */
MPP45_GPIO, /* JP1: 0: LCD, 1: serial console */
MPP46_GPIO, /* External SATA HDD1 error indicator */
MPP47_GPIO, /* External SATA HDD2 error indicator */
MPP48_GPIO, /* External SATA HDD3 error indicator */
MPP49_GPIO, /* External SATA HDD4 error indicator */
0
};
static void __init qnap_ts41x_init(void)
{
u32 dev, rev;
/*
* Basic setup. Needs to be called early.
*/
kirkwood_init();
kirkwood_mpp_conf(qnap_ts41x_mpp_config);
kirkwood_uart0_init();
kirkwood_uart1_init(); /* A PIC controller is connected here. */
qnap_tsx1x_register_flash();
kirkwood_i2c_init();
i2c_register_board_info(0, &qnap_ts41x_i2c_rtc, 1);
kirkwood_pcie_id(&dev, &rev);
if (dev == MV88F6282_DEV_ID) {
qnap_ts41x_ge00_data.phy_addr = MV643XX_ETH_PHY_ADDR(0);
qnap_ts41x_ge01_data.phy_addr = MV643XX_ETH_PHY_ADDR(1);
}
kirkwood_ge00_init(&qnap_ts41x_ge00_data);
kirkwood_ge01_init(&qnap_ts41x_ge01_data);
kirkwood_sata_init(&qnap_ts41x_sata_data);
kirkwood_ehci_init();
platform_device_register(&qnap_ts41x_button_device);
pm_power_off = qnap_tsx1x_power_off;
if (gpio_request(QNAP_TS41X_JUMPER_JP1, "JP1") == 0)
gpio_export(QNAP_TS41X_JUMPER_JP1, 0);
}
static int __init ts41x_pci_init(void)
{
if (machine_is_ts41x()) {
u32 dev, rev;
/*
* Without this explicit reset, the PCIe SATA controller
* (Marvell 88sx7042/sata_mv) is known to stop working
* after a few minutes.
*/
orion_pcie_reset((void __iomem *)PCIE_VIRT_BASE);
kirkwood_pcie_id(&dev, &rev);
if (dev == MV88F6282_DEV_ID)
kirkwood_pcie_init(KW_PCIE1 | KW_PCIE0);
else
kirkwood_pcie_init(KW_PCIE0);
}
return 0;
}
subsys_initcall(ts41x_pci_init);
MACHINE_START(TS41X, "QNAP TS-41x")
/* Maintainer: Martin Michlmayr <tbm@cyrius.com> */
.atag_offset = 0x100,
.init_machine = qnap_ts41x_init,
.map_io = kirkwood_map_io,
.init_early = kirkwood_init_early,
.init_irq = kirkwood_init_irq,
.timer = &kirkwood_timer,
.restart = kirkwood_restart,
MACHINE_END
| gpl-2.0 |
Fred6681/android_kernel_samsung_golden | arch/um/kernel/skas/process.c | 4962 | 1541 | /*
* Copyright (C) 2002 - 2007 Jeff Dike (jdike@{addtoit,linux.intel}.com)
* Licensed under the GPL
*/
#include "linux/init.h"
#include "linux/sched.h"
#include "as-layout.h"
#include "kern.h"
#include "os.h"
#include "skas.h"
int new_mm(unsigned long stack)
{
int fd, err;
fd = os_open_file("/proc/mm", of_cloexec(of_write(OPENFLAGS())), 0);
if (fd < 0)
return fd;
if (skas_needs_stub) {
err = map_stub_pages(fd, STUB_CODE, STUB_DATA, stack);
if (err) {
os_close_file(fd);
return err;
}
}
return fd;
}
extern void start_kernel(void);
static int __init start_kernel_proc(void *unused)
{
int pid;
block_signals();
pid = os_getpid();
cpu_tasks[0].pid = pid;
cpu_tasks[0].task = current;
#ifdef CONFIG_SMP
cpu_online_map = cpumask_of_cpu(0);
#endif
start_kernel();
return 0;
}
extern int userspace_pid[];
extern char cpu0_irqstack[];
int __init start_uml(void)
{
stack_protections((unsigned long) &cpu0_irqstack);
set_sigstack(cpu0_irqstack, THREAD_SIZE);
if (proc_mm) {
userspace_pid[0] = start_userspace(0);
if (userspace_pid[0] < 0) {
printf("start_uml - start_userspace returned %d\n",
userspace_pid[0]);
exit(1);
}
}
init_new_thread_signals();
init_task.thread.request.u.thread.proc = start_kernel_proc;
init_task.thread.request.u.thread.arg = NULL;
return start_idle_thread(task_stack_page(&init_task),
&init_task.thread.switch_buf);
}
unsigned long current_stub_stack(void)
{
if (current->mm == NULL)
return 0;
return current->mm->context.id.stack;
}
| gpl-2.0 |
Validus-Lollipop/android_kernel_motorola_msm8960dt-common | arch/mips/ar7/setup.c | 7010 | 2680 | /*
* Carsten Langgaard, carstenl@mips.com
* Copyright (C) 2000 MIPS Technologies, Inc. All rights reserved.
*
* This program is free software; you can distribute it and/or modify it
* under the terms of the GNU General Public License (Version 2) as
* published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston MA 02111-1307, USA.
*/
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/pm.h>
#include <linux/time.h>
#include <asm/reboot.h>
#include <asm/mach-ar7/ar7.h>
#include <asm/mach-ar7/prom.h>
#include <asm/mach-ar7/gpio.h>
static void ar7_machine_restart(char *command)
{
u32 *softres_reg = ioremap(AR7_REGS_RESET + AR7_RESET_SOFTWARE, 1);
writel(1, softres_reg);
}
static void ar7_machine_halt(void)
{
while (1)
;
}
static void ar7_machine_power_off(void)
{
u32 *power_reg = (u32 *)ioremap(AR7_REGS_POWER, 1);
u32 power_state = readl(power_reg) | (3 << 30);
writel(power_state, power_reg);
ar7_machine_halt();
}
const char *get_system_type(void)
{
u16 chip_id = ar7_chip_id();
u16 titan_variant_id = titan_chip_id();
switch (chip_id) {
case AR7_CHIP_7100:
return "TI AR7 (TNETD7100)";
case AR7_CHIP_7200:
return "TI AR7 (TNETD7200)";
case AR7_CHIP_7300:
return "TI AR7 (TNETD7300)";
case AR7_CHIP_TITAN:
switch (titan_variant_id) {
case TITAN_CHIP_1050:
return "TI AR7 (TNETV1050)";
case TITAN_CHIP_1055:
return "TI AR7 (TNETV1055)";
case TITAN_CHIP_1056:
return "TI AR7 (TNETV1056)";
case TITAN_CHIP_1060:
return "TI AR7 (TNETV1060)";
}
default:
return "TI AR7 (unknown)";
}
}
static int __init ar7_init_console(void)
{
return 0;
}
console_initcall(ar7_init_console);
/*
* Initializes basic routines and structures pointers, memory size (as
* given by the bios and saves the command line.
*/
void __init plat_mem_setup(void)
{
unsigned long io_base;
_machine_restart = ar7_machine_restart;
_machine_halt = ar7_machine_halt;
pm_power_off = ar7_machine_power_off;
panic_timeout = 3;
io_base = (unsigned long)ioremap(AR7_REGS_BASE, 0x10000);
if (!io_base)
panic("Can't remap IO base!");
set_io_port_base(io_base);
prom_meminit();
printk(KERN_INFO "%s, ID: 0x%04x, Revision: 0x%02x\n",
get_system_type(), ar7_chip_id(), ar7_chip_rev());
}
| gpl-2.0 |
Red--Code/Code-Red-honami | drivers/s390/scsi/zfcp_fc.c | 8034 | 26785 | /*
* zfcp device driver
*
* Fibre Channel related functions for the zfcp device driver.
*
* Copyright IBM Corporation 2008, 2010
*/
#define KMSG_COMPONENT "zfcp"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/utsname.h>
#include <scsi/fc/fc_els.h>
#include <scsi/libfc.h>
#include "zfcp_ext.h"
#include "zfcp_fc.h"
struct kmem_cache *zfcp_fc_req_cache;
static u32 zfcp_fc_rscn_range_mask[] = {
[ELS_ADDR_FMT_PORT] = 0xFFFFFF,
[ELS_ADDR_FMT_AREA] = 0xFFFF00,
[ELS_ADDR_FMT_DOM] = 0xFF0000,
[ELS_ADDR_FMT_FAB] = 0x000000,
};
/**
* zfcp_fc_post_event - post event to userspace via fc_transport
* @work: work struct with enqueued events
*/
void zfcp_fc_post_event(struct work_struct *work)
{
struct zfcp_fc_event *event = NULL, *tmp = NULL;
LIST_HEAD(tmp_lh);
struct zfcp_fc_events *events = container_of(work,
struct zfcp_fc_events, work);
struct zfcp_adapter *adapter = container_of(events, struct zfcp_adapter,
events);
spin_lock_bh(&events->list_lock);
list_splice_init(&events->list, &tmp_lh);
spin_unlock_bh(&events->list_lock);
list_for_each_entry_safe(event, tmp, &tmp_lh, list) {
fc_host_post_event(adapter->scsi_host, fc_get_event_number(),
event->code, event->data);
list_del(&event->list);
kfree(event);
}
}
/**
* zfcp_fc_enqueue_event - safely enqueue FC HBA API event from irq context
* @adapter: The adapter where to enqueue the event
* @event_code: The event code (as defined in fc_host_event_code in
* scsi_transport_fc.h)
* @event_data: The event data (e.g. n_port page in case of els)
*/
void zfcp_fc_enqueue_event(struct zfcp_adapter *adapter,
enum fc_host_event_code event_code, u32 event_data)
{
struct zfcp_fc_event *event;
event = kmalloc(sizeof(struct zfcp_fc_event), GFP_ATOMIC);
if (!event)
return;
event->code = event_code;
event->data = event_data;
spin_lock(&adapter->events.list_lock);
list_add_tail(&event->list, &adapter->events.list);
spin_unlock(&adapter->events.list_lock);
queue_work(adapter->work_queue, &adapter->events.work);
}
static int zfcp_fc_wka_port_get(struct zfcp_fc_wka_port *wka_port)
{
if (mutex_lock_interruptible(&wka_port->mutex))
return -ERESTARTSYS;
if (wka_port->status == ZFCP_FC_WKA_PORT_OFFLINE ||
wka_port->status == ZFCP_FC_WKA_PORT_CLOSING) {
wka_port->status = ZFCP_FC_WKA_PORT_OPENING;
if (zfcp_fsf_open_wka_port(wka_port))
wka_port->status = ZFCP_FC_WKA_PORT_OFFLINE;
}
mutex_unlock(&wka_port->mutex);
wait_event(wka_port->completion_wq,
wka_port->status == ZFCP_FC_WKA_PORT_ONLINE ||
wka_port->status == ZFCP_FC_WKA_PORT_OFFLINE);
if (wka_port->status == ZFCP_FC_WKA_PORT_ONLINE) {
atomic_inc(&wka_port->refcount);
return 0;
}
return -EIO;
}
static void zfcp_fc_wka_port_offline(struct work_struct *work)
{
struct delayed_work *dw = to_delayed_work(work);
struct zfcp_fc_wka_port *wka_port =
container_of(dw, struct zfcp_fc_wka_port, work);
mutex_lock(&wka_port->mutex);
if ((atomic_read(&wka_port->refcount) != 0) ||
(wka_port->status != ZFCP_FC_WKA_PORT_ONLINE))
goto out;
wka_port->status = ZFCP_FC_WKA_PORT_CLOSING;
if (zfcp_fsf_close_wka_port(wka_port)) {
wka_port->status = ZFCP_FC_WKA_PORT_OFFLINE;
wake_up(&wka_port->completion_wq);
}
out:
mutex_unlock(&wka_port->mutex);
}
static void zfcp_fc_wka_port_put(struct zfcp_fc_wka_port *wka_port)
{
if (atomic_dec_return(&wka_port->refcount) != 0)
return;
/* wait 10 milliseconds, other reqs might pop in */
schedule_delayed_work(&wka_port->work, HZ / 100);
}
static void zfcp_fc_wka_port_init(struct zfcp_fc_wka_port *wka_port, u32 d_id,
struct zfcp_adapter *adapter)
{
init_waitqueue_head(&wka_port->completion_wq);
wka_port->adapter = adapter;
wka_port->d_id = d_id;
wka_port->status = ZFCP_FC_WKA_PORT_OFFLINE;
atomic_set(&wka_port->refcount, 0);
mutex_init(&wka_port->mutex);
INIT_DELAYED_WORK(&wka_port->work, zfcp_fc_wka_port_offline);
}
static void zfcp_fc_wka_port_force_offline(struct zfcp_fc_wka_port *wka)
{
cancel_delayed_work_sync(&wka->work);
mutex_lock(&wka->mutex);
wka->status = ZFCP_FC_WKA_PORT_OFFLINE;
mutex_unlock(&wka->mutex);
}
void zfcp_fc_wka_ports_force_offline(struct zfcp_fc_wka_ports *gs)
{
if (!gs)
return;
zfcp_fc_wka_port_force_offline(&gs->ms);
zfcp_fc_wka_port_force_offline(&gs->ts);
zfcp_fc_wka_port_force_offline(&gs->ds);
zfcp_fc_wka_port_force_offline(&gs->as);
}
static void _zfcp_fc_incoming_rscn(struct zfcp_fsf_req *fsf_req, u32 range,
struct fc_els_rscn_page *page)
{
unsigned long flags;
struct zfcp_adapter *adapter = fsf_req->adapter;
struct zfcp_port *port;
read_lock_irqsave(&adapter->port_list_lock, flags);
list_for_each_entry(port, &adapter->port_list, list) {
if ((port->d_id & range) == (ntoh24(page->rscn_fid) & range))
zfcp_fc_test_link(port);
if (!port->d_id)
zfcp_erp_port_reopen(port,
ZFCP_STATUS_COMMON_ERP_FAILED,
"fcrscn1");
}
read_unlock_irqrestore(&adapter->port_list_lock, flags);
}
static void zfcp_fc_incoming_rscn(struct zfcp_fsf_req *fsf_req)
{
struct fsf_status_read_buffer *status_buffer = (void *)fsf_req->data;
struct fc_els_rscn *head;
struct fc_els_rscn_page *page;
u16 i;
u16 no_entries;
unsigned int afmt;
head = (struct fc_els_rscn *) status_buffer->payload.data;
page = (struct fc_els_rscn_page *) head;
/* see FC-FS */
no_entries = head->rscn_plen / sizeof(struct fc_els_rscn_page);
for (i = 1; i < no_entries; i++) {
/* skip head and start with 1st element */
page++;
afmt = page->rscn_page_flags & ELS_RSCN_ADDR_FMT_MASK;
_zfcp_fc_incoming_rscn(fsf_req, zfcp_fc_rscn_range_mask[afmt],
page);
zfcp_fc_enqueue_event(fsf_req->adapter, FCH_EVT_RSCN,
*(u32 *)page);
}
queue_work(fsf_req->adapter->work_queue, &fsf_req->adapter->scan_work);
}
static void zfcp_fc_incoming_wwpn(struct zfcp_fsf_req *req, u64 wwpn)
{
unsigned long flags;
struct zfcp_adapter *adapter = req->adapter;
struct zfcp_port *port;
read_lock_irqsave(&adapter->port_list_lock, flags);
list_for_each_entry(port, &adapter->port_list, list)
if (port->wwpn == wwpn) {
zfcp_erp_port_forced_reopen(port, 0, "fciwwp1");
break;
}
read_unlock_irqrestore(&adapter->port_list_lock, flags);
}
static void zfcp_fc_incoming_plogi(struct zfcp_fsf_req *req)
{
struct fsf_status_read_buffer *status_buffer;
struct fc_els_flogi *plogi;
status_buffer = (struct fsf_status_read_buffer *) req->data;
plogi = (struct fc_els_flogi *) status_buffer->payload.data;
zfcp_fc_incoming_wwpn(req, plogi->fl_wwpn);
}
static void zfcp_fc_incoming_logo(struct zfcp_fsf_req *req)
{
struct fsf_status_read_buffer *status_buffer =
(struct fsf_status_read_buffer *)req->data;
struct fc_els_logo *logo =
(struct fc_els_logo *) status_buffer->payload.data;
zfcp_fc_incoming_wwpn(req, logo->fl_n_port_wwn);
}
/**
* zfcp_fc_incoming_els - handle incoming ELS
* @fsf_req - request which contains incoming ELS
*/
void zfcp_fc_incoming_els(struct zfcp_fsf_req *fsf_req)
{
struct fsf_status_read_buffer *status_buffer =
(struct fsf_status_read_buffer *) fsf_req->data;
unsigned int els_type = status_buffer->payload.data[0];
zfcp_dbf_san_in_els("fciels1", fsf_req);
if (els_type == ELS_PLOGI)
zfcp_fc_incoming_plogi(fsf_req);
else if (els_type == ELS_LOGO)
zfcp_fc_incoming_logo(fsf_req);
else if (els_type == ELS_RSCN)
zfcp_fc_incoming_rscn(fsf_req);
}
static void zfcp_fc_ns_gid_pn_eval(struct zfcp_fc_req *fc_req)
{
struct zfcp_fsf_ct_els *ct_els = &fc_req->ct_els;
struct zfcp_fc_gid_pn_rsp *gid_pn_rsp = &fc_req->u.gid_pn.rsp;
if (ct_els->status)
return;
if (gid_pn_rsp->ct_hdr.ct_cmd != FC_FS_ACC)
return;
/* looks like a valid d_id */
ct_els->port->d_id = ntoh24(gid_pn_rsp->gid_pn.fp_fid);
}
static void zfcp_fc_complete(void *data)
{
complete(data);
}
static void zfcp_fc_ct_ns_init(struct fc_ct_hdr *ct_hdr, u16 cmd, u16 mr_size)
{
ct_hdr->ct_rev = FC_CT_REV;
ct_hdr->ct_fs_type = FC_FST_DIR;
ct_hdr->ct_fs_subtype = FC_NS_SUBTYPE;
ct_hdr->ct_cmd = cmd;
ct_hdr->ct_mr_size = mr_size / 4;
}
static int zfcp_fc_ns_gid_pn_request(struct zfcp_port *port,
struct zfcp_fc_req *fc_req)
{
struct zfcp_adapter *adapter = port->adapter;
DECLARE_COMPLETION_ONSTACK(completion);
struct zfcp_fc_gid_pn_req *gid_pn_req = &fc_req->u.gid_pn.req;
struct zfcp_fc_gid_pn_rsp *gid_pn_rsp = &fc_req->u.gid_pn.rsp;
int ret;
/* setup parameters for send generic command */
fc_req->ct_els.port = port;
fc_req->ct_els.handler = zfcp_fc_complete;
fc_req->ct_els.handler_data = &completion;
fc_req->ct_els.req = &fc_req->sg_req;
fc_req->ct_els.resp = &fc_req->sg_rsp;
sg_init_one(&fc_req->sg_req, gid_pn_req, sizeof(*gid_pn_req));
sg_init_one(&fc_req->sg_rsp, gid_pn_rsp, sizeof(*gid_pn_rsp));
zfcp_fc_ct_ns_init(&gid_pn_req->ct_hdr,
FC_NS_GID_PN, ZFCP_FC_CT_SIZE_PAGE);
gid_pn_req->gid_pn.fn_wwpn = port->wwpn;
ret = zfcp_fsf_send_ct(&adapter->gs->ds, &fc_req->ct_els,
adapter->pool.gid_pn_req,
ZFCP_FC_CTELS_TMO);
if (!ret) {
wait_for_completion(&completion);
zfcp_fc_ns_gid_pn_eval(fc_req);
}
return ret;
}
/**
* zfcp_fc_ns_gid_pn - initiate GID_PN nameserver request
* @port: port where GID_PN request is needed
* return: -ENOMEM on error, 0 otherwise
*/
static int zfcp_fc_ns_gid_pn(struct zfcp_port *port)
{
int ret;
struct zfcp_fc_req *fc_req;
struct zfcp_adapter *adapter = port->adapter;
fc_req = mempool_alloc(adapter->pool.gid_pn, GFP_ATOMIC);
if (!fc_req)
return -ENOMEM;
memset(fc_req, 0, sizeof(*fc_req));
ret = zfcp_fc_wka_port_get(&adapter->gs->ds);
if (ret)
goto out;
ret = zfcp_fc_ns_gid_pn_request(port, fc_req);
zfcp_fc_wka_port_put(&adapter->gs->ds);
out:
mempool_free(fc_req, adapter->pool.gid_pn);
return ret;
}
void zfcp_fc_port_did_lookup(struct work_struct *work)
{
int ret;
struct zfcp_port *port = container_of(work, struct zfcp_port,
gid_pn_work);
ret = zfcp_fc_ns_gid_pn(port);
if (ret) {
/* could not issue gid_pn for some reason */
zfcp_erp_adapter_reopen(port->adapter, 0, "fcgpn_1");
goto out;
}
if (!port->d_id) {
zfcp_erp_set_port_status(port, ZFCP_STATUS_COMMON_ERP_FAILED);
goto out;
}
zfcp_erp_port_reopen(port, 0, "fcgpn_3");
out:
put_device(&port->dev);
}
/**
* zfcp_fc_trigger_did_lookup - trigger the d_id lookup using a GID_PN request
* @port: The zfcp_port to lookup the d_id for.
*/
void zfcp_fc_trigger_did_lookup(struct zfcp_port *port)
{
get_device(&port->dev);
if (!queue_work(port->adapter->work_queue, &port->gid_pn_work))
put_device(&port->dev);
}
/**
* zfcp_fc_plogi_evaluate - evaluate PLOGI playload
* @port: zfcp_port structure
* @plogi: plogi payload
*
* Evaluate PLOGI playload and copy important fields into zfcp_port structure
*/
void zfcp_fc_plogi_evaluate(struct zfcp_port *port, struct fc_els_flogi *plogi)
{
if (plogi->fl_wwpn != port->wwpn) {
port->d_id = 0;
dev_warn(&port->adapter->ccw_device->dev,
"A port opened with WWPN 0x%016Lx returned data that "
"identifies it as WWPN 0x%016Lx\n",
(unsigned long long) port->wwpn,
(unsigned long long) plogi->fl_wwpn);
return;
}
port->wwnn = plogi->fl_wwnn;
port->maxframe_size = plogi->fl_csp.sp_bb_data;
if (plogi->fl_cssp[0].cp_class & FC_CPC_VALID)
port->supported_classes |= FC_COS_CLASS1;
if (plogi->fl_cssp[1].cp_class & FC_CPC_VALID)
port->supported_classes |= FC_COS_CLASS2;
if (plogi->fl_cssp[2].cp_class & FC_CPC_VALID)
port->supported_classes |= FC_COS_CLASS3;
if (plogi->fl_cssp[3].cp_class & FC_CPC_VALID)
port->supported_classes |= FC_COS_CLASS4;
}
static void zfcp_fc_adisc_handler(void *data)
{
struct zfcp_fc_req *fc_req = data;
struct zfcp_port *port = fc_req->ct_els.port;
struct fc_els_adisc *adisc_resp = &fc_req->u.adisc.rsp;
if (fc_req->ct_els.status) {
/* request rejected or timed out */
zfcp_erp_port_forced_reopen(port, ZFCP_STATUS_COMMON_ERP_FAILED,
"fcadh_1");
goto out;
}
if (!port->wwnn)
port->wwnn = adisc_resp->adisc_wwnn;
if ((port->wwpn != adisc_resp->adisc_wwpn) ||
!(atomic_read(&port->status) & ZFCP_STATUS_COMMON_OPEN)) {
zfcp_erp_port_reopen(port, ZFCP_STATUS_COMMON_ERP_FAILED,
"fcadh_2");
goto out;
}
/* port is good, unblock rport without going through erp */
zfcp_scsi_schedule_rport_register(port);
out:
atomic_clear_mask(ZFCP_STATUS_PORT_LINK_TEST, &port->status);
put_device(&port->dev);
kmem_cache_free(zfcp_fc_req_cache, fc_req);
}
static int zfcp_fc_adisc(struct zfcp_port *port)
{
struct zfcp_fc_req *fc_req;
struct zfcp_adapter *adapter = port->adapter;
struct Scsi_Host *shost = adapter->scsi_host;
int ret;
fc_req = kmem_cache_zalloc(zfcp_fc_req_cache, GFP_ATOMIC);
if (!fc_req)
return -ENOMEM;
fc_req->ct_els.port = port;
fc_req->ct_els.req = &fc_req->sg_req;
fc_req->ct_els.resp = &fc_req->sg_rsp;
sg_init_one(&fc_req->sg_req, &fc_req->u.adisc.req,
sizeof(struct fc_els_adisc));
sg_init_one(&fc_req->sg_rsp, &fc_req->u.adisc.rsp,
sizeof(struct fc_els_adisc));
fc_req->ct_els.handler = zfcp_fc_adisc_handler;
fc_req->ct_els.handler_data = fc_req;
/* acc. to FC-FS, hard_nport_id in ADISC should not be set for ports
without FC-AL-2 capability, so we don't set it */
fc_req->u.adisc.req.adisc_wwpn = fc_host_port_name(shost);
fc_req->u.adisc.req.adisc_wwnn = fc_host_node_name(shost);
fc_req->u.adisc.req.adisc_cmd = ELS_ADISC;
hton24(fc_req->u.adisc.req.adisc_port_id, fc_host_port_id(shost));
ret = zfcp_fsf_send_els(adapter, port->d_id, &fc_req->ct_els,
ZFCP_FC_CTELS_TMO);
if (ret)
kmem_cache_free(zfcp_fc_req_cache, fc_req);
return ret;
}
void zfcp_fc_link_test_work(struct work_struct *work)
{
struct zfcp_port *port =
container_of(work, struct zfcp_port, test_link_work);
int retval;
get_device(&port->dev);
port->rport_task = RPORT_DEL;
zfcp_scsi_rport_work(&port->rport_work);
/* only issue one test command at one time per port */
if (atomic_read(&port->status) & ZFCP_STATUS_PORT_LINK_TEST)
goto out;
atomic_set_mask(ZFCP_STATUS_PORT_LINK_TEST, &port->status);
retval = zfcp_fc_adisc(port);
if (retval == 0)
return;
/* send of ADISC was not possible */
atomic_clear_mask(ZFCP_STATUS_PORT_LINK_TEST, &port->status);
zfcp_erp_port_forced_reopen(port, 0, "fcltwk1");
out:
put_device(&port->dev);
}
/**
* zfcp_fc_test_link - lightweight link test procedure
* @port: port to be tested
*
* Test status of a link to a remote port using the ELS command ADISC.
* If there is a problem with the remote port, error recovery steps
* will be triggered.
*/
void zfcp_fc_test_link(struct zfcp_port *port)
{
get_device(&port->dev);
if (!queue_work(port->adapter->work_queue, &port->test_link_work))
put_device(&port->dev);
}
static struct zfcp_fc_req *zfcp_alloc_sg_env(int buf_num)
{
struct zfcp_fc_req *fc_req;
fc_req = kmem_cache_zalloc(zfcp_fc_req_cache, GFP_KERNEL);
if (!fc_req)
return NULL;
if (zfcp_sg_setup_table(&fc_req->sg_rsp, buf_num)) {
kmem_cache_free(zfcp_fc_req_cache, fc_req);
return NULL;
}
sg_init_one(&fc_req->sg_req, &fc_req->u.gpn_ft.req,
sizeof(struct zfcp_fc_gpn_ft_req));
return fc_req;
}
static int zfcp_fc_send_gpn_ft(struct zfcp_fc_req *fc_req,
struct zfcp_adapter *adapter, int max_bytes)
{
struct zfcp_fsf_ct_els *ct_els = &fc_req->ct_els;
struct zfcp_fc_gpn_ft_req *req = &fc_req->u.gpn_ft.req;
DECLARE_COMPLETION_ONSTACK(completion);
int ret;
zfcp_fc_ct_ns_init(&req->ct_hdr, FC_NS_GPN_FT, max_bytes);
req->gpn_ft.fn_fc4_type = FC_TYPE_FCP;
ct_els->handler = zfcp_fc_complete;
ct_els->handler_data = &completion;
ct_els->req = &fc_req->sg_req;
ct_els->resp = &fc_req->sg_rsp;
ret = zfcp_fsf_send_ct(&adapter->gs->ds, ct_els, NULL,
ZFCP_FC_CTELS_TMO);
if (!ret)
wait_for_completion(&completion);
return ret;
}
static void zfcp_fc_validate_port(struct zfcp_port *port, struct list_head *lh)
{
if (!(atomic_read(&port->status) & ZFCP_STATUS_COMMON_NOESC))
return;
atomic_clear_mask(ZFCP_STATUS_COMMON_NOESC, &port->status);
if ((port->supported_classes != 0) ||
!list_empty(&port->unit_list))
return;
list_move_tail(&port->list, lh);
}
static int zfcp_fc_eval_gpn_ft(struct zfcp_fc_req *fc_req,
struct zfcp_adapter *adapter, int max_entries)
{
struct zfcp_fsf_ct_els *ct_els = &fc_req->ct_els;
struct scatterlist *sg = &fc_req->sg_rsp;
struct fc_ct_hdr *hdr = sg_virt(sg);
struct fc_gpn_ft_resp *acc = sg_virt(sg);
struct zfcp_port *port, *tmp;
unsigned long flags;
LIST_HEAD(remove_lh);
u32 d_id;
int ret = 0, x, last = 0;
if (ct_els->status)
return -EIO;
if (hdr->ct_cmd != FC_FS_ACC) {
if (hdr->ct_reason == FC_BA_RJT_UNABLE)
return -EAGAIN; /* might be a temporary condition */
return -EIO;
}
if (hdr->ct_mr_size) {
dev_warn(&adapter->ccw_device->dev,
"The name server reported %d words residual data\n",
hdr->ct_mr_size);
return -E2BIG;
}
/* first entry is the header */
for (x = 1; x < max_entries && !last; x++) {
if (x % (ZFCP_FC_GPN_FT_ENT_PAGE + 1))
acc++;
else
acc = sg_virt(++sg);
last = acc->fp_flags & FC_NS_FID_LAST;
d_id = ntoh24(acc->fp_fid);
/* don't attach ports with a well known address */
if (d_id >= FC_FID_WELL_KNOWN_BASE)
continue;
/* skip the adapter's port and known remote ports */
if (acc->fp_wwpn == fc_host_port_name(adapter->scsi_host))
continue;
port = zfcp_port_enqueue(adapter, acc->fp_wwpn,
ZFCP_STATUS_COMMON_NOESC, d_id);
if (!IS_ERR(port))
zfcp_erp_port_reopen(port, 0, "fcegpf1");
else if (PTR_ERR(port) != -EEXIST)
ret = PTR_ERR(port);
}
zfcp_erp_wait(adapter);
write_lock_irqsave(&adapter->port_list_lock, flags);
list_for_each_entry_safe(port, tmp, &adapter->port_list, list)
zfcp_fc_validate_port(port, &remove_lh);
write_unlock_irqrestore(&adapter->port_list_lock, flags);
list_for_each_entry_safe(port, tmp, &remove_lh, list) {
zfcp_erp_port_shutdown(port, 0, "fcegpf2");
zfcp_device_unregister(&port->dev, &zfcp_sysfs_port_attrs);
}
return ret;
}
/**
* zfcp_fc_scan_ports - scan remote ports and attach new ports
* @work: reference to scheduled work
*/
void zfcp_fc_scan_ports(struct work_struct *work)
{
struct zfcp_adapter *adapter = container_of(work, struct zfcp_adapter,
scan_work);
int ret, i;
struct zfcp_fc_req *fc_req;
int chain, max_entries, buf_num, max_bytes;
chain = adapter->adapter_features & FSF_FEATURE_ELS_CT_CHAINED_SBALS;
buf_num = chain ? ZFCP_FC_GPN_FT_NUM_BUFS : 1;
max_entries = chain ? ZFCP_FC_GPN_FT_MAX_ENT : ZFCP_FC_GPN_FT_ENT_PAGE;
max_bytes = chain ? ZFCP_FC_GPN_FT_MAX_SIZE : ZFCP_FC_CT_SIZE_PAGE;
if (fc_host_port_type(adapter->scsi_host) != FC_PORTTYPE_NPORT &&
fc_host_port_type(adapter->scsi_host) != FC_PORTTYPE_NPIV)
return;
if (zfcp_fc_wka_port_get(&adapter->gs->ds))
return;
fc_req = zfcp_alloc_sg_env(buf_num);
if (!fc_req)
goto out;
for (i = 0; i < 3; i++) {
ret = zfcp_fc_send_gpn_ft(fc_req, adapter, max_bytes);
if (!ret) {
ret = zfcp_fc_eval_gpn_ft(fc_req, adapter, max_entries);
if (ret == -EAGAIN)
ssleep(1);
else
break;
}
}
zfcp_sg_free_table(&fc_req->sg_rsp, buf_num);
kmem_cache_free(zfcp_fc_req_cache, fc_req);
out:
zfcp_fc_wka_port_put(&adapter->gs->ds);
}
static int zfcp_fc_gspn(struct zfcp_adapter *adapter,
struct zfcp_fc_req *fc_req)
{
DECLARE_COMPLETION_ONSTACK(completion);
char devno[] = "DEVNO:";
struct zfcp_fsf_ct_els *ct_els = &fc_req->ct_els;
struct zfcp_fc_gspn_req *gspn_req = &fc_req->u.gspn.req;
struct zfcp_fc_gspn_rsp *gspn_rsp = &fc_req->u.gspn.rsp;
int ret;
zfcp_fc_ct_ns_init(&gspn_req->ct_hdr, FC_NS_GSPN_ID,
FC_SYMBOLIC_NAME_SIZE);
hton24(gspn_req->gspn.fp_fid, fc_host_port_id(adapter->scsi_host));
sg_init_one(&fc_req->sg_req, gspn_req, sizeof(*gspn_req));
sg_init_one(&fc_req->sg_rsp, gspn_rsp, sizeof(*gspn_rsp));
ct_els->handler = zfcp_fc_complete;
ct_els->handler_data = &completion;
ct_els->req = &fc_req->sg_req;
ct_els->resp = &fc_req->sg_rsp;
ret = zfcp_fsf_send_ct(&adapter->gs->ds, ct_els, NULL,
ZFCP_FC_CTELS_TMO);
if (ret)
return ret;
wait_for_completion(&completion);
if (ct_els->status)
return ct_els->status;
if (fc_host_port_type(adapter->scsi_host) == FC_PORTTYPE_NPIV &&
!(strstr(gspn_rsp->gspn.fp_name, devno)))
snprintf(fc_host_symbolic_name(adapter->scsi_host),
FC_SYMBOLIC_NAME_SIZE, "%s%s %s NAME: %s",
gspn_rsp->gspn.fp_name, devno,
dev_name(&adapter->ccw_device->dev),
init_utsname()->nodename);
else
strlcpy(fc_host_symbolic_name(adapter->scsi_host),
gspn_rsp->gspn.fp_name, FC_SYMBOLIC_NAME_SIZE);
return 0;
}
static void zfcp_fc_rspn(struct zfcp_adapter *adapter,
struct zfcp_fc_req *fc_req)
{
DECLARE_COMPLETION_ONSTACK(completion);
struct Scsi_Host *shost = adapter->scsi_host;
struct zfcp_fsf_ct_els *ct_els = &fc_req->ct_els;
struct zfcp_fc_rspn_req *rspn_req = &fc_req->u.rspn.req;
struct fc_ct_hdr *rspn_rsp = &fc_req->u.rspn.rsp;
int ret, len;
zfcp_fc_ct_ns_init(&rspn_req->ct_hdr, FC_NS_RSPN_ID,
FC_SYMBOLIC_NAME_SIZE);
hton24(rspn_req->rspn.fr_fid.fp_fid, fc_host_port_id(shost));
len = strlcpy(rspn_req->rspn.fr_name, fc_host_symbolic_name(shost),
FC_SYMBOLIC_NAME_SIZE);
rspn_req->rspn.fr_name_len = len;
sg_init_one(&fc_req->sg_req, rspn_req, sizeof(*rspn_req));
sg_init_one(&fc_req->sg_rsp, rspn_rsp, sizeof(*rspn_rsp));
ct_els->handler = zfcp_fc_complete;
ct_els->handler_data = &completion;
ct_els->req = &fc_req->sg_req;
ct_els->resp = &fc_req->sg_rsp;
ret = zfcp_fsf_send_ct(&adapter->gs->ds, ct_els, NULL,
ZFCP_FC_CTELS_TMO);
if (!ret)
wait_for_completion(&completion);
}
/**
* zfcp_fc_sym_name_update - Retrieve and update the symbolic port name
* @work: ns_up_work of the adapter where to update the symbolic port name
*
* Retrieve the current symbolic port name that may have been set by
* the hardware using the GSPN request and update the fc_host
* symbolic_name sysfs attribute. When running in NPIV mode (and hence
* the port name is unique for this system), update the symbolic port
* name to add Linux specific information and update the FC nameserver
* using the RSPN request.
*/
void zfcp_fc_sym_name_update(struct work_struct *work)
{
struct zfcp_adapter *adapter = container_of(work, struct zfcp_adapter,
ns_up_work);
int ret;
struct zfcp_fc_req *fc_req;
if (fc_host_port_type(adapter->scsi_host) != FC_PORTTYPE_NPORT &&
fc_host_port_type(adapter->scsi_host) != FC_PORTTYPE_NPIV)
return;
fc_req = kmem_cache_zalloc(zfcp_fc_req_cache, GFP_KERNEL);
if (!fc_req)
return;
ret = zfcp_fc_wka_port_get(&adapter->gs->ds);
if (ret)
goto out_free;
ret = zfcp_fc_gspn(adapter, fc_req);
if (ret || fc_host_port_type(adapter->scsi_host) != FC_PORTTYPE_NPIV)
goto out_ds_put;
memset(fc_req, 0, sizeof(*fc_req));
zfcp_fc_rspn(adapter, fc_req);
out_ds_put:
zfcp_fc_wka_port_put(&adapter->gs->ds);
out_free:
kmem_cache_free(zfcp_fc_req_cache, fc_req);
}
static void zfcp_fc_ct_els_job_handler(void *data)
{
struct fc_bsg_job *job = data;
struct zfcp_fsf_ct_els *zfcp_ct_els = job->dd_data;
struct fc_bsg_reply *jr = job->reply;
jr->reply_payload_rcv_len = job->reply_payload.payload_len;
jr->reply_data.ctels_reply.status = FC_CTELS_STATUS_OK;
jr->result = zfcp_ct_els->status ? -EIO : 0;
job->job_done(job);
}
static struct zfcp_fc_wka_port *zfcp_fc_job_wka_port(struct fc_bsg_job *job)
{
u32 preamble_word1;
u8 gs_type;
struct zfcp_adapter *adapter;
preamble_word1 = job->request->rqst_data.r_ct.preamble_word1;
gs_type = (preamble_word1 & 0xff000000) >> 24;
adapter = (struct zfcp_adapter *) job->shost->hostdata[0];
switch (gs_type) {
case FC_FST_ALIAS:
return &adapter->gs->as;
case FC_FST_MGMT:
return &adapter->gs->ms;
case FC_FST_TIME:
return &adapter->gs->ts;
break;
case FC_FST_DIR:
return &adapter->gs->ds;
break;
default:
return NULL;
}
}
static void zfcp_fc_ct_job_handler(void *data)
{
struct fc_bsg_job *job = data;
struct zfcp_fc_wka_port *wka_port;
wka_port = zfcp_fc_job_wka_port(job);
zfcp_fc_wka_port_put(wka_port);
zfcp_fc_ct_els_job_handler(data);
}
static int zfcp_fc_exec_els_job(struct fc_bsg_job *job,
struct zfcp_adapter *adapter)
{
struct zfcp_fsf_ct_els *els = job->dd_data;
struct fc_rport *rport = job->rport;
struct zfcp_port *port;
u32 d_id;
if (rport) {
port = zfcp_get_port_by_wwpn(adapter, rport->port_name);
if (!port)
return -EINVAL;
d_id = port->d_id;
put_device(&port->dev);
} else
d_id = ntoh24(job->request->rqst_data.h_els.port_id);
els->handler = zfcp_fc_ct_els_job_handler;
return zfcp_fsf_send_els(adapter, d_id, els, job->req->timeout / HZ);
}
static int zfcp_fc_exec_ct_job(struct fc_bsg_job *job,
struct zfcp_adapter *adapter)
{
int ret;
struct zfcp_fsf_ct_els *ct = job->dd_data;
struct zfcp_fc_wka_port *wka_port;
wka_port = zfcp_fc_job_wka_port(job);
if (!wka_port)
return -EINVAL;
ret = zfcp_fc_wka_port_get(wka_port);
if (ret)
return ret;
ct->handler = zfcp_fc_ct_job_handler;
ret = zfcp_fsf_send_ct(wka_port, ct, NULL, job->req->timeout / HZ);
if (ret)
zfcp_fc_wka_port_put(wka_port);
return ret;
}
int zfcp_fc_exec_bsg_job(struct fc_bsg_job *job)
{
struct Scsi_Host *shost;
struct zfcp_adapter *adapter;
struct zfcp_fsf_ct_els *ct_els = job->dd_data;
shost = job->rport ? rport_to_shost(job->rport) : job->shost;
adapter = (struct zfcp_adapter *)shost->hostdata[0];
if (!(atomic_read(&adapter->status) & ZFCP_STATUS_COMMON_OPEN))
return -EINVAL;
ct_els->req = job->request_payload.sg_list;
ct_els->resp = job->reply_payload.sg_list;
ct_els->handler_data = job;
switch (job->request->msgcode) {
case FC_BSG_RPT_ELS:
case FC_BSG_HST_ELS_NOLOGIN:
return zfcp_fc_exec_els_job(job, adapter);
case FC_BSG_RPT_CT:
case FC_BSG_HST_CT:
return zfcp_fc_exec_ct_job(job, adapter);
default:
return -EINVAL;
}
}
int zfcp_fc_timeout_bsg_job(struct fc_bsg_job *job)
{
/* hardware tracks timeout, reset bsg timeout to not interfere */
return -EAGAIN;
}
int zfcp_fc_gs_setup(struct zfcp_adapter *adapter)
{
struct zfcp_fc_wka_ports *wka_ports;
wka_ports = kzalloc(sizeof(struct zfcp_fc_wka_ports), GFP_KERNEL);
if (!wka_ports)
return -ENOMEM;
adapter->gs = wka_ports;
zfcp_fc_wka_port_init(&wka_ports->ms, FC_FID_MGMT_SERV, adapter);
zfcp_fc_wka_port_init(&wka_ports->ts, FC_FID_TIME_SERV, adapter);
zfcp_fc_wka_port_init(&wka_ports->ds, FC_FID_DIR_SERV, adapter);
zfcp_fc_wka_port_init(&wka_ports->as, FC_FID_ALIASES, adapter);
return 0;
}
void zfcp_fc_gs_destroy(struct zfcp_adapter *adapter)
{
kfree(adapter->gs);
adapter->gs = NULL;
}
| gpl-2.0 |
12019/android_kernel_samsung_lt02wifi | drivers/media/dvb/frontends/ves1820.c | 8802 | 11495 | /*
VES1820 - Single Chip Cable Channel Receiver driver module
Copyright (C) 1999 Convergence Integrated Media GmbH <ralph@convergence.de>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <asm/div64.h>
#include "dvb_frontend.h"
#include "ves1820.h"
struct ves1820_state {
struct i2c_adapter* i2c;
/* configuration settings */
const struct ves1820_config* config;
struct dvb_frontend frontend;
/* private demodulator data */
u8 reg0;
u8 pwm;
};
static int verbose;
static u8 ves1820_inittab[] = {
0x69, 0x6A, 0x93, 0x1A, 0x12, 0x46, 0x26, 0x1A,
0x43, 0x6A, 0xAA, 0xAA, 0x1E, 0x85, 0x43, 0x20,
0xE0, 0x00, 0xA1, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x40
};
static int ves1820_writereg(struct ves1820_state *state, u8 reg, u8 data)
{
u8 buf[] = { 0x00, reg, data };
struct i2c_msg msg = {.addr = state->config->demod_address,.flags = 0,.buf = buf,.len = 3 };
int ret;
ret = i2c_transfer(state->i2c, &msg, 1);
if (ret != 1)
printk("ves1820: %s(): writereg error (reg == 0x%02x, "
"val == 0x%02x, ret == %i)\n", __func__, reg, data, ret);
return (ret != 1) ? -EREMOTEIO : 0;
}
static u8 ves1820_readreg(struct ves1820_state *state, u8 reg)
{
u8 b0[] = { 0x00, reg };
u8 b1[] = { 0 };
struct i2c_msg msg[] = {
{.addr = state->config->demod_address,.flags = 0,.buf = b0,.len = 2},
{.addr = state->config->demod_address,.flags = I2C_M_RD,.buf = b1,.len = 1}
};
int ret;
ret = i2c_transfer(state->i2c, msg, 2);
if (ret != 2)
printk("ves1820: %s(): readreg error (reg == 0x%02x, "
"ret == %i)\n", __func__, reg, ret);
return b1[0];
}
static int ves1820_setup_reg0(struct ves1820_state *state, u8 reg0, fe_spectral_inversion_t inversion)
{
reg0 |= state->reg0 & 0x62;
if (INVERSION_ON == inversion) {
if (!state->config->invert) reg0 |= 0x20;
else reg0 &= ~0x20;
} else if (INVERSION_OFF == inversion) {
if (!state->config->invert) reg0 &= ~0x20;
else reg0 |= 0x20;
}
ves1820_writereg(state, 0x00, reg0 & 0xfe);
ves1820_writereg(state, 0x00, reg0 | 0x01);
state->reg0 = reg0;
return 0;
}
static int ves1820_set_symbolrate(struct ves1820_state *state, u32 symbolrate)
{
s32 BDR;
s32 BDRI;
s16 SFIL = 0;
u16 NDEC = 0;
u32 ratio;
u32 fin;
u32 tmp;
u64 fptmp;
u64 fpxin;
if (symbolrate > state->config->xin / 2)
symbolrate = state->config->xin / 2;
if (symbolrate < 500000)
symbolrate = 500000;
if (symbolrate < state->config->xin / 16)
NDEC = 1;
if (symbolrate < state->config->xin / 32)
NDEC = 2;
if (symbolrate < state->config->xin / 64)
NDEC = 3;
/* yeuch! */
fpxin = state->config->xin * 10;
fptmp = fpxin; do_div(fptmp, 123);
if (symbolrate < fptmp)
SFIL = 1;
fptmp = fpxin; do_div(fptmp, 160);
if (symbolrate < fptmp)
SFIL = 0;
fptmp = fpxin; do_div(fptmp, 246);
if (symbolrate < fptmp)
SFIL = 1;
fptmp = fpxin; do_div(fptmp, 320);
if (symbolrate < fptmp)
SFIL = 0;
fptmp = fpxin; do_div(fptmp, 492);
if (symbolrate < fptmp)
SFIL = 1;
fptmp = fpxin; do_div(fptmp, 640);
if (symbolrate < fptmp)
SFIL = 0;
fptmp = fpxin; do_div(fptmp, 984);
if (symbolrate < fptmp)
SFIL = 1;
fin = state->config->xin >> 4;
symbolrate <<= NDEC;
ratio = (symbolrate << 4) / fin;
tmp = ((symbolrate << 4) % fin) << 8;
ratio = (ratio << 8) + tmp / fin;
tmp = (tmp % fin) << 8;
ratio = (ratio << 8) + DIV_ROUND_CLOSEST(tmp, fin);
BDR = ratio;
BDRI = (((state->config->xin << 5) / symbolrate) + 1) / 2;
if (BDRI > 0xFF)
BDRI = 0xFF;
SFIL = (SFIL << 4) | ves1820_inittab[0x0E];
NDEC = (NDEC << 6) | ves1820_inittab[0x03];
ves1820_writereg(state, 0x03, NDEC);
ves1820_writereg(state, 0x0a, BDR & 0xff);
ves1820_writereg(state, 0x0b, (BDR >> 8) & 0xff);
ves1820_writereg(state, 0x0c, (BDR >> 16) & 0x3f);
ves1820_writereg(state, 0x0d, BDRI);
ves1820_writereg(state, 0x0e, SFIL);
return 0;
}
static int ves1820_init(struct dvb_frontend* fe)
{
struct ves1820_state* state = fe->demodulator_priv;
int i;
ves1820_writereg(state, 0, 0);
for (i = 0; i < sizeof(ves1820_inittab); i++)
ves1820_writereg(state, i, ves1820_inittab[i]);
if (state->config->selagc)
ves1820_writereg(state, 2, ves1820_inittab[2] | 0x08);
ves1820_writereg(state, 0x34, state->pwm);
return 0;
}
static int ves1820_set_parameters(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *p = &fe->dtv_property_cache;
struct ves1820_state* state = fe->demodulator_priv;
static const u8 reg0x00[] = { 0x00, 0x04, 0x08, 0x0c, 0x10 };
static const u8 reg0x01[] = { 140, 140, 106, 100, 92 };
static const u8 reg0x05[] = { 135, 100, 70, 54, 38 };
static const u8 reg0x08[] = { 162, 116, 67, 52, 35 };
static const u8 reg0x09[] = { 145, 150, 106, 126, 107 };
int real_qam = p->modulation - QAM_16;
if (real_qam < 0 || real_qam > 4)
return -EINVAL;
if (fe->ops.tuner_ops.set_params) {
fe->ops.tuner_ops.set_params(fe);
if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 0);
}
ves1820_set_symbolrate(state, p->symbol_rate);
ves1820_writereg(state, 0x34, state->pwm);
ves1820_writereg(state, 0x01, reg0x01[real_qam]);
ves1820_writereg(state, 0x05, reg0x05[real_qam]);
ves1820_writereg(state, 0x08, reg0x08[real_qam]);
ves1820_writereg(state, 0x09, reg0x09[real_qam]);
ves1820_setup_reg0(state, reg0x00[real_qam], p->inversion);
ves1820_writereg(state, 2, ves1820_inittab[2] | (state->config->selagc ? 0x08 : 0));
return 0;
}
static int ves1820_read_status(struct dvb_frontend* fe, fe_status_t* status)
{
struct ves1820_state* state = fe->demodulator_priv;
int sync;
*status = 0;
sync = ves1820_readreg(state, 0x11);
if (sync & 1)
*status |= FE_HAS_SIGNAL;
if (sync & 2)
*status |= FE_HAS_CARRIER;
if (sync & 2) /* XXX FIXME! */
*status |= FE_HAS_VITERBI;
if (sync & 4)
*status |= FE_HAS_SYNC;
if (sync & 8)
*status |= FE_HAS_LOCK;
return 0;
}
static int ves1820_read_ber(struct dvb_frontend* fe, u32* ber)
{
struct ves1820_state* state = fe->demodulator_priv;
u32 _ber = ves1820_readreg(state, 0x14) |
(ves1820_readreg(state, 0x15) << 8) |
((ves1820_readreg(state, 0x16) & 0x0f) << 16);
*ber = 10 * _ber;
return 0;
}
static int ves1820_read_signal_strength(struct dvb_frontend* fe, u16* strength)
{
struct ves1820_state* state = fe->demodulator_priv;
u8 gain = ves1820_readreg(state, 0x17);
*strength = (gain << 8) | gain;
return 0;
}
static int ves1820_read_snr(struct dvb_frontend* fe, u16* snr)
{
struct ves1820_state* state = fe->demodulator_priv;
u8 quality = ~ves1820_readreg(state, 0x18);
*snr = (quality << 8) | quality;
return 0;
}
static int ves1820_read_ucblocks(struct dvb_frontend* fe, u32* ucblocks)
{
struct ves1820_state* state = fe->demodulator_priv;
*ucblocks = ves1820_readreg(state, 0x13) & 0x7f;
if (*ucblocks == 0x7f)
*ucblocks = 0xffffffff;
/* reset uncorrected block counter */
ves1820_writereg(state, 0x10, ves1820_inittab[0x10] & 0xdf);
ves1820_writereg(state, 0x10, ves1820_inittab[0x10]);
return 0;
}
static int ves1820_get_frontend(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *p = &fe->dtv_property_cache;
struct ves1820_state* state = fe->demodulator_priv;
int sync;
s8 afc = 0;
sync = ves1820_readreg(state, 0x11);
afc = ves1820_readreg(state, 0x19);
if (verbose) {
/* AFC only valid when carrier has been recovered */
printk(sync & 2 ? "ves1820: AFC (%d) %dHz\n" :
"ves1820: [AFC (%d) %dHz]\n", afc, -((s32) p->symbol_rate * afc) >> 10);
}
if (!state->config->invert) {
p->inversion = (state->reg0 & 0x20) ? INVERSION_ON : INVERSION_OFF;
} else {
p->inversion = (!(state->reg0 & 0x20)) ? INVERSION_ON : INVERSION_OFF;
}
p->modulation = ((state->reg0 >> 2) & 7) + QAM_16;
p->fec_inner = FEC_NONE;
p->frequency = ((p->frequency + 31250) / 62500) * 62500;
if (sync & 2)
p->frequency -= ((s32) p->symbol_rate * afc) >> 10;
return 0;
}
static int ves1820_sleep(struct dvb_frontend* fe)
{
struct ves1820_state* state = fe->demodulator_priv;
ves1820_writereg(state, 0x1b, 0x02); /* pdown ADC */
ves1820_writereg(state, 0x00, 0x80); /* standby */
return 0;
}
static int ves1820_get_tune_settings(struct dvb_frontend* fe, struct dvb_frontend_tune_settings* fesettings)
{
fesettings->min_delay_ms = 200;
fesettings->step_size = 0;
fesettings->max_drift = 0;
return 0;
}
static void ves1820_release(struct dvb_frontend* fe)
{
struct ves1820_state* state = fe->demodulator_priv;
kfree(state);
}
static struct dvb_frontend_ops ves1820_ops;
struct dvb_frontend* ves1820_attach(const struct ves1820_config* config,
struct i2c_adapter* i2c,
u8 pwm)
{
struct ves1820_state* state = NULL;
/* allocate memory for the internal state */
state = kzalloc(sizeof(struct ves1820_state), GFP_KERNEL);
if (state == NULL)
goto error;
/* setup the state */
state->reg0 = ves1820_inittab[0];
state->config = config;
state->i2c = i2c;
state->pwm = pwm;
/* check if the demod is there */
if ((ves1820_readreg(state, 0x1a) & 0xf0) != 0x70)
goto error;
if (verbose)
printk("ves1820: pwm=0x%02x\n", state->pwm);
/* create dvb_frontend */
memcpy(&state->frontend.ops, &ves1820_ops, sizeof(struct dvb_frontend_ops));
state->frontend.ops.info.symbol_rate_min = (state->config->xin / 2) / 64; /* SACLK/64 == (XIN/2)/64 */
state->frontend.ops.info.symbol_rate_max = (state->config->xin / 2) / 4; /* SACLK/4 */
state->frontend.demodulator_priv = state;
return &state->frontend;
error:
kfree(state);
return NULL;
}
static struct dvb_frontend_ops ves1820_ops = {
.delsys = { SYS_DVBC_ANNEX_A },
.info = {
.name = "VLSI VES1820 DVB-C",
.frequency_stepsize = 62500,
.frequency_min = 47000000,
.frequency_max = 862000000,
.caps = FE_CAN_QAM_16 |
FE_CAN_QAM_32 |
FE_CAN_QAM_64 |
FE_CAN_QAM_128 |
FE_CAN_QAM_256 |
FE_CAN_FEC_AUTO
},
.release = ves1820_release,
.init = ves1820_init,
.sleep = ves1820_sleep,
.set_frontend = ves1820_set_parameters,
.get_frontend = ves1820_get_frontend,
.get_tune_settings = ves1820_get_tune_settings,
.read_status = ves1820_read_status,
.read_ber = ves1820_read_ber,
.read_signal_strength = ves1820_read_signal_strength,
.read_snr = ves1820_read_snr,
.read_ucblocks = ves1820_read_ucblocks,
};
module_param(verbose, int, 0644);
MODULE_PARM_DESC(verbose, "print AFC offset after tuning for debugging the PWM setting");
MODULE_DESCRIPTION("VLSI VES1820 DVB-C Demodulator driver");
MODULE_AUTHOR("Ralph Metzler, Holger Waechtler");
MODULE_LICENSE("GPL");
EXPORT_SYMBOL(ves1820_attach);
| gpl-2.0 |
loli10K/linux-sunxi | drivers/isdn/hisax/arcofi.c | 9570 | 3628 | /* $Id: arcofi.c,v 1.14.2.3 2004/01/13 14:31:24 keil Exp $
*
* Ansteuerung ARCOFI 2165
*
* Author Karsten Keil
* Copyright by Karsten Keil <keil@isdn4linux.de>
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
*/
#include <linux/sched.h>
#include "hisax.h"
#include "isdnl1.h"
#include "isac.h"
#include "arcofi.h"
#define ARCOFI_TIMER_VALUE 20
static void
add_arcofi_timer(struct IsdnCardState *cs) {
if (test_and_set_bit(FLG_ARCOFI_TIMER, &cs->HW_Flags)) {
del_timer(&cs->dc.isac.arcofitimer);
}
init_timer(&cs->dc.isac.arcofitimer);
cs->dc.isac.arcofitimer.expires = jiffies + ((ARCOFI_TIMER_VALUE * HZ) / 1000);
add_timer(&cs->dc.isac.arcofitimer);
}
static void
send_arcofi(struct IsdnCardState *cs) {
add_arcofi_timer(cs);
cs->dc.isac.mon_txp = 0;
cs->dc.isac.mon_txc = cs->dc.isac.arcofi_list->len;
memcpy(cs->dc.isac.mon_tx, cs->dc.isac.arcofi_list->msg, cs->dc.isac.mon_txc);
switch (cs->dc.isac.arcofi_bc) {
case 0: break;
case 1: cs->dc.isac.mon_tx[1] |= 0x40;
break;
default: break;
}
cs->dc.isac.mocr &= 0x0f;
cs->dc.isac.mocr |= 0xa0;
cs->writeisac(cs, ISAC_MOCR, cs->dc.isac.mocr);
(void) cs->readisac(cs, ISAC_MOSR);
cs->writeisac(cs, ISAC_MOX1, cs->dc.isac.mon_tx[cs->dc.isac.mon_txp++]);
cs->dc.isac.mocr |= 0x10;
cs->writeisac(cs, ISAC_MOCR, cs->dc.isac.mocr);
}
int
arcofi_fsm(struct IsdnCardState *cs, int event, void *data) {
if (cs->debug & L1_DEB_MONITOR) {
debugl1(cs, "arcofi state %d event %d", cs->dc.isac.arcofi_state, event);
}
if (event == ARCOFI_TIMEOUT) {
cs->dc.isac.arcofi_state = ARCOFI_NOP;
test_and_set_bit(FLG_ARCOFI_ERROR, &cs->HW_Flags);
wake_up(&cs->dc.isac.arcofi_wait);
return (1);
}
switch (cs->dc.isac.arcofi_state) {
case ARCOFI_NOP:
if (event == ARCOFI_START) {
cs->dc.isac.arcofi_list = data;
cs->dc.isac.arcofi_state = ARCOFI_TRANSMIT;
send_arcofi(cs);
}
break;
case ARCOFI_TRANSMIT:
if (event == ARCOFI_TX_END) {
if (cs->dc.isac.arcofi_list->receive) {
add_arcofi_timer(cs);
cs->dc.isac.arcofi_state = ARCOFI_RECEIVE;
} else {
if (cs->dc.isac.arcofi_list->next) {
cs->dc.isac.arcofi_list =
cs->dc.isac.arcofi_list->next;
send_arcofi(cs);
} else {
if (test_and_clear_bit(FLG_ARCOFI_TIMER, &cs->HW_Flags)) {
del_timer(&cs->dc.isac.arcofitimer);
}
cs->dc.isac.arcofi_state = ARCOFI_NOP;
wake_up(&cs->dc.isac.arcofi_wait);
}
}
}
break;
case ARCOFI_RECEIVE:
if (event == ARCOFI_RX_END) {
if (cs->dc.isac.arcofi_list->next) {
cs->dc.isac.arcofi_list =
cs->dc.isac.arcofi_list->next;
cs->dc.isac.arcofi_state = ARCOFI_TRANSMIT;
send_arcofi(cs);
} else {
if (test_and_clear_bit(FLG_ARCOFI_TIMER, &cs->HW_Flags)) {
del_timer(&cs->dc.isac.arcofitimer);
}
cs->dc.isac.arcofi_state = ARCOFI_NOP;
wake_up(&cs->dc.isac.arcofi_wait);
}
}
break;
default:
debugl1(cs, "Arcofi unknown state %x", cs->dc.isac.arcofi_state);
return (2);
}
return (0);
}
static void
arcofi_timer(struct IsdnCardState *cs) {
arcofi_fsm(cs, ARCOFI_TIMEOUT, NULL);
}
void
clear_arcofi(struct IsdnCardState *cs) {
if (test_and_clear_bit(FLG_ARCOFI_TIMER, &cs->HW_Flags)) {
del_timer(&cs->dc.isac.arcofitimer);
}
}
void
init_arcofi(struct IsdnCardState *cs) {
cs->dc.isac.arcofitimer.function = (void *) arcofi_timer;
cs->dc.isac.arcofitimer.data = (long) cs;
init_timer(&cs->dc.isac.arcofitimer);
init_waitqueue_head(&cs->dc.isac.arcofi_wait);
test_and_set_bit(HW_ARCOFI, &cs->HW_Flags);
}
| gpl-2.0 |
VentureROM-Legacy/android_kernel_lge_d85x | drivers/isdn/hisax/arcofi.c | 9570 | 3628 | /* $Id: arcofi.c,v 1.14.2.3 2004/01/13 14:31:24 keil Exp $
*
* Ansteuerung ARCOFI 2165
*
* Author Karsten Keil
* Copyright by Karsten Keil <keil@isdn4linux.de>
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
*/
#include <linux/sched.h>
#include "hisax.h"
#include "isdnl1.h"
#include "isac.h"
#include "arcofi.h"
#define ARCOFI_TIMER_VALUE 20
static void
add_arcofi_timer(struct IsdnCardState *cs) {
if (test_and_set_bit(FLG_ARCOFI_TIMER, &cs->HW_Flags)) {
del_timer(&cs->dc.isac.arcofitimer);
}
init_timer(&cs->dc.isac.arcofitimer);
cs->dc.isac.arcofitimer.expires = jiffies + ((ARCOFI_TIMER_VALUE * HZ) / 1000);
add_timer(&cs->dc.isac.arcofitimer);
}
static void
send_arcofi(struct IsdnCardState *cs) {
add_arcofi_timer(cs);
cs->dc.isac.mon_txp = 0;
cs->dc.isac.mon_txc = cs->dc.isac.arcofi_list->len;
memcpy(cs->dc.isac.mon_tx, cs->dc.isac.arcofi_list->msg, cs->dc.isac.mon_txc);
switch (cs->dc.isac.arcofi_bc) {
case 0: break;
case 1: cs->dc.isac.mon_tx[1] |= 0x40;
break;
default: break;
}
cs->dc.isac.mocr &= 0x0f;
cs->dc.isac.mocr |= 0xa0;
cs->writeisac(cs, ISAC_MOCR, cs->dc.isac.mocr);
(void) cs->readisac(cs, ISAC_MOSR);
cs->writeisac(cs, ISAC_MOX1, cs->dc.isac.mon_tx[cs->dc.isac.mon_txp++]);
cs->dc.isac.mocr |= 0x10;
cs->writeisac(cs, ISAC_MOCR, cs->dc.isac.mocr);
}
int
arcofi_fsm(struct IsdnCardState *cs, int event, void *data) {
if (cs->debug & L1_DEB_MONITOR) {
debugl1(cs, "arcofi state %d event %d", cs->dc.isac.arcofi_state, event);
}
if (event == ARCOFI_TIMEOUT) {
cs->dc.isac.arcofi_state = ARCOFI_NOP;
test_and_set_bit(FLG_ARCOFI_ERROR, &cs->HW_Flags);
wake_up(&cs->dc.isac.arcofi_wait);
return (1);
}
switch (cs->dc.isac.arcofi_state) {
case ARCOFI_NOP:
if (event == ARCOFI_START) {
cs->dc.isac.arcofi_list = data;
cs->dc.isac.arcofi_state = ARCOFI_TRANSMIT;
send_arcofi(cs);
}
break;
case ARCOFI_TRANSMIT:
if (event == ARCOFI_TX_END) {
if (cs->dc.isac.arcofi_list->receive) {
add_arcofi_timer(cs);
cs->dc.isac.arcofi_state = ARCOFI_RECEIVE;
} else {
if (cs->dc.isac.arcofi_list->next) {
cs->dc.isac.arcofi_list =
cs->dc.isac.arcofi_list->next;
send_arcofi(cs);
} else {
if (test_and_clear_bit(FLG_ARCOFI_TIMER, &cs->HW_Flags)) {
del_timer(&cs->dc.isac.arcofitimer);
}
cs->dc.isac.arcofi_state = ARCOFI_NOP;
wake_up(&cs->dc.isac.arcofi_wait);
}
}
}
break;
case ARCOFI_RECEIVE:
if (event == ARCOFI_RX_END) {
if (cs->dc.isac.arcofi_list->next) {
cs->dc.isac.arcofi_list =
cs->dc.isac.arcofi_list->next;
cs->dc.isac.arcofi_state = ARCOFI_TRANSMIT;
send_arcofi(cs);
} else {
if (test_and_clear_bit(FLG_ARCOFI_TIMER, &cs->HW_Flags)) {
del_timer(&cs->dc.isac.arcofitimer);
}
cs->dc.isac.arcofi_state = ARCOFI_NOP;
wake_up(&cs->dc.isac.arcofi_wait);
}
}
break;
default:
debugl1(cs, "Arcofi unknown state %x", cs->dc.isac.arcofi_state);
return (2);
}
return (0);
}
static void
arcofi_timer(struct IsdnCardState *cs) {
arcofi_fsm(cs, ARCOFI_TIMEOUT, NULL);
}
void
clear_arcofi(struct IsdnCardState *cs) {
if (test_and_clear_bit(FLG_ARCOFI_TIMER, &cs->HW_Flags)) {
del_timer(&cs->dc.isac.arcofitimer);
}
}
void
init_arcofi(struct IsdnCardState *cs) {
cs->dc.isac.arcofitimer.function = (void *) arcofi_timer;
cs->dc.isac.arcofitimer.data = (long) cs;
init_timer(&cs->dc.isac.arcofitimer);
init_waitqueue_head(&cs->dc.isac.arcofi_wait);
test_and_set_bit(HW_ARCOFI, &cs->HW_Flags);
}
| gpl-2.0 |
BenefitA3/android_kernel_ark_msm8916 | net/netfilter/xt_CLASSIFY.c | 12642 | 2012 | /*
* This is a module which is used for setting the skb->priority field
* of an skb for qdisc classification.
*/
/* (C) 2001-2002 Patrick McHardy <kaber@trash.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/ip.h>
#include <net/checksum.h>
#include <linux/netfilter_ipv4.h>
#include <linux/netfilter_ipv6.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter/xt_CLASSIFY.h>
#include <linux/netfilter_arp.h>
MODULE_AUTHOR("Patrick McHardy <kaber@trash.net>");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Xtables: Qdisc classification");
MODULE_ALIAS("ipt_CLASSIFY");
MODULE_ALIAS("ip6t_CLASSIFY");
MODULE_ALIAS("arpt_CLASSIFY");
static unsigned int
classify_tg(struct sk_buff *skb, const struct xt_action_param *par)
{
const struct xt_classify_target_info *clinfo = par->targinfo;
skb->priority = clinfo->priority;
return XT_CONTINUE;
}
static struct xt_target classify_tg_reg[] __read_mostly = {
{
.name = "CLASSIFY",
.revision = 0,
.family = NFPROTO_UNSPEC,
.hooks = (1 << NF_INET_LOCAL_OUT) | (1 << NF_INET_FORWARD) |
(1 << NF_INET_POST_ROUTING),
.target = classify_tg,
.targetsize = sizeof(struct xt_classify_target_info),
.me = THIS_MODULE,
},
{
.name = "CLASSIFY",
.revision = 0,
.family = NFPROTO_ARP,
.hooks = (1 << NF_ARP_OUT) | (1 << NF_ARP_FORWARD),
.target = classify_tg,
.targetsize = sizeof(struct xt_classify_target_info),
.me = THIS_MODULE,
},
};
static int __init classify_tg_init(void)
{
return xt_register_targets(classify_tg_reg, ARRAY_SIZE(classify_tg_reg));
}
static void __exit classify_tg_exit(void)
{
xt_unregister_targets(classify_tg_reg, ARRAY_SIZE(classify_tg_reg));
}
module_init(classify_tg_init);
module_exit(classify_tg_exit);
| gpl-2.0 |
AK-Kernel/AK-Mako | net/netfilter/xt_CLASSIFY.c | 12642 | 2012 | /*
* This is a module which is used for setting the skb->priority field
* of an skb for qdisc classification.
*/
/* (C) 2001-2002 Patrick McHardy <kaber@trash.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/ip.h>
#include <net/checksum.h>
#include <linux/netfilter_ipv4.h>
#include <linux/netfilter_ipv6.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter/xt_CLASSIFY.h>
#include <linux/netfilter_arp.h>
MODULE_AUTHOR("Patrick McHardy <kaber@trash.net>");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Xtables: Qdisc classification");
MODULE_ALIAS("ipt_CLASSIFY");
MODULE_ALIAS("ip6t_CLASSIFY");
MODULE_ALIAS("arpt_CLASSIFY");
static unsigned int
classify_tg(struct sk_buff *skb, const struct xt_action_param *par)
{
const struct xt_classify_target_info *clinfo = par->targinfo;
skb->priority = clinfo->priority;
return XT_CONTINUE;
}
static struct xt_target classify_tg_reg[] __read_mostly = {
{
.name = "CLASSIFY",
.revision = 0,
.family = NFPROTO_UNSPEC,
.hooks = (1 << NF_INET_LOCAL_OUT) | (1 << NF_INET_FORWARD) |
(1 << NF_INET_POST_ROUTING),
.target = classify_tg,
.targetsize = sizeof(struct xt_classify_target_info),
.me = THIS_MODULE,
},
{
.name = "CLASSIFY",
.revision = 0,
.family = NFPROTO_ARP,
.hooks = (1 << NF_ARP_OUT) | (1 << NF_ARP_FORWARD),
.target = classify_tg,
.targetsize = sizeof(struct xt_classify_target_info),
.me = THIS_MODULE,
},
};
static int __init classify_tg_init(void)
{
return xt_register_targets(classify_tg_reg, ARRAY_SIZE(classify_tg_reg));
}
static void __exit classify_tg_exit(void)
{
xt_unregister_targets(classify_tg_reg, ARRAY_SIZE(classify_tg_reg));
}
module_init(classify_tg_init);
module_exit(classify_tg_exit);
| gpl-2.0 |
hellsgod/hells-Core-N6P | arch/powerpc/boot/uartlite.c | 14178 | 1778 | /*
* Xilinx UARTLITE bootloader driver
*
* Copyright (C) 2007 Secret Lab Technologies Ltd.
*
* This file is licensed under the terms of the GNU General Public License
* version 2. This program is licensed "as is" without any warranty of any
* kind, whether express or implied.
*/
#include <stdarg.h>
#include <stddef.h>
#include "types.h"
#include "string.h"
#include "stdio.h"
#include "io.h"
#include "ops.h"
#define ULITE_RX 0x00
#define ULITE_TX 0x04
#define ULITE_STATUS 0x08
#define ULITE_CONTROL 0x0c
#define ULITE_STATUS_RXVALID 0x01
#define ULITE_STATUS_TXFULL 0x08
#define ULITE_CONTROL_RST_RX 0x02
static void * reg_base;
static int uartlite_open(void)
{
/* Clear the RX FIFO */
out_be32(reg_base + ULITE_CONTROL, ULITE_CONTROL_RST_RX);
return 0;
}
static void uartlite_putc(unsigned char c)
{
u32 reg = ULITE_STATUS_TXFULL;
while (reg & ULITE_STATUS_TXFULL) /* spin on TXFULL bit */
reg = in_be32(reg_base + ULITE_STATUS);
out_be32(reg_base + ULITE_TX, c);
}
static unsigned char uartlite_getc(void)
{
u32 reg = 0;
while (!(reg & ULITE_STATUS_RXVALID)) /* spin waiting for RXVALID bit */
reg = in_be32(reg_base + ULITE_STATUS);
return in_be32(reg_base + ULITE_RX);
}
static u8 uartlite_tstc(void)
{
u32 reg = in_be32(reg_base + ULITE_STATUS);
return reg & ULITE_STATUS_RXVALID;
}
int uartlite_console_init(void *devp, struct serial_console_data *scdp)
{
int n;
unsigned long reg_phys;
n = getprop(devp, "virtual-reg", ®_base, sizeof(reg_base));
if (n != sizeof(reg_base)) {
if (!dt_xlate_reg(devp, 0, ®_phys, NULL))
return -1;
reg_base = (void *)reg_phys;
}
scdp->open = uartlite_open;
scdp->putc = uartlite_putc;
scdp->getc = uartlite_getc;
scdp->tstc = uartlite_tstc;
scdp->close = NULL;
return 0;
}
| gpl-2.0 |
bowlofstew/gcc | gcc/testsuite/gcc.target/i386/avx512f-vpmovsxwd-2.c | 99 | 1124 | /* { dg-do run } */
/* { dg-options "-O2 -mavx512f" } */
/* { dg-require-effective-target avx512f } */
#define AVX512F
#include "avx512f-helper.h"
#define SIZE (AVX512F_LEN / 32)
#include "avx512f-mask-type.h"
static void
CALC (short *s, int *r)
{
int i;
for (i = 0; i < SIZE; i++)
{
r[i] = (int) s[i];
}
}
void
TEST (void)
{
UNION_TYPE (AVX512F_LEN_HALF, i_w) s;
UNION_TYPE (AVX512F_LEN, i_d) res1, res2, res3;
MASK_TYPE mask = MASK_VALUE;
int res_ref[SIZE];
int i, sign = 1;
for (i = 0; i < SIZE; i++)
{
s.a[i] = 2000 * i * sign;
res2.a[i] = DEFAULT_VALUE;
sign = -sign;
}
res1.x = INTRINSIC (_cvtepi16_epi32) (s.x);
res2.x = INTRINSIC (_mask_cvtepi16_epi32) (res2.x, mask, s.x);
res3.x = INTRINSIC (_maskz_cvtepi16_epi32) (mask, s.x);
CALC (s.a, res_ref);
if (UNION_CHECK (AVX512F_LEN, i_d) (res1, res_ref))
abort ();
MASK_MERGE (i_d) (res_ref, mask, SIZE);
if (UNION_CHECK (AVX512F_LEN, i_d) (res2, res_ref))
abort ();
MASK_ZERO (i_d) (res_ref, mask, SIZE);
if (UNION_CHECK (AVX512F_LEN, i_d) (res3, res_ref))
abort ();
}
| gpl-2.0 |
artemh/asuswrt-merlin | release/src/router/samba-3.0.25b/testsuite/libsmbclient/src/creat/creat_1.c | 99 | 1101 | #include <stdio.h>
#include <string.h>
#include <errno.h>
#include <libsmbclient.h>
#define MAX_BUFF_SIZE 255
char g_workgroup[MAX_BUFF_SIZE];
char g_username[MAX_BUFF_SIZE];
char g_password[MAX_BUFF_SIZE];
char g_server[MAX_BUFF_SIZE];
char g_share[MAX_BUFF_SIZE];
void auth_fn(const char *server, const char *share, char *workgroup, int wgmaxlen,
char *username, int unmaxlen, char *password, int pwmaxlen)
{
strncpy(workgroup, g_workgroup, wgmaxlen - 1);
strncpy(username, g_username, unmaxlen - 1);
strncpy(password, g_password, pwmaxlen - 1);
strcpy(g_server, server);
strcpy(g_share, share);
}
int main(int argc, char** argv)
{
int err = -1;
int fd = 0;
char url[MAX_BUFF_SIZE];
bzero(g_workgroup,MAX_BUFF_SIZE);
bzero(url,MAX_BUFF_SIZE);
if ( argc == 5 )
{
strncpy(g_workgroup,argv[1],strlen(argv[1]));
strncpy(g_username,argv[2],strlen(argv[2]));
strncpy(g_password,argv[3],strlen(argv[3]));
strncpy(url,argv[4],strlen(argv[4]));
smbc_init(auth_fn, 0);
fd = smbc_creat(url, 0666);
if ( fd < 0 )
err = 1;
else
err = 0;
}
return err;
}
| gpl-2.0 |
rbalint/xbmc | xbmc/screensavers/rsxs-0.9/lib/asnprintf.c | 99 | 1147 | /* Formatted output to strings.
Copyright (C) 1999, 2002 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
/* Specification. */
#include "vasnprintf.h"
#include <stdarg.h>
char *
asnprintf (char *resultbuf, size_t *lengthp, const char *format, ...)
{
va_list args;
char *result;
va_start (args, format);
result = vasnprintf (resultbuf, lengthp, format, args);
va_end (args);
return result;
}
| gpl-2.0 |
villevoutilainen/gcc | gcc/testsuite/gcc.dg/vect/slp-3.c | 99 | 4024 | /* { dg-require-effective-target vect_int } */
#include <stdarg.h>
#include "tree-vect.h"
#define N 12
unsigned short in[N*8] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};
int
main1 ()
{
int i;
unsigned short out[N*8];
for (i = 0; i < N; i++)
{
out[i*8] = in[i*8];
out[i*8 + 1] = in[i*8 + 1];
out[i*8 + 2] = in[i*8 + 2];
out[i*8 + 3] = in[i*8 + 3];
out[i*8 + 4] = in[i*8 + 4];
out[i*8 + 5] = in[i*8 + 5];
out[i*8 + 6] = in[i*8 + 6];
out[i*8 + 7] = in[i*8 + 7];
}
/* check results: */
for (i = 0; i < N; i++)
{
if (out[i*8] != in[i*8]
|| out[i*8 + 1] != in[i*8 + 1]
|| out[i*8 + 2] != in[i*8 + 2]
|| out[i*8 + 3] != in[i*8 + 3]
|| out[i*8 + 4] != in[i*8 + 4]
|| out[i*8 + 5] != in[i*8 + 5]
|| out[i*8 + 6] != in[i*8 + 6]
|| out[i*8 + 7] != in[i*8 + 7])
abort ();
}
for (i = 0; i < N*2; i++)
{
out[i*4] = in[i*4];
out[i*4 + 1] = in[i*4 + 1];
out[i*4 + 2] = in[i*4 + 2];
out[i*4 + 3] = in[i*4 + 3];
}
/* check results: */
for (i = 0; i < N*2; i++)
{
if (out[i*4] != in[i*4]
|| out[i*4 + 1] != in[i*4 + 1]
|| out[i*4 + 2] != in[i*4 + 2]
|| out[i*4 + 3] != in[i*4 + 3])
abort ();
}
for (i = 0; i < N/2; i++)
{
out[i*16] = in[i*16];
out[i*16 + 1] = in[i*16 + 1];
out[i*16 + 2] = in[i*16 + 2];
out[i*16 + 3] = in[i*16 + 3];
out[i*16 + 4] = in[i*16 + 4];
out[i*16 + 5] = in[i*16 + 5];
out[i*16 + 6] = in[i*16 + 6];
out[i*16 + 7] = in[i*16 + 7];
out[i*16 + 8] = in[i*16 + 8];
out[i*16 + 9] = in[i*16 + 9];
out[i*16 + 10] = in[i*16 + 10];
out[i*16 + 11] = in[i*16 + 11];
out[i*16 + 12] = in[i*16 + 12];
out[i*16 + 13] = in[i*16 + 13];
out[i*16 + 14] = in[i*16 + 14];
out[i*16 + 15] = in[i*16 + 15];
}
/* check results: */
for (i = 0; i < N/2; i++)
{
if (out[i*16] != in[i*16]
|| out[i*16 + 1] != in[i*16 + 1]
|| out[i*16 + 2] != in[i*16 + 2]
|| out[i*16 + 3] != in[i*16 + 3]
|| out[i*16 + 4] != in[i*16 + 4]
|| out[i*16 + 5] != in[i*16 + 5]
|| out[i*16 + 6] != in[i*16 + 6]
|| out[i*16 + 7] != in[i*16 + 7]
|| out[i*16 + 8] != in[i*16 + 8]
|| out[i*16 + 9] != in[i*16 + 9]
|| out[i*16 + 10] != in[i*16 + 10]
|| out[i*16 + 11] != in[i*16 + 11]
|| out[i*16 + 12] != in[i*16 + 12]
|| out[i*16 + 13] != in[i*16 + 13]
|| out[i*16 + 14] != in[i*16 + 14]
|| out[i*16 + 15] != in[i*16 + 15])
abort ();
}
/* SLP with unrolling by 8. */
for (i = 0; i < N/4; i++)
{
out[i*9] = in[i*9];
out[i*9 + 1] = in[i*9 + 1];
out[i*9 + 2] = in[i*9 + 2];
out[i*9 + 3] = in[i*9 + 3];
out[i*9 + 4] = in[i*9 + 4];
out[i*9 + 5] = in[i*9 + 5];
out[i*9 + 6] = in[i*9 + 6];
out[i*9 + 7] = in[i*9 + 7];
out[i*9 + 8] = in[i*9 + 8];
}
/* check results: */
for (i = 0; i < N/4; i++)
{
if (out[i*9] != in[i*9]
|| out[i*9 + 1] != in[i*9 + 1]
|| out[i*9 + 2] != in[i*9 + 2]
|| out[i*9 + 3] != in[i*9 + 3]
|| out[i*9 + 4] != in[i*9 + 4]
|| out[i*9 + 5] != in[i*9 + 5]
|| out[i*9 + 6] != in[i*9 + 6]
|| out[i*9 + 7] != in[i*9 + 7]
|| out[i*9 + 8] != in[i*9 + 8])
abort ();
}
return 0;
}
int main (void)
{
check_vect ();
main1 ();
return 0;
}
/* { dg-final { scan-tree-dump-times "vectorized 3 loops" 1 "vect" } } */
/* { dg-final { scan-tree-dump-times "vectorizing stmts using SLP" 3 "vect" } } */
/* { dg-final { cleanup-tree-dump "vect" } } */
| gpl-2.0 |
revel8n/dolphin | Externals/curl/lib/strdup.c | 99 | 2081 | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#include <curl/curl.h>
#include "strdup.h"
#include "curl_memory.h"
/* The last #include file should be: */
#include "memdebug.h"
#ifndef HAVE_STRDUP
char *curlx_strdup(const char *str)
{
size_t len;
char *newstr;
if(!str)
return (char *)NULL;
len = strlen(str);
if(len >= ((size_t)-1) / sizeof(char))
return (char *)NULL;
newstr = malloc((len+1)*sizeof(char));
if(!newstr)
return (char *)NULL;
memcpy(newstr, str, (len+1)*sizeof(char));
return newstr;
}
#endif
/***************************************************************************
*
* Curl_memdup(source, length)
*
* Copies the 'source' data to a newly allocated buffer (that is
* returned). Copies 'length' bytes.
*
* Returns the new pointer or NULL on failure.
*
***************************************************************************/
char *Curl_memdup(const char *src, size_t length)
{
char *buffer = malloc(length);
if(!buffer)
return NULL; /* fail */
memcpy(buffer, src, length);
return buffer;
}
| gpl-2.0 |
Hashcode/kernel_omap | fs/btrfs/file.c | 611 | 65812 | /*
* 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/pagemap.h>
#include <linux/highmem.h>
#include <linux/time.h>
#include <linux/init.h>
#include <linux/string.h>
#include <linux/backing-dev.h>
#include <linux/mpage.h>
#include <linux/aio.h>
#include <linux/falloc.h>
#include <linux/swap.h>
#include <linux/writeback.h>
#include <linux/statfs.h>
#include <linux/compat.h>
#include <linux/slab.h>
#include <linux/btrfs.h>
#include "ctree.h"
#include "disk-io.h"
#include "transaction.h"
#include "btrfs_inode.h"
#include "print-tree.h"
#include "tree-log.h"
#include "locking.h"
#include "compat.h"
#include "volumes.h"
static struct kmem_cache *btrfs_inode_defrag_cachep;
/*
* when auto defrag is enabled we
* queue up these defrag structs to remember which
* inodes need defragging passes
*/
struct inode_defrag {
struct rb_node rb_node;
/* objectid */
u64 ino;
/*
* transid where the defrag was added, we search for
* extents newer than this
*/
u64 transid;
/* root objectid */
u64 root;
/* last offset we were able to defrag */
u64 last_offset;
/* if we've wrapped around back to zero once already */
int cycled;
};
static int __compare_inode_defrag(struct inode_defrag *defrag1,
struct inode_defrag *defrag2)
{
if (defrag1->root > defrag2->root)
return 1;
else if (defrag1->root < defrag2->root)
return -1;
else if (defrag1->ino > defrag2->ino)
return 1;
else if (defrag1->ino < defrag2->ino)
return -1;
else
return 0;
}
/* pop a record for an inode into the defrag tree. The lock
* must be held already
*
* If you're inserting a record for an older transid than an
* existing record, the transid already in the tree is lowered
*
* If an existing record is found the defrag item you
* pass in is freed
*/
static int __btrfs_add_inode_defrag(struct inode *inode,
struct inode_defrag *defrag)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct inode_defrag *entry;
struct rb_node **p;
struct rb_node *parent = NULL;
int ret;
p = &root->fs_info->defrag_inodes.rb_node;
while (*p) {
parent = *p;
entry = rb_entry(parent, struct inode_defrag, rb_node);
ret = __compare_inode_defrag(defrag, entry);
if (ret < 0)
p = &parent->rb_left;
else if (ret > 0)
p = &parent->rb_right;
else {
/* if we're reinserting an entry for
* an old defrag run, make sure to
* lower the transid of our existing record
*/
if (defrag->transid < entry->transid)
entry->transid = defrag->transid;
if (defrag->last_offset > entry->last_offset)
entry->last_offset = defrag->last_offset;
return -EEXIST;
}
}
set_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags);
rb_link_node(&defrag->rb_node, parent, p);
rb_insert_color(&defrag->rb_node, &root->fs_info->defrag_inodes);
return 0;
}
static inline int __need_auto_defrag(struct btrfs_root *root)
{
if (!btrfs_test_opt(root, AUTO_DEFRAG))
return 0;
if (btrfs_fs_closing(root->fs_info))
return 0;
return 1;
}
/*
* insert a defrag record for this inode if auto defrag is
* enabled
*/
int btrfs_add_inode_defrag(struct btrfs_trans_handle *trans,
struct inode *inode)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct inode_defrag *defrag;
u64 transid;
int ret;
if (!__need_auto_defrag(root))
return 0;
if (test_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags))
return 0;
if (trans)
transid = trans->transid;
else
transid = BTRFS_I(inode)->root->last_trans;
defrag = kmem_cache_zalloc(btrfs_inode_defrag_cachep, GFP_NOFS);
if (!defrag)
return -ENOMEM;
defrag->ino = btrfs_ino(inode);
defrag->transid = transid;
defrag->root = root->root_key.objectid;
spin_lock(&root->fs_info->defrag_inodes_lock);
if (!test_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags)) {
/*
* If we set IN_DEFRAG flag and evict the inode from memory,
* and then re-read this inode, this new inode doesn't have
* IN_DEFRAG flag. At the case, we may find the existed defrag.
*/
ret = __btrfs_add_inode_defrag(inode, defrag);
if (ret)
kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
} else {
kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
}
spin_unlock(&root->fs_info->defrag_inodes_lock);
return 0;
}
/*
* Requeue the defrag object. If there is a defrag object that points to
* the same inode in the tree, we will merge them together (by
* __btrfs_add_inode_defrag()) and free the one that we want to requeue.
*/
static void btrfs_requeue_inode_defrag(struct inode *inode,
struct inode_defrag *defrag)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
int ret;
if (!__need_auto_defrag(root))
goto out;
/*
* Here we don't check the IN_DEFRAG flag, because we need merge
* them together.
*/
spin_lock(&root->fs_info->defrag_inodes_lock);
ret = __btrfs_add_inode_defrag(inode, defrag);
spin_unlock(&root->fs_info->defrag_inodes_lock);
if (ret)
goto out;
return;
out:
kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
}
/*
* pick the defragable inode that we want, if it doesn't exist, we will get
* the next one.
*/
static struct inode_defrag *
btrfs_pick_defrag_inode(struct btrfs_fs_info *fs_info, u64 root, u64 ino)
{
struct inode_defrag *entry = NULL;
struct inode_defrag tmp;
struct rb_node *p;
struct rb_node *parent = NULL;
int ret;
tmp.ino = ino;
tmp.root = root;
spin_lock(&fs_info->defrag_inodes_lock);
p = fs_info->defrag_inodes.rb_node;
while (p) {
parent = p;
entry = rb_entry(parent, struct inode_defrag, rb_node);
ret = __compare_inode_defrag(&tmp, entry);
if (ret < 0)
p = parent->rb_left;
else if (ret > 0)
p = parent->rb_right;
else
goto out;
}
if (parent && __compare_inode_defrag(&tmp, entry) > 0) {
parent = rb_next(parent);
if (parent)
entry = rb_entry(parent, struct inode_defrag, rb_node);
else
entry = NULL;
}
out:
if (entry)
rb_erase(parent, &fs_info->defrag_inodes);
spin_unlock(&fs_info->defrag_inodes_lock);
return entry;
}
void btrfs_cleanup_defrag_inodes(struct btrfs_fs_info *fs_info)
{
struct inode_defrag *defrag;
struct rb_node *node;
spin_lock(&fs_info->defrag_inodes_lock);
node = rb_first(&fs_info->defrag_inodes);
while (node) {
rb_erase(node, &fs_info->defrag_inodes);
defrag = rb_entry(node, struct inode_defrag, rb_node);
kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
if (need_resched()) {
spin_unlock(&fs_info->defrag_inodes_lock);
cond_resched();
spin_lock(&fs_info->defrag_inodes_lock);
}
node = rb_first(&fs_info->defrag_inodes);
}
spin_unlock(&fs_info->defrag_inodes_lock);
}
#define BTRFS_DEFRAG_BATCH 1024
static int __btrfs_run_defrag_inode(struct btrfs_fs_info *fs_info,
struct inode_defrag *defrag)
{
struct btrfs_root *inode_root;
struct inode *inode;
struct btrfs_key key;
struct btrfs_ioctl_defrag_range_args range;
int num_defrag;
int index;
int ret;
/* get the inode */
key.objectid = defrag->root;
btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
key.offset = (u64)-1;
index = srcu_read_lock(&fs_info->subvol_srcu);
inode_root = btrfs_read_fs_root_no_name(fs_info, &key);
if (IS_ERR(inode_root)) {
ret = PTR_ERR(inode_root);
goto cleanup;
}
if (btrfs_root_refs(&inode_root->root_item) == 0) {
ret = -ENOENT;
goto cleanup;
}
key.objectid = defrag->ino;
btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
key.offset = 0;
inode = btrfs_iget(fs_info->sb, &key, inode_root, NULL);
if (IS_ERR(inode)) {
ret = PTR_ERR(inode);
goto cleanup;
}
srcu_read_unlock(&fs_info->subvol_srcu, index);
/* do a chunk of defrag */
clear_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags);
memset(&range, 0, sizeof(range));
range.len = (u64)-1;
range.start = defrag->last_offset;
sb_start_write(fs_info->sb);
num_defrag = btrfs_defrag_file(inode, NULL, &range, defrag->transid,
BTRFS_DEFRAG_BATCH);
sb_end_write(fs_info->sb);
/*
* if we filled the whole defrag batch, there
* must be more work to do. Queue this defrag
* again
*/
if (num_defrag == BTRFS_DEFRAG_BATCH) {
defrag->last_offset = range.start;
btrfs_requeue_inode_defrag(inode, defrag);
} else if (defrag->last_offset && !defrag->cycled) {
/*
* we didn't fill our defrag batch, but
* we didn't start at zero. Make sure we loop
* around to the start of the file.
*/
defrag->last_offset = 0;
defrag->cycled = 1;
btrfs_requeue_inode_defrag(inode, defrag);
} else {
kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
}
iput(inode);
return 0;
cleanup:
srcu_read_unlock(&fs_info->subvol_srcu, index);
kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
return ret;
}
/*
* run through the list of inodes in the FS that need
* defragging
*/
int btrfs_run_defrag_inodes(struct btrfs_fs_info *fs_info)
{
struct inode_defrag *defrag;
u64 first_ino = 0;
u64 root_objectid = 0;
atomic_inc(&fs_info->defrag_running);
while(1) {
/* Pause the auto defragger. */
if (test_bit(BTRFS_FS_STATE_REMOUNTING,
&fs_info->fs_state))
break;
if (!__need_auto_defrag(fs_info->tree_root))
break;
/* find an inode to defrag */
defrag = btrfs_pick_defrag_inode(fs_info, root_objectid,
first_ino);
if (!defrag) {
if (root_objectid || first_ino) {
root_objectid = 0;
first_ino = 0;
continue;
} else {
break;
}
}
first_ino = defrag->ino + 1;
root_objectid = defrag->root;
__btrfs_run_defrag_inode(fs_info, defrag);
}
atomic_dec(&fs_info->defrag_running);
/*
* during unmount, we use the transaction_wait queue to
* wait for the defragger to stop
*/
wake_up(&fs_info->transaction_wait);
return 0;
}
/* simple helper to fault in pages and copy. This should go away
* and be replaced with calls into generic code.
*/
static noinline int btrfs_copy_from_user(loff_t pos, int num_pages,
size_t write_bytes,
struct page **prepared_pages,
struct iov_iter *i)
{
size_t copied = 0;
size_t total_copied = 0;
int pg = 0;
int offset = pos & (PAGE_CACHE_SIZE - 1);
while (write_bytes > 0) {
size_t count = min_t(size_t,
PAGE_CACHE_SIZE - offset, write_bytes);
struct page *page = prepared_pages[pg];
/*
* Copy data from userspace to the current page
*
* Disable pagefault to avoid recursive lock since
* the pages are already locked
*/
pagefault_disable();
copied = iov_iter_copy_from_user_atomic(page, i, offset, count);
pagefault_enable();
/* Flush processor's dcache for this page */
flush_dcache_page(page);
/*
* if we get a partial write, we can end up with
* partially up to date pages. These add
* a lot of complexity, so make sure they don't
* happen by forcing this copy to be retried.
*
* The rest of the btrfs_file_write code will fall
* back to page at a time copies after we return 0.
*/
if (!PageUptodate(page) && copied < count)
copied = 0;
iov_iter_advance(i, copied);
write_bytes -= copied;
total_copied += copied;
/* Return to btrfs_file_aio_write to fault page */
if (unlikely(copied == 0))
break;
if (unlikely(copied < PAGE_CACHE_SIZE - offset)) {
offset += copied;
} else {
pg++;
offset = 0;
}
}
return total_copied;
}
/*
* unlocks pages after btrfs_file_write is done with them
*/
static void btrfs_drop_pages(struct page **pages, size_t num_pages)
{
size_t i;
for (i = 0; i < num_pages; i++) {
/* page checked is some magic around finding pages that
* have been modified without going through btrfs_set_page_dirty
* clear it here
*/
ClearPageChecked(pages[i]);
unlock_page(pages[i]);
mark_page_accessed(pages[i]);
page_cache_release(pages[i]);
}
}
/*
* after copy_from_user, pages need to be dirtied and we need to make
* sure holes are created between the current EOF and the start of
* any next extents (if required).
*
* this also makes the decision about creating an inline extent vs
* doing real data extents, marking pages dirty and delalloc as required.
*/
int btrfs_dirty_pages(struct btrfs_root *root, struct inode *inode,
struct page **pages, size_t num_pages,
loff_t pos, size_t write_bytes,
struct extent_state **cached)
{
int err = 0;
int i;
u64 num_bytes;
u64 start_pos;
u64 end_of_last_block;
u64 end_pos = pos + write_bytes;
loff_t isize = i_size_read(inode);
start_pos = pos & ~((u64)root->sectorsize - 1);
num_bytes = ALIGN(write_bytes + pos - start_pos, root->sectorsize);
end_of_last_block = start_pos + num_bytes - 1;
err = btrfs_set_extent_delalloc(inode, start_pos, end_of_last_block,
cached);
if (err)
return err;
for (i = 0; i < num_pages; i++) {
struct page *p = pages[i];
SetPageUptodate(p);
ClearPageChecked(p);
set_page_dirty(p);
}
/*
* we've only changed i_size in ram, and we haven't updated
* the disk i_size. There is no need to log the inode
* at this time.
*/
if (end_pos > isize)
i_size_write(inode, end_pos);
return 0;
}
/*
* this drops all the extents in the cache that intersect the range
* [start, end]. Existing extents are split as required.
*/
void btrfs_drop_extent_cache(struct inode *inode, u64 start, u64 end,
int skip_pinned)
{
struct extent_map *em;
struct extent_map *split = NULL;
struct extent_map *split2 = NULL;
struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
u64 len = end - start + 1;
u64 gen;
int ret;
int testend = 1;
unsigned long flags;
int compressed = 0;
bool modified;
WARN_ON(end < start);
if (end == (u64)-1) {
len = (u64)-1;
testend = 0;
}
while (1) {
int no_splits = 0;
modified = false;
if (!split)
split = alloc_extent_map();
if (!split2)
split2 = alloc_extent_map();
if (!split || !split2)
no_splits = 1;
write_lock(&em_tree->lock);
em = lookup_extent_mapping(em_tree, start, len);
if (!em) {
write_unlock(&em_tree->lock);
break;
}
flags = em->flags;
gen = em->generation;
if (skip_pinned && test_bit(EXTENT_FLAG_PINNED, &em->flags)) {
if (testend && em->start + em->len >= start + len) {
free_extent_map(em);
write_unlock(&em_tree->lock);
break;
}
start = em->start + em->len;
if (testend)
len = start + len - (em->start + em->len);
free_extent_map(em);
write_unlock(&em_tree->lock);
continue;
}
compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
clear_bit(EXTENT_FLAG_PINNED, &em->flags);
clear_bit(EXTENT_FLAG_LOGGING, &flags);
modified = !list_empty(&em->list);
remove_extent_mapping(em_tree, em);
if (no_splits)
goto next;
if (em->block_start < EXTENT_MAP_LAST_BYTE &&
em->start < start) {
split->start = em->start;
split->len = start - em->start;
split->orig_start = em->orig_start;
split->block_start = em->block_start;
if (compressed)
split->block_len = em->block_len;
else
split->block_len = split->len;
split->ram_bytes = em->ram_bytes;
split->orig_block_len = max(split->block_len,
em->orig_block_len);
split->generation = gen;
split->bdev = em->bdev;
split->flags = flags;
split->compress_type = em->compress_type;
ret = add_extent_mapping(em_tree, split, modified);
BUG_ON(ret); /* Logic error */
free_extent_map(split);
split = split2;
split2 = NULL;
}
if (em->block_start < EXTENT_MAP_LAST_BYTE &&
testend && em->start + em->len > start + len) {
u64 diff = start + len - em->start;
split->start = start + len;
split->len = em->start + em->len - (start + len);
split->bdev = em->bdev;
split->flags = flags;
split->compress_type = em->compress_type;
split->generation = gen;
split->orig_block_len = max(em->block_len,
em->orig_block_len);
split->ram_bytes = em->ram_bytes;
if (compressed) {
split->block_len = em->block_len;
split->block_start = em->block_start;
split->orig_start = em->orig_start;
} else {
split->block_len = split->len;
split->block_start = em->block_start + diff;
split->orig_start = em->orig_start;
}
ret = add_extent_mapping(em_tree, split, modified);
BUG_ON(ret); /* Logic error */
free_extent_map(split);
split = NULL;
}
next:
write_unlock(&em_tree->lock);
/* once for us */
free_extent_map(em);
/* once for the tree*/
free_extent_map(em);
}
if (split)
free_extent_map(split);
if (split2)
free_extent_map(split2);
}
/*
* this is very complex, but the basic idea is to drop all extents
* in the range start - end. hint_block is filled in with a block number
* that would be a good hint to the block allocator for this file.
*
* If an extent intersects the range but is not entirely inside the range
* it is either truncated or split. Anything entirely inside the range
* is deleted from the tree.
*/
int __btrfs_drop_extents(struct btrfs_trans_handle *trans,
struct btrfs_root *root, struct inode *inode,
struct btrfs_path *path, u64 start, u64 end,
u64 *drop_end, int drop_cache)
{
struct extent_buffer *leaf;
struct btrfs_file_extent_item *fi;
struct btrfs_key key;
struct btrfs_key new_key;
u64 ino = btrfs_ino(inode);
u64 search_start = start;
u64 disk_bytenr = 0;
u64 num_bytes = 0;
u64 extent_offset = 0;
u64 extent_end = 0;
int del_nr = 0;
int del_slot = 0;
int extent_type;
int recow;
int ret;
int modify_tree = -1;
int update_refs = (root->ref_cows || root == root->fs_info->tree_root);
int found = 0;
if (drop_cache)
btrfs_drop_extent_cache(inode, start, end - 1, 0);
if (start >= BTRFS_I(inode)->disk_i_size)
modify_tree = 0;
while (1) {
recow = 0;
ret = btrfs_lookup_file_extent(trans, root, path, ino,
search_start, modify_tree);
if (ret < 0)
break;
if (ret > 0 && path->slots[0] > 0 && search_start == start) {
leaf = path->nodes[0];
btrfs_item_key_to_cpu(leaf, &key, path->slots[0] - 1);
if (key.objectid == ino &&
key.type == BTRFS_EXTENT_DATA_KEY)
path->slots[0]--;
}
ret = 0;
next_slot:
leaf = path->nodes[0];
if (path->slots[0] >= btrfs_header_nritems(leaf)) {
BUG_ON(del_nr > 0);
ret = btrfs_next_leaf(root, path);
if (ret < 0)
break;
if (ret > 0) {
ret = 0;
break;
}
leaf = path->nodes[0];
recow = 1;
}
btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
if (key.objectid > ino ||
key.type > BTRFS_EXTENT_DATA_KEY || key.offset >= end)
break;
fi = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_file_extent_item);
extent_type = btrfs_file_extent_type(leaf, fi);
if (extent_type == BTRFS_FILE_EXTENT_REG ||
extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
extent_offset = btrfs_file_extent_offset(leaf, fi);
extent_end = key.offset +
btrfs_file_extent_num_bytes(leaf, fi);
} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
extent_end = key.offset +
btrfs_file_extent_inline_len(leaf, fi);
} else {
WARN_ON(1);
extent_end = search_start;
}
if (extent_end <= search_start) {
path->slots[0]++;
goto next_slot;
}
found = 1;
search_start = max(key.offset, start);
if (recow || !modify_tree) {
modify_tree = -1;
btrfs_release_path(path);
continue;
}
/*
* | - range to drop - |
* | -------- extent -------- |
*/
if (start > key.offset && end < extent_end) {
BUG_ON(del_nr > 0);
BUG_ON(extent_type == BTRFS_FILE_EXTENT_INLINE);
memcpy(&new_key, &key, sizeof(new_key));
new_key.offset = start;
ret = btrfs_duplicate_item(trans, root, path,
&new_key);
if (ret == -EAGAIN) {
btrfs_release_path(path);
continue;
}
if (ret < 0)
break;
leaf = path->nodes[0];
fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
struct btrfs_file_extent_item);
btrfs_set_file_extent_num_bytes(leaf, fi,
start - key.offset);
fi = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_file_extent_item);
extent_offset += start - key.offset;
btrfs_set_file_extent_offset(leaf, fi, extent_offset);
btrfs_set_file_extent_num_bytes(leaf, fi,
extent_end - start);
btrfs_mark_buffer_dirty(leaf);
if (update_refs && disk_bytenr > 0) {
ret = btrfs_inc_extent_ref(trans, root,
disk_bytenr, num_bytes, 0,
root->root_key.objectid,
new_key.objectid,
start - extent_offset, 0);
BUG_ON(ret); /* -ENOMEM */
}
key.offset = start;
}
/*
* | ---- range to drop ----- |
* | -------- extent -------- |
*/
if (start <= key.offset && end < extent_end) {
BUG_ON(extent_type == BTRFS_FILE_EXTENT_INLINE);
memcpy(&new_key, &key, sizeof(new_key));
new_key.offset = end;
btrfs_set_item_key_safe(root, path, &new_key);
extent_offset += end - key.offset;
btrfs_set_file_extent_offset(leaf, fi, extent_offset);
btrfs_set_file_extent_num_bytes(leaf, fi,
extent_end - end);
btrfs_mark_buffer_dirty(leaf);
if (update_refs && disk_bytenr > 0)
inode_sub_bytes(inode, end - key.offset);
break;
}
search_start = extent_end;
/*
* | ---- range to drop ----- |
* | -------- extent -------- |
*/
if (start > key.offset && end >= extent_end) {
BUG_ON(del_nr > 0);
BUG_ON(extent_type == BTRFS_FILE_EXTENT_INLINE);
btrfs_set_file_extent_num_bytes(leaf, fi,
start - key.offset);
btrfs_mark_buffer_dirty(leaf);
if (update_refs && disk_bytenr > 0)
inode_sub_bytes(inode, extent_end - start);
if (end == extent_end)
break;
path->slots[0]++;
goto next_slot;
}
/*
* | ---- range to drop ----- |
* | ------ extent ------ |
*/
if (start <= key.offset && end >= extent_end) {
if (del_nr == 0) {
del_slot = path->slots[0];
del_nr = 1;
} else {
BUG_ON(del_slot + del_nr != path->slots[0]);
del_nr++;
}
if (update_refs &&
extent_type == BTRFS_FILE_EXTENT_INLINE) {
inode_sub_bytes(inode,
extent_end - key.offset);
extent_end = ALIGN(extent_end,
root->sectorsize);
} else if (update_refs && disk_bytenr > 0) {
ret = btrfs_free_extent(trans, root,
disk_bytenr, num_bytes, 0,
root->root_key.objectid,
key.objectid, key.offset -
extent_offset, 0);
BUG_ON(ret); /* -ENOMEM */
inode_sub_bytes(inode,
extent_end - key.offset);
}
if (end == extent_end)
break;
if (path->slots[0] + 1 < btrfs_header_nritems(leaf)) {
path->slots[0]++;
goto next_slot;
}
ret = btrfs_del_items(trans, root, path, del_slot,
del_nr);
if (ret) {
btrfs_abort_transaction(trans, root, ret);
break;
}
del_nr = 0;
del_slot = 0;
btrfs_release_path(path);
continue;
}
BUG_ON(1);
}
if (!ret && del_nr > 0) {
ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
if (ret)
btrfs_abort_transaction(trans, root, ret);
}
if (drop_end)
*drop_end = found ? min(end, extent_end) : end;
btrfs_release_path(path);
return ret;
}
int btrfs_drop_extents(struct btrfs_trans_handle *trans,
struct btrfs_root *root, struct inode *inode, u64 start,
u64 end, int drop_cache)
{
struct btrfs_path *path;
int ret;
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
ret = __btrfs_drop_extents(trans, root, inode, path, start, end, NULL,
drop_cache);
btrfs_free_path(path);
return ret;
}
static int extent_mergeable(struct extent_buffer *leaf, int slot,
u64 objectid, u64 bytenr, u64 orig_offset,
u64 *start, u64 *end)
{
struct btrfs_file_extent_item *fi;
struct btrfs_key key;
u64 extent_end;
if (slot < 0 || slot >= btrfs_header_nritems(leaf))
return 0;
btrfs_item_key_to_cpu(leaf, &key, slot);
if (key.objectid != objectid || key.type != BTRFS_EXTENT_DATA_KEY)
return 0;
fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG ||
btrfs_file_extent_disk_bytenr(leaf, fi) != bytenr ||
btrfs_file_extent_offset(leaf, fi) != key.offset - orig_offset ||
btrfs_file_extent_compression(leaf, fi) ||
btrfs_file_extent_encryption(leaf, fi) ||
btrfs_file_extent_other_encoding(leaf, fi))
return 0;
extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
if ((*start && *start != key.offset) || (*end && *end != extent_end))
return 0;
*start = key.offset;
*end = extent_end;
return 1;
}
/*
* Mark extent in the range start - end as written.
*
* This changes extent type from 'pre-allocated' to 'regular'. If only
* part of extent is marked as written, the extent will be split into
* two or three.
*/
int btrfs_mark_extent_written(struct btrfs_trans_handle *trans,
struct inode *inode, u64 start, u64 end)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct extent_buffer *leaf;
struct btrfs_path *path;
struct btrfs_file_extent_item *fi;
struct btrfs_key key;
struct btrfs_key new_key;
u64 bytenr;
u64 num_bytes;
u64 extent_end;
u64 orig_offset;
u64 other_start;
u64 other_end;
u64 split;
int del_nr = 0;
int del_slot = 0;
int recow;
int ret;
u64 ino = btrfs_ino(inode);
path = btrfs_alloc_path();
if (!path)
return -ENOMEM;
again:
recow = 0;
split = start;
key.objectid = ino;
key.type = BTRFS_EXTENT_DATA_KEY;
key.offset = split;
ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
if (ret < 0)
goto out;
if (ret > 0 && path->slots[0] > 0)
path->slots[0]--;
leaf = path->nodes[0];
btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
BUG_ON(key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY);
fi = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_file_extent_item);
BUG_ON(btrfs_file_extent_type(leaf, fi) !=
BTRFS_FILE_EXTENT_PREALLOC);
extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
BUG_ON(key.offset > start || extent_end < end);
bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
orig_offset = key.offset - btrfs_file_extent_offset(leaf, fi);
memcpy(&new_key, &key, sizeof(new_key));
if (start == key.offset && end < extent_end) {
other_start = 0;
other_end = start;
if (extent_mergeable(leaf, path->slots[0] - 1,
ino, bytenr, orig_offset,
&other_start, &other_end)) {
new_key.offset = end;
btrfs_set_item_key_safe(root, path, &new_key);
fi = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_file_extent_item);
btrfs_set_file_extent_generation(leaf, fi,
trans->transid);
btrfs_set_file_extent_num_bytes(leaf, fi,
extent_end - end);
btrfs_set_file_extent_offset(leaf, fi,
end - orig_offset);
fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
struct btrfs_file_extent_item);
btrfs_set_file_extent_generation(leaf, fi,
trans->transid);
btrfs_set_file_extent_num_bytes(leaf, fi,
end - other_start);
btrfs_mark_buffer_dirty(leaf);
goto out;
}
}
if (start > key.offset && end == extent_end) {
other_start = end;
other_end = 0;
if (extent_mergeable(leaf, path->slots[0] + 1,
ino, bytenr, orig_offset,
&other_start, &other_end)) {
fi = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_file_extent_item);
btrfs_set_file_extent_num_bytes(leaf, fi,
start - key.offset);
btrfs_set_file_extent_generation(leaf, fi,
trans->transid);
path->slots[0]++;
new_key.offset = start;
btrfs_set_item_key_safe(root, path, &new_key);
fi = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_file_extent_item);
btrfs_set_file_extent_generation(leaf, fi,
trans->transid);
btrfs_set_file_extent_num_bytes(leaf, fi,
other_end - start);
btrfs_set_file_extent_offset(leaf, fi,
start - orig_offset);
btrfs_mark_buffer_dirty(leaf);
goto out;
}
}
while (start > key.offset || end < extent_end) {
if (key.offset == start)
split = end;
new_key.offset = split;
ret = btrfs_duplicate_item(trans, root, path, &new_key);
if (ret == -EAGAIN) {
btrfs_release_path(path);
goto again;
}
if (ret < 0) {
btrfs_abort_transaction(trans, root, ret);
goto out;
}
leaf = path->nodes[0];
fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
struct btrfs_file_extent_item);
btrfs_set_file_extent_generation(leaf, fi, trans->transid);
btrfs_set_file_extent_num_bytes(leaf, fi,
split - key.offset);
fi = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_file_extent_item);
btrfs_set_file_extent_generation(leaf, fi, trans->transid);
btrfs_set_file_extent_offset(leaf, fi, split - orig_offset);
btrfs_set_file_extent_num_bytes(leaf, fi,
extent_end - split);
btrfs_mark_buffer_dirty(leaf);
ret = btrfs_inc_extent_ref(trans, root, bytenr, num_bytes, 0,
root->root_key.objectid,
ino, orig_offset, 0);
BUG_ON(ret); /* -ENOMEM */
if (split == start) {
key.offset = start;
} else {
BUG_ON(start != key.offset);
path->slots[0]--;
extent_end = end;
}
recow = 1;
}
other_start = end;
other_end = 0;
if (extent_mergeable(leaf, path->slots[0] + 1,
ino, bytenr, orig_offset,
&other_start, &other_end)) {
if (recow) {
btrfs_release_path(path);
goto again;
}
extent_end = other_end;
del_slot = path->slots[0] + 1;
del_nr++;
ret = btrfs_free_extent(trans, root, bytenr, num_bytes,
0, root->root_key.objectid,
ino, orig_offset, 0);
BUG_ON(ret); /* -ENOMEM */
}
other_start = 0;
other_end = start;
if (extent_mergeable(leaf, path->slots[0] - 1,
ino, bytenr, orig_offset,
&other_start, &other_end)) {
if (recow) {
btrfs_release_path(path);
goto again;
}
key.offset = other_start;
del_slot = path->slots[0];
del_nr++;
ret = btrfs_free_extent(trans, root, bytenr, num_bytes,
0, root->root_key.objectid,
ino, orig_offset, 0);
BUG_ON(ret); /* -ENOMEM */
}
if (del_nr == 0) {
fi = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_file_extent_item);
btrfs_set_file_extent_type(leaf, fi,
BTRFS_FILE_EXTENT_REG);
btrfs_set_file_extent_generation(leaf, fi, trans->transid);
btrfs_mark_buffer_dirty(leaf);
} else {
fi = btrfs_item_ptr(leaf, del_slot - 1,
struct btrfs_file_extent_item);
btrfs_set_file_extent_type(leaf, fi,
BTRFS_FILE_EXTENT_REG);
btrfs_set_file_extent_generation(leaf, fi, trans->transid);
btrfs_set_file_extent_num_bytes(leaf, fi,
extent_end - key.offset);
btrfs_mark_buffer_dirty(leaf);
ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
if (ret < 0) {
btrfs_abort_transaction(trans, root, ret);
goto out;
}
}
out:
btrfs_free_path(path);
return 0;
}
/*
* on error we return an unlocked page and the error value
* on success we return a locked page and 0
*/
static int prepare_uptodate_page(struct page *page, u64 pos,
bool force_uptodate)
{
int ret = 0;
if (((pos & (PAGE_CACHE_SIZE - 1)) || force_uptodate) &&
!PageUptodate(page)) {
ret = btrfs_readpage(NULL, page);
if (ret)
return ret;
lock_page(page);
if (!PageUptodate(page)) {
unlock_page(page);
return -EIO;
}
}
return 0;
}
/*
* this gets pages into the page cache and locks them down, it also properly
* waits for data=ordered extents to finish before allowing the pages to be
* modified.
*/
static noinline int prepare_pages(struct btrfs_root *root, struct file *file,
struct page **pages, size_t num_pages,
loff_t pos, unsigned long first_index,
size_t write_bytes, bool force_uptodate)
{
struct extent_state *cached_state = NULL;
int i;
unsigned long index = pos >> PAGE_CACHE_SHIFT;
struct inode *inode = file_inode(file);
gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
int err = 0;
int faili = 0;
u64 start_pos;
u64 last_pos;
start_pos = pos & ~((u64)root->sectorsize - 1);
last_pos = ((u64)index + num_pages) << PAGE_CACHE_SHIFT;
again:
for (i = 0; i < num_pages; i++) {
pages[i] = find_or_create_page(inode->i_mapping, index + i,
mask | __GFP_WRITE);
if (!pages[i]) {
faili = i - 1;
err = -ENOMEM;
goto fail;
}
if (i == 0)
err = prepare_uptodate_page(pages[i], pos,
force_uptodate);
if (i == num_pages - 1)
err = prepare_uptodate_page(pages[i],
pos + write_bytes, false);
if (err) {
page_cache_release(pages[i]);
faili = i - 1;
goto fail;
}
wait_on_page_writeback(pages[i]);
}
err = 0;
if (start_pos < inode->i_size) {
struct btrfs_ordered_extent *ordered;
lock_extent_bits(&BTRFS_I(inode)->io_tree,
start_pos, last_pos - 1, 0, &cached_state);
ordered = btrfs_lookup_first_ordered_extent(inode,
last_pos - 1);
if (ordered &&
ordered->file_offset + ordered->len > start_pos &&
ordered->file_offset < last_pos) {
btrfs_put_ordered_extent(ordered);
unlock_extent_cached(&BTRFS_I(inode)->io_tree,
start_pos, last_pos - 1,
&cached_state, GFP_NOFS);
for (i = 0; i < num_pages; i++) {
unlock_page(pages[i]);
page_cache_release(pages[i]);
}
btrfs_wait_ordered_range(inode, start_pos,
last_pos - start_pos);
goto again;
}
if (ordered)
btrfs_put_ordered_extent(ordered);
clear_extent_bit(&BTRFS_I(inode)->io_tree, start_pos,
last_pos - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
0, 0, &cached_state, GFP_NOFS);
unlock_extent_cached(&BTRFS_I(inode)->io_tree,
start_pos, last_pos - 1, &cached_state,
GFP_NOFS);
}
for (i = 0; i < num_pages; i++) {
if (clear_page_dirty_for_io(pages[i]))
account_page_redirty(pages[i]);
set_page_extent_mapped(pages[i]);
WARN_ON(!PageLocked(pages[i]));
}
return 0;
fail:
while (faili >= 0) {
unlock_page(pages[faili]);
page_cache_release(pages[faili]);
faili--;
}
return err;
}
static noinline ssize_t __btrfs_buffered_write(struct file *file,
struct iov_iter *i,
loff_t pos)
{
struct inode *inode = file_inode(file);
struct btrfs_root *root = BTRFS_I(inode)->root;
struct page **pages = NULL;
unsigned long first_index;
size_t num_written = 0;
int nrptrs;
int ret = 0;
bool force_page_uptodate = false;
nrptrs = min((iov_iter_count(i) + PAGE_CACHE_SIZE - 1) /
PAGE_CACHE_SIZE, PAGE_CACHE_SIZE /
(sizeof(struct page *)));
nrptrs = min(nrptrs, current->nr_dirtied_pause - current->nr_dirtied);
nrptrs = max(nrptrs, 8);
pages = kmalloc(nrptrs * sizeof(struct page *), GFP_KERNEL);
if (!pages)
return -ENOMEM;
first_index = pos >> PAGE_CACHE_SHIFT;
while (iov_iter_count(i) > 0) {
size_t offset = pos & (PAGE_CACHE_SIZE - 1);
size_t write_bytes = min(iov_iter_count(i),
nrptrs * (size_t)PAGE_CACHE_SIZE -
offset);
size_t num_pages = (write_bytes + offset +
PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
size_t dirty_pages;
size_t copied;
WARN_ON(num_pages > nrptrs);
/*
* Fault pages before locking them in prepare_pages
* to avoid recursive lock
*/
if (unlikely(iov_iter_fault_in_readable(i, write_bytes))) {
ret = -EFAULT;
break;
}
ret = btrfs_delalloc_reserve_space(inode,
num_pages << PAGE_CACHE_SHIFT);
if (ret)
break;
/*
* This is going to setup the pages array with the number of
* pages we want, so we don't really need to worry about the
* contents of pages from loop to loop
*/
ret = prepare_pages(root, file, pages, num_pages,
pos, first_index, write_bytes,
force_page_uptodate);
if (ret) {
btrfs_delalloc_release_space(inode,
num_pages << PAGE_CACHE_SHIFT);
break;
}
copied = btrfs_copy_from_user(pos, num_pages,
write_bytes, pages, i);
/*
* if we have trouble faulting in the pages, fall
* back to one page at a time
*/
if (copied < write_bytes)
nrptrs = 1;
if (copied == 0) {
force_page_uptodate = true;
dirty_pages = 0;
} else {
force_page_uptodate = false;
dirty_pages = (copied + offset +
PAGE_CACHE_SIZE - 1) >>
PAGE_CACHE_SHIFT;
}
/*
* If we had a short copy we need to release the excess delaloc
* bytes we reserved. We need to increment outstanding_extents
* because btrfs_delalloc_release_space will decrement it, but
* we still have an outstanding extent for the chunk we actually
* managed to copy.
*/
if (num_pages > dirty_pages) {
if (copied > 0) {
spin_lock(&BTRFS_I(inode)->lock);
BTRFS_I(inode)->outstanding_extents++;
spin_unlock(&BTRFS_I(inode)->lock);
}
btrfs_delalloc_release_space(inode,
(num_pages - dirty_pages) <<
PAGE_CACHE_SHIFT);
}
if (copied > 0) {
ret = btrfs_dirty_pages(root, inode, pages,
dirty_pages, pos, copied,
NULL);
if (ret) {
btrfs_delalloc_release_space(inode,
dirty_pages << PAGE_CACHE_SHIFT);
btrfs_drop_pages(pages, num_pages);
break;
}
}
btrfs_drop_pages(pages, num_pages);
cond_resched();
balance_dirty_pages_ratelimited(inode->i_mapping);
if (dirty_pages < (root->leafsize >> PAGE_CACHE_SHIFT) + 1)
btrfs_btree_balance_dirty(root);
pos += copied;
num_written += copied;
}
kfree(pages);
return num_written ? num_written : ret;
}
static ssize_t __btrfs_direct_write(struct kiocb *iocb,
const struct iovec *iov,
unsigned long nr_segs, loff_t pos,
loff_t *ppos, size_t count, size_t ocount)
{
struct file *file = iocb->ki_filp;
struct iov_iter i;
ssize_t written;
ssize_t written_buffered;
loff_t endbyte;
int err;
written = generic_file_direct_write(iocb, iov, &nr_segs, pos, ppos,
count, ocount);
if (written < 0 || written == count)
return written;
pos += written;
count -= written;
iov_iter_init(&i, iov, nr_segs, count, written);
written_buffered = __btrfs_buffered_write(file, &i, pos);
if (written_buffered < 0) {
err = written_buffered;
goto out;
}
endbyte = pos + written_buffered - 1;
err = filemap_write_and_wait_range(file->f_mapping, pos, endbyte);
if (err)
goto out;
written += written_buffered;
*ppos = pos + written_buffered;
invalidate_mapping_pages(file->f_mapping, pos >> PAGE_CACHE_SHIFT,
endbyte >> PAGE_CACHE_SHIFT);
out:
return written ? written : err;
}
static void update_time_for_write(struct inode *inode)
{
struct timespec now;
if (IS_NOCMTIME(inode))
return;
now = current_fs_time(inode->i_sb);
if (!timespec_equal(&inode->i_mtime, &now))
inode->i_mtime = now;
if (!timespec_equal(&inode->i_ctime, &now))
inode->i_ctime = now;
if (IS_I_VERSION(inode))
inode_inc_iversion(inode);
}
static ssize_t btrfs_file_aio_write(struct kiocb *iocb,
const struct iovec *iov,
unsigned long nr_segs, loff_t pos)
{
struct file *file = iocb->ki_filp;
struct inode *inode = file_inode(file);
struct btrfs_root *root = BTRFS_I(inode)->root;
loff_t *ppos = &iocb->ki_pos;
u64 start_pos;
ssize_t num_written = 0;
ssize_t err = 0;
size_t count, ocount;
bool sync = (file->f_flags & O_DSYNC) || IS_SYNC(file->f_mapping->host);
mutex_lock(&inode->i_mutex);
err = generic_segment_checks(iov, &nr_segs, &ocount, VERIFY_READ);
if (err) {
mutex_unlock(&inode->i_mutex);
goto out;
}
count = ocount;
current->backing_dev_info = inode->i_mapping->backing_dev_info;
err = generic_write_checks(file, &pos, &count, S_ISBLK(inode->i_mode));
if (err) {
mutex_unlock(&inode->i_mutex);
goto out;
}
if (count == 0) {
mutex_unlock(&inode->i_mutex);
goto out;
}
err = file_remove_suid(file);
if (err) {
mutex_unlock(&inode->i_mutex);
goto out;
}
/*
* If BTRFS flips readonly due to some impossible error
* (fs_info->fs_state now has BTRFS_SUPER_FLAG_ERROR),
* although we have opened a file as writable, we have
* to stop this write operation to ensure FS consistency.
*/
if (test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state)) {
mutex_unlock(&inode->i_mutex);
err = -EROFS;
goto out;
}
/*
* We reserve space for updating the inode when we reserve space for the
* extent we are going to write, so we will enospc out there. We don't
* need to start yet another transaction to update the inode as we will
* update the inode when we finish writing whatever data we write.
*/
update_time_for_write(inode);
start_pos = round_down(pos, root->sectorsize);
if (start_pos > i_size_read(inode)) {
err = btrfs_cont_expand(inode, i_size_read(inode), start_pos);
if (err) {
mutex_unlock(&inode->i_mutex);
goto out;
}
}
if (sync)
atomic_inc(&BTRFS_I(inode)->sync_writers);
if (unlikely(file->f_flags & O_DIRECT)) {
num_written = __btrfs_direct_write(iocb, iov, nr_segs,
pos, ppos, count, ocount);
} else {
struct iov_iter i;
iov_iter_init(&i, iov, nr_segs, count, num_written);
num_written = __btrfs_buffered_write(file, &i, pos);
if (num_written > 0)
*ppos = pos + num_written;
}
mutex_unlock(&inode->i_mutex);
/*
* We also have to set last_sub_trans to the current log transid,
* otherwise subsequent syncs to a file that's been synced in this
* transaction will appear to have already occured.
*/
BTRFS_I(inode)->last_sub_trans = root->log_transid;
if (num_written > 0 || num_written == -EIOCBQUEUED) {
err = generic_write_sync(file, pos, num_written);
if (err < 0 && num_written > 0)
num_written = err;
}
if (sync)
atomic_dec(&BTRFS_I(inode)->sync_writers);
out:
current->backing_dev_info = NULL;
return num_written ? num_written : err;
}
int btrfs_release_file(struct inode *inode, struct file *filp)
{
/*
* ordered_data_close is set by settattr when we are about to truncate
* a file from a non-zero size to a zero size. This tries to
* flush down new bytes that may have been written if the
* application were using truncate to replace a file in place.
*/
if (test_and_clear_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
&BTRFS_I(inode)->runtime_flags)) {
struct btrfs_trans_handle *trans;
struct btrfs_root *root = BTRFS_I(inode)->root;
/*
* We need to block on a committing transaction to keep us from
* throwing a ordered operation on to the list and causing
* something like sync to deadlock trying to flush out this
* inode.
*/
trans = btrfs_start_transaction(root, 0);
if (IS_ERR(trans))
return PTR_ERR(trans);
btrfs_add_ordered_operation(trans, BTRFS_I(inode)->root, inode);
btrfs_end_transaction(trans, root);
if (inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
filemap_flush(inode->i_mapping);
}
if (filp->private_data)
btrfs_ioctl_trans_end(filp);
return 0;
}
/*
* fsync call for both files and directories. This logs the inode into
* the tree log instead of forcing full commits whenever possible.
*
* It needs to call filemap_fdatawait so that all ordered extent updates are
* in the metadata btree are up to date for copying to the log.
*
* It drops the inode mutex before doing the tree log commit. This is an
* important optimization for directories because holding the mutex prevents
* new operations on the dir while we write to disk.
*/
int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
{
struct dentry *dentry = file->f_path.dentry;
struct inode *inode = dentry->d_inode;
struct btrfs_root *root = BTRFS_I(inode)->root;
int ret = 0;
struct btrfs_trans_handle *trans;
bool full_sync = 0;
trace_btrfs_sync_file(file, datasync);
/*
* We write the dirty pages in the range and wait until they complete
* out of the ->i_mutex. If so, we can flush the dirty pages by
* multi-task, and make the performance up. See
* btrfs_wait_ordered_range for an explanation of the ASYNC check.
*/
atomic_inc(&BTRFS_I(inode)->sync_writers);
ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
if (!ret && test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
&BTRFS_I(inode)->runtime_flags))
ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
atomic_dec(&BTRFS_I(inode)->sync_writers);
if (ret)
return ret;
mutex_lock(&inode->i_mutex);
/*
* We flush the dirty pages again to avoid some dirty pages in the
* range being left.
*/
atomic_inc(&root->log_batch);
full_sync = test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
&BTRFS_I(inode)->runtime_flags);
if (full_sync)
btrfs_wait_ordered_range(inode, start, end - start + 1);
atomic_inc(&root->log_batch);
/*
* If the last transaction that changed this file was before the current
* transaction and we have the full sync flag set in our inode, we can
* bail out now without any syncing.
*
* Note that we can't bail out if the full sync flag isn't set. This is
* because when the full sync flag is set we start all ordered extents
* and wait for them to fully complete - when they complete they update
* the inode's last_trans field through:
*
* btrfs_finish_ordered_io() ->
* btrfs_update_inode_fallback() ->
* btrfs_update_inode() ->
* btrfs_set_inode_last_trans()
*
* So we are sure that last_trans is up to date and can do this check to
* bail out safely. For the fast path, when the full sync flag is not
* set in our inode, we can not do it because we start only our ordered
* extents and don't wait for them to complete (that is when
* btrfs_finish_ordered_io runs), so here at this point their last_trans
* value might be less than or equals to fs_info->last_trans_committed,
* and setting a speculative last_trans for an inode when a buffered
* write is made (such as fs_info->generation + 1 for example) would not
* be reliable since after setting the value and before fsync is called
* any number of transactions can start and commit (transaction kthread
* commits the current transaction periodically), and a transaction
* commit does not start nor waits for ordered extents to complete.
*/
smp_mb();
if (btrfs_inode_in_log(inode, root->fs_info->generation) ||
(full_sync && BTRFS_I(inode)->last_trans <=
root->fs_info->last_trans_committed)) {
/*
* We'v had everything committed since the last time we were
* modified so clear this flag in case it was set for whatever
* reason, it's no longer relevant.
*/
clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
&BTRFS_I(inode)->runtime_flags);
mutex_unlock(&inode->i_mutex);
goto out;
}
/*
* ok we haven't committed the transaction yet, lets do a commit
*/
if (file->private_data)
btrfs_ioctl_trans_end(file);
trans = btrfs_start_transaction(root, 0);
if (IS_ERR(trans)) {
ret = PTR_ERR(trans);
mutex_unlock(&inode->i_mutex);
goto out;
}
ret = btrfs_log_dentry_safe(trans, root, dentry);
if (ret < 0) {
mutex_unlock(&inode->i_mutex);
goto out;
}
/* we've logged all the items and now have a consistent
* version of the file in the log. It is possible that
* someone will come in and modify the file, but that's
* fine because the log is consistent on disk, and we
* have references to all of the file's extents
*
* It is possible that someone will come in and log the
* file again, but that will end up using the synchronization
* inside btrfs_sync_log to keep things safe.
*/
mutex_unlock(&inode->i_mutex);
if (ret != BTRFS_NO_LOG_SYNC) {
if (ret > 0) {
/*
* If we didn't already wait for ordered extents we need
* to do that now.
*/
if (!full_sync)
btrfs_wait_ordered_range(inode, start,
end - start + 1);
ret = btrfs_commit_transaction(trans, root);
} else {
ret = btrfs_sync_log(trans, root);
if (ret == 0) {
ret = btrfs_end_transaction(trans, root);
} else {
if (!full_sync)
btrfs_wait_ordered_range(inode, start,
end -
start + 1);
ret = btrfs_commit_transaction(trans, root);
}
}
} else {
ret = btrfs_end_transaction(trans, root);
}
out:
return ret > 0 ? -EIO : ret;
}
static const struct vm_operations_struct btrfs_file_vm_ops = {
.fault = filemap_fault,
.page_mkwrite = btrfs_page_mkwrite,
.remap_pages = generic_file_remap_pages,
};
static int btrfs_file_mmap(struct file *filp, struct vm_area_struct *vma)
{
struct address_space *mapping = filp->f_mapping;
if (!mapping->a_ops->readpage)
return -ENOEXEC;
file_accessed(filp);
vma->vm_ops = &btrfs_file_vm_ops;
return 0;
}
static int hole_mergeable(struct inode *inode, struct extent_buffer *leaf,
int slot, u64 start, u64 end)
{
struct btrfs_file_extent_item *fi;
struct btrfs_key key;
if (slot < 0 || slot >= btrfs_header_nritems(leaf))
return 0;
btrfs_item_key_to_cpu(leaf, &key, slot);
if (key.objectid != btrfs_ino(inode) ||
key.type != BTRFS_EXTENT_DATA_KEY)
return 0;
fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
return 0;
if (btrfs_file_extent_disk_bytenr(leaf, fi))
return 0;
if (key.offset == end)
return 1;
if (key.offset + btrfs_file_extent_num_bytes(leaf, fi) == start)
return 1;
return 0;
}
static int fill_holes(struct btrfs_trans_handle *trans, struct inode *inode,
struct btrfs_path *path, u64 offset, u64 end)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct extent_buffer *leaf;
struct btrfs_file_extent_item *fi;
struct extent_map *hole_em;
struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
struct btrfs_key key;
int ret;
key.objectid = btrfs_ino(inode);
key.type = BTRFS_EXTENT_DATA_KEY;
key.offset = offset;
ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
if (ret < 0)
return ret;
BUG_ON(!ret);
leaf = path->nodes[0];
if (hole_mergeable(inode, leaf, path->slots[0]-1, offset, end)) {
u64 num_bytes;
path->slots[0]--;
fi = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_file_extent_item);
num_bytes = btrfs_file_extent_num_bytes(leaf, fi) +
end - offset;
btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
btrfs_set_file_extent_offset(leaf, fi, 0);
btrfs_mark_buffer_dirty(leaf);
goto out;
}
if (hole_mergeable(inode, leaf, path->slots[0]+1, offset, end)) {
u64 num_bytes;
path->slots[0]++;
key.offset = offset;
btrfs_set_item_key_safe(root, path, &key);
fi = btrfs_item_ptr(leaf, path->slots[0],
struct btrfs_file_extent_item);
num_bytes = btrfs_file_extent_num_bytes(leaf, fi) + end -
offset;
btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
btrfs_set_file_extent_offset(leaf, fi, 0);
btrfs_mark_buffer_dirty(leaf);
goto out;
}
btrfs_release_path(path);
ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset,
0, 0, end - offset, 0, end - offset,
0, 0, 0);
if (ret)
return ret;
out:
btrfs_release_path(path);
hole_em = alloc_extent_map();
if (!hole_em) {
btrfs_drop_extent_cache(inode, offset, end - 1, 0);
set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
&BTRFS_I(inode)->runtime_flags);
} else {
hole_em->start = offset;
hole_em->len = end - offset;
hole_em->ram_bytes = hole_em->len;
hole_em->orig_start = offset;
hole_em->block_start = EXTENT_MAP_HOLE;
hole_em->block_len = 0;
hole_em->orig_block_len = 0;
hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
hole_em->compress_type = BTRFS_COMPRESS_NONE;
hole_em->generation = trans->transid;
do {
btrfs_drop_extent_cache(inode, offset, end - 1, 0);
write_lock(&em_tree->lock);
ret = add_extent_mapping(em_tree, hole_em, 1);
write_unlock(&em_tree->lock);
} while (ret == -EEXIST);
free_extent_map(hole_em);
if (ret)
set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
&BTRFS_I(inode)->runtime_flags);
}
return 0;
}
static int btrfs_punch_hole(struct inode *inode, loff_t offset, loff_t len)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct extent_state *cached_state = NULL;
struct btrfs_path *path;
struct btrfs_block_rsv *rsv;
struct btrfs_trans_handle *trans;
u64 lockstart = round_up(offset, BTRFS_I(inode)->root->sectorsize);
u64 lockend = round_down(offset + len,
BTRFS_I(inode)->root->sectorsize) - 1;
u64 cur_offset = lockstart;
u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
u64 drop_end;
int ret = 0;
int err = 0;
bool same_page = ((offset >> PAGE_CACHE_SHIFT) ==
((offset + len - 1) >> PAGE_CACHE_SHIFT));
btrfs_wait_ordered_range(inode, offset, len);
mutex_lock(&inode->i_mutex);
/*
* We needn't truncate any page which is beyond the end of the file
* because we are sure there is no data there.
*/
/*
* Only do this if we are in the same page and we aren't doing the
* entire page.
*/
if (same_page && len < PAGE_CACHE_SIZE) {
if (offset < round_up(inode->i_size, PAGE_CACHE_SIZE))
ret = btrfs_truncate_page(inode, offset, len, 0);
mutex_unlock(&inode->i_mutex);
return ret;
}
/* zero back part of the first page */
if (offset < round_up(inode->i_size, PAGE_CACHE_SIZE)) {
ret = btrfs_truncate_page(inode, offset, 0, 0);
if (ret) {
mutex_unlock(&inode->i_mutex);
return ret;
}
}
/* zero the front end of the last page */
if (offset + len < round_up(inode->i_size, PAGE_CACHE_SIZE)) {
ret = btrfs_truncate_page(inode, offset + len, 0, 1);
if (ret) {
mutex_unlock(&inode->i_mutex);
return ret;
}
}
if (lockend < lockstart) {
mutex_unlock(&inode->i_mutex);
return 0;
}
while (1) {
struct btrfs_ordered_extent *ordered;
truncate_pagecache_range(inode, lockstart, lockend);
lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
0, &cached_state);
ordered = btrfs_lookup_first_ordered_extent(inode, lockend);
/*
* We need to make sure we have no ordered extents in this range
* and nobody raced in and read a page in this range, if we did
* we need to try again.
*/
if ((!ordered ||
(ordered->file_offset + ordered->len < lockstart ||
ordered->file_offset > lockend)) &&
!test_range_bit(&BTRFS_I(inode)->io_tree, lockstart,
lockend, EXTENT_UPTODATE, 0,
cached_state)) {
if (ordered)
btrfs_put_ordered_extent(ordered);
break;
}
if (ordered)
btrfs_put_ordered_extent(ordered);
unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart,
lockend, &cached_state, GFP_NOFS);
btrfs_wait_ordered_range(inode, lockstart,
lockend - lockstart + 1);
}
path = btrfs_alloc_path();
if (!path) {
ret = -ENOMEM;
goto out;
}
rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
if (!rsv) {
ret = -ENOMEM;
goto out_free;
}
rsv->size = btrfs_calc_trunc_metadata_size(root, 1);
rsv->failfast = 1;
/*
* 1 - update the inode
* 1 - removing the extents in the range
* 1 - adding the hole extent
*/
trans = btrfs_start_transaction(root, 3);
if (IS_ERR(trans)) {
err = PTR_ERR(trans);
goto out_free;
}
ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
min_size);
BUG_ON(ret);
trans->block_rsv = rsv;
while (cur_offset < lockend) {
ret = __btrfs_drop_extents(trans, root, inode, path,
cur_offset, lockend + 1,
&drop_end, 1);
if (ret != -ENOSPC)
break;
trans->block_rsv = &root->fs_info->trans_block_rsv;
ret = fill_holes(trans, inode, path, cur_offset, drop_end);
if (ret) {
err = ret;
break;
}
cur_offset = drop_end;
ret = btrfs_update_inode(trans, root, inode);
if (ret) {
err = ret;
break;
}
btrfs_end_transaction(trans, root);
btrfs_btree_balance_dirty(root);
trans = btrfs_start_transaction(root, 3);
if (IS_ERR(trans)) {
ret = PTR_ERR(trans);
trans = NULL;
break;
}
ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
rsv, min_size);
BUG_ON(ret); /* shouldn't happen */
trans->block_rsv = rsv;
}
if (ret) {
err = ret;
goto out_trans;
}
trans->block_rsv = &root->fs_info->trans_block_rsv;
ret = fill_holes(trans, inode, path, cur_offset, drop_end);
if (ret) {
err = ret;
goto out_trans;
}
out_trans:
if (!trans)
goto out_free;
inode_inc_iversion(inode);
inode->i_mtime = inode->i_ctime = CURRENT_TIME;
trans->block_rsv = &root->fs_info->trans_block_rsv;
ret = btrfs_update_inode(trans, root, inode);
btrfs_end_transaction(trans, root);
btrfs_btree_balance_dirty(root);
out_free:
btrfs_free_path(path);
btrfs_free_block_rsv(root, rsv);
out:
unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
&cached_state, GFP_NOFS);
mutex_unlock(&inode->i_mutex);
if (ret && !err)
err = ret;
return err;
}
static long btrfs_fallocate(struct file *file, int mode,
loff_t offset, loff_t len)
{
struct inode *inode = file_inode(file);
struct extent_state *cached_state = NULL;
struct btrfs_root *root = BTRFS_I(inode)->root;
u64 cur_offset;
u64 last_byte;
u64 alloc_start;
u64 alloc_end;
u64 alloc_hint = 0;
u64 locked_end;
struct extent_map *em;
int blocksize = BTRFS_I(inode)->root->sectorsize;
int ret;
alloc_start = round_down(offset, blocksize);
alloc_end = round_up(offset + len, blocksize);
/* Make sure we aren't being give some crap mode */
if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
return -EOPNOTSUPP;
if (mode & FALLOC_FL_PUNCH_HOLE)
return btrfs_punch_hole(inode, offset, len);
/*
* Make sure we have enough space before we do the
* allocation.
*/
ret = btrfs_check_data_free_space(inode, alloc_end - alloc_start);
if (ret)
return ret;
if (root->fs_info->quota_enabled) {
ret = btrfs_qgroup_reserve(root, alloc_end - alloc_start);
if (ret)
goto out_reserve_fail;
}
/*
* wait for ordered IO before we have any locks. We'll loop again
* below with the locks held.
*/
btrfs_wait_ordered_range(inode, alloc_start, alloc_end - alloc_start);
mutex_lock(&inode->i_mutex);
ret = inode_newsize_ok(inode, alloc_end);
if (ret)
goto out;
if (alloc_start > inode->i_size) {
ret = btrfs_cont_expand(inode, i_size_read(inode),
alloc_start);
if (ret)
goto out;
}
locked_end = alloc_end - 1;
while (1) {
struct btrfs_ordered_extent *ordered;
/* the extent lock is ordered inside the running
* transaction
*/
lock_extent_bits(&BTRFS_I(inode)->io_tree, alloc_start,
locked_end, 0, &cached_state);
ordered = btrfs_lookup_first_ordered_extent(inode,
alloc_end - 1);
if (ordered &&
ordered->file_offset + ordered->len > alloc_start &&
ordered->file_offset < alloc_end) {
btrfs_put_ordered_extent(ordered);
unlock_extent_cached(&BTRFS_I(inode)->io_tree,
alloc_start, locked_end,
&cached_state, GFP_NOFS);
/*
* we can't wait on the range with the transaction
* running or with the extent lock held
*/
btrfs_wait_ordered_range(inode, alloc_start,
alloc_end - alloc_start);
} else {
if (ordered)
btrfs_put_ordered_extent(ordered);
break;
}
}
cur_offset = alloc_start;
while (1) {
u64 actual_end;
em = btrfs_get_extent(inode, NULL, 0, cur_offset,
alloc_end - cur_offset, 0);
if (IS_ERR_OR_NULL(em)) {
if (!em)
ret = -ENOMEM;
else
ret = PTR_ERR(em);
break;
}
last_byte = min(extent_map_end(em), alloc_end);
actual_end = min_t(u64, extent_map_end(em), offset + len);
last_byte = ALIGN(last_byte, blocksize);
if (em->block_start == EXTENT_MAP_HOLE ||
(cur_offset >= inode->i_size &&
!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
ret = btrfs_prealloc_file_range(inode, mode, cur_offset,
last_byte - cur_offset,
1 << inode->i_blkbits,
offset + len,
&alloc_hint);
if (ret < 0) {
free_extent_map(em);
break;
}
} else if (actual_end > inode->i_size &&
!(mode & FALLOC_FL_KEEP_SIZE)) {
/*
* We didn't need to allocate any more space, but we
* still extended the size of the file so we need to
* update i_size.
*/
inode->i_ctime = CURRENT_TIME;
i_size_write(inode, actual_end);
btrfs_ordered_update_i_size(inode, actual_end, NULL);
}
free_extent_map(em);
cur_offset = last_byte;
if (cur_offset >= alloc_end) {
ret = 0;
break;
}
}
unlock_extent_cached(&BTRFS_I(inode)->io_tree, alloc_start, locked_end,
&cached_state, GFP_NOFS);
out:
mutex_unlock(&inode->i_mutex);
if (root->fs_info->quota_enabled)
btrfs_qgroup_free(root, alloc_end - alloc_start);
out_reserve_fail:
/* Let go of our reservation. */
btrfs_free_reserved_data_space(inode, alloc_end - alloc_start);
return ret;
}
static int find_desired_extent(struct inode *inode, loff_t *offset, int whence)
{
struct btrfs_root *root = BTRFS_I(inode)->root;
struct extent_map *em;
struct extent_state *cached_state = NULL;
u64 lockstart = *offset;
u64 lockend = i_size_read(inode);
u64 start = *offset;
u64 orig_start = *offset;
u64 len = i_size_read(inode);
u64 last_end = 0;
int ret = 0;
lockend = max_t(u64, root->sectorsize, lockend);
if (lockend <= lockstart)
lockend = lockstart + root->sectorsize;
lockend--;
len = lockend - lockstart + 1;
len = max_t(u64, len, root->sectorsize);
if (inode->i_size == 0)
return -ENXIO;
lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend, 0,
&cached_state);
/*
* Delalloc is such a pain. If we have a hole and we have pending
* delalloc for a portion of the hole we will get back a hole that
* exists for the entire range since it hasn't been actually written
* yet. So to take care of this case we need to look for an extent just
* before the position we want in case there is outstanding delalloc
* going on here.
*/
if (whence == SEEK_HOLE && start != 0) {
if (start <= root->sectorsize)
em = btrfs_get_extent_fiemap(inode, NULL, 0, 0,
root->sectorsize, 0);
else
em = btrfs_get_extent_fiemap(inode, NULL, 0,
start - root->sectorsize,
root->sectorsize, 0);
if (IS_ERR(em)) {
ret = PTR_ERR(em);
goto out;
}
last_end = em->start + em->len;
if (em->block_start == EXTENT_MAP_DELALLOC)
last_end = min_t(u64, last_end, inode->i_size);
free_extent_map(em);
}
while (1) {
em = btrfs_get_extent_fiemap(inode, NULL, 0, start, len, 0);
if (IS_ERR(em)) {
ret = PTR_ERR(em);
break;
}
if (em->block_start == EXTENT_MAP_HOLE) {
if (test_bit(EXTENT_FLAG_VACANCY, &em->flags)) {
if (last_end <= orig_start) {
free_extent_map(em);
ret = -ENXIO;
break;
}
}
if (whence == SEEK_HOLE) {
*offset = start;
free_extent_map(em);
break;
}
} else {
if (whence == SEEK_DATA) {
if (em->block_start == EXTENT_MAP_DELALLOC) {
if (start >= inode->i_size) {
free_extent_map(em);
ret = -ENXIO;
break;
}
}
if (!test_bit(EXTENT_FLAG_PREALLOC,
&em->flags)) {
*offset = start;
free_extent_map(em);
break;
}
}
}
start = em->start + em->len;
last_end = em->start + em->len;
if (em->block_start == EXTENT_MAP_DELALLOC)
last_end = min_t(u64, last_end, inode->i_size);
if (test_bit(EXTENT_FLAG_VACANCY, &em->flags)) {
free_extent_map(em);
ret = -ENXIO;
break;
}
free_extent_map(em);
cond_resched();
}
if (!ret)
*offset = min(*offset, inode->i_size);
out:
unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
&cached_state, GFP_NOFS);
return ret;
}
static loff_t btrfs_file_llseek(struct file *file, loff_t offset, int whence)
{
struct inode *inode = file->f_mapping->host;
int ret;
mutex_lock(&inode->i_mutex);
switch (whence) {
case SEEK_END:
case SEEK_CUR:
offset = generic_file_llseek(file, offset, whence);
goto out;
case SEEK_DATA:
case SEEK_HOLE:
if (offset >= i_size_read(inode)) {
mutex_unlock(&inode->i_mutex);
return -ENXIO;
}
ret = find_desired_extent(inode, &offset, whence);
if (ret) {
mutex_unlock(&inode->i_mutex);
return ret;
}
}
if (offset < 0 && !(file->f_mode & FMODE_UNSIGNED_OFFSET)) {
offset = -EINVAL;
goto out;
}
if (offset > inode->i_sb->s_maxbytes) {
offset = -EINVAL;
goto out;
}
/* Special lock needed here? */
if (offset != file->f_pos) {
file->f_pos = offset;
file->f_version = 0;
}
out:
mutex_unlock(&inode->i_mutex);
return offset;
}
const struct file_operations btrfs_file_operations = {
.llseek = btrfs_file_llseek,
.read = do_sync_read,
.write = do_sync_write,
.aio_read = generic_file_aio_read,
.splice_read = generic_file_splice_read,
.aio_write = btrfs_file_aio_write,
.mmap = btrfs_file_mmap,
.open = generic_file_open,
.release = btrfs_release_file,
.fsync = btrfs_sync_file,
.fallocate = btrfs_fallocate,
.unlocked_ioctl = btrfs_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = btrfs_ioctl,
#endif
};
void btrfs_auto_defrag_exit(void)
{
if (btrfs_inode_defrag_cachep)
kmem_cache_destroy(btrfs_inode_defrag_cachep);
}
int btrfs_auto_defrag_init(void)
{
btrfs_inode_defrag_cachep = kmem_cache_create("btrfs_inode_defrag",
sizeof(struct inode_defrag), 0,
SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
NULL);
if (!btrfs_inode_defrag_cachep)
return -ENOMEM;
return 0;
}
| gpl-2.0 |
BPI-SINOVOIP/BPI-Mainline-kernel | linux-5.4/drivers/input/touchscreen/mk712.c | 611 | 5688 | // SPDX-License-Identifier: GPL-2.0-only
/*
* ICS MK712 touchscreen controller driver
*
* Copyright (c) 1999-2002 Transmeta Corporation
* Copyright (c) 2005 Rick Koch <n1gp@hotmail.com>
* Copyright (c) 2005 Vojtech Pavlik <vojtech@suse.cz>
*/
/*
* This driver supports the ICS MicroClock MK712 TouchScreen controller,
* found in Gateway AOL Connected Touchpad computers.
*
* Documentation for ICS MK712 can be found at:
* https://www.idt.com/general-parts/mk712-touch-screen-controller
*/
/*
* 1999-12-18: original version, Daniel Quinlan
* 1999-12-19: added anti-jitter code, report pen-up events, fixed mk712_poll
* to use queue_empty, Nathan Laredo
* 1999-12-20: improved random point rejection, Nathan Laredo
* 2000-01-05: checked in new anti-jitter code, changed mouse protocol, fixed
* queue code, added module options, other fixes, Daniel Quinlan
* 2002-03-15: Clean up for kernel merge <alan@redhat.com>
* Fixed multi open race, fixed memory checks, fixed resource
* allocation, fixed close/powerdown bug, switched to new init
* 2005-01-18: Ported to 2.6 from 2.4.28, Rick Koch
* 2005-02-05: Rewritten for the input layer, Vojtech Pavlik
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/delay.h>
#include <linux/ioport.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#include <asm/io.h>
MODULE_AUTHOR("Daniel Quinlan <quinlan@pathname.com>, Vojtech Pavlik <vojtech@suse.cz>");
MODULE_DESCRIPTION("ICS MicroClock MK712 TouchScreen driver");
MODULE_LICENSE("GPL");
static unsigned int mk712_io = 0x260; /* Also 0x200, 0x208, 0x300 */
module_param_hw_named(io, mk712_io, uint, ioport, 0);
MODULE_PARM_DESC(io, "I/O base address of MK712 touchscreen controller");
static unsigned int mk712_irq = 10; /* Also 12, 14, 15 */
module_param_hw_named(irq, mk712_irq, uint, irq, 0);
MODULE_PARM_DESC(irq, "IRQ of MK712 touchscreen controller");
/* eight 8-bit registers */
#define MK712_STATUS 0
#define MK712_X 2
#define MK712_Y 4
#define MK712_CONTROL 6
#define MK712_RATE 7
/* status */
#define MK712_STATUS_TOUCH 0x10
#define MK712_CONVERSION_COMPLETE 0x80
/* control */
#define MK712_ENABLE_INT 0x01
#define MK712_INT_ON_CONVERSION_COMPLETE 0x02
#define MK712_INT_ON_CHANGE_IN_TOUCH_STATUS 0x04
#define MK712_ENABLE_PERIODIC_CONVERSIONS 0x10
#define MK712_READ_ONE_POINT 0x20
#define MK712_POWERUP 0x40
static struct input_dev *mk712_dev;
static DEFINE_SPINLOCK(mk712_lock);
static irqreturn_t mk712_interrupt(int irq, void *dev_id)
{
unsigned char status;
static int debounce = 1;
static unsigned short last_x;
static unsigned short last_y;
spin_lock(&mk712_lock);
status = inb(mk712_io + MK712_STATUS);
if (~status & MK712_CONVERSION_COMPLETE) {
debounce = 1;
goto end;
}
if (~status & MK712_STATUS_TOUCH) {
debounce = 1;
input_report_key(mk712_dev, BTN_TOUCH, 0);
goto end;
}
if (debounce) {
debounce = 0;
goto end;
}
input_report_key(mk712_dev, BTN_TOUCH, 1);
input_report_abs(mk712_dev, ABS_X, last_x);
input_report_abs(mk712_dev, ABS_Y, last_y);
end:
last_x = inw(mk712_io + MK712_X) & 0x0fff;
last_y = inw(mk712_io + MK712_Y) & 0x0fff;
input_sync(mk712_dev);
spin_unlock(&mk712_lock);
return IRQ_HANDLED;
}
static int mk712_open(struct input_dev *dev)
{
unsigned long flags;
spin_lock_irqsave(&mk712_lock, flags);
outb(0, mk712_io + MK712_CONTROL); /* Reset */
outb(MK712_ENABLE_INT | MK712_INT_ON_CONVERSION_COMPLETE |
MK712_INT_ON_CHANGE_IN_TOUCH_STATUS |
MK712_ENABLE_PERIODIC_CONVERSIONS |
MK712_POWERUP, mk712_io + MK712_CONTROL);
outb(10, mk712_io + MK712_RATE); /* 187 points per second */
spin_unlock_irqrestore(&mk712_lock, flags);
return 0;
}
static void mk712_close(struct input_dev *dev)
{
unsigned long flags;
spin_lock_irqsave(&mk712_lock, flags);
outb(0, mk712_io + MK712_CONTROL);
spin_unlock_irqrestore(&mk712_lock, flags);
}
static int __init mk712_init(void)
{
int err;
if (!request_region(mk712_io, 8, "mk712")) {
printk(KERN_WARNING "mk712: unable to get IO region\n");
return -ENODEV;
}
outb(0, mk712_io + MK712_CONTROL);
if ((inw(mk712_io + MK712_X) & 0xf000) || /* Sanity check */
(inw(mk712_io + MK712_Y) & 0xf000) ||
(inw(mk712_io + MK712_STATUS) & 0xf333)) {
printk(KERN_WARNING "mk712: device not present\n");
err = -ENODEV;
goto fail1;
}
mk712_dev = input_allocate_device();
if (!mk712_dev) {
printk(KERN_ERR "mk712: not enough memory\n");
err = -ENOMEM;
goto fail1;
}
mk712_dev->name = "ICS MicroClock MK712 TouchScreen";
mk712_dev->phys = "isa0260/input0";
mk712_dev->id.bustype = BUS_ISA;
mk712_dev->id.vendor = 0x0005;
mk712_dev->id.product = 0x0001;
mk712_dev->id.version = 0x0100;
mk712_dev->open = mk712_open;
mk712_dev->close = mk712_close;
mk712_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
mk712_dev->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH);
input_set_abs_params(mk712_dev, ABS_X, 0, 0xfff, 88, 0);
input_set_abs_params(mk712_dev, ABS_Y, 0, 0xfff, 88, 0);
if (request_irq(mk712_irq, mk712_interrupt, 0, "mk712", mk712_dev)) {
printk(KERN_WARNING "mk712: unable to get IRQ\n");
err = -EBUSY;
goto fail1;
}
err = input_register_device(mk712_dev);
if (err)
goto fail2;
return 0;
fail2: free_irq(mk712_irq, mk712_dev);
fail1: input_free_device(mk712_dev);
release_region(mk712_io, 8);
return err;
}
static void __exit mk712_exit(void)
{
input_unregister_device(mk712_dev);
free_irq(mk712_irq, mk712_dev);
release_region(mk712_io, 8);
}
module_init(mk712_init);
module_exit(mk712_exit);
| gpl-2.0 |
1DeMaCr/android_hd_kernel_samsung_codina | drivers/regulator/tps6524x-regulator.c | 1635 | 15862 | /*
* Regulator driver for TPS6524x PMIC
*
* Copyright (C) 2010 Texas Instruments
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation version 2.
*
* This program is distributed "as is" WITHOUT ANY WARRANTY of any kind,
* whether express or implied; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/err.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/spi/spi.h>
#include <linux/regulator/driver.h>
#include <linux/regulator/machine.h>
#define REG_LDO_SET 0x0
#define LDO_ILIM_MASK 1 /* 0 = 400-800, 1 = 900-1500 */
#define LDO_VSEL_MASK 0x0f
#define LDO2_ILIM_SHIFT 12
#define LDO2_VSEL_SHIFT 4
#define LDO1_ILIM_SHIFT 8
#define LDO1_VSEL_SHIFT 0
#define REG_BLOCK_EN 0x1
#define BLOCK_MASK 1
#define BLOCK_LDO1_SHIFT 0
#define BLOCK_LDO2_SHIFT 1
#define BLOCK_LCD_SHIFT 2
#define BLOCK_USB_SHIFT 3
#define REG_DCDC_SET 0x2
#define DCDC_VDCDC_MASK 0x1f
#define DCDC_VDCDC1_SHIFT 0
#define DCDC_VDCDC2_SHIFT 5
#define DCDC_VDCDC3_SHIFT 10
#define REG_DCDC_EN 0x3
#define DCDCDCDC_EN_MASK 0x1
#define DCDCDCDC1_EN_SHIFT 0
#define DCDCDCDC1_PG_MSK BIT(1)
#define DCDCDCDC2_EN_SHIFT 2
#define DCDCDCDC2_PG_MSK BIT(3)
#define DCDCDCDC3_EN_SHIFT 4
#define DCDCDCDC3_PG_MSK BIT(5)
#define REG_USB 0x4
#define USB_ILIM_SHIFT 0
#define USB_ILIM_MASK 0x3
#define USB_TSD_SHIFT 2
#define USB_TSD_MASK 0x3
#define USB_TWARN_SHIFT 4
#define USB_TWARN_MASK 0x3
#define USB_IWARN_SD BIT(6)
#define USB_FAST_LOOP BIT(7)
#define REG_ALARM 0x5
#define ALARM_LDO1 BIT(0)
#define ALARM_DCDC1 BIT(1)
#define ALARM_DCDC2 BIT(2)
#define ALARM_DCDC3 BIT(3)
#define ALARM_LDO2 BIT(4)
#define ALARM_USB_WARN BIT(5)
#define ALARM_USB_ALARM BIT(6)
#define ALARM_LCD BIT(9)
#define ALARM_TEMP_WARM BIT(10)
#define ALARM_TEMP_HOT BIT(11)
#define ALARM_NRST BIT(14)
#define ALARM_POWERUP BIT(15)
#define REG_INT_ENABLE 0x6
#define INT_LDO1 BIT(0)
#define INT_DCDC1 BIT(1)
#define INT_DCDC2 BIT(2)
#define INT_DCDC3 BIT(3)
#define INT_LDO2 BIT(4)
#define INT_USB_WARN BIT(5)
#define INT_USB_ALARM BIT(6)
#define INT_LCD BIT(9)
#define INT_TEMP_WARM BIT(10)
#define INT_TEMP_HOT BIT(11)
#define INT_GLOBAL_EN BIT(15)
#define REG_INT_STATUS 0x7
#define STATUS_LDO1 BIT(0)
#define STATUS_DCDC1 BIT(1)
#define STATUS_DCDC2 BIT(2)
#define STATUS_DCDC3 BIT(3)
#define STATUS_LDO2 BIT(4)
#define STATUS_USB_WARN BIT(5)
#define STATUS_USB_ALARM BIT(6)
#define STATUS_LCD BIT(9)
#define STATUS_TEMP_WARM BIT(10)
#define STATUS_TEMP_HOT BIT(11)
#define REG_SOFTWARE_RESET 0xb
#define REG_WRITE_ENABLE 0xd
#define REG_REV_ID 0xf
#define N_DCDC 3
#define N_LDO 2
#define N_SWITCH 2
#define N_REGULATORS (3 /* DCDC */ + \
2 /* LDO */ + \
2 /* switch */)
#define FIXED_ILIMSEL BIT(0)
#define FIXED_VOLTAGE BIT(1)
#define CMD_READ(reg) ((reg) << 6)
#define CMD_WRITE(reg) (BIT(5) | (reg) << 6)
#define STAT_CLK BIT(3)
#define STAT_WRITE BIT(2)
#define STAT_INVALID BIT(1)
#define STAT_WP BIT(0)
struct field {
int reg;
int shift;
int mask;
};
struct supply_info {
const char *name;
int n_voltages;
const int *voltages;
int fixed_voltage;
int n_ilimsels;
const int *ilimsels;
int fixed_ilimsel;
int flags;
struct field enable, voltage, ilimsel;
};
struct tps6524x {
struct device *dev;
struct spi_device *spi;
struct mutex lock;
struct regulator_desc desc[N_REGULATORS];
struct regulator_dev *rdev[N_REGULATORS];
};
static int __read_reg(struct tps6524x *hw, int reg)
{
int error = 0;
u16 cmd = CMD_READ(reg), in;
u8 status;
struct spi_message m;
struct spi_transfer t[3];
spi_message_init(&m);
memset(t, 0, sizeof(t));
t[0].tx_buf = &cmd;
t[0].len = 2;
t[0].bits_per_word = 12;
spi_message_add_tail(&t[0], &m);
t[1].rx_buf = ∈
t[1].len = 2;
t[1].bits_per_word = 16;
spi_message_add_tail(&t[1], &m);
t[2].rx_buf = &status;
t[2].len = 1;
t[2].bits_per_word = 4;
spi_message_add_tail(&t[2], &m);
error = spi_sync(hw->spi, &m);
if (error < 0)
return error;
dev_dbg(hw->dev, "read reg %d, data %x, status %x\n",
reg, in, status);
if (!(status & STAT_CLK) || (status & STAT_WRITE))
return -EIO;
if (status & STAT_INVALID)
return -EINVAL;
return in;
}
static int read_reg(struct tps6524x *hw, int reg)
{
int ret;
mutex_lock(&hw->lock);
ret = __read_reg(hw, reg);
mutex_unlock(&hw->lock);
return ret;
}
static int __write_reg(struct tps6524x *hw, int reg, int val)
{
int error = 0;
u16 cmd = CMD_WRITE(reg), out = val;
u8 status;
struct spi_message m;
struct spi_transfer t[3];
spi_message_init(&m);
memset(t, 0, sizeof(t));
t[0].tx_buf = &cmd;
t[0].len = 2;
t[0].bits_per_word = 12;
spi_message_add_tail(&t[0], &m);
t[1].tx_buf = &out;
t[1].len = 2;
t[1].bits_per_word = 16;
spi_message_add_tail(&t[1], &m);
t[2].rx_buf = &status;
t[2].len = 1;
t[2].bits_per_word = 4;
spi_message_add_tail(&t[2], &m);
error = spi_sync(hw->spi, &m);
if (error < 0)
return error;
dev_dbg(hw->dev, "wrote reg %d, data %x, status %x\n",
reg, out, status);
if (!(status & STAT_CLK) || !(status & STAT_WRITE))
return -EIO;
if (status & (STAT_INVALID | STAT_WP))
return -EINVAL;
return error;
}
static int __rmw_reg(struct tps6524x *hw, int reg, int mask, int val)
{
int ret;
ret = __read_reg(hw, reg);
if (ret < 0)
return ret;
ret &= ~mask;
ret |= val;
ret = __write_reg(hw, reg, ret);
return (ret < 0) ? ret : 0;
}
static int rmw_protect(struct tps6524x *hw, int reg, int mask, int val)
{
int ret;
mutex_lock(&hw->lock);
ret = __write_reg(hw, REG_WRITE_ENABLE, 1);
if (ret) {
dev_err(hw->dev, "failed to set write enable\n");
goto error;
}
ret = __rmw_reg(hw, reg, mask, val);
if (ret)
dev_err(hw->dev, "failed to rmw register %d\n", reg);
ret = __write_reg(hw, REG_WRITE_ENABLE, 0);
if (ret) {
dev_err(hw->dev, "failed to clear write enable\n");
goto error;
}
error:
mutex_unlock(&hw->lock);
return ret;
}
static int read_field(struct tps6524x *hw, const struct field *field)
{
int tmp;
tmp = read_reg(hw, field->reg);
if (tmp < 0)
return tmp;
return (tmp >> field->shift) & field->mask;
}
static int write_field(struct tps6524x *hw, const struct field *field,
int val)
{
if (val & ~field->mask)
return -EOVERFLOW;
return rmw_protect(hw, field->reg,
field->mask << field->shift,
val << field->shift);
}
static const int dcdc1_voltages[] = {
800000, 825000, 850000, 875000,
900000, 925000, 950000, 975000,
1000000, 1025000, 1050000, 1075000,
1100000, 1125000, 1150000, 1175000,
1200000, 1225000, 1250000, 1275000,
1300000, 1325000, 1350000, 1375000,
1400000, 1425000, 1450000, 1475000,
1500000, 1525000, 1550000, 1575000,
};
static const int dcdc2_voltages[] = {
1400000, 1450000, 1500000, 1550000,
1600000, 1650000, 1700000, 1750000,
1800000, 1850000, 1900000, 1950000,
2000000, 2050000, 2100000, 2150000,
2200000, 2250000, 2300000, 2350000,
2400000, 2450000, 2500000, 2550000,
2600000, 2650000, 2700000, 2750000,
2800000, 2850000, 2900000, 2950000,
};
static const int dcdc3_voltages[] = {
2400000, 2450000, 2500000, 2550000, 2600000,
2650000, 2700000, 2750000, 2800000, 2850000,
2900000, 2950000, 3000000, 3050000, 3100000,
3150000, 3200000, 3250000, 3300000, 3350000,
3400000, 3450000, 3500000, 3550000, 3600000,
};
static const int ldo1_voltages[] = {
4300000, 4350000, 4400000, 4450000,
4500000, 4550000, 4600000, 4650000,
4700000, 4750000, 4800000, 4850000,
4900000, 4950000, 5000000, 5050000,
};
static const int ldo2_voltages[] = {
1100000, 1150000, 1200000, 1250000,
1300000, 1700000, 1750000, 1800000,
1850000, 1900000, 3150000, 3200000,
3250000, 3300000, 3350000, 3400000,
};
static const int ldo_ilimsel[] = {
400000, 1500000
};
static const int usb_ilimsel[] = {
200000, 400000, 800000, 1000000
};
#define __MK_FIELD(_reg, _mask, _shift) \
{ .reg = (_reg), .mask = (_mask), .shift = (_shift), }
static const struct supply_info supply_info[N_REGULATORS] = {
{
.name = "DCDC1",
.flags = FIXED_ILIMSEL,
.n_voltages = ARRAY_SIZE(dcdc1_voltages),
.voltages = dcdc1_voltages,
.fixed_ilimsel = 2400000,
.enable = __MK_FIELD(REG_DCDC_EN, DCDCDCDC_EN_MASK,
DCDCDCDC1_EN_SHIFT),
.voltage = __MK_FIELD(REG_DCDC_SET, DCDC_VDCDC_MASK,
DCDC_VDCDC1_SHIFT),
},
{
.name = "DCDC2",
.flags = FIXED_ILIMSEL,
.n_voltages = ARRAY_SIZE(dcdc2_voltages),
.voltages = dcdc2_voltages,
.fixed_ilimsel = 1200000,
.enable = __MK_FIELD(REG_DCDC_EN, DCDCDCDC_EN_MASK,
DCDCDCDC2_EN_SHIFT),
.voltage = __MK_FIELD(REG_DCDC_SET, DCDC_VDCDC_MASK,
DCDC_VDCDC2_SHIFT),
},
{
.name = "DCDC3",
.flags = FIXED_ILIMSEL,
.n_voltages = ARRAY_SIZE(dcdc3_voltages),
.voltages = dcdc3_voltages,
.fixed_ilimsel = 1200000,
.enable = __MK_FIELD(REG_DCDC_EN, DCDCDCDC_EN_MASK,
DCDCDCDC3_EN_SHIFT),
.voltage = __MK_FIELD(REG_DCDC_SET, DCDC_VDCDC_MASK,
DCDC_VDCDC3_SHIFT),
},
{
.name = "LDO1",
.n_voltages = ARRAY_SIZE(ldo1_voltages),
.voltages = ldo1_voltages,
.n_ilimsels = ARRAY_SIZE(ldo_ilimsel),
.ilimsels = ldo_ilimsel,
.enable = __MK_FIELD(REG_BLOCK_EN, BLOCK_MASK,
BLOCK_LDO1_SHIFT),
.voltage = __MK_FIELD(REG_LDO_SET, LDO_VSEL_MASK,
LDO1_VSEL_SHIFT),
.ilimsel = __MK_FIELD(REG_LDO_SET, LDO_ILIM_MASK,
LDO1_ILIM_SHIFT),
},
{
.name = "LDO2",
.n_voltages = ARRAY_SIZE(ldo2_voltages),
.voltages = ldo2_voltages,
.n_ilimsels = ARRAY_SIZE(ldo_ilimsel),
.ilimsels = ldo_ilimsel,
.enable = __MK_FIELD(REG_BLOCK_EN, BLOCK_MASK,
BLOCK_LDO2_SHIFT),
.voltage = __MK_FIELD(REG_LDO_SET, LDO_VSEL_MASK,
LDO2_VSEL_SHIFT),
.ilimsel = __MK_FIELD(REG_LDO_SET, LDO_ILIM_MASK,
LDO2_ILIM_SHIFT),
},
{
.name = "USB",
.flags = FIXED_VOLTAGE,
.fixed_voltage = 5000000,
.n_ilimsels = ARRAY_SIZE(usb_ilimsel),
.ilimsels = usb_ilimsel,
.enable = __MK_FIELD(REG_BLOCK_EN, BLOCK_MASK,
BLOCK_USB_SHIFT),
.ilimsel = __MK_FIELD(REG_USB, USB_ILIM_MASK,
USB_ILIM_SHIFT),
},
{
.name = "LCD",
.flags = FIXED_VOLTAGE | FIXED_ILIMSEL,
.fixed_voltage = 5000000,
.fixed_ilimsel = 400000,
.enable = __MK_FIELD(REG_BLOCK_EN, BLOCK_MASK,
BLOCK_LCD_SHIFT),
},
};
static int list_voltage(struct regulator_dev *rdev, unsigned selector)
{
const struct supply_info *info;
struct tps6524x *hw;
hw = rdev_get_drvdata(rdev);
info = &supply_info[rdev_get_id(rdev)];
if (info->flags & FIXED_VOLTAGE)
return selector ? -EINVAL : info->fixed_voltage;
return ((selector < info->n_voltages) ?
info->voltages[selector] : -EINVAL);
}
static int set_voltage(struct regulator_dev *rdev, int min_uV, int max_uV,
unsigned *selector)
{
const struct supply_info *info;
struct tps6524x *hw;
unsigned i;
hw = rdev_get_drvdata(rdev);
info = &supply_info[rdev_get_id(rdev)];
if (info->flags & FIXED_VOLTAGE)
return -EINVAL;
for (i = 0; i < info->n_voltages; i++)
if (min_uV <= info->voltages[i] &&
max_uV >= info->voltages[i])
break;
if (i >= info->n_voltages)
i = info->n_voltages - 1;
*selector = i;
return write_field(hw, &info->voltage, i);
}
static int get_voltage(struct regulator_dev *rdev)
{
const struct supply_info *info;
struct tps6524x *hw;
int ret;
hw = rdev_get_drvdata(rdev);
info = &supply_info[rdev_get_id(rdev)];
if (info->flags & FIXED_VOLTAGE)
return info->fixed_voltage;
ret = read_field(hw, &info->voltage);
if (ret < 0)
return ret;
if (WARN_ON(ret >= info->n_voltages))
return -EIO;
return info->voltages[ret];
}
static int set_current_limit(struct regulator_dev *rdev, int min_uA,
int max_uA)
{
const struct supply_info *info;
struct tps6524x *hw;
int i;
hw = rdev_get_drvdata(rdev);
info = &supply_info[rdev_get_id(rdev)];
if (info->flags & FIXED_ILIMSEL)
return -EINVAL;
for (i = 0; i < info->n_ilimsels; i++)
if (min_uA <= info->ilimsels[i] &&
max_uA >= info->ilimsels[i])
break;
if (i >= info->n_ilimsels)
return -EINVAL;
return write_field(hw, &info->ilimsel, i);
}
static int get_current_limit(struct regulator_dev *rdev)
{
const struct supply_info *info;
struct tps6524x *hw;
int ret;
hw = rdev_get_drvdata(rdev);
info = &supply_info[rdev_get_id(rdev)];
if (info->flags & FIXED_ILIMSEL)
return info->fixed_ilimsel;
ret = read_field(hw, &info->ilimsel);
if (ret < 0)
return ret;
if (WARN_ON(ret >= info->n_ilimsels))
return -EIO;
return info->ilimsels[ret];
}
static int enable_supply(struct regulator_dev *rdev)
{
const struct supply_info *info;
struct tps6524x *hw;
hw = rdev_get_drvdata(rdev);
info = &supply_info[rdev_get_id(rdev)];
return write_field(hw, &info->enable, 1);
}
static int disable_supply(struct regulator_dev *rdev)
{
const struct supply_info *info;
struct tps6524x *hw;
hw = rdev_get_drvdata(rdev);
info = &supply_info[rdev_get_id(rdev)];
return write_field(hw, &info->enable, 0);
}
static int is_supply_enabled(struct regulator_dev *rdev)
{
const struct supply_info *info;
struct tps6524x *hw;
hw = rdev_get_drvdata(rdev);
info = &supply_info[rdev_get_id(rdev)];
return read_field(hw, &info->enable);
}
static struct regulator_ops regulator_ops = {
.is_enabled = is_supply_enabled,
.enable = enable_supply,
.disable = disable_supply,
.get_voltage = get_voltage,
.set_voltage = set_voltage,
.list_voltage = list_voltage,
.set_current_limit = set_current_limit,
.get_current_limit = get_current_limit,
};
static int pmic_remove(struct spi_device *spi)
{
struct tps6524x *hw = spi_get_drvdata(spi);
int i;
if (!hw)
return 0;
for (i = 0; i < N_REGULATORS; i++) {
if (hw->rdev[i])
regulator_unregister(hw->rdev[i]);
hw->rdev[i] = NULL;
}
spi_set_drvdata(spi, NULL);
kfree(hw);
return 0;
}
static int __devinit pmic_probe(struct spi_device *spi)
{
struct tps6524x *hw;
struct device *dev = &spi->dev;
const struct supply_info *info = supply_info;
struct regulator_init_data *init_data;
int ret = 0, i;
init_data = dev->platform_data;
if (!init_data) {
dev_err(dev, "could not find regulator platform data\n");
return -EINVAL;
}
hw = kzalloc(sizeof(struct tps6524x), GFP_KERNEL);
if (!hw) {
dev_err(dev, "cannot allocate regulator private data\n");
return -ENOMEM;
}
spi_set_drvdata(spi, hw);
memset(hw, 0, sizeof(struct tps6524x));
hw->dev = dev;
hw->spi = spi_dev_get(spi);
mutex_init(&hw->lock);
for (i = 0; i < N_REGULATORS; i++, info++, init_data++) {
hw->desc[i].name = info->name;
hw->desc[i].id = i;
hw->desc[i].n_voltages = info->n_voltages;
hw->desc[i].ops = ®ulator_ops;
hw->desc[i].type = REGULATOR_VOLTAGE;
hw->desc[i].owner = THIS_MODULE;
if (info->flags & FIXED_VOLTAGE)
hw->desc[i].n_voltages = 1;
hw->rdev[i] = regulator_register(&hw->desc[i], dev,
init_data, hw);
if (IS_ERR(hw->rdev[i])) {
ret = PTR_ERR(hw->rdev[i]);
hw->rdev[i] = NULL;
goto fail;
}
}
return 0;
fail:
pmic_remove(spi);
return ret;
}
static struct spi_driver pmic_driver = {
.probe = pmic_probe,
.remove = __devexit_p(pmic_remove),
.driver = {
.name = "tps6524x",
.owner = THIS_MODULE,
},
};
static int __init pmic_driver_init(void)
{
return spi_register_driver(&pmic_driver);
}
module_init(pmic_driver_init);
static void __exit pmic_driver_exit(void)
{
spi_unregister_driver(&pmic_driver);
}
module_exit(pmic_driver_exit);
MODULE_DESCRIPTION("TPS6524X PMIC Driver");
MODULE_AUTHOR("Cyril Chemparathy");
MODULE_LICENSE("GPL");
MODULE_ALIAS("spi:tps6524x");
| gpl-2.0 |
djmax81/Hani_Kernel_Exynos5433 | fs/logfs/dir.c | 2147 | 21221 | /*
* fs/logfs/dir.c - directory-related code
*
* As should be obvious for Linux kernel code, license is GPLv2
*
* Copyright (c) 2005-2008 Joern Engel <joern@logfs.org>
*/
#include "logfs.h"
#include <linux/slab.h>
/*
* Atomic dir operations
*
* Directory operations are by default not atomic. Dentries and Inodes are
* created/removed/altered in separate operations. Therefore we need to do
* a small amount of journaling.
*
* Create, link, mkdir, mknod and symlink all share the same function to do
* the work: __logfs_create. This function works in two atomic steps:
* 1. allocate inode (remember in journal)
* 2. allocate dentry (clear journal)
*
* As we can only get interrupted between the two, when the inode we just
* created is simply stored in the anchor. On next mount, if we were
* interrupted, we delete the inode. From a users point of view the
* operation never happened.
*
* Unlink and rmdir also share the same function: unlink. Again, this
* function works in two atomic steps
* 1. remove dentry (remember inode in journal)
* 2. unlink inode (clear journal)
*
* And again, on the next mount, if we were interrupted, we delete the inode.
* From a users point of view the operation succeeded.
*
* Rename is the real pain to deal with, harder than all the other methods
* combined. Depending on the circumstances we can run into three cases.
* A "target rename" where the target dentry already existed, a "local
* rename" where both parent directories are identical or a "cross-directory
* rename" in the remaining case.
*
* Local rename is atomic, as the old dentry is simply rewritten with a new
* name.
*
* Cross-directory rename works in two steps, similar to __logfs_create and
* logfs_unlink:
* 1. Write new dentry (remember old dentry in journal)
* 2. Remove old dentry (clear journal)
*
* Here we remember a dentry instead of an inode. On next mount, if we were
* interrupted, we delete the dentry. From a users point of view, the
* operation succeeded.
*
* Target rename works in three atomic steps:
* 1. Attach old inode to new dentry (remember old dentry and new inode)
* 2. Remove old dentry (still remember the new inode)
* 3. Remove victim inode
*
* Here we remember both an inode an a dentry. If we get interrupted
* between steps 1 and 2, we delete both the dentry and the inode. If
* we get interrupted between steps 2 and 3, we delete just the inode.
* In either case, the remaining objects are deleted on next mount. From
* a users point of view, the operation succeeded.
*/
static int write_dir(struct inode *dir, struct logfs_disk_dentry *dd,
loff_t pos)
{
return logfs_inode_write(dir, dd, sizeof(*dd), pos, WF_LOCK, NULL);
}
static int write_inode(struct inode *inode)
{
return __logfs_write_inode(inode, NULL, WF_LOCK);
}
static s64 dir_seek_data(struct inode *inode, s64 pos)
{
s64 new_pos = logfs_seek_data(inode, pos);
return max(pos, new_pos - 1);
}
static int beyond_eof(struct inode *inode, loff_t bix)
{
loff_t pos = bix << inode->i_sb->s_blocksize_bits;
return pos >= i_size_read(inode);
}
/*
* Prime value was chosen to be roughly 256 + 26. r5 hash uses 11,
* so short names (len <= 9) don't even occupy the complete 32bit name
* space. A prime >256 ensures short names quickly spread the 32bit
* name space. Add about 26 for the estimated amount of information
* of each character and pick a prime nearby, preferably a bit-sparse
* one.
*/
static u32 hash_32(const char *s, int len, u32 seed)
{
u32 hash = seed;
int i;
for (i = 0; i < len; i++)
hash = hash * 293 + s[i];
return hash;
}
/*
* We have to satisfy several conflicting requirements here. Small
* directories should stay fairly compact and not require too many
* indirect blocks. The number of possible locations for a given hash
* should be small to make lookup() fast. And we should try hard not
* to overflow the 32bit name space or nfs and 32bit host systems will
* be unhappy.
*
* So we use the following scheme. First we reduce the hash to 0..15
* and try a direct block. If that is occupied we reduce the hash to
* 16..255 and try an indirect block. Same for 2x and 3x indirect
* blocks. Lastly we reduce the hash to 0x800_0000 .. 0xffff_ffff,
* but use buckets containing eight entries instead of a single one.
*
* Using 16 entries should allow for a reasonable amount of hash
* collisions, so the 32bit name space can be packed fairly tight
* before overflowing. Oh and currently we don't overflow but return
* and error.
*
* How likely are collisions? Doing the appropriate math is beyond me
* and the Bronstein textbook. But running a test program to brute
* force collisions for a couple of days showed that on average the
* first collision occurs after 598M entries, with 290M being the
* smallest result. Obviously 21 entries could already cause a
* collision if all entries are carefully chosen.
*/
static pgoff_t hash_index(u32 hash, int round)
{
u32 i0_blocks = I0_BLOCKS;
u32 i1_blocks = I1_BLOCKS;
u32 i2_blocks = I2_BLOCKS;
u32 i3_blocks = I3_BLOCKS;
switch (round) {
case 0:
return hash % i0_blocks;
case 1:
return i0_blocks + hash % (i1_blocks - i0_blocks);
case 2:
return i1_blocks + hash % (i2_blocks - i1_blocks);
case 3:
return i2_blocks + hash % (i3_blocks - i2_blocks);
case 4 ... 19:
return i3_blocks + 16 * (hash % (((1<<31) - i3_blocks) / 16))
+ round - 4;
}
BUG();
}
static struct page *logfs_get_dd_page(struct inode *dir, struct dentry *dentry)
{
struct qstr *name = &dentry->d_name;
struct page *page;
struct logfs_disk_dentry *dd;
u32 hash = hash_32(name->name, name->len, 0);
pgoff_t index;
int round;
if (name->len > LOGFS_MAX_NAMELEN)
return ERR_PTR(-ENAMETOOLONG);
for (round = 0; round < 20; round++) {
index = hash_index(hash, round);
if (beyond_eof(dir, index))
return NULL;
if (!logfs_exist_block(dir, index))
continue;
page = read_cache_page(dir->i_mapping, index,
(filler_t *)logfs_readpage, NULL);
if (IS_ERR(page))
return page;
dd = kmap_atomic(page);
BUG_ON(dd->namelen == 0);
if (name->len != be16_to_cpu(dd->namelen) ||
memcmp(name->name, dd->name, name->len)) {
kunmap_atomic(dd);
page_cache_release(page);
continue;
}
kunmap_atomic(dd);
return page;
}
return NULL;
}
static int logfs_remove_inode(struct inode *inode)
{
int ret;
drop_nlink(inode);
ret = write_inode(inode);
LOGFS_BUG_ON(ret, inode->i_sb);
return ret;
}
static void abort_transaction(struct inode *inode, struct logfs_transaction *ta)
{
if (logfs_inode(inode)->li_block)
logfs_inode(inode)->li_block->ta = NULL;
kfree(ta);
}
static int logfs_unlink(struct inode *dir, struct dentry *dentry)
{
struct logfs_super *super = logfs_super(dir->i_sb);
struct inode *inode = dentry->d_inode;
struct logfs_transaction *ta;
struct page *page;
pgoff_t index;
int ret;
ta = kzalloc(sizeof(*ta), GFP_KERNEL);
if (!ta)
return -ENOMEM;
ta->state = UNLINK_1;
ta->ino = inode->i_ino;
inode->i_ctime = dir->i_ctime = dir->i_mtime = CURRENT_TIME;
page = logfs_get_dd_page(dir, dentry);
if (!page) {
kfree(ta);
return -ENOENT;
}
if (IS_ERR(page)) {
kfree(ta);
return PTR_ERR(page);
}
index = page->index;
page_cache_release(page);
mutex_lock(&super->s_dirop_mutex);
logfs_add_transaction(dir, ta);
ret = logfs_delete(dir, index, NULL);
if (!ret)
ret = write_inode(dir);
if (ret) {
abort_transaction(dir, ta);
printk(KERN_ERR"LOGFS: unable to delete inode\n");
goto out;
}
ta->state = UNLINK_2;
logfs_add_transaction(inode, ta);
ret = logfs_remove_inode(inode);
out:
mutex_unlock(&super->s_dirop_mutex);
return ret;
}
static inline int logfs_empty_dir(struct inode *dir)
{
u64 data;
data = logfs_seek_data(dir, 0) << dir->i_sb->s_blocksize_bits;
return data >= i_size_read(dir);
}
static int logfs_rmdir(struct inode *dir, struct dentry *dentry)
{
struct inode *inode = dentry->d_inode;
if (!logfs_empty_dir(inode))
return -ENOTEMPTY;
return logfs_unlink(dir, dentry);
}
/* FIXME: readdir currently has it's own dir_walk code. I don't see a good
* way to combine the two copies */
#define IMPLICIT_NODES 2
static int __logfs_readdir(struct file *file, void *buf, filldir_t filldir)
{
struct inode *dir = file_inode(file);
loff_t pos = file->f_pos - IMPLICIT_NODES;
struct page *page;
struct logfs_disk_dentry *dd;
int full;
BUG_ON(pos < 0);
for (;; pos++) {
if (beyond_eof(dir, pos))
break;
if (!logfs_exist_block(dir, pos)) {
/* deleted dentry */
pos = dir_seek_data(dir, pos);
continue;
}
page = read_cache_page(dir->i_mapping, pos,
(filler_t *)logfs_readpage, NULL);
if (IS_ERR(page))
return PTR_ERR(page);
dd = kmap(page);
BUG_ON(dd->namelen == 0);
full = filldir(buf, (char *)dd->name, be16_to_cpu(dd->namelen),
pos, be64_to_cpu(dd->ino), dd->type);
kunmap(page);
page_cache_release(page);
if (full)
break;
}
file->f_pos = pos + IMPLICIT_NODES;
return 0;
}
static int logfs_readdir(struct file *file, void *buf, filldir_t filldir)
{
struct inode *inode = file_inode(file);
ino_t pino = parent_ino(file->f_dentry);
int err;
if (file->f_pos < 0)
return -EINVAL;
if (file->f_pos == 0) {
if (filldir(buf, ".", 1, 1, inode->i_ino, DT_DIR) < 0)
return 0;
file->f_pos++;
}
if (file->f_pos == 1) {
if (filldir(buf, "..", 2, 2, pino, DT_DIR) < 0)
return 0;
file->f_pos++;
}
err = __logfs_readdir(file, buf, filldir);
return err;
}
static void logfs_set_name(struct logfs_disk_dentry *dd, struct qstr *name)
{
dd->namelen = cpu_to_be16(name->len);
memcpy(dd->name, name->name, name->len);
}
static struct dentry *logfs_lookup(struct inode *dir, struct dentry *dentry,
unsigned int flags)
{
struct page *page;
struct logfs_disk_dentry *dd;
pgoff_t index;
u64 ino = 0;
struct inode *inode;
page = logfs_get_dd_page(dir, dentry);
if (IS_ERR(page))
return ERR_CAST(page);
if (!page) {
d_add(dentry, NULL);
return NULL;
}
index = page->index;
dd = kmap_atomic(page);
ino = be64_to_cpu(dd->ino);
kunmap_atomic(dd);
page_cache_release(page);
inode = logfs_iget(dir->i_sb, ino);
if (IS_ERR(inode))
printk(KERN_ERR"LogFS: Cannot read inode #%llx for dentry (%lx, %lx)n",
ino, dir->i_ino, index);
return d_splice_alias(inode, dentry);
}
static void grow_dir(struct inode *dir, loff_t index)
{
index = (index + 1) << dir->i_sb->s_blocksize_bits;
if (i_size_read(dir) < index)
i_size_write(dir, index);
}
static int logfs_write_dir(struct inode *dir, struct dentry *dentry,
struct inode *inode)
{
struct page *page;
struct logfs_disk_dentry *dd;
u32 hash = hash_32(dentry->d_name.name, dentry->d_name.len, 0);
pgoff_t index;
int round, err;
for (round = 0; round < 20; round++) {
index = hash_index(hash, round);
if (logfs_exist_block(dir, index))
continue;
page = find_or_create_page(dir->i_mapping, index, GFP_KERNEL);
if (!page)
return -ENOMEM;
dd = kmap_atomic(page);
memset(dd, 0, sizeof(*dd));
dd->ino = cpu_to_be64(inode->i_ino);
dd->type = logfs_type(inode);
logfs_set_name(dd, &dentry->d_name);
kunmap_atomic(dd);
err = logfs_write_buf(dir, page, WF_LOCK);
unlock_page(page);
page_cache_release(page);
if (!err)
grow_dir(dir, index);
return err;
}
/* FIXME: Is there a better return value? In most cases neither
* the filesystem nor the directory are full. But we have had
* too many collisions for this particular hash and no fallback.
*/
return -ENOSPC;
}
static int __logfs_create(struct inode *dir, struct dentry *dentry,
struct inode *inode, const char *dest, long destlen)
{
struct logfs_super *super = logfs_super(dir->i_sb);
struct logfs_inode *li = logfs_inode(inode);
struct logfs_transaction *ta;
int ret;
ta = kzalloc(sizeof(*ta), GFP_KERNEL);
if (!ta) {
drop_nlink(inode);
iput(inode);
return -ENOMEM;
}
ta->state = CREATE_1;
ta->ino = inode->i_ino;
mutex_lock(&super->s_dirop_mutex);
logfs_add_transaction(inode, ta);
if (dest) {
/* symlink */
ret = logfs_inode_write(inode, dest, destlen, 0, WF_LOCK, NULL);
if (!ret)
ret = write_inode(inode);
} else {
/* creat/mkdir/mknod */
ret = write_inode(inode);
}
if (ret) {
abort_transaction(inode, ta);
li->li_flags |= LOGFS_IF_STILLBORN;
/* FIXME: truncate symlink */
drop_nlink(inode);
iput(inode);
goto out;
}
ta->state = CREATE_2;
logfs_add_transaction(dir, ta);
ret = logfs_write_dir(dir, dentry, inode);
/* sync directory */
if (!ret)
ret = write_inode(dir);
if (ret) {
logfs_del_transaction(dir, ta);
ta->state = CREATE_2;
logfs_add_transaction(inode, ta);
logfs_remove_inode(inode);
iput(inode);
goto out;
}
d_instantiate(dentry, inode);
out:
mutex_unlock(&super->s_dirop_mutex);
return ret;
}
static int logfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
{
struct inode *inode;
/*
* FIXME: why do we have to fill in S_IFDIR, while the mode is
* correct for mknod, creat, etc.? Smells like the vfs *should*
* do it for us but for some reason fails to do so.
*/
inode = logfs_new_inode(dir, S_IFDIR | mode);
if (IS_ERR(inode))
return PTR_ERR(inode);
inode->i_op = &logfs_dir_iops;
inode->i_fop = &logfs_dir_fops;
return __logfs_create(dir, dentry, inode, NULL, 0);
}
static int logfs_create(struct inode *dir, struct dentry *dentry, umode_t mode,
bool excl)
{
struct inode *inode;
inode = logfs_new_inode(dir, mode);
if (IS_ERR(inode))
return PTR_ERR(inode);
inode->i_op = &logfs_reg_iops;
inode->i_fop = &logfs_reg_fops;
inode->i_mapping->a_ops = &logfs_reg_aops;
return __logfs_create(dir, dentry, inode, NULL, 0);
}
static int logfs_mknod(struct inode *dir, struct dentry *dentry, umode_t mode,
dev_t rdev)
{
struct inode *inode;
if (dentry->d_name.len > LOGFS_MAX_NAMELEN)
return -ENAMETOOLONG;
inode = logfs_new_inode(dir, mode);
if (IS_ERR(inode))
return PTR_ERR(inode);
init_special_inode(inode, mode, rdev);
return __logfs_create(dir, dentry, inode, NULL, 0);
}
static int logfs_symlink(struct inode *dir, struct dentry *dentry,
const char *target)
{
struct inode *inode;
size_t destlen = strlen(target) + 1;
if (destlen > dir->i_sb->s_blocksize)
return -ENAMETOOLONG;
inode = logfs_new_inode(dir, S_IFLNK | 0777);
if (IS_ERR(inode))
return PTR_ERR(inode);
inode->i_op = &logfs_symlink_iops;
inode->i_mapping->a_ops = &logfs_reg_aops;
return __logfs_create(dir, dentry, inode, target, destlen);
}
static int logfs_link(struct dentry *old_dentry, struct inode *dir,
struct dentry *dentry)
{
struct inode *inode = old_dentry->d_inode;
inode->i_ctime = dir->i_ctime = dir->i_mtime = CURRENT_TIME;
ihold(inode);
inc_nlink(inode);
mark_inode_dirty_sync(inode);
return __logfs_create(dir, dentry, inode, NULL, 0);
}
static int logfs_get_dd(struct inode *dir, struct dentry *dentry,
struct logfs_disk_dentry *dd, loff_t *pos)
{
struct page *page;
void *map;
page = logfs_get_dd_page(dir, dentry);
if (IS_ERR(page))
return PTR_ERR(page);
*pos = page->index;
map = kmap_atomic(page);
memcpy(dd, map, sizeof(*dd));
kunmap_atomic(map);
page_cache_release(page);
return 0;
}
static int logfs_delete_dd(struct inode *dir, loff_t pos)
{
/*
* Getting called with pos somewhere beyond eof is either a goofup
* within this file or means someone maliciously edited the
* (crc-protected) journal.
*/
BUG_ON(beyond_eof(dir, pos));
dir->i_ctime = dir->i_mtime = CURRENT_TIME;
log_dir(" Delete dentry (%lx, %llx)\n", dir->i_ino, pos);
return logfs_delete(dir, pos, NULL);
}
/*
* Cross-directory rename, target does not exist. Just a little nasty.
* Create a new dentry in the target dir, then remove the old dentry,
* all the while taking care to remember our operation in the journal.
*/
static int logfs_rename_cross(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry)
{
struct logfs_super *super = logfs_super(old_dir->i_sb);
struct logfs_disk_dentry dd;
struct logfs_transaction *ta;
loff_t pos;
int err;
/* 1. locate source dd */
err = logfs_get_dd(old_dir, old_dentry, &dd, &pos);
if (err)
return err;
ta = kzalloc(sizeof(*ta), GFP_KERNEL);
if (!ta)
return -ENOMEM;
ta->state = CROSS_RENAME_1;
ta->dir = old_dir->i_ino;
ta->pos = pos;
/* 2. write target dd */
mutex_lock(&super->s_dirop_mutex);
logfs_add_transaction(new_dir, ta);
err = logfs_write_dir(new_dir, new_dentry, old_dentry->d_inode);
if (!err)
err = write_inode(new_dir);
if (err) {
super->s_rename_dir = 0;
super->s_rename_pos = 0;
abort_transaction(new_dir, ta);
goto out;
}
/* 3. remove source dd */
ta->state = CROSS_RENAME_2;
logfs_add_transaction(old_dir, ta);
err = logfs_delete_dd(old_dir, pos);
if (!err)
err = write_inode(old_dir);
LOGFS_BUG_ON(err, old_dir->i_sb);
out:
mutex_unlock(&super->s_dirop_mutex);
return err;
}
static int logfs_replace_inode(struct inode *dir, struct dentry *dentry,
struct logfs_disk_dentry *dd, struct inode *inode)
{
loff_t pos;
int err;
err = logfs_get_dd(dir, dentry, dd, &pos);
if (err)
return err;
dd->ino = cpu_to_be64(inode->i_ino);
dd->type = logfs_type(inode);
err = write_dir(dir, dd, pos);
if (err)
return err;
log_dir("Replace dentry (%lx, %llx) %s -> %llx\n", dir->i_ino, pos,
dd->name, be64_to_cpu(dd->ino));
return write_inode(dir);
}
/* Target dentry exists - the worst case. We need to attach the source
* inode to the target dentry, then remove the orphaned target inode and
* source dentry.
*/
static int logfs_rename_target(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry)
{
struct logfs_super *super = logfs_super(old_dir->i_sb);
struct inode *old_inode = old_dentry->d_inode;
struct inode *new_inode = new_dentry->d_inode;
int isdir = S_ISDIR(old_inode->i_mode);
struct logfs_disk_dentry dd;
struct logfs_transaction *ta;
loff_t pos;
int err;
BUG_ON(isdir != S_ISDIR(new_inode->i_mode));
if (isdir) {
if (!logfs_empty_dir(new_inode))
return -ENOTEMPTY;
}
/* 1. locate source dd */
err = logfs_get_dd(old_dir, old_dentry, &dd, &pos);
if (err)
return err;
ta = kzalloc(sizeof(*ta), GFP_KERNEL);
if (!ta)
return -ENOMEM;
ta->state = TARGET_RENAME_1;
ta->dir = old_dir->i_ino;
ta->pos = pos;
ta->ino = new_inode->i_ino;
/* 2. attach source inode to target dd */
mutex_lock(&super->s_dirop_mutex);
logfs_add_transaction(new_dir, ta);
err = logfs_replace_inode(new_dir, new_dentry, &dd, old_inode);
if (err) {
super->s_rename_dir = 0;
super->s_rename_pos = 0;
super->s_victim_ino = 0;
abort_transaction(new_dir, ta);
goto out;
}
/* 3. remove source dd */
ta->state = TARGET_RENAME_2;
logfs_add_transaction(old_dir, ta);
err = logfs_delete_dd(old_dir, pos);
if (!err)
err = write_inode(old_dir);
LOGFS_BUG_ON(err, old_dir->i_sb);
/* 4. remove target inode */
ta->state = TARGET_RENAME_3;
logfs_add_transaction(new_inode, ta);
err = logfs_remove_inode(new_inode);
out:
mutex_unlock(&super->s_dirop_mutex);
return err;
}
static int logfs_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry)
{
if (new_dentry->d_inode)
return logfs_rename_target(old_dir, old_dentry,
new_dir, new_dentry);
return logfs_rename_cross(old_dir, old_dentry, new_dir, new_dentry);
}
/* No locking done here, as this is called before .get_sb() returns. */
int logfs_replay_journal(struct super_block *sb)
{
struct logfs_super *super = logfs_super(sb);
struct inode *inode;
u64 ino, pos;
int err;
if (super->s_victim_ino) {
/* delete victim inode */
ino = super->s_victim_ino;
printk(KERN_INFO"LogFS: delete unmapped inode #%llx\n", ino);
inode = logfs_iget(sb, ino);
if (IS_ERR(inode))
goto fail;
LOGFS_BUG_ON(i_size_read(inode) > 0, sb);
super->s_victim_ino = 0;
err = logfs_remove_inode(inode);
iput(inode);
if (err) {
super->s_victim_ino = ino;
goto fail;
}
}
if (super->s_rename_dir) {
/* delete old dd from rename */
ino = super->s_rename_dir;
pos = super->s_rename_pos;
printk(KERN_INFO"LogFS: delete unbacked dentry (%llx, %llx)\n",
ino, pos);
inode = logfs_iget(sb, ino);
if (IS_ERR(inode))
goto fail;
super->s_rename_dir = 0;
super->s_rename_pos = 0;
err = logfs_delete_dd(inode, pos);
iput(inode);
if (err) {
super->s_rename_dir = ino;
super->s_rename_pos = pos;
goto fail;
}
}
return 0;
fail:
LOGFS_BUG(sb);
return -EIO;
}
const struct inode_operations logfs_symlink_iops = {
.readlink = generic_readlink,
.follow_link = page_follow_link_light,
};
const struct inode_operations logfs_dir_iops = {
.create = logfs_create,
.link = logfs_link,
.lookup = logfs_lookup,
.mkdir = logfs_mkdir,
.mknod = logfs_mknod,
.rename = logfs_rename,
.rmdir = logfs_rmdir,
.symlink = logfs_symlink,
.unlink = logfs_unlink,
};
const struct file_operations logfs_dir_fops = {
.fsync = logfs_fsync,
.unlocked_ioctl = logfs_ioctl,
.readdir = logfs_readdir,
.read = generic_read_dir,
.llseek = default_llseek,
};
| gpl-2.0 |
friedrich420/S6_AEL_Kernel_Multivariant_LL-5.1.1 | drivers/target/sbp/sbp_target.c | 2147 | 66426 | /*
* SBP2 target driver (SCSI over IEEE1394 in target mode)
*
* Copyright (C) 2011 Chris Boot <bootc@bootc.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.
*/
#define KMSG_COMPONENT "sbp_target"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/configfs.h>
#include <linux/ctype.h>
#include <linux/firewire.h>
#include <linux/firewire-constants.h>
#include <scsi/scsi.h>
#include <scsi/scsi_tcq.h>
#include <target/target_core_base.h>
#include <target/target_core_backend.h>
#include <target/target_core_fabric.h>
#include <target/target_core_fabric_configfs.h>
#include <target/target_core_configfs.h>
#include <target/configfs_macros.h>
#include <asm/unaligned.h>
#include "sbp_target.h"
/* Local pointer to allocated TCM configfs fabric module */
static struct target_fabric_configfs *sbp_fabric_configfs;
/* FireWire address region for management and command block address handlers */
static const struct fw_address_region sbp_register_region = {
.start = CSR_REGISTER_BASE + 0x10000,
.end = 0x1000000000000ULL,
};
static const u32 sbp_unit_directory_template[] = {
0x1200609e, /* unit_specifier_id: NCITS/T10 */
0x13010483, /* unit_sw_version: 1155D Rev 4 */
0x3800609e, /* command_set_specifier_id: NCITS/T10 */
0x390104d8, /* command_set: SPC-2 */
0x3b000000, /* command_set_revision: 0 */
0x3c000001, /* firmware_revision: 1 */
};
#define SESSION_MAINTENANCE_INTERVAL HZ
static atomic_t login_id = ATOMIC_INIT(0);
static void session_maintenance_work(struct work_struct *);
static int sbp_run_transaction(struct fw_card *, int, int, int, int,
unsigned long long, void *, size_t);
static int read_peer_guid(u64 *guid, const struct sbp_management_request *req)
{
int ret;
__be32 high, low;
ret = sbp_run_transaction(req->card, TCODE_READ_QUADLET_REQUEST,
req->node_addr, req->generation, req->speed,
(CSR_REGISTER_BASE | CSR_CONFIG_ROM) + 3 * 4,
&high, sizeof(high));
if (ret != RCODE_COMPLETE)
return ret;
ret = sbp_run_transaction(req->card, TCODE_READ_QUADLET_REQUEST,
req->node_addr, req->generation, req->speed,
(CSR_REGISTER_BASE | CSR_CONFIG_ROM) + 4 * 4,
&low, sizeof(low));
if (ret != RCODE_COMPLETE)
return ret;
*guid = (u64)be32_to_cpu(high) << 32 | be32_to_cpu(low);
return RCODE_COMPLETE;
}
static struct sbp_session *sbp_session_find_by_guid(
struct sbp_tpg *tpg, u64 guid)
{
struct se_session *se_sess;
struct sbp_session *sess, *found = NULL;
spin_lock_bh(&tpg->se_tpg.session_lock);
list_for_each_entry(se_sess, &tpg->se_tpg.tpg_sess_list, sess_list) {
sess = se_sess->fabric_sess_ptr;
if (sess->guid == guid)
found = sess;
}
spin_unlock_bh(&tpg->se_tpg.session_lock);
return found;
}
static struct sbp_login_descriptor *sbp_login_find_by_lun(
struct sbp_session *session, struct se_lun *lun)
{
struct sbp_login_descriptor *login, *found = NULL;
spin_lock_bh(&session->lock);
list_for_each_entry(login, &session->login_list, link) {
if (login->lun == lun)
found = login;
}
spin_unlock_bh(&session->lock);
return found;
}
static int sbp_login_count_all_by_lun(
struct sbp_tpg *tpg,
struct se_lun *lun,
int exclusive)
{
struct se_session *se_sess;
struct sbp_session *sess;
struct sbp_login_descriptor *login;
int count = 0;
spin_lock_bh(&tpg->se_tpg.session_lock);
list_for_each_entry(se_sess, &tpg->se_tpg.tpg_sess_list, sess_list) {
sess = se_sess->fabric_sess_ptr;
spin_lock_bh(&sess->lock);
list_for_each_entry(login, &sess->login_list, link) {
if (login->lun != lun)
continue;
if (!exclusive || login->exclusive)
count++;
}
spin_unlock_bh(&sess->lock);
}
spin_unlock_bh(&tpg->se_tpg.session_lock);
return count;
}
static struct sbp_login_descriptor *sbp_login_find_by_id(
struct sbp_tpg *tpg, int login_id)
{
struct se_session *se_sess;
struct sbp_session *sess;
struct sbp_login_descriptor *login, *found = NULL;
spin_lock_bh(&tpg->se_tpg.session_lock);
list_for_each_entry(se_sess, &tpg->se_tpg.tpg_sess_list, sess_list) {
sess = se_sess->fabric_sess_ptr;
spin_lock_bh(&sess->lock);
list_for_each_entry(login, &sess->login_list, link) {
if (login->login_id == login_id)
found = login;
}
spin_unlock_bh(&sess->lock);
}
spin_unlock_bh(&tpg->se_tpg.session_lock);
return found;
}
static struct se_lun *sbp_get_lun_from_tpg(struct sbp_tpg *tpg, int lun)
{
struct se_portal_group *se_tpg = &tpg->se_tpg;
struct se_lun *se_lun;
if (lun >= TRANSPORT_MAX_LUNS_PER_TPG)
return ERR_PTR(-EINVAL);
spin_lock(&se_tpg->tpg_lun_lock);
se_lun = se_tpg->tpg_lun_list[lun];
if (se_lun->lun_status != TRANSPORT_LUN_STATUS_ACTIVE)
se_lun = ERR_PTR(-ENODEV);
spin_unlock(&se_tpg->tpg_lun_lock);
return se_lun;
}
static struct sbp_session *sbp_session_create(
struct sbp_tpg *tpg,
u64 guid)
{
struct sbp_session *sess;
int ret;
char guid_str[17];
struct se_node_acl *se_nacl;
sess = kmalloc(sizeof(*sess), GFP_KERNEL);
if (!sess) {
pr_err("failed to allocate session descriptor\n");
return ERR_PTR(-ENOMEM);
}
sess->se_sess = transport_init_session();
if (IS_ERR(sess->se_sess)) {
pr_err("failed to init se_session\n");
ret = PTR_ERR(sess->se_sess);
kfree(sess);
return ERR_PTR(ret);
}
snprintf(guid_str, sizeof(guid_str), "%016llx", guid);
se_nacl = core_tpg_check_initiator_node_acl(&tpg->se_tpg, guid_str);
if (!se_nacl) {
pr_warn("Node ACL not found for %s\n", guid_str);
transport_free_session(sess->se_sess);
kfree(sess);
return ERR_PTR(-EPERM);
}
sess->se_sess->se_node_acl = se_nacl;
spin_lock_init(&sess->lock);
INIT_LIST_HEAD(&sess->login_list);
INIT_DELAYED_WORK(&sess->maint_work, session_maintenance_work);
sess->guid = guid;
transport_register_session(&tpg->se_tpg, se_nacl, sess->se_sess, sess);
return sess;
}
static void sbp_session_release(struct sbp_session *sess, bool cancel_work)
{
spin_lock_bh(&sess->lock);
if (!list_empty(&sess->login_list)) {
spin_unlock_bh(&sess->lock);
return;
}
spin_unlock_bh(&sess->lock);
if (cancel_work)
cancel_delayed_work_sync(&sess->maint_work);
transport_deregister_session_configfs(sess->se_sess);
transport_deregister_session(sess->se_sess);
if (sess->card)
fw_card_put(sess->card);
kfree(sess);
}
static void sbp_target_agent_unregister(struct sbp_target_agent *);
static void sbp_login_release(struct sbp_login_descriptor *login,
bool cancel_work)
{
struct sbp_session *sess = login->sess;
/* FIXME: abort/wait on tasks */
sbp_target_agent_unregister(login->tgt_agt);
if (sess) {
spin_lock_bh(&sess->lock);
list_del(&login->link);
spin_unlock_bh(&sess->lock);
sbp_session_release(sess, cancel_work);
}
kfree(login);
}
static struct sbp_target_agent *sbp_target_agent_register(
struct sbp_login_descriptor *);
static void sbp_management_request_login(
struct sbp_management_agent *agent, struct sbp_management_request *req,
int *status_data_size)
{
struct sbp_tport *tport = agent->tport;
struct sbp_tpg *tpg = tport->tpg;
struct se_lun *se_lun;
int ret;
u64 guid;
struct sbp_session *sess;
struct sbp_login_descriptor *login;
struct sbp_login_response_block *response;
int login_response_len;
se_lun = sbp_get_lun_from_tpg(tpg,
LOGIN_ORB_LUN(be32_to_cpu(req->orb.misc)));
if (IS_ERR(se_lun)) {
pr_notice("login to unknown LUN: %d\n",
LOGIN_ORB_LUN(be32_to_cpu(req->orb.misc)));
req->status.status = cpu_to_be32(
STATUS_BLOCK_RESP(STATUS_RESP_REQUEST_COMPLETE) |
STATUS_BLOCK_SBP_STATUS(SBP_STATUS_LUN_NOTSUPP));
return;
}
ret = read_peer_guid(&guid, req);
if (ret != RCODE_COMPLETE) {
pr_warn("failed to read peer GUID: %d\n", ret);
req->status.status = cpu_to_be32(
STATUS_BLOCK_RESP(STATUS_RESP_TRANSPORT_FAILURE) |
STATUS_BLOCK_SBP_STATUS(SBP_STATUS_UNSPECIFIED_ERROR));
return;
}
pr_notice("mgt_agent LOGIN to LUN %d from %016llx\n",
se_lun->unpacked_lun, guid);
sess = sbp_session_find_by_guid(tpg, guid);
if (sess) {
login = sbp_login_find_by_lun(sess, se_lun);
if (login) {
pr_notice("initiator already logged-in\n");
/*
* SBP-2 R4 says we should return access denied, but
* that can confuse initiators. Instead we need to
* treat this like a reconnect, but send the login
* response block like a fresh login.
*
* This is required particularly in the case of Apple
* devices booting off the FireWire target, where
* the firmware has an active login to the target. When
* the OS takes control of the session it issues its own
* LOGIN rather than a RECONNECT. To avoid the machine
* waiting until the reconnect_hold expires, we can skip
* the ACCESS_DENIED errors to speed things up.
*/
goto already_logged_in;
}
}
/*
* check exclusive bit in login request
* reject with access_denied if any logins present
*/
if (LOGIN_ORB_EXCLUSIVE(be32_to_cpu(req->orb.misc)) &&
sbp_login_count_all_by_lun(tpg, se_lun, 0)) {
pr_warn("refusing exclusive login with other active logins\n");
req->status.status = cpu_to_be32(
STATUS_BLOCK_RESP(STATUS_RESP_REQUEST_COMPLETE) |
STATUS_BLOCK_SBP_STATUS(SBP_STATUS_ACCESS_DENIED));
return;
}
/*
* check exclusive bit in any existing login descriptor
* reject with access_denied if any exclusive logins present
*/
if (sbp_login_count_all_by_lun(tpg, se_lun, 1)) {
pr_warn("refusing login while another exclusive login present\n");
req->status.status = cpu_to_be32(
STATUS_BLOCK_RESP(STATUS_RESP_REQUEST_COMPLETE) |
STATUS_BLOCK_SBP_STATUS(SBP_STATUS_ACCESS_DENIED));
return;
}
/*
* check we haven't exceeded the number of allowed logins
* reject with resources_unavailable if we have
*/
if (sbp_login_count_all_by_lun(tpg, se_lun, 0) >=
tport->max_logins_per_lun) {
pr_warn("max number of logins reached\n");
req->status.status = cpu_to_be32(
STATUS_BLOCK_RESP(STATUS_RESP_REQUEST_COMPLETE) |
STATUS_BLOCK_SBP_STATUS(SBP_STATUS_RESOURCES_UNAVAIL));
return;
}
if (!sess) {
sess = sbp_session_create(tpg, guid);
if (IS_ERR(sess)) {
switch (PTR_ERR(sess)) {
case -EPERM:
ret = SBP_STATUS_ACCESS_DENIED;
break;
default:
ret = SBP_STATUS_RESOURCES_UNAVAIL;
break;
}
req->status.status = cpu_to_be32(
STATUS_BLOCK_RESP(
STATUS_RESP_REQUEST_COMPLETE) |
STATUS_BLOCK_SBP_STATUS(ret));
return;
}
sess->node_id = req->node_addr;
sess->card = fw_card_get(req->card);
sess->generation = req->generation;
sess->speed = req->speed;
schedule_delayed_work(&sess->maint_work,
SESSION_MAINTENANCE_INTERVAL);
}
/* only take the latest reconnect_hold into account */
sess->reconnect_hold = min(
1 << LOGIN_ORB_RECONNECT(be32_to_cpu(req->orb.misc)),
tport->max_reconnect_timeout) - 1;
login = kmalloc(sizeof(*login), GFP_KERNEL);
if (!login) {
pr_err("failed to allocate login descriptor\n");
sbp_session_release(sess, true);
req->status.status = cpu_to_be32(
STATUS_BLOCK_RESP(STATUS_RESP_REQUEST_COMPLETE) |
STATUS_BLOCK_SBP_STATUS(SBP_STATUS_RESOURCES_UNAVAIL));
return;
}
login->sess = sess;
login->lun = se_lun;
login->status_fifo_addr = sbp2_pointer_to_addr(&req->orb.status_fifo);
login->exclusive = LOGIN_ORB_EXCLUSIVE(be32_to_cpu(req->orb.misc));
login->login_id = atomic_inc_return(&login_id);
login->tgt_agt = sbp_target_agent_register(login);
if (IS_ERR(login->tgt_agt)) {
ret = PTR_ERR(login->tgt_agt);
pr_err("failed to map command block handler: %d\n", ret);
sbp_session_release(sess, true);
kfree(login);
req->status.status = cpu_to_be32(
STATUS_BLOCK_RESP(STATUS_RESP_REQUEST_COMPLETE) |
STATUS_BLOCK_SBP_STATUS(SBP_STATUS_RESOURCES_UNAVAIL));
return;
}
spin_lock_bh(&sess->lock);
list_add_tail(&login->link, &sess->login_list);
spin_unlock_bh(&sess->lock);
already_logged_in:
response = kzalloc(sizeof(*response), GFP_KERNEL);
if (!response) {
pr_err("failed to allocate login response block\n");
sbp_login_release(login, true);
req->status.status = cpu_to_be32(
STATUS_BLOCK_RESP(STATUS_RESP_REQUEST_COMPLETE) |
STATUS_BLOCK_SBP_STATUS(SBP_STATUS_RESOURCES_UNAVAIL));
return;
}
login_response_len = clamp_val(
LOGIN_ORB_RESPONSE_LENGTH(be32_to_cpu(req->orb.length)),
12, sizeof(*response));
response->misc = cpu_to_be32(
((login_response_len & 0xffff) << 16) |
(login->login_id & 0xffff));
response->reconnect_hold = cpu_to_be32(sess->reconnect_hold & 0xffff);
addr_to_sbp2_pointer(login->tgt_agt->handler.offset,
&response->command_block_agent);
ret = sbp_run_transaction(sess->card, TCODE_WRITE_BLOCK_REQUEST,
sess->node_id, sess->generation, sess->speed,
sbp2_pointer_to_addr(&req->orb.ptr2), response,
login_response_len);
if (ret != RCODE_COMPLETE) {
pr_debug("failed to write login response block: %x\n", ret);
kfree(response);
sbp_login_release(login, true);
req->status.status = cpu_to_be32(
STATUS_BLOCK_RESP(STATUS_RESP_TRANSPORT_FAILURE) |
STATUS_BLOCK_SBP_STATUS(SBP_STATUS_UNSPECIFIED_ERROR));
return;
}
kfree(response);
req->status.status = cpu_to_be32(
STATUS_BLOCK_RESP(STATUS_RESP_REQUEST_COMPLETE) |
STATUS_BLOCK_SBP_STATUS(SBP_STATUS_OK));
}
static void sbp_management_request_query_logins(
struct sbp_management_agent *agent, struct sbp_management_request *req,
int *status_data_size)
{
pr_notice("QUERY LOGINS not implemented\n");
/* FIXME: implement */
req->status.status = cpu_to_be32(
STATUS_BLOCK_RESP(STATUS_RESP_REQUEST_COMPLETE) |
STATUS_BLOCK_SBP_STATUS(SBP_STATUS_REQ_TYPE_NOTSUPP));
}
static void sbp_management_request_reconnect(
struct sbp_management_agent *agent, struct sbp_management_request *req,
int *status_data_size)
{
struct sbp_tport *tport = agent->tport;
struct sbp_tpg *tpg = tport->tpg;
int ret;
u64 guid;
struct sbp_login_descriptor *login;
ret = read_peer_guid(&guid, req);
if (ret != RCODE_COMPLETE) {
pr_warn("failed to read peer GUID: %d\n", ret);
req->status.status = cpu_to_be32(
STATUS_BLOCK_RESP(STATUS_RESP_TRANSPORT_FAILURE) |
STATUS_BLOCK_SBP_STATUS(SBP_STATUS_UNSPECIFIED_ERROR));
return;
}
pr_notice("mgt_agent RECONNECT from %016llx\n", guid);
login = sbp_login_find_by_id(tpg,
RECONNECT_ORB_LOGIN_ID(be32_to_cpu(req->orb.misc)));
if (!login) {
pr_err("mgt_agent RECONNECT unknown login ID\n");
req->status.status = cpu_to_be32(
STATUS_BLOCK_RESP(STATUS_RESP_REQUEST_COMPLETE) |
STATUS_BLOCK_SBP_STATUS(SBP_STATUS_ACCESS_DENIED));
return;
}
if (login->sess->guid != guid) {
pr_err("mgt_agent RECONNECT login GUID doesn't match\n");
req->status.status = cpu_to_be32(
STATUS_BLOCK_RESP(STATUS_RESP_REQUEST_COMPLETE) |
STATUS_BLOCK_SBP_STATUS(SBP_STATUS_ACCESS_DENIED));
return;
}
spin_lock_bh(&login->sess->lock);
if (login->sess->card)
fw_card_put(login->sess->card);
/* update the node details */
login->sess->generation = req->generation;
login->sess->node_id = req->node_addr;
login->sess->card = fw_card_get(req->card);
login->sess->speed = req->speed;
spin_unlock_bh(&login->sess->lock);
req->status.status = cpu_to_be32(
STATUS_BLOCK_RESP(STATUS_RESP_REQUEST_COMPLETE) |
STATUS_BLOCK_SBP_STATUS(SBP_STATUS_OK));
}
static void sbp_management_request_logout(
struct sbp_management_agent *agent, struct sbp_management_request *req,
int *status_data_size)
{
struct sbp_tport *tport = agent->tport;
struct sbp_tpg *tpg = tport->tpg;
int id;
struct sbp_login_descriptor *login;
id = LOGOUT_ORB_LOGIN_ID(be32_to_cpu(req->orb.misc));
login = sbp_login_find_by_id(tpg, id);
if (!login) {
pr_warn("cannot find login: %d\n", id);
req->status.status = cpu_to_be32(
STATUS_BLOCK_RESP(STATUS_RESP_REQUEST_COMPLETE) |
STATUS_BLOCK_SBP_STATUS(SBP_STATUS_LOGIN_ID_UNKNOWN));
return;
}
pr_info("mgt_agent LOGOUT from LUN %d session %d\n",
login->lun->unpacked_lun, login->login_id);
if (req->node_addr != login->sess->node_id) {
pr_warn("logout from different node ID\n");
req->status.status = cpu_to_be32(
STATUS_BLOCK_RESP(STATUS_RESP_REQUEST_COMPLETE) |
STATUS_BLOCK_SBP_STATUS(SBP_STATUS_ACCESS_DENIED));
return;
}
sbp_login_release(login, true);
req->status.status = cpu_to_be32(
STATUS_BLOCK_RESP(STATUS_RESP_REQUEST_COMPLETE) |
STATUS_BLOCK_SBP_STATUS(SBP_STATUS_OK));
}
static void session_check_for_reset(struct sbp_session *sess)
{
bool card_valid = false;
spin_lock_bh(&sess->lock);
if (sess->card) {
spin_lock_irq(&sess->card->lock);
card_valid = (sess->card->local_node != NULL);
spin_unlock_irq(&sess->card->lock);
if (!card_valid) {
fw_card_put(sess->card);
sess->card = NULL;
}
}
if (!card_valid || (sess->generation != sess->card->generation)) {
pr_info("Waiting for reconnect from node: %016llx\n",
sess->guid);
sess->node_id = -1;
sess->reconnect_expires = get_jiffies_64() +
((sess->reconnect_hold + 1) * HZ);
}
spin_unlock_bh(&sess->lock);
}
static void session_reconnect_expired(struct sbp_session *sess)
{
struct sbp_login_descriptor *login, *temp;
LIST_HEAD(login_list);
pr_info("Reconnect timer expired for node: %016llx\n", sess->guid);
spin_lock_bh(&sess->lock);
list_for_each_entry_safe(login, temp, &sess->login_list, link) {
login->sess = NULL;
list_move_tail(&login->link, &login_list);
}
spin_unlock_bh(&sess->lock);
list_for_each_entry_safe(login, temp, &login_list, link) {
list_del(&login->link);
sbp_login_release(login, false);
}
sbp_session_release(sess, false);
}
static void session_maintenance_work(struct work_struct *work)
{
struct sbp_session *sess = container_of(work, struct sbp_session,
maint_work.work);
/* could be called while tearing down the session */
spin_lock_bh(&sess->lock);
if (list_empty(&sess->login_list)) {
spin_unlock_bh(&sess->lock);
return;
}
spin_unlock_bh(&sess->lock);
if (sess->node_id != -1) {
/* check for bus reset and make node_id invalid */
session_check_for_reset(sess);
schedule_delayed_work(&sess->maint_work,
SESSION_MAINTENANCE_INTERVAL);
} else if (!time_after64(get_jiffies_64(), sess->reconnect_expires)) {
/* still waiting for reconnect */
schedule_delayed_work(&sess->maint_work,
SESSION_MAINTENANCE_INTERVAL);
} else {
/* reconnect timeout has expired */
session_reconnect_expired(sess);
}
}
static int tgt_agent_rw_agent_state(struct fw_card *card, int tcode, void *data,
struct sbp_target_agent *agent)
{
int state;
switch (tcode) {
case TCODE_READ_QUADLET_REQUEST:
pr_debug("tgt_agent AGENT_STATE READ\n");
spin_lock_bh(&agent->lock);
state = agent->state;
spin_unlock_bh(&agent->lock);
*(__be32 *)data = cpu_to_be32(state);
return RCODE_COMPLETE;
case TCODE_WRITE_QUADLET_REQUEST:
/* ignored */
return RCODE_COMPLETE;
default:
return RCODE_TYPE_ERROR;
}
}
static int tgt_agent_rw_agent_reset(struct fw_card *card, int tcode, void *data,
struct sbp_target_agent *agent)
{
switch (tcode) {
case TCODE_WRITE_QUADLET_REQUEST:
pr_debug("tgt_agent AGENT_RESET\n");
spin_lock_bh(&agent->lock);
agent->state = AGENT_STATE_RESET;
spin_unlock_bh(&agent->lock);
return RCODE_COMPLETE;
default:
return RCODE_TYPE_ERROR;
}
}
static int tgt_agent_rw_orb_pointer(struct fw_card *card, int tcode, void *data,
struct sbp_target_agent *agent)
{
struct sbp2_pointer *ptr = data;
switch (tcode) {
case TCODE_WRITE_BLOCK_REQUEST:
spin_lock_bh(&agent->lock);
if (agent->state != AGENT_STATE_SUSPENDED &&
agent->state != AGENT_STATE_RESET) {
spin_unlock_bh(&agent->lock);
pr_notice("Ignoring ORB_POINTER write while active.\n");
return RCODE_CONFLICT_ERROR;
}
agent->state = AGENT_STATE_ACTIVE;
spin_unlock_bh(&agent->lock);
agent->orb_pointer = sbp2_pointer_to_addr(ptr);
agent->doorbell = false;
pr_debug("tgt_agent ORB_POINTER write: 0x%llx\n",
agent->orb_pointer);
queue_work(system_unbound_wq, &agent->work);
return RCODE_COMPLETE;
case TCODE_READ_BLOCK_REQUEST:
pr_debug("tgt_agent ORB_POINTER READ\n");
spin_lock_bh(&agent->lock);
addr_to_sbp2_pointer(agent->orb_pointer, ptr);
spin_unlock_bh(&agent->lock);
return RCODE_COMPLETE;
default:
return RCODE_TYPE_ERROR;
}
}
static int tgt_agent_rw_doorbell(struct fw_card *card, int tcode, void *data,
struct sbp_target_agent *agent)
{
switch (tcode) {
case TCODE_WRITE_QUADLET_REQUEST:
spin_lock_bh(&agent->lock);
if (agent->state != AGENT_STATE_SUSPENDED) {
spin_unlock_bh(&agent->lock);
pr_debug("Ignoring DOORBELL while active.\n");
return RCODE_CONFLICT_ERROR;
}
agent->state = AGENT_STATE_ACTIVE;
spin_unlock_bh(&agent->lock);
agent->doorbell = true;
pr_debug("tgt_agent DOORBELL\n");
queue_work(system_unbound_wq, &agent->work);
return RCODE_COMPLETE;
case TCODE_READ_QUADLET_REQUEST:
return RCODE_COMPLETE;
default:
return RCODE_TYPE_ERROR;
}
}
static int tgt_agent_rw_unsolicited_status_enable(struct fw_card *card,
int tcode, void *data, struct sbp_target_agent *agent)
{
switch (tcode) {
case TCODE_WRITE_QUADLET_REQUEST:
pr_debug("tgt_agent UNSOLICITED_STATUS_ENABLE\n");
/* ignored as we don't send unsolicited status */
return RCODE_COMPLETE;
case TCODE_READ_QUADLET_REQUEST:
return RCODE_COMPLETE;
default:
return RCODE_TYPE_ERROR;
}
}
static void tgt_agent_rw(struct fw_card *card, struct fw_request *request,
int tcode, int destination, int source, int generation,
unsigned long long offset, void *data, size_t length,
void *callback_data)
{
struct sbp_target_agent *agent = callback_data;
struct sbp_session *sess = agent->login->sess;
int sess_gen, sess_node, rcode;
spin_lock_bh(&sess->lock);
sess_gen = sess->generation;
sess_node = sess->node_id;
spin_unlock_bh(&sess->lock);
if (generation != sess_gen) {
pr_notice("ignoring request with wrong generation\n");
rcode = RCODE_TYPE_ERROR;
goto out;
}
if (source != sess_node) {
pr_notice("ignoring request from foreign node (%x != %x)\n",
source, sess_node);
rcode = RCODE_TYPE_ERROR;
goto out;
}
/* turn offset into the offset from the start of the block */
offset -= agent->handler.offset;
if (offset == 0x00 && length == 4) {
/* AGENT_STATE */
rcode = tgt_agent_rw_agent_state(card, tcode, data, agent);
} else if (offset == 0x04 && length == 4) {
/* AGENT_RESET */
rcode = tgt_agent_rw_agent_reset(card, tcode, data, agent);
} else if (offset == 0x08 && length == 8) {
/* ORB_POINTER */
rcode = tgt_agent_rw_orb_pointer(card, tcode, data, agent);
} else if (offset == 0x10 && length == 4) {
/* DOORBELL */
rcode = tgt_agent_rw_doorbell(card, tcode, data, agent);
} else if (offset == 0x14 && length == 4) {
/* UNSOLICITED_STATUS_ENABLE */
rcode = tgt_agent_rw_unsolicited_status_enable(card, tcode,
data, agent);
} else {
rcode = RCODE_ADDRESS_ERROR;
}
out:
fw_send_response(card, request, rcode);
}
static void sbp_handle_command(struct sbp_target_request *);
static int sbp_send_status(struct sbp_target_request *);
static void sbp_free_request(struct sbp_target_request *);
static void tgt_agent_process_work(struct work_struct *work)
{
struct sbp_target_request *req =
container_of(work, struct sbp_target_request, work);
pr_debug("tgt_orb ptr:0x%llx next_ORB:0x%llx data_descriptor:0x%llx misc:0x%x\n",
req->orb_pointer,
sbp2_pointer_to_addr(&req->orb.next_orb),
sbp2_pointer_to_addr(&req->orb.data_descriptor),
be32_to_cpu(req->orb.misc));
if (req->orb_pointer >> 32)
pr_debug("ORB with high bits set\n");
switch (ORB_REQUEST_FORMAT(be32_to_cpu(req->orb.misc))) {
case 0:/* Format specified by this standard */
sbp_handle_command(req);
return;
case 1: /* Reserved for future standardization */
case 2: /* Vendor-dependent */
req->status.status |= cpu_to_be32(
STATUS_BLOCK_RESP(
STATUS_RESP_REQUEST_COMPLETE) |
STATUS_BLOCK_DEAD(0) |
STATUS_BLOCK_LEN(1) |
STATUS_BLOCK_SBP_STATUS(
SBP_STATUS_REQ_TYPE_NOTSUPP));
sbp_send_status(req);
sbp_free_request(req);
return;
case 3: /* Dummy ORB */
req->status.status |= cpu_to_be32(
STATUS_BLOCK_RESP(
STATUS_RESP_REQUEST_COMPLETE) |
STATUS_BLOCK_DEAD(0) |
STATUS_BLOCK_LEN(1) |
STATUS_BLOCK_SBP_STATUS(
SBP_STATUS_DUMMY_ORB_COMPLETE));
sbp_send_status(req);
sbp_free_request(req);
return;
default:
BUG();
}
}
/* used to double-check we haven't been issued an AGENT_RESET */
static inline bool tgt_agent_check_active(struct sbp_target_agent *agent)
{
bool active;
spin_lock_bh(&agent->lock);
active = (agent->state == AGENT_STATE_ACTIVE);
spin_unlock_bh(&agent->lock);
return active;
}
static void tgt_agent_fetch_work(struct work_struct *work)
{
struct sbp_target_agent *agent =
container_of(work, struct sbp_target_agent, work);
struct sbp_session *sess = agent->login->sess;
struct sbp_target_request *req;
int ret;
bool doorbell = agent->doorbell;
u64 next_orb = agent->orb_pointer;
while (next_orb && tgt_agent_check_active(agent)) {
req = kzalloc(sizeof(*req), GFP_KERNEL);
if (!req) {
spin_lock_bh(&agent->lock);
agent->state = AGENT_STATE_DEAD;
spin_unlock_bh(&agent->lock);
return;
}
req->login = agent->login;
req->orb_pointer = next_orb;
req->status.status = cpu_to_be32(STATUS_BLOCK_ORB_OFFSET_HIGH(
req->orb_pointer >> 32));
req->status.orb_low = cpu_to_be32(
req->orb_pointer & 0xfffffffc);
/* read in the ORB */
ret = sbp_run_transaction(sess->card, TCODE_READ_BLOCK_REQUEST,
sess->node_id, sess->generation, sess->speed,
req->orb_pointer, &req->orb, sizeof(req->orb));
if (ret != RCODE_COMPLETE) {
pr_debug("tgt_orb fetch failed: %x\n", ret);
req->status.status |= cpu_to_be32(
STATUS_BLOCK_SRC(
STATUS_SRC_ORB_FINISHED) |
STATUS_BLOCK_RESP(
STATUS_RESP_TRANSPORT_FAILURE) |
STATUS_BLOCK_DEAD(1) |
STATUS_BLOCK_LEN(1) |
STATUS_BLOCK_SBP_STATUS(
SBP_STATUS_UNSPECIFIED_ERROR));
spin_lock_bh(&agent->lock);
agent->state = AGENT_STATE_DEAD;
spin_unlock_bh(&agent->lock);
sbp_send_status(req);
sbp_free_request(req);
return;
}
/* check the next_ORB field */
if (be32_to_cpu(req->orb.next_orb.high) & 0x80000000) {
next_orb = 0;
req->status.status |= cpu_to_be32(STATUS_BLOCK_SRC(
STATUS_SRC_ORB_FINISHED));
} else {
next_orb = sbp2_pointer_to_addr(&req->orb.next_orb);
req->status.status |= cpu_to_be32(STATUS_BLOCK_SRC(
STATUS_SRC_ORB_CONTINUING));
}
if (tgt_agent_check_active(agent) && !doorbell) {
INIT_WORK(&req->work, tgt_agent_process_work);
queue_work(system_unbound_wq, &req->work);
} else {
/* don't process this request, just check next_ORB */
sbp_free_request(req);
}
spin_lock_bh(&agent->lock);
doorbell = agent->doorbell = false;
/* check if we should carry on processing */
if (next_orb)
agent->orb_pointer = next_orb;
else
agent->state = AGENT_STATE_SUSPENDED;
spin_unlock_bh(&agent->lock);
};
}
static struct sbp_target_agent *sbp_target_agent_register(
struct sbp_login_descriptor *login)
{
struct sbp_target_agent *agent;
int ret;
agent = kmalloc(sizeof(*agent), GFP_KERNEL);
if (!agent)
return ERR_PTR(-ENOMEM);
spin_lock_init(&agent->lock);
agent->handler.length = 0x20;
agent->handler.address_callback = tgt_agent_rw;
agent->handler.callback_data = agent;
agent->login = login;
agent->state = AGENT_STATE_RESET;
INIT_WORK(&agent->work, tgt_agent_fetch_work);
agent->orb_pointer = 0;
agent->doorbell = false;
ret = fw_core_add_address_handler(&agent->handler,
&sbp_register_region);
if (ret < 0) {
kfree(agent);
return ERR_PTR(ret);
}
return agent;
}
static void sbp_target_agent_unregister(struct sbp_target_agent *agent)
{
fw_core_remove_address_handler(&agent->handler);
cancel_work_sync(&agent->work);
kfree(agent);
}
/*
* Simple wrapper around fw_run_transaction that retries the transaction several
* times in case of failure, with an exponential backoff.
*/
static int sbp_run_transaction(struct fw_card *card, int tcode, int destination_id,
int generation, int speed, unsigned long long offset,
void *payload, size_t length)
{
int attempt, ret, delay;
for (attempt = 1; attempt <= 5; attempt++) {
ret = fw_run_transaction(card, tcode, destination_id,
generation, speed, offset, payload, length);
switch (ret) {
case RCODE_COMPLETE:
case RCODE_TYPE_ERROR:
case RCODE_ADDRESS_ERROR:
case RCODE_GENERATION:
return ret;
default:
delay = 5 * attempt * attempt;
usleep_range(delay, delay * 2);
}
}
return ret;
}
/*
* Wrapper around sbp_run_transaction that gets the card, destination,
* generation and speed out of the request's session.
*/
static int sbp_run_request_transaction(struct sbp_target_request *req,
int tcode, unsigned long long offset, void *payload,
size_t length)
{
struct sbp_login_descriptor *login = req->login;
struct sbp_session *sess = login->sess;
struct fw_card *card;
int node_id, generation, speed, ret;
spin_lock_bh(&sess->lock);
card = fw_card_get(sess->card);
node_id = sess->node_id;
generation = sess->generation;
speed = sess->speed;
spin_unlock_bh(&sess->lock);
ret = sbp_run_transaction(card, tcode, node_id, generation, speed,
offset, payload, length);
fw_card_put(card);
return ret;
}
static int sbp_fetch_command(struct sbp_target_request *req)
{
int ret, cmd_len, copy_len;
cmd_len = scsi_command_size(req->orb.command_block);
req->cmd_buf = kmalloc(cmd_len, GFP_KERNEL);
if (!req->cmd_buf)
return -ENOMEM;
memcpy(req->cmd_buf, req->orb.command_block,
min_t(int, cmd_len, sizeof(req->orb.command_block)));
if (cmd_len > sizeof(req->orb.command_block)) {
pr_debug("sbp_fetch_command: filling in long command\n");
copy_len = cmd_len - sizeof(req->orb.command_block);
ret = sbp_run_request_transaction(req,
TCODE_READ_BLOCK_REQUEST,
req->orb_pointer + sizeof(req->orb),
req->cmd_buf + sizeof(req->orb.command_block),
copy_len);
if (ret != RCODE_COMPLETE)
return -EIO;
}
return 0;
}
static int sbp_fetch_page_table(struct sbp_target_request *req)
{
int pg_tbl_sz, ret;
struct sbp_page_table_entry *pg_tbl;
if (!CMDBLK_ORB_PG_TBL_PRESENT(be32_to_cpu(req->orb.misc)))
return 0;
pg_tbl_sz = CMDBLK_ORB_DATA_SIZE(be32_to_cpu(req->orb.misc)) *
sizeof(struct sbp_page_table_entry);
pg_tbl = kmalloc(pg_tbl_sz, GFP_KERNEL);
if (!pg_tbl)
return -ENOMEM;
ret = sbp_run_request_transaction(req, TCODE_READ_BLOCK_REQUEST,
sbp2_pointer_to_addr(&req->orb.data_descriptor),
pg_tbl, pg_tbl_sz);
if (ret != RCODE_COMPLETE) {
kfree(pg_tbl);
return -EIO;
}
req->pg_tbl = pg_tbl;
return 0;
}
static void sbp_calc_data_length_direction(struct sbp_target_request *req,
u32 *data_len, enum dma_data_direction *data_dir)
{
int data_size, direction, idx;
data_size = CMDBLK_ORB_DATA_SIZE(be32_to_cpu(req->orb.misc));
direction = CMDBLK_ORB_DIRECTION(be32_to_cpu(req->orb.misc));
if (!data_size) {
*data_len = 0;
*data_dir = DMA_NONE;
return;
}
*data_dir = direction ? DMA_FROM_DEVICE : DMA_TO_DEVICE;
if (req->pg_tbl) {
*data_len = 0;
for (idx = 0; idx < data_size; idx++) {
*data_len += be16_to_cpu(
req->pg_tbl[idx].segment_length);
}
} else {
*data_len = data_size;
}
}
static void sbp_handle_command(struct sbp_target_request *req)
{
struct sbp_login_descriptor *login = req->login;
struct sbp_session *sess = login->sess;
int ret, unpacked_lun;
u32 data_length;
enum dma_data_direction data_dir;
ret = sbp_fetch_command(req);
if (ret) {
pr_debug("sbp_handle_command: fetch command failed: %d\n", ret);
goto err;
}
ret = sbp_fetch_page_table(req);
if (ret) {
pr_debug("sbp_handle_command: fetch page table failed: %d\n",
ret);
goto err;
}
unpacked_lun = req->login->lun->unpacked_lun;
sbp_calc_data_length_direction(req, &data_length, &data_dir);
pr_debug("sbp_handle_command ORB:0x%llx unpacked_lun:%d data_len:%d data_dir:%d\n",
req->orb_pointer, unpacked_lun, data_length, data_dir);
if (target_submit_cmd(&req->se_cmd, sess->se_sess, req->cmd_buf,
req->sense_buf, unpacked_lun, data_length,
MSG_SIMPLE_TAG, data_dir, 0))
goto err;
return;
err:
req->status.status |= cpu_to_be32(
STATUS_BLOCK_RESP(STATUS_RESP_TRANSPORT_FAILURE) |
STATUS_BLOCK_DEAD(0) |
STATUS_BLOCK_LEN(1) |
STATUS_BLOCK_SBP_STATUS(SBP_STATUS_UNSPECIFIED_ERROR));
sbp_send_status(req);
sbp_free_request(req);
}
/*
* DMA_TO_DEVICE = read from initiator (SCSI WRITE)
* DMA_FROM_DEVICE = write to initiator (SCSI READ)
*/
static int sbp_rw_data(struct sbp_target_request *req)
{
struct sbp_session *sess = req->login->sess;
int tcode, sg_miter_flags, max_payload, pg_size, speed, node_id,
generation, num_pte, length, tfr_length,
rcode = RCODE_COMPLETE;
struct sbp_page_table_entry *pte;
unsigned long long offset;
struct fw_card *card;
struct sg_mapping_iter iter;
if (req->se_cmd.data_direction == DMA_FROM_DEVICE) {
tcode = TCODE_WRITE_BLOCK_REQUEST;
sg_miter_flags = SG_MITER_FROM_SG;
} else {
tcode = TCODE_READ_BLOCK_REQUEST;
sg_miter_flags = SG_MITER_TO_SG;
}
max_payload = 4 << CMDBLK_ORB_MAX_PAYLOAD(be32_to_cpu(req->orb.misc));
speed = CMDBLK_ORB_SPEED(be32_to_cpu(req->orb.misc));
pg_size = CMDBLK_ORB_PG_SIZE(be32_to_cpu(req->orb.misc));
if (pg_size) {
pr_err("sbp_run_transaction: page size ignored\n");
pg_size = 0x100 << pg_size;
}
spin_lock_bh(&sess->lock);
card = fw_card_get(sess->card);
node_id = sess->node_id;
generation = sess->generation;
spin_unlock_bh(&sess->lock);
if (req->pg_tbl) {
pte = req->pg_tbl;
num_pte = CMDBLK_ORB_DATA_SIZE(be32_to_cpu(req->orb.misc));
offset = 0;
length = 0;
} else {
pte = NULL;
num_pte = 0;
offset = sbp2_pointer_to_addr(&req->orb.data_descriptor);
length = req->se_cmd.data_length;
}
sg_miter_start(&iter, req->se_cmd.t_data_sg, req->se_cmd.t_data_nents,
sg_miter_flags);
while (length || num_pte) {
if (!length) {
offset = (u64)be16_to_cpu(pte->segment_base_hi) << 32 |
be32_to_cpu(pte->segment_base_lo);
length = be16_to_cpu(pte->segment_length);
pte++;
num_pte--;
}
sg_miter_next(&iter);
tfr_length = min3(length, max_payload, (int)iter.length);
/* FIXME: take page_size into account */
rcode = sbp_run_transaction(card, tcode, node_id,
generation, speed,
offset, iter.addr, tfr_length);
if (rcode != RCODE_COMPLETE)
break;
length -= tfr_length;
offset += tfr_length;
iter.consumed = tfr_length;
}
sg_miter_stop(&iter);
fw_card_put(card);
if (rcode == RCODE_COMPLETE) {
WARN_ON(length != 0);
return 0;
} else {
return -EIO;
}
}
static int sbp_send_status(struct sbp_target_request *req)
{
int ret, length;
struct sbp_login_descriptor *login = req->login;
length = (((be32_to_cpu(req->status.status) >> 24) & 0x07) + 1) * 4;
ret = sbp_run_request_transaction(req, TCODE_WRITE_BLOCK_REQUEST,
login->status_fifo_addr, &req->status, length);
if (ret != RCODE_COMPLETE) {
pr_debug("sbp_send_status: write failed: 0x%x\n", ret);
return -EIO;
}
pr_debug("sbp_send_status: status write complete for ORB: 0x%llx\n",
req->orb_pointer);
return 0;
}
static void sbp_sense_mangle(struct sbp_target_request *req)
{
struct se_cmd *se_cmd = &req->se_cmd;
u8 *sense = req->sense_buf;
u8 *status = req->status.data;
WARN_ON(se_cmd->scsi_sense_length < 18);
switch (sense[0] & 0x7f) { /* sfmt */
case 0x70: /* current, fixed */
status[0] = 0 << 6;
break;
case 0x71: /* deferred, fixed */
status[0] = 1 << 6;
break;
case 0x72: /* current, descriptor */
case 0x73: /* deferred, descriptor */
default:
/*
* TODO: SBP-3 specifies what we should do with descriptor
* format sense data
*/
pr_err("sbp_send_sense: unknown sense format: 0x%x\n",
sense[0]);
req->status.status |= cpu_to_be32(
STATUS_BLOCK_RESP(STATUS_RESP_REQUEST_COMPLETE) |
STATUS_BLOCK_DEAD(0) |
STATUS_BLOCK_LEN(1) |
STATUS_BLOCK_SBP_STATUS(SBP_STATUS_REQUEST_ABORTED));
return;
}
status[0] |= se_cmd->scsi_status & 0x3f;/* status */
status[1] =
(sense[0] & 0x80) | /* valid */
((sense[2] & 0xe0) >> 1) | /* mark, eom, ili */
(sense[2] & 0x0f); /* sense_key */
status[2] = se_cmd->scsi_asc; /* sense_code */
status[3] = se_cmd->scsi_ascq; /* sense_qualifier */
/* information */
status[4] = sense[3];
status[5] = sense[4];
status[6] = sense[5];
status[7] = sense[6];
/* CDB-dependent */
status[8] = sense[8];
status[9] = sense[9];
status[10] = sense[10];
status[11] = sense[11];
/* fru */
status[12] = sense[14];
/* sense_key-dependent */
status[13] = sense[15];
status[14] = sense[16];
status[15] = sense[17];
req->status.status |= cpu_to_be32(
STATUS_BLOCK_RESP(STATUS_RESP_REQUEST_COMPLETE) |
STATUS_BLOCK_DEAD(0) |
STATUS_BLOCK_LEN(5) |
STATUS_BLOCK_SBP_STATUS(SBP_STATUS_OK));
}
static int sbp_send_sense(struct sbp_target_request *req)
{
struct se_cmd *se_cmd = &req->se_cmd;
if (se_cmd->scsi_sense_length) {
sbp_sense_mangle(req);
} else {
req->status.status |= cpu_to_be32(
STATUS_BLOCK_RESP(STATUS_RESP_REQUEST_COMPLETE) |
STATUS_BLOCK_DEAD(0) |
STATUS_BLOCK_LEN(1) |
STATUS_BLOCK_SBP_STATUS(SBP_STATUS_OK));
}
return sbp_send_status(req);
}
static void sbp_free_request(struct sbp_target_request *req)
{
kfree(req->pg_tbl);
kfree(req->cmd_buf);
kfree(req);
}
static void sbp_mgt_agent_process(struct work_struct *work)
{
struct sbp_management_agent *agent =
container_of(work, struct sbp_management_agent, work);
struct sbp_management_request *req = agent->request;
int ret;
int status_data_len = 0;
/* fetch the ORB from the initiator */
ret = sbp_run_transaction(req->card, TCODE_READ_BLOCK_REQUEST,
req->node_addr, req->generation, req->speed,
agent->orb_offset, &req->orb, sizeof(req->orb));
if (ret != RCODE_COMPLETE) {
pr_debug("mgt_orb fetch failed: %x\n", ret);
goto out;
}
pr_debug("mgt_orb ptr1:0x%llx ptr2:0x%llx misc:0x%x len:0x%x status_fifo:0x%llx\n",
sbp2_pointer_to_addr(&req->orb.ptr1),
sbp2_pointer_to_addr(&req->orb.ptr2),
be32_to_cpu(req->orb.misc), be32_to_cpu(req->orb.length),
sbp2_pointer_to_addr(&req->orb.status_fifo));
if (!ORB_NOTIFY(be32_to_cpu(req->orb.misc)) ||
ORB_REQUEST_FORMAT(be32_to_cpu(req->orb.misc)) != 0) {
pr_err("mgt_orb bad request\n");
goto out;
}
switch (MANAGEMENT_ORB_FUNCTION(be32_to_cpu(req->orb.misc))) {
case MANAGEMENT_ORB_FUNCTION_LOGIN:
sbp_management_request_login(agent, req, &status_data_len);
break;
case MANAGEMENT_ORB_FUNCTION_QUERY_LOGINS:
sbp_management_request_query_logins(agent, req,
&status_data_len);
break;
case MANAGEMENT_ORB_FUNCTION_RECONNECT:
sbp_management_request_reconnect(agent, req, &status_data_len);
break;
case MANAGEMENT_ORB_FUNCTION_SET_PASSWORD:
pr_notice("SET PASSWORD not implemented\n");
req->status.status = cpu_to_be32(
STATUS_BLOCK_RESP(STATUS_RESP_REQUEST_COMPLETE) |
STATUS_BLOCK_SBP_STATUS(SBP_STATUS_REQ_TYPE_NOTSUPP));
break;
case MANAGEMENT_ORB_FUNCTION_LOGOUT:
sbp_management_request_logout(agent, req, &status_data_len);
break;
case MANAGEMENT_ORB_FUNCTION_ABORT_TASK:
pr_notice("ABORT TASK not implemented\n");
req->status.status = cpu_to_be32(
STATUS_BLOCK_RESP(STATUS_RESP_REQUEST_COMPLETE) |
STATUS_BLOCK_SBP_STATUS(SBP_STATUS_REQ_TYPE_NOTSUPP));
break;
case MANAGEMENT_ORB_FUNCTION_ABORT_TASK_SET:
pr_notice("ABORT TASK SET not implemented\n");
req->status.status = cpu_to_be32(
STATUS_BLOCK_RESP(STATUS_RESP_REQUEST_COMPLETE) |
STATUS_BLOCK_SBP_STATUS(SBP_STATUS_REQ_TYPE_NOTSUPP));
break;
case MANAGEMENT_ORB_FUNCTION_LOGICAL_UNIT_RESET:
pr_notice("LOGICAL UNIT RESET not implemented\n");
req->status.status = cpu_to_be32(
STATUS_BLOCK_RESP(STATUS_RESP_REQUEST_COMPLETE) |
STATUS_BLOCK_SBP_STATUS(SBP_STATUS_REQ_TYPE_NOTSUPP));
break;
case MANAGEMENT_ORB_FUNCTION_TARGET_RESET:
pr_notice("TARGET RESET not implemented\n");
req->status.status = cpu_to_be32(
STATUS_BLOCK_RESP(STATUS_RESP_REQUEST_COMPLETE) |
STATUS_BLOCK_SBP_STATUS(SBP_STATUS_REQ_TYPE_NOTSUPP));
break;
default:
pr_notice("unknown management function 0x%x\n",
MANAGEMENT_ORB_FUNCTION(be32_to_cpu(req->orb.misc)));
req->status.status = cpu_to_be32(
STATUS_BLOCK_RESP(STATUS_RESP_REQUEST_COMPLETE) |
STATUS_BLOCK_SBP_STATUS(SBP_STATUS_REQ_TYPE_NOTSUPP));
break;
}
req->status.status |= cpu_to_be32(
STATUS_BLOCK_SRC(1) | /* Response to ORB, next_ORB absent */
STATUS_BLOCK_LEN(DIV_ROUND_UP(status_data_len, 4) + 1) |
STATUS_BLOCK_ORB_OFFSET_HIGH(agent->orb_offset >> 32));
req->status.orb_low = cpu_to_be32(agent->orb_offset);
/* write the status block back to the initiator */
ret = sbp_run_transaction(req->card, TCODE_WRITE_BLOCK_REQUEST,
req->node_addr, req->generation, req->speed,
sbp2_pointer_to_addr(&req->orb.status_fifo),
&req->status, 8 + status_data_len);
if (ret != RCODE_COMPLETE) {
pr_debug("mgt_orb status write failed: %x\n", ret);
goto out;
}
out:
fw_card_put(req->card);
kfree(req);
spin_lock_bh(&agent->lock);
agent->state = MANAGEMENT_AGENT_STATE_IDLE;
spin_unlock_bh(&agent->lock);
}
static void sbp_mgt_agent_rw(struct fw_card *card,
struct fw_request *request, int tcode, int destination, int source,
int generation, unsigned long long offset, void *data, size_t length,
void *callback_data)
{
struct sbp_management_agent *agent = callback_data;
struct sbp2_pointer *ptr = data;
int rcode = RCODE_ADDRESS_ERROR;
if (!agent->tport->enable)
goto out;
if ((offset != agent->handler.offset) || (length != 8))
goto out;
if (tcode == TCODE_WRITE_BLOCK_REQUEST) {
struct sbp_management_request *req;
int prev_state;
spin_lock_bh(&agent->lock);
prev_state = agent->state;
agent->state = MANAGEMENT_AGENT_STATE_BUSY;
spin_unlock_bh(&agent->lock);
if (prev_state == MANAGEMENT_AGENT_STATE_BUSY) {
pr_notice("ignoring management request while busy\n");
rcode = RCODE_CONFLICT_ERROR;
goto out;
}
req = kzalloc(sizeof(*req), GFP_ATOMIC);
if (!req) {
rcode = RCODE_CONFLICT_ERROR;
goto out;
}
req->card = fw_card_get(card);
req->generation = generation;
req->node_addr = source;
req->speed = fw_get_request_speed(request);
agent->orb_offset = sbp2_pointer_to_addr(ptr);
agent->request = req;
queue_work(system_unbound_wq, &agent->work);
rcode = RCODE_COMPLETE;
} else if (tcode == TCODE_READ_BLOCK_REQUEST) {
addr_to_sbp2_pointer(agent->orb_offset, ptr);
rcode = RCODE_COMPLETE;
} else {
rcode = RCODE_TYPE_ERROR;
}
out:
fw_send_response(card, request, rcode);
}
static struct sbp_management_agent *sbp_management_agent_register(
struct sbp_tport *tport)
{
int ret;
struct sbp_management_agent *agent;
agent = kmalloc(sizeof(*agent), GFP_KERNEL);
if (!agent)
return ERR_PTR(-ENOMEM);
spin_lock_init(&agent->lock);
agent->tport = tport;
agent->handler.length = 0x08;
agent->handler.address_callback = sbp_mgt_agent_rw;
agent->handler.callback_data = agent;
agent->state = MANAGEMENT_AGENT_STATE_IDLE;
INIT_WORK(&agent->work, sbp_mgt_agent_process);
agent->orb_offset = 0;
agent->request = NULL;
ret = fw_core_add_address_handler(&agent->handler,
&sbp_register_region);
if (ret < 0) {
kfree(agent);
return ERR_PTR(ret);
}
return agent;
}
static void sbp_management_agent_unregister(struct sbp_management_agent *agent)
{
fw_core_remove_address_handler(&agent->handler);
cancel_work_sync(&agent->work);
kfree(agent);
}
static int sbp_check_true(struct se_portal_group *se_tpg)
{
return 1;
}
static int sbp_check_false(struct se_portal_group *se_tpg)
{
return 0;
}
static char *sbp_get_fabric_name(void)
{
return "sbp";
}
static char *sbp_get_fabric_wwn(struct se_portal_group *se_tpg)
{
struct sbp_tpg *tpg = container_of(se_tpg, struct sbp_tpg, se_tpg);
struct sbp_tport *tport = tpg->tport;
return &tport->tport_name[0];
}
static u16 sbp_get_tag(struct se_portal_group *se_tpg)
{
struct sbp_tpg *tpg = container_of(se_tpg, struct sbp_tpg, se_tpg);
return tpg->tport_tpgt;
}
static u32 sbp_get_default_depth(struct se_portal_group *se_tpg)
{
return 1;
}
static struct se_node_acl *sbp_alloc_fabric_acl(struct se_portal_group *se_tpg)
{
struct sbp_nacl *nacl;
nacl = kzalloc(sizeof(struct sbp_nacl), GFP_KERNEL);
if (!nacl) {
pr_err("Unable to allocate struct sbp_nacl\n");
return NULL;
}
return &nacl->se_node_acl;
}
static void sbp_release_fabric_acl(
struct se_portal_group *se_tpg,
struct se_node_acl *se_nacl)
{
struct sbp_nacl *nacl =
container_of(se_nacl, struct sbp_nacl, se_node_acl);
kfree(nacl);
}
static u32 sbp_tpg_get_inst_index(struct se_portal_group *se_tpg)
{
return 1;
}
static void sbp_release_cmd(struct se_cmd *se_cmd)
{
struct sbp_target_request *req = container_of(se_cmd,
struct sbp_target_request, se_cmd);
sbp_free_request(req);
}
static int sbp_shutdown_session(struct se_session *se_sess)
{
return 0;
}
static void sbp_close_session(struct se_session *se_sess)
{
return;
}
static u32 sbp_sess_get_index(struct se_session *se_sess)
{
return 0;
}
static int sbp_write_pending(struct se_cmd *se_cmd)
{
struct sbp_target_request *req = container_of(se_cmd,
struct sbp_target_request, se_cmd);
int ret;
ret = sbp_rw_data(req);
if (ret) {
req->status.status |= cpu_to_be32(
STATUS_BLOCK_RESP(
STATUS_RESP_TRANSPORT_FAILURE) |
STATUS_BLOCK_DEAD(0) |
STATUS_BLOCK_LEN(1) |
STATUS_BLOCK_SBP_STATUS(
SBP_STATUS_UNSPECIFIED_ERROR));
sbp_send_status(req);
return ret;
}
target_execute_cmd(se_cmd);
return 0;
}
static int sbp_write_pending_status(struct se_cmd *se_cmd)
{
return 0;
}
static void sbp_set_default_node_attrs(struct se_node_acl *nacl)
{
return;
}
static u32 sbp_get_task_tag(struct se_cmd *se_cmd)
{
struct sbp_target_request *req = container_of(se_cmd,
struct sbp_target_request, se_cmd);
/* only used for printk until we do TMRs */
return (u32)req->orb_pointer;
}
static int sbp_get_cmd_state(struct se_cmd *se_cmd)
{
return 0;
}
static int sbp_queue_data_in(struct se_cmd *se_cmd)
{
struct sbp_target_request *req = container_of(se_cmd,
struct sbp_target_request, se_cmd);
int ret;
ret = sbp_rw_data(req);
if (ret) {
req->status.status |= cpu_to_be32(
STATUS_BLOCK_RESP(STATUS_RESP_TRANSPORT_FAILURE) |
STATUS_BLOCK_DEAD(0) |
STATUS_BLOCK_LEN(1) |
STATUS_BLOCK_SBP_STATUS(SBP_STATUS_UNSPECIFIED_ERROR));
sbp_send_status(req);
return ret;
}
return sbp_send_sense(req);
}
/*
* Called after command (no data transfer) or after the write (to device)
* operation is completed
*/
static int sbp_queue_status(struct se_cmd *se_cmd)
{
struct sbp_target_request *req = container_of(se_cmd,
struct sbp_target_request, se_cmd);
return sbp_send_sense(req);
}
static int sbp_queue_tm_rsp(struct se_cmd *se_cmd)
{
return 0;
}
static int sbp_check_stop_free(struct se_cmd *se_cmd)
{
struct sbp_target_request *req = container_of(se_cmd,
struct sbp_target_request, se_cmd);
transport_generic_free_cmd(&req->se_cmd, 0);
return 1;
}
/*
* Handlers for Serial Bus Protocol 2/3 (SBP-2 / SBP-3)
*/
static u8 sbp_get_fabric_proto_ident(struct se_portal_group *se_tpg)
{
/*
* Return a IEEE 1394 SCSI Protocol identifier for loopback operations
* This is defined in section 7.5.1 Table 362 in spc4r17
*/
return SCSI_PROTOCOL_SBP;
}
static u32 sbp_get_pr_transport_id(
struct se_portal_group *se_tpg,
struct se_node_acl *se_nacl,
struct t10_pr_registration *pr_reg,
int *format_code,
unsigned char *buf)
{
int ret;
/*
* Set PROTOCOL IDENTIFIER to 3h for SBP
*/
buf[0] = SCSI_PROTOCOL_SBP;
/*
* From spc4r17, 7.5.4.4 TransportID for initiator ports using SCSI
* over IEEE 1394
*/
ret = hex2bin(&buf[8], se_nacl->initiatorname, 8);
if (ret < 0)
pr_debug("sbp transport_id: invalid hex string\n");
/*
* The IEEE 1394 Transport ID is a hardcoded 24-byte length
*/
return 24;
}
static u32 sbp_get_pr_transport_id_len(
struct se_portal_group *se_tpg,
struct se_node_acl *se_nacl,
struct t10_pr_registration *pr_reg,
int *format_code)
{
*format_code = 0;
/*
* From spc4r17, 7.5.4.4 TransportID for initiator ports using SCSI
* over IEEE 1394
*
* The SBP Transport ID is a hardcoded 24-byte length
*/
return 24;
}
/*
* Used for handling SCSI fabric dependent TransportIDs in SPC-3 and above
* Persistent Reservation SPEC_I_PT=1 and PROUT REGISTER_AND_MOVE operations.
*/
static char *sbp_parse_pr_out_transport_id(
struct se_portal_group *se_tpg,
const char *buf,
u32 *out_tid_len,
char **port_nexus_ptr)
{
/*
* Assume the FORMAT CODE 00b from spc4r17, 7.5.4.4 TransportID
* for initiator ports using SCSI over SBP Serial SCSI Protocol
*
* The TransportID for a IEEE 1394 Initiator Port is of fixed size of
* 24 bytes, and IEEE 1394 does not contain a I_T nexus identifier,
* so we return the **port_nexus_ptr set to NULL.
*/
*port_nexus_ptr = NULL;
*out_tid_len = 24;
return (char *)&buf[8];
}
static int sbp_count_se_tpg_luns(struct se_portal_group *tpg)
{
int i, count = 0;
spin_lock(&tpg->tpg_lun_lock);
for (i = 0; i < TRANSPORT_MAX_LUNS_PER_TPG; i++) {
struct se_lun *se_lun = tpg->tpg_lun_list[i];
if (se_lun->lun_status == TRANSPORT_LUN_STATUS_FREE)
continue;
count++;
}
spin_unlock(&tpg->tpg_lun_lock);
return count;
}
static int sbp_update_unit_directory(struct sbp_tport *tport)
{
int num_luns, num_entries, idx = 0, mgt_agt_addr, ret, i;
u32 *data;
if (tport->unit_directory.data) {
fw_core_remove_descriptor(&tport->unit_directory);
kfree(tport->unit_directory.data);
tport->unit_directory.data = NULL;
}
if (!tport->enable || !tport->tpg)
return 0;
num_luns = sbp_count_se_tpg_luns(&tport->tpg->se_tpg);
/*
* Number of entries in the final unit directory:
* - all of those in the template
* - management_agent
* - unit_characteristics
* - reconnect_timeout
* - unit unique ID
* - one for each LUN
*
* MUST NOT include leaf or sub-directory entries
*/
num_entries = ARRAY_SIZE(sbp_unit_directory_template) + 4 + num_luns;
if (tport->directory_id != -1)
num_entries++;
/* allocate num_entries + 4 for the header and unique ID leaf */
data = kcalloc((num_entries + 4), sizeof(u32), GFP_KERNEL);
if (!data)
return -ENOMEM;
/* directory_length */
data[idx++] = num_entries << 16;
/* directory_id */
if (tport->directory_id != -1)
data[idx++] = (CSR_DIRECTORY_ID << 24) | tport->directory_id;
/* unit directory template */
memcpy(&data[idx], sbp_unit_directory_template,
sizeof(sbp_unit_directory_template));
idx += ARRAY_SIZE(sbp_unit_directory_template);
/* management_agent */
mgt_agt_addr = (tport->mgt_agt->handler.offset - CSR_REGISTER_BASE) / 4;
data[idx++] = 0x54000000 | (mgt_agt_addr & 0x00ffffff);
/* unit_characteristics */
data[idx++] = 0x3a000000 |
(((tport->mgt_orb_timeout * 2) << 8) & 0xff00) |
SBP_ORB_FETCH_SIZE;
/* reconnect_timeout */
data[idx++] = 0x3d000000 | (tport->max_reconnect_timeout & 0xffff);
/* unit unique ID (leaf is just after LUNs) */
data[idx++] = 0x8d000000 | (num_luns + 1);
spin_lock(&tport->tpg->se_tpg.tpg_lun_lock);
for (i = 0; i < TRANSPORT_MAX_LUNS_PER_TPG; i++) {
struct se_lun *se_lun = tport->tpg->se_tpg.tpg_lun_list[i];
struct se_device *dev;
int type;
if (se_lun->lun_status == TRANSPORT_LUN_STATUS_FREE)
continue;
spin_unlock(&tport->tpg->se_tpg.tpg_lun_lock);
dev = se_lun->lun_se_dev;
type = dev->transport->get_device_type(dev);
/* logical_unit_number */
data[idx++] = 0x14000000 |
((type << 16) & 0x1f0000) |
(se_lun->unpacked_lun & 0xffff);
spin_lock(&tport->tpg->se_tpg.tpg_lun_lock);
}
spin_unlock(&tport->tpg->se_tpg.tpg_lun_lock);
/* unit unique ID leaf */
data[idx++] = 2 << 16;
data[idx++] = tport->guid >> 32;
data[idx++] = tport->guid;
tport->unit_directory.length = idx;
tport->unit_directory.key = (CSR_DIRECTORY | CSR_UNIT) << 24;
tport->unit_directory.data = data;
ret = fw_core_add_descriptor(&tport->unit_directory);
if (ret < 0) {
kfree(tport->unit_directory.data);
tport->unit_directory.data = NULL;
}
return ret;
}
static ssize_t sbp_parse_wwn(const char *name, u64 *wwn)
{
const char *cp;
char c, nibble;
int pos = 0, err;
*wwn = 0;
for (cp = name; cp < &name[SBP_NAMELEN - 1]; cp++) {
c = *cp;
if (c == '\n' && cp[1] == '\0')
continue;
if (c == '\0') {
err = 2;
if (pos != 16)
goto fail;
return cp - name;
}
err = 3;
if (isdigit(c))
nibble = c - '0';
else if (isxdigit(c))
nibble = tolower(c) - 'a' + 10;
else
goto fail;
*wwn = (*wwn << 4) | nibble;
pos++;
}
err = 4;
fail:
printk(KERN_INFO "err %u len %zu pos %u\n",
err, cp - name, pos);
return -1;
}
static ssize_t sbp_format_wwn(char *buf, size_t len, u64 wwn)
{
return snprintf(buf, len, "%016llx", wwn);
}
static struct se_node_acl *sbp_make_nodeacl(
struct se_portal_group *se_tpg,
struct config_group *group,
const char *name)
{
struct se_node_acl *se_nacl, *se_nacl_new;
struct sbp_nacl *nacl;
u64 guid = 0;
u32 nexus_depth = 1;
if (sbp_parse_wwn(name, &guid) < 0)
return ERR_PTR(-EINVAL);
se_nacl_new = sbp_alloc_fabric_acl(se_tpg);
if (!se_nacl_new)
return ERR_PTR(-ENOMEM);
/*
* se_nacl_new may be released by core_tpg_add_initiator_node_acl()
* when converting a NodeACL from demo mode -> explict
*/
se_nacl = core_tpg_add_initiator_node_acl(se_tpg, se_nacl_new,
name, nexus_depth);
if (IS_ERR(se_nacl)) {
sbp_release_fabric_acl(se_tpg, se_nacl_new);
return se_nacl;
}
nacl = container_of(se_nacl, struct sbp_nacl, se_node_acl);
nacl->guid = guid;
sbp_format_wwn(nacl->iport_name, SBP_NAMELEN, guid);
return se_nacl;
}
static void sbp_drop_nodeacl(struct se_node_acl *se_acl)
{
struct sbp_nacl *nacl =
container_of(se_acl, struct sbp_nacl, se_node_acl);
core_tpg_del_initiator_node_acl(se_acl->se_tpg, se_acl, 1);
kfree(nacl);
}
static int sbp_post_link_lun(
struct se_portal_group *se_tpg,
struct se_lun *se_lun)
{
struct sbp_tpg *tpg = container_of(se_tpg, struct sbp_tpg, se_tpg);
return sbp_update_unit_directory(tpg->tport);
}
static void sbp_pre_unlink_lun(
struct se_portal_group *se_tpg,
struct se_lun *se_lun)
{
struct sbp_tpg *tpg = container_of(se_tpg, struct sbp_tpg, se_tpg);
struct sbp_tport *tport = tpg->tport;
int ret;
if (sbp_count_se_tpg_luns(&tpg->se_tpg) == 0)
tport->enable = 0;
ret = sbp_update_unit_directory(tport);
if (ret < 0)
pr_err("unlink LUN: failed to update unit directory\n");
}
static struct se_portal_group *sbp_make_tpg(
struct se_wwn *wwn,
struct config_group *group,
const char *name)
{
struct sbp_tport *tport =
container_of(wwn, struct sbp_tport, tport_wwn);
struct sbp_tpg *tpg;
unsigned long tpgt;
int ret;
if (strstr(name, "tpgt_") != name)
return ERR_PTR(-EINVAL);
if (kstrtoul(name + 5, 10, &tpgt) || tpgt > UINT_MAX)
return ERR_PTR(-EINVAL);
if (tport->tpg) {
pr_err("Only one TPG per Unit is possible.\n");
return ERR_PTR(-EBUSY);
}
tpg = kzalloc(sizeof(*tpg), GFP_KERNEL);
if (!tpg) {
pr_err("Unable to allocate struct sbp_tpg\n");
return ERR_PTR(-ENOMEM);
}
tpg->tport = tport;
tpg->tport_tpgt = tpgt;
tport->tpg = tpg;
/* default attribute values */
tport->enable = 0;
tport->directory_id = -1;
tport->mgt_orb_timeout = 15;
tport->max_reconnect_timeout = 5;
tport->max_logins_per_lun = 1;
tport->mgt_agt = sbp_management_agent_register(tport);
if (IS_ERR(tport->mgt_agt)) {
ret = PTR_ERR(tport->mgt_agt);
goto out_free_tpg;
}
ret = core_tpg_register(&sbp_fabric_configfs->tf_ops, wwn,
&tpg->se_tpg, (void *)tpg,
TRANSPORT_TPG_TYPE_NORMAL);
if (ret < 0)
goto out_unreg_mgt_agt;
return &tpg->se_tpg;
out_unreg_mgt_agt:
sbp_management_agent_unregister(tport->mgt_agt);
out_free_tpg:
tport->tpg = NULL;
kfree(tpg);
return ERR_PTR(ret);
}
static void sbp_drop_tpg(struct se_portal_group *se_tpg)
{
struct sbp_tpg *tpg = container_of(se_tpg, struct sbp_tpg, se_tpg);
struct sbp_tport *tport = tpg->tport;
core_tpg_deregister(se_tpg);
sbp_management_agent_unregister(tport->mgt_agt);
tport->tpg = NULL;
kfree(tpg);
}
static struct se_wwn *sbp_make_tport(
struct target_fabric_configfs *tf,
struct config_group *group,
const char *name)
{
struct sbp_tport *tport;
u64 guid = 0;
if (sbp_parse_wwn(name, &guid) < 0)
return ERR_PTR(-EINVAL);
tport = kzalloc(sizeof(*tport), GFP_KERNEL);
if (!tport) {
pr_err("Unable to allocate struct sbp_tport\n");
return ERR_PTR(-ENOMEM);
}
tport->guid = guid;
sbp_format_wwn(tport->tport_name, SBP_NAMELEN, guid);
return &tport->tport_wwn;
}
static void sbp_drop_tport(struct se_wwn *wwn)
{
struct sbp_tport *tport =
container_of(wwn, struct sbp_tport, tport_wwn);
kfree(tport);
}
static ssize_t sbp_wwn_show_attr_version(
struct target_fabric_configfs *tf,
char *page)
{
return sprintf(page, "FireWire SBP fabric module %s\n", SBP_VERSION);
}
TF_WWN_ATTR_RO(sbp, version);
static struct configfs_attribute *sbp_wwn_attrs[] = {
&sbp_wwn_version.attr,
NULL,
};
static ssize_t sbp_tpg_show_directory_id(
struct se_portal_group *se_tpg,
char *page)
{
struct sbp_tpg *tpg = container_of(se_tpg, struct sbp_tpg, se_tpg);
struct sbp_tport *tport = tpg->tport;
if (tport->directory_id == -1)
return sprintf(page, "implicit\n");
else
return sprintf(page, "%06x\n", tport->directory_id);
}
static ssize_t sbp_tpg_store_directory_id(
struct se_portal_group *se_tpg,
const char *page,
size_t count)
{
struct sbp_tpg *tpg = container_of(se_tpg, struct sbp_tpg, se_tpg);
struct sbp_tport *tport = tpg->tport;
unsigned long val;
if (tport->enable) {
pr_err("Cannot change the directory_id on an active target.\n");
return -EBUSY;
}
if (strstr(page, "implicit") == page) {
tport->directory_id = -1;
} else {
if (kstrtoul(page, 16, &val) < 0)
return -EINVAL;
if (val > 0xffffff)
return -EINVAL;
tport->directory_id = val;
}
return count;
}
static ssize_t sbp_tpg_show_enable(
struct se_portal_group *se_tpg,
char *page)
{
struct sbp_tpg *tpg = container_of(se_tpg, struct sbp_tpg, se_tpg);
struct sbp_tport *tport = tpg->tport;
return sprintf(page, "%d\n", tport->enable);
}
static ssize_t sbp_tpg_store_enable(
struct se_portal_group *se_tpg,
const char *page,
size_t count)
{
struct sbp_tpg *tpg = container_of(se_tpg, struct sbp_tpg, se_tpg);
struct sbp_tport *tport = tpg->tport;
unsigned long val;
int ret;
if (kstrtoul(page, 0, &val) < 0)
return -EINVAL;
if ((val != 0) && (val != 1))
return -EINVAL;
if (tport->enable == val)
return count;
if (val) {
if (sbp_count_se_tpg_luns(&tpg->se_tpg) == 0) {
pr_err("Cannot enable a target with no LUNs!\n");
return -EINVAL;
}
} else {
/* XXX: force-shutdown sessions instead? */
spin_lock_bh(&se_tpg->session_lock);
if (!list_empty(&se_tpg->tpg_sess_list)) {
spin_unlock_bh(&se_tpg->session_lock);
return -EBUSY;
}
spin_unlock_bh(&se_tpg->session_lock);
}
tport->enable = val;
ret = sbp_update_unit_directory(tport);
if (ret < 0) {
pr_err("Could not update Config ROM\n");
return ret;
}
return count;
}
TF_TPG_BASE_ATTR(sbp, directory_id, S_IRUGO | S_IWUSR);
TF_TPG_BASE_ATTR(sbp, enable, S_IRUGO | S_IWUSR);
static struct configfs_attribute *sbp_tpg_base_attrs[] = {
&sbp_tpg_directory_id.attr,
&sbp_tpg_enable.attr,
NULL,
};
static ssize_t sbp_tpg_attrib_show_mgt_orb_timeout(
struct se_portal_group *se_tpg,
char *page)
{
struct sbp_tpg *tpg = container_of(se_tpg, struct sbp_tpg, se_tpg);
struct sbp_tport *tport = tpg->tport;
return sprintf(page, "%d\n", tport->mgt_orb_timeout);
}
static ssize_t sbp_tpg_attrib_store_mgt_orb_timeout(
struct se_portal_group *se_tpg,
const char *page,
size_t count)
{
struct sbp_tpg *tpg = container_of(se_tpg, struct sbp_tpg, se_tpg);
struct sbp_tport *tport = tpg->tport;
unsigned long val;
int ret;
if (kstrtoul(page, 0, &val) < 0)
return -EINVAL;
if ((val < 1) || (val > 127))
return -EINVAL;
if (tport->mgt_orb_timeout == val)
return count;
tport->mgt_orb_timeout = val;
ret = sbp_update_unit_directory(tport);
if (ret < 0)
return ret;
return count;
}
static ssize_t sbp_tpg_attrib_show_max_reconnect_timeout(
struct se_portal_group *se_tpg,
char *page)
{
struct sbp_tpg *tpg = container_of(se_tpg, struct sbp_tpg, se_tpg);
struct sbp_tport *tport = tpg->tport;
return sprintf(page, "%d\n", tport->max_reconnect_timeout);
}
static ssize_t sbp_tpg_attrib_store_max_reconnect_timeout(
struct se_portal_group *se_tpg,
const char *page,
size_t count)
{
struct sbp_tpg *tpg = container_of(se_tpg, struct sbp_tpg, se_tpg);
struct sbp_tport *tport = tpg->tport;
unsigned long val;
int ret;
if (kstrtoul(page, 0, &val) < 0)
return -EINVAL;
if ((val < 1) || (val > 32767))
return -EINVAL;
if (tport->max_reconnect_timeout == val)
return count;
tport->max_reconnect_timeout = val;
ret = sbp_update_unit_directory(tport);
if (ret < 0)
return ret;
return count;
}
static ssize_t sbp_tpg_attrib_show_max_logins_per_lun(
struct se_portal_group *se_tpg,
char *page)
{
struct sbp_tpg *tpg = container_of(se_tpg, struct sbp_tpg, se_tpg);
struct sbp_tport *tport = tpg->tport;
return sprintf(page, "%d\n", tport->max_logins_per_lun);
}
static ssize_t sbp_tpg_attrib_store_max_logins_per_lun(
struct se_portal_group *se_tpg,
const char *page,
size_t count)
{
struct sbp_tpg *tpg = container_of(se_tpg, struct sbp_tpg, se_tpg);
struct sbp_tport *tport = tpg->tport;
unsigned long val;
if (kstrtoul(page, 0, &val) < 0)
return -EINVAL;
if ((val < 1) || (val > 127))
return -EINVAL;
/* XXX: also check against current count? */
tport->max_logins_per_lun = val;
return count;
}
TF_TPG_ATTRIB_ATTR(sbp, mgt_orb_timeout, S_IRUGO | S_IWUSR);
TF_TPG_ATTRIB_ATTR(sbp, max_reconnect_timeout, S_IRUGO | S_IWUSR);
TF_TPG_ATTRIB_ATTR(sbp, max_logins_per_lun, S_IRUGO | S_IWUSR);
static struct configfs_attribute *sbp_tpg_attrib_attrs[] = {
&sbp_tpg_attrib_mgt_orb_timeout.attr,
&sbp_tpg_attrib_max_reconnect_timeout.attr,
&sbp_tpg_attrib_max_logins_per_lun.attr,
NULL,
};
static struct target_core_fabric_ops sbp_ops = {
.get_fabric_name = sbp_get_fabric_name,
.get_fabric_proto_ident = sbp_get_fabric_proto_ident,
.tpg_get_wwn = sbp_get_fabric_wwn,
.tpg_get_tag = sbp_get_tag,
.tpg_get_default_depth = sbp_get_default_depth,
.tpg_get_pr_transport_id = sbp_get_pr_transport_id,
.tpg_get_pr_transport_id_len = sbp_get_pr_transport_id_len,
.tpg_parse_pr_out_transport_id = sbp_parse_pr_out_transport_id,
.tpg_check_demo_mode = sbp_check_true,
.tpg_check_demo_mode_cache = sbp_check_true,
.tpg_check_demo_mode_write_protect = sbp_check_false,
.tpg_check_prod_mode_write_protect = sbp_check_false,
.tpg_alloc_fabric_acl = sbp_alloc_fabric_acl,
.tpg_release_fabric_acl = sbp_release_fabric_acl,
.tpg_get_inst_index = sbp_tpg_get_inst_index,
.release_cmd = sbp_release_cmd,
.shutdown_session = sbp_shutdown_session,
.close_session = sbp_close_session,
.sess_get_index = sbp_sess_get_index,
.write_pending = sbp_write_pending,
.write_pending_status = sbp_write_pending_status,
.set_default_node_attributes = sbp_set_default_node_attrs,
.get_task_tag = sbp_get_task_tag,
.get_cmd_state = sbp_get_cmd_state,
.queue_data_in = sbp_queue_data_in,
.queue_status = sbp_queue_status,
.queue_tm_rsp = sbp_queue_tm_rsp,
.check_stop_free = sbp_check_stop_free,
.fabric_make_wwn = sbp_make_tport,
.fabric_drop_wwn = sbp_drop_tport,
.fabric_make_tpg = sbp_make_tpg,
.fabric_drop_tpg = sbp_drop_tpg,
.fabric_post_link = sbp_post_link_lun,
.fabric_pre_unlink = sbp_pre_unlink_lun,
.fabric_make_np = NULL,
.fabric_drop_np = NULL,
.fabric_make_nodeacl = sbp_make_nodeacl,
.fabric_drop_nodeacl = sbp_drop_nodeacl,
};
static int sbp_register_configfs(void)
{
struct target_fabric_configfs *fabric;
int ret;
fabric = target_fabric_configfs_init(THIS_MODULE, "sbp");
if (IS_ERR(fabric)) {
pr_err("target_fabric_configfs_init() failed\n");
return PTR_ERR(fabric);
}
fabric->tf_ops = sbp_ops;
/*
* Setup default attribute lists for various fabric->tf_cit_tmpl
*/
TF_CIT_TMPL(fabric)->tfc_wwn_cit.ct_attrs = sbp_wwn_attrs;
TF_CIT_TMPL(fabric)->tfc_tpg_base_cit.ct_attrs = sbp_tpg_base_attrs;
TF_CIT_TMPL(fabric)->tfc_tpg_attrib_cit.ct_attrs = sbp_tpg_attrib_attrs;
TF_CIT_TMPL(fabric)->tfc_tpg_param_cit.ct_attrs = NULL;
TF_CIT_TMPL(fabric)->tfc_tpg_np_base_cit.ct_attrs = NULL;
TF_CIT_TMPL(fabric)->tfc_tpg_nacl_base_cit.ct_attrs = NULL;
TF_CIT_TMPL(fabric)->tfc_tpg_nacl_attrib_cit.ct_attrs = NULL;
TF_CIT_TMPL(fabric)->tfc_tpg_nacl_auth_cit.ct_attrs = NULL;
TF_CIT_TMPL(fabric)->tfc_tpg_nacl_param_cit.ct_attrs = NULL;
ret = target_fabric_configfs_register(fabric);
if (ret < 0) {
pr_err("target_fabric_configfs_register() failed for SBP\n");
return ret;
}
sbp_fabric_configfs = fabric;
return 0;
};
static void sbp_deregister_configfs(void)
{
if (!sbp_fabric_configfs)
return;
target_fabric_configfs_deregister(sbp_fabric_configfs);
sbp_fabric_configfs = NULL;
};
static int __init sbp_init(void)
{
int ret;
ret = sbp_register_configfs();
if (ret < 0)
return ret;
return 0;
};
static void __exit sbp_exit(void)
{
sbp_deregister_configfs();
};
MODULE_DESCRIPTION("FireWire SBP fabric driver");
MODULE_LICENSE("GPL");
module_init(sbp_init);
module_exit(sbp_exit);
| gpl-2.0 |
Arc-Team/android_kernel_htc_ruby | drivers/ptp/ptp_clock.c | 2403 | 8261 | /*
* PTP 1588 clock support
*
* Copyright (C) 2010 OMICRON electronics GmbH
*
* 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/bitops.h>
#include <linux/device.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/posix-clock.h>
#include <linux/pps_kernel.h>
#include <linux/slab.h>
#include <linux/syscalls.h>
#include <linux/uaccess.h>
#include "ptp_private.h"
#define PTP_MAX_ALARMS 4
#define PTP_MAX_CLOCKS 8
#define PTP_PPS_DEFAULTS (PPS_CAPTUREASSERT | PPS_OFFSETASSERT)
#define PTP_PPS_EVENT PPS_CAPTUREASSERT
#define PTP_PPS_MODE (PTP_PPS_DEFAULTS | PPS_CANWAIT | PPS_TSFMT_TSPEC)
/* private globals */
static dev_t ptp_devt;
static struct class *ptp_class;
static DECLARE_BITMAP(ptp_clocks_map, PTP_MAX_CLOCKS);
static DEFINE_MUTEX(ptp_clocks_mutex); /* protects 'ptp_clocks_map' */
/* time stamp event queue operations */
static inline int queue_free(struct timestamp_event_queue *q)
{
return PTP_MAX_TIMESTAMPS - queue_cnt(q) - 1;
}
static void enqueue_external_timestamp(struct timestamp_event_queue *queue,
struct ptp_clock_event *src)
{
struct ptp_extts_event *dst;
unsigned long flags;
s64 seconds;
u32 remainder;
seconds = div_u64_rem(src->timestamp, 1000000000, &remainder);
spin_lock_irqsave(&queue->lock, flags);
dst = &queue->buf[queue->tail];
dst->index = src->index;
dst->t.sec = seconds;
dst->t.nsec = remainder;
if (!queue_free(queue))
queue->head = (queue->head + 1) % PTP_MAX_TIMESTAMPS;
queue->tail = (queue->tail + 1) % PTP_MAX_TIMESTAMPS;
spin_unlock_irqrestore(&queue->lock, flags);
}
static s32 scaled_ppm_to_ppb(long ppm)
{
/*
* The 'freq' field in the 'struct timex' is in parts per
* million, but with a 16 bit binary fractional field.
*
* We want to calculate
*
* ppb = scaled_ppm * 1000 / 2^16
*
* which simplifies to
*
* ppb = scaled_ppm * 125 / 2^13
*/
s64 ppb = 1 + ppm;
ppb *= 125;
ppb >>= 13;
return (s32) ppb;
}
/* posix clock implementation */
static int ptp_clock_getres(struct posix_clock *pc, struct timespec *tp)
{
tp->tv_sec = 0;
tp->tv_nsec = 1;
return 0;
}
static int ptp_clock_settime(struct posix_clock *pc, const struct timespec *tp)
{
struct ptp_clock *ptp = container_of(pc, struct ptp_clock, clock);
return ptp->info->settime(ptp->info, tp);
}
static int ptp_clock_gettime(struct posix_clock *pc, struct timespec *tp)
{
struct ptp_clock *ptp = container_of(pc, struct ptp_clock, clock);
return ptp->info->gettime(ptp->info, tp);
}
static int ptp_clock_adjtime(struct posix_clock *pc, struct timex *tx)
{
struct ptp_clock *ptp = container_of(pc, struct ptp_clock, clock);
struct ptp_clock_info *ops;
int err = -EOPNOTSUPP;
ops = ptp->info;
if (tx->modes & ADJ_SETOFFSET) {
struct timespec ts;
ktime_t kt;
s64 delta;
ts.tv_sec = tx->time.tv_sec;
ts.tv_nsec = tx->time.tv_usec;
if (!(tx->modes & ADJ_NANO))
ts.tv_nsec *= 1000;
if ((unsigned long) ts.tv_nsec >= NSEC_PER_SEC)
return -EINVAL;
kt = timespec_to_ktime(ts);
delta = ktime_to_ns(kt);
err = ops->adjtime(ops, delta);
} else if (tx->modes & ADJ_FREQUENCY) {
err = ops->adjfreq(ops, scaled_ppm_to_ppb(tx->freq));
}
return err;
}
static struct posix_clock_operations ptp_clock_ops = {
.owner = THIS_MODULE,
.clock_adjtime = ptp_clock_adjtime,
.clock_gettime = ptp_clock_gettime,
.clock_getres = ptp_clock_getres,
.clock_settime = ptp_clock_settime,
.ioctl = ptp_ioctl,
.open = ptp_open,
.poll = ptp_poll,
.read = ptp_read,
};
static void delete_ptp_clock(struct posix_clock *pc)
{
struct ptp_clock *ptp = container_of(pc, struct ptp_clock, clock);
mutex_destroy(&ptp->tsevq_mux);
/* Remove the clock from the bit map. */
mutex_lock(&ptp_clocks_mutex);
clear_bit(ptp->index, ptp_clocks_map);
mutex_unlock(&ptp_clocks_mutex);
kfree(ptp);
}
/* public interface */
struct ptp_clock *ptp_clock_register(struct ptp_clock_info *info)
{
struct ptp_clock *ptp;
int err = 0, index, major = MAJOR(ptp_devt);
if (info->n_alarm > PTP_MAX_ALARMS)
return ERR_PTR(-EINVAL);
/* Find a free clock slot and reserve it. */
err = -EBUSY;
mutex_lock(&ptp_clocks_mutex);
index = find_first_zero_bit(ptp_clocks_map, PTP_MAX_CLOCKS);
if (index < PTP_MAX_CLOCKS)
set_bit(index, ptp_clocks_map);
else
goto no_slot;
/* Initialize a clock structure. */
err = -ENOMEM;
ptp = kzalloc(sizeof(struct ptp_clock), GFP_KERNEL);
if (ptp == NULL)
goto no_memory;
ptp->clock.ops = ptp_clock_ops;
ptp->clock.release = delete_ptp_clock;
ptp->info = info;
ptp->devid = MKDEV(major, index);
ptp->index = index;
spin_lock_init(&ptp->tsevq.lock);
mutex_init(&ptp->tsevq_mux);
init_waitqueue_head(&ptp->tsev_wq);
/* Create a new device in our class. */
ptp->dev = device_create(ptp_class, NULL, ptp->devid, ptp,
"ptp%d", ptp->index);
if (IS_ERR(ptp->dev))
goto no_device;
dev_set_drvdata(ptp->dev, ptp);
err = ptp_populate_sysfs(ptp);
if (err)
goto no_sysfs;
/* Register a new PPS source. */
if (info->pps) {
struct pps_source_info pps;
memset(&pps, 0, sizeof(pps));
snprintf(pps.name, PPS_MAX_NAME_LEN, "ptp%d", index);
pps.mode = PTP_PPS_MODE;
pps.owner = info->owner;
ptp->pps_source = pps_register_source(&pps, PTP_PPS_DEFAULTS);
if (!ptp->pps_source) {
pr_err("failed to register pps source\n");
goto no_pps;
}
}
/* Create a posix clock. */
err = posix_clock_register(&ptp->clock, ptp->devid);
if (err) {
pr_err("failed to create posix clock\n");
goto no_clock;
}
mutex_unlock(&ptp_clocks_mutex);
return ptp;
no_clock:
if (ptp->pps_source)
pps_unregister_source(ptp->pps_source);
no_pps:
ptp_cleanup_sysfs(ptp);
no_sysfs:
device_destroy(ptp_class, ptp->devid);
no_device:
mutex_destroy(&ptp->tsevq_mux);
kfree(ptp);
no_memory:
clear_bit(index, ptp_clocks_map);
no_slot:
mutex_unlock(&ptp_clocks_mutex);
return ERR_PTR(err);
}
EXPORT_SYMBOL(ptp_clock_register);
int ptp_clock_unregister(struct ptp_clock *ptp)
{
ptp->defunct = 1;
wake_up_interruptible(&ptp->tsev_wq);
/* Release the clock's resources. */
if (ptp->pps_source)
pps_unregister_source(ptp->pps_source);
ptp_cleanup_sysfs(ptp);
device_destroy(ptp_class, ptp->devid);
posix_clock_unregister(&ptp->clock);
return 0;
}
EXPORT_SYMBOL(ptp_clock_unregister);
void ptp_clock_event(struct ptp_clock *ptp, struct ptp_clock_event *event)
{
struct pps_event_time evt;
switch (event->type) {
case PTP_CLOCK_ALARM:
break;
case PTP_CLOCK_EXTTS:
enqueue_external_timestamp(&ptp->tsevq, event);
wake_up_interruptible(&ptp->tsev_wq);
break;
case PTP_CLOCK_PPS:
pps_get_ts(&evt);
pps_event(ptp->pps_source, &evt, PTP_PPS_EVENT, NULL);
break;
}
}
EXPORT_SYMBOL(ptp_clock_event);
/* module operations */
static void __exit ptp_exit(void)
{
class_destroy(ptp_class);
unregister_chrdev_region(ptp_devt, PTP_MAX_CLOCKS);
}
static int __init ptp_init(void)
{
int err;
ptp_class = class_create(THIS_MODULE, "ptp");
if (IS_ERR(ptp_class)) {
pr_err("ptp: failed to allocate class\n");
return PTR_ERR(ptp_class);
}
err = alloc_chrdev_region(&ptp_devt, 0, PTP_MAX_CLOCKS, "ptp");
if (err < 0) {
pr_err("ptp: failed to allocate device region\n");
goto no_region;
}
ptp_class->dev_attrs = ptp_dev_attrs;
pr_info("PTP clock support registered\n");
return 0;
no_region:
class_destroy(ptp_class);
return err;
}
subsys_initcall(ptp_init);
module_exit(ptp_exit);
MODULE_AUTHOR("Richard Cochran <richard.cochran@omicron.at>");
MODULE_DESCRIPTION("PTP clocks support");
MODULE_LICENSE("GPL");
| gpl-2.0 |
airidosas252/linux-allwinner-a10 | drivers/net/can/sja1000/sja1000.c | 2915 | 16734 | /*
* sja1000.c - Philips SJA1000 network device driver
*
* Copyright (c) 2003 Matthias Brukner, Trajet Gmbh, Rebenring 33,
* 38106 Braunschweig, GERMANY
*
* Copyright (c) 2002-2007 Volkswagen Group Electronic Research
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Volkswagen nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* Alternatively, provided that this notice is retained in full, this
* software may be distributed under the terms of the GNU General
* Public License ("GPL") version 2, in which case the provisions of the
* GPL apply INSTEAD OF those given above.
*
* The provided data structures and external interfaces from this code
* are not restricted to be used by modules with a GPL compatible license.
*
* 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.
*
* Send feedback to <socketcan-users@lists.berlios.de>
*
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/types.h>
#include <linux/fcntl.h>
#include <linux/interrupt.h>
#include <linux/ptrace.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/netdevice.h>
#include <linux/if_arp.h>
#include <linux/if_ether.h>
#include <linux/skbuff.h>
#include <linux/delay.h>
#include <linux/can/dev.h>
#include <linux/can/error.h>
#include "sja1000.h"
#define DRV_NAME "sja1000"
MODULE_AUTHOR("Oliver Hartkopp <oliver.hartkopp@volkswagen.de>");
MODULE_LICENSE("Dual BSD/GPL");
MODULE_DESCRIPTION(DRV_NAME "CAN netdevice driver");
static struct can_bittiming_const sja1000_bittiming_const = {
.name = DRV_NAME,
.tseg1_min = 1,
.tseg1_max = 16,
.tseg2_min = 1,
.tseg2_max = 8,
.sjw_max = 4,
.brp_min = 1,
.brp_max = 64,
.brp_inc = 1,
};
static void sja1000_write_cmdreg(struct sja1000_priv *priv, u8 val)
{
unsigned long flags;
/*
* The command register needs some locking and time to settle
* the write_reg() operation - especially on SMP systems.
*/
spin_lock_irqsave(&priv->cmdreg_lock, flags);
priv->write_reg(priv, REG_CMR, val);
priv->read_reg(priv, REG_SR);
spin_unlock_irqrestore(&priv->cmdreg_lock, flags);
}
static int sja1000_probe_chip(struct net_device *dev)
{
struct sja1000_priv *priv = netdev_priv(dev);
if (priv->reg_base && (priv->read_reg(priv, 0) == 0xFF)) {
printk(KERN_INFO "%s: probing @0x%lX failed\n",
DRV_NAME, dev->base_addr);
return 0;
}
return -1;
}
static void set_reset_mode(struct net_device *dev)
{
struct sja1000_priv *priv = netdev_priv(dev);
unsigned char status = priv->read_reg(priv, REG_MOD);
int i;
/* disable interrupts */
priv->write_reg(priv, REG_IER, IRQ_OFF);
for (i = 0; i < 100; i++) {
/* check reset bit */
if (status & MOD_RM) {
priv->can.state = CAN_STATE_STOPPED;
return;
}
priv->write_reg(priv, REG_MOD, MOD_RM); /* reset chip */
udelay(10);
status = priv->read_reg(priv, REG_MOD);
}
dev_err(dev->dev.parent, "setting SJA1000 into reset mode failed!\n");
}
static void set_normal_mode(struct net_device *dev)
{
struct sja1000_priv *priv = netdev_priv(dev);
unsigned char status = priv->read_reg(priv, REG_MOD);
int i;
for (i = 0; i < 100; i++) {
/* check reset bit */
if ((status & MOD_RM) == 0) {
priv->can.state = CAN_STATE_ERROR_ACTIVE;
/* enable interrupts */
if (priv->can.ctrlmode & CAN_CTRLMODE_BERR_REPORTING)
priv->write_reg(priv, REG_IER, IRQ_ALL);
else
priv->write_reg(priv, REG_IER,
IRQ_ALL & ~IRQ_BEI);
return;
}
/* set chip to normal mode */
priv->write_reg(priv, REG_MOD, 0x00);
udelay(10);
status = priv->read_reg(priv, REG_MOD);
}
dev_err(dev->dev.parent, "setting SJA1000 into normal mode failed!\n");
}
static void sja1000_start(struct net_device *dev)
{
struct sja1000_priv *priv = netdev_priv(dev);
/* leave reset mode */
if (priv->can.state != CAN_STATE_STOPPED)
set_reset_mode(dev);
/* Clear error counters and error code capture */
priv->write_reg(priv, REG_TXERR, 0x0);
priv->write_reg(priv, REG_RXERR, 0x0);
priv->read_reg(priv, REG_ECC);
/* leave reset mode */
set_normal_mode(dev);
}
static int sja1000_set_mode(struct net_device *dev, enum can_mode mode)
{
struct sja1000_priv *priv = netdev_priv(dev);
if (!priv->open_time)
return -EINVAL;
switch (mode) {
case CAN_MODE_START:
sja1000_start(dev);
if (netif_queue_stopped(dev))
netif_wake_queue(dev);
break;
default:
return -EOPNOTSUPP;
}
return 0;
}
static int sja1000_set_bittiming(struct net_device *dev)
{
struct sja1000_priv *priv = netdev_priv(dev);
struct can_bittiming *bt = &priv->can.bittiming;
u8 btr0, btr1;
btr0 = ((bt->brp - 1) & 0x3f) | (((bt->sjw - 1) & 0x3) << 6);
btr1 = ((bt->prop_seg + bt->phase_seg1 - 1) & 0xf) |
(((bt->phase_seg2 - 1) & 0x7) << 4);
if (priv->can.ctrlmode & CAN_CTRLMODE_3_SAMPLES)
btr1 |= 0x80;
dev_info(dev->dev.parent,
"setting BTR0=0x%02x BTR1=0x%02x\n", btr0, btr1);
priv->write_reg(priv, REG_BTR0, btr0);
priv->write_reg(priv, REG_BTR1, btr1);
return 0;
}
static int sja1000_get_berr_counter(const struct net_device *dev,
struct can_berr_counter *bec)
{
struct sja1000_priv *priv = netdev_priv(dev);
bec->txerr = priv->read_reg(priv, REG_TXERR);
bec->rxerr = priv->read_reg(priv, REG_RXERR);
return 0;
}
/*
* initialize SJA1000 chip:
* - reset chip
* - set output mode
* - set baudrate
* - enable interrupts
* - start operating mode
*/
static void chipset_init(struct net_device *dev)
{
struct sja1000_priv *priv = netdev_priv(dev);
/* set clock divider and output control register */
priv->write_reg(priv, REG_CDR, priv->cdr | CDR_PELICAN);
/* set acceptance filter (accept all) */
priv->write_reg(priv, REG_ACCC0, 0x00);
priv->write_reg(priv, REG_ACCC1, 0x00);
priv->write_reg(priv, REG_ACCC2, 0x00);
priv->write_reg(priv, REG_ACCC3, 0x00);
priv->write_reg(priv, REG_ACCM0, 0xFF);
priv->write_reg(priv, REG_ACCM1, 0xFF);
priv->write_reg(priv, REG_ACCM2, 0xFF);
priv->write_reg(priv, REG_ACCM3, 0xFF);
priv->write_reg(priv, REG_OCR, priv->ocr | OCR_MODE_NORMAL);
}
/*
* transmit a CAN message
* message layout in the sk_buff should be like this:
* xx xx xx xx ff ll 00 11 22 33 44 55 66 77
* [ can-id ] [flags] [len] [can data (up to 8 bytes]
*/
static netdev_tx_t sja1000_start_xmit(struct sk_buff *skb,
struct net_device *dev)
{
struct sja1000_priv *priv = netdev_priv(dev);
struct can_frame *cf = (struct can_frame *)skb->data;
uint8_t fi;
uint8_t dlc;
canid_t id;
uint8_t dreg;
int i;
if (can_dropped_invalid_skb(dev, skb))
return NETDEV_TX_OK;
netif_stop_queue(dev);
fi = dlc = cf->can_dlc;
id = cf->can_id;
if (id & CAN_RTR_FLAG)
fi |= FI_RTR;
if (id & CAN_EFF_FLAG) {
fi |= FI_FF;
dreg = EFF_BUF;
priv->write_reg(priv, REG_FI, fi);
priv->write_reg(priv, REG_ID1, (id & 0x1fe00000) >> (5 + 16));
priv->write_reg(priv, REG_ID2, (id & 0x001fe000) >> (5 + 8));
priv->write_reg(priv, REG_ID3, (id & 0x00001fe0) >> 5);
priv->write_reg(priv, REG_ID4, (id & 0x0000001f) << 3);
} else {
dreg = SFF_BUF;
priv->write_reg(priv, REG_FI, fi);
priv->write_reg(priv, REG_ID1, (id & 0x000007f8) >> 3);
priv->write_reg(priv, REG_ID2, (id & 0x00000007) << 5);
}
for (i = 0; i < dlc; i++)
priv->write_reg(priv, dreg++, cf->data[i]);
can_put_echo_skb(skb, dev, 0);
sja1000_write_cmdreg(priv, CMD_TR);
return NETDEV_TX_OK;
}
static void sja1000_rx(struct net_device *dev)
{
struct sja1000_priv *priv = netdev_priv(dev);
struct net_device_stats *stats = &dev->stats;
struct can_frame *cf;
struct sk_buff *skb;
uint8_t fi;
uint8_t dreg;
canid_t id;
int i;
/* create zero'ed CAN frame buffer */
skb = alloc_can_skb(dev, &cf);
if (skb == NULL)
return;
fi = priv->read_reg(priv, REG_FI);
if (fi & FI_FF) {
/* extended frame format (EFF) */
dreg = EFF_BUF;
id = (priv->read_reg(priv, REG_ID1) << (5 + 16))
| (priv->read_reg(priv, REG_ID2) << (5 + 8))
| (priv->read_reg(priv, REG_ID3) << 5)
| (priv->read_reg(priv, REG_ID4) >> 3);
id |= CAN_EFF_FLAG;
} else {
/* standard frame format (SFF) */
dreg = SFF_BUF;
id = (priv->read_reg(priv, REG_ID1) << 3)
| (priv->read_reg(priv, REG_ID2) >> 5);
}
cf->can_dlc = get_can_dlc(fi & 0x0F);
if (fi & FI_RTR) {
id |= CAN_RTR_FLAG;
} else {
for (i = 0; i < cf->can_dlc; i++)
cf->data[i] = priv->read_reg(priv, dreg++);
}
cf->can_id = id;
/* release receive buffer */
sja1000_write_cmdreg(priv, CMD_RRB);
netif_rx(skb);
stats->rx_packets++;
stats->rx_bytes += cf->can_dlc;
}
static int sja1000_err(struct net_device *dev, uint8_t isrc, uint8_t status)
{
struct sja1000_priv *priv = netdev_priv(dev);
struct net_device_stats *stats = &dev->stats;
struct can_frame *cf;
struct sk_buff *skb;
enum can_state state = priv->can.state;
uint8_t ecc, alc;
skb = alloc_can_err_skb(dev, &cf);
if (skb == NULL)
return -ENOMEM;
if (isrc & IRQ_DOI) {
/* data overrun interrupt */
dev_dbg(dev->dev.parent, "data overrun interrupt\n");
cf->can_id |= CAN_ERR_CRTL;
cf->data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
stats->rx_over_errors++;
stats->rx_errors++;
sja1000_write_cmdreg(priv, CMD_CDO); /* clear bit */
}
if (isrc & IRQ_EI) {
/* error warning interrupt */
dev_dbg(dev->dev.parent, "error warning interrupt\n");
if (status & SR_BS) {
state = CAN_STATE_BUS_OFF;
cf->can_id |= CAN_ERR_BUSOFF;
can_bus_off(dev);
} else if (status & SR_ES) {
state = CAN_STATE_ERROR_WARNING;
} else
state = CAN_STATE_ERROR_ACTIVE;
}
if (isrc & IRQ_BEI) {
/* bus error interrupt */
priv->can.can_stats.bus_error++;
stats->rx_errors++;
ecc = priv->read_reg(priv, REG_ECC);
cf->can_id |= CAN_ERR_PROT | CAN_ERR_BUSERROR;
switch (ecc & ECC_MASK) {
case ECC_BIT:
cf->data[2] |= CAN_ERR_PROT_BIT;
break;
case ECC_FORM:
cf->data[2] |= CAN_ERR_PROT_FORM;
break;
case ECC_STUFF:
cf->data[2] |= CAN_ERR_PROT_STUFF;
break;
default:
cf->data[2] |= CAN_ERR_PROT_UNSPEC;
cf->data[3] = ecc & ECC_SEG;
break;
}
/* Error occurred during transmission? */
if ((ecc & ECC_DIR) == 0)
cf->data[2] |= CAN_ERR_PROT_TX;
}
if (isrc & IRQ_EPI) {
/* error passive interrupt */
dev_dbg(dev->dev.parent, "error passive interrupt\n");
if (status & SR_ES)
state = CAN_STATE_ERROR_PASSIVE;
else
state = CAN_STATE_ERROR_ACTIVE;
}
if (isrc & IRQ_ALI) {
/* arbitration lost interrupt */
dev_dbg(dev->dev.parent, "arbitration lost interrupt\n");
alc = priv->read_reg(priv, REG_ALC);
priv->can.can_stats.arbitration_lost++;
stats->tx_errors++;
cf->can_id |= CAN_ERR_LOSTARB;
cf->data[0] = alc & 0x1f;
}
if (state != priv->can.state && (state == CAN_STATE_ERROR_WARNING ||
state == CAN_STATE_ERROR_PASSIVE)) {
uint8_t rxerr = priv->read_reg(priv, REG_RXERR);
uint8_t txerr = priv->read_reg(priv, REG_TXERR);
cf->can_id |= CAN_ERR_CRTL;
if (state == CAN_STATE_ERROR_WARNING) {
priv->can.can_stats.error_warning++;
cf->data[1] = (txerr > rxerr) ?
CAN_ERR_CRTL_TX_WARNING :
CAN_ERR_CRTL_RX_WARNING;
} else {
priv->can.can_stats.error_passive++;
cf->data[1] = (txerr > rxerr) ?
CAN_ERR_CRTL_TX_PASSIVE :
CAN_ERR_CRTL_RX_PASSIVE;
}
cf->data[6] = txerr;
cf->data[7] = rxerr;
}
priv->can.state = state;
netif_rx(skb);
stats->rx_packets++;
stats->rx_bytes += cf->can_dlc;
return 0;
}
irqreturn_t sja1000_interrupt(int irq, void *dev_id)
{
struct net_device *dev = (struct net_device *)dev_id;
struct sja1000_priv *priv = netdev_priv(dev);
struct net_device_stats *stats = &dev->stats;
uint8_t isrc, status;
int n = 0;
/* Shared interrupts and IRQ off? */
if (priv->read_reg(priv, REG_IER) == IRQ_OFF)
return IRQ_NONE;
if (priv->pre_irq)
priv->pre_irq(priv);
while ((isrc = priv->read_reg(priv, REG_IR)) && (n < SJA1000_MAX_IRQ)) {
n++;
status = priv->read_reg(priv, REG_SR);
if (isrc & IRQ_WUI)
dev_warn(dev->dev.parent, "wakeup interrupt\n");
if (isrc & IRQ_TI) {
/* transmission complete interrupt */
stats->tx_bytes += priv->read_reg(priv, REG_FI) & 0xf;
stats->tx_packets++;
can_get_echo_skb(dev, 0);
netif_wake_queue(dev);
}
if (isrc & IRQ_RI) {
/* receive interrupt */
while (status & SR_RBS) {
sja1000_rx(dev);
status = priv->read_reg(priv, REG_SR);
}
}
if (isrc & (IRQ_DOI | IRQ_EI | IRQ_BEI | IRQ_EPI | IRQ_ALI)) {
/* error interrupt */
if (sja1000_err(dev, isrc, status))
break;
}
}
if (priv->post_irq)
priv->post_irq(priv);
if (n >= SJA1000_MAX_IRQ)
dev_dbg(dev->dev.parent, "%d messages handled in ISR", n);
return (n) ? IRQ_HANDLED : IRQ_NONE;
}
EXPORT_SYMBOL_GPL(sja1000_interrupt);
static int sja1000_open(struct net_device *dev)
{
struct sja1000_priv *priv = netdev_priv(dev);
int err;
/* set chip into reset mode */
set_reset_mode(dev);
/* common open */
err = open_candev(dev);
if (err)
return err;
/* register interrupt handler, if not done by the device driver */
if (!(priv->flags & SJA1000_CUSTOM_IRQ_HANDLER)) {
err = request_irq(dev->irq, sja1000_interrupt, priv->irq_flags,
dev->name, (void *)dev);
if (err) {
close_candev(dev);
return -EAGAIN;
}
}
/* init and start chi */
sja1000_start(dev);
priv->open_time = jiffies;
netif_start_queue(dev);
return 0;
}
static int sja1000_close(struct net_device *dev)
{
struct sja1000_priv *priv = netdev_priv(dev);
netif_stop_queue(dev);
set_reset_mode(dev);
if (!(priv->flags & SJA1000_CUSTOM_IRQ_HANDLER))
free_irq(dev->irq, (void *)dev);
close_candev(dev);
priv->open_time = 0;
return 0;
}
struct net_device *alloc_sja1000dev(int sizeof_priv)
{
struct net_device *dev;
struct sja1000_priv *priv;
dev = alloc_candev(sizeof(struct sja1000_priv) + sizeof_priv,
SJA1000_ECHO_SKB_MAX);
if (!dev)
return NULL;
priv = netdev_priv(dev);
priv->dev = dev;
priv->can.bittiming_const = &sja1000_bittiming_const;
priv->can.do_set_bittiming = sja1000_set_bittiming;
priv->can.do_set_mode = sja1000_set_mode;
priv->can.do_get_berr_counter = sja1000_get_berr_counter;
priv->can.ctrlmode_supported = CAN_CTRLMODE_3_SAMPLES |
CAN_CTRLMODE_BERR_REPORTING;
spin_lock_init(&priv->cmdreg_lock);
if (sizeof_priv)
priv->priv = (void *)priv + sizeof(struct sja1000_priv);
return dev;
}
EXPORT_SYMBOL_GPL(alloc_sja1000dev);
void free_sja1000dev(struct net_device *dev)
{
free_candev(dev);
}
EXPORT_SYMBOL_GPL(free_sja1000dev);
static const struct net_device_ops sja1000_netdev_ops = {
.ndo_open = sja1000_open,
.ndo_stop = sja1000_close,
.ndo_start_xmit = sja1000_start_xmit,
};
int register_sja1000dev(struct net_device *dev)
{
if (!sja1000_probe_chip(dev))
return -ENODEV;
dev->flags |= IFF_ECHO; /* we support local echo */
dev->netdev_ops = &sja1000_netdev_ops;
set_reset_mode(dev);
chipset_init(dev);
return register_candev(dev);
}
EXPORT_SYMBOL_GPL(register_sja1000dev);
void unregister_sja1000dev(struct net_device *dev)
{
set_reset_mode(dev);
unregister_candev(dev);
}
EXPORT_SYMBOL_GPL(unregister_sja1000dev);
static __init int sja1000_init(void)
{
printk(KERN_INFO "%s CAN netdevice driver\n", DRV_NAME);
return 0;
}
module_init(sja1000_init);
static __exit void sja1000_exit(void)
{
printk(KERN_INFO "%s: driver removed\n", DRV_NAME);
}
module_exit(sja1000_exit);
| gpl-2.0 |
heyoufei2/yocto3.14.38_kernel | arch/powerpc/sysdev/xics/ics-rtas.c | 2915 | 6021 | #include <linux/types.h>
#include <linux/kernel.h>
#include <linux/irq.h>
#include <linux/smp.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/cpu.h>
#include <linux/of.h>
#include <linux/spinlock.h>
#include <linux/msi.h>
#include <asm/prom.h>
#include <asm/smp.h>
#include <asm/machdep.h>
#include <asm/irq.h>
#include <asm/errno.h>
#include <asm/xics.h>
#include <asm/rtas.h>
/* RTAS service tokens */
static int ibm_get_xive;
static int ibm_set_xive;
static int ibm_int_on;
static int ibm_int_off;
static int ics_rtas_map(struct ics *ics, unsigned int virq);
static void ics_rtas_mask_unknown(struct ics *ics, unsigned long vec);
static long ics_rtas_get_server(struct ics *ics, unsigned long vec);
static int ics_rtas_host_match(struct ics *ics, struct device_node *node);
/* Only one global & state struct ics */
static struct ics ics_rtas = {
.map = ics_rtas_map,
.mask_unknown = ics_rtas_mask_unknown,
.get_server = ics_rtas_get_server,
.host_match = ics_rtas_host_match,
};
static void ics_rtas_unmask_irq(struct irq_data *d)
{
unsigned int hw_irq = (unsigned int)irqd_to_hwirq(d);
int call_status;
int server;
pr_devel("xics: unmask virq %d [hw 0x%x]\n", d->irq, hw_irq);
if (hw_irq == XICS_IPI || hw_irq == XICS_IRQ_SPURIOUS)
return;
server = xics_get_irq_server(d->irq, d->affinity, 0);
call_status = rtas_call(ibm_set_xive, 3, 1, NULL, hw_irq, server,
DEFAULT_PRIORITY);
if (call_status != 0) {
printk(KERN_ERR
"%s: ibm_set_xive irq %u server %x returned %d\n",
__func__, hw_irq, server, call_status);
return;
}
/* Now unmask the interrupt (often a no-op) */
call_status = rtas_call(ibm_int_on, 1, 1, NULL, hw_irq);
if (call_status != 0) {
printk(KERN_ERR "%s: ibm_int_on irq=%u returned %d\n",
__func__, hw_irq, call_status);
return;
}
}
static unsigned int ics_rtas_startup(struct irq_data *d)
{
#ifdef CONFIG_PCI_MSI
/*
* The generic MSI code returns with the interrupt disabled on the
* card, using the MSI mask bits. Firmware doesn't appear to unmask
* at that level, so we do it here by hand.
*/
if (d->msi_desc)
unmask_msi_irq(d);
#endif
/* unmask it */
ics_rtas_unmask_irq(d);
return 0;
}
static void ics_rtas_mask_real_irq(unsigned int hw_irq)
{
int call_status;
if (hw_irq == XICS_IPI)
return;
call_status = rtas_call(ibm_int_off, 1, 1, NULL, hw_irq);
if (call_status != 0) {
printk(KERN_ERR "%s: ibm_int_off irq=%u returned %d\n",
__func__, hw_irq, call_status);
return;
}
/* Have to set XIVE to 0xff to be able to remove a slot */
call_status = rtas_call(ibm_set_xive, 3, 1, NULL, hw_irq,
xics_default_server, 0xff);
if (call_status != 0) {
printk(KERN_ERR "%s: ibm_set_xive(0xff) irq=%u returned %d\n",
__func__, hw_irq, call_status);
return;
}
}
static void ics_rtas_mask_irq(struct irq_data *d)
{
unsigned int hw_irq = (unsigned int)irqd_to_hwirq(d);
pr_devel("xics: mask virq %d [hw 0x%x]\n", d->irq, hw_irq);
if (hw_irq == XICS_IPI || hw_irq == XICS_IRQ_SPURIOUS)
return;
ics_rtas_mask_real_irq(hw_irq);
}
static int ics_rtas_set_affinity(struct irq_data *d,
const struct cpumask *cpumask,
bool force)
{
unsigned int hw_irq = (unsigned int)irqd_to_hwirq(d);
int status;
int xics_status[2];
int irq_server;
if (hw_irq == XICS_IPI || hw_irq == XICS_IRQ_SPURIOUS)
return -1;
status = rtas_call(ibm_get_xive, 1, 3, xics_status, hw_irq);
if (status) {
printk(KERN_ERR "%s: ibm,get-xive irq=%u returns %d\n",
__func__, hw_irq, status);
return -1;
}
irq_server = xics_get_irq_server(d->irq, cpumask, 1);
if (irq_server == -1) {
char cpulist[128];
cpumask_scnprintf(cpulist, sizeof(cpulist), cpumask);
printk(KERN_WARNING
"%s: No online cpus in the mask %s for irq %d\n",
__func__, cpulist, d->irq);
return -1;
}
status = rtas_call(ibm_set_xive, 3, 1, NULL,
hw_irq, irq_server, xics_status[1]);
if (status) {
printk(KERN_ERR "%s: ibm,set-xive irq=%u returns %d\n",
__func__, hw_irq, status);
return -1;
}
return IRQ_SET_MASK_OK;
}
static struct irq_chip ics_rtas_irq_chip = {
.name = "XICS",
.irq_startup = ics_rtas_startup,
.irq_mask = ics_rtas_mask_irq,
.irq_unmask = ics_rtas_unmask_irq,
.irq_eoi = NULL, /* Patched at init time */
.irq_set_affinity = ics_rtas_set_affinity
};
static int ics_rtas_map(struct ics *ics, unsigned int virq)
{
unsigned int hw_irq = (unsigned int)virq_to_hw(virq);
int status[2];
int rc;
if (WARN_ON(hw_irq == XICS_IPI || hw_irq == XICS_IRQ_SPURIOUS))
return -EINVAL;
/* Check if RTAS knows about this interrupt */
rc = rtas_call(ibm_get_xive, 1, 3, status, hw_irq);
if (rc)
return -ENXIO;
irq_set_chip_and_handler(virq, &ics_rtas_irq_chip, handle_fasteoi_irq);
irq_set_chip_data(virq, &ics_rtas);
return 0;
}
static void ics_rtas_mask_unknown(struct ics *ics, unsigned long vec)
{
ics_rtas_mask_real_irq(vec);
}
static long ics_rtas_get_server(struct ics *ics, unsigned long vec)
{
int rc, status[2];
rc = rtas_call(ibm_get_xive, 1, 3, status, vec);
if (rc)
return -1;
return status[0];
}
static int ics_rtas_host_match(struct ics *ics, struct device_node *node)
{
/* IBM machines have interrupt parents of various funky types for things
* like vdevices, events, etc... The trick we use here is to match
* everything here except the legacy 8259 which is compatible "chrp,iic"
*/
return !of_device_is_compatible(node, "chrp,iic");
}
__init int ics_rtas_init(void)
{
ibm_get_xive = rtas_token("ibm,get-xive");
ibm_set_xive = rtas_token("ibm,set-xive");
ibm_int_on = rtas_token("ibm,int-on");
ibm_int_off = rtas_token("ibm,int-off");
/* We enable the RTAS "ICS" if RTAS is present with the
* appropriate tokens
*/
if (ibm_get_xive == RTAS_UNKNOWN_SERVICE ||
ibm_set_xive == RTAS_UNKNOWN_SERVICE)
return -ENODEV;
/* We need to patch our irq chip's EOI to point to the
* right ICP
*/
ics_rtas_irq_chip.irq_eoi = icp_ops->eoi;
/* Register ourselves */
xics_register_ics(&ics_rtas);
return 0;
}
| gpl-2.0 |
MoKee/android_kernel_lge_sniper | drivers/ata/pata_arasan_cf.c | 2915 | 26825 | /*
* drivers/ata/pata_arasan_cf.c
*
* Arasan Compact Flash host controller source file
*
* Copyright (C) 2011 ST Microelectronics
* Viresh Kumar <viresh.kumar@st.com>
*
* This file is licensed under the terms of the GNU General Public
* License version 2. This program is licensed "as is" without any
* warranty of any kind, whether express or implied.
*/
/*
* The Arasan CompactFlash Device Controller IP core has three basic modes of
* operation: PC card ATA using I/O mode, PC card ATA using memory mode, PC card
* ATA using true IDE modes. This driver supports only True IDE mode currently.
*
* Arasan CF Controller shares global irq register with Arasan XD Controller.
*
* Tested on arch/arm/mach-spear13xx
*/
#include <linux/ata.h>
#include <linux/clk.h>
#include <linux/completion.h>
#include <linux/delay.h>
#include <linux/dmaengine.h>
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/kernel.h>
#include <linux/libata.h>
#include <linux/module.h>
#include <linux/pata_arasan_cf_data.h>
#include <linux/platform_device.h>
#include <linux/pm.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/types.h>
#include <linux/workqueue.h>
#define DRIVER_NAME "arasan_cf"
#define TIMEOUT msecs_to_jiffies(3000)
/* Registers */
/* CompactFlash Interface Status */
#define CFI_STS 0x000
#define STS_CHG (1)
#define BIN_AUDIO_OUT (1 << 1)
#define CARD_DETECT1 (1 << 2)
#define CARD_DETECT2 (1 << 3)
#define INP_ACK (1 << 4)
#define CARD_READY (1 << 5)
#define IO_READY (1 << 6)
#define B16_IO_PORT_SEL (1 << 7)
/* IRQ */
#define IRQ_STS 0x004
/* Interrupt Enable */
#define IRQ_EN 0x008
#define CARD_DETECT_IRQ (1)
#define STATUS_CHNG_IRQ (1 << 1)
#define MEM_MODE_IRQ (1 << 2)
#define IO_MODE_IRQ (1 << 3)
#define TRUE_IDE_MODE_IRQ (1 << 8)
#define PIO_XFER_ERR_IRQ (1 << 9)
#define BUF_AVAIL_IRQ (1 << 10)
#define XFER_DONE_IRQ (1 << 11)
#define IGNORED_IRQS (STATUS_CHNG_IRQ | MEM_MODE_IRQ | IO_MODE_IRQ |\
TRUE_IDE_MODE_IRQ)
#define TRUE_IDE_IRQS (CARD_DETECT_IRQ | PIO_XFER_ERR_IRQ |\
BUF_AVAIL_IRQ | XFER_DONE_IRQ)
/* Operation Mode */
#define OP_MODE 0x00C
#define CARD_MODE_MASK (0x3)
#define MEM_MODE (0x0)
#define IO_MODE (0x1)
#define TRUE_IDE_MODE (0x2)
#define CARD_TYPE_MASK (1 << 2)
#define CF_CARD (0)
#define CF_PLUS_CARD (1 << 2)
#define CARD_RESET (1 << 3)
#define CFHOST_ENB (1 << 4)
#define OUTPUTS_TRISTATE (1 << 5)
#define ULTRA_DMA_ENB (1 << 8)
#define MULTI_WORD_DMA_ENB (1 << 9)
#define DRQ_BLOCK_SIZE_MASK (0x3 << 11)
#define DRQ_BLOCK_SIZE_512 (0)
#define DRQ_BLOCK_SIZE_1024 (1 << 11)
#define DRQ_BLOCK_SIZE_2048 (2 << 11)
#define DRQ_BLOCK_SIZE_4096 (3 << 11)
/* CF Interface Clock Configuration */
#define CLK_CFG 0x010
#define CF_IF_CLK_MASK (0XF)
/* CF Timing Mode Configuration */
#define TM_CFG 0x014
#define MEM_MODE_TIMING_MASK (0x3)
#define MEM_MODE_TIMING_250NS (0x0)
#define MEM_MODE_TIMING_120NS (0x1)
#define MEM_MODE_TIMING_100NS (0x2)
#define MEM_MODE_TIMING_80NS (0x3)
#define IO_MODE_TIMING_MASK (0x3 << 2)
#define IO_MODE_TIMING_250NS (0x0 << 2)
#define IO_MODE_TIMING_120NS (0x1 << 2)
#define IO_MODE_TIMING_100NS (0x2 << 2)
#define IO_MODE_TIMING_80NS (0x3 << 2)
#define TRUEIDE_PIO_TIMING_MASK (0x7 << 4)
#define TRUEIDE_PIO_TIMING_SHIFT 4
#define TRUEIDE_MWORD_DMA_TIMING_MASK (0x7 << 7)
#define TRUEIDE_MWORD_DMA_TIMING_SHIFT 7
#define ULTRA_DMA_TIMING_MASK (0x7 << 10)
#define ULTRA_DMA_TIMING_SHIFT 10
/* CF Transfer Address */
#define XFER_ADDR 0x014
#define XFER_ADDR_MASK (0x7FF)
#define MAX_XFER_COUNT 0x20000u
/* Transfer Control */
#define XFER_CTR 0x01C
#define XFER_COUNT_MASK (0x3FFFF)
#define ADDR_INC_DISABLE (1 << 24)
#define XFER_WIDTH_MASK (1 << 25)
#define XFER_WIDTH_8B (0)
#define XFER_WIDTH_16B (1 << 25)
#define MEM_TYPE_MASK (1 << 26)
#define MEM_TYPE_COMMON (0)
#define MEM_TYPE_ATTRIBUTE (1 << 26)
#define MEM_IO_XFER_MASK (1 << 27)
#define MEM_XFER (0)
#define IO_XFER (1 << 27)
#define DMA_XFER_MODE (1 << 28)
#define AHB_BUS_NORMAL_PIO_OPRTN (~(1 << 29))
#define XFER_DIR_MASK (1 << 30)
#define XFER_READ (0)
#define XFER_WRITE (1 << 30)
#define XFER_START (1 << 31)
/* Write Data Port */
#define WRITE_PORT 0x024
/* Read Data Port */
#define READ_PORT 0x028
/* ATA Data Port */
#define ATA_DATA_PORT 0x030
#define ATA_DATA_PORT_MASK (0xFFFF)
/* ATA Error/Features */
#define ATA_ERR_FTR 0x034
/* ATA Sector Count */
#define ATA_SC 0x038
/* ATA Sector Number */
#define ATA_SN 0x03C
/* ATA Cylinder Low */
#define ATA_CL 0x040
/* ATA Cylinder High */
#define ATA_CH 0x044
/* ATA Select Card/Head */
#define ATA_SH 0x048
/* ATA Status-Command */
#define ATA_STS_CMD 0x04C
/* ATA Alternate Status/Device Control */
#define ATA_ASTS_DCTR 0x050
/* Extended Write Data Port 0x200-0x3FC */
#define EXT_WRITE_PORT 0x200
/* Extended Read Data Port 0x400-0x5FC */
#define EXT_READ_PORT 0x400
#define FIFO_SIZE 0x200u
/* Global Interrupt Status */
#define GIRQ_STS 0x800
/* Global Interrupt Status enable */
#define GIRQ_STS_EN 0x804
/* Global Interrupt Signal enable */
#define GIRQ_SGN_EN 0x808
#define GIRQ_CF (1)
#define GIRQ_XD (1 << 1)
/* Compact Flash Controller Dev Structure */
struct arasan_cf_dev {
/* pointer to ata_host structure */
struct ata_host *host;
/* clk structure, only if HAVE_CLK is defined */
#ifdef CONFIG_HAVE_CLK
struct clk *clk;
#endif
/* physical base address of controller */
dma_addr_t pbase;
/* virtual base address of controller */
void __iomem *vbase;
/* irq number*/
int irq;
/* status to be updated to framework regarding DMA transfer */
u8 dma_status;
/* Card is present or Not */
u8 card_present;
/* dma specific */
/* Completion for transfer complete interrupt from controller */
struct completion cf_completion;
/* Completion for DMA transfer complete. */
struct completion dma_completion;
/* Dma channel allocated */
struct dma_chan *dma_chan;
/* Mask for DMA transfers */
dma_cap_mask_t mask;
/* dma channel private data */
void *dma_priv;
/* DMA transfer work */
struct work_struct work;
/* DMA delayed finish work */
struct delayed_work dwork;
/* qc to be transferred using DMA */
struct ata_queued_cmd *qc;
};
static struct scsi_host_template arasan_cf_sht = {
ATA_BASE_SHT(DRIVER_NAME),
.sg_tablesize = SG_NONE,
.dma_boundary = 0xFFFFFFFFUL,
};
static void cf_dumpregs(struct arasan_cf_dev *acdev)
{
struct device *dev = acdev->host->dev;
dev_dbg(dev, ": =========== REGISTER DUMP ===========");
dev_dbg(dev, ": CFI_STS: %x", readl(acdev->vbase + CFI_STS));
dev_dbg(dev, ": IRQ_STS: %x", readl(acdev->vbase + IRQ_STS));
dev_dbg(dev, ": IRQ_EN: %x", readl(acdev->vbase + IRQ_EN));
dev_dbg(dev, ": OP_MODE: %x", readl(acdev->vbase + OP_MODE));
dev_dbg(dev, ": CLK_CFG: %x", readl(acdev->vbase + CLK_CFG));
dev_dbg(dev, ": TM_CFG: %x", readl(acdev->vbase + TM_CFG));
dev_dbg(dev, ": XFER_CTR: %x", readl(acdev->vbase + XFER_CTR));
dev_dbg(dev, ": GIRQ_STS: %x", readl(acdev->vbase + GIRQ_STS));
dev_dbg(dev, ": GIRQ_STS_EN: %x", readl(acdev->vbase + GIRQ_STS_EN));
dev_dbg(dev, ": GIRQ_SGN_EN: %x", readl(acdev->vbase + GIRQ_SGN_EN));
dev_dbg(dev, ": =====================================");
}
/* Enable/Disable global interrupts shared between CF and XD ctrlr. */
static void cf_ginterrupt_enable(struct arasan_cf_dev *acdev, bool enable)
{
/* enable should be 0 or 1 */
writel(enable, acdev->vbase + GIRQ_STS_EN);
writel(enable, acdev->vbase + GIRQ_SGN_EN);
}
/* Enable/Disable CF interrupts */
static inline void
cf_interrupt_enable(struct arasan_cf_dev *acdev, u32 mask, bool enable)
{
u32 val = readl(acdev->vbase + IRQ_EN);
/* clear & enable/disable irqs */
if (enable) {
writel(mask, acdev->vbase + IRQ_STS);
writel(val | mask, acdev->vbase + IRQ_EN);
} else
writel(val & ~mask, acdev->vbase + IRQ_EN);
}
static inline void cf_card_reset(struct arasan_cf_dev *acdev)
{
u32 val = readl(acdev->vbase + OP_MODE);
writel(val | CARD_RESET, acdev->vbase + OP_MODE);
udelay(200);
writel(val & ~CARD_RESET, acdev->vbase + OP_MODE);
}
static inline void cf_ctrl_reset(struct arasan_cf_dev *acdev)
{
writel(readl(acdev->vbase + OP_MODE) & ~CFHOST_ENB,
acdev->vbase + OP_MODE);
writel(readl(acdev->vbase + OP_MODE) | CFHOST_ENB,
acdev->vbase + OP_MODE);
}
static void cf_card_detect(struct arasan_cf_dev *acdev, bool hotplugged)
{
struct ata_port *ap = acdev->host->ports[0];
struct ata_eh_info *ehi = &ap->link.eh_info;
u32 val = readl(acdev->vbase + CFI_STS);
/* Both CD1 & CD2 should be low if card inserted completely */
if (!(val & (CARD_DETECT1 | CARD_DETECT2))) {
if (acdev->card_present)
return;
acdev->card_present = 1;
cf_card_reset(acdev);
} else {
if (!acdev->card_present)
return;
acdev->card_present = 0;
}
if (hotplugged) {
ata_ehi_hotplugged(ehi);
ata_port_freeze(ap);
}
}
static int cf_init(struct arasan_cf_dev *acdev)
{
struct arasan_cf_pdata *pdata = dev_get_platdata(acdev->host->dev);
unsigned long flags;
int ret = 0;
#ifdef CONFIG_HAVE_CLK
ret = clk_enable(acdev->clk);
if (ret) {
dev_dbg(acdev->host->dev, "clock enable failed");
return ret;
}
#endif
spin_lock_irqsave(&acdev->host->lock, flags);
/* configure CF interface clock */
writel((pdata->cf_if_clk <= CF_IF_CLK_200M) ? pdata->cf_if_clk :
CF_IF_CLK_166M, acdev->vbase + CLK_CFG);
writel(TRUE_IDE_MODE | CFHOST_ENB, acdev->vbase + OP_MODE);
cf_interrupt_enable(acdev, CARD_DETECT_IRQ, 1);
cf_ginterrupt_enable(acdev, 1);
spin_unlock_irqrestore(&acdev->host->lock, flags);
return ret;
}
static void cf_exit(struct arasan_cf_dev *acdev)
{
unsigned long flags;
spin_lock_irqsave(&acdev->host->lock, flags);
cf_ginterrupt_enable(acdev, 0);
cf_interrupt_enable(acdev, TRUE_IDE_IRQS, 0);
cf_card_reset(acdev);
writel(readl(acdev->vbase + OP_MODE) & ~CFHOST_ENB,
acdev->vbase + OP_MODE);
spin_unlock_irqrestore(&acdev->host->lock, flags);
#ifdef CONFIG_HAVE_CLK
clk_disable(acdev->clk);
#endif
}
static void dma_callback(void *dev)
{
struct arasan_cf_dev *acdev = (struct arasan_cf_dev *) dev;
complete(&acdev->dma_completion);
}
static bool filter(struct dma_chan *chan, void *slave)
{
chan->private = slave;
return true;
}
static inline void dma_complete(struct arasan_cf_dev *acdev)
{
struct ata_queued_cmd *qc = acdev->qc;
unsigned long flags;
acdev->qc = NULL;
ata_sff_interrupt(acdev->irq, acdev->host);
spin_lock_irqsave(&acdev->host->lock, flags);
if (unlikely(qc->err_mask) && ata_is_dma(qc->tf.protocol))
ata_ehi_push_desc(&qc->ap->link.eh_info, "DMA Failed: Timeout");
spin_unlock_irqrestore(&acdev->host->lock, flags);
}
static inline int wait4buf(struct arasan_cf_dev *acdev)
{
if (!wait_for_completion_timeout(&acdev->cf_completion, TIMEOUT)) {
u32 rw = acdev->qc->tf.flags & ATA_TFLAG_WRITE;
dev_err(acdev->host->dev, "%s TimeOut", rw ? "write" : "read");
return -ETIMEDOUT;
}
/* Check if PIO Error interrupt has occurred */
if (acdev->dma_status & ATA_DMA_ERR)
return -EAGAIN;
return 0;
}
static int
dma_xfer(struct arasan_cf_dev *acdev, dma_addr_t src, dma_addr_t dest, u32 len)
{
struct dma_async_tx_descriptor *tx;
struct dma_chan *chan = acdev->dma_chan;
dma_cookie_t cookie;
unsigned long flags = DMA_PREP_INTERRUPT | DMA_COMPL_SKIP_SRC_UNMAP |
DMA_COMPL_SKIP_DEST_UNMAP;
int ret = 0;
tx = chan->device->device_prep_dma_memcpy(chan, dest, src, len, flags);
if (!tx) {
dev_err(acdev->host->dev, "device_prep_dma_memcpy failed\n");
return -EAGAIN;
}
tx->callback = dma_callback;
tx->callback_param = acdev;
cookie = tx->tx_submit(tx);
ret = dma_submit_error(cookie);
if (ret) {
dev_err(acdev->host->dev, "dma_submit_error\n");
return ret;
}
chan->device->device_issue_pending(chan);
/* Wait for DMA to complete */
if (!wait_for_completion_timeout(&acdev->dma_completion, TIMEOUT)) {
chan->device->device_control(chan, DMA_TERMINATE_ALL, 0);
dev_err(acdev->host->dev, "wait_for_completion_timeout\n");
return -ETIMEDOUT;
}
return ret;
}
static int sg_xfer(struct arasan_cf_dev *acdev, struct scatterlist *sg)
{
dma_addr_t dest = 0, src = 0;
u32 xfer_cnt, sglen, dma_len, xfer_ctr;
u32 write = acdev->qc->tf.flags & ATA_TFLAG_WRITE;
unsigned long flags;
int ret = 0;
sglen = sg_dma_len(sg);
if (write) {
src = sg_dma_address(sg);
dest = acdev->pbase + EXT_WRITE_PORT;
} else {
dest = sg_dma_address(sg);
src = acdev->pbase + EXT_READ_PORT;
}
/*
* For each sg:
* MAX_XFER_COUNT data will be transferred before we get transfer
* complete interrupt. Between after FIFO_SIZE data
* buffer available interrupt will be generated. At this time we will
* fill FIFO again: max FIFO_SIZE data.
*/
while (sglen) {
xfer_cnt = min(sglen, MAX_XFER_COUNT);
spin_lock_irqsave(&acdev->host->lock, flags);
xfer_ctr = readl(acdev->vbase + XFER_CTR) &
~XFER_COUNT_MASK;
writel(xfer_ctr | xfer_cnt | XFER_START,
acdev->vbase + XFER_CTR);
spin_unlock_irqrestore(&acdev->host->lock, flags);
/* continue dma xfers until current sg is completed */
while (xfer_cnt) {
/* wait for read to complete */
if (!write) {
ret = wait4buf(acdev);
if (ret)
goto fail;
}
/* read/write FIFO in chunk of FIFO_SIZE */
dma_len = min(xfer_cnt, FIFO_SIZE);
ret = dma_xfer(acdev, src, dest, dma_len);
if (ret) {
dev_err(acdev->host->dev, "dma failed");
goto fail;
}
if (write)
src += dma_len;
else
dest += dma_len;
sglen -= dma_len;
xfer_cnt -= dma_len;
/* wait for write to complete */
if (write) {
ret = wait4buf(acdev);
if (ret)
goto fail;
}
}
}
fail:
spin_lock_irqsave(&acdev->host->lock, flags);
writel(readl(acdev->vbase + XFER_CTR) & ~XFER_START,
acdev->vbase + XFER_CTR);
spin_unlock_irqrestore(&acdev->host->lock, flags);
return ret;
}
/*
* This routine uses External DMA controller to read/write data to FIFO of CF
* controller. There are two xfer related interrupt supported by CF controller:
* - buf_avail: This interrupt is generated as soon as we have buffer of 512
* bytes available for reading or empty buffer available for writing.
* - xfer_done: This interrupt is generated on transfer of "xfer_size" amount of
* data to/from FIFO. xfer_size is programmed in XFER_CTR register.
*
* Max buffer size = FIFO_SIZE = 512 Bytes.
* Max xfer_size = MAX_XFER_COUNT = 256 KB.
*/
static void data_xfer(struct work_struct *work)
{
struct arasan_cf_dev *acdev = container_of(work, struct arasan_cf_dev,
work);
struct ata_queued_cmd *qc = acdev->qc;
struct scatterlist *sg;
unsigned long flags;
u32 temp;
int ret = 0;
/* request dma channels */
/* dma_request_channel may sleep, so calling from process context */
acdev->dma_chan = dma_request_channel(acdev->mask, filter,
acdev->dma_priv);
if (!acdev->dma_chan) {
dev_err(acdev->host->dev, "Unable to get dma_chan\n");
goto chan_request_fail;
}
for_each_sg(qc->sg, sg, qc->n_elem, temp) {
ret = sg_xfer(acdev, sg);
if (ret)
break;
}
dma_release_channel(acdev->dma_chan);
/* data xferred successfully */
if (!ret) {
u32 status;
spin_lock_irqsave(&acdev->host->lock, flags);
status = ioread8(qc->ap->ioaddr.altstatus_addr);
spin_unlock_irqrestore(&acdev->host->lock, flags);
if (status & (ATA_BUSY | ATA_DRQ)) {
ata_sff_queue_delayed_work(&acdev->dwork, 1);
return;
}
goto sff_intr;
}
cf_dumpregs(acdev);
chan_request_fail:
spin_lock_irqsave(&acdev->host->lock, flags);
/* error when transferring data to/from memory */
qc->err_mask |= AC_ERR_HOST_BUS;
qc->ap->hsm_task_state = HSM_ST_ERR;
cf_ctrl_reset(acdev);
spin_unlock_irqrestore(qc->ap->lock, flags);
sff_intr:
dma_complete(acdev);
}
static void delayed_finish(struct work_struct *work)
{
struct arasan_cf_dev *acdev = container_of(work, struct arasan_cf_dev,
dwork.work);
struct ata_queued_cmd *qc = acdev->qc;
unsigned long flags;
u8 status;
spin_lock_irqsave(&acdev->host->lock, flags);
status = ioread8(qc->ap->ioaddr.altstatus_addr);
spin_unlock_irqrestore(&acdev->host->lock, flags);
if (status & (ATA_BUSY | ATA_DRQ))
ata_sff_queue_delayed_work(&acdev->dwork, 1);
else
dma_complete(acdev);
}
static irqreturn_t arasan_cf_interrupt(int irq, void *dev)
{
struct arasan_cf_dev *acdev = ((struct ata_host *)dev)->private_data;
unsigned long flags;
u32 irqsts;
irqsts = readl(acdev->vbase + GIRQ_STS);
if (!(irqsts & GIRQ_CF))
return IRQ_NONE;
spin_lock_irqsave(&acdev->host->lock, flags);
irqsts = readl(acdev->vbase + IRQ_STS);
writel(irqsts, acdev->vbase + IRQ_STS); /* clear irqs */
writel(GIRQ_CF, acdev->vbase + GIRQ_STS); /* clear girqs */
/* handle only relevant interrupts */
irqsts &= ~IGNORED_IRQS;
if (irqsts & CARD_DETECT_IRQ) {
cf_card_detect(acdev, 1);
spin_unlock_irqrestore(&acdev->host->lock, flags);
return IRQ_HANDLED;
}
if (irqsts & PIO_XFER_ERR_IRQ) {
acdev->dma_status = ATA_DMA_ERR;
writel(readl(acdev->vbase + XFER_CTR) & ~XFER_START,
acdev->vbase + XFER_CTR);
spin_unlock_irqrestore(&acdev->host->lock, flags);
complete(&acdev->cf_completion);
dev_err(acdev->host->dev, "pio xfer err irq\n");
return IRQ_HANDLED;
}
spin_unlock_irqrestore(&acdev->host->lock, flags);
if (irqsts & BUF_AVAIL_IRQ) {
complete(&acdev->cf_completion);
return IRQ_HANDLED;
}
if (irqsts & XFER_DONE_IRQ) {
struct ata_queued_cmd *qc = acdev->qc;
/* Send Complete only for write */
if (qc->tf.flags & ATA_TFLAG_WRITE)
complete(&acdev->cf_completion);
}
return IRQ_HANDLED;
}
static void arasan_cf_freeze(struct ata_port *ap)
{
struct arasan_cf_dev *acdev = ap->host->private_data;
/* stop transfer and reset controller */
writel(readl(acdev->vbase + XFER_CTR) & ~XFER_START,
acdev->vbase + XFER_CTR);
cf_ctrl_reset(acdev);
acdev->dma_status = ATA_DMA_ERR;
ata_sff_dma_pause(ap);
ata_sff_freeze(ap);
}
void arasan_cf_error_handler(struct ata_port *ap)
{
struct arasan_cf_dev *acdev = ap->host->private_data;
/*
* DMA transfers using an external DMA controller may be scheduled.
* Abort them before handling error. Refer data_xfer() for further
* details.
*/
cancel_work_sync(&acdev->work);
cancel_delayed_work_sync(&acdev->dwork);
return ata_sff_error_handler(ap);
}
static void arasan_cf_dma_start(struct arasan_cf_dev *acdev)
{
u32 xfer_ctr = readl(acdev->vbase + XFER_CTR) & ~XFER_DIR_MASK;
u32 write = acdev->qc->tf.flags & ATA_TFLAG_WRITE;
xfer_ctr |= write ? XFER_WRITE : XFER_READ;
writel(xfer_ctr, acdev->vbase + XFER_CTR);
acdev->qc->ap->ops->sff_exec_command(acdev->qc->ap, &acdev->qc->tf);
ata_sff_queue_work(&acdev->work);
}
unsigned int arasan_cf_qc_issue(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct arasan_cf_dev *acdev = ap->host->private_data;
/* defer PIO handling to sff_qc_issue */
if (!ata_is_dma(qc->tf.protocol))
return ata_sff_qc_issue(qc);
/* select the device */
ata_wait_idle(ap);
ata_sff_dev_select(ap, qc->dev->devno);
ata_wait_idle(ap);
/* start the command */
switch (qc->tf.protocol) {
case ATA_PROT_DMA:
WARN_ON_ONCE(qc->tf.flags & ATA_TFLAG_POLLING);
ap->ops->sff_tf_load(ap, &qc->tf);
acdev->dma_status = 0;
acdev->qc = qc;
arasan_cf_dma_start(acdev);
ap->hsm_task_state = HSM_ST_LAST;
break;
default:
WARN_ON(1);
return AC_ERR_SYSTEM;
}
return 0;
}
static void arasan_cf_set_piomode(struct ata_port *ap, struct ata_device *adev)
{
struct arasan_cf_dev *acdev = ap->host->private_data;
u8 pio = adev->pio_mode - XFER_PIO_0;
unsigned long flags;
u32 val;
/* Arasan ctrl supports Mode0 -> Mode6 */
if (pio > 6) {
dev_err(ap->dev, "Unknown PIO mode\n");
return;
}
spin_lock_irqsave(&acdev->host->lock, flags);
val = readl(acdev->vbase + OP_MODE) &
~(ULTRA_DMA_ENB | MULTI_WORD_DMA_ENB | DRQ_BLOCK_SIZE_MASK);
writel(val, acdev->vbase + OP_MODE);
val = readl(acdev->vbase + TM_CFG) & ~TRUEIDE_PIO_TIMING_MASK;
val |= pio << TRUEIDE_PIO_TIMING_SHIFT;
writel(val, acdev->vbase + TM_CFG);
cf_interrupt_enable(acdev, BUF_AVAIL_IRQ | XFER_DONE_IRQ, 0);
cf_interrupt_enable(acdev, PIO_XFER_ERR_IRQ, 1);
spin_unlock_irqrestore(&acdev->host->lock, flags);
}
static void arasan_cf_set_dmamode(struct ata_port *ap, struct ata_device *adev)
{
struct arasan_cf_dev *acdev = ap->host->private_data;
u32 opmode, tmcfg, dma_mode = adev->dma_mode;
unsigned long flags;
spin_lock_irqsave(&acdev->host->lock, flags);
opmode = readl(acdev->vbase + OP_MODE) &
~(MULTI_WORD_DMA_ENB | ULTRA_DMA_ENB);
tmcfg = readl(acdev->vbase + TM_CFG);
if ((dma_mode >= XFER_UDMA_0) && (dma_mode <= XFER_UDMA_6)) {
opmode |= ULTRA_DMA_ENB;
tmcfg &= ~ULTRA_DMA_TIMING_MASK;
tmcfg |= (dma_mode - XFER_UDMA_0) << ULTRA_DMA_TIMING_SHIFT;
} else if ((dma_mode >= XFER_MW_DMA_0) && (dma_mode <= XFER_MW_DMA_4)) {
opmode |= MULTI_WORD_DMA_ENB;
tmcfg &= ~TRUEIDE_MWORD_DMA_TIMING_MASK;
tmcfg |= (dma_mode - XFER_MW_DMA_0) <<
TRUEIDE_MWORD_DMA_TIMING_SHIFT;
} else {
dev_err(ap->dev, "Unknown DMA mode\n");
spin_unlock_irqrestore(&acdev->host->lock, flags);
return;
}
writel(opmode, acdev->vbase + OP_MODE);
writel(tmcfg, acdev->vbase + TM_CFG);
writel(DMA_XFER_MODE, acdev->vbase + XFER_CTR);
cf_interrupt_enable(acdev, PIO_XFER_ERR_IRQ, 0);
cf_interrupt_enable(acdev, BUF_AVAIL_IRQ | XFER_DONE_IRQ, 1);
spin_unlock_irqrestore(&acdev->host->lock, flags);
}
static struct ata_port_operations arasan_cf_ops = {
.inherits = &ata_sff_port_ops,
.freeze = arasan_cf_freeze,
.error_handler = arasan_cf_error_handler,
.qc_issue = arasan_cf_qc_issue,
.set_piomode = arasan_cf_set_piomode,
.set_dmamode = arasan_cf_set_dmamode,
};
static int __devinit arasan_cf_probe(struct platform_device *pdev)
{
struct arasan_cf_dev *acdev;
struct arasan_cf_pdata *pdata = dev_get_platdata(&pdev->dev);
struct ata_host *host;
struct ata_port *ap;
struct resource *res;
irq_handler_t irq_handler = NULL;
int ret = 0;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res)
return -EINVAL;
if (!devm_request_mem_region(&pdev->dev, res->start, resource_size(res),
DRIVER_NAME)) {
dev_warn(&pdev->dev, "Failed to get memory region resource\n");
return -ENOENT;
}
acdev = devm_kzalloc(&pdev->dev, sizeof(*acdev), GFP_KERNEL);
if (!acdev) {
dev_warn(&pdev->dev, "kzalloc fail\n");
return -ENOMEM;
}
/* if irq is 0, support only PIO */
acdev->irq = platform_get_irq(pdev, 0);
if (acdev->irq)
irq_handler = arasan_cf_interrupt;
else
pdata->quirk |= CF_BROKEN_MWDMA | CF_BROKEN_UDMA;
acdev->pbase = res->start;
acdev->vbase = devm_ioremap_nocache(&pdev->dev, res->start,
resource_size(res));
if (!acdev->vbase) {
dev_warn(&pdev->dev, "ioremap fail\n");
return -ENOMEM;
}
#ifdef CONFIG_HAVE_CLK
acdev->clk = clk_get(&pdev->dev, NULL);
if (IS_ERR(acdev->clk)) {
dev_warn(&pdev->dev, "Clock not found\n");
return PTR_ERR(acdev->clk);
}
#endif
/* allocate host */
host = ata_host_alloc(&pdev->dev, 1);
if (!host) {
ret = -ENOMEM;
dev_warn(&pdev->dev, "alloc host fail\n");
goto free_clk;
}
ap = host->ports[0];
host->private_data = acdev;
acdev->host = host;
ap->ops = &arasan_cf_ops;
ap->pio_mask = ATA_PIO6;
ap->mwdma_mask = ATA_MWDMA4;
ap->udma_mask = ATA_UDMA6;
init_completion(&acdev->cf_completion);
init_completion(&acdev->dma_completion);
INIT_WORK(&acdev->work, data_xfer);
INIT_DELAYED_WORK(&acdev->dwork, delayed_finish);
dma_cap_set(DMA_MEMCPY, acdev->mask);
acdev->dma_priv = pdata->dma_priv;
/* Handle platform specific quirks */
if (pdata->quirk) {
if (pdata->quirk & CF_BROKEN_PIO) {
ap->ops->set_piomode = NULL;
ap->pio_mask = 0;
}
if (pdata->quirk & CF_BROKEN_MWDMA)
ap->mwdma_mask = 0;
if (pdata->quirk & CF_BROKEN_UDMA)
ap->udma_mask = 0;
}
ap->flags |= ATA_FLAG_PIO_POLLING | ATA_FLAG_NO_ATAPI;
ap->ioaddr.cmd_addr = acdev->vbase + ATA_DATA_PORT;
ap->ioaddr.data_addr = acdev->vbase + ATA_DATA_PORT;
ap->ioaddr.error_addr = acdev->vbase + ATA_ERR_FTR;
ap->ioaddr.feature_addr = acdev->vbase + ATA_ERR_FTR;
ap->ioaddr.nsect_addr = acdev->vbase + ATA_SC;
ap->ioaddr.lbal_addr = acdev->vbase + ATA_SN;
ap->ioaddr.lbam_addr = acdev->vbase + ATA_CL;
ap->ioaddr.lbah_addr = acdev->vbase + ATA_CH;
ap->ioaddr.device_addr = acdev->vbase + ATA_SH;
ap->ioaddr.status_addr = acdev->vbase + ATA_STS_CMD;
ap->ioaddr.command_addr = acdev->vbase + ATA_STS_CMD;
ap->ioaddr.altstatus_addr = acdev->vbase + ATA_ASTS_DCTR;
ap->ioaddr.ctl_addr = acdev->vbase + ATA_ASTS_DCTR;
ata_port_desc(ap, "phy_addr %llx virt_addr %p",
(unsigned long long) res->start, acdev->vbase);
ret = cf_init(acdev);
if (ret)
goto free_clk;
cf_card_detect(acdev, 0);
return ata_host_activate(host, acdev->irq, irq_handler, 0,
&arasan_cf_sht);
free_clk:
#ifdef CONFIG_HAVE_CLK
clk_put(acdev->clk);
#endif
return ret;
}
static int __devexit arasan_cf_remove(struct platform_device *pdev)
{
struct ata_host *host = dev_get_drvdata(&pdev->dev);
struct arasan_cf_dev *acdev = host->ports[0]->private_data;
ata_host_detach(host);
cf_exit(acdev);
#ifdef CONFIG_HAVE_CLK
clk_put(acdev->clk);
#endif
return 0;
}
#ifdef CONFIG_PM
static int arasan_cf_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct ata_host *host = dev_get_drvdata(&pdev->dev);
struct arasan_cf_dev *acdev = host->ports[0]->private_data;
if (acdev->dma_chan) {
acdev->dma_chan->device->device_control(acdev->dma_chan,
DMA_TERMINATE_ALL, 0);
dma_release_channel(acdev->dma_chan);
}
cf_exit(acdev);
return ata_host_suspend(host, PMSG_SUSPEND);
}
static int arasan_cf_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct ata_host *host = dev_get_drvdata(&pdev->dev);
struct arasan_cf_dev *acdev = host->ports[0]->private_data;
cf_init(acdev);
ata_host_resume(host);
return 0;
}
static const struct dev_pm_ops arasan_cf_pm_ops = {
.suspend = arasan_cf_suspend,
.resume = arasan_cf_resume,
};
#endif
static struct platform_driver arasan_cf_driver = {
.probe = arasan_cf_probe,
.remove = __devexit_p(arasan_cf_remove),
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE,
#ifdef CONFIG_PM
.pm = &arasan_cf_pm_ops,
#endif
},
};
static int __init arasan_cf_init(void)
{
return platform_driver_register(&arasan_cf_driver);
}
module_init(arasan_cf_init);
static void __exit arasan_cf_exit(void)
{
platform_driver_unregister(&arasan_cf_driver);
}
module_exit(arasan_cf_exit);
MODULE_AUTHOR("Viresh Kumar <viresh.kumar@st.com>");
MODULE_DESCRIPTION("Arasan ATA Compact Flash driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:" DRIVER_NAME);
| gpl-2.0 |
libing64/manifold_linux | arch/mips/ath79/common.c | 3427 | 2868 | /*
* Atheros AR71XX/AR724X/AR913X common routines
*
* Copyright (C) 2010-2011 Jaiganesh Narayanan <jnarayanan@atheros.com>
* Copyright (C) 2008-2011 Gabor Juhos <juhosg@openwrt.org>
* Copyright (C) 2008 Imre Kaloz <kaloz@openwrt.org>
*
* Parts of this file are based on Atheros' 2.6.15/2.6.31 BSP
*
* 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/module.h>
#include <linux/types.h>
#include <linux/spinlock.h>
#include <asm/mach-ath79/ath79.h>
#include <asm/mach-ath79/ar71xx_regs.h>
#include "common.h"
static DEFINE_SPINLOCK(ath79_device_reset_lock);
u32 ath79_cpu_freq;
EXPORT_SYMBOL_GPL(ath79_cpu_freq);
u32 ath79_ahb_freq;
EXPORT_SYMBOL_GPL(ath79_ahb_freq);
u32 ath79_ddr_freq;
EXPORT_SYMBOL_GPL(ath79_ddr_freq);
enum ath79_soc_type ath79_soc;
unsigned int ath79_soc_rev;
void __iomem *ath79_pll_base;
void __iomem *ath79_reset_base;
EXPORT_SYMBOL_GPL(ath79_reset_base);
void __iomem *ath79_ddr_base;
void ath79_ddr_wb_flush(u32 reg)
{
void __iomem *flush_reg = ath79_ddr_base + reg;
/* Flush the DDR write buffer. */
__raw_writel(0x1, flush_reg);
while (__raw_readl(flush_reg) & 0x1)
;
/* It must be run twice. */
__raw_writel(0x1, flush_reg);
while (__raw_readl(flush_reg) & 0x1)
;
}
EXPORT_SYMBOL_GPL(ath79_ddr_wb_flush);
void ath79_device_reset_set(u32 mask)
{
unsigned long flags;
u32 reg;
u32 t;
if (soc_is_ar71xx())
reg = AR71XX_RESET_REG_RESET_MODULE;
else if (soc_is_ar724x())
reg = AR724X_RESET_REG_RESET_MODULE;
else if (soc_is_ar913x())
reg = AR913X_RESET_REG_RESET_MODULE;
else if (soc_is_ar933x())
reg = AR933X_RESET_REG_RESET_MODULE;
else if (soc_is_ar934x())
reg = AR934X_RESET_REG_RESET_MODULE;
else if (soc_is_qca955x())
reg = QCA955X_RESET_REG_RESET_MODULE;
else
BUG();
spin_lock_irqsave(&ath79_device_reset_lock, flags);
t = ath79_reset_rr(reg);
ath79_reset_wr(reg, t | mask);
spin_unlock_irqrestore(&ath79_device_reset_lock, flags);
}
EXPORT_SYMBOL_GPL(ath79_device_reset_set);
void ath79_device_reset_clear(u32 mask)
{
unsigned long flags;
u32 reg;
u32 t;
if (soc_is_ar71xx())
reg = AR71XX_RESET_REG_RESET_MODULE;
else if (soc_is_ar724x())
reg = AR724X_RESET_REG_RESET_MODULE;
else if (soc_is_ar913x())
reg = AR913X_RESET_REG_RESET_MODULE;
else if (soc_is_ar933x())
reg = AR933X_RESET_REG_RESET_MODULE;
else if (soc_is_ar934x())
reg = AR934X_RESET_REG_RESET_MODULE;
else if (soc_is_qca955x())
reg = QCA955X_RESET_REG_RESET_MODULE;
else
BUG();
spin_lock_irqsave(&ath79_device_reset_lock, flags);
t = ath79_reset_rr(reg);
ath79_reset_wr(reg, t & ~mask);
spin_unlock_irqrestore(&ath79_device_reset_lock, flags);
}
EXPORT_SYMBOL_GPL(ath79_device_reset_clear);
| gpl-2.0 |
uwehermann/easybox-904-lte-firmware | linux/linux-2.6.32.32/arch/powerpc/kernel/module_64.c | 3939 | 13375 | /* Kernel module help for PPC64.
Copyright (C) 2001, 2003 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/module.h>
#include <linux/elf.h>
#include <linux/moduleloader.h>
#include <linux/err.h>
#include <linux/vmalloc.h>
#include <linux/ftrace.h>
#include <linux/bug.h>
#include <asm/module.h>
#include <asm/firmware.h>
#include <asm/code-patching.h>
#include <linux/sort.h>
#include "setup.h"
/* FIXME: We don't do .init separately. To do this, we'd need to have
a separate r2 value in the init and core section, and stub between
them, too.
Using a magic allocator which places modules within 32MB solves
this, and makes other things simpler. Anton?
--RR. */
#if 0
#define DEBUGP printk
#else
#define DEBUGP(fmt , ...)
#endif
/* Like PPC32, we need little trampolines to do > 24-bit jumps (into
the kernel itself). But on PPC64, these need to be used for every
jump, actually, to reset r2 (TOC+0x8000). */
struct ppc64_stub_entry
{
/* 28 byte jump instruction sequence (7 instructions) */
unsigned char jump[28];
unsigned char unused[4];
/* Data for the above code */
struct ppc64_opd_entry opd;
};
/* We use a stub to fix up r2 (TOC ptr) and to jump to the (external)
function which may be more than 24-bits away. We could simply
patch the new r2 value and function pointer into the stub, but it's
significantly shorter to put these values at the end of the stub
code, and patch the stub address (32-bits relative to the TOC ptr,
r2) into the stub. */
static struct ppc64_stub_entry ppc64_stub =
{ .jump = {
0x3d, 0x82, 0x00, 0x00, /* addis r12,r2, <high> */
0x39, 0x8c, 0x00, 0x00, /* addi r12,r12, <low> */
/* Save current r2 value in magic place on the stack. */
0xf8, 0x41, 0x00, 0x28, /* std r2,40(r1) */
0xe9, 0x6c, 0x00, 0x20, /* ld r11,32(r12) */
0xe8, 0x4c, 0x00, 0x28, /* ld r2,40(r12) */
0x7d, 0x69, 0x03, 0xa6, /* mtctr r11 */
0x4e, 0x80, 0x04, 0x20 /* bctr */
} };
/* Count how many different 24-bit relocations (different symbol,
different addend) */
static unsigned int count_relocs(const Elf64_Rela *rela, unsigned int num)
{
unsigned int i, r_info, r_addend, _count_relocs;
/* FIXME: Only count external ones --RR */
_count_relocs = 0;
r_info = 0;
r_addend = 0;
for (i = 0; i < num; i++)
/* Only count 24-bit relocs, others don't need stubs */
if (ELF64_R_TYPE(rela[i].r_info) == R_PPC_REL24 &&
(r_info != ELF64_R_SYM(rela[i].r_info) ||
r_addend != rela[i].r_addend)) {
_count_relocs++;
r_info = ELF64_R_SYM(rela[i].r_info);
r_addend = rela[i].r_addend;
}
return _count_relocs;
}
static int relacmp(const void *_x, const void *_y)
{
const Elf64_Rela *x, *y;
y = (Elf64_Rela *)_x;
x = (Elf64_Rela *)_y;
/* Compare the entire r_info (as opposed to ELF64_R_SYM(r_info) only) to
* make the comparison cheaper/faster. It won't affect the sorting or
* the counting algorithms' performance
*/
if (x->r_info < y->r_info)
return -1;
else if (x->r_info > y->r_info)
return 1;
else if (x->r_addend < y->r_addend)
return -1;
else if (x->r_addend > y->r_addend)
return 1;
else
return 0;
}
static void relaswap(void *_x, void *_y, int size)
{
uint64_t *x, *y, tmp;
int i;
y = (uint64_t *)_x;
x = (uint64_t *)_y;
for (i = 0; i < sizeof(Elf64_Rela) / sizeof(uint64_t); i++) {
tmp = x[i];
x[i] = y[i];
y[i] = tmp;
}
}
/* Get size of potential trampolines required. */
static unsigned long get_stubs_size(const Elf64_Ehdr *hdr,
const Elf64_Shdr *sechdrs)
{
/* One extra reloc so it's always 0-funcaddr terminated */
unsigned long relocs = 1;
unsigned i;
/* Every relocated section... */
for (i = 1; i < hdr->e_shnum; i++) {
if (sechdrs[i].sh_type == SHT_RELA) {
DEBUGP("Found relocations in section %u\n", i);
DEBUGP("Ptr: %p. Number: %lu\n",
(void *)sechdrs[i].sh_addr,
sechdrs[i].sh_size / sizeof(Elf64_Rela));
/* Sort the relocation information based on a symbol and
* addend key. This is a stable O(n*log n) complexity
* alogrithm but it will reduce the complexity of
* count_relocs() to linear complexity O(n)
*/
sort((void *)sechdrs[i].sh_addr,
sechdrs[i].sh_size / sizeof(Elf64_Rela),
sizeof(Elf64_Rela), relacmp, relaswap);
relocs += count_relocs((void *)sechdrs[i].sh_addr,
sechdrs[i].sh_size
/ sizeof(Elf64_Rela));
}
}
#ifdef CONFIG_DYNAMIC_FTRACE
/* make the trampoline to the ftrace_caller */
relocs++;
#endif
DEBUGP("Looks like a total of %lu stubs, max\n", relocs);
return relocs * sizeof(struct ppc64_stub_entry);
}
static void dedotify_versions(struct modversion_info *vers,
unsigned long size)
{
struct modversion_info *end;
for (end = (void *)vers + size; vers < end; vers++)
if (vers->name[0] == '.')
memmove(vers->name, vers->name+1, strlen(vers->name));
}
/* Undefined symbols which refer to .funcname, hack to funcname */
static void dedotify(Elf64_Sym *syms, unsigned int numsyms, char *strtab)
{
unsigned int i;
for (i = 1; i < numsyms; i++) {
if (syms[i].st_shndx == SHN_UNDEF) {
char *name = strtab + syms[i].st_name;
if (name[0] == '.')
memmove(name, name+1, strlen(name));
}
}
}
int module_frob_arch_sections(Elf64_Ehdr *hdr,
Elf64_Shdr *sechdrs,
char *secstrings,
struct module *me)
{
unsigned int i;
/* Find .toc and .stubs sections, symtab and strtab */
for (i = 1; i < hdr->e_shnum; i++) {
char *p;
if (strcmp(secstrings + sechdrs[i].sh_name, ".stubs") == 0)
me->arch.stubs_section = i;
else if (strcmp(secstrings + sechdrs[i].sh_name, ".toc") == 0)
me->arch.toc_section = i;
else if (strcmp(secstrings+sechdrs[i].sh_name,"__versions")==0)
dedotify_versions((void *)hdr + sechdrs[i].sh_offset,
sechdrs[i].sh_size);
/* We don't handle .init for the moment: rename to _init */
while ((p = strstr(secstrings + sechdrs[i].sh_name, ".init")))
p[0] = '_';
if (sechdrs[i].sh_type == SHT_SYMTAB)
dedotify((void *)hdr + sechdrs[i].sh_offset,
sechdrs[i].sh_size / sizeof(Elf64_Sym),
(void *)hdr
+ sechdrs[sechdrs[i].sh_link].sh_offset);
}
if (!me->arch.stubs_section) {
printk("%s: doesn't contain .stubs.\n", me->name);
return -ENOEXEC;
}
/* If we don't have a .toc, just use .stubs. We need to set r2
to some reasonable value in case the module calls out to
other functions via a stub, or if a function pointer escapes
the module by some means. */
if (!me->arch.toc_section)
me->arch.toc_section = me->arch.stubs_section;
/* Override the stubs size */
sechdrs[me->arch.stubs_section].sh_size = get_stubs_size(hdr, sechdrs);
return 0;
}
int apply_relocate(Elf64_Shdr *sechdrs,
const char *strtab,
unsigned int symindex,
unsigned int relsec,
struct module *me)
{
printk(KERN_ERR "%s: Non-ADD RELOCATION unsupported\n", me->name);
return -ENOEXEC;
}
/* r2 is the TOC pointer: it actually points 0x8000 into the TOC (this
gives the value maximum span in an instruction which uses a signed
offset) */
static inline unsigned long my_r2(Elf64_Shdr *sechdrs, struct module *me)
{
return sechdrs[me->arch.toc_section].sh_addr + 0x8000;
}
/* Both low and high 16 bits are added as SIGNED additions, so if low
16 bits has high bit set, high 16 bits must be adjusted. These
macros do that (stolen from binutils). */
#define PPC_LO(v) ((v) & 0xffff)
#define PPC_HI(v) (((v) >> 16) & 0xffff)
#define PPC_HA(v) PPC_HI ((v) + 0x8000)
/* Patch stub to reference function and correct r2 value. */
static inline int create_stub(Elf64_Shdr *sechdrs,
struct ppc64_stub_entry *entry,
struct ppc64_opd_entry *opd,
struct module *me)
{
Elf64_Half *loc1, *loc2;
long reladdr;
*entry = ppc64_stub;
loc1 = (Elf64_Half *)&entry->jump[2];
loc2 = (Elf64_Half *)&entry->jump[6];
/* Stub uses address relative to r2. */
reladdr = (unsigned long)entry - my_r2(sechdrs, me);
if (reladdr > 0x7FFFFFFF || reladdr < -(0x80000000L)) {
printk("%s: Address %p of stub out of range of %p.\n",
me->name, (void *)reladdr, (void *)my_r2);
return 0;
}
DEBUGP("Stub %p get data from reladdr %li\n", entry, reladdr);
*loc1 = PPC_HA(reladdr);
*loc2 = PPC_LO(reladdr);
entry->opd.funcaddr = opd->funcaddr;
entry->opd.r2 = opd->r2;
return 1;
}
/* Create stub to jump to function described in this OPD: we need the
stub to set up the TOC ptr (r2) for the function. */
static unsigned long stub_for_addr(Elf64_Shdr *sechdrs,
unsigned long opdaddr,
struct module *me)
{
struct ppc64_stub_entry *stubs;
struct ppc64_opd_entry *opd = (void *)opdaddr;
unsigned int i, num_stubs;
num_stubs = sechdrs[me->arch.stubs_section].sh_size / sizeof(*stubs);
/* Find this stub, or if that fails, the next avail. entry */
stubs = (void *)sechdrs[me->arch.stubs_section].sh_addr;
for (i = 0; stubs[i].opd.funcaddr; i++) {
BUG_ON(i >= num_stubs);
if (stubs[i].opd.funcaddr == opd->funcaddr)
return (unsigned long)&stubs[i];
}
if (!create_stub(sechdrs, &stubs[i], opd, me))
return 0;
return (unsigned long)&stubs[i];
}
/* We expect a noop next: if it is, replace it with instruction to
restore r2. */
static int restore_r2(u32 *instruction, struct module *me)
{
if (*instruction != PPC_INST_NOP) {
printk("%s: Expect noop after relocate, got %08x\n",
me->name, *instruction);
return 0;
}
*instruction = 0xe8410028; /* ld r2,40(r1) */
return 1;
}
int apply_relocate_add(Elf64_Shdr *sechdrs,
const char *strtab,
unsigned int symindex,
unsigned int relsec,
struct module *me)
{
unsigned int i;
Elf64_Rela *rela = (void *)sechdrs[relsec].sh_addr;
Elf64_Sym *sym;
unsigned long *location;
unsigned long value;
DEBUGP("Applying ADD relocate section %u to %u\n", relsec,
sechdrs[relsec].sh_info);
for (i = 0; i < sechdrs[relsec].sh_size / sizeof(*rela); i++) {
/* This is where to make the change */
location = (void *)sechdrs[sechdrs[relsec].sh_info].sh_addr
+ rela[i].r_offset;
/* This is the symbol it is referring to */
sym = (Elf64_Sym *)sechdrs[symindex].sh_addr
+ ELF64_R_SYM(rela[i].r_info);
DEBUGP("RELOC at %p: %li-type as %s (%lu) + %li\n",
location, (long)ELF64_R_TYPE(rela[i].r_info),
strtab + sym->st_name, (unsigned long)sym->st_value,
(long)rela[i].r_addend);
/* `Everything is relative'. */
value = sym->st_value + rela[i].r_addend;
switch (ELF64_R_TYPE(rela[i].r_info)) {
case R_PPC64_ADDR32:
/* Simply set it */
*(u32 *)location = value;
break;
case R_PPC64_ADDR64:
/* Simply set it */
*(unsigned long *)location = value;
break;
case R_PPC64_TOC:
*(unsigned long *)location = my_r2(sechdrs, me);
break;
case R_PPC64_TOC16:
/* Subtract TOC pointer */
value -= my_r2(sechdrs, me);
if (value + 0x8000 > 0xffff) {
printk("%s: bad TOC16 relocation (%lu)\n",
me->name, value);
return -ENOEXEC;
}
*((uint16_t *) location)
= (*((uint16_t *) location) & ~0xffff)
| (value & 0xffff);
break;
case R_PPC64_TOC16_DS:
/* Subtract TOC pointer */
value -= my_r2(sechdrs, me);
if ((value & 3) != 0 || value + 0x8000 > 0xffff) {
printk("%s: bad TOC16_DS relocation (%lu)\n",
me->name, value);
return -ENOEXEC;
}
*((uint16_t *) location)
= (*((uint16_t *) location) & ~0xfffc)
| (value & 0xfffc);
break;
case R_PPC_REL24:
/* FIXME: Handle weak symbols here --RR */
if (sym->st_shndx == SHN_UNDEF) {
/* External: go via stub */
value = stub_for_addr(sechdrs, value, me);
if (!value)
return -ENOENT;
if (!restore_r2((u32 *)location + 1, me))
return -ENOEXEC;
}
/* Convert value to relative */
value -= (unsigned long)location;
if (value + 0x2000000 > 0x3ffffff || (value & 3) != 0){
printk("%s: REL24 %li out of range!\n",
me->name, (long int)value);
return -ENOEXEC;
}
/* Only replace bits 2 through 26 */
*(uint32_t *)location
= (*(uint32_t *)location & ~0x03fffffc)
| (value & 0x03fffffc);
break;
case R_PPC64_REL64:
/* 64 bits relative (used by features fixups) */
*location = value - (unsigned long)location;
break;
default:
printk("%s: Unknown ADD relocation: %lu\n",
me->name,
(unsigned long)ELF64_R_TYPE(rela[i].r_info));
return -ENOEXEC;
}
}
#ifdef CONFIG_DYNAMIC_FTRACE
me->arch.toc = my_r2(sechdrs, me);
me->arch.tramp = stub_for_addr(sechdrs,
(unsigned long)ftrace_caller,
me);
#endif
return 0;
}
| gpl-2.0 |
faux123/Endeavoru | drivers/net/wireless/bcm4329/siutils.c | 4195 | 35763 | /*
* Misc utility routines for accessing chip-specific features
* of the SiliconBackplane-based Broadcom chips.
*
* Copyright (C) 1999-2010, Broadcom Corporation
*
* Unless you and Broadcom execute a separate written software license
* agreement governing use of this software, this software is licensed to you
* under the terms of the GNU General Public License version 2 (the "GPL"),
* available at http://www.broadcom.com/licenses/GPLv2.php, with the
* following added to such license:
*
* As a special exception, the copyright holders of this software give you
* permission to link this software with independent modules, and to copy and
* distribute the resulting executable under terms of your choice, provided that
* you also meet, for each linked independent module, the terms and conditions of
* the license of that module. An independent module is a module which is not
* derived from this software. The special exception does not apply to any
* modifications of the software.
*
* Notwithstanding the above, under no circumstances may you combine this
* software in any way with any other Broadcom software provided under a license
* other than the GPL, without Broadcom's express prior written consent.
*
* $Id: siutils.c,v 1.662.4.4.4.16.4.28 2010/06/23 21:37:54 Exp $
*/
#include <typedefs.h>
#include <bcmdefs.h>
#include <osl.h>
#include <bcmutils.h>
#include <siutils.h>
#include <bcmdevs.h>
#include <hndsoc.h>
#include <sbchipc.h>
#include <pcicfg.h>
#include <sbpcmcia.h>
#include <sbsocram.h>
#include <bcmsdh.h>
#include <sdio.h>
#include <sbsdio.h>
#include <sbhnddma.h>
#include <sbsdpcmdev.h>
#include <bcmsdpcm.h>
#include <hndpmu.h>
#include "siutils_priv.h"
/* local prototypes */
static si_info_t *si_doattach(si_info_t *sii, uint devid, osl_t *osh, void *regs,
uint bustype, void *sdh, char **vars, uint *varsz);
static bool si_buscore_prep(si_info_t *sii, uint bustype, uint devid, void *sdh);
static bool si_buscore_setup(si_info_t *sii, chipcregs_t *cc, uint bustype, uint32 savewin,
uint *origidx, void *regs);
/* global variable to indicate reservation/release of gpio's */
static uint32 si_gpioreservation = 0;
static void *common_info_alloced = NULL;
/* global flag to prevent shared resources from being initialized multiple times in si_attach() */
/*
* Allocate a si handle.
* devid - pci device id (used to determine chip#)
* osh - opaque OS handle
* regs - virtual address of initial core registers
* bustype - pci/pcmcia/sb/sdio/etc
* vars - pointer to a pointer area for "environment" variables
* varsz - pointer to int to return the size of the vars
*/
si_t *
si_attach(uint devid, osl_t *osh, void *regs,
uint bustype, void *sdh, char **vars, uint *varsz)
{
si_info_t *sii;
/* alloc si_info_t */
if ((sii = MALLOC(osh, sizeof (si_info_t))) == NULL) {
SI_ERROR(("si_attach: malloc failed! malloced %d bytes\n", MALLOCED(osh)));
return (NULL);
}
if (si_doattach(sii, devid, osh, regs, bustype, sdh, vars, varsz) == NULL) {
if (NULL != sii->common_info)
MFREE(osh, sii->common_info, sizeof(si_common_info_t));
MFREE(osh, sii, sizeof(si_info_t));
return (NULL);
}
sii->vars = vars ? *vars : NULL;
sii->varsz = varsz ? *varsz : 0;
return (si_t *)sii;
}
/* global kernel resource */
static si_info_t ksii;
static uint32 wd_msticks; /* watchdog timer ticks normalized to ms */
/* generic kernel variant of si_attach() */
si_t *
si_kattach(osl_t *osh)
{
static bool ksii_attached = FALSE;
if (!ksii_attached) {
void *regs = REG_MAP(SI_ENUM_BASE, SI_CORE_SIZE);
if (si_doattach(&ksii, BCM4710_DEVICE_ID, osh, regs,
SI_BUS, NULL,
osh != SI_OSH ? &ksii.vars : NULL,
osh != SI_OSH ? &ksii.varsz : NULL) == NULL) {
if (NULL != ksii.common_info)
MFREE(osh, ksii.common_info, sizeof(si_common_info_t));
SI_ERROR(("si_kattach: si_doattach failed\n"));
REG_UNMAP(regs);
return NULL;
}
REG_UNMAP(regs);
/* save ticks normalized to ms for si_watchdog_ms() */
if (PMUCTL_ENAB(&ksii.pub)) {
/* based on 32KHz ILP clock */
wd_msticks = 32;
} else {
wd_msticks = ALP_CLOCK / 1000;
}
ksii_attached = TRUE;
SI_MSG(("si_kattach done. ccrev = %d, wd_msticks = %d\n",
ksii.pub.ccrev, wd_msticks));
}
return &ksii.pub;
}
static bool
si_buscore_prep(si_info_t *sii, uint bustype, uint devid, void *sdh)
{
/* need to set memseg flag for CF card first before any sb registers access */
if (BUSTYPE(bustype) == PCMCIA_BUS)
sii->memseg = TRUE;
if (BUSTYPE(bustype) == SDIO_BUS) {
int err;
uint8 clkset;
/* Try forcing SDIO core to do ALPAvail request only */
clkset = SBSDIO_FORCE_HW_CLKREQ_OFF | SBSDIO_ALP_AVAIL_REQ;
bcmsdh_cfg_write(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, clkset, &err);
if (!err) {
uint8 clkval;
/* If register supported, wait for ALPAvail and then force ALP */
clkval = bcmsdh_cfg_read(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, NULL);
if ((clkval & ~SBSDIO_AVBITS) == clkset) {
SPINWAIT(((clkval = bcmsdh_cfg_read(sdh, SDIO_FUNC_1,
SBSDIO_FUNC1_CHIPCLKCSR, NULL)), !SBSDIO_ALPAV(clkval)),
PMU_MAX_TRANSITION_DLY);
if (!SBSDIO_ALPAV(clkval)) {
SI_ERROR(("timeout on ALPAV wait, clkval 0x%02x\n",
clkval));
return FALSE;
}
clkset = SBSDIO_FORCE_HW_CLKREQ_OFF | SBSDIO_FORCE_ALP;
bcmsdh_cfg_write(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR,
clkset, &err);
OSL_DELAY(65);
}
}
/* Also, disable the extra SDIO pull-ups */
bcmsdh_cfg_write(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_SDIOPULLUP, 0, NULL);
}
return TRUE;
}
static bool
si_buscore_setup(si_info_t *sii, chipcregs_t *cc, uint bustype, uint32 savewin,
uint *origidx, void *regs)
{
bool pci, pcie;
uint i;
uint pciidx, pcieidx, pcirev, pcierev;
cc = si_setcoreidx(&sii->pub, SI_CC_IDX);
ASSERT((uintptr)cc);
/* get chipcommon rev */
sii->pub.ccrev = (int)si_corerev(&sii->pub);
/* get chipcommon chipstatus */
if (sii->pub.ccrev >= 11)
sii->pub.chipst = R_REG(sii->osh, &cc->chipstatus);
/* get chipcommon capabilites */
sii->pub.cccaps = R_REG(sii->osh, &cc->capabilities);
/* get pmu rev and caps */
if (sii->pub.cccaps & CC_CAP_PMU) {
sii->pub.pmucaps = R_REG(sii->osh, &cc->pmucapabilities);
sii->pub.pmurev = sii->pub.pmucaps & PCAP_REV_MASK;
}
SI_MSG(("Chipc: rev %d, caps 0x%x, chipst 0x%x pmurev %d, pmucaps 0x%x\n",
sii->pub.ccrev, sii->pub.cccaps, sii->pub.chipst, sii->pub.pmurev,
sii->pub.pmucaps));
/* figure out bus/orignal core idx */
sii->pub.buscoretype = NODEV_CORE_ID;
sii->pub.buscorerev = NOREV;
sii->pub.buscoreidx = BADIDX;
pci = pcie = FALSE;
pcirev = pcierev = NOREV;
pciidx = pcieidx = BADIDX;
for (i = 0; i < sii->numcores; i++) {
uint cid, crev;
si_setcoreidx(&sii->pub, i);
cid = si_coreid(&sii->pub);
crev = si_corerev(&sii->pub);
/* Display cores found */
SI_MSG(("CORE[%d]: id 0x%x rev %d base 0x%x regs 0x%p\n",
i, cid, crev, sii->common_info->coresba[i], sii->common_info->regs[i]));
if (BUSTYPE(bustype) == PCI_BUS) {
if (cid == PCI_CORE_ID) {
pciidx = i;
pcirev = crev;
pci = TRUE;
} else if (cid == PCIE_CORE_ID) {
pcieidx = i;
pcierev = crev;
pcie = TRUE;
}
} else if ((BUSTYPE(bustype) == PCMCIA_BUS) &&
(cid == PCMCIA_CORE_ID)) {
sii->pub.buscorerev = crev;
sii->pub.buscoretype = cid;
sii->pub.buscoreidx = i;
}
else if (((BUSTYPE(bustype) == SDIO_BUS) ||
(BUSTYPE(bustype) == SPI_BUS)) &&
((cid == PCMCIA_CORE_ID) ||
(cid == SDIOD_CORE_ID))) {
sii->pub.buscorerev = crev;
sii->pub.buscoretype = cid;
sii->pub.buscoreidx = i;
}
/* find the core idx before entering this func. */
if ((savewin && (savewin == sii->common_info->coresba[i])) ||
(regs == sii->common_info->regs[i]))
*origidx = i;
}
SI_MSG(("Buscore id/type/rev %d/0x%x/%d\n", sii->pub.buscoreidx, sii->pub.buscoretype,
sii->pub.buscorerev));
if (BUSTYPE(sii->pub.bustype) == SI_BUS && (CHIPID(sii->pub.chip) == BCM4712_CHIP_ID) &&
(sii->pub.chippkg != BCM4712LARGE_PKG_ID) && (sii->pub.chiprev <= 3))
OR_REG(sii->osh, &cc->slow_clk_ctl, SCC_SS_XTAL);
/* Make sure any on-chip ARM is off (in case strapping is wrong), or downloaded code was
* already running.
*/
if ((BUSTYPE(bustype) == SDIO_BUS) || (BUSTYPE(bustype) == SPI_BUS)) {
if (si_setcore(&sii->pub, ARM7S_CORE_ID, 0) ||
si_setcore(&sii->pub, ARMCM3_CORE_ID, 0))
si_core_disable(&sii->pub, 0);
}
/* return to the original core */
si_setcoreidx(&sii->pub, *origidx);
return TRUE;
}
static si_info_t *
si_doattach(si_info_t *sii, uint devid, osl_t *osh, void *regs,
uint bustype, void *sdh, char **vars, uint *varsz)
{
struct si_pub *sih = &sii->pub;
uint32 w, savewin;
chipcregs_t *cc;
char *pvars = NULL;
uint origidx;
ASSERT(GOODREGS(regs));
bzero((uchar*)sii, sizeof(si_info_t));
{
if (NULL == (common_info_alloced = (void *)MALLOC(osh, sizeof(si_common_info_t)))) {
SI_ERROR(("si_doattach: malloc failed! malloced %dbytes\n", MALLOCED(osh)));
return (NULL);
}
bzero((uchar*)(common_info_alloced), sizeof(si_common_info_t));
}
sii->common_info = (si_common_info_t *)common_info_alloced;
sii->common_info->attach_count++;
savewin = 0;
sih->buscoreidx = BADIDX;
sii->curmap = regs;
sii->sdh = sdh;
sii->osh = osh;
/* find Chipcommon address */
if (bustype == PCI_BUS) {
savewin = OSL_PCI_READ_CONFIG(sii->osh, PCI_BAR0_WIN, sizeof(uint32));
if (!GOODCOREADDR(savewin, SI_ENUM_BASE))
savewin = SI_ENUM_BASE;
OSL_PCI_WRITE_CONFIG(sii->osh, PCI_BAR0_WIN, 4, SI_ENUM_BASE);
cc = (chipcregs_t *)regs;
} else
if ((bustype == SDIO_BUS) || (bustype == SPI_BUS)) {
cc = (chipcregs_t *)sii->curmap;
} else {
cc = (chipcregs_t *)REG_MAP(SI_ENUM_BASE, SI_CORE_SIZE);
}
sih->bustype = bustype;
if (bustype != BUSTYPE(bustype)) {
SI_ERROR(("si_doattach: bus type %d does not match configured bus type %d\n",
bustype, BUSTYPE(bustype)));
return NULL;
}
/* bus/core/clk setup for register access */
if (!si_buscore_prep(sii, bustype, devid, sdh)) {
SI_ERROR(("si_doattach: si_core_clk_prep failed %d\n", bustype));
return NULL;
}
/* ChipID recognition.
* We assume we can read chipid at offset 0 from the regs arg.
* If we add other chiptypes (or if we need to support old sdio hosts w/o chipcommon),
* some way of recognizing them needs to be added here.
*/
w = R_REG(osh, &cc->chipid);
sih->socitype = (w & CID_TYPE_MASK) >> CID_TYPE_SHIFT;
/* Might as wll fill in chip id rev & pkg */
sih->chip = w & CID_ID_MASK;
sih->chiprev = (w & CID_REV_MASK) >> CID_REV_SHIFT;
sih->chippkg = (w & CID_PKG_MASK) >> CID_PKG_SHIFT;
if ((CHIPID(sih->chip) == BCM4329_CHIP_ID) && (sih->chippkg != BCM4329_289PIN_PKG_ID))
sih->chippkg = BCM4329_182PIN_PKG_ID;
sih->issim = IS_SIM(sih->chippkg);
/* scan for cores */
if (CHIPTYPE(sii->pub.socitype) == SOCI_SB) {
SI_MSG(("Found chip type SB (0x%08x)\n", w));
sb_scan(&sii->pub, regs, devid);
} else if (CHIPTYPE(sii->pub.socitype) == SOCI_AI) {
SI_MSG(("Found chip type AI (0x%08x)\n", w));
/* pass chipc address instead of original core base */
ai_scan(&sii->pub, (void *)cc, devid);
} else {
SI_ERROR(("Found chip of unkown type (0x%08x)\n", w));
return NULL;
}
/* no cores found, bail out */
if (sii->numcores == 0) {
SI_ERROR(("si_doattach: could not find any cores\n"));
return NULL;
}
/* bus/core/clk setup */
origidx = SI_CC_IDX;
if (!si_buscore_setup(sii, cc, bustype, savewin, &origidx, regs)) {
SI_ERROR(("si_doattach: si_buscore_setup failed\n"));
return NULL;
}
pvars = NULL;
if (sii->pub.ccrev >= 20) {
cc = (chipcregs_t *)si_setcore(sih, CC_CORE_ID, 0);
W_REG(osh, &cc->gpiopullup, 0);
W_REG(osh, &cc->gpiopulldown, 0);
si_setcoreidx(sih, origidx);
}
/* Skip PMU initialization from the Dongle Host.
* Firmware will take care of it when it comes up.
*/
return (sii);
}
/* may be called with core in reset */
void
si_detach(si_t *sih)
{
si_info_t *sii;
uint idx;
sii = SI_INFO(sih);
if (sii == NULL)
return;
if (BUSTYPE(sih->bustype) == SI_BUS)
for (idx = 0; idx < SI_MAXCORES; idx++)
if (sii->common_info->regs[idx]) {
REG_UNMAP(sii->common_info->regs[idx]);
sii->common_info->regs[idx] = NULL;
}
if (1 == sii->common_info->attach_count--) {
MFREE(sii->osh, sii->common_info, sizeof(si_common_info_t));
common_info_alloced = NULL;
}
#if !defined(BCMBUSTYPE) || (BCMBUSTYPE == SI_BUS)
if (sii != &ksii)
#endif /* !BCMBUSTYPE || (BCMBUSTYPE == SI_BUS) */
MFREE(sii->osh, sii, sizeof(si_info_t));
}
void *
si_osh(si_t *sih)
{
si_info_t *sii;
sii = SI_INFO(sih);
return sii->osh;
}
void
si_setosh(si_t *sih, osl_t *osh)
{
si_info_t *sii;
sii = SI_INFO(sih);
if (sii->osh != NULL) {
SI_ERROR(("osh is already set....\n"));
ASSERT(!sii->osh);
}
sii->osh = osh;
}
/* register driver interrupt disabling and restoring callback functions */
void
si_register_intr_callback(si_t *sih, void *intrsoff_fn, void *intrsrestore_fn,
void *intrsenabled_fn, void *intr_arg)
{
si_info_t *sii;
sii = SI_INFO(sih);
sii->intr_arg = intr_arg;
sii->intrsoff_fn = (si_intrsoff_t)intrsoff_fn;
sii->intrsrestore_fn = (si_intrsrestore_t)intrsrestore_fn;
sii->intrsenabled_fn = (si_intrsenabled_t)intrsenabled_fn;
/* save current core id. when this function called, the current core
* must be the core which provides driver functions(il, et, wl, etc.)
*/
sii->dev_coreid = sii->common_info->coreid[sii->curidx];
}
void
si_deregister_intr_callback(si_t *sih)
{
si_info_t *sii;
sii = SI_INFO(sih);
sii->intrsoff_fn = NULL;
}
uint
si_intflag(si_t *sih)
{
si_info_t *sii = SI_INFO(sih);
if (CHIPTYPE(sih->socitype) == SOCI_SB) {
sbconfig_t *ccsbr = (sbconfig_t *)((uintptr)((ulong)
(sii->common_info->coresba[SI_CC_IDX]) + SBCONFIGOFF));
return R_REG(sii->osh, &ccsbr->sbflagst);
} else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return R_REG(sii->osh, ((uint32 *)(uintptr)
(sii->common_info->oob_router + OOB_STATUSA)));
else {
ASSERT(0);
return 0;
}
}
uint
si_flag(si_t *sih)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_flag(sih);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_flag(sih);
else {
ASSERT(0);
return 0;
}
}
void
si_setint(si_t *sih, int siflag)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
sb_setint(sih, siflag);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
ai_setint(sih, siflag);
else
ASSERT(0);
}
uint
si_coreid(si_t *sih)
{
si_info_t *sii;
sii = SI_INFO(sih);
return sii->common_info->coreid[sii->curidx];
}
uint
si_coreidx(si_t *sih)
{
si_info_t *sii;
sii = SI_INFO(sih);
return sii->curidx;
}
/* return the core-type instantiation # of the current core */
uint
si_coreunit(si_t *sih)
{
si_info_t *sii;
uint idx;
uint coreid;
uint coreunit;
uint i;
sii = SI_INFO(sih);
coreunit = 0;
idx = sii->curidx;
ASSERT(GOODREGS(sii->curmap));
coreid = si_coreid(sih);
/* count the cores of our type */
for (i = 0; i < idx; i++)
if (sii->common_info->coreid[i] == coreid)
coreunit++;
return (coreunit);
}
uint
si_corevendor(si_t *sih)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_corevendor(sih);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_corevendor(sih);
else {
ASSERT(0);
return 0;
}
}
bool
si_backplane64(si_t *sih)
{
return ((sih->cccaps & CC_CAP_BKPLN64) != 0);
}
uint
si_corerev(si_t *sih)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_corerev(sih);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_corerev(sih);
else {
ASSERT(0);
return 0;
}
}
/* return index of coreid or BADIDX if not found */
uint
si_findcoreidx(si_t *sih, uint coreid, uint coreunit)
{
si_info_t *sii;
uint found;
uint i;
sii = SI_INFO(sih);
found = 0;
for (i = 0; i < sii->numcores; i++)
if (sii->common_info->coreid[i] == coreid) {
if (found == coreunit)
return (i);
found++;
}
return (BADIDX);
}
/* return list of found cores */
uint
si_corelist(si_t *sih, uint coreid[])
{
si_info_t *sii;
sii = SI_INFO(sih);
bcopy((uchar*)sii->common_info->coreid, (uchar*)coreid, (sii->numcores * sizeof(uint)));
return (sii->numcores);
}
/* return current register mapping */
void *
si_coreregs(si_t *sih)
{
si_info_t *sii;
sii = SI_INFO(sih);
ASSERT(GOODREGS(sii->curmap));
return (sii->curmap);
}
/*
* This function changes logical "focus" to the indicated core;
* must be called with interrupts off.
* Moreover, callers should keep interrupts off during switching out of and back to d11 core
*/
void *
si_setcore(si_t *sih, uint coreid, uint coreunit)
{
uint idx;
idx = si_findcoreidx(sih, coreid, coreunit);
if (!GOODIDX(idx))
return (NULL);
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_setcoreidx(sih, idx);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_setcoreidx(sih, idx);
else {
ASSERT(0);
return NULL;
}
}
void *
si_setcoreidx(si_t *sih, uint coreidx)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_setcoreidx(sih, coreidx);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_setcoreidx(sih, coreidx);
else {
ASSERT(0);
return NULL;
}
}
/* Turn off interrupt as required by sb_setcore, before switch core */
void *si_switch_core(si_t *sih, uint coreid, uint *origidx, uint *intr_val)
{
void *cc;
si_info_t *sii;
sii = SI_INFO(sih);
INTR_OFF(sii, *intr_val);
*origidx = sii->curidx;
cc = si_setcore(sih, coreid, 0);
ASSERT(cc != NULL);
return cc;
}
/* restore coreidx and restore interrupt */
void si_restore_core(si_t *sih, uint coreid, uint intr_val)
{
si_info_t *sii;
sii = SI_INFO(sih);
si_setcoreidx(sih, coreid);
INTR_RESTORE(sii, intr_val);
}
int
si_numaddrspaces(si_t *sih)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_numaddrspaces(sih);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_numaddrspaces(sih);
else {
ASSERT(0);
return 0;
}
}
uint32
si_addrspace(si_t *sih, uint asidx)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_addrspace(sih, asidx);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_addrspace(sih, asidx);
else {
ASSERT(0);
return 0;
}
}
uint32
si_addrspacesize(si_t *sih, uint asidx)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_addrspacesize(sih, asidx);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_addrspacesize(sih, asidx);
else {
ASSERT(0);
return 0;
}
}
uint32
si_core_cflags(si_t *sih, uint32 mask, uint32 val)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_core_cflags(sih, mask, val);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_core_cflags(sih, mask, val);
else {
ASSERT(0);
return 0;
}
}
void
si_core_cflags_wo(si_t *sih, uint32 mask, uint32 val)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
sb_core_cflags_wo(sih, mask, val);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
ai_core_cflags_wo(sih, mask, val);
else
ASSERT(0);
}
uint32
si_core_sflags(si_t *sih, uint32 mask, uint32 val)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_core_sflags(sih, mask, val);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_core_sflags(sih, mask, val);
else {
ASSERT(0);
return 0;
}
}
bool
si_iscoreup(si_t *sih)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_iscoreup(sih);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_iscoreup(sih);
else {
ASSERT(0);
return FALSE;
}
}
void
si_write_wrapperreg(si_t *sih, uint32 offset, uint32 val)
{
/* only for 4319, no requirement for SOCI_SB */
if (CHIPTYPE(sih->socitype) == SOCI_AI) {
ai_write_wrap_reg(sih, offset, val);
}
else
return;
return;
}
uint
si_corereg(si_t *sih, uint coreidx, uint regoff, uint mask, uint val)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_corereg(sih, coreidx, regoff, mask, val);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_corereg(sih, coreidx, regoff, mask, val);
else {
ASSERT(0);
return 0;
}
}
void
si_core_disable(si_t *sih, uint32 bits)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
sb_core_disable(sih, bits);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
ai_core_disable(sih, bits);
}
void
si_core_reset(si_t *sih, uint32 bits, uint32 resetbits)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
sb_core_reset(sih, bits, resetbits);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
ai_core_reset(sih, bits, resetbits);
}
void
si_core_tofixup(si_t *sih)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
sb_core_tofixup(sih);
}
/* Run bist on current core. Caller needs to take care of core-specific bist hazards */
int
si_corebist(si_t *sih)
{
uint32 cflags;
int result = 0;
/* Read core control flags */
cflags = si_core_cflags(sih, 0, 0);
/* Set bist & fgc */
si_core_cflags(sih, 0, (SICF_BIST_EN | SICF_FGC));
/* Wait for bist done */
SPINWAIT(((si_core_sflags(sih, 0, 0) & SISF_BIST_DONE) == 0), 100000);
if (si_core_sflags(sih, 0, 0) & SISF_BIST_ERROR)
result = BCME_ERROR;
/* Reset core control flags */
si_core_cflags(sih, 0xffff, cflags);
return result;
}
static uint32
factor6(uint32 x)
{
switch (x) {
case CC_F6_2: return 2;
case CC_F6_3: return 3;
case CC_F6_4: return 4;
case CC_F6_5: return 5;
case CC_F6_6: return 6;
case CC_F6_7: return 7;
default: return 0;
}
}
/* calculate the speed the SI would run at given a set of clockcontrol values */
uint32
si_clock_rate(uint32 pll_type, uint32 n, uint32 m)
{
uint32 n1, n2, clock, m1, m2, m3, mc;
n1 = n & CN_N1_MASK;
n2 = (n & CN_N2_MASK) >> CN_N2_SHIFT;
if (pll_type == PLL_TYPE6) {
if (m & CC_T6_MMASK)
return CC_T6_M1;
else
return CC_T6_M0;
} else if ((pll_type == PLL_TYPE1) ||
(pll_type == PLL_TYPE3) ||
(pll_type == PLL_TYPE4) ||
(pll_type == PLL_TYPE7)) {
n1 = factor6(n1);
n2 += CC_F5_BIAS;
} else if (pll_type == PLL_TYPE2) {
n1 += CC_T2_BIAS;
n2 += CC_T2_BIAS;
ASSERT((n1 >= 2) && (n1 <= 7));
ASSERT((n2 >= 5) && (n2 <= 23));
} else if (pll_type == PLL_TYPE5) {
return (100000000);
} else
ASSERT(0);
/* PLL types 3 and 7 use BASE2 (25Mhz) */
if ((pll_type == PLL_TYPE3) ||
(pll_type == PLL_TYPE7)) {
clock = CC_CLOCK_BASE2 * n1 * n2;
} else
clock = CC_CLOCK_BASE1 * n1 * n2;
if (clock == 0)
return 0;
m1 = m & CC_M1_MASK;
m2 = (m & CC_M2_MASK) >> CC_M2_SHIFT;
m3 = (m & CC_M3_MASK) >> CC_M3_SHIFT;
mc = (m & CC_MC_MASK) >> CC_MC_SHIFT;
if ((pll_type == PLL_TYPE1) ||
(pll_type == PLL_TYPE3) ||
(pll_type == PLL_TYPE4) ||
(pll_type == PLL_TYPE7)) {
m1 = factor6(m1);
if ((pll_type == PLL_TYPE1) || (pll_type == PLL_TYPE3))
m2 += CC_F5_BIAS;
else
m2 = factor6(m2);
m3 = factor6(m3);
switch (mc) {
case CC_MC_BYPASS: return (clock);
case CC_MC_M1: return (clock / m1);
case CC_MC_M1M2: return (clock / (m1 * m2));
case CC_MC_M1M2M3: return (clock / (m1 * m2 * m3));
case CC_MC_M1M3: return (clock / (m1 * m3));
default: return (0);
}
} else {
ASSERT(pll_type == PLL_TYPE2);
m1 += CC_T2_BIAS;
m2 += CC_T2M2_BIAS;
m3 += CC_T2_BIAS;
ASSERT((m1 >= 2) && (m1 <= 7));
ASSERT((m2 >= 3) && (m2 <= 10));
ASSERT((m3 >= 2) && (m3 <= 7));
if ((mc & CC_T2MC_M1BYP) == 0)
clock /= m1;
if ((mc & CC_T2MC_M2BYP) == 0)
clock /= m2;
if ((mc & CC_T2MC_M3BYP) == 0)
clock /= m3;
return (clock);
}
}
/* set chip watchdog reset timer to fire in 'ticks' */
void
si_watchdog(si_t *sih, uint ticks)
{
if (PMUCTL_ENAB(sih)) {
if ((sih->chip == BCM4319_CHIP_ID) && (sih->chiprev == 0) && (ticks != 0)) {
si_corereg(sih, SI_CC_IDX, OFFSETOF(chipcregs_t, clk_ctl_st), ~0, 0x2);
si_setcore(sih, USB20D_CORE_ID, 0);
si_core_disable(sih, 1);
si_setcore(sih, CC_CORE_ID, 0);
}
if (ticks == 1)
ticks = 2;
si_corereg(sih, SI_CC_IDX, OFFSETOF(chipcregs_t, pmuwatchdog), ~0, ticks);
} else {
/* instant NMI */
si_corereg(sih, SI_CC_IDX, OFFSETOF(chipcregs_t, watchdog), ~0, ticks);
}
}
#if !defined(BCMBUSTYPE) || (BCMBUSTYPE == SI_BUS)
/* trigger watchdog reset after ms milliseconds */
void
si_watchdog_ms(si_t *sih, uint32 ms)
{
si_info_t *sii;
sii = SI_INFO(sih);
si_watchdog(sih, wd_msticks * ms);
}
#endif
/* initialize the sdio core */
void
si_sdio_init(si_t *sih)
{
si_info_t *sii = SI_INFO(sih);
if (((sih->buscoretype == PCMCIA_CORE_ID) && (sih->buscorerev >= 8)) ||
(sih->buscoretype == SDIOD_CORE_ID)) {
uint idx;
sdpcmd_regs_t *sdpregs;
/* get the current core index */
idx = sii->curidx;
ASSERT(idx == si_findcoreidx(sih, D11_CORE_ID, 0));
/* switch to sdio core */
if (!(sdpregs = (sdpcmd_regs_t *)si_setcore(sih, PCMCIA_CORE_ID, 0)))
sdpregs = (sdpcmd_regs_t *)si_setcore(sih, SDIOD_CORE_ID, 0);
ASSERT(sdpregs);
SI_MSG(("si_sdio_init: For PCMCIA/SDIO Corerev %d, enable ints from core %d "
"through SD core %d (%p)\n",
sih->buscorerev, idx, sii->curidx, sdpregs));
/* enable backplane error and core interrupts */
W_REG(sii->osh, &sdpregs->hostintmask, I_SBINT);
W_REG(sii->osh, &sdpregs->sbintmask, (I_SB_SERR | I_SB_RESPERR | (1 << idx)));
/* switch back to previous core */
si_setcoreidx(sih, idx);
}
/* enable interrupts */
bcmsdh_intr_enable(sii->sdh);
}
/* change logical "focus" to the gpio core for optimized access */
void *
si_gpiosetcore(si_t *sih)
{
return (si_setcoreidx(sih, SI_CC_IDX));
}
/* mask&set gpiocontrol bits */
uint32
si_gpiocontrol(si_t *sih, uint32 mask, uint32 val, uint8 priority)
{
uint regoff;
regoff = 0;
/* gpios could be shared on router platforms
* ignore reservation if it's high priority (e.g., test apps)
*/
if ((priority != GPIO_HI_PRIORITY) &&
(BUSTYPE(sih->bustype) == SI_BUS) && (val || mask)) {
mask = priority ? (si_gpioreservation & mask) :
((si_gpioreservation | mask) & ~(si_gpioreservation));
val &= mask;
}
regoff = OFFSETOF(chipcregs_t, gpiocontrol);
return (si_corereg(sih, SI_CC_IDX, regoff, mask, val));
}
/* mask&set gpio output enable bits */
uint32
si_gpioouten(si_t *sih, uint32 mask, uint32 val, uint8 priority)
{
uint regoff;
regoff = 0;
/* gpios could be shared on router platforms
* ignore reservation if it's high priority (e.g., test apps)
*/
if ((priority != GPIO_HI_PRIORITY) &&
(BUSTYPE(sih->bustype) == SI_BUS) && (val || mask)) {
mask = priority ? (si_gpioreservation & mask) :
((si_gpioreservation | mask) & ~(si_gpioreservation));
val &= mask;
}
regoff = OFFSETOF(chipcregs_t, gpioouten);
return (si_corereg(sih, SI_CC_IDX, regoff, mask, val));
}
/* mask&set gpio output bits */
uint32
si_gpioout(si_t *sih, uint32 mask, uint32 val, uint8 priority)
{
uint regoff;
regoff = 0;
/* gpios could be shared on router platforms
* ignore reservation if it's high priority (e.g., test apps)
*/
if ((priority != GPIO_HI_PRIORITY) &&
(BUSTYPE(sih->bustype) == SI_BUS) && (val || mask)) {
mask = priority ? (si_gpioreservation & mask) :
((si_gpioreservation | mask) & ~(si_gpioreservation));
val &= mask;
}
regoff = OFFSETOF(chipcregs_t, gpioout);
return (si_corereg(sih, SI_CC_IDX, regoff, mask, val));
}
/* reserve one gpio */
uint32
si_gpioreserve(si_t *sih, uint32 gpio_bitmask, uint8 priority)
{
si_info_t *sii;
sii = SI_INFO(sih);
/* only cores on SI_BUS share GPIO's and only applcation users need to
* reserve/release GPIO
*/
if ((BUSTYPE(sih->bustype) != SI_BUS) || (!priority)) {
ASSERT((BUSTYPE(sih->bustype) == SI_BUS) && (priority));
return -1;
}
/* make sure only one bit is set */
if ((!gpio_bitmask) || ((gpio_bitmask) & (gpio_bitmask - 1))) {
ASSERT((gpio_bitmask) && !((gpio_bitmask) & (gpio_bitmask - 1)));
return -1;
}
/* already reserved */
if (si_gpioreservation & gpio_bitmask)
return -1;
/* set reservation */
si_gpioreservation |= gpio_bitmask;
return si_gpioreservation;
}
/* release one gpio */
/*
* releasing the gpio doesn't change the current value on the GPIO last write value
* persists till some one overwrites it
*/
uint32
si_gpiorelease(si_t *sih, uint32 gpio_bitmask, uint8 priority)
{
si_info_t *sii;
sii = SI_INFO(sih);
/* only cores on SI_BUS share GPIO's and only applcation users need to
* reserve/release GPIO
*/
if ((BUSTYPE(sih->bustype) != SI_BUS) || (!priority)) {
ASSERT((BUSTYPE(sih->bustype) == SI_BUS) && (priority));
return -1;
}
/* make sure only one bit is set */
if ((!gpio_bitmask) || ((gpio_bitmask) & (gpio_bitmask - 1))) {
ASSERT((gpio_bitmask) && !((gpio_bitmask) & (gpio_bitmask - 1)));
return -1;
}
/* already released */
if (!(si_gpioreservation & gpio_bitmask))
return -1;
/* clear reservation */
si_gpioreservation &= ~gpio_bitmask;
return si_gpioreservation;
}
/* return the current gpioin register value */
uint32
si_gpioin(si_t *sih)
{
si_info_t *sii;
uint regoff;
sii = SI_INFO(sih);
regoff = 0;
regoff = OFFSETOF(chipcregs_t, gpioin);
return (si_corereg(sih, SI_CC_IDX, regoff, 0, 0));
}
/* mask&set gpio interrupt polarity bits */
uint32
si_gpiointpolarity(si_t *sih, uint32 mask, uint32 val, uint8 priority)
{
si_info_t *sii;
uint regoff;
sii = SI_INFO(sih);
regoff = 0;
/* gpios could be shared on router platforms */
if ((BUSTYPE(sih->bustype) == SI_BUS) && (val || mask)) {
mask = priority ? (si_gpioreservation & mask) :
((si_gpioreservation | mask) & ~(si_gpioreservation));
val &= mask;
}
regoff = OFFSETOF(chipcregs_t, gpiointpolarity);
return (si_corereg(sih, SI_CC_IDX, regoff, mask, val));
}
/* mask&set gpio interrupt mask bits */
uint32
si_gpiointmask(si_t *sih, uint32 mask, uint32 val, uint8 priority)
{
si_info_t *sii;
uint regoff;
sii = SI_INFO(sih);
regoff = 0;
/* gpios could be shared on router platforms */
if ((BUSTYPE(sih->bustype) == SI_BUS) && (val || mask)) {
mask = priority ? (si_gpioreservation & mask) :
((si_gpioreservation | mask) & ~(si_gpioreservation));
val &= mask;
}
regoff = OFFSETOF(chipcregs_t, gpiointmask);
return (si_corereg(sih, SI_CC_IDX, regoff, mask, val));
}
/* assign the gpio to an led */
uint32
si_gpioled(si_t *sih, uint32 mask, uint32 val)
{
si_info_t *sii;
sii = SI_INFO(sih);
if (sih->ccrev < 16)
return -1;
/* gpio led powersave reg */
return (si_corereg(sih, SI_CC_IDX, OFFSETOF(chipcregs_t, gpiotimeroutmask), mask, val));
}
/* mask&set gpio timer val */
uint32
si_gpiotimerval(si_t *sih, uint32 mask, uint32 gpiotimerval)
{
si_info_t *sii;
sii = SI_INFO(sih);
if (sih->ccrev < 16)
return -1;
return (si_corereg(sih, SI_CC_IDX,
OFFSETOF(chipcregs_t, gpiotimerval), mask, gpiotimerval));
}
uint32
si_gpiopull(si_t *sih, bool updown, uint32 mask, uint32 val)
{
si_info_t *sii;
uint offs;
sii = SI_INFO(sih);
if (sih->ccrev < 20)
return -1;
offs = (updown ? OFFSETOF(chipcregs_t, gpiopulldown) : OFFSETOF(chipcregs_t, gpiopullup));
return (si_corereg(sih, SI_CC_IDX, offs, mask, val));
}
uint32
si_gpioevent(si_t *sih, uint regtype, uint32 mask, uint32 val)
{
si_info_t *sii;
uint offs;
sii = SI_INFO(sih);
if (sih->ccrev < 11)
return -1;
if (regtype == GPIO_REGEVT)
offs = OFFSETOF(chipcregs_t, gpioevent);
else if (regtype == GPIO_REGEVT_INTMSK)
offs = OFFSETOF(chipcregs_t, gpioeventintmask);
else if (regtype == GPIO_REGEVT_INTPOL)
offs = OFFSETOF(chipcregs_t, gpioeventintpolarity);
else
return -1;
return (si_corereg(sih, SI_CC_IDX, offs, mask, val));
}
void *
si_gpio_handler_register(si_t *sih, uint32 event,
bool level, gpio_handler_t cb, void *arg)
{
si_info_t *sii;
gpioh_item_t *gi;
ASSERT(event);
ASSERT(cb != NULL);
sii = SI_INFO(sih);
if (sih->ccrev < 11)
return NULL;
if ((gi = MALLOC(sii->osh, sizeof(gpioh_item_t))) == NULL)
return NULL;
bzero(gi, sizeof(gpioh_item_t));
gi->event = event;
gi->handler = cb;
gi->arg = arg;
gi->level = level;
gi->next = sii->gpioh_head;
sii->gpioh_head = gi;
return (void *)(gi);
}
void
si_gpio_handler_unregister(si_t *sih, void *gpioh)
{
si_info_t *sii;
gpioh_item_t *p, *n;
sii = SI_INFO(sih);
if (sih->ccrev < 11)
return;
ASSERT(sii->gpioh_head != NULL);
if ((void*)sii->gpioh_head == gpioh) {
sii->gpioh_head = sii->gpioh_head->next;
MFREE(sii->osh, gpioh, sizeof(gpioh_item_t));
return;
} else {
p = sii->gpioh_head;
n = p->next;
while (n) {
if ((void*)n == gpioh) {
p->next = n->next;
MFREE(sii->osh, gpioh, sizeof(gpioh_item_t));
return;
}
p = n;
n = n->next;
}
}
ASSERT(0); /* Not found in list */
}
void
si_gpio_handler_process(si_t *sih)
{
si_info_t *sii;
gpioh_item_t *h;
uint32 status;
uint32 level = si_gpioin(sih);
uint32 edge = si_gpioevent(sih, GPIO_REGEVT, 0, 0);
sii = SI_INFO(sih);
for (h = sii->gpioh_head; h != NULL; h = h->next) {
if (h->handler) {
status = (h->level ? level : edge);
if (status & h->event)
h->handler(status, h->arg);
}
}
si_gpioevent(sih, GPIO_REGEVT, edge, edge); /* clear edge-trigger status */
}
uint32
si_gpio_int_enable(si_t *sih, bool enable)
{
si_info_t *sii;
uint offs;
sii = SI_INFO(sih);
if (sih->ccrev < 11)
return -1;
offs = OFFSETOF(chipcregs_t, intmask);
return (si_corereg(sih, SI_CC_IDX, offs, CI_GPIO, (enable ? CI_GPIO : 0)));
}
/* Return the RAM size of the SOCRAM core */
uint32
si_socram_size(si_t *sih)
{
si_info_t *sii;
uint origidx;
uint intr_val = 0;
sbsocramregs_t *regs;
bool wasup;
uint corerev;
uint32 coreinfo;
uint memsize = 0;
sii = SI_INFO(sih);
/* Block ints and save current core */
INTR_OFF(sii, intr_val);
origidx = si_coreidx(sih);
/* Switch to SOCRAM core */
if (!(regs = si_setcore(sih, SOCRAM_CORE_ID, 0)))
goto done;
/* Get info for determining size */
if (!(wasup = si_iscoreup(sih)))
si_core_reset(sih, 0, 0);
corerev = si_corerev(sih);
coreinfo = R_REG(sii->osh, ®s->coreinfo);
/* Calculate size from coreinfo based on rev */
if (corerev == 0)
memsize = 1 << (16 + (coreinfo & SRCI_MS0_MASK));
else if (corerev < 3) {
memsize = 1 << (SR_BSZ_BASE + (coreinfo & SRCI_SRBSZ_MASK));
memsize *= (coreinfo & SRCI_SRNB_MASK) >> SRCI_SRNB_SHIFT;
} else {
uint nb = (coreinfo & SRCI_SRNB_MASK) >> SRCI_SRNB_SHIFT;
uint bsz = (coreinfo & SRCI_SRBSZ_MASK);
uint lss = (coreinfo & SRCI_LSS_MASK) >> SRCI_LSS_SHIFT;
if (lss != 0)
nb --;
memsize = nb * (1 << (bsz + SR_BSZ_BASE));
if (lss != 0)
memsize += (1 << ((lss - 1) + SR_BSZ_BASE));
}
/* Return to previous state and core */
if (!wasup)
si_core_disable(sih, 0);
si_setcoreidx(sih, origidx);
done:
INTR_RESTORE(sii, intr_val);
return memsize;
}
void
si_btcgpiowar(si_t *sih)
{
si_info_t *sii;
uint origidx;
uint intr_val = 0;
chipcregs_t *cc;
sii = SI_INFO(sih);
/* Make sure that there is ChipCommon core present &&
* UART_TX is strapped to 1
*/
if (!(sih->cccaps & CC_CAP_UARTGPIO))
return;
/* si_corereg cannot be used as we have to guarantee 8-bit read/writes */
INTR_OFF(sii, intr_val);
origidx = si_coreidx(sih);
cc = (chipcregs_t *)si_setcore(sih, CC_CORE_ID, 0);
ASSERT(cc != NULL);
W_REG(sii->osh, &cc->uart0mcr, R_REG(sii->osh, &cc->uart0mcr) | 0x04);
/* restore the original index */
si_setcoreidx(sih, origidx);
INTR_RESTORE(sii, intr_val);
}
/* check if the device is removed */
bool
si_deviceremoved(si_t *sih)
{
uint32 w;
si_info_t *sii;
sii = SI_INFO(sih);
switch (BUSTYPE(sih->bustype)) {
case PCI_BUS:
ASSERT(sii->osh != NULL);
w = OSL_PCI_READ_CONFIG(sii->osh, PCI_CFG_VID, sizeof(uint32));
if ((w & 0xFFFF) != VENDOR_BROADCOM)
return TRUE;
else
return FALSE;
default:
return FALSE;
}
return FALSE;
}
| gpl-2.0 |
brymaster5000/m7wlv_4.3 | drivers/media/dvb/dvb-usb/gp8psk-fe.c | 8803 | 9519 | /* DVB USB compliant Linux driver for the
* - GENPIX 8pks/qpsk/DCII USB2.0 DVB-S module
*
* Copyright (C) 2006,2007 Alan Nisota (alannisota@gmail.com)
* Copyright (C) 2006,2007 Genpix Electronics (genpix@genpix-electronics.com)
*
* Thanks to GENPIX for the sample code used to implement this module.
*
* This module is based off the vp7045 and vp702x modules
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, version 2.
*
* see Documentation/dvb/README.dvb-usb for more information
*/
#include "gp8psk.h"
struct gp8psk_fe_state {
struct dvb_frontend fe;
struct dvb_usb_device *d;
u8 lock;
u16 snr;
unsigned long next_status_check;
unsigned long status_check_interval;
};
static int gp8psk_tuned_to_DCII(struct dvb_frontend *fe)
{
struct gp8psk_fe_state *st = fe->demodulator_priv;
u8 status;
gp8psk_usb_in_op(st->d, GET_8PSK_CONFIG, 0, 0, &status, 1);
return status & bmDCtuned;
}
static int gp8psk_set_tuner_mode(struct dvb_frontend *fe, int mode)
{
struct gp8psk_fe_state *state = fe->demodulator_priv;
return gp8psk_usb_out_op(state->d, SET_8PSK_CONFIG, mode, 0, NULL, 0);
}
static int gp8psk_fe_update_status(struct gp8psk_fe_state *st)
{
u8 buf[6];
if (time_after(jiffies,st->next_status_check)) {
gp8psk_usb_in_op(st->d, GET_SIGNAL_LOCK, 0,0,&st->lock,1);
gp8psk_usb_in_op(st->d, GET_SIGNAL_STRENGTH, 0,0,buf,6);
st->snr = (buf[1]) << 8 | buf[0];
st->next_status_check = jiffies + (st->status_check_interval*HZ)/1000;
}
return 0;
}
static int gp8psk_fe_read_status(struct dvb_frontend* fe, fe_status_t *status)
{
struct gp8psk_fe_state *st = fe->demodulator_priv;
gp8psk_fe_update_status(st);
if (st->lock)
*status = FE_HAS_LOCK | FE_HAS_SYNC | FE_HAS_VITERBI | FE_HAS_SIGNAL | FE_HAS_CARRIER;
else
*status = 0;
if (*status & FE_HAS_LOCK)
st->status_check_interval = 1000;
else
st->status_check_interval = 100;
return 0;
}
/* not supported by this Frontend */
static int gp8psk_fe_read_ber(struct dvb_frontend* fe, u32 *ber)
{
(void) fe;
*ber = 0;
return 0;
}
/* not supported by this Frontend */
static int gp8psk_fe_read_unc_blocks(struct dvb_frontend* fe, u32 *unc)
{
(void) fe;
*unc = 0;
return 0;
}
static int gp8psk_fe_read_snr(struct dvb_frontend* fe, u16 *snr)
{
struct gp8psk_fe_state *st = fe->demodulator_priv;
gp8psk_fe_update_status(st);
/* snr is reported in dBu*256 */
*snr = st->snr;
return 0;
}
static int gp8psk_fe_read_signal_strength(struct dvb_frontend* fe, u16 *strength)
{
struct gp8psk_fe_state *st = fe->demodulator_priv;
gp8psk_fe_update_status(st);
/* snr is reported in dBu*256 */
/* snr / 38.4 ~= 100% strength */
/* snr * 17 returns 100% strength as 65535 */
if (st->snr > 0xf00)
*strength = 0xffff;
else
*strength = (st->snr << 4) + st->snr; /* snr*17 */
return 0;
}
static int gp8psk_fe_get_tune_settings(struct dvb_frontend* fe, struct dvb_frontend_tune_settings *tune)
{
tune->min_delay_ms = 800;
return 0;
}
static int gp8psk_fe_set_frontend(struct dvb_frontend *fe)
{
struct gp8psk_fe_state *state = fe->demodulator_priv;
struct dtv_frontend_properties *c = &fe->dtv_property_cache;
u8 cmd[10];
u32 freq = c->frequency * 1000;
int gp_product_id = le16_to_cpu(state->d->udev->descriptor.idProduct);
deb_fe("%s()\n", __func__);
cmd[4] = freq & 0xff;
cmd[5] = (freq >> 8) & 0xff;
cmd[6] = (freq >> 16) & 0xff;
cmd[7] = (freq >> 24) & 0xff;
/* backwards compatibility: DVB-S + 8-PSK were used for Turbo-FEC */
if (c->delivery_system == SYS_DVBS && c->modulation == PSK_8)
c->delivery_system = SYS_TURBO;
switch (c->delivery_system) {
case SYS_DVBS:
if (c->modulation != QPSK) {
deb_fe("%s: unsupported modulation selected (%d)\n",
__func__, c->modulation);
return -EOPNOTSUPP;
}
c->fec_inner = FEC_AUTO;
break;
case SYS_DVBS2: /* kept for backwards compatibility */
deb_fe("%s: DVB-S2 delivery system selected\n", __func__);
break;
case SYS_TURBO:
deb_fe("%s: Turbo-FEC delivery system selected\n", __func__);
break;
default:
deb_fe("%s: unsupported delivery system selected (%d)\n",
__func__, c->delivery_system);
return -EOPNOTSUPP;
}
cmd[0] = c->symbol_rate & 0xff;
cmd[1] = (c->symbol_rate >> 8) & 0xff;
cmd[2] = (c->symbol_rate >> 16) & 0xff;
cmd[3] = (c->symbol_rate >> 24) & 0xff;
switch (c->modulation) {
case QPSK:
if (gp_product_id == USB_PID_GENPIX_8PSK_REV_1_WARM)
if (gp8psk_tuned_to_DCII(fe))
gp8psk_bcm4500_reload(state->d);
switch (c->fec_inner) {
case FEC_1_2:
cmd[9] = 0; break;
case FEC_2_3:
cmd[9] = 1; break;
case FEC_3_4:
cmd[9] = 2; break;
case FEC_5_6:
cmd[9] = 3; break;
case FEC_7_8:
cmd[9] = 4; break;
case FEC_AUTO:
cmd[9] = 5; break;
default:
cmd[9] = 5; break;
}
if (c->delivery_system == SYS_TURBO)
cmd[8] = ADV_MOD_TURBO_QPSK;
else
cmd[8] = ADV_MOD_DVB_QPSK;
break;
case PSK_8: /* PSK_8 is for compatibility with DN */
cmd[8] = ADV_MOD_TURBO_8PSK;
switch (c->fec_inner) {
case FEC_2_3:
cmd[9] = 0; break;
case FEC_3_4:
cmd[9] = 1; break;
case FEC_3_5:
cmd[9] = 2; break;
case FEC_5_6:
cmd[9] = 3; break;
case FEC_8_9:
cmd[9] = 4; break;
default:
cmd[9] = 0; break;
}
break;
case QAM_16: /* QAM_16 is for compatibility with DN */
cmd[8] = ADV_MOD_TURBO_16QAM;
cmd[9] = 0;
break;
default: /* Unknown modulation */
deb_fe("%s: unsupported modulation selected (%d)\n",
__func__, c->modulation);
return -EOPNOTSUPP;
}
if (gp_product_id == USB_PID_GENPIX_8PSK_REV_1_WARM)
gp8psk_set_tuner_mode(fe, 0);
gp8psk_usb_out_op(state->d, TUNE_8PSK, 0, 0, cmd, 10);
state->lock = 0;
state->next_status_check = jiffies;
state->status_check_interval = 200;
return 0;
}
static int gp8psk_fe_send_diseqc_msg (struct dvb_frontend* fe,
struct dvb_diseqc_master_cmd *m)
{
struct gp8psk_fe_state *st = fe->demodulator_priv;
deb_fe("%s\n",__func__);
if (gp8psk_usb_out_op(st->d,SEND_DISEQC_COMMAND, m->msg[0], 0,
m->msg, m->msg_len)) {
return -EINVAL;
}
return 0;
}
static int gp8psk_fe_send_diseqc_burst (struct dvb_frontend* fe,
fe_sec_mini_cmd_t burst)
{
struct gp8psk_fe_state *st = fe->demodulator_priv;
u8 cmd;
deb_fe("%s\n",__func__);
/* These commands are certainly wrong */
cmd = (burst == SEC_MINI_A) ? 0x00 : 0x01;
if (gp8psk_usb_out_op(st->d,SEND_DISEQC_COMMAND, cmd, 0,
&cmd, 0)) {
return -EINVAL;
}
return 0;
}
static int gp8psk_fe_set_tone (struct dvb_frontend* fe, fe_sec_tone_mode_t tone)
{
struct gp8psk_fe_state* state = fe->demodulator_priv;
if (gp8psk_usb_out_op(state->d,SET_22KHZ_TONE,
(tone == SEC_TONE_ON), 0, NULL, 0)) {
return -EINVAL;
}
return 0;
}
static int gp8psk_fe_set_voltage (struct dvb_frontend* fe, fe_sec_voltage_t voltage)
{
struct gp8psk_fe_state* state = fe->demodulator_priv;
if (gp8psk_usb_out_op(state->d,SET_LNB_VOLTAGE,
voltage == SEC_VOLTAGE_18, 0, NULL, 0)) {
return -EINVAL;
}
return 0;
}
static int gp8psk_fe_enable_high_lnb_voltage(struct dvb_frontend* fe, long onoff)
{
struct gp8psk_fe_state* state = fe->demodulator_priv;
return gp8psk_usb_out_op(state->d, USE_EXTRA_VOLT, onoff, 0,NULL,0);
}
static int gp8psk_fe_send_legacy_dish_cmd (struct dvb_frontend* fe, unsigned long sw_cmd)
{
struct gp8psk_fe_state* state = fe->demodulator_priv;
u8 cmd = sw_cmd & 0x7f;
if (gp8psk_usb_out_op(state->d,SET_DN_SWITCH, cmd, 0,
NULL, 0)) {
return -EINVAL;
}
if (gp8psk_usb_out_op(state->d,SET_LNB_VOLTAGE, !!(sw_cmd & 0x80),
0, NULL, 0)) {
return -EINVAL;
}
return 0;
}
static void gp8psk_fe_release(struct dvb_frontend* fe)
{
struct gp8psk_fe_state *state = fe->demodulator_priv;
kfree(state);
}
static struct dvb_frontend_ops gp8psk_fe_ops;
struct dvb_frontend * gp8psk_fe_attach(struct dvb_usb_device *d)
{
struct gp8psk_fe_state *s = kzalloc(sizeof(struct gp8psk_fe_state), GFP_KERNEL);
if (s == NULL)
goto error;
s->d = d;
memcpy(&s->fe.ops, &gp8psk_fe_ops, sizeof(struct dvb_frontend_ops));
s->fe.demodulator_priv = s;
goto success;
error:
return NULL;
success:
return &s->fe;
}
static struct dvb_frontend_ops gp8psk_fe_ops = {
.delsys = { SYS_DVBS },
.info = {
.name = "Genpix DVB-S",
.frequency_min = 800000,
.frequency_max = 2250000,
.frequency_stepsize = 100,
.symbol_rate_min = 1000000,
.symbol_rate_max = 45000000,
.symbol_rate_tolerance = 500, /* ppm */
.caps = FE_CAN_INVERSION_AUTO |
FE_CAN_FEC_1_2 | FE_CAN_FEC_2_3 | FE_CAN_FEC_3_4 |
FE_CAN_FEC_5_6 | FE_CAN_FEC_7_8 | FE_CAN_FEC_AUTO |
/*
* FE_CAN_QAM_16 is for compatibility
* (Myth incorrectly detects Turbo-QPSK as plain QAM-16)
*/
FE_CAN_QPSK | FE_CAN_QAM_16 | FE_CAN_TURBO_FEC
},
.release = gp8psk_fe_release,
.init = NULL,
.sleep = NULL,
.set_frontend = gp8psk_fe_set_frontend,
.get_tune_settings = gp8psk_fe_get_tune_settings,
.read_status = gp8psk_fe_read_status,
.read_ber = gp8psk_fe_read_ber,
.read_signal_strength = gp8psk_fe_read_signal_strength,
.read_snr = gp8psk_fe_read_snr,
.read_ucblocks = gp8psk_fe_read_unc_blocks,
.diseqc_send_master_cmd = gp8psk_fe_send_diseqc_msg,
.diseqc_send_burst = gp8psk_fe_send_diseqc_burst,
.set_tone = gp8psk_fe_set_tone,
.set_voltage = gp8psk_fe_set_voltage,
.dishnetwork_send_legacy_command = gp8psk_fe_send_legacy_dish_cmd,
.enable_high_lnb_voltage = gp8psk_fe_enable_high_lnb_voltage
};
| gpl-2.0 |
beboom/a10s-linux | modules/wifi/nano-c047.12/driverenv/src/application.c | 100 | 5320 | /*****************************************************************************
Copyright (c) 2004 by Nanoradio AB
This software is copyrighted by and is the sole property of Nanoradio AB.
All rights, title, ownership, or other interests in the
software remain the property of Nanoradio AB. This software may
only be used in accordance with the corresponding license agreement. Any
unauthorized use, duplication, transmission, distribution, or disclosure of
this software is expressly forbidden.
This Copyright notice may not be removed or modified without prior written
consent of Nanoradio AB.
Nanoradio AB reserves the right to modify this software without
notice.
Nanoradio AB
Torshamnsgatan 39 info@nanoradio.se
164 40 Kista http://www.nanoradio.se
SWEDEN
Module Description :
==================
This module is part of the t_btit unit. It performs bla, bla and bla.
*****************************************************************************/
#include "sysdef.h" /* Must be first include */
#include "ucos.h"
#include "application.h"
#include "hmg.h"
#include "hmg_traffic.h"
#include "hmg_ps.h"
#if (DE_NETWORK_SUPPORT & CFG_NETWORK_AMP)
#include "hmg_pal.h"
#endif
/*****************************************************************************
T E M P O R A R Y T E S T V A R I A B L E S
*****************************************************************************/
/*****************************************************************************
C O N S T A N T S / M A C R O S
*****************************************************************************/
#define OBJID_MYSELF SYSDEF_OBJID_APP
#define INTSIG_START 0xF0
/*****************************************************************************
L O C A L D A T A T Y P E S
*****************************************************************************/
/*****************************************************************************
L O C A L F U N C T I O N P R O T O T Y P E S
*****************************************************************************/
static void APP_entry(ucos_msg_id_t signal, ucos_msg_param_t inData);
static void APP_init(void);
static void APP_startUp(void);
/*****************************************************************************
M O D U L E V A R I A B L E S
*****************************************************************************/
/*********************/
/* Error class table */
/*********************/
/*****************************************************************************
G L O B A L C O N S T A N T S / V A R I A B L E S
*****************************************************************************/
/*
There is one external dependency for UCOS to resolve in runtime,
and that is the number of objects (that is tasks) defined in the
custom application.
*/
uint16_t NR_UCOS_OBJECTS = SYSDEF_MAX_NO_OBJECTS;
/*****************************************************************************
G L O B A L F U N C T I O N S
*****************************************************************************/
/*-----------------------------------------------------------------------------
A little more thorough description than was provided for global
functions, as this is the only place to put descriptions for local functions.
Returns: Describe return value here.
-----------------------------------------------------------------------------*/
int app_init()
{
ucos_init();
ucos_startup();
/* Register all objects */
ucos_register_object(SYSDEF_OBJID_APP,
SYSCFG_UCOS_OBJECT_PRIO_LOW,
(ucos_object_entry_t)APP_entry,
"APP");
/*******************************************************/
/* Initialize all objects. NOTE: the order is of great */
/* importance and must not be changed */
/*******************************************************/
APP_init();
HMG_init_ps();
HMG_init_traffic();
#if (defined(DE_NETWORK_SUPPORT) && (DE_NETWORK_SUPPORT & CFG_NETWORK_AMP ))
HMG_init_pal();
#endif
/*******************************************************/
/* Now startup all objects.NOTE: the order is of great */
/* importance and must not be changed */
/*******************************************************/
APP_startUp();
HMG_startUp_ps();
HMG_startUp_traffic();
#if (defined(DE_NETWORK_SUPPORT) && (DE_NETWORK_SUPPORT & CFG_NETWORK_AMP ))
HMG_startUp_pal();
#endif
return 0;
}
/*****************************************************************************
L O C A L F U N C T I O N S
*****************************************************************************/
static void APP_init(void)
{
}
static void APP_startUp(void)
{
ucos_send_msg(INTSIG_START, OBJID_MYSELF, DUMMY);
}
static void APP_entry(ucos_msg_id_t msg, ucos_msg_param_t param)
{
switch(msg)
{
case INTSIG_START:
{
}
break;
case SIG_UCOS_TIMEOUT:
break;
default:
break;
}
// S_BUF_free_all((S_BUF_BufType)inData);
}
/******************************* END OF FILE ********************************/
| gpl-2.0 |
arunthomas/linux | drivers/net/wireless/iwlegacy/4965-mac.c | 356 | 189627 | /******************************************************************************
*
* Copyright(c) 2003 - 2011 Intel Corporation. All rights reserved.
*
* Portions of this file are derived from the ipw3945 project, as well
* as portions of the ieee80211 subsystem header files.
*
* 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.
*
* Contact Information:
* Intel Linux Wireless <ilw@linux.intel.com>
* Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*
*****************************************************************************/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/pci-aspm.h>
#include <linux/slab.h>
#include <linux/dma-mapping.h>
#include <linux/delay.h>
#include <linux/sched.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/firmware.h>
#include <linux/etherdevice.h>
#include <linux/if_arp.h>
#include <net/mac80211.h>
#include <asm/div64.h>
#define DRV_NAME "iwl4965"
#include "common.h"
#include "4965.h"
/******************************************************************************
*
* module boiler plate
*
******************************************************************************/
/*
* module name, copyright, version, etc.
*/
#define DRV_DESCRIPTION "Intel(R) Wireless WiFi 4965 driver for Linux"
#ifdef CONFIG_IWLEGACY_DEBUG
#define VD "d"
#else
#define VD
#endif
#define DRV_VERSION IWLWIFI_VERSION VD
MODULE_DESCRIPTION(DRV_DESCRIPTION);
MODULE_VERSION(DRV_VERSION);
MODULE_AUTHOR(DRV_COPYRIGHT " " DRV_AUTHOR);
MODULE_LICENSE("GPL");
MODULE_ALIAS("iwl4965");
void
il4965_check_abort_status(struct il_priv *il, u8 frame_count, u32 status)
{
if (frame_count == 1 && status == TX_STATUS_FAIL_RFKILL_FLUSH) {
IL_ERR("Tx flush command to flush out all frames\n");
if (!test_bit(S_EXIT_PENDING, &il->status))
queue_work(il->workqueue, &il->tx_flush);
}
}
/*
* EEPROM
*/
struct il_mod_params il4965_mod_params = {
.restart_fw = 1,
/* the rest are 0 by default */
};
void
il4965_rx_queue_reset(struct il_priv *il, struct il_rx_queue *rxq)
{
unsigned long flags;
int i;
spin_lock_irqsave(&rxq->lock, flags);
INIT_LIST_HEAD(&rxq->rx_free);
INIT_LIST_HEAD(&rxq->rx_used);
/* Fill the rx_used queue with _all_ of the Rx buffers */
for (i = 0; i < RX_FREE_BUFFERS + RX_QUEUE_SIZE; i++) {
/* In the reset function, these buffers may have been allocated
* to an SKB, so we need to unmap and free potential storage */
if (rxq->pool[i].page != NULL) {
pci_unmap_page(il->pci_dev, rxq->pool[i].page_dma,
PAGE_SIZE << il->hw_params.rx_page_order,
PCI_DMA_FROMDEVICE);
__il_free_pages(il, rxq->pool[i].page);
rxq->pool[i].page = NULL;
}
list_add_tail(&rxq->pool[i].list, &rxq->rx_used);
}
for (i = 0; i < RX_QUEUE_SIZE; i++)
rxq->queue[i] = NULL;
/* Set us so that we have processed and used all buffers, but have
* not restocked the Rx queue with fresh buffers */
rxq->read = rxq->write = 0;
rxq->write_actual = 0;
rxq->free_count = 0;
spin_unlock_irqrestore(&rxq->lock, flags);
}
int
il4965_rx_init(struct il_priv *il, struct il_rx_queue *rxq)
{
u32 rb_size;
const u32 rfdnlog = RX_QUEUE_SIZE_LOG; /* 256 RBDs */
u32 rb_timeout = 0;
if (il->cfg->mod_params->amsdu_size_8K)
rb_size = FH49_RCSR_RX_CONFIG_REG_VAL_RB_SIZE_8K;
else
rb_size = FH49_RCSR_RX_CONFIG_REG_VAL_RB_SIZE_4K;
/* Stop Rx DMA */
il_wr(il, FH49_MEM_RCSR_CHNL0_CONFIG_REG, 0);
/* Reset driver's Rx queue write idx */
il_wr(il, FH49_RSCSR_CHNL0_RBDCB_WPTR_REG, 0);
/* Tell device where to find RBD circular buffer in DRAM */
il_wr(il, FH49_RSCSR_CHNL0_RBDCB_BASE_REG, (u32) (rxq->bd_dma >> 8));
/* Tell device where in DRAM to update its Rx status */
il_wr(il, FH49_RSCSR_CHNL0_STTS_WPTR_REG, rxq->rb_stts_dma >> 4);
/* Enable Rx DMA
* Direct rx interrupts to hosts
* Rx buffer size 4 or 8k
* RB timeout 0x10
* 256 RBDs
*/
il_wr(il, FH49_MEM_RCSR_CHNL0_CONFIG_REG,
FH49_RCSR_RX_CONFIG_CHNL_EN_ENABLE_VAL |
FH49_RCSR_CHNL0_RX_CONFIG_IRQ_DEST_INT_HOST_VAL |
FH49_RCSR_CHNL0_RX_CONFIG_SINGLE_FRAME_MSK |
rb_size |
(rb_timeout << FH49_RCSR_RX_CONFIG_REG_IRQ_RBTH_POS) |
(rfdnlog << FH49_RCSR_RX_CONFIG_RBDCB_SIZE_POS));
/* Set interrupt coalescing timer to default (2048 usecs) */
il_write8(il, CSR_INT_COALESCING, IL_HOST_INT_TIMEOUT_DEF);
return 0;
}
static void
il4965_set_pwr_vmain(struct il_priv *il)
{
/*
* (for documentation purposes)
* to set power to V_AUX, do:
if (pci_pme_capable(il->pci_dev, PCI_D3cold))
il_set_bits_mask_prph(il, APMG_PS_CTRL_REG,
APMG_PS_CTRL_VAL_PWR_SRC_VAUX,
~APMG_PS_CTRL_MSK_PWR_SRC);
*/
il_set_bits_mask_prph(il, APMG_PS_CTRL_REG,
APMG_PS_CTRL_VAL_PWR_SRC_VMAIN,
~APMG_PS_CTRL_MSK_PWR_SRC);
}
int
il4965_hw_nic_init(struct il_priv *il)
{
unsigned long flags;
struct il_rx_queue *rxq = &il->rxq;
int ret;
spin_lock_irqsave(&il->lock, flags);
il_apm_init(il);
/* Set interrupt coalescing calibration timer to default (512 usecs) */
il_write8(il, CSR_INT_COALESCING, IL_HOST_INT_CALIB_TIMEOUT_DEF);
spin_unlock_irqrestore(&il->lock, flags);
il4965_set_pwr_vmain(il);
il4965_nic_config(il);
/* Allocate the RX queue, or reset if it is already allocated */
if (!rxq->bd) {
ret = il_rx_queue_alloc(il);
if (ret) {
IL_ERR("Unable to initialize Rx queue\n");
return -ENOMEM;
}
} else
il4965_rx_queue_reset(il, rxq);
il4965_rx_replenish(il);
il4965_rx_init(il, rxq);
spin_lock_irqsave(&il->lock, flags);
rxq->need_update = 1;
il_rx_queue_update_write_ptr(il, rxq);
spin_unlock_irqrestore(&il->lock, flags);
/* Allocate or reset and init all Tx and Command queues */
if (!il->txq) {
ret = il4965_txq_ctx_alloc(il);
if (ret)
return ret;
} else
il4965_txq_ctx_reset(il);
set_bit(S_INIT, &il->status);
return 0;
}
/**
* il4965_dma_addr2rbd_ptr - convert a DMA address to a uCode read buffer ptr
*/
static inline __le32
il4965_dma_addr2rbd_ptr(struct il_priv *il, dma_addr_t dma_addr)
{
return cpu_to_le32((u32) (dma_addr >> 8));
}
/**
* il4965_rx_queue_restock - refill RX queue from pre-allocated pool
*
* If there are slots in the RX queue that need to be restocked,
* and we have free pre-allocated buffers, fill the ranks as much
* as we can, pulling from rx_free.
*
* This moves the 'write' idx forward to catch up with 'processed', and
* also updates the memory address in the firmware to reference the new
* target buffer.
*/
void
il4965_rx_queue_restock(struct il_priv *il)
{
struct il_rx_queue *rxq = &il->rxq;
struct list_head *element;
struct il_rx_buf *rxb;
unsigned long flags;
spin_lock_irqsave(&rxq->lock, flags);
while (il_rx_queue_space(rxq) > 0 && rxq->free_count) {
/* The overwritten rxb must be a used one */
rxb = rxq->queue[rxq->write];
BUG_ON(rxb && rxb->page);
/* Get next free Rx buffer, remove from free list */
element = rxq->rx_free.next;
rxb = list_entry(element, struct il_rx_buf, list);
list_del(element);
/* Point to Rx buffer via next RBD in circular buffer */
rxq->bd[rxq->write] =
il4965_dma_addr2rbd_ptr(il, rxb->page_dma);
rxq->queue[rxq->write] = rxb;
rxq->write = (rxq->write + 1) & RX_QUEUE_MASK;
rxq->free_count--;
}
spin_unlock_irqrestore(&rxq->lock, flags);
/* If the pre-allocated buffer pool is dropping low, schedule to
* refill it */
if (rxq->free_count <= RX_LOW_WATERMARK)
queue_work(il->workqueue, &il->rx_replenish);
/* If we've added more space for the firmware to place data, tell it.
* Increment device's write pointer in multiples of 8. */
if (rxq->write_actual != (rxq->write & ~0x7)) {
spin_lock_irqsave(&rxq->lock, flags);
rxq->need_update = 1;
spin_unlock_irqrestore(&rxq->lock, flags);
il_rx_queue_update_write_ptr(il, rxq);
}
}
/**
* il4965_rx_replenish - Move all used packet from rx_used to rx_free
*
* When moving to rx_free an SKB is allocated for the slot.
*
* Also restock the Rx queue via il_rx_queue_restock.
* This is called as a scheduled work item (except for during initialization)
*/
static void
il4965_rx_allocate(struct il_priv *il, gfp_t priority)
{
struct il_rx_queue *rxq = &il->rxq;
struct list_head *element;
struct il_rx_buf *rxb;
struct page *page;
dma_addr_t page_dma;
unsigned long flags;
gfp_t gfp_mask = priority;
while (1) {
spin_lock_irqsave(&rxq->lock, flags);
if (list_empty(&rxq->rx_used)) {
spin_unlock_irqrestore(&rxq->lock, flags);
return;
}
spin_unlock_irqrestore(&rxq->lock, flags);
if (rxq->free_count > RX_LOW_WATERMARK)
gfp_mask |= __GFP_NOWARN;
if (il->hw_params.rx_page_order > 0)
gfp_mask |= __GFP_COMP;
/* Alloc a new receive buffer */
page = alloc_pages(gfp_mask, il->hw_params.rx_page_order);
if (!page) {
if (net_ratelimit())
D_INFO("alloc_pages failed, " "order: %d\n",
il->hw_params.rx_page_order);
if (rxq->free_count <= RX_LOW_WATERMARK &&
net_ratelimit())
IL_ERR("Failed to alloc_pages with %s. "
"Only %u free buffers remaining.\n",
priority ==
GFP_ATOMIC ? "GFP_ATOMIC" : "GFP_KERNEL",
rxq->free_count);
/* We don't reschedule replenish work here -- we will
* call the restock method and if it still needs
* more buffers it will schedule replenish */
return;
}
/* Get physical address of the RB */
page_dma =
pci_map_page(il->pci_dev, page, 0,
PAGE_SIZE << il->hw_params.rx_page_order,
PCI_DMA_FROMDEVICE);
if (unlikely(pci_dma_mapping_error(il->pci_dev, page_dma))) {
__free_pages(page, il->hw_params.rx_page_order);
break;
}
spin_lock_irqsave(&rxq->lock, flags);
if (list_empty(&rxq->rx_used)) {
spin_unlock_irqrestore(&rxq->lock, flags);
pci_unmap_page(il->pci_dev, page_dma,
PAGE_SIZE << il->hw_params.rx_page_order,
PCI_DMA_FROMDEVICE);
__free_pages(page, il->hw_params.rx_page_order);
return;
}
element = rxq->rx_used.next;
rxb = list_entry(element, struct il_rx_buf, list);
list_del(element);
BUG_ON(rxb->page);
rxb->page = page;
rxb->page_dma = page_dma;
list_add_tail(&rxb->list, &rxq->rx_free);
rxq->free_count++;
il->alloc_rxb_page++;
spin_unlock_irqrestore(&rxq->lock, flags);
}
}
void
il4965_rx_replenish(struct il_priv *il)
{
unsigned long flags;
il4965_rx_allocate(il, GFP_KERNEL);
spin_lock_irqsave(&il->lock, flags);
il4965_rx_queue_restock(il);
spin_unlock_irqrestore(&il->lock, flags);
}
void
il4965_rx_replenish_now(struct il_priv *il)
{
il4965_rx_allocate(il, GFP_ATOMIC);
il4965_rx_queue_restock(il);
}
/* Assumes that the skb field of the buffers in 'pool' is kept accurate.
* If an SKB has been detached, the POOL needs to have its SKB set to NULL
* This free routine walks the list of POOL entries and if SKB is set to
* non NULL it is unmapped and freed
*/
void
il4965_rx_queue_free(struct il_priv *il, struct il_rx_queue *rxq)
{
int i;
for (i = 0; i < RX_QUEUE_SIZE + RX_FREE_BUFFERS; i++) {
if (rxq->pool[i].page != NULL) {
pci_unmap_page(il->pci_dev, rxq->pool[i].page_dma,
PAGE_SIZE << il->hw_params.rx_page_order,
PCI_DMA_FROMDEVICE);
__il_free_pages(il, rxq->pool[i].page);
rxq->pool[i].page = NULL;
}
}
dma_free_coherent(&il->pci_dev->dev, 4 * RX_QUEUE_SIZE, rxq->bd,
rxq->bd_dma);
dma_free_coherent(&il->pci_dev->dev, sizeof(struct il_rb_status),
rxq->rb_stts, rxq->rb_stts_dma);
rxq->bd = NULL;
rxq->rb_stts = NULL;
}
int
il4965_rxq_stop(struct il_priv *il)
{
int ret;
_il_wr(il, FH49_MEM_RCSR_CHNL0_CONFIG_REG, 0);
ret = _il_poll_bit(il, FH49_MEM_RSSR_RX_STATUS_REG,
FH49_RSSR_CHNL0_RX_STATUS_CHNL_IDLE,
FH49_RSSR_CHNL0_RX_STATUS_CHNL_IDLE,
1000);
if (ret < 0)
IL_ERR("Can't stop Rx DMA.\n");
return 0;
}
int
il4965_hwrate_to_mac80211_idx(u32 rate_n_flags, enum ieee80211_band band)
{
int idx = 0;
int band_offset = 0;
/* HT rate format: mac80211 wants an MCS number, which is just LSB */
if (rate_n_flags & RATE_MCS_HT_MSK) {
idx = (rate_n_flags & 0xff);
return idx;
/* Legacy rate format, search for match in table */
} else {
if (band == IEEE80211_BAND_5GHZ)
band_offset = IL_FIRST_OFDM_RATE;
for (idx = band_offset; idx < RATE_COUNT_LEGACY; idx++)
if (il_rates[idx].plcp == (rate_n_flags & 0xFF))
return idx - band_offset;
}
return -1;
}
static int
il4965_calc_rssi(struct il_priv *il, struct il_rx_phy_res *rx_resp)
{
/* data from PHY/DSP regarding signal strength, etc.,
* contents are always there, not configurable by host. */
struct il4965_rx_non_cfg_phy *ncphy =
(struct il4965_rx_non_cfg_phy *)rx_resp->non_cfg_phy_buf;
u32 agc =
(le16_to_cpu(ncphy->agc_info) & IL49_AGC_DB_MASK) >>
IL49_AGC_DB_POS;
u32 valid_antennae =
(le16_to_cpu(rx_resp->phy_flags) & IL49_RX_PHY_FLAGS_ANTENNAE_MASK)
>> IL49_RX_PHY_FLAGS_ANTENNAE_OFFSET;
u8 max_rssi = 0;
u32 i;
/* Find max rssi among 3 possible receivers.
* These values are measured by the digital signal processor (DSP).
* They should stay fairly constant even as the signal strength varies,
* if the radio's automatic gain control (AGC) is working right.
* AGC value (see below) will provide the "interesting" info. */
for (i = 0; i < 3; i++)
if (valid_antennae & (1 << i))
max_rssi = max(ncphy->rssi_info[i << 1], max_rssi);
D_STATS("Rssi In A %d B %d C %d Max %d AGC dB %d\n",
ncphy->rssi_info[0], ncphy->rssi_info[2], ncphy->rssi_info[4],
max_rssi, agc);
/* dBm = max_rssi dB - agc dB - constant.
* Higher AGC (higher radio gain) means lower signal. */
return max_rssi - agc - IL4965_RSSI_OFFSET;
}
static u32
il4965_translate_rx_status(struct il_priv *il, u32 decrypt_in)
{
u32 decrypt_out = 0;
if ((decrypt_in & RX_RES_STATUS_STATION_FOUND) ==
RX_RES_STATUS_STATION_FOUND)
decrypt_out |=
(RX_RES_STATUS_STATION_FOUND |
RX_RES_STATUS_NO_STATION_INFO_MISMATCH);
decrypt_out |= (decrypt_in & RX_RES_STATUS_SEC_TYPE_MSK);
/* packet was not encrypted */
if ((decrypt_in & RX_RES_STATUS_SEC_TYPE_MSK) ==
RX_RES_STATUS_SEC_TYPE_NONE)
return decrypt_out;
/* packet was encrypted with unknown alg */
if ((decrypt_in & RX_RES_STATUS_SEC_TYPE_MSK) ==
RX_RES_STATUS_SEC_TYPE_ERR)
return decrypt_out;
/* decryption was not done in HW */
if ((decrypt_in & RX_MPDU_RES_STATUS_DEC_DONE_MSK) !=
RX_MPDU_RES_STATUS_DEC_DONE_MSK)
return decrypt_out;
switch (decrypt_in & RX_RES_STATUS_SEC_TYPE_MSK) {
case RX_RES_STATUS_SEC_TYPE_CCMP:
/* alg is CCM: check MIC only */
if (!(decrypt_in & RX_MPDU_RES_STATUS_MIC_OK))
/* Bad MIC */
decrypt_out |= RX_RES_STATUS_BAD_ICV_MIC;
else
decrypt_out |= RX_RES_STATUS_DECRYPT_OK;
break;
case RX_RES_STATUS_SEC_TYPE_TKIP:
if (!(decrypt_in & RX_MPDU_RES_STATUS_TTAK_OK)) {
/* Bad TTAK */
decrypt_out |= RX_RES_STATUS_BAD_KEY_TTAK;
break;
}
/* fall through if TTAK OK */
default:
if (!(decrypt_in & RX_MPDU_RES_STATUS_ICV_OK))
decrypt_out |= RX_RES_STATUS_BAD_ICV_MIC;
else
decrypt_out |= RX_RES_STATUS_DECRYPT_OK;
break;
}
D_RX("decrypt_in:0x%x decrypt_out = 0x%x\n", decrypt_in, decrypt_out);
return decrypt_out;
}
#define SMALL_PACKET_SIZE 256
static void
il4965_pass_packet_to_mac80211(struct il_priv *il, struct ieee80211_hdr *hdr,
u32 len, u32 ampdu_status, struct il_rx_buf *rxb,
struct ieee80211_rx_status *stats)
{
struct sk_buff *skb;
__le16 fc = hdr->frame_control;
/* We only process data packets if the interface is open */
if (unlikely(!il->is_open)) {
D_DROP("Dropping packet while interface is not open.\n");
return;
}
if (unlikely(test_bit(IL_STOP_REASON_PASSIVE, &il->stop_reason))) {
il_wake_queues_by_reason(il, IL_STOP_REASON_PASSIVE);
D_INFO("Woke queues - frame received on passive channel\n");
}
/* In case of HW accelerated crypto and bad decryption, drop */
if (!il->cfg->mod_params->sw_crypto &&
il_set_decrypted_flag(il, hdr, ampdu_status, stats))
return;
skb = dev_alloc_skb(SMALL_PACKET_SIZE);
if (!skb) {
IL_ERR("dev_alloc_skb failed\n");
return;
}
if (len <= SMALL_PACKET_SIZE) {
memcpy(skb_put(skb, len), hdr, len);
} else {
skb_add_rx_frag(skb, 0, rxb->page, (void *)hdr - rxb_addr(rxb),
len, PAGE_SIZE << il->hw_params.rx_page_order);
il->alloc_rxb_page--;
rxb->page = NULL;
}
il_update_stats(il, false, fc, len);
memcpy(IEEE80211_SKB_RXCB(skb), stats, sizeof(*stats));
ieee80211_rx(il->hw, skb);
}
/* Called for N_RX (legacy ABG frames), or
* N_RX_MPDU (HT high-throughput N frames). */
static void
il4965_hdl_rx(struct il_priv *il, struct il_rx_buf *rxb)
{
struct ieee80211_hdr *header;
struct ieee80211_rx_status rx_status = {};
struct il_rx_pkt *pkt = rxb_addr(rxb);
struct il_rx_phy_res *phy_res;
__le32 rx_pkt_status;
struct il_rx_mpdu_res_start *amsdu;
u32 len;
u32 ampdu_status;
u32 rate_n_flags;
/**
* N_RX and N_RX_MPDU are handled differently.
* N_RX: physical layer info is in this buffer
* N_RX_MPDU: physical layer info was sent in separate
* command and cached in il->last_phy_res
*
* Here we set up local variables depending on which command is
* received.
*/
if (pkt->hdr.cmd == N_RX) {
phy_res = (struct il_rx_phy_res *)pkt->u.raw;
header =
(struct ieee80211_hdr *)(pkt->u.raw + sizeof(*phy_res) +
phy_res->cfg_phy_cnt);
len = le16_to_cpu(phy_res->byte_count);
rx_pkt_status =
*(__le32 *) (pkt->u.raw + sizeof(*phy_res) +
phy_res->cfg_phy_cnt + len);
ampdu_status = le32_to_cpu(rx_pkt_status);
} else {
if (!il->_4965.last_phy_res_valid) {
IL_ERR("MPDU frame without cached PHY data\n");
return;
}
phy_res = &il->_4965.last_phy_res;
amsdu = (struct il_rx_mpdu_res_start *)pkt->u.raw;
header = (struct ieee80211_hdr *)(pkt->u.raw + sizeof(*amsdu));
len = le16_to_cpu(amsdu->byte_count);
rx_pkt_status = *(__le32 *) (pkt->u.raw + sizeof(*amsdu) + len);
ampdu_status =
il4965_translate_rx_status(il, le32_to_cpu(rx_pkt_status));
}
if ((unlikely(phy_res->cfg_phy_cnt > 20))) {
D_DROP("dsp size out of range [0,20]: %d\n",
phy_res->cfg_phy_cnt);
return;
}
if (!(rx_pkt_status & RX_RES_STATUS_NO_CRC32_ERROR) ||
!(rx_pkt_status & RX_RES_STATUS_NO_RXE_OVERFLOW)) {
D_RX("Bad CRC or FIFO: 0x%08X.\n", le32_to_cpu(rx_pkt_status));
return;
}
/* This will be used in several places later */
rate_n_flags = le32_to_cpu(phy_res->rate_n_flags);
/* rx_status carries information about the packet to mac80211 */
rx_status.mactime = le64_to_cpu(phy_res->timestamp);
rx_status.band =
(phy_res->
phy_flags & RX_RES_PHY_FLAGS_BAND_24_MSK) ? IEEE80211_BAND_2GHZ :
IEEE80211_BAND_5GHZ;
rx_status.freq =
ieee80211_channel_to_frequency(le16_to_cpu(phy_res->channel),
rx_status.band);
rx_status.rate_idx =
il4965_hwrate_to_mac80211_idx(rate_n_flags, rx_status.band);
rx_status.flag = 0;
/* TSF isn't reliable. In order to allow smooth user experience,
* this W/A doesn't propagate it to the mac80211 */
/*rx_status.flag |= RX_FLAG_MACTIME_START; */
il->ucode_beacon_time = le32_to_cpu(phy_res->beacon_time_stamp);
/* Find max signal strength (dBm) among 3 antenna/receiver chains */
rx_status.signal = il4965_calc_rssi(il, phy_res);
D_STATS("Rssi %d, TSF %llu\n", rx_status.signal,
(unsigned long long)rx_status.mactime);
/*
* "antenna number"
*
* It seems that the antenna field in the phy flags value
* is actually a bit field. This is undefined by radiotap,
* it wants an actual antenna number but I always get "7"
* for most legacy frames I receive indicating that the
* same frame was received on all three RX chains.
*
* I think this field should be removed in favor of a
* new 802.11n radiotap field "RX chains" that is defined
* as a bitmask.
*/
rx_status.antenna =
(le16_to_cpu(phy_res->phy_flags) & RX_RES_PHY_FLAGS_ANTENNA_MSK) >>
RX_RES_PHY_FLAGS_ANTENNA_POS;
/* set the preamble flag if appropriate */
if (phy_res->phy_flags & RX_RES_PHY_FLAGS_SHORT_PREAMBLE_MSK)
rx_status.flag |= RX_FLAG_SHORTPRE;
/* Set up the HT phy flags */
if (rate_n_flags & RATE_MCS_HT_MSK)
rx_status.flag |= RX_FLAG_HT;
if (rate_n_flags & RATE_MCS_HT40_MSK)
rx_status.flag |= RX_FLAG_40MHZ;
if (rate_n_flags & RATE_MCS_SGI_MSK)
rx_status.flag |= RX_FLAG_SHORT_GI;
if (phy_res->phy_flags & RX_RES_PHY_FLAGS_AGG_MSK) {
/* We know which subframes of an A-MPDU belong
* together since we get a single PHY response
* from the firmware for all of them.
*/
rx_status.flag |= RX_FLAG_AMPDU_DETAILS;
rx_status.ampdu_reference = il->_4965.ampdu_ref;
}
il4965_pass_packet_to_mac80211(il, header, len, ampdu_status, rxb,
&rx_status);
}
/* Cache phy data (Rx signal strength, etc) for HT frame (N_RX_PHY).
* This will be used later in il_hdl_rx() for N_RX_MPDU. */
static void
il4965_hdl_rx_phy(struct il_priv *il, struct il_rx_buf *rxb)
{
struct il_rx_pkt *pkt = rxb_addr(rxb);
il->_4965.last_phy_res_valid = true;
il->_4965.ampdu_ref++;
memcpy(&il->_4965.last_phy_res, pkt->u.raw,
sizeof(struct il_rx_phy_res));
}
static int
il4965_get_channels_for_scan(struct il_priv *il, struct ieee80211_vif *vif,
enum ieee80211_band band, u8 is_active,
u8 n_probes, struct il_scan_channel *scan_ch)
{
struct ieee80211_channel *chan;
const struct ieee80211_supported_band *sband;
const struct il_channel_info *ch_info;
u16 passive_dwell = 0;
u16 active_dwell = 0;
int added, i;
u16 channel;
sband = il_get_hw_mode(il, band);
if (!sband)
return 0;
active_dwell = il_get_active_dwell_time(il, band, n_probes);
passive_dwell = il_get_passive_dwell_time(il, band, vif);
if (passive_dwell <= active_dwell)
passive_dwell = active_dwell + 1;
for (i = 0, added = 0; i < il->scan_request->n_channels; i++) {
chan = il->scan_request->channels[i];
if (chan->band != band)
continue;
channel = chan->hw_value;
scan_ch->channel = cpu_to_le16(channel);
ch_info = il_get_channel_info(il, band, channel);
if (!il_is_channel_valid(ch_info)) {
D_SCAN("Channel %d is INVALID for this band.\n",
channel);
continue;
}
if (!is_active || il_is_channel_passive(ch_info) ||
(chan->flags & IEEE80211_CHAN_NO_IR))
scan_ch->type = SCAN_CHANNEL_TYPE_PASSIVE;
else
scan_ch->type = SCAN_CHANNEL_TYPE_ACTIVE;
if (n_probes)
scan_ch->type |= IL_SCAN_PROBE_MASK(n_probes);
scan_ch->active_dwell = cpu_to_le16(active_dwell);
scan_ch->passive_dwell = cpu_to_le16(passive_dwell);
/* Set txpower levels to defaults */
scan_ch->dsp_atten = 110;
/* NOTE: if we were doing 6Mb OFDM for scans we'd use
* power level:
* scan_ch->tx_gain = ((1 << 5) | (2 << 3)) | 3;
*/
if (band == IEEE80211_BAND_5GHZ)
scan_ch->tx_gain = ((1 << 5) | (3 << 3)) | 3;
else
scan_ch->tx_gain = ((1 << 5) | (5 << 3));
D_SCAN("Scanning ch=%d prob=0x%X [%s %d]\n", channel,
le32_to_cpu(scan_ch->type),
(scan_ch->
type & SCAN_CHANNEL_TYPE_ACTIVE) ? "ACTIVE" : "PASSIVE",
(scan_ch->
type & SCAN_CHANNEL_TYPE_ACTIVE) ? active_dwell :
passive_dwell);
scan_ch++;
added++;
}
D_SCAN("total channels to scan %d\n", added);
return added;
}
static void
il4965_toggle_tx_ant(struct il_priv *il, u8 *ant, u8 valid)
{
int i;
u8 ind = *ant;
for (i = 0; i < RATE_ANT_NUM - 1; i++) {
ind = (ind + 1) < RATE_ANT_NUM ? ind + 1 : 0;
if (valid & BIT(ind)) {
*ant = ind;
return;
}
}
}
int
il4965_request_scan(struct il_priv *il, struct ieee80211_vif *vif)
{
struct il_host_cmd cmd = {
.id = C_SCAN,
.len = sizeof(struct il_scan_cmd),
.flags = CMD_SIZE_HUGE,
};
struct il_scan_cmd *scan;
u32 rate_flags = 0;
u16 cmd_len;
u16 rx_chain = 0;
enum ieee80211_band band;
u8 n_probes = 0;
u8 rx_ant = il->hw_params.valid_rx_ant;
u8 rate;
bool is_active = false;
int chan_mod;
u8 active_chains;
u8 scan_tx_antennas = il->hw_params.valid_tx_ant;
int ret;
lockdep_assert_held(&il->mutex);
if (!il->scan_cmd) {
il->scan_cmd =
kmalloc(sizeof(struct il_scan_cmd) + IL_MAX_SCAN_SIZE,
GFP_KERNEL);
if (!il->scan_cmd) {
D_SCAN("fail to allocate memory for scan\n");
return -ENOMEM;
}
}
scan = il->scan_cmd;
memset(scan, 0, sizeof(struct il_scan_cmd) + IL_MAX_SCAN_SIZE);
scan->quiet_plcp_th = IL_PLCP_QUIET_THRESH;
scan->quiet_time = IL_ACTIVE_QUIET_TIME;
if (il_is_any_associated(il)) {
u16 interval;
u32 extra;
u32 suspend_time = 100;
u32 scan_suspend_time = 100;
D_INFO("Scanning while associated...\n");
interval = vif->bss_conf.beacon_int;
scan->suspend_time = 0;
scan->max_out_time = cpu_to_le32(200 * 1024);
if (!interval)
interval = suspend_time;
extra = (suspend_time / interval) << 22;
scan_suspend_time =
(extra | ((suspend_time % interval) * 1024));
scan->suspend_time = cpu_to_le32(scan_suspend_time);
D_SCAN("suspend_time 0x%X beacon interval %d\n",
scan_suspend_time, interval);
}
if (il->scan_request->n_ssids) {
int i, p = 0;
D_SCAN("Kicking off active scan\n");
for (i = 0; i < il->scan_request->n_ssids; i++) {
/* always does wildcard anyway */
if (!il->scan_request->ssids[i].ssid_len)
continue;
scan->direct_scan[p].id = WLAN_EID_SSID;
scan->direct_scan[p].len =
il->scan_request->ssids[i].ssid_len;
memcpy(scan->direct_scan[p].ssid,
il->scan_request->ssids[i].ssid,
il->scan_request->ssids[i].ssid_len);
n_probes++;
p++;
}
is_active = true;
} else
D_SCAN("Start passive scan.\n");
scan->tx_cmd.tx_flags = TX_CMD_FLG_SEQ_CTL_MSK;
scan->tx_cmd.sta_id = il->hw_params.bcast_id;
scan->tx_cmd.stop_time.life_time = TX_CMD_LIFE_TIME_INFINITE;
switch (il->scan_band) {
case IEEE80211_BAND_2GHZ:
scan->flags = RXON_FLG_BAND_24G_MSK | RXON_FLG_AUTO_DETECT_MSK;
chan_mod =
le32_to_cpu(il->active.flags & RXON_FLG_CHANNEL_MODE_MSK) >>
RXON_FLG_CHANNEL_MODE_POS;
if (chan_mod == CHANNEL_MODE_PURE_40) {
rate = RATE_6M_PLCP;
} else {
rate = RATE_1M_PLCP;
rate_flags = RATE_MCS_CCK_MSK;
}
break;
case IEEE80211_BAND_5GHZ:
rate = RATE_6M_PLCP;
break;
default:
IL_WARN("Invalid scan band\n");
return -EIO;
}
/*
* If active scanning is requested but a certain channel is
* marked passive, we can do active scanning if we detect
* transmissions.
*
* There is an issue with some firmware versions that triggers
* a sysassert on a "good CRC threshold" of zero (== disabled),
* on a radar channel even though this means that we should NOT
* send probes.
*
* The "good CRC threshold" is the number of frames that we
* need to receive during our dwell time on a channel before
* sending out probes -- setting this to a huge value will
* mean we never reach it, but at the same time work around
* the aforementioned issue. Thus use IL_GOOD_CRC_TH_NEVER
* here instead of IL_GOOD_CRC_TH_DISABLED.
*/
scan->good_CRC_th =
is_active ? IL_GOOD_CRC_TH_DEFAULT : IL_GOOD_CRC_TH_NEVER;
band = il->scan_band;
if (il->cfg->scan_rx_antennas[band])
rx_ant = il->cfg->scan_rx_antennas[band];
il4965_toggle_tx_ant(il, &il->scan_tx_ant[band], scan_tx_antennas);
rate_flags |= BIT(il->scan_tx_ant[band]) << RATE_MCS_ANT_POS;
scan->tx_cmd.rate_n_flags = cpu_to_le32(rate | rate_flags);
/* In power save mode use one chain, otherwise use all chains */
if (test_bit(S_POWER_PMI, &il->status)) {
/* rx_ant has been set to all valid chains previously */
active_chains =
rx_ant & ((u8) (il->chain_noise_data.active_chains));
if (!active_chains)
active_chains = rx_ant;
D_SCAN("chain_noise_data.active_chains: %u\n",
il->chain_noise_data.active_chains);
rx_ant = il4965_first_antenna(active_chains);
}
/* MIMO is not used here, but value is required */
rx_chain |= il->hw_params.valid_rx_ant << RXON_RX_CHAIN_VALID_POS;
rx_chain |= rx_ant << RXON_RX_CHAIN_FORCE_MIMO_SEL_POS;
rx_chain |= rx_ant << RXON_RX_CHAIN_FORCE_SEL_POS;
rx_chain |= 0x1 << RXON_RX_CHAIN_DRIVER_FORCE_POS;
scan->rx_chain = cpu_to_le16(rx_chain);
cmd_len =
il_fill_probe_req(il, (struct ieee80211_mgmt *)scan->data,
vif->addr, il->scan_request->ie,
il->scan_request->ie_len,
IL_MAX_SCAN_SIZE - sizeof(*scan));
scan->tx_cmd.len = cpu_to_le16(cmd_len);
scan->filter_flags |=
(RXON_FILTER_ACCEPT_GRP_MSK | RXON_FILTER_BCON_AWARE_MSK);
scan->channel_count =
il4965_get_channels_for_scan(il, vif, band, is_active, n_probes,
(void *)&scan->data[cmd_len]);
if (scan->channel_count == 0) {
D_SCAN("channel count %d\n", scan->channel_count);
return -EIO;
}
cmd.len +=
le16_to_cpu(scan->tx_cmd.len) +
scan->channel_count * sizeof(struct il_scan_channel);
cmd.data = scan;
scan->len = cpu_to_le16(cmd.len);
set_bit(S_SCAN_HW, &il->status);
ret = il_send_cmd_sync(il, &cmd);
if (ret)
clear_bit(S_SCAN_HW, &il->status);
return ret;
}
int
il4965_manage_ibss_station(struct il_priv *il, struct ieee80211_vif *vif,
bool add)
{
struct il_vif_priv *vif_priv = (void *)vif->drv_priv;
if (add)
return il4965_add_bssid_station(il, vif->bss_conf.bssid,
&vif_priv->ibss_bssid_sta_id);
return il_remove_station(il, vif_priv->ibss_bssid_sta_id,
vif->bss_conf.bssid);
}
void
il4965_free_tfds_in_queue(struct il_priv *il, int sta_id, int tid, int freed)
{
lockdep_assert_held(&il->sta_lock);
if (il->stations[sta_id].tid[tid].tfds_in_queue >= freed)
il->stations[sta_id].tid[tid].tfds_in_queue -= freed;
else {
D_TX("free more than tfds_in_queue (%u:%d)\n",
il->stations[sta_id].tid[tid].tfds_in_queue, freed);
il->stations[sta_id].tid[tid].tfds_in_queue = 0;
}
}
#define IL_TX_QUEUE_MSK 0xfffff
static bool
il4965_is_single_rx_stream(struct il_priv *il)
{
return il->current_ht_config.smps == IEEE80211_SMPS_STATIC ||
il->current_ht_config.single_chain_sufficient;
}
#define IL_NUM_RX_CHAINS_MULTIPLE 3
#define IL_NUM_RX_CHAINS_SINGLE 2
#define IL_NUM_IDLE_CHAINS_DUAL 2
#define IL_NUM_IDLE_CHAINS_SINGLE 1
/*
* Determine how many receiver/antenna chains to use.
*
* More provides better reception via diversity. Fewer saves power
* at the expense of throughput, but only when not in powersave to
* start with.
*
* MIMO (dual stream) requires at least 2, but works better with 3.
* This does not determine *which* chains to use, just how many.
*/
static int
il4965_get_active_rx_chain_count(struct il_priv *il)
{
/* # of Rx chains to use when expecting MIMO. */
if (il4965_is_single_rx_stream(il))
return IL_NUM_RX_CHAINS_SINGLE;
else
return IL_NUM_RX_CHAINS_MULTIPLE;
}
/*
* When we are in power saving mode, unless device support spatial
* multiplexing power save, use the active count for rx chain count.
*/
static int
il4965_get_idle_rx_chain_count(struct il_priv *il, int active_cnt)
{
/* # Rx chains when idling, depending on SMPS mode */
switch (il->current_ht_config.smps) {
case IEEE80211_SMPS_STATIC:
case IEEE80211_SMPS_DYNAMIC:
return IL_NUM_IDLE_CHAINS_SINGLE;
case IEEE80211_SMPS_OFF:
return active_cnt;
default:
WARN(1, "invalid SMPS mode %d", il->current_ht_config.smps);
return active_cnt;
}
}
/* up to 4 chains */
static u8
il4965_count_chain_bitmap(u32 chain_bitmap)
{
u8 res;
res = (chain_bitmap & BIT(0)) >> 0;
res += (chain_bitmap & BIT(1)) >> 1;
res += (chain_bitmap & BIT(2)) >> 2;
res += (chain_bitmap & BIT(3)) >> 3;
return res;
}
/**
* il4965_set_rxon_chain - Set up Rx chain usage in "staging" RXON image
*
* Selects how many and which Rx receivers/antennas/chains to use.
* This should not be used for scan command ... it puts data in wrong place.
*/
void
il4965_set_rxon_chain(struct il_priv *il)
{
bool is_single = il4965_is_single_rx_stream(il);
bool is_cam = !test_bit(S_POWER_PMI, &il->status);
u8 idle_rx_cnt, active_rx_cnt, valid_rx_cnt;
u32 active_chains;
u16 rx_chain;
/* Tell uCode which antennas are actually connected.
* Before first association, we assume all antennas are connected.
* Just after first association, il4965_chain_noise_calibration()
* checks which antennas actually *are* connected. */
if (il->chain_noise_data.active_chains)
active_chains = il->chain_noise_data.active_chains;
else
active_chains = il->hw_params.valid_rx_ant;
rx_chain = active_chains << RXON_RX_CHAIN_VALID_POS;
/* How many receivers should we use? */
active_rx_cnt = il4965_get_active_rx_chain_count(il);
idle_rx_cnt = il4965_get_idle_rx_chain_count(il, active_rx_cnt);
/* correct rx chain count according hw settings
* and chain noise calibration
*/
valid_rx_cnt = il4965_count_chain_bitmap(active_chains);
if (valid_rx_cnt < active_rx_cnt)
active_rx_cnt = valid_rx_cnt;
if (valid_rx_cnt < idle_rx_cnt)
idle_rx_cnt = valid_rx_cnt;
rx_chain |= active_rx_cnt << RXON_RX_CHAIN_MIMO_CNT_POS;
rx_chain |= idle_rx_cnt << RXON_RX_CHAIN_CNT_POS;
il->staging.rx_chain = cpu_to_le16(rx_chain);
if (!is_single && active_rx_cnt >= IL_NUM_RX_CHAINS_SINGLE && is_cam)
il->staging.rx_chain |= RXON_RX_CHAIN_MIMO_FORCE_MSK;
else
il->staging.rx_chain &= ~RXON_RX_CHAIN_MIMO_FORCE_MSK;
D_ASSOC("rx_chain=0x%X active=%d idle=%d\n", il->staging.rx_chain,
active_rx_cnt, idle_rx_cnt);
WARN_ON(active_rx_cnt == 0 || idle_rx_cnt == 0 ||
active_rx_cnt < idle_rx_cnt);
}
static const char *
il4965_get_fh_string(int cmd)
{
switch (cmd) {
IL_CMD(FH49_RSCSR_CHNL0_STTS_WPTR_REG);
IL_CMD(FH49_RSCSR_CHNL0_RBDCB_BASE_REG);
IL_CMD(FH49_RSCSR_CHNL0_WPTR);
IL_CMD(FH49_MEM_RCSR_CHNL0_CONFIG_REG);
IL_CMD(FH49_MEM_RSSR_SHARED_CTRL_REG);
IL_CMD(FH49_MEM_RSSR_RX_STATUS_REG);
IL_CMD(FH49_MEM_RSSR_RX_ENABLE_ERR_IRQ2DRV);
IL_CMD(FH49_TSSR_TX_STATUS_REG);
IL_CMD(FH49_TSSR_TX_ERROR_REG);
default:
return "UNKNOWN";
}
}
int
il4965_dump_fh(struct il_priv *il, char **buf, bool display)
{
int i;
#ifdef CONFIG_IWLEGACY_DEBUG
int pos = 0;
size_t bufsz = 0;
#endif
static const u32 fh_tbl[] = {
FH49_RSCSR_CHNL0_STTS_WPTR_REG,
FH49_RSCSR_CHNL0_RBDCB_BASE_REG,
FH49_RSCSR_CHNL0_WPTR,
FH49_MEM_RCSR_CHNL0_CONFIG_REG,
FH49_MEM_RSSR_SHARED_CTRL_REG,
FH49_MEM_RSSR_RX_STATUS_REG,
FH49_MEM_RSSR_RX_ENABLE_ERR_IRQ2DRV,
FH49_TSSR_TX_STATUS_REG,
FH49_TSSR_TX_ERROR_REG
};
#ifdef CONFIG_IWLEGACY_DEBUG
if (display) {
bufsz = ARRAY_SIZE(fh_tbl) * 48 + 40;
*buf = kmalloc(bufsz, GFP_KERNEL);
if (!*buf)
return -ENOMEM;
pos +=
scnprintf(*buf + pos, bufsz - pos, "FH register values:\n");
for (i = 0; i < ARRAY_SIZE(fh_tbl); i++) {
pos +=
scnprintf(*buf + pos, bufsz - pos,
" %34s: 0X%08x\n",
il4965_get_fh_string(fh_tbl[i]),
il_rd(il, fh_tbl[i]));
}
return pos;
}
#endif
IL_ERR("FH register values:\n");
for (i = 0; i < ARRAY_SIZE(fh_tbl); i++) {
IL_ERR(" %34s: 0X%08x\n", il4965_get_fh_string(fh_tbl[i]),
il_rd(il, fh_tbl[i]));
}
return 0;
}
static void
il4965_hdl_missed_beacon(struct il_priv *il, struct il_rx_buf *rxb)
{
struct il_rx_pkt *pkt = rxb_addr(rxb);
struct il_missed_beacon_notif *missed_beacon;
missed_beacon = &pkt->u.missed_beacon;
if (le32_to_cpu(missed_beacon->consecutive_missed_beacons) >
il->missed_beacon_threshold) {
D_CALIB("missed bcn cnsq %d totl %d rcd %d expctd %d\n",
le32_to_cpu(missed_beacon->consecutive_missed_beacons),
le32_to_cpu(missed_beacon->total_missed_becons),
le32_to_cpu(missed_beacon->num_recvd_beacons),
le32_to_cpu(missed_beacon->num_expected_beacons));
if (!test_bit(S_SCANNING, &il->status))
il4965_init_sensitivity(il);
}
}
/* Calculate noise level, based on measurements during network silence just
* before arriving beacon. This measurement can be done only if we know
* exactly when to expect beacons, therefore only when we're associated. */
static void
il4965_rx_calc_noise(struct il_priv *il)
{
struct stats_rx_non_phy *rx_info;
int num_active_rx = 0;
int total_silence = 0;
int bcn_silence_a, bcn_silence_b, bcn_silence_c;
int last_rx_noise;
rx_info = &(il->_4965.stats.rx.general);
bcn_silence_a =
le32_to_cpu(rx_info->beacon_silence_rssi_a) & IN_BAND_FILTER;
bcn_silence_b =
le32_to_cpu(rx_info->beacon_silence_rssi_b) & IN_BAND_FILTER;
bcn_silence_c =
le32_to_cpu(rx_info->beacon_silence_rssi_c) & IN_BAND_FILTER;
if (bcn_silence_a) {
total_silence += bcn_silence_a;
num_active_rx++;
}
if (bcn_silence_b) {
total_silence += bcn_silence_b;
num_active_rx++;
}
if (bcn_silence_c) {
total_silence += bcn_silence_c;
num_active_rx++;
}
/* Average among active antennas */
if (num_active_rx)
last_rx_noise = (total_silence / num_active_rx) - 107;
else
last_rx_noise = IL_NOISE_MEAS_NOT_AVAILABLE;
D_CALIB("inband silence a %u, b %u, c %u, dBm %d\n", bcn_silence_a,
bcn_silence_b, bcn_silence_c, last_rx_noise);
}
#ifdef CONFIG_IWLEGACY_DEBUGFS
/*
* based on the assumption of all stats counter are in DWORD
* FIXME: This function is for debugging, do not deal with
* the case of counters roll-over.
*/
static void
il4965_accumulative_stats(struct il_priv *il, __le32 * stats)
{
int i, size;
__le32 *prev_stats;
u32 *accum_stats;
u32 *delta, *max_delta;
struct stats_general_common *general, *accum_general;
struct stats_tx *tx, *accum_tx;
prev_stats = (__le32 *) &il->_4965.stats;
accum_stats = (u32 *) &il->_4965.accum_stats;
size = sizeof(struct il_notif_stats);
general = &il->_4965.stats.general.common;
accum_general = &il->_4965.accum_stats.general.common;
tx = &il->_4965.stats.tx;
accum_tx = &il->_4965.accum_stats.tx;
delta = (u32 *) &il->_4965.delta_stats;
max_delta = (u32 *) &il->_4965.max_delta;
for (i = sizeof(__le32); i < size;
i +=
sizeof(__le32), stats++, prev_stats++, delta++, max_delta++,
accum_stats++) {
if (le32_to_cpu(*stats) > le32_to_cpu(*prev_stats)) {
*delta =
(le32_to_cpu(*stats) - le32_to_cpu(*prev_stats));
*accum_stats += *delta;
if (*delta > *max_delta)
*max_delta = *delta;
}
}
/* reset accumulative stats for "no-counter" type stats */
accum_general->temperature = general->temperature;
accum_general->ttl_timestamp = general->ttl_timestamp;
}
#endif
static void
il4965_hdl_stats(struct il_priv *il, struct il_rx_buf *rxb)
{
const int recalib_seconds = 60;
bool change;
struct il_rx_pkt *pkt = rxb_addr(rxb);
D_RX("Statistics notification received (%d vs %d).\n",
(int)sizeof(struct il_notif_stats),
le32_to_cpu(pkt->len_n_flags) & IL_RX_FRAME_SIZE_MSK);
change =
((il->_4965.stats.general.common.temperature !=
pkt->u.stats.general.common.temperature) ||
((il->_4965.stats.flag & STATS_REPLY_FLG_HT40_MODE_MSK) !=
(pkt->u.stats.flag & STATS_REPLY_FLG_HT40_MODE_MSK)));
#ifdef CONFIG_IWLEGACY_DEBUGFS
il4965_accumulative_stats(il, (__le32 *) &pkt->u.stats);
#endif
/* TODO: reading some of stats is unneeded */
memcpy(&il->_4965.stats, &pkt->u.stats, sizeof(il->_4965.stats));
set_bit(S_STATS, &il->status);
/*
* Reschedule the stats timer to occur in recalib_seconds to ensure
* we get a thermal update even if the uCode doesn't give us one
*/
mod_timer(&il->stats_periodic,
jiffies + msecs_to_jiffies(recalib_seconds * 1000));
if (unlikely(!test_bit(S_SCANNING, &il->status)) &&
(pkt->hdr.cmd == N_STATS)) {
il4965_rx_calc_noise(il);
queue_work(il->workqueue, &il->run_time_calib_work);
}
if (change)
il4965_temperature_calib(il);
}
static void
il4965_hdl_c_stats(struct il_priv *il, struct il_rx_buf *rxb)
{
struct il_rx_pkt *pkt = rxb_addr(rxb);
if (le32_to_cpu(pkt->u.stats.flag) & UCODE_STATS_CLEAR_MSK) {
#ifdef CONFIG_IWLEGACY_DEBUGFS
memset(&il->_4965.accum_stats, 0,
sizeof(struct il_notif_stats));
memset(&il->_4965.delta_stats, 0,
sizeof(struct il_notif_stats));
memset(&il->_4965.max_delta, 0, sizeof(struct il_notif_stats));
#endif
D_RX("Statistics have been cleared\n");
}
il4965_hdl_stats(il, rxb);
}
/*
* mac80211 queues, ACs, hardware queues, FIFOs.
*
* Cf. http://wireless.kernel.org/en/developers/Documentation/mac80211/queues
*
* Mac80211 uses the following numbers, which we get as from it
* by way of skb_get_queue_mapping(skb):
*
* VO 0
* VI 1
* BE 2
* BK 3
*
*
* Regular (not A-MPDU) frames are put into hardware queues corresponding
* to the FIFOs, see comments in iwl-prph.h. Aggregated frames get their
* own queue per aggregation session (RA/TID combination), such queues are
* set up to map into FIFOs too, for which we need an AC->FIFO mapping. In
* order to map frames to the right queue, we also need an AC->hw queue
* mapping. This is implemented here.
*
* Due to the way hw queues are set up (by the hw specific modules like
* 4965.c), the AC->hw queue mapping is the identity
* mapping.
*/
static const u8 tid_to_ac[] = {
IEEE80211_AC_BE,
IEEE80211_AC_BK,
IEEE80211_AC_BK,
IEEE80211_AC_BE,
IEEE80211_AC_VI,
IEEE80211_AC_VI,
IEEE80211_AC_VO,
IEEE80211_AC_VO
};
static inline int
il4965_get_ac_from_tid(u16 tid)
{
if (likely(tid < ARRAY_SIZE(tid_to_ac)))
return tid_to_ac[tid];
/* no support for TIDs 8-15 yet */
return -EINVAL;
}
static inline int
il4965_get_fifo_from_tid(u16 tid)
{
const u8 ac_to_fifo[] = {
IL_TX_FIFO_VO,
IL_TX_FIFO_VI,
IL_TX_FIFO_BE,
IL_TX_FIFO_BK,
};
if (likely(tid < ARRAY_SIZE(tid_to_ac)))
return ac_to_fifo[tid_to_ac[tid]];
/* no support for TIDs 8-15 yet */
return -EINVAL;
}
/*
* handle build C_TX command notification.
*/
static void
il4965_tx_cmd_build_basic(struct il_priv *il, struct sk_buff *skb,
struct il_tx_cmd *tx_cmd,
struct ieee80211_tx_info *info,
struct ieee80211_hdr *hdr, u8 std_id)
{
__le16 fc = hdr->frame_control;
__le32 tx_flags = tx_cmd->tx_flags;
tx_cmd->stop_time.life_time = TX_CMD_LIFE_TIME_INFINITE;
if (!(info->flags & IEEE80211_TX_CTL_NO_ACK)) {
tx_flags |= TX_CMD_FLG_ACK_MSK;
if (ieee80211_is_mgmt(fc))
tx_flags |= TX_CMD_FLG_SEQ_CTL_MSK;
if (ieee80211_is_probe_resp(fc) &&
!(le16_to_cpu(hdr->seq_ctrl) & 0xf))
tx_flags |= TX_CMD_FLG_TSF_MSK;
} else {
tx_flags &= (~TX_CMD_FLG_ACK_MSK);
tx_flags |= TX_CMD_FLG_SEQ_CTL_MSK;
}
if (ieee80211_is_back_req(fc))
tx_flags |= TX_CMD_FLG_ACK_MSK | TX_CMD_FLG_IMM_BA_RSP_MASK;
tx_cmd->sta_id = std_id;
if (ieee80211_has_morefrags(fc))
tx_flags |= TX_CMD_FLG_MORE_FRAG_MSK;
if (ieee80211_is_data_qos(fc)) {
u8 *qc = ieee80211_get_qos_ctl(hdr);
tx_cmd->tid_tspec = qc[0] & 0xf;
tx_flags &= ~TX_CMD_FLG_SEQ_CTL_MSK;
} else {
tx_flags |= TX_CMD_FLG_SEQ_CTL_MSK;
}
il_tx_cmd_protection(il, info, fc, &tx_flags);
tx_flags &= ~(TX_CMD_FLG_ANT_SEL_MSK);
if (ieee80211_is_mgmt(fc)) {
if (ieee80211_is_assoc_req(fc) || ieee80211_is_reassoc_req(fc))
tx_cmd->timeout.pm_frame_timeout = cpu_to_le16(3);
else
tx_cmd->timeout.pm_frame_timeout = cpu_to_le16(2);
} else {
tx_cmd->timeout.pm_frame_timeout = 0;
}
tx_cmd->driver_txop = 0;
tx_cmd->tx_flags = tx_flags;
tx_cmd->next_frame_len = 0;
}
static void
il4965_tx_cmd_build_rate(struct il_priv *il,
struct il_tx_cmd *tx_cmd,
struct ieee80211_tx_info *info,
struct ieee80211_sta *sta,
__le16 fc)
{
const u8 rts_retry_limit = 60;
u32 rate_flags;
int rate_idx;
u8 data_retry_limit;
u8 rate_plcp;
/* Set retry limit on DATA packets and Probe Responses */
if (ieee80211_is_probe_resp(fc))
data_retry_limit = 3;
else
data_retry_limit = IL4965_DEFAULT_TX_RETRY;
tx_cmd->data_retry_limit = data_retry_limit;
/* Set retry limit on RTS packets */
tx_cmd->rts_retry_limit = min(data_retry_limit, rts_retry_limit);
/* DATA packets will use the uCode station table for rate/antenna
* selection */
if (ieee80211_is_data(fc)) {
tx_cmd->initial_rate_idx = 0;
tx_cmd->tx_flags |= TX_CMD_FLG_STA_RATE_MSK;
return;
}
/**
* If the current TX rate stored in mac80211 has the MCS bit set, it's
* not really a TX rate. Thus, we use the lowest supported rate for
* this band. Also use the lowest supported rate if the stored rate
* idx is invalid.
*/
rate_idx = info->control.rates[0].idx;
if ((info->control.rates[0].flags & IEEE80211_TX_RC_MCS) || rate_idx < 0
|| rate_idx > RATE_COUNT_LEGACY)
rate_idx = rate_lowest_index(&il->bands[info->band], sta);
/* For 5 GHZ band, remap mac80211 rate indices into driver indices */
if (info->band == IEEE80211_BAND_5GHZ)
rate_idx += IL_FIRST_OFDM_RATE;
/* Get PLCP rate for tx_cmd->rate_n_flags */
rate_plcp = il_rates[rate_idx].plcp;
/* Zero out flags for this packet */
rate_flags = 0;
/* Set CCK flag as needed */
if (rate_idx >= IL_FIRST_CCK_RATE && rate_idx <= IL_LAST_CCK_RATE)
rate_flags |= RATE_MCS_CCK_MSK;
/* Set up antennas */
il4965_toggle_tx_ant(il, &il->mgmt_tx_ant, il->hw_params.valid_tx_ant);
rate_flags |= BIT(il->mgmt_tx_ant) << RATE_MCS_ANT_POS;
/* Set the rate in the TX cmd */
tx_cmd->rate_n_flags = cpu_to_le32(rate_plcp | rate_flags);
}
static void
il4965_tx_cmd_build_hwcrypto(struct il_priv *il, struct ieee80211_tx_info *info,
struct il_tx_cmd *tx_cmd, struct sk_buff *skb_frag,
int sta_id)
{
struct ieee80211_key_conf *keyconf = info->control.hw_key;
switch (keyconf->cipher) {
case WLAN_CIPHER_SUITE_CCMP:
tx_cmd->sec_ctl = TX_CMD_SEC_CCM;
memcpy(tx_cmd->key, keyconf->key, keyconf->keylen);
if (info->flags & IEEE80211_TX_CTL_AMPDU)
tx_cmd->tx_flags |= TX_CMD_FLG_AGG_CCMP_MSK;
D_TX("tx_cmd with AES hwcrypto\n");
break;
case WLAN_CIPHER_SUITE_TKIP:
tx_cmd->sec_ctl = TX_CMD_SEC_TKIP;
ieee80211_get_tkip_p2k(keyconf, skb_frag, tx_cmd->key);
D_TX("tx_cmd with tkip hwcrypto\n");
break;
case WLAN_CIPHER_SUITE_WEP104:
tx_cmd->sec_ctl |= TX_CMD_SEC_KEY128;
/* fall through */
case WLAN_CIPHER_SUITE_WEP40:
tx_cmd->sec_ctl |=
(TX_CMD_SEC_WEP | (keyconf->keyidx & TX_CMD_SEC_MSK) <<
TX_CMD_SEC_SHIFT);
memcpy(&tx_cmd->key[3], keyconf->key, keyconf->keylen);
D_TX("Configuring packet for WEP encryption " "with key %d\n",
keyconf->keyidx);
break;
default:
IL_ERR("Unknown encode cipher %x\n", keyconf->cipher);
break;
}
}
/*
* start C_TX command process
*/
int
il4965_tx_skb(struct il_priv *il,
struct ieee80211_sta *sta,
struct sk_buff *skb)
{
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
struct il_station_priv *sta_priv = NULL;
struct il_tx_queue *txq;
struct il_queue *q;
struct il_device_cmd *out_cmd;
struct il_cmd_meta *out_meta;
struct il_tx_cmd *tx_cmd;
int txq_id;
dma_addr_t phys_addr;
dma_addr_t txcmd_phys;
dma_addr_t scratch_phys;
u16 len, firstlen, secondlen;
u16 seq_number = 0;
__le16 fc;
u8 hdr_len;
u8 sta_id;
u8 wait_write_ptr = 0;
u8 tid = 0;
u8 *qc = NULL;
unsigned long flags;
bool is_agg = false;
spin_lock_irqsave(&il->lock, flags);
if (il_is_rfkill(il)) {
D_DROP("Dropping - RF KILL\n");
goto drop_unlock;
}
fc = hdr->frame_control;
#ifdef CONFIG_IWLEGACY_DEBUG
if (ieee80211_is_auth(fc))
D_TX("Sending AUTH frame\n");
else if (ieee80211_is_assoc_req(fc))
D_TX("Sending ASSOC frame\n");
else if (ieee80211_is_reassoc_req(fc))
D_TX("Sending REASSOC frame\n");
#endif
hdr_len = ieee80211_hdrlen(fc);
/* For management frames use broadcast id to do not break aggregation */
if (!ieee80211_is_data(fc))
sta_id = il->hw_params.bcast_id;
else {
/* Find idx into station table for destination station */
sta_id = il_sta_id_or_broadcast(il, sta);
if (sta_id == IL_INVALID_STATION) {
D_DROP("Dropping - INVALID STATION: %pM\n", hdr->addr1);
goto drop_unlock;
}
}
D_TX("station Id %d\n", sta_id);
if (sta)
sta_priv = (void *)sta->drv_priv;
if (sta_priv && sta_priv->asleep &&
(info->flags & IEEE80211_TX_CTL_NO_PS_BUFFER)) {
/*
* This sends an asynchronous command to the device,
* but we can rely on it being processed before the
* next frame is processed -- and the next frame to
* this station is the one that will consume this
* counter.
* For now set the counter to just 1 since we do not
* support uAPSD yet.
*/
il4965_sta_modify_sleep_tx_count(il, sta_id, 1);
}
/* FIXME: remove me ? */
WARN_ON_ONCE(info->flags & IEEE80211_TX_CTL_SEND_AFTER_DTIM);
/* Access category (AC) is also the queue number */
txq_id = skb_get_queue_mapping(skb);
/* irqs already disabled/saved above when locking il->lock */
spin_lock(&il->sta_lock);
if (ieee80211_is_data_qos(fc)) {
qc = ieee80211_get_qos_ctl(hdr);
tid = qc[0] & IEEE80211_QOS_CTL_TID_MASK;
if (WARN_ON_ONCE(tid >= MAX_TID_COUNT)) {
spin_unlock(&il->sta_lock);
goto drop_unlock;
}
seq_number = il->stations[sta_id].tid[tid].seq_number;
seq_number &= IEEE80211_SCTL_SEQ;
hdr->seq_ctrl =
hdr->seq_ctrl & cpu_to_le16(IEEE80211_SCTL_FRAG);
hdr->seq_ctrl |= cpu_to_le16(seq_number);
seq_number += 0x10;
/* aggregation is on for this <sta,tid> */
if (info->flags & IEEE80211_TX_CTL_AMPDU &&
il->stations[sta_id].tid[tid].agg.state == IL_AGG_ON) {
txq_id = il->stations[sta_id].tid[tid].agg.txq_id;
is_agg = true;
}
}
txq = &il->txq[txq_id];
q = &txq->q;
if (unlikely(il_queue_space(q) < q->high_mark)) {
spin_unlock(&il->sta_lock);
goto drop_unlock;
}
if (ieee80211_is_data_qos(fc)) {
il->stations[sta_id].tid[tid].tfds_in_queue++;
if (!ieee80211_has_morefrags(fc))
il->stations[sta_id].tid[tid].seq_number = seq_number;
}
spin_unlock(&il->sta_lock);
txq->skbs[q->write_ptr] = skb;
/* Set up first empty entry in queue's array of Tx/cmd buffers */
out_cmd = txq->cmd[q->write_ptr];
out_meta = &txq->meta[q->write_ptr];
tx_cmd = &out_cmd->cmd.tx;
memset(&out_cmd->hdr, 0, sizeof(out_cmd->hdr));
memset(tx_cmd, 0, sizeof(struct il_tx_cmd));
/*
* Set up the Tx-command (not MAC!) header.
* Store the chosen Tx queue and TFD idx within the sequence field;
* after Tx, uCode's Tx response will return this value so driver can
* locate the frame within the tx queue and do post-tx processing.
*/
out_cmd->hdr.cmd = C_TX;
out_cmd->hdr.sequence =
cpu_to_le16((u16)
(QUEUE_TO_SEQ(txq_id) | IDX_TO_SEQ(q->write_ptr)));
/* Copy MAC header from skb into command buffer */
memcpy(tx_cmd->hdr, hdr, hdr_len);
/* Total # bytes to be transmitted */
tx_cmd->len = cpu_to_le16((u16) skb->len);
if (info->control.hw_key)
il4965_tx_cmd_build_hwcrypto(il, info, tx_cmd, skb, sta_id);
/* TODO need this for burst mode later on */
il4965_tx_cmd_build_basic(il, skb, tx_cmd, info, hdr, sta_id);
il4965_tx_cmd_build_rate(il, tx_cmd, info, sta, fc);
/*
* Use the first empty entry in this queue's command buffer array
* to contain the Tx command and MAC header concatenated together
* (payload data will be in another buffer).
* Size of this varies, due to varying MAC header length.
* If end is not dword aligned, we'll have 2 extra bytes at the end
* of the MAC header (device reads on dword boundaries).
* We'll tell device about this padding later.
*/
len = sizeof(struct il_tx_cmd) + sizeof(struct il_cmd_header) + hdr_len;
firstlen = (len + 3) & ~3;
/* Tell NIC about any 2-byte padding after MAC header */
if (firstlen != len)
tx_cmd->tx_flags |= TX_CMD_FLG_MH_PAD_MSK;
/* Physical address of this Tx command's header (not MAC header!),
* within command buffer array. */
txcmd_phys =
pci_map_single(il->pci_dev, &out_cmd->hdr, firstlen,
PCI_DMA_BIDIRECTIONAL);
if (unlikely(pci_dma_mapping_error(il->pci_dev, txcmd_phys)))
goto drop_unlock;
/* Set up TFD's 2nd entry to point directly to remainder of skb,
* if any (802.11 null frames have no payload). */
secondlen = skb->len - hdr_len;
if (secondlen > 0) {
phys_addr =
pci_map_single(il->pci_dev, skb->data + hdr_len, secondlen,
PCI_DMA_TODEVICE);
if (unlikely(pci_dma_mapping_error(il->pci_dev, phys_addr)))
goto drop_unlock;
}
/* Add buffer containing Tx command and MAC(!) header to TFD's
* first entry */
il->ops->txq_attach_buf_to_tfd(il, txq, txcmd_phys, firstlen, 1, 0);
dma_unmap_addr_set(out_meta, mapping, txcmd_phys);
dma_unmap_len_set(out_meta, len, firstlen);
if (secondlen)
il->ops->txq_attach_buf_to_tfd(il, txq, phys_addr, secondlen,
0, 0);
if (!ieee80211_has_morefrags(hdr->frame_control)) {
txq->need_update = 1;
} else {
wait_write_ptr = 1;
txq->need_update = 0;
}
scratch_phys =
txcmd_phys + sizeof(struct il_cmd_header) +
offsetof(struct il_tx_cmd, scratch);
/* take back ownership of DMA buffer to enable update */
pci_dma_sync_single_for_cpu(il->pci_dev, txcmd_phys, firstlen,
PCI_DMA_BIDIRECTIONAL);
tx_cmd->dram_lsb_ptr = cpu_to_le32(scratch_phys);
tx_cmd->dram_msb_ptr = il_get_dma_hi_addr(scratch_phys);
il_update_stats(il, true, fc, skb->len);
D_TX("sequence nr = 0X%x\n", le16_to_cpu(out_cmd->hdr.sequence));
D_TX("tx_flags = 0X%x\n", le32_to_cpu(tx_cmd->tx_flags));
il_print_hex_dump(il, IL_DL_TX, (u8 *) tx_cmd, sizeof(*tx_cmd));
il_print_hex_dump(il, IL_DL_TX, (u8 *) tx_cmd->hdr, hdr_len);
/* Set up entry for this TFD in Tx byte-count array */
if (info->flags & IEEE80211_TX_CTL_AMPDU)
il->ops->txq_update_byte_cnt_tbl(il, txq, le16_to_cpu(tx_cmd->len));
pci_dma_sync_single_for_device(il->pci_dev, txcmd_phys, firstlen,
PCI_DMA_BIDIRECTIONAL);
/* Tell device the write idx *just past* this latest filled TFD */
q->write_ptr = il_queue_inc_wrap(q->write_ptr, q->n_bd);
il_txq_update_write_ptr(il, txq);
spin_unlock_irqrestore(&il->lock, flags);
/*
* At this point the frame is "transmitted" successfully
* and we will get a TX status notification eventually,
* regardless of the value of ret. "ret" only indicates
* whether or not we should update the write pointer.
*/
/*
* Avoid atomic ops if it isn't an associated client.
* Also, if this is a packet for aggregation, don't
* increase the counter because the ucode will stop
* aggregation queues when their respective station
* goes to sleep.
*/
if (sta_priv && sta_priv->client && !is_agg)
atomic_inc(&sta_priv->pending_frames);
if (il_queue_space(q) < q->high_mark && il->mac80211_registered) {
if (wait_write_ptr) {
spin_lock_irqsave(&il->lock, flags);
txq->need_update = 1;
il_txq_update_write_ptr(il, txq);
spin_unlock_irqrestore(&il->lock, flags);
} else {
il_stop_queue(il, txq);
}
}
return 0;
drop_unlock:
spin_unlock_irqrestore(&il->lock, flags);
return -1;
}
static inline int
il4965_alloc_dma_ptr(struct il_priv *il, struct il_dma_ptr *ptr, size_t size)
{
ptr->addr = dma_alloc_coherent(&il->pci_dev->dev, size, &ptr->dma,
GFP_KERNEL);
if (!ptr->addr)
return -ENOMEM;
ptr->size = size;
return 0;
}
static inline void
il4965_free_dma_ptr(struct il_priv *il, struct il_dma_ptr *ptr)
{
if (unlikely(!ptr->addr))
return;
dma_free_coherent(&il->pci_dev->dev, ptr->size, ptr->addr, ptr->dma);
memset(ptr, 0, sizeof(*ptr));
}
/**
* il4965_hw_txq_ctx_free - Free TXQ Context
*
* Destroy all TX DMA queues and structures
*/
void
il4965_hw_txq_ctx_free(struct il_priv *il)
{
int txq_id;
/* Tx queues */
if (il->txq) {
for (txq_id = 0; txq_id < il->hw_params.max_txq_num; txq_id++)
if (txq_id == il->cmd_queue)
il_cmd_queue_free(il);
else
il_tx_queue_free(il, txq_id);
}
il4965_free_dma_ptr(il, &il->kw);
il4965_free_dma_ptr(il, &il->scd_bc_tbls);
/* free tx queue structure */
il_free_txq_mem(il);
}
/**
* il4965_txq_ctx_alloc - allocate TX queue context
* Allocate all Tx DMA structures and initialize them
*
* @param il
* @return error code
*/
int
il4965_txq_ctx_alloc(struct il_priv *il)
{
int ret, txq_id;
unsigned long flags;
/* Free all tx/cmd queues and keep-warm buffer */
il4965_hw_txq_ctx_free(il);
ret =
il4965_alloc_dma_ptr(il, &il->scd_bc_tbls,
il->hw_params.scd_bc_tbls_size);
if (ret) {
IL_ERR("Scheduler BC Table allocation failed\n");
goto error_bc_tbls;
}
/* Alloc keep-warm buffer */
ret = il4965_alloc_dma_ptr(il, &il->kw, IL_KW_SIZE);
if (ret) {
IL_ERR("Keep Warm allocation failed\n");
goto error_kw;
}
/* allocate tx queue structure */
ret = il_alloc_txq_mem(il);
if (ret)
goto error;
spin_lock_irqsave(&il->lock, flags);
/* Turn off all Tx DMA fifos */
il4965_txq_set_sched(il, 0);
/* Tell NIC where to find the "keep warm" buffer */
il_wr(il, FH49_KW_MEM_ADDR_REG, il->kw.dma >> 4);
spin_unlock_irqrestore(&il->lock, flags);
/* Alloc and init all Tx queues, including the command queue (#4/#9) */
for (txq_id = 0; txq_id < il->hw_params.max_txq_num; txq_id++) {
ret = il_tx_queue_init(il, txq_id);
if (ret) {
IL_ERR("Tx %d queue init failed\n", txq_id);
goto error;
}
}
return ret;
error:
il4965_hw_txq_ctx_free(il);
il4965_free_dma_ptr(il, &il->kw);
error_kw:
il4965_free_dma_ptr(il, &il->scd_bc_tbls);
error_bc_tbls:
return ret;
}
void
il4965_txq_ctx_reset(struct il_priv *il)
{
int txq_id;
unsigned long flags;
spin_lock_irqsave(&il->lock, flags);
/* Turn off all Tx DMA fifos */
il4965_txq_set_sched(il, 0);
/* Tell NIC where to find the "keep warm" buffer */
il_wr(il, FH49_KW_MEM_ADDR_REG, il->kw.dma >> 4);
spin_unlock_irqrestore(&il->lock, flags);
/* Alloc and init all Tx queues, including the command queue (#4) */
for (txq_id = 0; txq_id < il->hw_params.max_txq_num; txq_id++)
il_tx_queue_reset(il, txq_id);
}
static void
il4965_txq_ctx_unmap(struct il_priv *il)
{
int txq_id;
if (!il->txq)
return;
/* Unmap DMA from host system and free skb's */
for (txq_id = 0; txq_id < il->hw_params.max_txq_num; txq_id++)
if (txq_id == il->cmd_queue)
il_cmd_queue_unmap(il);
else
il_tx_queue_unmap(il, txq_id);
}
/**
* il4965_txq_ctx_stop - Stop all Tx DMA channels
*/
void
il4965_txq_ctx_stop(struct il_priv *il)
{
int ch, ret;
_il_wr_prph(il, IL49_SCD_TXFACT, 0);
/* Stop each Tx DMA channel, and wait for it to be idle */
for (ch = 0; ch < il->hw_params.dma_chnl_num; ch++) {
_il_wr(il, FH49_TCSR_CHNL_TX_CONFIG_REG(ch), 0x0);
ret =
_il_poll_bit(il, FH49_TSSR_TX_STATUS_REG,
FH49_TSSR_TX_STATUS_REG_MSK_CHNL_IDLE(ch),
FH49_TSSR_TX_STATUS_REG_MSK_CHNL_IDLE(ch),
1000);
if (ret < 0)
IL_ERR("Timeout stopping DMA channel %d [0x%08x]",
ch, _il_rd(il, FH49_TSSR_TX_STATUS_REG));
}
}
/*
* Find first available (lowest unused) Tx Queue, mark it "active".
* Called only when finding queue for aggregation.
* Should never return anything < 7, because they should already
* be in use as EDCA AC (0-3), Command (4), reserved (5, 6)
*/
static int
il4965_txq_ctx_activate_free(struct il_priv *il)
{
int txq_id;
for (txq_id = 0; txq_id < il->hw_params.max_txq_num; txq_id++)
if (!test_and_set_bit(txq_id, &il->txq_ctx_active_msk))
return txq_id;
return -1;
}
/**
* il4965_tx_queue_stop_scheduler - Stop queue, but keep configuration
*/
static void
il4965_tx_queue_stop_scheduler(struct il_priv *il, u16 txq_id)
{
/* Simply stop the queue, but don't change any configuration;
* the SCD_ACT_EN bit is the write-enable mask for the ACTIVE bit. */
il_wr_prph(il, IL49_SCD_QUEUE_STATUS_BITS(txq_id),
(0 << IL49_SCD_QUEUE_STTS_REG_POS_ACTIVE) |
(1 << IL49_SCD_QUEUE_STTS_REG_POS_SCD_ACT_EN));
}
/**
* il4965_tx_queue_set_q2ratid - Map unique receiver/tid combination to a queue
*/
static int
il4965_tx_queue_set_q2ratid(struct il_priv *il, u16 ra_tid, u16 txq_id)
{
u32 tbl_dw_addr;
u32 tbl_dw;
u16 scd_q2ratid;
scd_q2ratid = ra_tid & IL_SCD_QUEUE_RA_TID_MAP_RATID_MSK;
tbl_dw_addr =
il->scd_base_addr + IL49_SCD_TRANSLATE_TBL_OFFSET_QUEUE(txq_id);
tbl_dw = il_read_targ_mem(il, tbl_dw_addr);
if (txq_id & 0x1)
tbl_dw = (scd_q2ratid << 16) | (tbl_dw & 0x0000FFFF);
else
tbl_dw = scd_q2ratid | (tbl_dw & 0xFFFF0000);
il_write_targ_mem(il, tbl_dw_addr, tbl_dw);
return 0;
}
/**
* il4965_tx_queue_agg_enable - Set up & enable aggregation for selected queue
*
* NOTE: txq_id must be greater than IL49_FIRST_AMPDU_QUEUE,
* i.e. it must be one of the higher queues used for aggregation
*/
static int
il4965_txq_agg_enable(struct il_priv *il, int txq_id, int tx_fifo, int sta_id,
int tid, u16 ssn_idx)
{
unsigned long flags;
u16 ra_tid;
int ret;
if ((IL49_FIRST_AMPDU_QUEUE > txq_id) ||
(IL49_FIRST_AMPDU_QUEUE +
il->cfg->num_of_ampdu_queues <= txq_id)) {
IL_WARN("queue number out of range: %d, must be %d to %d\n",
txq_id, IL49_FIRST_AMPDU_QUEUE,
IL49_FIRST_AMPDU_QUEUE +
il->cfg->num_of_ampdu_queues - 1);
return -EINVAL;
}
ra_tid = BUILD_RAxTID(sta_id, tid);
/* Modify device's station table to Tx this TID */
ret = il4965_sta_tx_modify_enable_tid(il, sta_id, tid);
if (ret)
return ret;
spin_lock_irqsave(&il->lock, flags);
/* Stop this Tx queue before configuring it */
il4965_tx_queue_stop_scheduler(il, txq_id);
/* Map receiver-address / traffic-ID to this queue */
il4965_tx_queue_set_q2ratid(il, ra_tid, txq_id);
/* Set this queue as a chain-building queue */
il_set_bits_prph(il, IL49_SCD_QUEUECHAIN_SEL, (1 << txq_id));
/* Place first TFD at idx corresponding to start sequence number.
* Assumes that ssn_idx is valid (!= 0xFFF) */
il->txq[txq_id].q.read_ptr = (ssn_idx & 0xff);
il->txq[txq_id].q.write_ptr = (ssn_idx & 0xff);
il4965_set_wr_ptrs(il, txq_id, ssn_idx);
/* Set up Tx win size and frame limit for this queue */
il_write_targ_mem(il,
il->scd_base_addr +
IL49_SCD_CONTEXT_QUEUE_OFFSET(txq_id),
(SCD_WIN_SIZE << IL49_SCD_QUEUE_CTX_REG1_WIN_SIZE_POS)
& IL49_SCD_QUEUE_CTX_REG1_WIN_SIZE_MSK);
il_write_targ_mem(il,
il->scd_base_addr +
IL49_SCD_CONTEXT_QUEUE_OFFSET(txq_id) + sizeof(u32),
(SCD_FRAME_LIMIT <<
IL49_SCD_QUEUE_CTX_REG2_FRAME_LIMIT_POS) &
IL49_SCD_QUEUE_CTX_REG2_FRAME_LIMIT_MSK);
il_set_bits_prph(il, IL49_SCD_INTERRUPT_MASK, (1 << txq_id));
/* Set up Status area in SRAM, map to Tx DMA/FIFO, activate the queue */
il4965_tx_queue_set_status(il, &il->txq[txq_id], tx_fifo, 1);
spin_unlock_irqrestore(&il->lock, flags);
return 0;
}
int
il4965_tx_agg_start(struct il_priv *il, struct ieee80211_vif *vif,
struct ieee80211_sta *sta, u16 tid, u16 * ssn)
{
int sta_id;
int tx_fifo;
int txq_id;
int ret;
unsigned long flags;
struct il_tid_data *tid_data;
/* FIXME: warning if tx fifo not found ? */
tx_fifo = il4965_get_fifo_from_tid(tid);
if (unlikely(tx_fifo < 0))
return tx_fifo;
D_HT("%s on ra = %pM tid = %d\n", __func__, sta->addr, tid);
sta_id = il_sta_id(sta);
if (sta_id == IL_INVALID_STATION) {
IL_ERR("Start AGG on invalid station\n");
return -ENXIO;
}
if (unlikely(tid >= MAX_TID_COUNT))
return -EINVAL;
if (il->stations[sta_id].tid[tid].agg.state != IL_AGG_OFF) {
IL_ERR("Start AGG when state is not IL_AGG_OFF !\n");
return -ENXIO;
}
txq_id = il4965_txq_ctx_activate_free(il);
if (txq_id == -1) {
IL_ERR("No free aggregation queue available\n");
return -ENXIO;
}
spin_lock_irqsave(&il->sta_lock, flags);
tid_data = &il->stations[sta_id].tid[tid];
*ssn = IEEE80211_SEQ_TO_SN(tid_data->seq_number);
tid_data->agg.txq_id = txq_id;
il_set_swq_id(&il->txq[txq_id], il4965_get_ac_from_tid(tid), txq_id);
spin_unlock_irqrestore(&il->sta_lock, flags);
ret = il4965_txq_agg_enable(il, txq_id, tx_fifo, sta_id, tid, *ssn);
if (ret)
return ret;
spin_lock_irqsave(&il->sta_lock, flags);
tid_data = &il->stations[sta_id].tid[tid];
if (tid_data->tfds_in_queue == 0) {
D_HT("HW queue is empty\n");
tid_data->agg.state = IL_AGG_ON;
ieee80211_start_tx_ba_cb_irqsafe(vif, sta->addr, tid);
} else {
D_HT("HW queue is NOT empty: %d packets in HW queue\n",
tid_data->tfds_in_queue);
tid_data->agg.state = IL_EMPTYING_HW_QUEUE_ADDBA;
}
spin_unlock_irqrestore(&il->sta_lock, flags);
return ret;
}
/**
* txq_id must be greater than IL49_FIRST_AMPDU_QUEUE
* il->lock must be held by the caller
*/
static int
il4965_txq_agg_disable(struct il_priv *il, u16 txq_id, u16 ssn_idx, u8 tx_fifo)
{
if ((IL49_FIRST_AMPDU_QUEUE > txq_id) ||
(IL49_FIRST_AMPDU_QUEUE +
il->cfg->num_of_ampdu_queues <= txq_id)) {
IL_WARN("queue number out of range: %d, must be %d to %d\n",
txq_id, IL49_FIRST_AMPDU_QUEUE,
IL49_FIRST_AMPDU_QUEUE +
il->cfg->num_of_ampdu_queues - 1);
return -EINVAL;
}
il4965_tx_queue_stop_scheduler(il, txq_id);
il_clear_bits_prph(il, IL49_SCD_QUEUECHAIN_SEL, (1 << txq_id));
il->txq[txq_id].q.read_ptr = (ssn_idx & 0xff);
il->txq[txq_id].q.write_ptr = (ssn_idx & 0xff);
/* supposes that ssn_idx is valid (!= 0xFFF) */
il4965_set_wr_ptrs(il, txq_id, ssn_idx);
il_clear_bits_prph(il, IL49_SCD_INTERRUPT_MASK, (1 << txq_id));
il_txq_ctx_deactivate(il, txq_id);
il4965_tx_queue_set_status(il, &il->txq[txq_id], tx_fifo, 0);
return 0;
}
int
il4965_tx_agg_stop(struct il_priv *il, struct ieee80211_vif *vif,
struct ieee80211_sta *sta, u16 tid)
{
int tx_fifo_id, txq_id, sta_id, ssn;
struct il_tid_data *tid_data;
int write_ptr, read_ptr;
unsigned long flags;
/* FIXME: warning if tx_fifo_id not found ? */
tx_fifo_id = il4965_get_fifo_from_tid(tid);
if (unlikely(tx_fifo_id < 0))
return tx_fifo_id;
sta_id = il_sta_id(sta);
if (sta_id == IL_INVALID_STATION) {
IL_ERR("Invalid station for AGG tid %d\n", tid);
return -ENXIO;
}
spin_lock_irqsave(&il->sta_lock, flags);
tid_data = &il->stations[sta_id].tid[tid];
ssn = (tid_data->seq_number & IEEE80211_SCTL_SEQ) >> 4;
txq_id = tid_data->agg.txq_id;
switch (il->stations[sta_id].tid[tid].agg.state) {
case IL_EMPTYING_HW_QUEUE_ADDBA:
/*
* This can happen if the peer stops aggregation
* again before we've had a chance to drain the
* queue we selected previously, i.e. before the
* session was really started completely.
*/
D_HT("AGG stop before setup done\n");
goto turn_off;
case IL_AGG_ON:
break;
default:
IL_WARN("Stopping AGG while state not ON or starting\n");
}
write_ptr = il->txq[txq_id].q.write_ptr;
read_ptr = il->txq[txq_id].q.read_ptr;
/* The queue is not empty */
if (write_ptr != read_ptr) {
D_HT("Stopping a non empty AGG HW QUEUE\n");
il->stations[sta_id].tid[tid].agg.state =
IL_EMPTYING_HW_QUEUE_DELBA;
spin_unlock_irqrestore(&il->sta_lock, flags);
return 0;
}
D_HT("HW queue is empty\n");
turn_off:
il->stations[sta_id].tid[tid].agg.state = IL_AGG_OFF;
/* do not restore/save irqs */
spin_unlock(&il->sta_lock);
spin_lock(&il->lock);
/*
* the only reason this call can fail is queue number out of range,
* which can happen if uCode is reloaded and all the station
* information are lost. if it is outside the range, there is no need
* to deactivate the uCode queue, just return "success" to allow
* mac80211 to clean up it own data.
*/
il4965_txq_agg_disable(il, txq_id, ssn, tx_fifo_id);
spin_unlock_irqrestore(&il->lock, flags);
ieee80211_stop_tx_ba_cb_irqsafe(vif, sta->addr, tid);
return 0;
}
int
il4965_txq_check_empty(struct il_priv *il, int sta_id, u8 tid, int txq_id)
{
struct il_queue *q = &il->txq[txq_id].q;
u8 *addr = il->stations[sta_id].sta.sta.addr;
struct il_tid_data *tid_data = &il->stations[sta_id].tid[tid];
lockdep_assert_held(&il->sta_lock);
switch (il->stations[sta_id].tid[tid].agg.state) {
case IL_EMPTYING_HW_QUEUE_DELBA:
/* We are reclaiming the last packet of the */
/* aggregated HW queue */
if (txq_id == tid_data->agg.txq_id &&
q->read_ptr == q->write_ptr) {
u16 ssn = IEEE80211_SEQ_TO_SN(tid_data->seq_number);
int tx_fifo = il4965_get_fifo_from_tid(tid);
D_HT("HW queue empty: continue DELBA flow\n");
il4965_txq_agg_disable(il, txq_id, ssn, tx_fifo);
tid_data->agg.state = IL_AGG_OFF;
ieee80211_stop_tx_ba_cb_irqsafe(il->vif, addr, tid);
}
break;
case IL_EMPTYING_HW_QUEUE_ADDBA:
/* We are reclaiming the last packet of the queue */
if (tid_data->tfds_in_queue == 0) {
D_HT("HW queue empty: continue ADDBA flow\n");
tid_data->agg.state = IL_AGG_ON;
ieee80211_start_tx_ba_cb_irqsafe(il->vif, addr, tid);
}
break;
}
return 0;
}
static void
il4965_non_agg_tx_status(struct il_priv *il, const u8 *addr1)
{
struct ieee80211_sta *sta;
struct il_station_priv *sta_priv;
rcu_read_lock();
sta = ieee80211_find_sta(il->vif, addr1);
if (sta) {
sta_priv = (void *)sta->drv_priv;
/* avoid atomic ops if this isn't a client */
if (sta_priv->client &&
atomic_dec_return(&sta_priv->pending_frames) == 0)
ieee80211_sta_block_awake(il->hw, sta, false);
}
rcu_read_unlock();
}
static void
il4965_tx_status(struct il_priv *il, struct sk_buff *skb, bool is_agg)
{
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
if (!is_agg)
il4965_non_agg_tx_status(il, hdr->addr1);
ieee80211_tx_status_irqsafe(il->hw, skb);
}
int
il4965_tx_queue_reclaim(struct il_priv *il, int txq_id, int idx)
{
struct il_tx_queue *txq = &il->txq[txq_id];
struct il_queue *q = &txq->q;
int nfreed = 0;
struct ieee80211_hdr *hdr;
struct sk_buff *skb;
if (idx >= q->n_bd || il_queue_used(q, idx) == 0) {
IL_ERR("Read idx for DMA queue txq id (%d), idx %d, "
"is out of range [0-%d] %d %d.\n", txq_id, idx, q->n_bd,
q->write_ptr, q->read_ptr);
return 0;
}
for (idx = il_queue_inc_wrap(idx, q->n_bd); q->read_ptr != idx;
q->read_ptr = il_queue_inc_wrap(q->read_ptr, q->n_bd)) {
skb = txq->skbs[txq->q.read_ptr];
if (WARN_ON_ONCE(skb == NULL))
continue;
hdr = (struct ieee80211_hdr *) skb->data;
if (ieee80211_is_data_qos(hdr->frame_control))
nfreed++;
il4965_tx_status(il, skb, txq_id >= IL4965_FIRST_AMPDU_QUEUE);
txq->skbs[txq->q.read_ptr] = NULL;
il->ops->txq_free_tfd(il, txq);
}
return nfreed;
}
/**
* il4965_tx_status_reply_compressed_ba - Update tx status from block-ack
*
* Go through block-ack's bitmap of ACK'd frames, update driver's record of
* ACK vs. not. This gets sent to mac80211, then to rate scaling algo.
*/
static int
il4965_tx_status_reply_compressed_ba(struct il_priv *il, struct il_ht_agg *agg,
struct il_compressed_ba_resp *ba_resp)
{
int i, sh, ack;
u16 seq_ctl = le16_to_cpu(ba_resp->seq_ctl);
u16 scd_flow = le16_to_cpu(ba_resp->scd_flow);
int successes = 0;
struct ieee80211_tx_info *info;
u64 bitmap, sent_bitmap;
if (unlikely(!agg->wait_for_ba)) {
if (unlikely(ba_resp->bitmap))
IL_ERR("Received BA when not expected\n");
return -EINVAL;
}
/* Mark that the expected block-ack response arrived */
agg->wait_for_ba = 0;
D_TX_REPLY("BA %d %d\n", agg->start_idx, ba_resp->seq_ctl);
/* Calculate shift to align block-ack bits with our Tx win bits */
sh = agg->start_idx - SEQ_TO_IDX(seq_ctl >> 4);
if (sh < 0) /* tbw something is wrong with indices */
sh += 0x100;
if (agg->frame_count > (64 - sh)) {
D_TX_REPLY("more frames than bitmap size");
return -1;
}
/* don't use 64-bit values for now */
bitmap = le64_to_cpu(ba_resp->bitmap) >> sh;
/* check for success or failure according to the
* transmitted bitmap and block-ack bitmap */
sent_bitmap = bitmap & agg->bitmap;
/* For each frame attempted in aggregation,
* update driver's record of tx frame's status. */
i = 0;
while (sent_bitmap) {
ack = sent_bitmap & 1ULL;
successes += ack;
D_TX_REPLY("%s ON i=%d idx=%d raw=%d\n", ack ? "ACK" : "NACK",
i, (agg->start_idx + i) & 0xff, agg->start_idx + i);
sent_bitmap >>= 1;
++i;
}
D_TX_REPLY("Bitmap %llx\n", (unsigned long long)bitmap);
info = IEEE80211_SKB_CB(il->txq[scd_flow].skbs[agg->start_idx]);
memset(&info->status, 0, sizeof(info->status));
info->flags |= IEEE80211_TX_STAT_ACK;
info->flags |= IEEE80211_TX_STAT_AMPDU;
info->status.ampdu_ack_len = successes;
info->status.ampdu_len = agg->frame_count;
il4965_hwrate_to_tx_control(il, agg->rate_n_flags, info);
return 0;
}
static inline bool
il4965_is_tx_success(u32 status)
{
status &= TX_STATUS_MSK;
return (status == TX_STATUS_SUCCESS || status == TX_STATUS_DIRECT_DONE);
}
static u8
il4965_find_station(struct il_priv *il, const u8 *addr)
{
int i;
int start = 0;
int ret = IL_INVALID_STATION;
unsigned long flags;
if (il->iw_mode == NL80211_IFTYPE_ADHOC)
start = IL_STA_ID;
if (is_broadcast_ether_addr(addr))
return il->hw_params.bcast_id;
spin_lock_irqsave(&il->sta_lock, flags);
for (i = start; i < il->hw_params.max_stations; i++)
if (il->stations[i].used &&
ether_addr_equal(il->stations[i].sta.sta.addr, addr)) {
ret = i;
goto out;
}
D_ASSOC("can not find STA %pM total %d\n", addr, il->num_stations);
out:
/*
* It may be possible that more commands interacting with stations
* arrive before we completed processing the adding of
* station
*/
if (ret != IL_INVALID_STATION &&
(!(il->stations[ret].used & IL_STA_UCODE_ACTIVE) ||
((il->stations[ret].used & IL_STA_UCODE_ACTIVE) &&
(il->stations[ret].used & IL_STA_UCODE_INPROGRESS)))) {
IL_ERR("Requested station info for sta %d before ready.\n",
ret);
ret = IL_INVALID_STATION;
}
spin_unlock_irqrestore(&il->sta_lock, flags);
return ret;
}
static int
il4965_get_ra_sta_id(struct il_priv *il, struct ieee80211_hdr *hdr)
{
if (il->iw_mode == NL80211_IFTYPE_STATION)
return IL_AP_ID;
else {
u8 *da = ieee80211_get_DA(hdr);
return il4965_find_station(il, da);
}
}
static inline u32
il4965_get_scd_ssn(struct il4965_tx_resp *tx_resp)
{
return le32_to_cpup(&tx_resp->u.status +
tx_resp->frame_count) & IEEE80211_MAX_SN;
}
static inline u32
il4965_tx_status_to_mac80211(u32 status)
{
status &= TX_STATUS_MSK;
switch (status) {
case TX_STATUS_SUCCESS:
case TX_STATUS_DIRECT_DONE:
return IEEE80211_TX_STAT_ACK;
case TX_STATUS_FAIL_DEST_PS:
return IEEE80211_TX_STAT_TX_FILTERED;
default:
return 0;
}
}
/**
* il4965_tx_status_reply_tx - Handle Tx response for frames in aggregation queue
*/
static int
il4965_tx_status_reply_tx(struct il_priv *il, struct il_ht_agg *agg,
struct il4965_tx_resp *tx_resp, int txq_id,
u16 start_idx)
{
u16 status;
struct agg_tx_status *frame_status = tx_resp->u.agg_status;
struct ieee80211_tx_info *info = NULL;
struct ieee80211_hdr *hdr = NULL;
u32 rate_n_flags = le32_to_cpu(tx_resp->rate_n_flags);
int i, sh, idx;
u16 seq;
if (agg->wait_for_ba)
D_TX_REPLY("got tx response w/o block-ack\n");
agg->frame_count = tx_resp->frame_count;
agg->start_idx = start_idx;
agg->rate_n_flags = rate_n_flags;
agg->bitmap = 0;
/* num frames attempted by Tx command */
if (agg->frame_count == 1) {
/* Only one frame was attempted; no block-ack will arrive */
status = le16_to_cpu(frame_status[0].status);
idx = start_idx;
D_TX_REPLY("FrameCnt = %d, StartIdx=%d idx=%d\n",
agg->frame_count, agg->start_idx, idx);
info = IEEE80211_SKB_CB(il->txq[txq_id].skbs[idx]);
info->status.rates[0].count = tx_resp->failure_frame + 1;
info->flags &= ~IEEE80211_TX_CTL_AMPDU;
info->flags |= il4965_tx_status_to_mac80211(status);
il4965_hwrate_to_tx_control(il, rate_n_flags, info);
D_TX_REPLY("1 Frame 0x%x failure :%d\n", status & 0xff,
tx_resp->failure_frame);
D_TX_REPLY("Rate Info rate_n_flags=%x\n", rate_n_flags);
agg->wait_for_ba = 0;
} else {
/* Two or more frames were attempted; expect block-ack */
u64 bitmap = 0;
int start = agg->start_idx;
struct sk_buff *skb;
/* Construct bit-map of pending frames within Tx win */
for (i = 0; i < agg->frame_count; i++) {
u16 sc;
status = le16_to_cpu(frame_status[i].status);
seq = le16_to_cpu(frame_status[i].sequence);
idx = SEQ_TO_IDX(seq);
txq_id = SEQ_TO_QUEUE(seq);
if (status &
(AGG_TX_STATE_FEW_BYTES_MSK |
AGG_TX_STATE_ABORT_MSK))
continue;
D_TX_REPLY("FrameCnt = %d, txq_id=%d idx=%d\n",
agg->frame_count, txq_id, idx);
skb = il->txq[txq_id].skbs[idx];
if (WARN_ON_ONCE(skb == NULL))
return -1;
hdr = (struct ieee80211_hdr *) skb->data;
sc = le16_to_cpu(hdr->seq_ctrl);
if (idx != (IEEE80211_SEQ_TO_SN(sc) & 0xff)) {
IL_ERR("BUG_ON idx doesn't match seq control"
" idx=%d, seq_idx=%d, seq=%d\n", idx,
IEEE80211_SEQ_TO_SN(sc), hdr->seq_ctrl);
return -1;
}
D_TX_REPLY("AGG Frame i=%d idx %d seq=%d\n", i, idx,
IEEE80211_SEQ_TO_SN(sc));
sh = idx - start;
if (sh > 64) {
sh = (start - idx) + 0xff;
bitmap = bitmap << sh;
sh = 0;
start = idx;
} else if (sh < -64)
sh = 0xff - (start - idx);
else if (sh < 0) {
sh = start - idx;
start = idx;
bitmap = bitmap << sh;
sh = 0;
}
bitmap |= 1ULL << sh;
D_TX_REPLY("start=%d bitmap=0x%llx\n", start,
(unsigned long long)bitmap);
}
agg->bitmap = bitmap;
agg->start_idx = start;
D_TX_REPLY("Frames %d start_idx=%d bitmap=0x%llx\n",
agg->frame_count, agg->start_idx,
(unsigned long long)agg->bitmap);
if (bitmap)
agg->wait_for_ba = 1;
}
return 0;
}
/**
* il4965_hdl_tx - Handle standard (non-aggregation) Tx response
*/
static void
il4965_hdl_tx(struct il_priv *il, struct il_rx_buf *rxb)
{
struct il_rx_pkt *pkt = rxb_addr(rxb);
u16 sequence = le16_to_cpu(pkt->hdr.sequence);
int txq_id = SEQ_TO_QUEUE(sequence);
int idx = SEQ_TO_IDX(sequence);
struct il_tx_queue *txq = &il->txq[txq_id];
struct sk_buff *skb;
struct ieee80211_hdr *hdr;
struct ieee80211_tx_info *info;
struct il4965_tx_resp *tx_resp = (void *)&pkt->u.raw[0];
u32 status = le32_to_cpu(tx_resp->u.status);
int uninitialized_var(tid);
int sta_id;
int freed;
u8 *qc = NULL;
unsigned long flags;
if (idx >= txq->q.n_bd || il_queue_used(&txq->q, idx) == 0) {
IL_ERR("Read idx for DMA queue txq_id (%d) idx %d "
"is out of range [0-%d] %d %d\n", txq_id, idx,
txq->q.n_bd, txq->q.write_ptr, txq->q.read_ptr);
return;
}
txq->time_stamp = jiffies;
skb = txq->skbs[txq->q.read_ptr];
info = IEEE80211_SKB_CB(skb);
memset(&info->status, 0, sizeof(info->status));
hdr = (struct ieee80211_hdr *) skb->data;
if (ieee80211_is_data_qos(hdr->frame_control)) {
qc = ieee80211_get_qos_ctl(hdr);
tid = qc[0] & 0xf;
}
sta_id = il4965_get_ra_sta_id(il, hdr);
if (txq->sched_retry && unlikely(sta_id == IL_INVALID_STATION)) {
IL_ERR("Station not known\n");
return;
}
/*
* Firmware will not transmit frame on passive channel, if it not yet
* received some valid frame on that channel. When this error happen
* we have to wait until firmware will unblock itself i.e. when we
* note received beacon or other frame. We unblock queues in
* il4965_pass_packet_to_mac80211 or in il_mac_bss_info_changed.
*/
if (unlikely((status & TX_STATUS_MSK) == TX_STATUS_FAIL_PASSIVE_NO_RX) &&
il->iw_mode == NL80211_IFTYPE_STATION) {
il_stop_queues_by_reason(il, IL_STOP_REASON_PASSIVE);
D_INFO("Stopped queues - RX waiting on passive channel\n");
}
spin_lock_irqsave(&il->sta_lock, flags);
if (txq->sched_retry) {
const u32 scd_ssn = il4965_get_scd_ssn(tx_resp);
struct il_ht_agg *agg = NULL;
WARN_ON(!qc);
agg = &il->stations[sta_id].tid[tid].agg;
il4965_tx_status_reply_tx(il, agg, tx_resp, txq_id, idx);
/* check if BAR is needed */
if (tx_resp->frame_count == 1 &&
!il4965_is_tx_success(status))
info->flags |= IEEE80211_TX_STAT_AMPDU_NO_BACK;
if (txq->q.read_ptr != (scd_ssn & 0xff)) {
idx = il_queue_dec_wrap(scd_ssn & 0xff, txq->q.n_bd);
D_TX_REPLY("Retry scheduler reclaim scd_ssn "
"%d idx %d\n", scd_ssn, idx);
freed = il4965_tx_queue_reclaim(il, txq_id, idx);
if (qc)
il4965_free_tfds_in_queue(il, sta_id, tid,
freed);
if (il->mac80211_registered &&
il_queue_space(&txq->q) > txq->q.low_mark &&
agg->state != IL_EMPTYING_HW_QUEUE_DELBA)
il_wake_queue(il, txq);
}
} else {
info->status.rates[0].count = tx_resp->failure_frame + 1;
info->flags |= il4965_tx_status_to_mac80211(status);
il4965_hwrate_to_tx_control(il,
le32_to_cpu(tx_resp->rate_n_flags),
info);
D_TX_REPLY("TXQ %d status %s (0x%08x) "
"rate_n_flags 0x%x retries %d\n", txq_id,
il4965_get_tx_fail_reason(status), status,
le32_to_cpu(tx_resp->rate_n_flags),
tx_resp->failure_frame);
freed = il4965_tx_queue_reclaim(il, txq_id, idx);
if (qc && likely(sta_id != IL_INVALID_STATION))
il4965_free_tfds_in_queue(il, sta_id, tid, freed);
else if (sta_id == IL_INVALID_STATION)
D_TX_REPLY("Station not known\n");
if (il->mac80211_registered &&
il_queue_space(&txq->q) > txq->q.low_mark)
il_wake_queue(il, txq);
}
if (qc && likely(sta_id != IL_INVALID_STATION))
il4965_txq_check_empty(il, sta_id, tid, txq_id);
il4965_check_abort_status(il, tx_resp->frame_count, status);
spin_unlock_irqrestore(&il->sta_lock, flags);
}
/**
* translate ucode response to mac80211 tx status control values
*/
void
il4965_hwrate_to_tx_control(struct il_priv *il, u32 rate_n_flags,
struct ieee80211_tx_info *info)
{
struct ieee80211_tx_rate *r = &info->status.rates[0];
info->status.antenna =
((rate_n_flags & RATE_MCS_ANT_ABC_MSK) >> RATE_MCS_ANT_POS);
if (rate_n_flags & RATE_MCS_HT_MSK)
r->flags |= IEEE80211_TX_RC_MCS;
if (rate_n_flags & RATE_MCS_GF_MSK)
r->flags |= IEEE80211_TX_RC_GREEN_FIELD;
if (rate_n_flags & RATE_MCS_HT40_MSK)
r->flags |= IEEE80211_TX_RC_40_MHZ_WIDTH;
if (rate_n_flags & RATE_MCS_DUP_MSK)
r->flags |= IEEE80211_TX_RC_DUP_DATA;
if (rate_n_flags & RATE_MCS_SGI_MSK)
r->flags |= IEEE80211_TX_RC_SHORT_GI;
r->idx = il4965_hwrate_to_mac80211_idx(rate_n_flags, info->band);
}
/**
* il4965_hdl_compressed_ba - Handler for N_COMPRESSED_BA
*
* Handles block-acknowledge notification from device, which reports success
* of frames sent via aggregation.
*/
static void
il4965_hdl_compressed_ba(struct il_priv *il, struct il_rx_buf *rxb)
{
struct il_rx_pkt *pkt = rxb_addr(rxb);
struct il_compressed_ba_resp *ba_resp = &pkt->u.compressed_ba;
struct il_tx_queue *txq = NULL;
struct il_ht_agg *agg;
int idx;
int sta_id;
int tid;
unsigned long flags;
/* "flow" corresponds to Tx queue */
u16 scd_flow = le16_to_cpu(ba_resp->scd_flow);
/* "ssn" is start of block-ack Tx win, corresponds to idx
* (in Tx queue's circular buffer) of first TFD/frame in win */
u16 ba_resp_scd_ssn = le16_to_cpu(ba_resp->scd_ssn);
if (scd_flow >= il->hw_params.max_txq_num) {
IL_ERR("BUG_ON scd_flow is bigger than number of queues\n");
return;
}
txq = &il->txq[scd_flow];
sta_id = ba_resp->sta_id;
tid = ba_resp->tid;
agg = &il->stations[sta_id].tid[tid].agg;
if (unlikely(agg->txq_id != scd_flow)) {
/*
* FIXME: this is a uCode bug which need to be addressed,
* log the information and return for now!
* since it is possible happen very often and in order
* not to fill the syslog, don't enable the logging by default
*/
D_TX_REPLY("BA scd_flow %d does not match txq_id %d\n",
scd_flow, agg->txq_id);
return;
}
/* Find idx just before block-ack win */
idx = il_queue_dec_wrap(ba_resp_scd_ssn & 0xff, txq->q.n_bd);
spin_lock_irqsave(&il->sta_lock, flags);
D_TX_REPLY("N_COMPRESSED_BA [%d] Received from %pM, " "sta_id = %d\n",
agg->wait_for_ba, (u8 *) &ba_resp->sta_addr_lo32,
ba_resp->sta_id);
D_TX_REPLY("TID = %d, SeqCtl = %d, bitmap = 0x%llx," "scd_flow = "
"%d, scd_ssn = %d\n", ba_resp->tid, ba_resp->seq_ctl,
(unsigned long long)le64_to_cpu(ba_resp->bitmap),
ba_resp->scd_flow, ba_resp->scd_ssn);
D_TX_REPLY("DAT start_idx = %d, bitmap = 0x%llx\n", agg->start_idx,
(unsigned long long)agg->bitmap);
/* Update driver's record of ACK vs. not for each frame in win */
il4965_tx_status_reply_compressed_ba(il, agg, ba_resp);
/* Release all TFDs before the SSN, i.e. all TFDs in front of
* block-ack win (we assume that they've been successfully
* transmitted ... if not, it's too late anyway). */
if (txq->q.read_ptr != (ba_resp_scd_ssn & 0xff)) {
/* calculate mac80211 ampdu sw queue to wake */
int freed = il4965_tx_queue_reclaim(il, scd_flow, idx);
il4965_free_tfds_in_queue(il, sta_id, tid, freed);
if (il_queue_space(&txq->q) > txq->q.low_mark &&
il->mac80211_registered &&
agg->state != IL_EMPTYING_HW_QUEUE_DELBA)
il_wake_queue(il, txq);
il4965_txq_check_empty(il, sta_id, tid, scd_flow);
}
spin_unlock_irqrestore(&il->sta_lock, flags);
}
#ifdef CONFIG_IWLEGACY_DEBUG
const char *
il4965_get_tx_fail_reason(u32 status)
{
#define TX_STATUS_FAIL(x) case TX_STATUS_FAIL_ ## x: return #x
#define TX_STATUS_POSTPONE(x) case TX_STATUS_POSTPONE_ ## x: return #x
switch (status & TX_STATUS_MSK) {
case TX_STATUS_SUCCESS:
return "SUCCESS";
TX_STATUS_POSTPONE(DELAY);
TX_STATUS_POSTPONE(FEW_BYTES);
TX_STATUS_POSTPONE(QUIET_PERIOD);
TX_STATUS_POSTPONE(CALC_TTAK);
TX_STATUS_FAIL(INTERNAL_CROSSED_RETRY);
TX_STATUS_FAIL(SHORT_LIMIT);
TX_STATUS_FAIL(LONG_LIMIT);
TX_STATUS_FAIL(FIFO_UNDERRUN);
TX_STATUS_FAIL(DRAIN_FLOW);
TX_STATUS_FAIL(RFKILL_FLUSH);
TX_STATUS_FAIL(LIFE_EXPIRE);
TX_STATUS_FAIL(DEST_PS);
TX_STATUS_FAIL(HOST_ABORTED);
TX_STATUS_FAIL(BT_RETRY);
TX_STATUS_FAIL(STA_INVALID);
TX_STATUS_FAIL(FRAG_DROPPED);
TX_STATUS_FAIL(TID_DISABLE);
TX_STATUS_FAIL(FIFO_FLUSHED);
TX_STATUS_FAIL(INSUFFICIENT_CF_POLL);
TX_STATUS_FAIL(PASSIVE_NO_RX);
TX_STATUS_FAIL(NO_BEACON_ON_RADAR);
}
return "UNKNOWN";
#undef TX_STATUS_FAIL
#undef TX_STATUS_POSTPONE
}
#endif /* CONFIG_IWLEGACY_DEBUG */
static struct il_link_quality_cmd *
il4965_sta_alloc_lq(struct il_priv *il, u8 sta_id)
{
int i, r;
struct il_link_quality_cmd *link_cmd;
u32 rate_flags = 0;
__le32 rate_n_flags;
link_cmd = kzalloc(sizeof(struct il_link_quality_cmd), GFP_KERNEL);
if (!link_cmd) {
IL_ERR("Unable to allocate memory for LQ cmd.\n");
return NULL;
}
/* Set up the rate scaling to start at selected rate, fall back
* all the way down to 1M in IEEE order, and then spin on 1M */
if (il->band == IEEE80211_BAND_5GHZ)
r = RATE_6M_IDX;
else
r = RATE_1M_IDX;
if (r >= IL_FIRST_CCK_RATE && r <= IL_LAST_CCK_RATE)
rate_flags |= RATE_MCS_CCK_MSK;
rate_flags |=
il4965_first_antenna(il->hw_params.
valid_tx_ant) << RATE_MCS_ANT_POS;
rate_n_flags = cpu_to_le32(il_rates[r].plcp | rate_flags);
for (i = 0; i < LINK_QUAL_MAX_RETRY_NUM; i++)
link_cmd->rs_table[i].rate_n_flags = rate_n_flags;
link_cmd->general_params.single_stream_ant_msk =
il4965_first_antenna(il->hw_params.valid_tx_ant);
link_cmd->general_params.dual_stream_ant_msk =
il->hw_params.valid_tx_ant & ~il4965_first_antenna(il->hw_params.
valid_tx_ant);
if (!link_cmd->general_params.dual_stream_ant_msk) {
link_cmd->general_params.dual_stream_ant_msk = ANT_AB;
} else if (il4965_num_of_ant(il->hw_params.valid_tx_ant) == 2) {
link_cmd->general_params.dual_stream_ant_msk =
il->hw_params.valid_tx_ant;
}
link_cmd->agg_params.agg_dis_start_th = LINK_QUAL_AGG_DISABLE_START_DEF;
link_cmd->agg_params.agg_time_limit =
cpu_to_le16(LINK_QUAL_AGG_TIME_LIMIT_DEF);
link_cmd->sta_id = sta_id;
return link_cmd;
}
/*
* il4965_add_bssid_station - Add the special IBSS BSSID station
*
* Function sleeps.
*/
int
il4965_add_bssid_station(struct il_priv *il, const u8 *addr, u8 *sta_id_r)
{
int ret;
u8 sta_id;
struct il_link_quality_cmd *link_cmd;
unsigned long flags;
if (sta_id_r)
*sta_id_r = IL_INVALID_STATION;
ret = il_add_station_common(il, addr, 0, NULL, &sta_id);
if (ret) {
IL_ERR("Unable to add station %pM\n", addr);
return ret;
}
if (sta_id_r)
*sta_id_r = sta_id;
spin_lock_irqsave(&il->sta_lock, flags);
il->stations[sta_id].used |= IL_STA_LOCAL;
spin_unlock_irqrestore(&il->sta_lock, flags);
/* Set up default rate scaling table in device's station table */
link_cmd = il4965_sta_alloc_lq(il, sta_id);
if (!link_cmd) {
IL_ERR("Unable to initialize rate scaling for station %pM.\n",
addr);
return -ENOMEM;
}
ret = il_send_lq_cmd(il, link_cmd, CMD_SYNC, true);
if (ret)
IL_ERR("Link quality command failed (%d)\n", ret);
spin_lock_irqsave(&il->sta_lock, flags);
il->stations[sta_id].lq = link_cmd;
spin_unlock_irqrestore(&il->sta_lock, flags);
return 0;
}
static int
il4965_static_wepkey_cmd(struct il_priv *il, bool send_if_empty)
{
int i;
u8 buff[sizeof(struct il_wep_cmd) +
sizeof(struct il_wep_key) * WEP_KEYS_MAX];
struct il_wep_cmd *wep_cmd = (struct il_wep_cmd *)buff;
size_t cmd_size = sizeof(struct il_wep_cmd);
struct il_host_cmd cmd = {
.id = C_WEPKEY,
.data = wep_cmd,
.flags = CMD_SYNC,
};
bool not_empty = false;
might_sleep();
memset(wep_cmd, 0,
cmd_size + (sizeof(struct il_wep_key) * WEP_KEYS_MAX));
for (i = 0; i < WEP_KEYS_MAX; i++) {
u8 key_size = il->_4965.wep_keys[i].key_size;
wep_cmd->key[i].key_idx = i;
if (key_size) {
wep_cmd->key[i].key_offset = i;
not_empty = true;
} else
wep_cmd->key[i].key_offset = WEP_INVALID_OFFSET;
wep_cmd->key[i].key_size = key_size;
memcpy(&wep_cmd->key[i].key[3], il->_4965.wep_keys[i].key, key_size);
}
wep_cmd->global_key_type = WEP_KEY_WEP_TYPE;
wep_cmd->num_keys = WEP_KEYS_MAX;
cmd_size += sizeof(struct il_wep_key) * WEP_KEYS_MAX;
cmd.len = cmd_size;
if (not_empty || send_if_empty)
return il_send_cmd(il, &cmd);
else
return 0;
}
int
il4965_restore_default_wep_keys(struct il_priv *il)
{
lockdep_assert_held(&il->mutex);
return il4965_static_wepkey_cmd(il, false);
}
int
il4965_remove_default_wep_key(struct il_priv *il,
struct ieee80211_key_conf *keyconf)
{
int ret;
int idx = keyconf->keyidx;
lockdep_assert_held(&il->mutex);
D_WEP("Removing default WEP key: idx=%d\n", idx);
memset(&il->_4965.wep_keys[idx], 0, sizeof(struct il_wep_key));
if (il_is_rfkill(il)) {
D_WEP("Not sending C_WEPKEY command due to RFKILL.\n");
/* but keys in device are clear anyway so return success */
return 0;
}
ret = il4965_static_wepkey_cmd(il, 1);
D_WEP("Remove default WEP key: idx=%d ret=%d\n", idx, ret);
return ret;
}
int
il4965_set_default_wep_key(struct il_priv *il,
struct ieee80211_key_conf *keyconf)
{
int ret;
int len = keyconf->keylen;
int idx = keyconf->keyidx;
lockdep_assert_held(&il->mutex);
if (len != WEP_KEY_LEN_128 && len != WEP_KEY_LEN_64) {
D_WEP("Bad WEP key length %d\n", keyconf->keylen);
return -EINVAL;
}
keyconf->flags &= ~IEEE80211_KEY_FLAG_GENERATE_IV;
keyconf->hw_key_idx = HW_KEY_DEFAULT;
il->stations[IL_AP_ID].keyinfo.cipher = keyconf->cipher;
il->_4965.wep_keys[idx].key_size = len;
memcpy(&il->_4965.wep_keys[idx].key, &keyconf->key, len);
ret = il4965_static_wepkey_cmd(il, false);
D_WEP("Set default WEP key: len=%d idx=%d ret=%d\n", len, idx, ret);
return ret;
}
static int
il4965_set_wep_dynamic_key_info(struct il_priv *il,
struct ieee80211_key_conf *keyconf, u8 sta_id)
{
unsigned long flags;
__le16 key_flags = 0;
struct il_addsta_cmd sta_cmd;
lockdep_assert_held(&il->mutex);
keyconf->flags &= ~IEEE80211_KEY_FLAG_GENERATE_IV;
key_flags |= (STA_KEY_FLG_WEP | STA_KEY_FLG_MAP_KEY_MSK);
key_flags |= cpu_to_le16(keyconf->keyidx << STA_KEY_FLG_KEYID_POS);
key_flags &= ~STA_KEY_FLG_INVALID;
if (keyconf->keylen == WEP_KEY_LEN_128)
key_flags |= STA_KEY_FLG_KEY_SIZE_MSK;
if (sta_id == il->hw_params.bcast_id)
key_flags |= STA_KEY_MULTICAST_MSK;
spin_lock_irqsave(&il->sta_lock, flags);
il->stations[sta_id].keyinfo.cipher = keyconf->cipher;
il->stations[sta_id].keyinfo.keylen = keyconf->keylen;
il->stations[sta_id].keyinfo.keyidx = keyconf->keyidx;
memcpy(il->stations[sta_id].keyinfo.key, keyconf->key, keyconf->keylen);
memcpy(&il->stations[sta_id].sta.key.key[3], keyconf->key,
keyconf->keylen);
if ((il->stations[sta_id].sta.key.
key_flags & STA_KEY_FLG_ENCRYPT_MSK) == STA_KEY_FLG_NO_ENC)
il->stations[sta_id].sta.key.key_offset =
il_get_free_ucode_key_idx(il);
/* else, we are overriding an existing key => no need to allocated room
* in uCode. */
WARN(il->stations[sta_id].sta.key.key_offset == WEP_INVALID_OFFSET,
"no space for a new key");
il->stations[sta_id].sta.key.key_flags = key_flags;
il->stations[sta_id].sta.sta.modify_mask = STA_MODIFY_KEY_MASK;
il->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
memcpy(&sta_cmd, &il->stations[sta_id].sta,
sizeof(struct il_addsta_cmd));
spin_unlock_irqrestore(&il->sta_lock, flags);
return il_send_add_sta(il, &sta_cmd, CMD_SYNC);
}
static int
il4965_set_ccmp_dynamic_key_info(struct il_priv *il,
struct ieee80211_key_conf *keyconf, u8 sta_id)
{
unsigned long flags;
__le16 key_flags = 0;
struct il_addsta_cmd sta_cmd;
lockdep_assert_held(&il->mutex);
key_flags |= (STA_KEY_FLG_CCMP | STA_KEY_FLG_MAP_KEY_MSK);
key_flags |= cpu_to_le16(keyconf->keyidx << STA_KEY_FLG_KEYID_POS);
key_flags &= ~STA_KEY_FLG_INVALID;
if (sta_id == il->hw_params.bcast_id)
key_flags |= STA_KEY_MULTICAST_MSK;
keyconf->flags |= IEEE80211_KEY_FLAG_GENERATE_IV;
spin_lock_irqsave(&il->sta_lock, flags);
il->stations[sta_id].keyinfo.cipher = keyconf->cipher;
il->stations[sta_id].keyinfo.keylen = keyconf->keylen;
memcpy(il->stations[sta_id].keyinfo.key, keyconf->key, keyconf->keylen);
memcpy(il->stations[sta_id].sta.key.key, keyconf->key, keyconf->keylen);
if ((il->stations[sta_id].sta.key.
key_flags & STA_KEY_FLG_ENCRYPT_MSK) == STA_KEY_FLG_NO_ENC)
il->stations[sta_id].sta.key.key_offset =
il_get_free_ucode_key_idx(il);
/* else, we are overriding an existing key => no need to allocated room
* in uCode. */
WARN(il->stations[sta_id].sta.key.key_offset == WEP_INVALID_OFFSET,
"no space for a new key");
il->stations[sta_id].sta.key.key_flags = key_flags;
il->stations[sta_id].sta.sta.modify_mask = STA_MODIFY_KEY_MASK;
il->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
memcpy(&sta_cmd, &il->stations[sta_id].sta,
sizeof(struct il_addsta_cmd));
spin_unlock_irqrestore(&il->sta_lock, flags);
return il_send_add_sta(il, &sta_cmd, CMD_SYNC);
}
static int
il4965_set_tkip_dynamic_key_info(struct il_priv *il,
struct ieee80211_key_conf *keyconf, u8 sta_id)
{
unsigned long flags;
int ret = 0;
__le16 key_flags = 0;
key_flags |= (STA_KEY_FLG_TKIP | STA_KEY_FLG_MAP_KEY_MSK);
key_flags |= cpu_to_le16(keyconf->keyidx << STA_KEY_FLG_KEYID_POS);
key_flags &= ~STA_KEY_FLG_INVALID;
if (sta_id == il->hw_params.bcast_id)
key_flags |= STA_KEY_MULTICAST_MSK;
keyconf->flags |= IEEE80211_KEY_FLAG_GENERATE_IV;
keyconf->flags |= IEEE80211_KEY_FLAG_GENERATE_MMIC;
spin_lock_irqsave(&il->sta_lock, flags);
il->stations[sta_id].keyinfo.cipher = keyconf->cipher;
il->stations[sta_id].keyinfo.keylen = 16;
if ((il->stations[sta_id].sta.key.
key_flags & STA_KEY_FLG_ENCRYPT_MSK) == STA_KEY_FLG_NO_ENC)
il->stations[sta_id].sta.key.key_offset =
il_get_free_ucode_key_idx(il);
/* else, we are overriding an existing key => no need to allocated room
* in uCode. */
WARN(il->stations[sta_id].sta.key.key_offset == WEP_INVALID_OFFSET,
"no space for a new key");
il->stations[sta_id].sta.key.key_flags = key_flags;
/* This copy is acutally not needed: we get the key with each TX */
memcpy(il->stations[sta_id].keyinfo.key, keyconf->key, 16);
memcpy(il->stations[sta_id].sta.key.key, keyconf->key, 16);
spin_unlock_irqrestore(&il->sta_lock, flags);
return ret;
}
void
il4965_update_tkip_key(struct il_priv *il, struct ieee80211_key_conf *keyconf,
struct ieee80211_sta *sta, u32 iv32, u16 *phase1key)
{
u8 sta_id;
unsigned long flags;
int i;
if (il_scan_cancel(il)) {
/* cancel scan failed, just live w/ bad key and rely
briefly on SW decryption */
return;
}
sta_id = il_sta_id_or_broadcast(il, sta);
if (sta_id == IL_INVALID_STATION)
return;
spin_lock_irqsave(&il->sta_lock, flags);
il->stations[sta_id].sta.key.tkip_rx_tsc_byte2 = (u8) iv32;
for (i = 0; i < 5; i++)
il->stations[sta_id].sta.key.tkip_rx_ttak[i] =
cpu_to_le16(phase1key[i]);
il->stations[sta_id].sta.sta.modify_mask = STA_MODIFY_KEY_MASK;
il->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
il_send_add_sta(il, &il->stations[sta_id].sta, CMD_ASYNC);
spin_unlock_irqrestore(&il->sta_lock, flags);
}
int
il4965_remove_dynamic_key(struct il_priv *il,
struct ieee80211_key_conf *keyconf, u8 sta_id)
{
unsigned long flags;
u16 key_flags;
u8 keyidx;
struct il_addsta_cmd sta_cmd;
lockdep_assert_held(&il->mutex);
il->_4965.key_mapping_keys--;
spin_lock_irqsave(&il->sta_lock, flags);
key_flags = le16_to_cpu(il->stations[sta_id].sta.key.key_flags);
keyidx = (key_flags >> STA_KEY_FLG_KEYID_POS) & 0x3;
D_WEP("Remove dynamic key: idx=%d sta=%d\n", keyconf->keyidx, sta_id);
if (keyconf->keyidx != keyidx) {
/* We need to remove a key with idx different that the one
* in the uCode. This means that the key we need to remove has
* been replaced by another one with different idx.
* Don't do anything and return ok
*/
spin_unlock_irqrestore(&il->sta_lock, flags);
return 0;
}
if (il->stations[sta_id].sta.key.key_flags & STA_KEY_FLG_INVALID) {
IL_WARN("Removing wrong key %d 0x%x\n", keyconf->keyidx,
key_flags);
spin_unlock_irqrestore(&il->sta_lock, flags);
return 0;
}
if (!test_and_clear_bit
(il->stations[sta_id].sta.key.key_offset, &il->ucode_key_table))
IL_ERR("idx %d not used in uCode key table.\n",
il->stations[sta_id].sta.key.key_offset);
memset(&il->stations[sta_id].keyinfo, 0, sizeof(struct il_hw_key));
memset(&il->stations[sta_id].sta.key, 0, sizeof(struct il4965_keyinfo));
il->stations[sta_id].sta.key.key_flags =
STA_KEY_FLG_NO_ENC | STA_KEY_FLG_INVALID;
il->stations[sta_id].sta.key.key_offset = keyconf->hw_key_idx;
il->stations[sta_id].sta.sta.modify_mask = STA_MODIFY_KEY_MASK;
il->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
if (il_is_rfkill(il)) {
D_WEP
("Not sending C_ADD_STA command because RFKILL enabled.\n");
spin_unlock_irqrestore(&il->sta_lock, flags);
return 0;
}
memcpy(&sta_cmd, &il->stations[sta_id].sta,
sizeof(struct il_addsta_cmd));
spin_unlock_irqrestore(&il->sta_lock, flags);
return il_send_add_sta(il, &sta_cmd, CMD_SYNC);
}
int
il4965_set_dynamic_key(struct il_priv *il, struct ieee80211_key_conf *keyconf,
u8 sta_id)
{
int ret;
lockdep_assert_held(&il->mutex);
il->_4965.key_mapping_keys++;
keyconf->hw_key_idx = HW_KEY_DYNAMIC;
switch (keyconf->cipher) {
case WLAN_CIPHER_SUITE_CCMP:
ret =
il4965_set_ccmp_dynamic_key_info(il, keyconf, sta_id);
break;
case WLAN_CIPHER_SUITE_TKIP:
ret =
il4965_set_tkip_dynamic_key_info(il, keyconf, sta_id);
break;
case WLAN_CIPHER_SUITE_WEP40:
case WLAN_CIPHER_SUITE_WEP104:
ret = il4965_set_wep_dynamic_key_info(il, keyconf, sta_id);
break;
default:
IL_ERR("Unknown alg: %s cipher = %x\n", __func__,
keyconf->cipher);
ret = -EINVAL;
}
D_WEP("Set dynamic key: cipher=%x len=%d idx=%d sta=%d ret=%d\n",
keyconf->cipher, keyconf->keylen, keyconf->keyidx, sta_id, ret);
return ret;
}
/**
* il4965_alloc_bcast_station - add broadcast station into driver's station table.
*
* This adds the broadcast station into the driver's station table
* and marks it driver active, so that it will be restored to the
* device at the next best time.
*/
int
il4965_alloc_bcast_station(struct il_priv *il)
{
struct il_link_quality_cmd *link_cmd;
unsigned long flags;
u8 sta_id;
spin_lock_irqsave(&il->sta_lock, flags);
sta_id = il_prep_station(il, il_bcast_addr, false, NULL);
if (sta_id == IL_INVALID_STATION) {
IL_ERR("Unable to prepare broadcast station\n");
spin_unlock_irqrestore(&il->sta_lock, flags);
return -EINVAL;
}
il->stations[sta_id].used |= IL_STA_DRIVER_ACTIVE;
il->stations[sta_id].used |= IL_STA_BCAST;
spin_unlock_irqrestore(&il->sta_lock, flags);
link_cmd = il4965_sta_alloc_lq(il, sta_id);
if (!link_cmd) {
IL_ERR
("Unable to initialize rate scaling for bcast station.\n");
return -ENOMEM;
}
spin_lock_irqsave(&il->sta_lock, flags);
il->stations[sta_id].lq = link_cmd;
spin_unlock_irqrestore(&il->sta_lock, flags);
return 0;
}
/**
* il4965_update_bcast_station - update broadcast station's LQ command
*
* Only used by iwl4965. Placed here to have all bcast station management
* code together.
*/
static int
il4965_update_bcast_station(struct il_priv *il)
{
unsigned long flags;
struct il_link_quality_cmd *link_cmd;
u8 sta_id = il->hw_params.bcast_id;
link_cmd = il4965_sta_alloc_lq(il, sta_id);
if (!link_cmd) {
IL_ERR("Unable to initialize rate scaling for bcast sta.\n");
return -ENOMEM;
}
spin_lock_irqsave(&il->sta_lock, flags);
if (il->stations[sta_id].lq)
kfree(il->stations[sta_id].lq);
else
D_INFO("Bcast sta rate scaling has not been initialized.\n");
il->stations[sta_id].lq = link_cmd;
spin_unlock_irqrestore(&il->sta_lock, flags);
return 0;
}
int
il4965_update_bcast_stations(struct il_priv *il)
{
return il4965_update_bcast_station(il);
}
/**
* il4965_sta_tx_modify_enable_tid - Enable Tx for this TID in station table
*/
int
il4965_sta_tx_modify_enable_tid(struct il_priv *il, int sta_id, int tid)
{
unsigned long flags;
struct il_addsta_cmd sta_cmd;
lockdep_assert_held(&il->mutex);
/* Remove "disable" flag, to enable Tx for this TID */
spin_lock_irqsave(&il->sta_lock, flags);
il->stations[sta_id].sta.sta.modify_mask = STA_MODIFY_TID_DISABLE_TX;
il->stations[sta_id].sta.tid_disable_tx &= cpu_to_le16(~(1 << tid));
il->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
memcpy(&sta_cmd, &il->stations[sta_id].sta,
sizeof(struct il_addsta_cmd));
spin_unlock_irqrestore(&il->sta_lock, flags);
return il_send_add_sta(il, &sta_cmd, CMD_SYNC);
}
int
il4965_sta_rx_agg_start(struct il_priv *il, struct ieee80211_sta *sta, int tid,
u16 ssn)
{
unsigned long flags;
int sta_id;
struct il_addsta_cmd sta_cmd;
lockdep_assert_held(&il->mutex);
sta_id = il_sta_id(sta);
if (sta_id == IL_INVALID_STATION)
return -ENXIO;
spin_lock_irqsave(&il->sta_lock, flags);
il->stations[sta_id].sta.station_flags_msk = 0;
il->stations[sta_id].sta.sta.modify_mask = STA_MODIFY_ADDBA_TID_MSK;
il->stations[sta_id].sta.add_immediate_ba_tid = (u8) tid;
il->stations[sta_id].sta.add_immediate_ba_ssn = cpu_to_le16(ssn);
il->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
memcpy(&sta_cmd, &il->stations[sta_id].sta,
sizeof(struct il_addsta_cmd));
spin_unlock_irqrestore(&il->sta_lock, flags);
return il_send_add_sta(il, &sta_cmd, CMD_SYNC);
}
int
il4965_sta_rx_agg_stop(struct il_priv *il, struct ieee80211_sta *sta, int tid)
{
unsigned long flags;
int sta_id;
struct il_addsta_cmd sta_cmd;
lockdep_assert_held(&il->mutex);
sta_id = il_sta_id(sta);
if (sta_id == IL_INVALID_STATION) {
IL_ERR("Invalid station for AGG tid %d\n", tid);
return -ENXIO;
}
spin_lock_irqsave(&il->sta_lock, flags);
il->stations[sta_id].sta.station_flags_msk = 0;
il->stations[sta_id].sta.sta.modify_mask = STA_MODIFY_DELBA_TID_MSK;
il->stations[sta_id].sta.remove_immediate_ba_tid = (u8) tid;
il->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
memcpy(&sta_cmd, &il->stations[sta_id].sta,
sizeof(struct il_addsta_cmd));
spin_unlock_irqrestore(&il->sta_lock, flags);
return il_send_add_sta(il, &sta_cmd, CMD_SYNC);
}
void
il4965_sta_modify_sleep_tx_count(struct il_priv *il, int sta_id, int cnt)
{
unsigned long flags;
spin_lock_irqsave(&il->sta_lock, flags);
il->stations[sta_id].sta.station_flags |= STA_FLG_PWR_SAVE_MSK;
il->stations[sta_id].sta.station_flags_msk = STA_FLG_PWR_SAVE_MSK;
il->stations[sta_id].sta.sta.modify_mask =
STA_MODIFY_SLEEP_TX_COUNT_MSK;
il->stations[sta_id].sta.sleep_tx_count = cpu_to_le16(cnt);
il->stations[sta_id].sta.mode = STA_CONTROL_MODIFY_MSK;
il_send_add_sta(il, &il->stations[sta_id].sta, CMD_ASYNC);
spin_unlock_irqrestore(&il->sta_lock, flags);
}
void
il4965_update_chain_flags(struct il_priv *il)
{
if (il->ops->set_rxon_chain) {
il->ops->set_rxon_chain(il);
if (il->active.rx_chain != il->staging.rx_chain)
il_commit_rxon(il);
}
}
static void
il4965_clear_free_frames(struct il_priv *il)
{
struct list_head *element;
D_INFO("%d frames on pre-allocated heap on clear.\n", il->frames_count);
while (!list_empty(&il->free_frames)) {
element = il->free_frames.next;
list_del(element);
kfree(list_entry(element, struct il_frame, list));
il->frames_count--;
}
if (il->frames_count) {
IL_WARN("%d frames still in use. Did we lose one?\n",
il->frames_count);
il->frames_count = 0;
}
}
static struct il_frame *
il4965_get_free_frame(struct il_priv *il)
{
struct il_frame *frame;
struct list_head *element;
if (list_empty(&il->free_frames)) {
frame = kzalloc(sizeof(*frame), GFP_KERNEL);
if (!frame) {
IL_ERR("Could not allocate frame!\n");
return NULL;
}
il->frames_count++;
return frame;
}
element = il->free_frames.next;
list_del(element);
return list_entry(element, struct il_frame, list);
}
static void
il4965_free_frame(struct il_priv *il, struct il_frame *frame)
{
memset(frame, 0, sizeof(*frame));
list_add(&frame->list, &il->free_frames);
}
static u32
il4965_fill_beacon_frame(struct il_priv *il, struct ieee80211_hdr *hdr,
int left)
{
lockdep_assert_held(&il->mutex);
if (!il->beacon_skb)
return 0;
if (il->beacon_skb->len > left)
return 0;
memcpy(hdr, il->beacon_skb->data, il->beacon_skb->len);
return il->beacon_skb->len;
}
/* Parse the beacon frame to find the TIM element and set tim_idx & tim_size */
static void
il4965_set_beacon_tim(struct il_priv *il,
struct il_tx_beacon_cmd *tx_beacon_cmd, u8 * beacon,
u32 frame_size)
{
u16 tim_idx;
struct ieee80211_mgmt *mgmt = (struct ieee80211_mgmt *)beacon;
/*
* The idx is relative to frame start but we start looking at the
* variable-length part of the beacon.
*/
tim_idx = mgmt->u.beacon.variable - beacon;
/* Parse variable-length elements of beacon to find WLAN_EID_TIM */
while ((tim_idx < (frame_size - 2)) &&
(beacon[tim_idx] != WLAN_EID_TIM))
tim_idx += beacon[tim_idx + 1] + 2;
/* If TIM field was found, set variables */
if ((tim_idx < (frame_size - 1)) && (beacon[tim_idx] == WLAN_EID_TIM)) {
tx_beacon_cmd->tim_idx = cpu_to_le16(tim_idx);
tx_beacon_cmd->tim_size = beacon[tim_idx + 1];
} else
IL_WARN("Unable to find TIM Element in beacon\n");
}
static unsigned int
il4965_hw_get_beacon_cmd(struct il_priv *il, struct il_frame *frame)
{
struct il_tx_beacon_cmd *tx_beacon_cmd;
u32 frame_size;
u32 rate_flags;
u32 rate;
/*
* We have to set up the TX command, the TX Beacon command, and the
* beacon contents.
*/
lockdep_assert_held(&il->mutex);
if (!il->beacon_enabled) {
IL_ERR("Trying to build beacon without beaconing enabled\n");
return 0;
}
/* Initialize memory */
tx_beacon_cmd = &frame->u.beacon;
memset(tx_beacon_cmd, 0, sizeof(*tx_beacon_cmd));
/* Set up TX beacon contents */
frame_size =
il4965_fill_beacon_frame(il, tx_beacon_cmd->frame,
sizeof(frame->u) - sizeof(*tx_beacon_cmd));
if (WARN_ON_ONCE(frame_size > MAX_MPDU_SIZE))
return 0;
if (!frame_size)
return 0;
/* Set up TX command fields */
tx_beacon_cmd->tx.len = cpu_to_le16((u16) frame_size);
tx_beacon_cmd->tx.sta_id = il->hw_params.bcast_id;
tx_beacon_cmd->tx.stop_time.life_time = TX_CMD_LIFE_TIME_INFINITE;
tx_beacon_cmd->tx.tx_flags =
TX_CMD_FLG_SEQ_CTL_MSK | TX_CMD_FLG_TSF_MSK |
TX_CMD_FLG_STA_RATE_MSK;
/* Set up TX beacon command fields */
il4965_set_beacon_tim(il, tx_beacon_cmd, (u8 *) tx_beacon_cmd->frame,
frame_size);
/* Set up packet rate and flags */
rate = il_get_lowest_plcp(il);
il4965_toggle_tx_ant(il, &il->mgmt_tx_ant, il->hw_params.valid_tx_ant);
rate_flags = BIT(il->mgmt_tx_ant) << RATE_MCS_ANT_POS;
if ((rate >= IL_FIRST_CCK_RATE) && (rate <= IL_LAST_CCK_RATE))
rate_flags |= RATE_MCS_CCK_MSK;
tx_beacon_cmd->tx.rate_n_flags = cpu_to_le32(rate | rate_flags);
return sizeof(*tx_beacon_cmd) + frame_size;
}
int
il4965_send_beacon_cmd(struct il_priv *il)
{
struct il_frame *frame;
unsigned int frame_size;
int rc;
frame = il4965_get_free_frame(il);
if (!frame) {
IL_ERR("Could not obtain free frame buffer for beacon "
"command.\n");
return -ENOMEM;
}
frame_size = il4965_hw_get_beacon_cmd(il, frame);
if (!frame_size) {
IL_ERR("Error configuring the beacon command\n");
il4965_free_frame(il, frame);
return -EINVAL;
}
rc = il_send_cmd_pdu(il, C_TX_BEACON, frame_size, &frame->u.cmd[0]);
il4965_free_frame(il, frame);
return rc;
}
static inline dma_addr_t
il4965_tfd_tb_get_addr(struct il_tfd *tfd, u8 idx)
{
struct il_tfd_tb *tb = &tfd->tbs[idx];
dma_addr_t addr = get_unaligned_le32(&tb->lo);
if (sizeof(dma_addr_t) > sizeof(u32))
addr |=
((dma_addr_t) (le16_to_cpu(tb->hi_n_len) & 0xF) << 16) <<
16;
return addr;
}
static inline u16
il4965_tfd_tb_get_len(struct il_tfd *tfd, u8 idx)
{
struct il_tfd_tb *tb = &tfd->tbs[idx];
return le16_to_cpu(tb->hi_n_len) >> 4;
}
static inline void
il4965_tfd_set_tb(struct il_tfd *tfd, u8 idx, dma_addr_t addr, u16 len)
{
struct il_tfd_tb *tb = &tfd->tbs[idx];
u16 hi_n_len = len << 4;
put_unaligned_le32(addr, &tb->lo);
if (sizeof(dma_addr_t) > sizeof(u32))
hi_n_len |= ((addr >> 16) >> 16) & 0xF;
tb->hi_n_len = cpu_to_le16(hi_n_len);
tfd->num_tbs = idx + 1;
}
static inline u8
il4965_tfd_get_num_tbs(struct il_tfd *tfd)
{
return tfd->num_tbs & 0x1f;
}
/**
* il4965_hw_txq_free_tfd - Free all chunks referenced by TFD [txq->q.read_ptr]
* @il - driver ilate data
* @txq - tx queue
*
* Does NOT advance any TFD circular buffer read/write idxes
* Does NOT free the TFD itself (which is within circular buffer)
*/
void
il4965_hw_txq_free_tfd(struct il_priv *il, struct il_tx_queue *txq)
{
struct il_tfd *tfd_tmp = (struct il_tfd *)txq->tfds;
struct il_tfd *tfd;
struct pci_dev *dev = il->pci_dev;
int idx = txq->q.read_ptr;
int i;
int num_tbs;
tfd = &tfd_tmp[idx];
/* Sanity check on number of chunks */
num_tbs = il4965_tfd_get_num_tbs(tfd);
if (num_tbs >= IL_NUM_OF_TBS) {
IL_ERR("Too many chunks: %i\n", num_tbs);
/* @todo issue fatal error, it is quite serious situation */
return;
}
/* Unmap tx_cmd */
if (num_tbs)
pci_unmap_single(dev, dma_unmap_addr(&txq->meta[idx], mapping),
dma_unmap_len(&txq->meta[idx], len),
PCI_DMA_BIDIRECTIONAL);
/* Unmap chunks, if any. */
for (i = 1; i < num_tbs; i++)
pci_unmap_single(dev, il4965_tfd_tb_get_addr(tfd, i),
il4965_tfd_tb_get_len(tfd, i),
PCI_DMA_TODEVICE);
/* free SKB */
if (txq->skbs) {
struct sk_buff *skb = txq->skbs[txq->q.read_ptr];
/* can be called from irqs-disabled context */
if (skb) {
dev_kfree_skb_any(skb);
txq->skbs[txq->q.read_ptr] = NULL;
}
}
}
int
il4965_hw_txq_attach_buf_to_tfd(struct il_priv *il, struct il_tx_queue *txq,
dma_addr_t addr, u16 len, u8 reset, u8 pad)
{
struct il_queue *q;
struct il_tfd *tfd, *tfd_tmp;
u32 num_tbs;
q = &txq->q;
tfd_tmp = (struct il_tfd *)txq->tfds;
tfd = &tfd_tmp[q->write_ptr];
if (reset)
memset(tfd, 0, sizeof(*tfd));
num_tbs = il4965_tfd_get_num_tbs(tfd);
/* Each TFD can point to a maximum 20 Tx buffers */
if (num_tbs >= IL_NUM_OF_TBS) {
IL_ERR("Error can not send more than %d chunks\n",
IL_NUM_OF_TBS);
return -EINVAL;
}
BUG_ON(addr & ~DMA_BIT_MASK(36));
if (unlikely(addr & ~IL_TX_DMA_MASK))
IL_ERR("Unaligned address = %llx\n", (unsigned long long)addr);
il4965_tfd_set_tb(tfd, num_tbs, addr, len);
return 0;
}
/*
* Tell nic where to find circular buffer of Tx Frame Descriptors for
* given Tx queue, and enable the DMA channel used for that queue.
*
* 4965 supports up to 16 Tx queues in DRAM, mapped to up to 8 Tx DMA
* channels supported in hardware.
*/
int
il4965_hw_tx_queue_init(struct il_priv *il, struct il_tx_queue *txq)
{
int txq_id = txq->q.id;
/* Circular buffer (TFD queue in DRAM) physical base address */
il_wr(il, FH49_MEM_CBBC_QUEUE(txq_id), txq->q.dma_addr >> 8);
return 0;
}
/******************************************************************************
*
* Generic RX handler implementations
*
******************************************************************************/
static void
il4965_hdl_alive(struct il_priv *il, struct il_rx_buf *rxb)
{
struct il_rx_pkt *pkt = rxb_addr(rxb);
struct il_alive_resp *palive;
struct delayed_work *pwork;
palive = &pkt->u.alive_frame;
D_INFO("Alive ucode status 0x%08X revision " "0x%01X 0x%01X\n",
palive->is_valid, palive->ver_type, palive->ver_subtype);
if (palive->ver_subtype == INITIALIZE_SUBTYPE) {
D_INFO("Initialization Alive received.\n");
memcpy(&il->card_alive_init, &pkt->u.alive_frame,
sizeof(struct il_init_alive_resp));
pwork = &il->init_alive_start;
} else {
D_INFO("Runtime Alive received.\n");
memcpy(&il->card_alive, &pkt->u.alive_frame,
sizeof(struct il_alive_resp));
pwork = &il->alive_start;
}
/* We delay the ALIVE response by 5ms to
* give the HW RF Kill time to activate... */
if (palive->is_valid == UCODE_VALID_OK)
queue_delayed_work(il->workqueue, pwork, msecs_to_jiffies(5));
else
IL_WARN("uCode did not respond OK.\n");
}
/**
* il4965_bg_stats_periodic - Timer callback to queue stats
*
* This callback is provided in order to send a stats request.
*
* This timer function is continually reset to execute within
* 60 seconds since the last N_STATS was received. We need to
* ensure we receive the stats in order to update the temperature
* used for calibrating the TXPOWER.
*/
static void
il4965_bg_stats_periodic(unsigned long data)
{
struct il_priv *il = (struct il_priv *)data;
if (test_bit(S_EXIT_PENDING, &il->status))
return;
/* dont send host command if rf-kill is on */
if (!il_is_ready_rf(il))
return;
il_send_stats_request(il, CMD_ASYNC, false);
}
static void
il4965_hdl_beacon(struct il_priv *il, struct il_rx_buf *rxb)
{
struct il_rx_pkt *pkt = rxb_addr(rxb);
struct il4965_beacon_notif *beacon =
(struct il4965_beacon_notif *)pkt->u.raw;
#ifdef CONFIG_IWLEGACY_DEBUG
u8 rate = il4965_hw_get_rate(beacon->beacon_notify_hdr.rate_n_flags);
D_RX("beacon status %x retries %d iss %d tsf:0x%.8x%.8x rate %d\n",
le32_to_cpu(beacon->beacon_notify_hdr.u.status) & TX_STATUS_MSK,
beacon->beacon_notify_hdr.failure_frame,
le32_to_cpu(beacon->ibss_mgr_status),
le32_to_cpu(beacon->high_tsf), le32_to_cpu(beacon->low_tsf), rate);
#endif
il->ibss_manager = le32_to_cpu(beacon->ibss_mgr_status);
}
static void
il4965_perform_ct_kill_task(struct il_priv *il)
{
unsigned long flags;
D_POWER("Stop all queues\n");
if (il->mac80211_registered)
ieee80211_stop_queues(il->hw);
_il_wr(il, CSR_UCODE_DRV_GP1_SET,
CSR_UCODE_DRV_GP1_REG_BIT_CT_KILL_EXIT);
_il_rd(il, CSR_UCODE_DRV_GP1);
spin_lock_irqsave(&il->reg_lock, flags);
if (likely(_il_grab_nic_access(il)))
_il_release_nic_access(il);
spin_unlock_irqrestore(&il->reg_lock, flags);
}
/* Handle notification from uCode that card's power state is changing
* due to software, hardware, or critical temperature RFKILL */
static void
il4965_hdl_card_state(struct il_priv *il, struct il_rx_buf *rxb)
{
struct il_rx_pkt *pkt = rxb_addr(rxb);
u32 flags = le32_to_cpu(pkt->u.card_state_notif.flags);
unsigned long status = il->status;
D_RF_KILL("Card state received: HW:%s SW:%s CT:%s\n",
(flags & HW_CARD_DISABLED) ? "Kill" : "On",
(flags & SW_CARD_DISABLED) ? "Kill" : "On",
(flags & CT_CARD_DISABLED) ? "Reached" : "Not reached");
if (flags & (SW_CARD_DISABLED | HW_CARD_DISABLED | CT_CARD_DISABLED)) {
_il_wr(il, CSR_UCODE_DRV_GP1_SET,
CSR_UCODE_DRV_GP1_BIT_CMD_BLOCKED);
il_wr(il, HBUS_TARG_MBX_C, HBUS_TARG_MBX_C_REG_BIT_CMD_BLOCKED);
if (!(flags & RXON_CARD_DISABLED)) {
_il_wr(il, CSR_UCODE_DRV_GP1_CLR,
CSR_UCODE_DRV_GP1_BIT_CMD_BLOCKED);
il_wr(il, HBUS_TARG_MBX_C,
HBUS_TARG_MBX_C_REG_BIT_CMD_BLOCKED);
}
}
if (flags & CT_CARD_DISABLED)
il4965_perform_ct_kill_task(il);
if (flags & HW_CARD_DISABLED)
set_bit(S_RFKILL, &il->status);
else
clear_bit(S_RFKILL, &il->status);
if (!(flags & RXON_CARD_DISABLED))
il_scan_cancel(il);
if ((test_bit(S_RFKILL, &status) !=
test_bit(S_RFKILL, &il->status)))
wiphy_rfkill_set_hw_state(il->hw->wiphy,
test_bit(S_RFKILL, &il->status));
else
wake_up(&il->wait_command_queue);
}
/**
* il4965_setup_handlers - Initialize Rx handler callbacks
*
* Setup the RX handlers for each of the reply types sent from the uCode
* to the host.
*
* This function chains into the hardware specific files for them to setup
* any hardware specific handlers as well.
*/
static void
il4965_setup_handlers(struct il_priv *il)
{
il->handlers[N_ALIVE] = il4965_hdl_alive;
il->handlers[N_ERROR] = il_hdl_error;
il->handlers[N_CHANNEL_SWITCH] = il_hdl_csa;
il->handlers[N_SPECTRUM_MEASUREMENT] = il_hdl_spectrum_measurement;
il->handlers[N_PM_SLEEP] = il_hdl_pm_sleep;
il->handlers[N_PM_DEBUG_STATS] = il_hdl_pm_debug_stats;
il->handlers[N_BEACON] = il4965_hdl_beacon;
/*
* The same handler is used for both the REPLY to a discrete
* stats request from the host as well as for the periodic
* stats notifications (after received beacons) from the uCode.
*/
il->handlers[C_STATS] = il4965_hdl_c_stats;
il->handlers[N_STATS] = il4965_hdl_stats;
il_setup_rx_scan_handlers(il);
/* status change handler */
il->handlers[N_CARD_STATE] = il4965_hdl_card_state;
il->handlers[N_MISSED_BEACONS] = il4965_hdl_missed_beacon;
/* Rx handlers */
il->handlers[N_RX_PHY] = il4965_hdl_rx_phy;
il->handlers[N_RX_MPDU] = il4965_hdl_rx;
il->handlers[N_RX] = il4965_hdl_rx;
/* block ack */
il->handlers[N_COMPRESSED_BA] = il4965_hdl_compressed_ba;
/* Tx response */
il->handlers[C_TX] = il4965_hdl_tx;
}
/**
* il4965_rx_handle - Main entry function for receiving responses from uCode
*
* Uses the il->handlers callback function array to invoke
* the appropriate handlers, including command responses,
* frame-received notifications, and other notifications.
*/
void
il4965_rx_handle(struct il_priv *il)
{
struct il_rx_buf *rxb;
struct il_rx_pkt *pkt;
struct il_rx_queue *rxq = &il->rxq;
u32 r, i;
int reclaim;
unsigned long flags;
u8 fill_rx = 0;
u32 count = 8;
int total_empty;
/* uCode's read idx (stored in shared DRAM) indicates the last Rx
* buffer that the driver may process (last buffer filled by ucode). */
r = le16_to_cpu(rxq->rb_stts->closed_rb_num) & 0x0FFF;
i = rxq->read;
/* Rx interrupt, but nothing sent from uCode */
if (i == r)
D_RX("r = %d, i = %d\n", r, i);
/* calculate total frames need to be restock after handling RX */
total_empty = r - rxq->write_actual;
if (total_empty < 0)
total_empty += RX_QUEUE_SIZE;
if (total_empty > (RX_QUEUE_SIZE / 2))
fill_rx = 1;
while (i != r) {
int len;
rxb = rxq->queue[i];
/* If an RXB doesn't have a Rx queue slot associated with it,
* then a bug has been introduced in the queue refilling
* routines -- catch it here */
BUG_ON(rxb == NULL);
rxq->queue[i] = NULL;
pci_unmap_page(il->pci_dev, rxb->page_dma,
PAGE_SIZE << il->hw_params.rx_page_order,
PCI_DMA_FROMDEVICE);
pkt = rxb_addr(rxb);
len = le32_to_cpu(pkt->len_n_flags) & IL_RX_FRAME_SIZE_MSK;
len += sizeof(u32); /* account for status word */
reclaim = il_need_reclaim(il, pkt);
/* Based on type of command response or notification,
* handle those that need handling via function in
* handlers table. See il4965_setup_handlers() */
if (il->handlers[pkt->hdr.cmd]) {
D_RX("r = %d, i = %d, %s, 0x%02x\n", r, i,
il_get_cmd_string(pkt->hdr.cmd), pkt->hdr.cmd);
il->isr_stats.handlers[pkt->hdr.cmd]++;
il->handlers[pkt->hdr.cmd] (il, rxb);
} else {
/* No handling needed */
D_RX("r %d i %d No handler needed for %s, 0x%02x\n", r,
i, il_get_cmd_string(pkt->hdr.cmd), pkt->hdr.cmd);
}
/*
* XXX: After here, we should always check rxb->page
* against NULL before touching it or its virtual
* memory (pkt). Because some handler might have
* already taken or freed the pages.
*/
if (reclaim) {
/* Invoke any callbacks, transfer the buffer to caller,
* and fire off the (possibly) blocking il_send_cmd()
* as we reclaim the driver command queue */
if (rxb->page)
il_tx_cmd_complete(il, rxb);
else
IL_WARN("Claim null rxb?\n");
}
/* Reuse the page if possible. For notification packets and
* SKBs that fail to Rx correctly, add them back into the
* rx_free list for reuse later. */
spin_lock_irqsave(&rxq->lock, flags);
if (rxb->page != NULL) {
rxb->page_dma =
pci_map_page(il->pci_dev, rxb->page, 0,
PAGE_SIZE << il->hw_params.
rx_page_order, PCI_DMA_FROMDEVICE);
if (unlikely(pci_dma_mapping_error(il->pci_dev,
rxb->page_dma))) {
__il_free_pages(il, rxb->page);
rxb->page = NULL;
list_add_tail(&rxb->list, &rxq->rx_used);
} else {
list_add_tail(&rxb->list, &rxq->rx_free);
rxq->free_count++;
}
} else
list_add_tail(&rxb->list, &rxq->rx_used);
spin_unlock_irqrestore(&rxq->lock, flags);
i = (i + 1) & RX_QUEUE_MASK;
/* If there are a lot of unused frames,
* restock the Rx queue so ucode wont assert. */
if (fill_rx) {
count++;
if (count >= 8) {
rxq->read = i;
il4965_rx_replenish_now(il);
count = 0;
}
}
}
/* Backtrack one entry */
rxq->read = i;
if (fill_rx)
il4965_rx_replenish_now(il);
else
il4965_rx_queue_restock(il);
}
/* call this function to flush any scheduled tasklet */
static inline void
il4965_synchronize_irq(struct il_priv *il)
{
/* wait to make sure we flush pending tasklet */
synchronize_irq(il->pci_dev->irq);
tasklet_kill(&il->irq_tasklet);
}
static void
il4965_irq_tasklet(struct il_priv *il)
{
u32 inta, handled = 0;
u32 inta_fh;
unsigned long flags;
u32 i;
#ifdef CONFIG_IWLEGACY_DEBUG
u32 inta_mask;
#endif
spin_lock_irqsave(&il->lock, flags);
/* Ack/clear/reset pending uCode interrupts.
* Note: Some bits in CSR_INT are "OR" of bits in CSR_FH_INT_STATUS,
* and will clear only when CSR_FH_INT_STATUS gets cleared. */
inta = _il_rd(il, CSR_INT);
_il_wr(il, CSR_INT, inta);
/* Ack/clear/reset pending flow-handler (DMA) interrupts.
* Any new interrupts that happen after this, either while we're
* in this tasklet, or later, will show up in next ISR/tasklet. */
inta_fh = _il_rd(il, CSR_FH_INT_STATUS);
_il_wr(il, CSR_FH_INT_STATUS, inta_fh);
#ifdef CONFIG_IWLEGACY_DEBUG
if (il_get_debug_level(il) & IL_DL_ISR) {
/* just for debug */
inta_mask = _il_rd(il, CSR_INT_MASK);
D_ISR("inta 0x%08x, enabled 0x%08x, fh 0x%08x\n", inta,
inta_mask, inta_fh);
}
#endif
spin_unlock_irqrestore(&il->lock, flags);
/* Since CSR_INT and CSR_FH_INT_STATUS reads and clears are not
* atomic, make sure that inta covers all the interrupts that
* we've discovered, even if FH interrupt came in just after
* reading CSR_INT. */
if (inta_fh & CSR49_FH_INT_RX_MASK)
inta |= CSR_INT_BIT_FH_RX;
if (inta_fh & CSR49_FH_INT_TX_MASK)
inta |= CSR_INT_BIT_FH_TX;
/* Now service all interrupt bits discovered above. */
if (inta & CSR_INT_BIT_HW_ERR) {
IL_ERR("Hardware error detected. Restarting.\n");
/* Tell the device to stop sending interrupts */
il_disable_interrupts(il);
il->isr_stats.hw++;
il_irq_handle_error(il);
handled |= CSR_INT_BIT_HW_ERR;
return;
}
#ifdef CONFIG_IWLEGACY_DEBUG
if (il_get_debug_level(il) & (IL_DL_ISR)) {
/* NIC fires this, but we don't use it, redundant with WAKEUP */
if (inta & CSR_INT_BIT_SCD) {
D_ISR("Scheduler finished to transmit "
"the frame/frames.\n");
il->isr_stats.sch++;
}
/* Alive notification via Rx interrupt will do the real work */
if (inta & CSR_INT_BIT_ALIVE) {
D_ISR("Alive interrupt\n");
il->isr_stats.alive++;
}
}
#endif
/* Safely ignore these bits for debug checks below */
inta &= ~(CSR_INT_BIT_SCD | CSR_INT_BIT_ALIVE);
/* HW RF KILL switch toggled */
if (inta & CSR_INT_BIT_RF_KILL) {
int hw_rf_kill = 0;
if (!(_il_rd(il, CSR_GP_CNTRL) & CSR_GP_CNTRL_REG_FLAG_HW_RF_KILL_SW))
hw_rf_kill = 1;
IL_WARN("RF_KILL bit toggled to %s.\n",
hw_rf_kill ? "disable radio" : "enable radio");
il->isr_stats.rfkill++;
/* driver only loads ucode once setting the interface up.
* the driver allows loading the ucode even if the radio
* is killed. Hence update the killswitch state here. The
* rfkill handler will care about restarting if needed.
*/
if (hw_rf_kill) {
set_bit(S_RFKILL, &il->status);
} else {
clear_bit(S_RFKILL, &il->status);
il_force_reset(il, true);
}
wiphy_rfkill_set_hw_state(il->hw->wiphy, hw_rf_kill);
handled |= CSR_INT_BIT_RF_KILL;
}
/* Chip got too hot and stopped itself */
if (inta & CSR_INT_BIT_CT_KILL) {
IL_ERR("Microcode CT kill error detected.\n");
il->isr_stats.ctkill++;
handled |= CSR_INT_BIT_CT_KILL;
}
/* Error detected by uCode */
if (inta & CSR_INT_BIT_SW_ERR) {
IL_ERR("Microcode SW error detected. " " Restarting 0x%X.\n",
inta);
il->isr_stats.sw++;
il_irq_handle_error(il);
handled |= CSR_INT_BIT_SW_ERR;
}
/*
* uCode wakes up after power-down sleep.
* Tell device about any new tx or host commands enqueued,
* and about any Rx buffers made available while asleep.
*/
if (inta & CSR_INT_BIT_WAKEUP) {
D_ISR("Wakeup interrupt\n");
il_rx_queue_update_write_ptr(il, &il->rxq);
for (i = 0; i < il->hw_params.max_txq_num; i++)
il_txq_update_write_ptr(il, &il->txq[i]);
il->isr_stats.wakeup++;
handled |= CSR_INT_BIT_WAKEUP;
}
/* All uCode command responses, including Tx command responses,
* Rx "responses" (frame-received notification), and other
* notifications from uCode come through here*/
if (inta & (CSR_INT_BIT_FH_RX | CSR_INT_BIT_SW_RX)) {
il4965_rx_handle(il);
il->isr_stats.rx++;
handled |= (CSR_INT_BIT_FH_RX | CSR_INT_BIT_SW_RX);
}
/* This "Tx" DMA channel is used only for loading uCode */
if (inta & CSR_INT_BIT_FH_TX) {
D_ISR("uCode load interrupt\n");
il->isr_stats.tx++;
handled |= CSR_INT_BIT_FH_TX;
/* Wake up uCode load routine, now that load is complete */
il->ucode_write_complete = 1;
wake_up(&il->wait_command_queue);
}
if (inta & ~handled) {
IL_ERR("Unhandled INTA bits 0x%08x\n", inta & ~handled);
il->isr_stats.unhandled++;
}
if (inta & ~(il->inta_mask)) {
IL_WARN("Disabled INTA bits 0x%08x were pending\n",
inta & ~il->inta_mask);
IL_WARN(" with FH49_INT = 0x%08x\n", inta_fh);
}
/* Re-enable all interrupts */
/* only Re-enable if disabled by irq */
if (test_bit(S_INT_ENABLED, &il->status))
il_enable_interrupts(il);
/* Re-enable RF_KILL if it occurred */
else if (handled & CSR_INT_BIT_RF_KILL)
il_enable_rfkill_int(il);
#ifdef CONFIG_IWLEGACY_DEBUG
if (il_get_debug_level(il) & (IL_DL_ISR)) {
inta = _il_rd(il, CSR_INT);
inta_mask = _il_rd(il, CSR_INT_MASK);
inta_fh = _il_rd(il, CSR_FH_INT_STATUS);
D_ISR("End inta 0x%08x, enabled 0x%08x, fh 0x%08x, "
"flags 0x%08lx\n", inta, inta_mask, inta_fh, flags);
}
#endif
}
/*****************************************************************************
*
* sysfs attributes
*
*****************************************************************************/
#ifdef CONFIG_IWLEGACY_DEBUG
/*
* The following adds a new attribute to the sysfs representation
* of this device driver (i.e. a new file in /sys/class/net/wlan0/device/)
* used for controlling the debug level.
*
* See the level definitions in iwl for details.
*
* The debug_level being managed using sysfs below is a per device debug
* level that is used instead of the global debug level if it (the per
* device debug level) is set.
*/
static ssize_t
il4965_show_debug_level(struct device *d, struct device_attribute *attr,
char *buf)
{
struct il_priv *il = dev_get_drvdata(d);
return sprintf(buf, "0x%08X\n", il_get_debug_level(il));
}
static ssize_t
il4965_store_debug_level(struct device *d, struct device_attribute *attr,
const char *buf, size_t count)
{
struct il_priv *il = dev_get_drvdata(d);
unsigned long val;
int ret;
ret = kstrtoul(buf, 0, &val);
if (ret)
IL_ERR("%s is not in hex or decimal form.\n", buf);
else
il->debug_level = val;
return strnlen(buf, count);
}
static DEVICE_ATTR(debug_level, S_IWUSR | S_IRUGO, il4965_show_debug_level,
il4965_store_debug_level);
#endif /* CONFIG_IWLEGACY_DEBUG */
static ssize_t
il4965_show_temperature(struct device *d, struct device_attribute *attr,
char *buf)
{
struct il_priv *il = dev_get_drvdata(d);
if (!il_is_alive(il))
return -EAGAIN;
return sprintf(buf, "%d\n", il->temperature);
}
static DEVICE_ATTR(temperature, S_IRUGO, il4965_show_temperature, NULL);
static ssize_t
il4965_show_tx_power(struct device *d, struct device_attribute *attr, char *buf)
{
struct il_priv *il = dev_get_drvdata(d);
if (!il_is_ready_rf(il))
return sprintf(buf, "off\n");
else
return sprintf(buf, "%d\n", il->tx_power_user_lmt);
}
static ssize_t
il4965_store_tx_power(struct device *d, struct device_attribute *attr,
const char *buf, size_t count)
{
struct il_priv *il = dev_get_drvdata(d);
unsigned long val;
int ret;
ret = kstrtoul(buf, 10, &val);
if (ret)
IL_INFO("%s is not in decimal form.\n", buf);
else {
ret = il_set_tx_power(il, val, false);
if (ret)
IL_ERR("failed setting tx power (0x%08x).\n", ret);
else
ret = count;
}
return ret;
}
static DEVICE_ATTR(tx_power, S_IWUSR | S_IRUGO, il4965_show_tx_power,
il4965_store_tx_power);
static struct attribute *il_sysfs_entries[] = {
&dev_attr_temperature.attr,
&dev_attr_tx_power.attr,
#ifdef CONFIG_IWLEGACY_DEBUG
&dev_attr_debug_level.attr,
#endif
NULL
};
static struct attribute_group il_attribute_group = {
.name = NULL, /* put in device directory */
.attrs = il_sysfs_entries,
};
/******************************************************************************
*
* uCode download functions
*
******************************************************************************/
static void
il4965_dealloc_ucode_pci(struct il_priv *il)
{
il_free_fw_desc(il->pci_dev, &il->ucode_code);
il_free_fw_desc(il->pci_dev, &il->ucode_data);
il_free_fw_desc(il->pci_dev, &il->ucode_data_backup);
il_free_fw_desc(il->pci_dev, &il->ucode_init);
il_free_fw_desc(il->pci_dev, &il->ucode_init_data);
il_free_fw_desc(il->pci_dev, &il->ucode_boot);
}
static void
il4965_nic_start(struct il_priv *il)
{
/* Remove all resets to allow NIC to operate */
_il_wr(il, CSR_RESET, 0);
}
static void il4965_ucode_callback(const struct firmware *ucode_raw,
void *context);
static int il4965_mac_setup_register(struct il_priv *il, u32 max_probe_length);
static int __must_check
il4965_request_firmware(struct il_priv *il, bool first)
{
const char *name_pre = il->cfg->fw_name_pre;
char tag[8];
if (first) {
il->fw_idx = il->cfg->ucode_api_max;
sprintf(tag, "%d", il->fw_idx);
} else {
il->fw_idx--;
sprintf(tag, "%d", il->fw_idx);
}
if (il->fw_idx < il->cfg->ucode_api_min) {
IL_ERR("no suitable firmware found!\n");
return -ENOENT;
}
sprintf(il->firmware_name, "%s%s%s", name_pre, tag, ".ucode");
D_INFO("attempting to load firmware '%s'\n", il->firmware_name);
return request_firmware_nowait(THIS_MODULE, 1, il->firmware_name,
&il->pci_dev->dev, GFP_KERNEL, il,
il4965_ucode_callback);
}
struct il4965_firmware_pieces {
const void *inst, *data, *init, *init_data, *boot;
size_t inst_size, data_size, init_size, init_data_size, boot_size;
};
static int
il4965_load_firmware(struct il_priv *il, const struct firmware *ucode_raw,
struct il4965_firmware_pieces *pieces)
{
struct il_ucode_header *ucode = (void *)ucode_raw->data;
u32 api_ver, hdr_size;
const u8 *src;
il->ucode_ver = le32_to_cpu(ucode->ver);
api_ver = IL_UCODE_API(il->ucode_ver);
switch (api_ver) {
default:
case 0:
case 1:
case 2:
hdr_size = 24;
if (ucode_raw->size < hdr_size) {
IL_ERR("File size too small!\n");
return -EINVAL;
}
pieces->inst_size = le32_to_cpu(ucode->v1.inst_size);
pieces->data_size = le32_to_cpu(ucode->v1.data_size);
pieces->init_size = le32_to_cpu(ucode->v1.init_size);
pieces->init_data_size = le32_to_cpu(ucode->v1.init_data_size);
pieces->boot_size = le32_to_cpu(ucode->v1.boot_size);
src = ucode->v1.data;
break;
}
/* Verify size of file vs. image size info in file's header */
if (ucode_raw->size !=
hdr_size + pieces->inst_size + pieces->data_size +
pieces->init_size + pieces->init_data_size + pieces->boot_size) {
IL_ERR("uCode file size %d does not match expected size\n",
(int)ucode_raw->size);
return -EINVAL;
}
pieces->inst = src;
src += pieces->inst_size;
pieces->data = src;
src += pieces->data_size;
pieces->init = src;
src += pieces->init_size;
pieces->init_data = src;
src += pieces->init_data_size;
pieces->boot = src;
src += pieces->boot_size;
return 0;
}
/**
* il4965_ucode_callback - callback when firmware was loaded
*
* If loaded successfully, copies the firmware into buffers
* for the card to fetch (via DMA).
*/
static void
il4965_ucode_callback(const struct firmware *ucode_raw, void *context)
{
struct il_priv *il = context;
struct il_ucode_header *ucode;
int err;
struct il4965_firmware_pieces pieces;
const unsigned int api_max = il->cfg->ucode_api_max;
const unsigned int api_min = il->cfg->ucode_api_min;
u32 api_ver;
u32 max_probe_length = 200;
u32 standard_phy_calibration_size =
IL_DEFAULT_STANDARD_PHY_CALIBRATE_TBL_SIZE;
memset(&pieces, 0, sizeof(pieces));
if (!ucode_raw) {
if (il->fw_idx <= il->cfg->ucode_api_max)
IL_ERR("request for firmware file '%s' failed.\n",
il->firmware_name);
goto try_again;
}
D_INFO("Loaded firmware file '%s' (%zd bytes).\n", il->firmware_name,
ucode_raw->size);
/* Make sure that we got at least the API version number */
if (ucode_raw->size < 4) {
IL_ERR("File size way too small!\n");
goto try_again;
}
/* Data from ucode file: header followed by uCode images */
ucode = (struct il_ucode_header *)ucode_raw->data;
err = il4965_load_firmware(il, ucode_raw, &pieces);
if (err)
goto try_again;
api_ver = IL_UCODE_API(il->ucode_ver);
/*
* api_ver should match the api version forming part of the
* firmware filename ... but we don't check for that and only rely
* on the API version read from firmware header from here on forward
*/
if (api_ver < api_min || api_ver > api_max) {
IL_ERR("Driver unable to support your firmware API. "
"Driver supports v%u, firmware is v%u.\n", api_max,
api_ver);
goto try_again;
}
if (api_ver != api_max)
IL_ERR("Firmware has old API version. Expected v%u, "
"got v%u. New firmware can be obtained "
"from http://www.intellinuxwireless.org.\n", api_max,
api_ver);
IL_INFO("loaded firmware version %u.%u.%u.%u\n",
IL_UCODE_MAJOR(il->ucode_ver), IL_UCODE_MINOR(il->ucode_ver),
IL_UCODE_API(il->ucode_ver), IL_UCODE_SERIAL(il->ucode_ver));
snprintf(il->hw->wiphy->fw_version, sizeof(il->hw->wiphy->fw_version),
"%u.%u.%u.%u", IL_UCODE_MAJOR(il->ucode_ver),
IL_UCODE_MINOR(il->ucode_ver), IL_UCODE_API(il->ucode_ver),
IL_UCODE_SERIAL(il->ucode_ver));
/*
* For any of the failures below (before allocating pci memory)
* we will try to load a version with a smaller API -- maybe the
* user just got a corrupted version of the latest API.
*/
D_INFO("f/w package hdr ucode version raw = 0x%x\n", il->ucode_ver);
D_INFO("f/w package hdr runtime inst size = %Zd\n", pieces.inst_size);
D_INFO("f/w package hdr runtime data size = %Zd\n", pieces.data_size);
D_INFO("f/w package hdr init inst size = %Zd\n", pieces.init_size);
D_INFO("f/w package hdr init data size = %Zd\n", pieces.init_data_size);
D_INFO("f/w package hdr boot inst size = %Zd\n", pieces.boot_size);
/* Verify that uCode images will fit in card's SRAM */
if (pieces.inst_size > il->hw_params.max_inst_size) {
IL_ERR("uCode instr len %Zd too large to fit in\n",
pieces.inst_size);
goto try_again;
}
if (pieces.data_size > il->hw_params.max_data_size) {
IL_ERR("uCode data len %Zd too large to fit in\n",
pieces.data_size);
goto try_again;
}
if (pieces.init_size > il->hw_params.max_inst_size) {
IL_ERR("uCode init instr len %Zd too large to fit in\n",
pieces.init_size);
goto try_again;
}
if (pieces.init_data_size > il->hw_params.max_data_size) {
IL_ERR("uCode init data len %Zd too large to fit in\n",
pieces.init_data_size);
goto try_again;
}
if (pieces.boot_size > il->hw_params.max_bsm_size) {
IL_ERR("uCode boot instr len %Zd too large to fit in\n",
pieces.boot_size);
goto try_again;
}
/* Allocate ucode buffers for card's bus-master loading ... */
/* Runtime instructions and 2 copies of data:
* 1) unmodified from disk
* 2) backup cache for save/restore during power-downs */
il->ucode_code.len = pieces.inst_size;
il_alloc_fw_desc(il->pci_dev, &il->ucode_code);
il->ucode_data.len = pieces.data_size;
il_alloc_fw_desc(il->pci_dev, &il->ucode_data);
il->ucode_data_backup.len = pieces.data_size;
il_alloc_fw_desc(il->pci_dev, &il->ucode_data_backup);
if (!il->ucode_code.v_addr || !il->ucode_data.v_addr ||
!il->ucode_data_backup.v_addr)
goto err_pci_alloc;
/* Initialization instructions and data */
if (pieces.init_size && pieces.init_data_size) {
il->ucode_init.len = pieces.init_size;
il_alloc_fw_desc(il->pci_dev, &il->ucode_init);
il->ucode_init_data.len = pieces.init_data_size;
il_alloc_fw_desc(il->pci_dev, &il->ucode_init_data);
if (!il->ucode_init.v_addr || !il->ucode_init_data.v_addr)
goto err_pci_alloc;
}
/* Bootstrap (instructions only, no data) */
if (pieces.boot_size) {
il->ucode_boot.len = pieces.boot_size;
il_alloc_fw_desc(il->pci_dev, &il->ucode_boot);
if (!il->ucode_boot.v_addr)
goto err_pci_alloc;
}
/* Now that we can no longer fail, copy information */
il->sta_key_max_num = STA_KEY_MAX_NUM;
/* Copy images into buffers for card's bus-master reads ... */
/* Runtime instructions (first block of data in file) */
D_INFO("Copying (but not loading) uCode instr len %Zd\n",
pieces.inst_size);
memcpy(il->ucode_code.v_addr, pieces.inst, pieces.inst_size);
D_INFO("uCode instr buf vaddr = 0x%p, paddr = 0x%08x\n",
il->ucode_code.v_addr, (u32) il->ucode_code.p_addr);
/*
* Runtime data
* NOTE: Copy into backup buffer will be done in il_up()
*/
D_INFO("Copying (but not loading) uCode data len %Zd\n",
pieces.data_size);
memcpy(il->ucode_data.v_addr, pieces.data, pieces.data_size);
memcpy(il->ucode_data_backup.v_addr, pieces.data, pieces.data_size);
/* Initialization instructions */
if (pieces.init_size) {
D_INFO("Copying (but not loading) init instr len %Zd\n",
pieces.init_size);
memcpy(il->ucode_init.v_addr, pieces.init, pieces.init_size);
}
/* Initialization data */
if (pieces.init_data_size) {
D_INFO("Copying (but not loading) init data len %Zd\n",
pieces.init_data_size);
memcpy(il->ucode_init_data.v_addr, pieces.init_data,
pieces.init_data_size);
}
/* Bootstrap instructions */
D_INFO("Copying (but not loading) boot instr len %Zd\n",
pieces.boot_size);
memcpy(il->ucode_boot.v_addr, pieces.boot, pieces.boot_size);
/*
* figure out the offset of chain noise reset and gain commands
* base on the size of standard phy calibration commands table size
*/
il->_4965.phy_calib_chain_noise_reset_cmd =
standard_phy_calibration_size;
il->_4965.phy_calib_chain_noise_gain_cmd =
standard_phy_calibration_size + 1;
/**************************************************
* This is still part of probe() in a sense...
*
* 9. Setup and register with mac80211 and debugfs
**************************************************/
err = il4965_mac_setup_register(il, max_probe_length);
if (err)
goto out_unbind;
err = il_dbgfs_register(il, DRV_NAME);
if (err)
IL_ERR("failed to create debugfs files. Ignoring error: %d\n",
err);
err = sysfs_create_group(&il->pci_dev->dev.kobj, &il_attribute_group);
if (err) {
IL_ERR("failed to create sysfs device attributes\n");
goto out_unbind;
}
/* We have our copies now, allow OS release its copies */
release_firmware(ucode_raw);
complete(&il->_4965.firmware_loading_complete);
return;
try_again:
/* try next, if any */
if (il4965_request_firmware(il, false))
goto out_unbind;
release_firmware(ucode_raw);
return;
err_pci_alloc:
IL_ERR("failed to allocate pci memory\n");
il4965_dealloc_ucode_pci(il);
out_unbind:
complete(&il->_4965.firmware_loading_complete);
device_release_driver(&il->pci_dev->dev);
release_firmware(ucode_raw);
}
static const char *const desc_lookup_text[] = {
"OK",
"FAIL",
"BAD_PARAM",
"BAD_CHECKSUM",
"NMI_INTERRUPT_WDG",
"SYSASSERT",
"FATAL_ERROR",
"BAD_COMMAND",
"HW_ERROR_TUNE_LOCK",
"HW_ERROR_TEMPERATURE",
"ILLEGAL_CHAN_FREQ",
"VCC_NOT_STBL",
"FH49_ERROR",
"NMI_INTERRUPT_HOST",
"NMI_INTERRUPT_ACTION_PT",
"NMI_INTERRUPT_UNKNOWN",
"UCODE_VERSION_MISMATCH",
"HW_ERROR_ABS_LOCK",
"HW_ERROR_CAL_LOCK_FAIL",
"NMI_INTERRUPT_INST_ACTION_PT",
"NMI_INTERRUPT_DATA_ACTION_PT",
"NMI_TRM_HW_ER",
"NMI_INTERRUPT_TRM",
"NMI_INTERRUPT_BREAK_POINT",
"DEBUG_0",
"DEBUG_1",
"DEBUG_2",
"DEBUG_3",
};
static struct {
char *name;
u8 num;
} advanced_lookup[] = {
{
"NMI_INTERRUPT_WDG", 0x34}, {
"SYSASSERT", 0x35}, {
"UCODE_VERSION_MISMATCH", 0x37}, {
"BAD_COMMAND", 0x38}, {
"NMI_INTERRUPT_DATA_ACTION_PT", 0x3C}, {
"FATAL_ERROR", 0x3D}, {
"NMI_TRM_HW_ERR", 0x46}, {
"NMI_INTERRUPT_TRM", 0x4C}, {
"NMI_INTERRUPT_BREAK_POINT", 0x54}, {
"NMI_INTERRUPT_WDG_RXF_FULL", 0x5C}, {
"NMI_INTERRUPT_WDG_NO_RBD_RXF_FULL", 0x64}, {
"NMI_INTERRUPT_HOST", 0x66}, {
"NMI_INTERRUPT_ACTION_PT", 0x7C}, {
"NMI_INTERRUPT_UNKNOWN", 0x84}, {
"NMI_INTERRUPT_INST_ACTION_PT", 0x86}, {
"ADVANCED_SYSASSERT", 0},};
static const char *
il4965_desc_lookup(u32 num)
{
int i;
int max = ARRAY_SIZE(desc_lookup_text);
if (num < max)
return desc_lookup_text[num];
max = ARRAY_SIZE(advanced_lookup) - 1;
for (i = 0; i < max; i++) {
if (advanced_lookup[i].num == num)
break;
}
return advanced_lookup[i].name;
}
#define ERROR_START_OFFSET (1 * sizeof(u32))
#define ERROR_ELEM_SIZE (7 * sizeof(u32))
void
il4965_dump_nic_error_log(struct il_priv *il)
{
u32 data2, line;
u32 desc, time, count, base, data1;
u32 blink1, blink2, ilink1, ilink2;
u32 pc, hcmd;
if (il->ucode_type == UCODE_INIT)
base = le32_to_cpu(il->card_alive_init.error_event_table_ptr);
else
base = le32_to_cpu(il->card_alive.error_event_table_ptr);
if (!il->ops->is_valid_rtc_data_addr(base)) {
IL_ERR("Not valid error log pointer 0x%08X for %s uCode\n",
base, (il->ucode_type == UCODE_INIT) ? "Init" : "RT");
return;
}
count = il_read_targ_mem(il, base);
if (ERROR_START_OFFSET <= count * ERROR_ELEM_SIZE) {
IL_ERR("Start IWL Error Log Dump:\n");
IL_ERR("Status: 0x%08lX, count: %d\n", il->status, count);
}
desc = il_read_targ_mem(il, base + 1 * sizeof(u32));
il->isr_stats.err_code = desc;
pc = il_read_targ_mem(il, base + 2 * sizeof(u32));
blink1 = il_read_targ_mem(il, base + 3 * sizeof(u32));
blink2 = il_read_targ_mem(il, base + 4 * sizeof(u32));
ilink1 = il_read_targ_mem(il, base + 5 * sizeof(u32));
ilink2 = il_read_targ_mem(il, base + 6 * sizeof(u32));
data1 = il_read_targ_mem(il, base + 7 * sizeof(u32));
data2 = il_read_targ_mem(il, base + 8 * sizeof(u32));
line = il_read_targ_mem(il, base + 9 * sizeof(u32));
time = il_read_targ_mem(il, base + 11 * sizeof(u32));
hcmd = il_read_targ_mem(il, base + 22 * sizeof(u32));
IL_ERR("Desc Time "
"data1 data2 line\n");
IL_ERR("%-28s (0x%04X) %010u 0x%08X 0x%08X %u\n",
il4965_desc_lookup(desc), desc, time, data1, data2, line);
IL_ERR("pc blink1 blink2 ilink1 ilink2 hcmd\n");
IL_ERR("0x%05X 0x%05X 0x%05X 0x%05X 0x%05X 0x%05X\n", pc, blink1,
blink2, ilink1, ilink2, hcmd);
}
static void
il4965_rf_kill_ct_config(struct il_priv *il)
{
struct il_ct_kill_config cmd;
unsigned long flags;
int ret = 0;
spin_lock_irqsave(&il->lock, flags);
_il_wr(il, CSR_UCODE_DRV_GP1_CLR,
CSR_UCODE_DRV_GP1_REG_BIT_CT_KILL_EXIT);
spin_unlock_irqrestore(&il->lock, flags);
cmd.critical_temperature_R =
cpu_to_le32(il->hw_params.ct_kill_threshold);
ret = il_send_cmd_pdu(il, C_CT_KILL_CONFIG, sizeof(cmd), &cmd);
if (ret)
IL_ERR("C_CT_KILL_CONFIG failed\n");
else
D_INFO("C_CT_KILL_CONFIG " "succeeded, "
"critical temperature is %d\n",
il->hw_params.ct_kill_threshold);
}
static const s8 default_queue_to_tx_fifo[] = {
IL_TX_FIFO_VO,
IL_TX_FIFO_VI,
IL_TX_FIFO_BE,
IL_TX_FIFO_BK,
IL49_CMD_FIFO_NUM,
IL_TX_FIFO_UNUSED,
IL_TX_FIFO_UNUSED,
};
#define IL_MASK(lo, hi) ((1 << (hi)) | ((1 << (hi)) - (1 << (lo))))
static int
il4965_alive_notify(struct il_priv *il)
{
u32 a;
unsigned long flags;
int i, chan;
u32 reg_val;
spin_lock_irqsave(&il->lock, flags);
/* Clear 4965's internal Tx Scheduler data base */
il->scd_base_addr = il_rd_prph(il, IL49_SCD_SRAM_BASE_ADDR);
a = il->scd_base_addr + IL49_SCD_CONTEXT_DATA_OFFSET;
for (; a < il->scd_base_addr + IL49_SCD_TX_STTS_BITMAP_OFFSET; a += 4)
il_write_targ_mem(il, a, 0);
for (; a < il->scd_base_addr + IL49_SCD_TRANSLATE_TBL_OFFSET; a += 4)
il_write_targ_mem(il, a, 0);
for (;
a <
il->scd_base_addr +
IL49_SCD_TRANSLATE_TBL_OFFSET_QUEUE(il->hw_params.max_txq_num);
a += 4)
il_write_targ_mem(il, a, 0);
/* Tel 4965 where to find Tx byte count tables */
il_wr_prph(il, IL49_SCD_DRAM_BASE_ADDR, il->scd_bc_tbls.dma >> 10);
/* Enable DMA channel */
for (chan = 0; chan < FH49_TCSR_CHNL_NUM; chan++)
il_wr(il, FH49_TCSR_CHNL_TX_CONFIG_REG(chan),
FH49_TCSR_TX_CONFIG_REG_VAL_DMA_CHNL_ENABLE |
FH49_TCSR_TX_CONFIG_REG_VAL_DMA_CREDIT_ENABLE);
/* Update FH chicken bits */
reg_val = il_rd(il, FH49_TX_CHICKEN_BITS_REG);
il_wr(il, FH49_TX_CHICKEN_BITS_REG,
reg_val | FH49_TX_CHICKEN_BITS_SCD_AUTO_RETRY_EN);
/* Disable chain mode for all queues */
il_wr_prph(il, IL49_SCD_QUEUECHAIN_SEL, 0);
/* Initialize each Tx queue (including the command queue) */
for (i = 0; i < il->hw_params.max_txq_num; i++) {
/* TFD circular buffer read/write idxes */
il_wr_prph(il, IL49_SCD_QUEUE_RDPTR(i), 0);
il_wr(il, HBUS_TARG_WRPTR, 0 | (i << 8));
/* Max Tx Window size for Scheduler-ACK mode */
il_write_targ_mem(il,
il->scd_base_addr +
IL49_SCD_CONTEXT_QUEUE_OFFSET(i),
(SCD_WIN_SIZE <<
IL49_SCD_QUEUE_CTX_REG1_WIN_SIZE_POS) &
IL49_SCD_QUEUE_CTX_REG1_WIN_SIZE_MSK);
/* Frame limit */
il_write_targ_mem(il,
il->scd_base_addr +
IL49_SCD_CONTEXT_QUEUE_OFFSET(i) +
sizeof(u32),
(SCD_FRAME_LIMIT <<
IL49_SCD_QUEUE_CTX_REG2_FRAME_LIMIT_POS) &
IL49_SCD_QUEUE_CTX_REG2_FRAME_LIMIT_MSK);
}
il_wr_prph(il, IL49_SCD_INTERRUPT_MASK,
(1 << il->hw_params.max_txq_num) - 1);
/* Activate all Tx DMA/FIFO channels */
il4965_txq_set_sched(il, IL_MASK(0, 6));
il4965_set_wr_ptrs(il, IL_DEFAULT_CMD_QUEUE_NUM, 0);
/* make sure all queue are not stopped */
memset(&il->queue_stopped[0], 0, sizeof(il->queue_stopped));
for (i = 0; i < 4; i++)
atomic_set(&il->queue_stop_count[i], 0);
/* reset to 0 to enable all the queue first */
il->txq_ctx_active_msk = 0;
/* Map each Tx/cmd queue to its corresponding fifo */
BUILD_BUG_ON(ARRAY_SIZE(default_queue_to_tx_fifo) != 7);
for (i = 0; i < ARRAY_SIZE(default_queue_to_tx_fifo); i++) {
int ac = default_queue_to_tx_fifo[i];
il_txq_ctx_activate(il, i);
if (ac == IL_TX_FIFO_UNUSED)
continue;
il4965_tx_queue_set_status(il, &il->txq[i], ac, 0);
}
spin_unlock_irqrestore(&il->lock, flags);
return 0;
}
/**
* il4965_alive_start - called after N_ALIVE notification received
* from protocol/runtime uCode (initialization uCode's
* Alive gets handled by il_init_alive_start()).
*/
static void
il4965_alive_start(struct il_priv *il)
{
int ret = 0;
D_INFO("Runtime Alive received.\n");
if (il->card_alive.is_valid != UCODE_VALID_OK) {
/* We had an error bringing up the hardware, so take it
* all the way back down so we can try again */
D_INFO("Alive failed.\n");
goto restart;
}
/* Initialize uCode has loaded Runtime uCode ... verify inst image.
* This is a paranoid check, because we would not have gotten the
* "runtime" alive if code weren't properly loaded. */
if (il4965_verify_ucode(il)) {
/* Runtime instruction load was bad;
* take it all the way back down so we can try again */
D_INFO("Bad runtime uCode load.\n");
goto restart;
}
ret = il4965_alive_notify(il);
if (ret) {
IL_WARN("Could not complete ALIVE transition [ntf]: %d\n", ret);
goto restart;
}
/* After the ALIVE response, we can send host commands to the uCode */
set_bit(S_ALIVE, &il->status);
/* Enable watchdog to monitor the driver tx queues */
il_setup_watchdog(il);
if (il_is_rfkill(il))
return;
ieee80211_wake_queues(il->hw);
il->active_rate = RATES_MASK;
il_power_update_mode(il, true);
D_INFO("Updated power mode\n");
if (il_is_associated(il)) {
struct il_rxon_cmd *active_rxon =
(struct il_rxon_cmd *)&il->active;
/* apply any changes in staging */
il->staging.filter_flags |= RXON_FILTER_ASSOC_MSK;
active_rxon->filter_flags &= ~RXON_FILTER_ASSOC_MSK;
} else {
/* Initialize our rx_config data */
il_connection_init_rx_config(il);
if (il->ops->set_rxon_chain)
il->ops->set_rxon_chain(il);
}
/* Configure bluetooth coexistence if enabled */
il_send_bt_config(il);
il4965_reset_run_time_calib(il);
set_bit(S_READY, &il->status);
/* Configure the adapter for unassociated operation */
il_commit_rxon(il);
/* At this point, the NIC is initialized and operational */
il4965_rf_kill_ct_config(il);
D_INFO("ALIVE processing complete.\n");
wake_up(&il->wait_command_queue);
return;
restart:
queue_work(il->workqueue, &il->restart);
}
static void il4965_cancel_deferred_work(struct il_priv *il);
static void
__il4965_down(struct il_priv *il)
{
unsigned long flags;
int exit_pending;
D_INFO(DRV_NAME " is going down\n");
il_scan_cancel_timeout(il, 200);
exit_pending = test_and_set_bit(S_EXIT_PENDING, &il->status);
/* Stop TX queues watchdog. We need to have S_EXIT_PENDING bit set
* to prevent rearm timer */
del_timer_sync(&il->watchdog);
il_clear_ucode_stations(il);
/* FIXME: race conditions ? */
spin_lock_irq(&il->sta_lock);
/*
* Remove all key information that is not stored as part
* of station information since mac80211 may not have had
* a chance to remove all the keys. When device is
* reconfigured by mac80211 after an error all keys will
* be reconfigured.
*/
memset(il->_4965.wep_keys, 0, sizeof(il->_4965.wep_keys));
il->_4965.key_mapping_keys = 0;
spin_unlock_irq(&il->sta_lock);
il_dealloc_bcast_stations(il);
il_clear_driver_stations(il);
/* Unblock any waiting calls */
wake_up_all(&il->wait_command_queue);
/* Wipe out the EXIT_PENDING status bit if we are not actually
* exiting the module */
if (!exit_pending)
clear_bit(S_EXIT_PENDING, &il->status);
/* stop and reset the on-board processor */
_il_wr(il, CSR_RESET, CSR_RESET_REG_FLAG_NEVO_RESET);
/* tell the device to stop sending interrupts */
spin_lock_irqsave(&il->lock, flags);
il_disable_interrupts(il);
spin_unlock_irqrestore(&il->lock, flags);
il4965_synchronize_irq(il);
if (il->mac80211_registered)
ieee80211_stop_queues(il->hw);
/* If we have not previously called il_init() then
* clear all bits but the RF Kill bit and return */
if (!il_is_init(il)) {
il->status =
test_bit(S_RFKILL, &il->status) << S_RFKILL |
test_bit(S_GEO_CONFIGURED, &il->status) << S_GEO_CONFIGURED |
test_bit(S_EXIT_PENDING, &il->status) << S_EXIT_PENDING;
goto exit;
}
/* ...otherwise clear out all the status bits but the RF Kill
* bit and continue taking the NIC down. */
il->status &=
test_bit(S_RFKILL, &il->status) << S_RFKILL |
test_bit(S_GEO_CONFIGURED, &il->status) << S_GEO_CONFIGURED |
test_bit(S_FW_ERROR, &il->status) << S_FW_ERROR |
test_bit(S_EXIT_PENDING, &il->status) << S_EXIT_PENDING;
/*
* We disabled and synchronized interrupt, and priv->mutex is taken, so
* here is the only thread which will program device registers, but
* still have lockdep assertions, so we are taking reg_lock.
*/
spin_lock_irq(&il->reg_lock);
/* FIXME: il_grab_nic_access if rfkill is off ? */
il4965_txq_ctx_stop(il);
il4965_rxq_stop(il);
/* Power-down device's busmaster DMA clocks */
_il_wr_prph(il, APMG_CLK_DIS_REG, APMG_CLK_VAL_DMA_CLK_RQT);
udelay(5);
/* Make sure (redundant) we've released our request to stay awake */
_il_clear_bit(il, CSR_GP_CNTRL, CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
/* Stop the device, and put it in low power state */
_il_apm_stop(il);
spin_unlock_irq(&il->reg_lock);
il4965_txq_ctx_unmap(il);
exit:
memset(&il->card_alive, 0, sizeof(struct il_alive_resp));
dev_kfree_skb(il->beacon_skb);
il->beacon_skb = NULL;
/* clear out any free frames */
il4965_clear_free_frames(il);
}
static void
il4965_down(struct il_priv *il)
{
mutex_lock(&il->mutex);
__il4965_down(il);
mutex_unlock(&il->mutex);
il4965_cancel_deferred_work(il);
}
static void
il4965_set_hw_ready(struct il_priv *il)
{
int ret;
il_set_bit(il, CSR_HW_IF_CONFIG_REG,
CSR_HW_IF_CONFIG_REG_BIT_NIC_READY);
/* See if we got it */
ret = _il_poll_bit(il, CSR_HW_IF_CONFIG_REG,
CSR_HW_IF_CONFIG_REG_BIT_NIC_READY,
CSR_HW_IF_CONFIG_REG_BIT_NIC_READY,
100);
if (ret >= 0)
il->hw_ready = true;
D_INFO("hardware %s ready\n", (il->hw_ready) ? "" : "not");
}
static void
il4965_prepare_card_hw(struct il_priv *il)
{
int ret;
il->hw_ready = false;
il4965_set_hw_ready(il);
if (il->hw_ready)
return;
/* If HW is not ready, prepare the conditions to check again */
il_set_bit(il, CSR_HW_IF_CONFIG_REG, CSR_HW_IF_CONFIG_REG_PREPARE);
ret =
_il_poll_bit(il, CSR_HW_IF_CONFIG_REG,
~CSR_HW_IF_CONFIG_REG_BIT_NIC_PREPARE_DONE,
CSR_HW_IF_CONFIG_REG_BIT_NIC_PREPARE_DONE, 150000);
/* HW should be ready by now, check again. */
if (ret != -ETIMEDOUT)
il4965_set_hw_ready(il);
}
#define MAX_HW_RESTARTS 5
static int
__il4965_up(struct il_priv *il)
{
int i;
int ret;
if (test_bit(S_EXIT_PENDING, &il->status)) {
IL_WARN("Exit pending; will not bring the NIC up\n");
return -EIO;
}
if (!il->ucode_data_backup.v_addr || !il->ucode_data.v_addr) {
IL_ERR("ucode not available for device bringup\n");
return -EIO;
}
ret = il4965_alloc_bcast_station(il);
if (ret) {
il_dealloc_bcast_stations(il);
return ret;
}
il4965_prepare_card_hw(il);
if (!il->hw_ready) {
IL_ERR("HW not ready\n");
return -EIO;
}
/* If platform's RF_KILL switch is NOT set to KILL */
if (_il_rd(il, CSR_GP_CNTRL) & CSR_GP_CNTRL_REG_FLAG_HW_RF_KILL_SW)
clear_bit(S_RFKILL, &il->status);
else {
set_bit(S_RFKILL, &il->status);
wiphy_rfkill_set_hw_state(il->hw->wiphy, true);
il_enable_rfkill_int(il);
IL_WARN("Radio disabled by HW RF Kill switch\n");
return 0;
}
_il_wr(il, CSR_INT, 0xFFFFFFFF);
/* must be initialised before il_hw_nic_init */
il->cmd_queue = IL_DEFAULT_CMD_QUEUE_NUM;
ret = il4965_hw_nic_init(il);
if (ret) {
IL_ERR("Unable to init nic\n");
return ret;
}
/* make sure rfkill handshake bits are cleared */
_il_wr(il, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
_il_wr(il, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_DRV_GP1_BIT_CMD_BLOCKED);
/* clear (again), then enable host interrupts */
_il_wr(il, CSR_INT, 0xFFFFFFFF);
il_enable_interrupts(il);
/* really make sure rfkill handshake bits are cleared */
_il_wr(il, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
_il_wr(il, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
/* Copy original ucode data image from disk into backup cache.
* This will be used to initialize the on-board processor's
* data SRAM for a clean start when the runtime program first loads. */
memcpy(il->ucode_data_backup.v_addr, il->ucode_data.v_addr,
il->ucode_data.len);
for (i = 0; i < MAX_HW_RESTARTS; i++) {
/* load bootstrap state machine,
* load bootstrap program into processor's memory,
* prepare to load the "initialize" uCode */
ret = il->ops->load_ucode(il);
if (ret) {
IL_ERR("Unable to set up bootstrap uCode: %d\n", ret);
continue;
}
/* start card; "initialize" will load runtime ucode */
il4965_nic_start(il);
D_INFO(DRV_NAME " is coming up\n");
return 0;
}
set_bit(S_EXIT_PENDING, &il->status);
__il4965_down(il);
clear_bit(S_EXIT_PENDING, &il->status);
/* tried to restart and config the device for as long as our
* patience could withstand */
IL_ERR("Unable to initialize device after %d attempts.\n", i);
return -EIO;
}
/*****************************************************************************
*
* Workqueue callbacks
*
*****************************************************************************/
static void
il4965_bg_init_alive_start(struct work_struct *data)
{
struct il_priv *il =
container_of(data, struct il_priv, init_alive_start.work);
mutex_lock(&il->mutex);
if (test_bit(S_EXIT_PENDING, &il->status))
goto out;
il->ops->init_alive_start(il);
out:
mutex_unlock(&il->mutex);
}
static void
il4965_bg_alive_start(struct work_struct *data)
{
struct il_priv *il =
container_of(data, struct il_priv, alive_start.work);
mutex_lock(&il->mutex);
if (test_bit(S_EXIT_PENDING, &il->status))
goto out;
il4965_alive_start(il);
out:
mutex_unlock(&il->mutex);
}
static void
il4965_bg_run_time_calib_work(struct work_struct *work)
{
struct il_priv *il = container_of(work, struct il_priv,
run_time_calib_work);
mutex_lock(&il->mutex);
if (test_bit(S_EXIT_PENDING, &il->status) ||
test_bit(S_SCANNING, &il->status)) {
mutex_unlock(&il->mutex);
return;
}
if (il->start_calib) {
il4965_chain_noise_calibration(il, (void *)&il->_4965.stats);
il4965_sensitivity_calibration(il, (void *)&il->_4965.stats);
}
mutex_unlock(&il->mutex);
}
static void
il4965_bg_restart(struct work_struct *data)
{
struct il_priv *il = container_of(data, struct il_priv, restart);
if (test_bit(S_EXIT_PENDING, &il->status))
return;
if (test_and_clear_bit(S_FW_ERROR, &il->status)) {
mutex_lock(&il->mutex);
il->is_open = 0;
__il4965_down(il);
mutex_unlock(&il->mutex);
il4965_cancel_deferred_work(il);
ieee80211_restart_hw(il->hw);
} else {
il4965_down(il);
mutex_lock(&il->mutex);
if (test_bit(S_EXIT_PENDING, &il->status)) {
mutex_unlock(&il->mutex);
return;
}
__il4965_up(il);
mutex_unlock(&il->mutex);
}
}
static void
il4965_bg_rx_replenish(struct work_struct *data)
{
struct il_priv *il = container_of(data, struct il_priv, rx_replenish);
if (test_bit(S_EXIT_PENDING, &il->status))
return;
mutex_lock(&il->mutex);
il4965_rx_replenish(il);
mutex_unlock(&il->mutex);
}
/*****************************************************************************
*
* mac80211 entry point functions
*
*****************************************************************************/
#define UCODE_READY_TIMEOUT (4 * HZ)
/*
* Not a mac80211 entry point function, but it fits in with all the
* other mac80211 functions grouped here.
*/
static int
il4965_mac_setup_register(struct il_priv *il, u32 max_probe_length)
{
int ret;
struct ieee80211_hw *hw = il->hw;
hw->rate_control_algorithm = "iwl-4965-rs";
/* Tell mac80211 our characteristics */
hw->flags =
IEEE80211_HW_SIGNAL_DBM | IEEE80211_HW_AMPDU_AGGREGATION |
IEEE80211_HW_NEED_DTIM_BEFORE_ASSOC | IEEE80211_HW_SPECTRUM_MGMT |
IEEE80211_HW_REPORTS_TX_ACK_STATUS | IEEE80211_HW_SUPPORTS_PS |
IEEE80211_HW_SUPPORTS_DYNAMIC_PS;
if (il->cfg->sku & IL_SKU_N)
hw->wiphy->features |= NL80211_FEATURE_DYNAMIC_SMPS |
NL80211_FEATURE_STATIC_SMPS;
hw->sta_data_size = sizeof(struct il_station_priv);
hw->vif_data_size = sizeof(struct il_vif_priv);
hw->wiphy->interface_modes =
BIT(NL80211_IFTYPE_STATION) | BIT(NL80211_IFTYPE_ADHOC);
hw->wiphy->flags |= WIPHY_FLAG_IBSS_RSN;
hw->wiphy->regulatory_flags |= REGULATORY_CUSTOM_REG |
REGULATORY_DISABLE_BEACON_HINTS;
/*
* For now, disable PS by default because it affects
* RX performance significantly.
*/
hw->wiphy->flags &= ~WIPHY_FLAG_PS_ON_BY_DEFAULT;
hw->wiphy->max_scan_ssids = PROBE_OPTION_MAX;
/* we create the 802.11 header and a zero-length SSID element */
hw->wiphy->max_scan_ie_len = max_probe_length - 24 - 2;
/* Default value; 4 EDCA QOS priorities */
hw->queues = 4;
hw->max_listen_interval = IL_CONN_MAX_LISTEN_INTERVAL;
if (il->bands[IEEE80211_BAND_2GHZ].n_channels)
il->hw->wiphy->bands[IEEE80211_BAND_2GHZ] =
&il->bands[IEEE80211_BAND_2GHZ];
if (il->bands[IEEE80211_BAND_5GHZ].n_channels)
il->hw->wiphy->bands[IEEE80211_BAND_5GHZ] =
&il->bands[IEEE80211_BAND_5GHZ];
il_leds_init(il);
ret = ieee80211_register_hw(il->hw);
if (ret) {
IL_ERR("Failed to register hw (error %d)\n", ret);
return ret;
}
il->mac80211_registered = 1;
return 0;
}
int
il4965_mac_start(struct ieee80211_hw *hw)
{
struct il_priv *il = hw->priv;
int ret;
D_MAC80211("enter\n");
/* we should be verifying the device is ready to be opened */
mutex_lock(&il->mutex);
ret = __il4965_up(il);
mutex_unlock(&il->mutex);
if (ret)
return ret;
if (il_is_rfkill(il))
goto out;
D_INFO("Start UP work done.\n");
/* Wait for START_ALIVE from Run Time ucode. Otherwise callbacks from
* mac80211 will not be run successfully. */
ret = wait_event_timeout(il->wait_command_queue,
test_bit(S_READY, &il->status),
UCODE_READY_TIMEOUT);
if (!ret) {
if (!test_bit(S_READY, &il->status)) {
IL_ERR("START_ALIVE timeout after %dms.\n",
jiffies_to_msecs(UCODE_READY_TIMEOUT));
return -ETIMEDOUT;
}
}
il4965_led_enable(il);
out:
il->is_open = 1;
D_MAC80211("leave\n");
return 0;
}
void
il4965_mac_stop(struct ieee80211_hw *hw)
{
struct il_priv *il = hw->priv;
D_MAC80211("enter\n");
if (!il->is_open)
return;
il->is_open = 0;
il4965_down(il);
flush_workqueue(il->workqueue);
/* User space software may expect getting rfkill changes
* even if interface is down */
_il_wr(il, CSR_INT, 0xFFFFFFFF);
il_enable_rfkill_int(il);
D_MAC80211("leave\n");
}
void
il4965_mac_tx(struct ieee80211_hw *hw,
struct ieee80211_tx_control *control,
struct sk_buff *skb)
{
struct il_priv *il = hw->priv;
D_MACDUMP("enter\n");
D_TX("dev->xmit(%d bytes) at rate 0x%02x\n", skb->len,
ieee80211_get_tx_rate(hw, IEEE80211_SKB_CB(skb))->bitrate);
if (il4965_tx_skb(il, control->sta, skb))
dev_kfree_skb_any(skb);
D_MACDUMP("leave\n");
}
void
il4965_mac_update_tkip_key(struct ieee80211_hw *hw, struct ieee80211_vif *vif,
struct ieee80211_key_conf *keyconf,
struct ieee80211_sta *sta, u32 iv32, u16 * phase1key)
{
struct il_priv *il = hw->priv;
D_MAC80211("enter\n");
il4965_update_tkip_key(il, keyconf, sta, iv32, phase1key);
D_MAC80211("leave\n");
}
int
il4965_mac_set_key(struct ieee80211_hw *hw, enum set_key_cmd cmd,
struct ieee80211_vif *vif, struct ieee80211_sta *sta,
struct ieee80211_key_conf *key)
{
struct il_priv *il = hw->priv;
int ret;
u8 sta_id;
bool is_default_wep_key = false;
D_MAC80211("enter\n");
if (il->cfg->mod_params->sw_crypto) {
D_MAC80211("leave - hwcrypto disabled\n");
return -EOPNOTSUPP;
}
/*
* To support IBSS RSN, don't program group keys in IBSS, the
* hardware will then not attempt to decrypt the frames.
*/
if (vif->type == NL80211_IFTYPE_ADHOC &&
!(key->flags & IEEE80211_KEY_FLAG_PAIRWISE)) {
D_MAC80211("leave - ad-hoc group key\n");
return -EOPNOTSUPP;
}
sta_id = il_sta_id_or_broadcast(il, sta);
if (sta_id == IL_INVALID_STATION)
return -EINVAL;
mutex_lock(&il->mutex);
il_scan_cancel_timeout(il, 100);
/*
* If we are getting WEP group key and we didn't receive any key mapping
* so far, we are in legacy wep mode (group key only), otherwise we are
* in 1X mode.
* In legacy wep mode, we use another host command to the uCode.
*/
if ((key->cipher == WLAN_CIPHER_SUITE_WEP40 ||
key->cipher == WLAN_CIPHER_SUITE_WEP104) && !sta) {
if (cmd == SET_KEY)
is_default_wep_key = !il->_4965.key_mapping_keys;
else
is_default_wep_key =
(key->hw_key_idx == HW_KEY_DEFAULT);
}
switch (cmd) {
case SET_KEY:
if (is_default_wep_key)
ret = il4965_set_default_wep_key(il, key);
else
ret = il4965_set_dynamic_key(il, key, sta_id);
D_MAC80211("enable hwcrypto key\n");
break;
case DISABLE_KEY:
if (is_default_wep_key)
ret = il4965_remove_default_wep_key(il, key);
else
ret = il4965_remove_dynamic_key(il, key, sta_id);
D_MAC80211("disable hwcrypto key\n");
break;
default:
ret = -EINVAL;
}
mutex_unlock(&il->mutex);
D_MAC80211("leave\n");
return ret;
}
int
il4965_mac_ampdu_action(struct ieee80211_hw *hw, struct ieee80211_vif *vif,
enum ieee80211_ampdu_mlme_action action,
struct ieee80211_sta *sta, u16 tid, u16 * ssn,
u8 buf_size)
{
struct il_priv *il = hw->priv;
int ret = -EINVAL;
D_HT("A-MPDU action on addr %pM tid %d\n", sta->addr, tid);
if (!(il->cfg->sku & IL_SKU_N))
return -EACCES;
mutex_lock(&il->mutex);
switch (action) {
case IEEE80211_AMPDU_RX_START:
D_HT("start Rx\n");
ret = il4965_sta_rx_agg_start(il, sta, tid, *ssn);
break;
case IEEE80211_AMPDU_RX_STOP:
D_HT("stop Rx\n");
ret = il4965_sta_rx_agg_stop(il, sta, tid);
if (test_bit(S_EXIT_PENDING, &il->status))
ret = 0;
break;
case IEEE80211_AMPDU_TX_START:
D_HT("start Tx\n");
ret = il4965_tx_agg_start(il, vif, sta, tid, ssn);
break;
case IEEE80211_AMPDU_TX_STOP_CONT:
case IEEE80211_AMPDU_TX_STOP_FLUSH:
case IEEE80211_AMPDU_TX_STOP_FLUSH_CONT:
D_HT("stop Tx\n");
ret = il4965_tx_agg_stop(il, vif, sta, tid);
if (test_bit(S_EXIT_PENDING, &il->status))
ret = 0;
break;
case IEEE80211_AMPDU_TX_OPERATIONAL:
ret = 0;
break;
}
mutex_unlock(&il->mutex);
return ret;
}
int
il4965_mac_sta_add(struct ieee80211_hw *hw, struct ieee80211_vif *vif,
struct ieee80211_sta *sta)
{
struct il_priv *il = hw->priv;
struct il_station_priv *sta_priv = (void *)sta->drv_priv;
bool is_ap = vif->type == NL80211_IFTYPE_STATION;
int ret;
u8 sta_id;
D_INFO("received request to add station %pM\n", sta->addr);
mutex_lock(&il->mutex);
D_INFO("proceeding to add station %pM\n", sta->addr);
sta_priv->common.sta_id = IL_INVALID_STATION;
atomic_set(&sta_priv->pending_frames, 0);
ret =
il_add_station_common(il, sta->addr, is_ap, sta, &sta_id);
if (ret) {
IL_ERR("Unable to add station %pM (%d)\n", sta->addr, ret);
/* Should we return success if return code is EEXIST ? */
mutex_unlock(&il->mutex);
return ret;
}
sta_priv->common.sta_id = sta_id;
/* Initialize rate scaling */
D_INFO("Initializing rate scaling for station %pM\n", sta->addr);
il4965_rs_rate_init(il, sta, sta_id);
mutex_unlock(&il->mutex);
return 0;
}
void
il4965_mac_channel_switch(struct ieee80211_hw *hw, struct ieee80211_vif *vif,
struct ieee80211_channel_switch *ch_switch)
{
struct il_priv *il = hw->priv;
const struct il_channel_info *ch_info;
struct ieee80211_conf *conf = &hw->conf;
struct ieee80211_channel *channel = ch_switch->chandef.chan;
struct il_ht_config *ht_conf = &il->current_ht_config;
u16 ch;
D_MAC80211("enter\n");
mutex_lock(&il->mutex);
if (il_is_rfkill(il))
goto out;
if (test_bit(S_EXIT_PENDING, &il->status) ||
test_bit(S_SCANNING, &il->status) ||
test_bit(S_CHANNEL_SWITCH_PENDING, &il->status))
goto out;
if (!il_is_associated(il))
goto out;
if (!il->ops->set_channel_switch)
goto out;
ch = channel->hw_value;
if (le16_to_cpu(il->active.channel) == ch)
goto out;
ch_info = il_get_channel_info(il, channel->band, ch);
if (!il_is_channel_valid(ch_info)) {
D_MAC80211("invalid channel\n");
goto out;
}
spin_lock_irq(&il->lock);
il->current_ht_config.smps = conf->smps_mode;
/* Configure HT40 channels */
switch (cfg80211_get_chandef_type(&ch_switch->chandef)) {
case NL80211_CHAN_NO_HT:
case NL80211_CHAN_HT20:
il->ht.is_40mhz = false;
il->ht.extension_chan_offset = IEEE80211_HT_PARAM_CHA_SEC_NONE;
break;
case NL80211_CHAN_HT40MINUS:
il->ht.extension_chan_offset = IEEE80211_HT_PARAM_CHA_SEC_BELOW;
il->ht.is_40mhz = true;
break;
case NL80211_CHAN_HT40PLUS:
il->ht.extension_chan_offset = IEEE80211_HT_PARAM_CHA_SEC_ABOVE;
il->ht.is_40mhz = true;
break;
}
if ((le16_to_cpu(il->staging.channel) != ch))
il->staging.flags = 0;
il_set_rxon_channel(il, channel);
il_set_rxon_ht(il, ht_conf);
il_set_flags_for_band(il, channel->band, il->vif);
spin_unlock_irq(&il->lock);
il_set_rate(il);
/*
* at this point, staging_rxon has the
* configuration for channel switch
*/
set_bit(S_CHANNEL_SWITCH_PENDING, &il->status);
il->switch_channel = cpu_to_le16(ch);
if (il->ops->set_channel_switch(il, ch_switch)) {
clear_bit(S_CHANNEL_SWITCH_PENDING, &il->status);
il->switch_channel = 0;
ieee80211_chswitch_done(il->vif, false);
}
out:
mutex_unlock(&il->mutex);
D_MAC80211("leave\n");
}
void
il4965_configure_filter(struct ieee80211_hw *hw, unsigned int changed_flags,
unsigned int *total_flags, u64 multicast)
{
struct il_priv *il = hw->priv;
__le32 filter_or = 0, filter_nand = 0;
#define CHK(test, flag) do { \
if (*total_flags & (test)) \
filter_or |= (flag); \
else \
filter_nand |= (flag); \
} while (0)
D_MAC80211("Enter: changed: 0x%x, total: 0x%x\n", changed_flags,
*total_flags);
CHK(FIF_OTHER_BSS | FIF_PROMISC_IN_BSS, RXON_FILTER_PROMISC_MSK);
/* Setting _just_ RXON_FILTER_CTL2HOST_MSK causes FH errors */
CHK(FIF_CONTROL, RXON_FILTER_CTL2HOST_MSK | RXON_FILTER_PROMISC_MSK);
CHK(FIF_BCN_PRBRESP_PROMISC, RXON_FILTER_BCON_AWARE_MSK);
#undef CHK
mutex_lock(&il->mutex);
il->staging.filter_flags &= ~filter_nand;
il->staging.filter_flags |= filter_or;
/*
* Not committing directly because hardware can perform a scan,
* but we'll eventually commit the filter flags change anyway.
*/
mutex_unlock(&il->mutex);
/*
* Receiving all multicast frames is always enabled by the
* default flags setup in il_connection_init_rx_config()
* since we currently do not support programming multicast
* filters into the device.
*/
*total_flags &=
FIF_OTHER_BSS | FIF_ALLMULTI | FIF_PROMISC_IN_BSS |
FIF_BCN_PRBRESP_PROMISC | FIF_CONTROL;
}
/*****************************************************************************
*
* driver setup and teardown
*
*****************************************************************************/
static void
il4965_bg_txpower_work(struct work_struct *work)
{
struct il_priv *il = container_of(work, struct il_priv,
txpower_work);
mutex_lock(&il->mutex);
/* If a scan happened to start before we got here
* then just return; the stats notification will
* kick off another scheduled work to compensate for
* any temperature delta we missed here. */
if (test_bit(S_EXIT_PENDING, &il->status) ||
test_bit(S_SCANNING, &il->status))
goto out;
/* Regardless of if we are associated, we must reconfigure the
* TX power since frames can be sent on non-radar channels while
* not associated */
il->ops->send_tx_power(il);
/* Update last_temperature to keep is_calib_needed from running
* when it isn't needed... */
il->last_temperature = il->temperature;
out:
mutex_unlock(&il->mutex);
}
static void
il4965_setup_deferred_work(struct il_priv *il)
{
il->workqueue = create_singlethread_workqueue(DRV_NAME);
init_waitqueue_head(&il->wait_command_queue);
INIT_WORK(&il->restart, il4965_bg_restart);
INIT_WORK(&il->rx_replenish, il4965_bg_rx_replenish);
INIT_WORK(&il->run_time_calib_work, il4965_bg_run_time_calib_work);
INIT_DELAYED_WORK(&il->init_alive_start, il4965_bg_init_alive_start);
INIT_DELAYED_WORK(&il->alive_start, il4965_bg_alive_start);
il_setup_scan_deferred_work(il);
INIT_WORK(&il->txpower_work, il4965_bg_txpower_work);
setup_timer(&il->stats_periodic, il4965_bg_stats_periodic,
(unsigned long)il);
setup_timer(&il->watchdog, il_bg_watchdog, (unsigned long)il);
tasklet_init(&il->irq_tasklet,
(void (*)(unsigned long))il4965_irq_tasklet,
(unsigned long)il);
}
static void
il4965_cancel_deferred_work(struct il_priv *il)
{
cancel_work_sync(&il->txpower_work);
cancel_delayed_work_sync(&il->init_alive_start);
cancel_delayed_work(&il->alive_start);
cancel_work_sync(&il->run_time_calib_work);
il_cancel_scan_deferred_work(il);
del_timer_sync(&il->stats_periodic);
}
static void
il4965_init_hw_rates(struct il_priv *il, struct ieee80211_rate *rates)
{
int i;
for (i = 0; i < RATE_COUNT_LEGACY; i++) {
rates[i].bitrate = il_rates[i].ieee * 5;
rates[i].hw_value = i; /* Rate scaling will work on idxes */
rates[i].hw_value_short = i;
rates[i].flags = 0;
if ((i >= IL_FIRST_CCK_RATE) && (i <= IL_LAST_CCK_RATE)) {
/*
* If CCK != 1M then set short preamble rate flag.
*/
rates[i].flags |=
(il_rates[i].plcp ==
RATE_1M_PLCP) ? 0 : IEEE80211_RATE_SHORT_PREAMBLE;
}
}
}
/*
* Acquire il->lock before calling this function !
*/
void
il4965_set_wr_ptrs(struct il_priv *il, int txq_id, u32 idx)
{
il_wr(il, HBUS_TARG_WRPTR, (idx & 0xff) | (txq_id << 8));
il_wr_prph(il, IL49_SCD_QUEUE_RDPTR(txq_id), idx);
}
void
il4965_tx_queue_set_status(struct il_priv *il, struct il_tx_queue *txq,
int tx_fifo_id, int scd_retry)
{
int txq_id = txq->q.id;
/* Find out whether to activate Tx queue */
int active = test_bit(txq_id, &il->txq_ctx_active_msk) ? 1 : 0;
/* Set up and activate */
il_wr_prph(il, IL49_SCD_QUEUE_STATUS_BITS(txq_id),
(active << IL49_SCD_QUEUE_STTS_REG_POS_ACTIVE) |
(tx_fifo_id << IL49_SCD_QUEUE_STTS_REG_POS_TXF) |
(scd_retry << IL49_SCD_QUEUE_STTS_REG_POS_WSL) |
(scd_retry << IL49_SCD_QUEUE_STTS_REG_POS_SCD_ACK) |
IL49_SCD_QUEUE_STTS_REG_MSK);
txq->sched_retry = scd_retry;
D_INFO("%s %s Queue %d on AC %d\n", active ? "Activate" : "Deactivate",
scd_retry ? "BA" : "AC", txq_id, tx_fifo_id);
}
static const struct ieee80211_ops il4965_mac_ops = {
.tx = il4965_mac_tx,
.start = il4965_mac_start,
.stop = il4965_mac_stop,
.add_interface = il_mac_add_interface,
.remove_interface = il_mac_remove_interface,
.change_interface = il_mac_change_interface,
.config = il_mac_config,
.configure_filter = il4965_configure_filter,
.set_key = il4965_mac_set_key,
.update_tkip_key = il4965_mac_update_tkip_key,
.conf_tx = il_mac_conf_tx,
.reset_tsf = il_mac_reset_tsf,
.bss_info_changed = il_mac_bss_info_changed,
.ampdu_action = il4965_mac_ampdu_action,
.hw_scan = il_mac_hw_scan,
.sta_add = il4965_mac_sta_add,
.sta_remove = il_mac_sta_remove,
.channel_switch = il4965_mac_channel_switch,
.tx_last_beacon = il_mac_tx_last_beacon,
.flush = il_mac_flush,
};
static int
il4965_init_drv(struct il_priv *il)
{
int ret;
spin_lock_init(&il->sta_lock);
spin_lock_init(&il->hcmd_lock);
INIT_LIST_HEAD(&il->free_frames);
mutex_init(&il->mutex);
il->ieee_channels = NULL;
il->ieee_rates = NULL;
il->band = IEEE80211_BAND_2GHZ;
il->iw_mode = NL80211_IFTYPE_STATION;
il->current_ht_config.smps = IEEE80211_SMPS_STATIC;
il->missed_beacon_threshold = IL_MISSED_BEACON_THRESHOLD_DEF;
/* initialize force reset */
il->force_reset.reset_duration = IL_DELAY_NEXT_FORCE_FW_RELOAD;
/* Choose which receivers/antennas to use */
if (il->ops->set_rxon_chain)
il->ops->set_rxon_chain(il);
il_init_scan_params(il);
ret = il_init_channel_map(il);
if (ret) {
IL_ERR("initializing regulatory failed: %d\n", ret);
goto err;
}
ret = il_init_geos(il);
if (ret) {
IL_ERR("initializing geos failed: %d\n", ret);
goto err_free_channel_map;
}
il4965_init_hw_rates(il, il->ieee_rates);
return 0;
err_free_channel_map:
il_free_channel_map(il);
err:
return ret;
}
static void
il4965_uninit_drv(struct il_priv *il)
{
il_free_geos(il);
il_free_channel_map(il);
kfree(il->scan_cmd);
}
static void
il4965_hw_detect(struct il_priv *il)
{
il->hw_rev = _il_rd(il, CSR_HW_REV);
il->hw_wa_rev = _il_rd(il, CSR_HW_REV_WA_REG);
il->rev_id = il->pci_dev->revision;
D_INFO("HW Revision ID = 0x%X\n", il->rev_id);
}
static struct il_sensitivity_ranges il4965_sensitivity = {
.min_nrg_cck = 97,
.max_nrg_cck = 0, /* not used, set to 0 */
.auto_corr_min_ofdm = 85,
.auto_corr_min_ofdm_mrc = 170,
.auto_corr_min_ofdm_x1 = 105,
.auto_corr_min_ofdm_mrc_x1 = 220,
.auto_corr_max_ofdm = 120,
.auto_corr_max_ofdm_mrc = 210,
.auto_corr_max_ofdm_x1 = 140,
.auto_corr_max_ofdm_mrc_x1 = 270,
.auto_corr_min_cck = 125,
.auto_corr_max_cck = 200,
.auto_corr_min_cck_mrc = 200,
.auto_corr_max_cck_mrc = 400,
.nrg_th_cck = 100,
.nrg_th_ofdm = 100,
.barker_corr_th_min = 190,
.barker_corr_th_min_mrc = 390,
.nrg_th_cca = 62,
};
static void
il4965_set_hw_params(struct il_priv *il)
{
il->hw_params.bcast_id = IL4965_BROADCAST_ID;
il->hw_params.max_rxq_size = RX_QUEUE_SIZE;
il->hw_params.max_rxq_log = RX_QUEUE_SIZE_LOG;
if (il->cfg->mod_params->amsdu_size_8K)
il->hw_params.rx_page_order = get_order(IL_RX_BUF_SIZE_8K);
else
il->hw_params.rx_page_order = get_order(IL_RX_BUF_SIZE_4K);
il->hw_params.max_beacon_itrvl = IL_MAX_UCODE_BEACON_INTERVAL;
if (il->cfg->mod_params->disable_11n)
il->cfg->sku &= ~IL_SKU_N;
if (il->cfg->mod_params->num_of_queues >= IL_MIN_NUM_QUEUES &&
il->cfg->mod_params->num_of_queues <= IL49_NUM_QUEUES)
il->cfg->num_of_queues =
il->cfg->mod_params->num_of_queues;
il->hw_params.max_txq_num = il->cfg->num_of_queues;
il->hw_params.dma_chnl_num = FH49_TCSR_CHNL_NUM;
il->hw_params.scd_bc_tbls_size =
il->cfg->num_of_queues *
sizeof(struct il4965_scd_bc_tbl);
il->hw_params.tfd_size = sizeof(struct il_tfd);
il->hw_params.max_stations = IL4965_STATION_COUNT;
il->hw_params.max_data_size = IL49_RTC_DATA_SIZE;
il->hw_params.max_inst_size = IL49_RTC_INST_SIZE;
il->hw_params.max_bsm_size = BSM_SRAM_SIZE;
il->hw_params.ht40_channel = BIT(IEEE80211_BAND_5GHZ);
il->hw_params.rx_wrt_ptr_reg = FH49_RSCSR_CHNL0_WPTR;
il->hw_params.tx_chains_num = il4965_num_of_ant(il->cfg->valid_tx_ant);
il->hw_params.rx_chains_num = il4965_num_of_ant(il->cfg->valid_rx_ant);
il->hw_params.valid_tx_ant = il->cfg->valid_tx_ant;
il->hw_params.valid_rx_ant = il->cfg->valid_rx_ant;
il->hw_params.ct_kill_threshold =
CELSIUS_TO_KELVIN(CT_KILL_THRESHOLD_LEGACY);
il->hw_params.sens = &il4965_sensitivity;
il->hw_params.beacon_time_tsf_bits = IL4965_EXT_BEACON_TIME_POS;
}
static int
il4965_pci_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
{
int err = 0;
struct il_priv *il;
struct ieee80211_hw *hw;
struct il_cfg *cfg = (struct il_cfg *)(ent->driver_data);
unsigned long flags;
u16 pci_cmd;
/************************
* 1. Allocating HW data
************************/
hw = ieee80211_alloc_hw(sizeof(struct il_priv), &il4965_mac_ops);
if (!hw) {
err = -ENOMEM;
goto out;
}
il = hw->priv;
il->hw = hw;
SET_IEEE80211_DEV(hw, &pdev->dev);
D_INFO("*** LOAD DRIVER ***\n");
il->cfg = cfg;
il->ops = &il4965_ops;
#ifdef CONFIG_IWLEGACY_DEBUGFS
il->debugfs_ops = &il4965_debugfs_ops;
#endif
il->pci_dev = pdev;
il->inta_mask = CSR_INI_SET_MASK;
/**************************
* 2. Initializing PCI bus
**************************/
pci_disable_link_state(pdev,
PCIE_LINK_STATE_L0S | PCIE_LINK_STATE_L1 |
PCIE_LINK_STATE_CLKPM);
if (pci_enable_device(pdev)) {
err = -ENODEV;
goto out_ieee80211_free_hw;
}
pci_set_master(pdev);
err = pci_set_dma_mask(pdev, DMA_BIT_MASK(36));
if (!err)
err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(36));
if (err) {
err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (!err)
err =
pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
/* both attempts failed: */
if (err) {
IL_WARN("No suitable DMA available.\n");
goto out_pci_disable_device;
}
}
err = pci_request_regions(pdev, DRV_NAME);
if (err)
goto out_pci_disable_device;
pci_set_drvdata(pdev, il);
/***********************
* 3. Read REV register
***********************/
il->hw_base = pci_ioremap_bar(pdev, 0);
if (!il->hw_base) {
err = -ENODEV;
goto out_pci_release_regions;
}
D_INFO("pci_resource_len = 0x%08llx\n",
(unsigned long long)pci_resource_len(pdev, 0));
D_INFO("pci_resource_base = %p\n", il->hw_base);
/* these spin locks will be used in apm_ops.init and EEPROM access
* we should init now
*/
spin_lock_init(&il->reg_lock);
spin_lock_init(&il->lock);
/*
* stop and reset the on-board processor just in case it is in a
* strange state ... like being left stranded by a primary kernel
* and this is now the kdump kernel trying to start up
*/
_il_wr(il, CSR_RESET, CSR_RESET_REG_FLAG_NEVO_RESET);
il4965_hw_detect(il);
IL_INFO("Detected %s, REV=0x%X\n", il->cfg->name, il->hw_rev);
/* 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);
il4965_prepare_card_hw(il);
if (!il->hw_ready) {
IL_WARN("Failed, HW not ready\n");
err = -EIO;
goto out_iounmap;
}
/*****************
* 4. Read EEPROM
*****************/
/* Read the EEPROM */
err = il_eeprom_init(il);
if (err) {
IL_ERR("Unable to init EEPROM\n");
goto out_iounmap;
}
err = il4965_eeprom_check_version(il);
if (err)
goto out_free_eeprom;
/* extract MAC Address */
il4965_eeprom_get_mac(il, il->addresses[0].addr);
D_INFO("MAC address: %pM\n", il->addresses[0].addr);
il->hw->wiphy->addresses = il->addresses;
il->hw->wiphy->n_addresses = 1;
/************************
* 5. Setup HW constants
************************/
il4965_set_hw_params(il);
/*******************
* 6. Setup il
*******************/
err = il4965_init_drv(il);
if (err)
goto out_free_eeprom;
/* At this point both hw and il are initialized. */
/********************
* 7. Setup services
********************/
spin_lock_irqsave(&il->lock, flags);
il_disable_interrupts(il);
spin_unlock_irqrestore(&il->lock, flags);
pci_enable_msi(il->pci_dev);
err = request_irq(il->pci_dev->irq, il_isr, IRQF_SHARED, DRV_NAME, il);
if (err) {
IL_ERR("Error allocating IRQ %d\n", il->pci_dev->irq);
goto out_disable_msi;
}
il4965_setup_deferred_work(il);
il4965_setup_handlers(il);
/*********************************************
* 8. Enable interrupts and read RFKILL state
*********************************************/
/* enable rfkill interrupt: hw bug w/a */
pci_read_config_word(il->pci_dev, PCI_COMMAND, &pci_cmd);
if (pci_cmd & PCI_COMMAND_INTX_DISABLE) {
pci_cmd &= ~PCI_COMMAND_INTX_DISABLE;
pci_write_config_word(il->pci_dev, PCI_COMMAND, pci_cmd);
}
il_enable_rfkill_int(il);
/* If platform's RF_KILL switch is NOT set to KILL */
if (_il_rd(il, CSR_GP_CNTRL) & CSR_GP_CNTRL_REG_FLAG_HW_RF_KILL_SW)
clear_bit(S_RFKILL, &il->status);
else
set_bit(S_RFKILL, &il->status);
wiphy_rfkill_set_hw_state(il->hw->wiphy,
test_bit(S_RFKILL, &il->status));
il_power_initialize(il);
init_completion(&il->_4965.firmware_loading_complete);
err = il4965_request_firmware(il, true);
if (err)
goto out_destroy_workqueue;
return 0;
out_destroy_workqueue:
destroy_workqueue(il->workqueue);
il->workqueue = NULL;
free_irq(il->pci_dev->irq, il);
out_disable_msi:
pci_disable_msi(il->pci_dev);
il4965_uninit_drv(il);
out_free_eeprom:
il_eeprom_free(il);
out_iounmap:
iounmap(il->hw_base);
out_pci_release_regions:
pci_release_regions(pdev);
out_pci_disable_device:
pci_disable_device(pdev);
out_ieee80211_free_hw:
ieee80211_free_hw(il->hw);
out:
return err;
}
static void
il4965_pci_remove(struct pci_dev *pdev)
{
struct il_priv *il = pci_get_drvdata(pdev);
unsigned long flags;
if (!il)
return;
wait_for_completion(&il->_4965.firmware_loading_complete);
D_INFO("*** UNLOAD DRIVER ***\n");
il_dbgfs_unregister(il);
sysfs_remove_group(&pdev->dev.kobj, &il_attribute_group);
/* ieee80211_unregister_hw call wil cause il_mac_stop to
* to be called and il4965_down since we are removing the device
* we need to set S_EXIT_PENDING bit.
*/
set_bit(S_EXIT_PENDING, &il->status);
il_leds_exit(il);
if (il->mac80211_registered) {
ieee80211_unregister_hw(il->hw);
il->mac80211_registered = 0;
} else {
il4965_down(il);
}
/*
* Make sure device is reset to low power before unloading driver.
* This may be redundant with il4965_down(), but there are paths to
* run il4965_down() without calling apm_ops.stop(), and there are
* paths to avoid running il4965_down() at all before leaving driver.
* This (inexpensive) call *makes sure* device is reset.
*/
il_apm_stop(il);
/* make sure we flush any pending irq or
* tasklet for the driver
*/
spin_lock_irqsave(&il->lock, flags);
il_disable_interrupts(il);
spin_unlock_irqrestore(&il->lock, flags);
il4965_synchronize_irq(il);
il4965_dealloc_ucode_pci(il);
if (il->rxq.bd)
il4965_rx_queue_free(il, &il->rxq);
il4965_hw_txq_ctx_free(il);
il_eeprom_free(il);
/*netif_stop_queue(dev); */
flush_workqueue(il->workqueue);
/* ieee80211_unregister_hw calls il_mac_stop, which flushes
* il->workqueue... so we can't take down the workqueue
* until now... */
destroy_workqueue(il->workqueue);
il->workqueue = NULL;
free_irq(il->pci_dev->irq, il);
pci_disable_msi(il->pci_dev);
iounmap(il->hw_base);
pci_release_regions(pdev);
pci_disable_device(pdev);
il4965_uninit_drv(il);
dev_kfree_skb(il->beacon_skb);
ieee80211_free_hw(il->hw);
}
/*
* Activate/Deactivate Tx DMA/FIFO channels according tx fifos mask
* must be called under il->lock and mac access
*/
void
il4965_txq_set_sched(struct il_priv *il, u32 mask)
{
il_wr_prph(il, IL49_SCD_TXFACT, mask);
}
/*****************************************************************************
*
* driver and module entry point
*
*****************************************************************************/
/* Hardware specific file defines the PCI IDs table for that hardware module */
static const struct pci_device_id il4965_hw_card_ids[] = {
{IL_PCI_DEVICE(0x4229, PCI_ANY_ID, il4965_cfg)},
{IL_PCI_DEVICE(0x4230, PCI_ANY_ID, il4965_cfg)},
{0}
};
MODULE_DEVICE_TABLE(pci, il4965_hw_card_ids);
static struct pci_driver il4965_driver = {
.name = DRV_NAME,
.id_table = il4965_hw_card_ids,
.probe = il4965_pci_probe,
.remove = il4965_pci_remove,
.driver.pm = IL_LEGACY_PM_OPS,
};
static int __init
il4965_init(void)
{
int ret;
pr_info(DRV_DESCRIPTION ", " DRV_VERSION "\n");
pr_info(DRV_COPYRIGHT "\n");
ret = il4965_rate_control_register();
if (ret) {
pr_err("Unable to register rate control algorithm: %d\n", ret);
return ret;
}
ret = pci_register_driver(&il4965_driver);
if (ret) {
pr_err("Unable to initialize PCI module\n");
goto error_register;
}
return ret;
error_register:
il4965_rate_control_unregister();
return ret;
}
static void __exit
il4965_exit(void)
{
pci_unregister_driver(&il4965_driver);
il4965_rate_control_unregister();
}
module_exit(il4965_exit);
module_init(il4965_init);
#ifdef CONFIG_IWLEGACY_DEBUG
module_param_named(debug, il_debug_level, uint, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, "debug output mask");
#endif
module_param_named(swcrypto, il4965_mod_params.sw_crypto, int, S_IRUGO);
MODULE_PARM_DESC(swcrypto, "using crypto in software (default 0 [hardware])");
module_param_named(queues_num, il4965_mod_params.num_of_queues, int, S_IRUGO);
MODULE_PARM_DESC(queues_num, "number of hw queues.");
module_param_named(11n_disable, il4965_mod_params.disable_11n, int, S_IRUGO);
MODULE_PARM_DESC(11n_disable, "disable 11n functionality");
module_param_named(amsdu_size_8K, il4965_mod_params.amsdu_size_8K, int,
S_IRUGO);
MODULE_PARM_DESC(amsdu_size_8K, "enable 8K amsdu size (default 0 [disabled])");
module_param_named(fw_restart, il4965_mod_params.restart_fw, int, S_IRUGO);
MODULE_PARM_DESC(fw_restart, "restart firmware in case of error");
| gpl-2.0 |
ribalda/linux-old | net/ipv6/netfilter/nft_chain_nat_ipv6.c | 612 | 2861 | /*
* Copyright (c) 2011 Patrick McHardy <kaber@trash.net>
* Copyright (c) 2012 Intel Corporation
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/skbuff.h>
#include <linux/ip.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv6.h>
#include <linux/netfilter/nf_tables.h>
#include <net/netfilter/nf_conntrack.h>
#include <net/netfilter/nf_nat.h>
#include <net/netfilter/nf_nat_core.h>
#include <net/netfilter/nf_tables.h>
#include <net/netfilter/nf_tables_ipv6.h>
#include <net/netfilter/nf_nat_l3proto.h>
#include <net/ipv6.h>
static unsigned int nft_nat_do_chain(const struct nf_hook_ops *ops,
struct sk_buff *skb,
const struct nf_hook_state *state,
struct nf_conn *ct)
{
struct nft_pktinfo pkt;
nft_set_pktinfo_ipv6(&pkt, ops, skb, state);
return nft_do_chain(&pkt, ops);
}
static unsigned int nft_nat_ipv6_fn(const struct nf_hook_ops *ops,
struct sk_buff *skb,
const struct nf_hook_state *state)
{
return nf_nat_ipv6_fn(ops, skb, state, nft_nat_do_chain);
}
static unsigned int nft_nat_ipv6_in(const struct nf_hook_ops *ops,
struct sk_buff *skb,
const struct nf_hook_state *state)
{
return nf_nat_ipv6_in(ops, skb, state, nft_nat_do_chain);
}
static unsigned int nft_nat_ipv6_out(const struct nf_hook_ops *ops,
struct sk_buff *skb,
const struct nf_hook_state *state)
{
return nf_nat_ipv6_out(ops, skb, state, nft_nat_do_chain);
}
static unsigned int nft_nat_ipv6_local_fn(const struct nf_hook_ops *ops,
struct sk_buff *skb,
const struct nf_hook_state *state)
{
return nf_nat_ipv6_local_fn(ops, skb, state, nft_nat_do_chain);
}
static const struct nf_chain_type nft_chain_nat_ipv6 = {
.name = "nat",
.type = NFT_CHAIN_T_NAT,
.family = NFPROTO_IPV6,
.owner = THIS_MODULE,
.hook_mask = (1 << NF_INET_PRE_ROUTING) |
(1 << NF_INET_POST_ROUTING) |
(1 << NF_INET_LOCAL_OUT) |
(1 << NF_INET_LOCAL_IN),
.hooks = {
[NF_INET_PRE_ROUTING] = nft_nat_ipv6_in,
[NF_INET_POST_ROUTING] = nft_nat_ipv6_out,
[NF_INET_LOCAL_OUT] = nft_nat_ipv6_local_fn,
[NF_INET_LOCAL_IN] = nft_nat_ipv6_fn,
},
};
static int __init nft_chain_nat_ipv6_init(void)
{
int err;
err = nft_register_chain_type(&nft_chain_nat_ipv6);
if (err < 0)
return err;
return 0;
}
static void __exit nft_chain_nat_ipv6_exit(void)
{
nft_unregister_chain_type(&nft_chain_nat_ipv6);
}
module_init(nft_chain_nat_ipv6_init);
module_exit(nft_chain_nat_ipv6_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Tomasz Bursztyka <tomasz.bursztyka@linux.intel.com>");
MODULE_ALIAS_NFT_CHAIN(AF_INET6, "nat");
| gpl-2.0 |
paalsteek/android_kernel_moto_milestone2 | arch/sparc/kernel/pcic.c | 612 | 26771 | /*
* pcic.c: MicroSPARC-IIep PCI controller support
*
* Copyright (C) 1998 V. Roganov and G. Raiko
*
* Code is derived from Ultra/PCI PSYCHO controller support, see that
* for author info.
*
* Support for diverse IIep based platforms by Pete Zaitcev.
* CP-1200 by Eric Brower.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <asm/swift.h> /* for cache flushing. */
#include <asm/io.h>
#include <linux/ctype.h>
#include <linux/pci.h>
#include <linux/time.h>
#include <linux/timex.h>
#include <linux/interrupt.h>
#include <asm/irq.h>
#include <asm/oplib.h>
#include <asm/prom.h>
#include <asm/pcic.h>
#include <asm/timer.h>
#include <asm/uaccess.h>
#include <asm/irq_regs.h>
#include "irq.h"
/*
* I studied different documents and many live PROMs both from 2.30
* family and 3.xx versions. I came to the amazing conclusion: there is
* absolutely no way to route interrupts in IIep systems relying on
* information which PROM presents. We must hardcode interrupt routing
* schematics. And this actually sucks. -- zaitcev 1999/05/12
*
* To find irq for a device we determine which routing map
* is in effect or, in other words, on which machine we are running.
* We use PROM name for this although other techniques may be used
* in special cases (Gleb reports a PROMless IIep based system).
* Once we know the map we take device configuration address and
* find PCIC pin number where INT line goes. Then we may either program
* preferred irq into the PCIC or supply the preexisting irq to the device.
*/
struct pcic_ca2irq {
unsigned char busno; /* PCI bus number */
unsigned char devfn; /* Configuration address */
unsigned char pin; /* PCIC external interrupt pin */
unsigned char irq; /* Preferred IRQ (mappable in PCIC) */
unsigned int force; /* Enforce preferred IRQ */
};
struct pcic_sn2list {
char *sysname;
struct pcic_ca2irq *intmap;
int mapdim;
};
/*
* JavaEngine-1 apparently has different versions.
*
* According to communications with Sun folks, for P2 build 501-4628-03:
* pin 0 - parallel, audio;
* pin 1 - Ethernet;
* pin 2 - su;
* pin 3 - PS/2 kbd and mouse.
*
* OEM manual (805-1486):
* pin 0: Ethernet
* pin 1: All EBus
* pin 2: IGA (unused)
* pin 3: Not connected
* OEM manual says that 501-4628 & 501-4811 are the same thing,
* only the latter has NAND flash in place.
*
* So far unofficial Sun wins over the OEM manual. Poor OEMs...
*/
static struct pcic_ca2irq pcic_i_je1a[] = { /* 501-4811-03 */
{ 0, 0x00, 2, 12, 0 }, /* EBus: hogs all */
{ 0, 0x01, 1, 6, 1 }, /* Happy Meal */
{ 0, 0x80, 0, 7, 0 }, /* IGA (unused) */
};
/* XXX JS-E entry is incomplete - PCI Slot 2 address (pin 7)? */
static struct pcic_ca2irq pcic_i_jse[] = {
{ 0, 0x00, 0, 13, 0 }, /* Ebus - serial and keyboard */
{ 0, 0x01, 1, 6, 0 }, /* hme */
{ 0, 0x08, 2, 9, 0 }, /* VGA - we hope not used :) */
{ 0, 0x10, 6, 8, 0 }, /* PCI INTA# in Slot 1 */
{ 0, 0x18, 7, 12, 0 }, /* PCI INTA# in Slot 2, shared w. RTC */
{ 0, 0x38, 4, 9, 0 }, /* All ISA devices. Read 8259. */
{ 0, 0x80, 5, 11, 0 }, /* EIDE */
/* {0,0x88, 0,0,0} - unknown device... PMU? Probably no interrupt. */
{ 0, 0xA0, 4, 9, 0 }, /* USB */
/*
* Some pins belong to non-PCI devices, we hardcode them in drivers.
* sun4m timers - irq 10, 14
* PC style RTC - pin 7, irq 4 ?
* Smart card, Parallel - pin 4 shared with USB, ISA
* audio - pin 3, irq 5 ?
*/
};
/* SPARCengine-6 was the original release name of CP1200.
* The documentation differs between the two versions
*/
static struct pcic_ca2irq pcic_i_se6[] = {
{ 0, 0x08, 0, 2, 0 }, /* SCSI */
{ 0, 0x01, 1, 6, 0 }, /* HME */
{ 0, 0x00, 3, 13, 0 }, /* EBus */
};
/*
* Krups (courtesy of Varol Kaptan)
* No documentation available, but it was easy to guess
* because it was very similar to Espresso.
*
* pin 0 - kbd, mouse, serial;
* pin 1 - Ethernet;
* pin 2 - igs (we do not use it);
* pin 3 - audio;
* pin 4,5,6 - unused;
* pin 7 - RTC (from P2 onwards as David B. says).
*/
static struct pcic_ca2irq pcic_i_jk[] = {
{ 0, 0x00, 0, 13, 0 }, /* Ebus - serial and keyboard */
{ 0, 0x01, 1, 6, 0 }, /* hme */
};
/*
* Several entries in this list may point to the same routing map
* as several PROMs may be installed on the same physical board.
*/
#define SN2L_INIT(name, map) \
{ name, map, ARRAY_SIZE(map) }
static struct pcic_sn2list pcic_known_sysnames[] = {
SN2L_INIT("SUNW,JavaEngine1", pcic_i_je1a), /* JE1, PROM 2.32 */
SN2L_INIT("SUNW,JS-E", pcic_i_jse), /* PROLL JavaStation-E */
SN2L_INIT("SUNW,SPARCengine-6", pcic_i_se6), /* SPARCengine-6/CP-1200 */
SN2L_INIT("SUNW,JS-NC", pcic_i_jk), /* PROLL JavaStation-NC */
SN2L_INIT("SUNW,JSIIep", pcic_i_jk), /* OBP JavaStation-NC */
{ NULL, NULL, 0 }
};
/*
* Only one PCIC per IIep,
* and since we have no SMP IIep, only one per system.
*/
static int pcic0_up;
static struct linux_pcic pcic0;
void __iomem *pcic_regs;
volatile int pcic_speculative;
volatile int pcic_trapped;
static void pci_do_gettimeofday(struct timeval *tv);
static int pci_do_settimeofday(struct timespec *tv);
#define CONFIG_CMD(bus, device_fn, where) (0x80000000 | (((unsigned int)bus) << 16) | (((unsigned int)device_fn) << 8) | (where & ~3))
static int pcic_read_config_dword(unsigned int busno, unsigned int devfn,
int where, u32 *value)
{
struct linux_pcic *pcic;
unsigned long flags;
pcic = &pcic0;
local_irq_save(flags);
#if 0 /* does not fail here */
pcic_speculative = 1;
pcic_trapped = 0;
#endif
writel(CONFIG_CMD(busno, devfn, where), pcic->pcic_config_space_addr);
#if 0 /* does not fail here */
nop();
if (pcic_trapped) {
local_irq_restore(flags);
*value = ~0;
return 0;
}
#endif
pcic_speculative = 2;
pcic_trapped = 0;
*value = readl(pcic->pcic_config_space_data + (where&4));
nop();
if (pcic_trapped) {
pcic_speculative = 0;
local_irq_restore(flags);
*value = ~0;
return 0;
}
pcic_speculative = 0;
local_irq_restore(flags);
return 0;
}
static int pcic_read_config(struct pci_bus *bus, unsigned int devfn,
int where, int size, u32 *val)
{
unsigned int v;
if (bus->number != 0) return -EINVAL;
switch (size) {
case 1:
pcic_read_config_dword(bus->number, devfn, where&~3, &v);
*val = 0xff & (v >> (8*(where & 3)));
return 0;
case 2:
if (where&1) return -EINVAL;
pcic_read_config_dword(bus->number, devfn, where&~3, &v);
*val = 0xffff & (v >> (8*(where & 3)));
return 0;
case 4:
if (where&3) return -EINVAL;
pcic_read_config_dword(bus->number, devfn, where&~3, val);
return 0;
}
return -EINVAL;
}
static int pcic_write_config_dword(unsigned int busno, unsigned int devfn,
int where, u32 value)
{
struct linux_pcic *pcic;
unsigned long flags;
pcic = &pcic0;
local_irq_save(flags);
writel(CONFIG_CMD(busno, devfn, where), pcic->pcic_config_space_addr);
writel(value, pcic->pcic_config_space_data + (where&4));
local_irq_restore(flags);
return 0;
}
static int pcic_write_config(struct pci_bus *bus, unsigned int devfn,
int where, int size, u32 val)
{
unsigned int v;
if (bus->number != 0) return -EINVAL;
switch (size) {
case 1:
pcic_read_config_dword(bus->number, devfn, where&~3, &v);
v = (v & ~(0xff << (8*(where&3)))) |
((0xff&val) << (8*(where&3)));
return pcic_write_config_dword(bus->number, devfn, where&~3, v);
case 2:
if (where&1) return -EINVAL;
pcic_read_config_dword(bus->number, devfn, where&~3, &v);
v = (v & ~(0xffff << (8*(where&3)))) |
((0xffff&val) << (8*(where&3)));
return pcic_write_config_dword(bus->number, devfn, where&~3, v);
case 4:
if (where&3) return -EINVAL;
return pcic_write_config_dword(bus->number, devfn, where, val);
}
return -EINVAL;
}
static struct pci_ops pcic_ops = {
.read = pcic_read_config,
.write = pcic_write_config,
};
/*
* On sparc64 pcibios_init() calls pci_controller_probe().
* We want PCIC probed little ahead so that interrupt controller
* would be operational.
*/
int __init pcic_probe(void)
{
struct linux_pcic *pcic;
struct linux_prom_registers regs[PROMREG_MAX];
struct linux_pbm_info* pbm;
char namebuf[64];
int node;
int err;
if (pcic0_up) {
prom_printf("PCIC: called twice!\n");
prom_halt();
}
pcic = &pcic0;
node = prom_getchild (prom_root_node);
node = prom_searchsiblings (node, "pci");
if (node == 0)
return -ENODEV;
/*
* Map in PCIC register set, config space, and IO base
*/
err = prom_getproperty(node, "reg", (char*)regs, sizeof(regs));
if (err == 0 || err == -1) {
prom_printf("PCIC: Error, cannot get PCIC registers "
"from PROM.\n");
prom_halt();
}
pcic0_up = 1;
pcic->pcic_res_regs.name = "pcic_registers";
pcic->pcic_regs = ioremap(regs[0].phys_addr, regs[0].reg_size);
if (!pcic->pcic_regs) {
prom_printf("PCIC: Error, cannot map PCIC registers.\n");
prom_halt();
}
pcic->pcic_res_io.name = "pcic_io";
if ((pcic->pcic_io = (unsigned long)
ioremap(regs[1].phys_addr, 0x10000)) == 0) {
prom_printf("PCIC: Error, cannot map PCIC IO Base.\n");
prom_halt();
}
pcic->pcic_res_cfg_addr.name = "pcic_cfg_addr";
if ((pcic->pcic_config_space_addr =
ioremap(regs[2].phys_addr, regs[2].reg_size * 2)) == 0) {
prom_printf("PCIC: Error, cannot map "
"PCI Configuration Space Address.\n");
prom_halt();
}
/*
* Docs say three least significant bits in address and data
* must be the same. Thus, we need adjust size of data.
*/
pcic->pcic_res_cfg_data.name = "pcic_cfg_data";
if ((pcic->pcic_config_space_data =
ioremap(regs[3].phys_addr, regs[3].reg_size * 2)) == 0) {
prom_printf("PCIC: Error, cannot map "
"PCI Configuration Space Data.\n");
prom_halt();
}
pbm = &pcic->pbm;
pbm->prom_node = node;
prom_getstring(node, "name", namebuf, 63); namebuf[63] = 0;
strcpy(pbm->prom_name, namebuf);
{
extern volatile int t_nmi[1];
extern int pcic_nmi_trap_patch[1];
t_nmi[0] = pcic_nmi_trap_patch[0];
t_nmi[1] = pcic_nmi_trap_patch[1];
t_nmi[2] = pcic_nmi_trap_patch[2];
t_nmi[3] = pcic_nmi_trap_patch[3];
swift_flush_dcache();
pcic_regs = pcic->pcic_regs;
}
prom_getstring(prom_root_node, "name", namebuf, 63); namebuf[63] = 0;
{
struct pcic_sn2list *p;
for (p = pcic_known_sysnames; p->sysname != NULL; p++) {
if (strcmp(namebuf, p->sysname) == 0)
break;
}
pcic->pcic_imap = p->intmap;
pcic->pcic_imdim = p->mapdim;
}
if (pcic->pcic_imap == NULL) {
/*
* We do not panic here for the sake of embedded systems.
*/
printk("PCIC: System %s is unknown, cannot route interrupts\n",
namebuf);
}
return 0;
}
static void __init pcic_pbm_scan_bus(struct linux_pcic *pcic)
{
struct linux_pbm_info *pbm = &pcic->pbm;
pbm->pci_bus = pci_scan_bus(pbm->pci_first_busno, &pcic_ops, pbm);
#if 0 /* deadwood transplanted from sparc64 */
pci_fill_in_pbm_cookies(pbm->pci_bus, pbm, pbm->prom_node);
pci_record_assignments(pbm, pbm->pci_bus);
pci_assign_unassigned(pbm, pbm->pci_bus);
pci_fixup_irq(pbm, pbm->pci_bus);
#endif
}
/*
* Main entry point from the PCI subsystem.
*/
static int __init pcic_init(void)
{
struct linux_pcic *pcic;
/*
* PCIC should be initialized at start of the timer.
* So, here we report the presence of PCIC and do some magic passes.
*/
if(!pcic0_up)
return 0;
pcic = &pcic0;
/*
* Switch off IOTLB translation.
*/
writeb(PCI_DVMA_CONTROL_IOTLB_DISABLE,
pcic->pcic_regs+PCI_DVMA_CONTROL);
/*
* Increase mapped size for PCI memory space (DMA access).
* Should be done in that order (size first, address second).
* Why we couldn't set up 4GB and forget about it? XXX
*/
writel(0xF0000000UL, pcic->pcic_regs+PCI_SIZE_0);
writel(0+PCI_BASE_ADDRESS_SPACE_MEMORY,
pcic->pcic_regs+PCI_BASE_ADDRESS_0);
pcic_pbm_scan_bus(pcic);
return 0;
}
int pcic_present(void)
{
return pcic0_up;
}
static int __devinit pdev_to_pnode(struct linux_pbm_info *pbm,
struct pci_dev *pdev)
{
struct linux_prom_pci_registers regs[PROMREG_MAX];
int err;
int node = prom_getchild(pbm->prom_node);
while(node) {
err = prom_getproperty(node, "reg",
(char *)®s[0], sizeof(regs));
if(err != 0 && err != -1) {
unsigned long devfn = (regs[0].which_io >> 8) & 0xff;
if(devfn == pdev->devfn)
return node;
}
node = prom_getsibling(node);
}
return 0;
}
static inline struct pcidev_cookie *pci_devcookie_alloc(void)
{
return kmalloc(sizeof(struct pcidev_cookie), GFP_ATOMIC);
}
static void pcic_map_pci_device(struct linux_pcic *pcic,
struct pci_dev *dev, int node)
{
char namebuf[64];
unsigned long address;
unsigned long flags;
int j;
if (node == 0 || node == -1) {
strcpy(namebuf, "???");
} else {
prom_getstring(node, "name", namebuf, 63); namebuf[63] = 0;
}
for (j = 0; j < 6; j++) {
address = dev->resource[j].start;
if (address == 0) break; /* are sequential */
flags = dev->resource[j].flags;
if ((flags & IORESOURCE_IO) != 0) {
if (address < 0x10000) {
/*
* A device responds to I/O cycles on PCI.
* We generate these cycles with memory
* access into the fixed map (phys 0x30000000).
*
* Since a device driver does not want to
* do ioremap() before accessing PC-style I/O,
* we supply virtual, ready to access address.
*
* Note that request_region()
* works for these devices.
*
* XXX Neat trick, but it's a *bad* idea
* to shit into regions like that.
* What if we want to allocate one more
* PCI base address...
*/
dev->resource[j].start =
pcic->pcic_io + address;
dev->resource[j].end = 1; /* XXX */
dev->resource[j].flags =
(flags & ~IORESOURCE_IO) | IORESOURCE_MEM;
} else {
/*
* OOPS... PCI Spec allows this. Sun does
* not have any devices getting above 64K
* so it must be user with a weird I/O
* board in a PCI slot. We must remap it
* under 64K but it is not done yet. XXX
*/
printk("PCIC: Skipping I/O space at 0x%lx, "
"this will Oops if a driver attaches "
"device '%s' at %02x:%02x)\n", address,
namebuf, dev->bus->number, dev->devfn);
}
}
}
}
static void
pcic_fill_irq(struct linux_pcic *pcic, struct pci_dev *dev, int node)
{
struct pcic_ca2irq *p;
int i, ivec;
char namebuf[64];
if (node == 0 || node == -1) {
strcpy(namebuf, "???");
} else {
prom_getstring(node, "name", namebuf, sizeof(namebuf));
}
if ((p = pcic->pcic_imap) == 0) {
dev->irq = 0;
return;
}
for (i = 0; i < pcic->pcic_imdim; i++) {
if (p->busno == dev->bus->number && p->devfn == dev->devfn)
break;
p++;
}
if (i >= pcic->pcic_imdim) {
printk("PCIC: device %s devfn %02x:%02x not found in %d\n",
namebuf, dev->bus->number, dev->devfn, pcic->pcic_imdim);
dev->irq = 0;
return;
}
i = p->pin;
if (i >= 0 && i < 4) {
ivec = readw(pcic->pcic_regs+PCI_INT_SELECT_LO);
dev->irq = ivec >> (i << 2) & 0xF;
} else if (i >= 4 && i < 8) {
ivec = readw(pcic->pcic_regs+PCI_INT_SELECT_HI);
dev->irq = ivec >> ((i-4) << 2) & 0xF;
} else { /* Corrupted map */
printk("PCIC: BAD PIN %d\n", i); for (;;) {}
}
/* P3 */ /* printk("PCIC: device %s pin %d ivec 0x%x irq %x\n", namebuf, i, ivec, dev->irq); */
/*
* dev->irq=0 means PROM did not bother to program the upper
* half of PCIC. This happens on JS-E with PROM 3.11, for instance.
*/
if (dev->irq == 0 || p->force) {
if (p->irq == 0 || p->irq >= 15) { /* Corrupted map */
printk("PCIC: BAD IRQ %d\n", p->irq); for (;;) {}
}
printk("PCIC: setting irq %d at pin %d for device %02x:%02x\n",
p->irq, p->pin, dev->bus->number, dev->devfn);
dev->irq = p->irq;
i = p->pin;
if (i >= 4) {
ivec = readw(pcic->pcic_regs+PCI_INT_SELECT_HI);
ivec &= ~(0xF << ((i - 4) << 2));
ivec |= p->irq << ((i - 4) << 2);
writew(ivec, pcic->pcic_regs+PCI_INT_SELECT_HI);
} else {
ivec = readw(pcic->pcic_regs+PCI_INT_SELECT_LO);
ivec &= ~(0xF << (i << 2));
ivec |= p->irq << (i << 2);
writew(ivec, pcic->pcic_regs+PCI_INT_SELECT_LO);
}
}
return;
}
/*
* Normally called from {do_}pci_scan_bus...
*/
void __devinit pcibios_fixup_bus(struct pci_bus *bus)
{
struct pci_dev *dev;
int i, has_io, has_mem;
unsigned int cmd;
struct linux_pcic *pcic;
/* struct linux_pbm_info* pbm = &pcic->pbm; */
int node;
struct pcidev_cookie *pcp;
if (!pcic0_up) {
printk("pcibios_fixup_bus: no PCIC\n");
return;
}
pcic = &pcic0;
/*
* Next crud is an equivalent of pbm = pcic_bus_to_pbm(bus);
*/
if (bus->number != 0) {
printk("pcibios_fixup_bus: nonzero bus 0x%x\n", bus->number);
return;
}
list_for_each_entry(dev, &bus->devices, bus_list) {
/*
* Comment from i386 branch:
* There are buggy BIOSes that forget to enable I/O and memory
* access to PCI devices. We try to fix this, but we need to
* be sure that the BIOS didn't forget to assign an address
* to the device. [mj]
* OBP is a case of such BIOS :-)
*/
has_io = has_mem = 0;
for(i=0; i<6; i++) {
unsigned long f = dev->resource[i].flags;
if (f & IORESOURCE_IO) {
has_io = 1;
} else if (f & IORESOURCE_MEM)
has_mem = 1;
}
pcic_read_config(dev->bus, dev->devfn, PCI_COMMAND, 2, &cmd);
if (has_io && !(cmd & PCI_COMMAND_IO)) {
printk("PCIC: Enabling I/O for device %02x:%02x\n",
dev->bus->number, dev->devfn);
cmd |= PCI_COMMAND_IO;
pcic_write_config(dev->bus, dev->devfn,
PCI_COMMAND, 2, cmd);
}
if (has_mem && !(cmd & PCI_COMMAND_MEMORY)) {
printk("PCIC: Enabling memory for device %02x:%02x\n",
dev->bus->number, dev->devfn);
cmd |= PCI_COMMAND_MEMORY;
pcic_write_config(dev->bus, dev->devfn,
PCI_COMMAND, 2, cmd);
}
node = pdev_to_pnode(&pcic->pbm, dev);
if(node == 0)
node = -1;
/* cookies */
pcp = pci_devcookie_alloc();
pcp->pbm = &pcic->pbm;
pcp->prom_node = of_find_node_by_phandle(node);
dev->sysdata = pcp;
/* fixing I/O to look like memory */
if ((dev->class>>16) != PCI_BASE_CLASS_BRIDGE)
pcic_map_pci_device(pcic, dev, node);
pcic_fill_irq(pcic, dev, node);
}
}
/*
* pcic_pin_to_irq() is exported to bus probing code
*/
unsigned int
pcic_pin_to_irq(unsigned int pin, const char *name)
{
struct linux_pcic *pcic = &pcic0;
unsigned int irq;
unsigned int ivec;
if (pin < 4) {
ivec = readw(pcic->pcic_regs+PCI_INT_SELECT_LO);
irq = ivec >> (pin << 2) & 0xF;
} else if (pin < 8) {
ivec = readw(pcic->pcic_regs+PCI_INT_SELECT_HI);
irq = ivec >> ((pin-4) << 2) & 0xF;
} else { /* Corrupted map */
printk("PCIC: BAD PIN %d FOR %s\n", pin, name);
for (;;) {} /* XXX Cannot panic properly in case of PROLL */
}
/* P3 */ /* printk("PCIC: dev %s pin %d ivec 0x%x irq %x\n", name, pin, ivec, irq); */
return irq;
}
/* Makes compiler happy */
static volatile int pcic_timer_dummy;
static void pcic_clear_clock_irq(void)
{
pcic_timer_dummy = readl(pcic0.pcic_regs+PCI_SYS_LIMIT);
}
static irqreturn_t pcic_timer_handler (int irq, void *h)
{
write_seqlock(&xtime_lock); /* Dummy, to show that we remember */
pcic_clear_clock_irq();
do_timer(1);
write_sequnlock(&xtime_lock);
#ifndef CONFIG_SMP
update_process_times(user_mode(get_irq_regs()));
#endif
return IRQ_HANDLED;
}
#define USECS_PER_JIFFY 10000 /* We have 100HZ "standard" timer for sparc */
#define TICK_TIMER_LIMIT ((100*1000000/4)/100)
void __init pci_time_init(void)
{
struct linux_pcic *pcic = &pcic0;
unsigned long v;
int timer_irq, irq;
/* A hack until do_gettimeofday prototype is moved to arch specific headers
and btfixupped. Patch do_gettimeofday with ba pci_do_gettimeofday; nop */
((unsigned int *)do_gettimeofday)[0] =
0x10800000 | ((((unsigned long)pci_do_gettimeofday -
(unsigned long)do_gettimeofday) >> 2) & 0x003fffff);
((unsigned int *)do_gettimeofday)[1] = 0x01000000;
BTFIXUPSET_CALL(bus_do_settimeofday, pci_do_settimeofday, BTFIXUPCALL_NORM);
btfixup();
writel (TICK_TIMER_LIMIT, pcic->pcic_regs+PCI_SYS_LIMIT);
/* PROM should set appropriate irq */
v = readb(pcic->pcic_regs+PCI_COUNTER_IRQ);
timer_irq = PCI_COUNTER_IRQ_SYS(v);
writel (PCI_COUNTER_IRQ_SET(timer_irq, 0),
pcic->pcic_regs+PCI_COUNTER_IRQ);
irq = request_irq(timer_irq, pcic_timer_handler,
(IRQF_DISABLED | SA_STATIC_ALLOC), "timer", NULL);
if (irq) {
prom_printf("time_init: unable to attach IRQ%d\n", timer_irq);
prom_halt();
}
local_irq_enable();
}
static inline unsigned long do_gettimeoffset(void)
{
/*
* We divide all by 100
* to have microsecond resolution and to avoid overflow
*/
unsigned long count =
readl(pcic0.pcic_regs+PCI_SYS_COUNTER) & ~PCI_SYS_COUNTER_OVERFLOW;
count = ((count/100)*USECS_PER_JIFFY) / (TICK_TIMER_LIMIT/100);
return count;
}
static void pci_do_gettimeofday(struct timeval *tv)
{
unsigned long flags;
unsigned long seq;
unsigned long usec, sec;
unsigned long max_ntp_tick = tick_usec - tickadj;
do {
seq = read_seqbegin_irqsave(&xtime_lock, flags);
usec = do_gettimeoffset();
/*
* If time_adjust is negative then NTP is slowing the clock
* so make sure not to go into next possible interval.
* Better to lose some accuracy than have time go backwards..
*/
if (unlikely(time_adjust < 0))
usec = min(usec, max_ntp_tick);
sec = xtime.tv_sec;
usec += (xtime.tv_nsec / 1000);
} while (read_seqretry_irqrestore(&xtime_lock, seq, flags));
while (usec >= 1000000) {
usec -= 1000000;
sec++;
}
tv->tv_sec = sec;
tv->tv_usec = usec;
}
static int pci_do_settimeofday(struct timespec *tv)
{
if ((unsigned long)tv->tv_nsec >= NSEC_PER_SEC)
return -EINVAL;
/*
* This is revolting. We need to set "xtime" correctly. However, the
* value in this location is the value at the most recent update of
* wall time. Discover what correction gettimeofday() would have
* made, and then undo it!
*/
tv->tv_nsec -= 1000 * do_gettimeoffset();
while (tv->tv_nsec < 0) {
tv->tv_nsec += NSEC_PER_SEC;
tv->tv_sec--;
}
wall_to_monotonic.tv_sec += xtime.tv_sec - tv->tv_sec;
wall_to_monotonic.tv_nsec += xtime.tv_nsec - tv->tv_nsec;
if (wall_to_monotonic.tv_nsec > NSEC_PER_SEC) {
wall_to_monotonic.tv_nsec -= NSEC_PER_SEC;
wall_to_monotonic.tv_sec++;
}
if (wall_to_monotonic.tv_nsec < 0) {
wall_to_monotonic.tv_nsec += NSEC_PER_SEC;
wall_to_monotonic.tv_sec--;
}
xtime.tv_sec = tv->tv_sec;
xtime.tv_nsec = tv->tv_nsec;
ntp_clear();
return 0;
}
#if 0
static void watchdog_reset() {
writeb(0, pcic->pcic_regs+PCI_SYS_STATUS);
}
#endif
/*
* Other archs parse arguments here.
*/
char * __devinit pcibios_setup(char *str)
{
return str;
}
void pcibios_align_resource(void *data, struct resource *res,
resource_size_t size, resource_size_t align)
{
}
int pcibios_enable_device(struct pci_dev *pdev, int mask)
{
return 0;
}
/*
* NMI
*/
void pcic_nmi(unsigned int pend, struct pt_regs *regs)
{
pend = flip_dword(pend);
if (!pcic_speculative || (pend & PCI_SYS_INT_PENDING_PIO) == 0) {
/*
* XXX On CP-1200 PCI #SERR may happen, we do not know
* what to do about it yet.
*/
printk("Aiee, NMI pend 0x%x pc 0x%x spec %d, hanging\n",
pend, (int)regs->pc, pcic_speculative);
for (;;) { }
}
pcic_speculative = 0;
pcic_trapped = 1;
regs->pc = regs->npc;
regs->npc += 4;
}
static inline unsigned long get_irqmask(int irq_nr)
{
return 1 << irq_nr;
}
static void pcic_disable_irq(unsigned int irq_nr)
{
unsigned long mask, flags;
mask = get_irqmask(irq_nr);
local_irq_save(flags);
writel(mask, pcic0.pcic_regs+PCI_SYS_INT_TARGET_MASK_SET);
local_irq_restore(flags);
}
static void pcic_enable_irq(unsigned int irq_nr)
{
unsigned long mask, flags;
mask = get_irqmask(irq_nr);
local_irq_save(flags);
writel(mask, pcic0.pcic_regs+PCI_SYS_INT_TARGET_MASK_CLEAR);
local_irq_restore(flags);
}
static void pcic_load_profile_irq(int cpu, unsigned int limit)
{
printk("PCIC: unimplemented code: FILE=%s LINE=%d", __FILE__, __LINE__);
}
/* We assume the caller has disabled local interrupts when these are called,
* or else very bizarre behavior will result.
*/
static void pcic_disable_pil_irq(unsigned int pil)
{
writel(get_irqmask(pil), pcic0.pcic_regs+PCI_SYS_INT_TARGET_MASK_SET);
}
static void pcic_enable_pil_irq(unsigned int pil)
{
writel(get_irqmask(pil), pcic0.pcic_regs+PCI_SYS_INT_TARGET_MASK_CLEAR);
}
void __init sun4m_pci_init_IRQ(void)
{
BTFIXUPSET_CALL(enable_irq, pcic_enable_irq, BTFIXUPCALL_NORM);
BTFIXUPSET_CALL(disable_irq, pcic_disable_irq, BTFIXUPCALL_NORM);
BTFIXUPSET_CALL(enable_pil_irq, pcic_enable_pil_irq, BTFIXUPCALL_NORM);
BTFIXUPSET_CALL(disable_pil_irq, pcic_disable_pil_irq, BTFIXUPCALL_NORM);
BTFIXUPSET_CALL(clear_clock_irq, pcic_clear_clock_irq, BTFIXUPCALL_NORM);
BTFIXUPSET_CALL(load_profile_irq, pcic_load_profile_irq, BTFIXUPCALL_NORM);
}
int pcibios_assign_resource(struct pci_dev *pdev, int resource)
{
return -ENXIO;
}
struct device_node *pci_device_to_OF_node(struct pci_dev *pdev)
{
struct pcidev_cookie *pc = pdev->sysdata;
return pc->prom_node;
}
EXPORT_SYMBOL(pci_device_to_OF_node);
/*
* This probably belongs here rather than ioport.c because
* we do not want this crud linked into SBus kernels.
* Also, think for a moment about likes of floppy.c that
* include architecture specific parts. They may want to redefine ins/outs.
*
* We do not use horrible macros here because we want to
* advance pointer by sizeof(size).
*/
void outsb(unsigned long addr, const void *src, unsigned long count)
{
while (count) {
count -= 1;
outb(*(const char *)src, addr);
src += 1;
/* addr += 1; */
}
}
EXPORT_SYMBOL(outsb);
void outsw(unsigned long addr, const void *src, unsigned long count)
{
while (count) {
count -= 2;
outw(*(const short *)src, addr);
src += 2;
/* addr += 2; */
}
}
EXPORT_SYMBOL(outsw);
void outsl(unsigned long addr, const void *src, unsigned long count)
{
while (count) {
count -= 4;
outl(*(const long *)src, addr);
src += 4;
/* addr += 4; */
}
}
EXPORT_SYMBOL(outsl);
void insb(unsigned long addr, void *dst, unsigned long count)
{
while (count) {
count -= 1;
*(unsigned char *)dst = inb(addr);
dst += 1;
/* addr += 1; */
}
}
EXPORT_SYMBOL(insb);
void insw(unsigned long addr, void *dst, unsigned long count)
{
while (count) {
count -= 2;
*(unsigned short *)dst = inw(addr);
dst += 2;
/* addr += 2; */
}
}
EXPORT_SYMBOL(insw);
void insl(unsigned long addr, void *dst, unsigned long count)
{
while (count) {
count -= 4;
/*
* XXX I am sure we are in for an unaligned trap here.
*/
*(unsigned long *)dst = inl(addr);
dst += 4;
/* addr += 4; */
}
}
EXPORT_SYMBOL(insl);
subsys_initcall(pcic_init);
| gpl-2.0 |
psyke83/kernel_samsung_gio2europa | drivers/video/tridentfb.c | 612 | 41175 | /*
* Frame buffer driver for Trident TGUI, Blade and Image series
*
* Copyright 2001, 2002 - Jani Monoses <jani@iv.ro>
* Copyright 2009 Krzysztof Helt <krzysztof.h1@wp.pl>
*
* CREDITS:(in order of appearance)
* skeletonfb.c by Geert Uytterhoeven and other fb code in drivers/video
* Special thanks ;) to Mattia Crivellini <tia@mclink.it>
* much inspired by the XFree86 4.x Trident driver sources
* by Alan Hourihane the FreeVGA project
* Francesco Salvestrini <salvestrini@users.sf.net> XP support,
* code, suggestions
* TODO:
* timing value tweaking so it looks good on every monitor in every mode
*/
#include <linux/module.h>
#include <linux/fb.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/delay.h>
#include <video/vga.h>
#include <video/trident.h>
struct tridentfb_par {
void __iomem *io_virt; /* iospace virtual memory address */
u32 pseudo_pal[16];
int chip_id;
int flatpanel;
void (*init_accel) (struct tridentfb_par *, int, int);
void (*wait_engine) (struct tridentfb_par *);
void (*fill_rect)
(struct tridentfb_par *par, u32, u32, u32, u32, u32, u32);
void (*copy_rect)
(struct tridentfb_par *par, u32, u32, u32, u32, u32, u32);
void (*image_blit)
(struct tridentfb_par *par, const char*,
u32, u32, u32, u32, u32, u32);
unsigned char eng_oper; /* engine operation... */
};
static struct fb_fix_screeninfo tridentfb_fix = {
.id = "Trident",
.type = FB_TYPE_PACKED_PIXELS,
.ypanstep = 1,
.visual = FB_VISUAL_PSEUDOCOLOR,
.accel = FB_ACCEL_NONE,
};
/* defaults which are normally overriden by user values */
/* video mode */
static char *mode_option __devinitdata = "640x480-8@60";
static int bpp __devinitdata = 8;
static int noaccel __devinitdata;
static int center;
static int stretch;
static int fp __devinitdata;
static int crt __devinitdata;
static int memsize __devinitdata;
static int memdiff __devinitdata;
static int nativex;
module_param(mode_option, charp, 0);
MODULE_PARM_DESC(mode_option, "Initial video mode e.g. '648x480-8@60'");
module_param_named(mode, mode_option, charp, 0);
MODULE_PARM_DESC(mode, "Initial video mode e.g. '648x480-8@60' (deprecated)");
module_param(bpp, int, 0);
module_param(center, int, 0);
module_param(stretch, int, 0);
module_param(noaccel, int, 0);
module_param(memsize, int, 0);
module_param(memdiff, int, 0);
module_param(nativex, int, 0);
module_param(fp, int, 0);
MODULE_PARM_DESC(fp, "Define if flatpanel is connected");
module_param(crt, int, 0);
MODULE_PARM_DESC(crt, "Define if CRT is connected");
static inline int is_oldclock(int id)
{
return (id == TGUI9440) ||
(id == TGUI9660) ||
(id == CYBER9320);
}
static inline int is_oldprotect(int id)
{
return is_oldclock(id) ||
(id == PROVIDIA9685) ||
(id == CYBER9382) ||
(id == CYBER9385);
}
static inline int is_blade(int id)
{
return (id == BLADE3D) ||
(id == CYBERBLADEE4) ||
(id == CYBERBLADEi7) ||
(id == CYBERBLADEi7D) ||
(id == CYBERBLADEi1) ||
(id == CYBERBLADEi1D) ||
(id == CYBERBLADEAi1) ||
(id == CYBERBLADEAi1D);
}
static inline int is_xp(int id)
{
return (id == CYBERBLADEXPAi1) ||
(id == CYBERBLADEXPm8) ||
(id == CYBERBLADEXPm16);
}
static inline int is3Dchip(int id)
{
return is_blade(id) || is_xp(id) ||
(id == CYBER9397) || (id == CYBER9397DVD) ||
(id == CYBER9520) || (id == CYBER9525DVD) ||
(id == IMAGE975) || (id == IMAGE985);
}
static inline int iscyber(int id)
{
switch (id) {
case CYBER9388:
case CYBER9382:
case CYBER9385:
case CYBER9397:
case CYBER9397DVD:
case CYBER9520:
case CYBER9525DVD:
case CYBERBLADEE4:
case CYBERBLADEi7D:
case CYBERBLADEi1:
case CYBERBLADEi1D:
case CYBERBLADEAi1:
case CYBERBLADEAi1D:
case CYBERBLADEXPAi1:
return 1;
case CYBER9320:
case CYBERBLADEi7: /* VIA MPV4 integrated version */
default:
/* case CYBERBLDAEXPm8: Strange */
/* case CYBERBLDAEXPm16: Strange */
return 0;
}
}
static inline void t_outb(struct tridentfb_par *p, u8 val, u16 reg)
{
fb_writeb(val, p->io_virt + reg);
}
static inline u8 t_inb(struct tridentfb_par *p, u16 reg)
{
return fb_readb(p->io_virt + reg);
}
static inline void writemmr(struct tridentfb_par *par, u16 r, u32 v)
{
fb_writel(v, par->io_virt + r);
}
static inline u32 readmmr(struct tridentfb_par *par, u16 r)
{
return fb_readl(par->io_virt + r);
}
/*
* Blade specific acceleration.
*/
#define point(x, y) ((y) << 16 | (x))
static void blade_init_accel(struct tridentfb_par *par, int pitch, int bpp)
{
int v1 = (pitch >> 3) << 20;
int tmp = bpp == 24 ? 2 : (bpp >> 4);
int v2 = v1 | (tmp << 29);
writemmr(par, 0x21C0, v2);
writemmr(par, 0x21C4, v2);
writemmr(par, 0x21B8, v2);
writemmr(par, 0x21BC, v2);
writemmr(par, 0x21D0, v1);
writemmr(par, 0x21D4, v1);
writemmr(par, 0x21C8, v1);
writemmr(par, 0x21CC, v1);
writemmr(par, 0x216C, 0);
}
static void blade_wait_engine(struct tridentfb_par *par)
{
while (readmmr(par, STATUS) & 0xFA800000)
cpu_relax();
}
static void blade_fill_rect(struct tridentfb_par *par,
u32 x, u32 y, u32 w, u32 h, u32 c, u32 rop)
{
writemmr(par, COLOR, c);
writemmr(par, ROP, rop ? ROP_X : ROP_S);
writemmr(par, CMD, 0x20000000 | 1 << 19 | 1 << 4 | 2 << 2);
writemmr(par, DST1, point(x, y));
writemmr(par, DST2, point(x + w - 1, y + h - 1));
}
static void blade_image_blit(struct tridentfb_par *par, const char *data,
u32 x, u32 y, u32 w, u32 h, u32 c, u32 b)
{
unsigned size = ((w + 31) >> 5) * h;
writemmr(par, COLOR, c);
writemmr(par, BGCOLOR, b);
writemmr(par, CMD, 0xa0000000 | 3 << 19);
writemmr(par, DST1, point(x, y));
writemmr(par, DST2, point(x + w - 1, y + h - 1));
memcpy(par->io_virt + 0x10000, data, 4 * size);
}
static void blade_copy_rect(struct tridentfb_par *par,
u32 x1, u32 y1, u32 x2, u32 y2, u32 w, u32 h)
{
int direction = 2;
u32 s1 = point(x1, y1);
u32 s2 = point(x1 + w - 1, y1 + h - 1);
u32 d1 = point(x2, y2);
u32 d2 = point(x2 + w - 1, y2 + h - 1);
if ((y1 > y2) || ((y1 == y2) && (x1 > x2)))
direction = 0;
writemmr(par, ROP, ROP_S);
writemmr(par, CMD, 0xE0000000 | 1 << 19 | 1 << 4 | 1 << 2 | direction);
writemmr(par, SRC1, direction ? s2 : s1);
writemmr(par, SRC2, direction ? s1 : s2);
writemmr(par, DST1, direction ? d2 : d1);
writemmr(par, DST2, direction ? d1 : d2);
}
/*
* BladeXP specific acceleration functions
*/
static void xp_init_accel(struct tridentfb_par *par, int pitch, int bpp)
{
unsigned char x = bpp == 24 ? 3 : (bpp >> 4);
int v1 = pitch << (bpp == 24 ? 20 : (18 + x));
switch (pitch << (bpp >> 3)) {
case 8192:
case 512:
x |= 0x00;
break;
case 1024:
x |= 0x04;
break;
case 2048:
x |= 0x08;
break;
case 4096:
x |= 0x0C;
break;
}
t_outb(par, x, 0x2125);
par->eng_oper = x | 0x40;
writemmr(par, 0x2154, v1);
writemmr(par, 0x2150, v1);
t_outb(par, 3, 0x2126);
}
static void xp_wait_engine(struct tridentfb_par *par)
{
int count = 0;
int timeout = 0;
while (t_inb(par, STATUS) & 0x80) {
count++;
if (count == 10000000) {
/* Timeout */
count = 9990000;
timeout++;
if (timeout == 8) {
/* Reset engine */
t_outb(par, 0x00, STATUS);
return;
}
}
cpu_relax();
}
}
static void xp_fill_rect(struct tridentfb_par *par,
u32 x, u32 y, u32 w, u32 h, u32 c, u32 rop)
{
writemmr(par, 0x2127, ROP_P);
writemmr(par, 0x2158, c);
writemmr(par, DRAWFL, 0x4000);
writemmr(par, OLDDIM, point(h, w));
writemmr(par, OLDDST, point(y, x));
t_outb(par, 0x01, OLDCMD);
t_outb(par, par->eng_oper, 0x2125);
}
static void xp_copy_rect(struct tridentfb_par *par,
u32 x1, u32 y1, u32 x2, u32 y2, u32 w, u32 h)
{
u32 x1_tmp, x2_tmp, y1_tmp, y2_tmp;
int direction = 0x0004;
if ((x1 < x2) && (y1 == y2)) {
direction |= 0x0200;
x1_tmp = x1 + w - 1;
x2_tmp = x2 + w - 1;
} else {
x1_tmp = x1;
x2_tmp = x2;
}
if (y1 < y2) {
direction |= 0x0100;
y1_tmp = y1 + h - 1;
y2_tmp = y2 + h - 1;
} else {
y1_tmp = y1;
y2_tmp = y2;
}
writemmr(par, DRAWFL, direction);
t_outb(par, ROP_S, 0x2127);
writemmr(par, OLDSRC, point(y1_tmp, x1_tmp));
writemmr(par, OLDDST, point(y2_tmp, x2_tmp));
writemmr(par, OLDDIM, point(h, w));
t_outb(par, 0x01, OLDCMD);
}
/*
* Image specific acceleration functions
*/
static void image_init_accel(struct tridentfb_par *par, int pitch, int bpp)
{
int tmp = bpp == 24 ? 2: (bpp >> 4);
writemmr(par, 0x2120, 0xF0000000);
writemmr(par, 0x2120, 0x40000000 | tmp);
writemmr(par, 0x2120, 0x80000000);
writemmr(par, 0x2144, 0x00000000);
writemmr(par, 0x2148, 0x00000000);
writemmr(par, 0x2150, 0x00000000);
writemmr(par, 0x2154, 0x00000000);
writemmr(par, 0x2120, 0x60000000 | (pitch << 16) | pitch);
writemmr(par, 0x216C, 0x00000000);
writemmr(par, 0x2170, 0x00000000);
writemmr(par, 0x217C, 0x00000000);
writemmr(par, 0x2120, 0x10000000);
writemmr(par, 0x2130, (2047 << 16) | 2047);
}
static void image_wait_engine(struct tridentfb_par *par)
{
while (readmmr(par, 0x2164) & 0xF0000000)
cpu_relax();
}
static void image_fill_rect(struct tridentfb_par *par,
u32 x, u32 y, u32 w, u32 h, u32 c, u32 rop)
{
writemmr(par, 0x2120, 0x80000000);
writemmr(par, 0x2120, 0x90000000 | ROP_S);
writemmr(par, 0x2144, c);
writemmr(par, DST1, point(x, y));
writemmr(par, DST2, point(x + w - 1, y + h - 1));
writemmr(par, 0x2124, 0x80000000 | 3 << 22 | 1 << 10 | 1 << 9);
}
static void image_copy_rect(struct tridentfb_par *par,
u32 x1, u32 y1, u32 x2, u32 y2, u32 w, u32 h)
{
int direction = 0x4;
u32 s1 = point(x1, y1);
u32 s2 = point(x1 + w - 1, y1 + h - 1);
u32 d1 = point(x2, y2);
u32 d2 = point(x2 + w - 1, y2 + h - 1);
if ((y1 > y2) || ((y1 == y2) && (x1 > x2)))
direction = 0;
writemmr(par, 0x2120, 0x80000000);
writemmr(par, 0x2120, 0x90000000 | ROP_S);
writemmr(par, SRC1, direction ? s2 : s1);
writemmr(par, SRC2, direction ? s1 : s2);
writemmr(par, DST1, direction ? d2 : d1);
writemmr(par, DST2, direction ? d1 : d2);
writemmr(par, 0x2124,
0x80000000 | 1 << 22 | 1 << 10 | 1 << 7 | direction);
}
/*
* TGUI 9440/96XX acceleration
*/
static void tgui_init_accel(struct tridentfb_par *par, int pitch, int bpp)
{
unsigned char x = bpp == 24 ? 3 : (bpp >> 4);
/* disable clipping */
writemmr(par, 0x2148, 0);
writemmr(par, 0x214C, point(4095, 2047));
switch ((pitch * bpp) / 8) {
case 8192:
case 512:
x |= 0x00;
break;
case 1024:
x |= 0x04;
break;
case 2048:
x |= 0x08;
break;
case 4096:
x |= 0x0C;
break;
}
fb_writew(x, par->io_virt + 0x2122);
}
static void tgui_fill_rect(struct tridentfb_par *par,
u32 x, u32 y, u32 w, u32 h, u32 c, u32 rop)
{
t_outb(par, ROP_P, 0x2127);
writemmr(par, OLDCLR, c);
writemmr(par, DRAWFL, 0x4020);
writemmr(par, OLDDIM, point(w - 1, h - 1));
writemmr(par, OLDDST, point(x, y));
t_outb(par, 1, OLDCMD);
}
static void tgui_copy_rect(struct tridentfb_par *par,
u32 x1, u32 y1, u32 x2, u32 y2, u32 w, u32 h)
{
int flags = 0;
u16 x1_tmp, x2_tmp, y1_tmp, y2_tmp;
if ((x1 < x2) && (y1 == y2)) {
flags |= 0x0200;
x1_tmp = x1 + w - 1;
x2_tmp = x2 + w - 1;
} else {
x1_tmp = x1;
x2_tmp = x2;
}
if (y1 < y2) {
flags |= 0x0100;
y1_tmp = y1 + h - 1;
y2_tmp = y2 + h - 1;
} else {
y1_tmp = y1;
y2_tmp = y2;
}
writemmr(par, DRAWFL, 0x4 | flags);
t_outb(par, ROP_S, 0x2127);
writemmr(par, OLDSRC, point(x1_tmp, y1_tmp));
writemmr(par, OLDDST, point(x2_tmp, y2_tmp));
writemmr(par, OLDDIM, point(w - 1, h - 1));
t_outb(par, 1, OLDCMD);
}
/*
* Accel functions called by the upper layers
*/
static void tridentfb_fillrect(struct fb_info *info,
const struct fb_fillrect *fr)
{
struct tridentfb_par *par = info->par;
int col;
if (info->flags & FBINFO_HWACCEL_DISABLED) {
cfb_fillrect(info, fr);
return;
}
if (info->var.bits_per_pixel == 8) {
col = fr->color;
col |= col << 8;
col |= col << 16;
} else
col = ((u32 *)(info->pseudo_palette))[fr->color];
par->wait_engine(par);
par->fill_rect(par, fr->dx, fr->dy, fr->width,
fr->height, col, fr->rop);
}
static void tridentfb_imageblit(struct fb_info *info,
const struct fb_image *img)
{
struct tridentfb_par *par = info->par;
int col, bgcol;
if ((info->flags & FBINFO_HWACCEL_DISABLED) || img->depth != 1) {
cfb_imageblit(info, img);
return;
}
if (info->var.bits_per_pixel == 8) {
col = img->fg_color;
col |= col << 8;
col |= col << 16;
bgcol = img->bg_color;
bgcol |= bgcol << 8;
bgcol |= bgcol << 16;
} else {
col = ((u32 *)(info->pseudo_palette))[img->fg_color];
bgcol = ((u32 *)(info->pseudo_palette))[img->bg_color];
}
par->wait_engine(par);
if (par->image_blit)
par->image_blit(par, img->data, img->dx, img->dy,
img->width, img->height, col, bgcol);
else
cfb_imageblit(info, img);
}
static void tridentfb_copyarea(struct fb_info *info,
const struct fb_copyarea *ca)
{
struct tridentfb_par *par = info->par;
if (info->flags & FBINFO_HWACCEL_DISABLED) {
cfb_copyarea(info, ca);
return;
}
par->wait_engine(par);
par->copy_rect(par, ca->sx, ca->sy, ca->dx, ca->dy,
ca->width, ca->height);
}
static int tridentfb_sync(struct fb_info *info)
{
struct tridentfb_par *par = info->par;
if (!(info->flags & FBINFO_HWACCEL_DISABLED))
par->wait_engine(par);
return 0;
}
/*
* Hardware access functions
*/
static inline unsigned char read3X4(struct tridentfb_par *par, int reg)
{
return vga_mm_rcrt(par->io_virt, reg);
}
static inline void write3X4(struct tridentfb_par *par, int reg,
unsigned char val)
{
vga_mm_wcrt(par->io_virt, reg, val);
}
static inline unsigned char read3CE(struct tridentfb_par *par,
unsigned char reg)
{
return vga_mm_rgfx(par->io_virt, reg);
}
static inline void writeAttr(struct tridentfb_par *par, int reg,
unsigned char val)
{
fb_readb(par->io_virt + VGA_IS1_RC); /* flip-flop to index */
vga_mm_wattr(par->io_virt, reg, val);
}
static inline void write3CE(struct tridentfb_par *par, int reg,
unsigned char val)
{
vga_mm_wgfx(par->io_virt, reg, val);
}
static void enable_mmio(struct tridentfb_par *par)
{
/* Goto New Mode */
vga_io_rseq(0x0B);
/* Unprotect registers */
vga_io_wseq(NewMode1, 0x80);
if (!is_oldprotect(par->chip_id))
vga_io_wseq(Protection, 0x92);
/* Enable MMIO */
outb(PCIReg, 0x3D4);
outb(inb(0x3D5) | 0x01, 0x3D5);
}
static void disable_mmio(struct tridentfb_par *par)
{
/* Goto New Mode */
vga_mm_rseq(par->io_virt, 0x0B);
/* Unprotect registers */
vga_mm_wseq(par->io_virt, NewMode1, 0x80);
if (!is_oldprotect(par->chip_id))
vga_mm_wseq(par->io_virt, Protection, 0x92);
/* Disable MMIO */
t_outb(par, PCIReg, 0x3D4);
t_outb(par, t_inb(par, 0x3D5) & ~0x01, 0x3D5);
}
static inline void crtc_unlock(struct tridentfb_par *par)
{
write3X4(par, VGA_CRTC_V_SYNC_END,
read3X4(par, VGA_CRTC_V_SYNC_END) & 0x7F);
}
/* Return flat panel's maximum x resolution */
static int __devinit get_nativex(struct tridentfb_par *par)
{
int x, y, tmp;
if (nativex)
return nativex;
tmp = (read3CE(par, VertStretch) >> 4) & 3;
switch (tmp) {
case 0:
x = 1280; y = 1024;
break;
case 2:
x = 1024; y = 768;
break;
case 3:
x = 800; y = 600;
break;
case 4:
x = 1400; y = 1050;
break;
case 1:
default:
x = 640; y = 480;
break;
}
output("%dx%d flat panel found\n", x, y);
return x;
}
/* Set pitch */
static inline void set_lwidth(struct tridentfb_par *par, int width)
{
write3X4(par, VGA_CRTC_OFFSET, width & 0xFF);
write3X4(par, AddColReg,
(read3X4(par, AddColReg) & 0xCF) | ((width & 0x300) >> 4));
}
/* For resolutions smaller than FP resolution stretch */
static void screen_stretch(struct tridentfb_par *par)
{
if (par->chip_id != CYBERBLADEXPAi1)
write3CE(par, BiosReg, 0);
else
write3CE(par, BiosReg, 8);
write3CE(par, VertStretch, (read3CE(par, VertStretch) & 0x7C) | 1);
write3CE(par, HorStretch, (read3CE(par, HorStretch) & 0x7C) | 1);
}
/* For resolutions smaller than FP resolution center */
static inline void screen_center(struct tridentfb_par *par)
{
write3CE(par, VertStretch, (read3CE(par, VertStretch) & 0x7C) | 0x80);
write3CE(par, HorStretch, (read3CE(par, HorStretch) & 0x7C) | 0x80);
}
/* Address of first shown pixel in display memory */
static void set_screen_start(struct tridentfb_par *par, int base)
{
u8 tmp;
write3X4(par, VGA_CRTC_START_LO, base & 0xFF);
write3X4(par, VGA_CRTC_START_HI, (base & 0xFF00) >> 8);
tmp = read3X4(par, CRTCModuleTest) & 0xDF;
write3X4(par, CRTCModuleTest, tmp | ((base & 0x10000) >> 11));
tmp = read3X4(par, CRTHiOrd) & 0xF8;
write3X4(par, CRTHiOrd, tmp | ((base & 0xE0000) >> 17));
}
/* Set dotclock frequency */
static void set_vclk(struct tridentfb_par *par, unsigned long freq)
{
int m, n, k;
unsigned long fi, d, di;
unsigned char best_m = 0, best_n = 0, best_k = 0;
unsigned char hi, lo;
unsigned char shift = !is_oldclock(par->chip_id) ? 2 : 1;
d = 20000;
for (k = shift; k >= 0; k--)
for (m = 1; m < 32; m++) {
n = ((m + 2) << shift) - 8;
for (n = (n < 0 ? 0 : n); n < 122; n++) {
fi = ((14318l * (n + 8)) / (m + 2)) >> k;
di = abs(fi - freq);
if (di < d || (di == d && k == best_k)) {
d = di;
best_n = n;
best_m = m;
best_k = k;
}
if (fi > freq)
break;
}
}
if (is_oldclock(par->chip_id)) {
lo = best_n | (best_m << 7);
hi = (best_m >> 1) | (best_k << 4);
} else {
lo = best_n;
hi = best_m | (best_k << 6);
}
if (is3Dchip(par->chip_id)) {
vga_mm_wseq(par->io_virt, ClockHigh, hi);
vga_mm_wseq(par->io_virt, ClockLow, lo);
} else {
t_outb(par, lo, 0x43C8);
t_outb(par, hi, 0x43C9);
}
debug("VCLK = %X %X\n", hi, lo);
}
/* Set number of lines for flat panels*/
static void set_number_of_lines(struct tridentfb_par *par, int lines)
{
int tmp = read3CE(par, CyberEnhance) & 0x8F;
if (lines > 1024)
tmp |= 0x50;
else if (lines > 768)
tmp |= 0x30;
else if (lines > 600)
tmp |= 0x20;
else if (lines > 480)
tmp |= 0x10;
write3CE(par, CyberEnhance, tmp);
}
/*
* If we see that FP is active we assume we have one.
* Otherwise we have a CRT display. User can override.
*/
static int __devinit is_flatpanel(struct tridentfb_par *par)
{
if (fp)
return 1;
if (crt || !iscyber(par->chip_id))
return 0;
return (read3CE(par, FPConfig) & 0x10) ? 1 : 0;
}
/* Try detecting the video memory size */
static unsigned int __devinit get_memsize(struct tridentfb_par *par)
{
unsigned char tmp, tmp2;
unsigned int k;
/* If memory size provided by user */
if (memsize)
k = memsize * Kb;
else
switch (par->chip_id) {
case CYBER9525DVD:
k = 2560 * Kb;
break;
default:
tmp = read3X4(par, SPR) & 0x0F;
switch (tmp) {
case 0x01:
k = 512 * Kb;
break;
case 0x02:
k = 6 * Mb; /* XP */
break;
case 0x03:
k = 1 * Mb;
break;
case 0x04:
k = 8 * Mb;
break;
case 0x06:
k = 10 * Mb; /* XP */
break;
case 0x07:
k = 2 * Mb;
break;
case 0x08:
k = 12 * Mb; /* XP */
break;
case 0x0A:
k = 14 * Mb; /* XP */
break;
case 0x0C:
k = 16 * Mb; /* XP */
break;
case 0x0E: /* XP */
tmp2 = vga_mm_rseq(par->io_virt, 0xC1);
switch (tmp2) {
case 0x00:
k = 20 * Mb;
break;
case 0x01:
k = 24 * Mb;
break;
case 0x10:
k = 28 * Mb;
break;
case 0x11:
k = 32 * Mb;
break;
default:
k = 1 * Mb;
break;
}
break;
case 0x0F:
k = 4 * Mb;
break;
default:
k = 1 * Mb;
break;
}
}
k -= memdiff * Kb;
output("framebuffer size = %d Kb\n", k / Kb);
return k;
}
/* See if we can handle the video mode described in var */
static int tridentfb_check_var(struct fb_var_screeninfo *var,
struct fb_info *info)
{
struct tridentfb_par *par = info->par;
int bpp = var->bits_per_pixel;
int line_length;
int ramdac = 230000; /* 230MHz for most 3D chips */
debug("enter\n");
/* check color depth */
if (bpp == 24)
bpp = var->bits_per_pixel = 32;
if (bpp != 8 && bpp != 16 && bpp != 32)
return -EINVAL;
if (par->chip_id == TGUI9440 && bpp == 32)
return -EINVAL;
/* check whether resolution fits on panel and in memory */
if (par->flatpanel && nativex && var->xres > nativex)
return -EINVAL;
/* various resolution checks */
var->xres = (var->xres + 7) & ~0x7;
if (var->xres > var->xres_virtual)
var->xres_virtual = var->xres;
if (var->yres > var->yres_virtual)
var->yres_virtual = var->yres;
if (var->xres_virtual > 4095 || var->yres > 2048)
return -EINVAL;
/* prevent from position overflow for acceleration */
if (var->yres_virtual > 0xffff)
return -EINVAL;
line_length = var->xres_virtual * bpp / 8;
if (!is3Dchip(par->chip_id) &&
!(info->flags & FBINFO_HWACCEL_DISABLED)) {
/* acceleration requires line length to be power of 2 */
if (line_length <= 512)
var->xres_virtual = 512 * 8 / bpp;
else if (line_length <= 1024)
var->xres_virtual = 1024 * 8 / bpp;
else if (line_length <= 2048)
var->xres_virtual = 2048 * 8 / bpp;
else if (line_length <= 4096)
var->xres_virtual = 4096 * 8 / bpp;
else if (line_length <= 8192)
var->xres_virtual = 8192 * 8 / bpp;
else
return -EINVAL;
line_length = var->xres_virtual * bpp / 8;
}
/* datasheet specifies how to set panning only up to 4 MB */
if (line_length * (var->yres_virtual - var->yres) > (4 << 20))
var->yres_virtual = ((4 << 20) / line_length) + var->yres;
if (line_length * var->yres_virtual > info->fix.smem_len)
return -EINVAL;
switch (bpp) {
case 8:
var->red.offset = 0;
var->red.length = 8;
var->green = var->red;
var->blue = var->red;
break;
case 16:
var->red.offset = 11;
var->green.offset = 5;
var->blue.offset = 0;
var->red.length = 5;
var->green.length = 6;
var->blue.length = 5;
break;
case 32:
var->red.offset = 16;
var->green.offset = 8;
var->blue.offset = 0;
var->red.length = 8;
var->green.length = 8;
var->blue.length = 8;
break;
default:
return -EINVAL;
}
if (is_xp(par->chip_id))
ramdac = 350000;
switch (par->chip_id) {
case TGUI9440:
ramdac = (bpp >= 16) ? 45000 : 90000;
break;
case CYBER9320:
case TGUI9660:
ramdac = 135000;
break;
case PROVIDIA9685:
case CYBER9388:
case CYBER9382:
case CYBER9385:
ramdac = 170000;
break;
}
/* The clock is doubled for 32 bpp */
if (bpp == 32)
ramdac /= 2;
if (PICOS2KHZ(var->pixclock) > ramdac)
return -EINVAL;
debug("exit\n");
return 0;
}
/* Pan the display */
static int tridentfb_pan_display(struct fb_var_screeninfo *var,
struct fb_info *info)
{
struct tridentfb_par *par = info->par;
unsigned int offset;
debug("enter\n");
offset = (var->xoffset + (var->yoffset * var->xres_virtual))
* var->bits_per_pixel / 32;
set_screen_start(par, offset);
debug("exit\n");
return 0;
}
static inline void shadowmode_on(struct tridentfb_par *par)
{
write3CE(par, CyberControl, read3CE(par, CyberControl) | 0x81);
}
static inline void shadowmode_off(struct tridentfb_par *par)
{
write3CE(par, CyberControl, read3CE(par, CyberControl) & 0x7E);
}
/* Set the hardware to the requested video mode */
static int tridentfb_set_par(struct fb_info *info)
{
struct tridentfb_par *par = info->par;
u32 htotal, hdispend, hsyncstart, hsyncend, hblankstart, hblankend;
u32 vtotal, vdispend, vsyncstart, vsyncend, vblankstart, vblankend;
struct fb_var_screeninfo *var = &info->var;
int bpp = var->bits_per_pixel;
unsigned char tmp;
unsigned long vclk;
debug("enter\n");
hdispend = var->xres / 8 - 1;
hsyncstart = (var->xres + var->right_margin) / 8;
hsyncend = (var->xres + var->right_margin + var->hsync_len) / 8;
htotal = (var->xres + var->left_margin + var->right_margin +
var->hsync_len) / 8 - 5;
hblankstart = hdispend + 1;
hblankend = htotal + 3;
vdispend = var->yres - 1;
vsyncstart = var->yres + var->lower_margin;
vsyncend = vsyncstart + var->vsync_len;
vtotal = var->upper_margin + vsyncend - 2;
vblankstart = vdispend + 1;
vblankend = vtotal;
if (info->var.vmode & FB_VMODE_INTERLACED) {
vtotal /= 2;
vdispend /= 2;
vsyncstart /= 2;
vsyncend /= 2;
vblankstart /= 2;
vblankend /= 2;
}
enable_mmio(par);
crtc_unlock(par);
write3CE(par, CyberControl, 8);
tmp = 0xEB;
if (var->sync & FB_SYNC_HOR_HIGH_ACT)
tmp &= ~0x40;
if (var->sync & FB_SYNC_VERT_HIGH_ACT)
tmp &= ~0x80;
if (par->flatpanel && var->xres < nativex) {
/*
* on flat panels with native size larger
* than requested resolution decide whether
* we stretch or center
*/
t_outb(par, tmp | 0xC0, VGA_MIS_W);
shadowmode_on(par);
if (center)
screen_center(par);
else if (stretch)
screen_stretch(par);
} else {
t_outb(par, tmp, VGA_MIS_W);
write3CE(par, CyberControl, 8);
}
/* vertical timing values */
write3X4(par, VGA_CRTC_V_TOTAL, vtotal & 0xFF);
write3X4(par, VGA_CRTC_V_DISP_END, vdispend & 0xFF);
write3X4(par, VGA_CRTC_V_SYNC_START, vsyncstart & 0xFF);
write3X4(par, VGA_CRTC_V_SYNC_END, (vsyncend & 0x0F));
write3X4(par, VGA_CRTC_V_BLANK_START, vblankstart & 0xFF);
write3X4(par, VGA_CRTC_V_BLANK_END, vblankend & 0xFF);
/* horizontal timing values */
write3X4(par, VGA_CRTC_H_TOTAL, htotal & 0xFF);
write3X4(par, VGA_CRTC_H_DISP, hdispend & 0xFF);
write3X4(par, VGA_CRTC_H_SYNC_START, hsyncstart & 0xFF);
write3X4(par, VGA_CRTC_H_SYNC_END,
(hsyncend & 0x1F) | ((hblankend & 0x20) << 2));
write3X4(par, VGA_CRTC_H_BLANK_START, hblankstart & 0xFF);
write3X4(par, VGA_CRTC_H_BLANK_END, hblankend & 0x1F);
/* higher bits of vertical timing values */
tmp = 0x10;
if (vtotal & 0x100) tmp |= 0x01;
if (vdispend & 0x100) tmp |= 0x02;
if (vsyncstart & 0x100) tmp |= 0x04;
if (vblankstart & 0x100) tmp |= 0x08;
if (vtotal & 0x200) tmp |= 0x20;
if (vdispend & 0x200) tmp |= 0x40;
if (vsyncstart & 0x200) tmp |= 0x80;
write3X4(par, VGA_CRTC_OVERFLOW, tmp);
tmp = read3X4(par, CRTHiOrd) & 0x07;
tmp |= 0x08; /* line compare bit 10 */
if (vtotal & 0x400) tmp |= 0x80;
if (vblankstart & 0x400) tmp |= 0x40;
if (vsyncstart & 0x400) tmp |= 0x20;
if (vdispend & 0x400) tmp |= 0x10;
write3X4(par, CRTHiOrd, tmp);
tmp = (htotal >> 8) & 0x01;
tmp |= (hdispend >> 7) & 0x02;
tmp |= (hsyncstart >> 5) & 0x08;
tmp |= (hblankstart >> 4) & 0x10;
write3X4(par, HorizOverflow, tmp);
tmp = 0x40;
if (vblankstart & 0x200) tmp |= 0x20;
//FIXME if (info->var.vmode & FB_VMODE_DOUBLE) tmp |= 0x80; /* double scan for 200 line modes */
write3X4(par, VGA_CRTC_MAX_SCAN, tmp);
write3X4(par, VGA_CRTC_LINE_COMPARE, 0xFF);
write3X4(par, VGA_CRTC_PRESET_ROW, 0);
write3X4(par, VGA_CRTC_MODE, 0xC3);
write3X4(par, LinearAddReg, 0x20); /* enable linear addressing */
tmp = (info->var.vmode & FB_VMODE_INTERLACED) ? 0x84 : 0x80;
/* enable access extended memory */
write3X4(par, CRTCModuleTest, tmp);
tmp = read3CE(par, MiscIntContReg) & ~0x4;
if (info->var.vmode & FB_VMODE_INTERLACED)
tmp |= 0x4;
write3CE(par, MiscIntContReg, tmp);
/* enable GE for text acceleration */
write3X4(par, GraphEngReg, 0x80);
switch (bpp) {
case 8:
tmp = 0x00;
break;
case 16:
tmp = 0x05;
break;
case 24:
tmp = 0x29;
break;
case 32:
tmp = 0x09;
break;
}
write3X4(par, PixelBusReg, tmp);
tmp = read3X4(par, DRAMControl);
if (!is_oldprotect(par->chip_id))
tmp |= 0x10;
if (iscyber(par->chip_id))
tmp |= 0x20;
write3X4(par, DRAMControl, tmp); /* both IO, linear enable */
write3X4(par, InterfaceSel, read3X4(par, InterfaceSel) | 0x40);
if (!is_xp(par->chip_id))
write3X4(par, Performance, read3X4(par, Performance) | 0x10);
/* MMIO & PCI read and write burst enable */
if (par->chip_id != TGUI9440 && par->chip_id != IMAGE975)
write3X4(par, PCIReg, read3X4(par, PCIReg) | 0x06);
vga_mm_wseq(par->io_virt, 0, 3);
vga_mm_wseq(par->io_virt, 1, 1); /* set char clock 8 dots wide */
/* enable 4 maps because needed in chain4 mode */
vga_mm_wseq(par->io_virt, 2, 0x0F);
vga_mm_wseq(par->io_virt, 3, 0);
vga_mm_wseq(par->io_virt, 4, 0x0E); /* memory mode enable bitmaps ?? */
/* convert from picoseconds to kHz */
vclk = PICOS2KHZ(info->var.pixclock);
/* divide clock by 2 if 32bpp chain4 mode display and CPU path */
tmp = read3CE(par, MiscExtFunc) & 0xF0;
if (bpp == 32 || (par->chip_id == TGUI9440 && bpp == 16)) {
tmp |= 8;
vclk *= 2;
}
set_vclk(par, vclk);
write3CE(par, MiscExtFunc, tmp | 0x12);
write3CE(par, 0x5, 0x40); /* no CGA compat, allow 256 col */
write3CE(par, 0x6, 0x05); /* graphics mode */
write3CE(par, 0x7, 0x0F); /* planes? */
/* graphics mode and support 256 color modes */
writeAttr(par, 0x10, 0x41);
writeAttr(par, 0x12, 0x0F); /* planes */
writeAttr(par, 0x13, 0); /* horizontal pel panning */
/* colors */
for (tmp = 0; tmp < 0x10; tmp++)
writeAttr(par, tmp, tmp);
fb_readb(par->io_virt + VGA_IS1_RC); /* flip-flop to index */
t_outb(par, 0x20, VGA_ATT_W); /* enable attr */
switch (bpp) {
case 8:
tmp = 0;
break;
case 16:
tmp = 0x30;
break;
case 24:
case 32:
tmp = 0xD0;
break;
}
t_inb(par, VGA_PEL_IW);
t_inb(par, VGA_PEL_MSK);
t_inb(par, VGA_PEL_MSK);
t_inb(par, VGA_PEL_MSK);
t_inb(par, VGA_PEL_MSK);
t_outb(par, tmp, VGA_PEL_MSK);
t_inb(par, VGA_PEL_IW);
if (par->flatpanel)
set_number_of_lines(par, info->var.yres);
info->fix.line_length = info->var.xres_virtual * bpp / 8;
set_lwidth(par, info->fix.line_length / 8);
if (!(info->flags & FBINFO_HWACCEL_DISABLED))
par->init_accel(par, info->var.xres_virtual, bpp);
info->fix.visual = (bpp == 8) ? FB_VISUAL_PSEUDOCOLOR : FB_VISUAL_TRUECOLOR;
info->cmap.len = (bpp == 8) ? 256 : 16;
debug("exit\n");
return 0;
}
/* Set one color register */
static int tridentfb_setcolreg(unsigned regno, unsigned red, unsigned green,
unsigned blue, unsigned transp,
struct fb_info *info)
{
int bpp = info->var.bits_per_pixel;
struct tridentfb_par *par = info->par;
if (regno >= info->cmap.len)
return 1;
if (bpp == 8) {
t_outb(par, 0xFF, VGA_PEL_MSK);
t_outb(par, regno, VGA_PEL_IW);
t_outb(par, red >> 10, VGA_PEL_D);
t_outb(par, green >> 10, VGA_PEL_D);
t_outb(par, blue >> 10, VGA_PEL_D);
} else if (regno < 16) {
if (bpp == 16) { /* RGB 565 */
u32 col;
col = (red & 0xF800) | ((green & 0xFC00) >> 5) |
((blue & 0xF800) >> 11);
col |= col << 16;
((u32 *)(info->pseudo_palette))[regno] = col;
} else if (bpp == 32) /* ARGB 8888 */
((u32 *)info->pseudo_palette)[regno] =
((transp & 0xFF00) << 16) |
((red & 0xFF00) << 8) |
((green & 0xFF00)) |
((blue & 0xFF00) >> 8);
}
return 0;
}
/* Try blanking the screen. For flat panels it does nothing */
static int tridentfb_blank(int blank_mode, struct fb_info *info)
{
unsigned char PMCont, DPMSCont;
struct tridentfb_par *par = info->par;
debug("enter\n");
if (par->flatpanel)
return 0;
t_outb(par, 0x04, 0x83C8); /* Read DPMS Control */
PMCont = t_inb(par, 0x83C6) & 0xFC;
DPMSCont = read3CE(par, PowerStatus) & 0xFC;
switch (blank_mode) {
case FB_BLANK_UNBLANK:
/* Screen: On, HSync: On, VSync: On */
case FB_BLANK_NORMAL:
/* Screen: Off, HSync: On, VSync: On */
PMCont |= 0x03;
DPMSCont |= 0x00;
break;
case FB_BLANK_HSYNC_SUSPEND:
/* Screen: Off, HSync: Off, VSync: On */
PMCont |= 0x02;
DPMSCont |= 0x01;
break;
case FB_BLANK_VSYNC_SUSPEND:
/* Screen: Off, HSync: On, VSync: Off */
PMCont |= 0x02;
DPMSCont |= 0x02;
break;
case FB_BLANK_POWERDOWN:
/* Screen: Off, HSync: Off, VSync: Off */
PMCont |= 0x00;
DPMSCont |= 0x03;
break;
}
write3CE(par, PowerStatus, DPMSCont);
t_outb(par, 4, 0x83C8);
t_outb(par, PMCont, 0x83C6);
debug("exit\n");
/* let fbcon do a softblank for us */
return (blank_mode == FB_BLANK_NORMAL) ? 1 : 0;
}
static struct fb_ops tridentfb_ops = {
.owner = THIS_MODULE,
.fb_setcolreg = tridentfb_setcolreg,
.fb_pan_display = tridentfb_pan_display,
.fb_blank = tridentfb_blank,
.fb_check_var = tridentfb_check_var,
.fb_set_par = tridentfb_set_par,
.fb_fillrect = tridentfb_fillrect,
.fb_copyarea = tridentfb_copyarea,
.fb_imageblit = tridentfb_imageblit,
.fb_sync = tridentfb_sync,
};
static int __devinit trident_pci_probe(struct pci_dev *dev,
const struct pci_device_id *id)
{
int err;
unsigned char revision;
struct fb_info *info;
struct tridentfb_par *default_par;
int chip3D;
int chip_id;
err = pci_enable_device(dev);
if (err)
return err;
info = framebuffer_alloc(sizeof(struct tridentfb_par), &dev->dev);
if (!info)
return -ENOMEM;
default_par = info->par;
chip_id = id->device;
/* If PCI id is 0x9660 then further detect chip type */
if (chip_id == TGUI9660) {
revision = vga_io_rseq(RevisionID);
switch (revision) {
case 0x21:
chip_id = PROVIDIA9685;
break;
case 0x22:
case 0x23:
chip_id = CYBER9397;
break;
case 0x2A:
chip_id = CYBER9397DVD;
break;
case 0x30:
case 0x33:
case 0x34:
case 0x35:
case 0x38:
case 0x3A:
case 0xB3:
chip_id = CYBER9385;
break;
case 0x40 ... 0x43:
chip_id = CYBER9382;
break;
case 0x4A:
chip_id = CYBER9388;
break;
default:
break;
}
}
chip3D = is3Dchip(chip_id);
if (is_xp(chip_id)) {
default_par->init_accel = xp_init_accel;
default_par->wait_engine = xp_wait_engine;
default_par->fill_rect = xp_fill_rect;
default_par->copy_rect = xp_copy_rect;
tridentfb_fix.accel = FB_ACCEL_TRIDENT_BLADEXP;
} else if (is_blade(chip_id)) {
default_par->init_accel = blade_init_accel;
default_par->wait_engine = blade_wait_engine;
default_par->fill_rect = blade_fill_rect;
default_par->copy_rect = blade_copy_rect;
default_par->image_blit = blade_image_blit;
tridentfb_fix.accel = FB_ACCEL_TRIDENT_BLADE3D;
} else if (chip3D) { /* 3DImage family left */
default_par->init_accel = image_init_accel;
default_par->wait_engine = image_wait_engine;
default_par->fill_rect = image_fill_rect;
default_par->copy_rect = image_copy_rect;
tridentfb_fix.accel = FB_ACCEL_TRIDENT_3DIMAGE;
} else { /* TGUI 9440/96XX family */
default_par->init_accel = tgui_init_accel;
default_par->wait_engine = xp_wait_engine;
default_par->fill_rect = tgui_fill_rect;
default_par->copy_rect = tgui_copy_rect;
tridentfb_fix.accel = FB_ACCEL_TRIDENT_TGUI;
}
default_par->chip_id = chip_id;
/* setup MMIO region */
tridentfb_fix.mmio_start = pci_resource_start(dev, 1);
tridentfb_fix.mmio_len = pci_resource_len(dev, 1);
if (!request_mem_region(tridentfb_fix.mmio_start,
tridentfb_fix.mmio_len, "tridentfb")) {
debug("request_region failed!\n");
framebuffer_release(info);
return -1;
}
default_par->io_virt = ioremap_nocache(tridentfb_fix.mmio_start,
tridentfb_fix.mmio_len);
if (!default_par->io_virt) {
debug("ioremap failed\n");
err = -1;
goto out_unmap1;
}
enable_mmio(default_par);
/* setup framebuffer memory */
tridentfb_fix.smem_start = pci_resource_start(dev, 0);
tridentfb_fix.smem_len = get_memsize(default_par);
if (!request_mem_region(tridentfb_fix.smem_start,
tridentfb_fix.smem_len, "tridentfb")) {
debug("request_mem_region failed!\n");
disable_mmio(info->par);
err = -1;
goto out_unmap1;
}
info->screen_base = ioremap_nocache(tridentfb_fix.smem_start,
tridentfb_fix.smem_len);
if (!info->screen_base) {
debug("ioremap failed\n");
err = -1;
goto out_unmap2;
}
default_par->flatpanel = is_flatpanel(default_par);
if (default_par->flatpanel)
nativex = get_nativex(default_par);
info->fix = tridentfb_fix;
info->fbops = &tridentfb_ops;
info->pseudo_palette = default_par->pseudo_pal;
info->flags = FBINFO_DEFAULT | FBINFO_HWACCEL_YPAN;
if (!noaccel && default_par->init_accel) {
info->flags &= ~FBINFO_HWACCEL_DISABLED;
info->flags |= FBINFO_HWACCEL_COPYAREA;
info->flags |= FBINFO_HWACCEL_FILLRECT;
} else
info->flags |= FBINFO_HWACCEL_DISABLED;
if (is_blade(chip_id) && chip_id != BLADE3D)
info->flags |= FBINFO_READS_FAST;
info->pixmap.addr = kmalloc(4096, GFP_KERNEL);
if (!info->pixmap.addr) {
err = -ENOMEM;
goto out_unmap2;
}
info->pixmap.size = 4096;
info->pixmap.buf_align = 4;
info->pixmap.scan_align = 1;
info->pixmap.access_align = 32;
info->pixmap.flags = FB_PIXMAP_SYSTEM;
if (default_par->image_blit) {
info->flags |= FBINFO_HWACCEL_IMAGEBLIT;
info->pixmap.scan_align = 4;
}
if (noaccel) {
printk(KERN_DEBUG "disabling acceleration\n");
info->flags |= FBINFO_HWACCEL_DISABLED;
info->pixmap.scan_align = 1;
}
if (!fb_find_mode(&info->var, info,
mode_option, NULL, 0, NULL, bpp)) {
err = -EINVAL;
goto out_unmap2;
}
err = fb_alloc_cmap(&info->cmap, 256, 0);
if (err < 0)
goto out_unmap2;
info->var.activate |= FB_ACTIVATE_NOW;
info->device = &dev->dev;
if (register_framebuffer(info) < 0) {
printk(KERN_ERR "tridentfb: could not register framebuffer\n");
fb_dealloc_cmap(&info->cmap);
err = -EINVAL;
goto out_unmap2;
}
output("fb%d: %s frame buffer device %dx%d-%dbpp\n",
info->node, info->fix.id, info->var.xres,
info->var.yres, info->var.bits_per_pixel);
pci_set_drvdata(dev, info);
return 0;
out_unmap2:
kfree(info->pixmap.addr);
if (info->screen_base)
iounmap(info->screen_base);
release_mem_region(tridentfb_fix.smem_start, tridentfb_fix.smem_len);
disable_mmio(info->par);
out_unmap1:
if (default_par->io_virt)
iounmap(default_par->io_virt);
release_mem_region(tridentfb_fix.mmio_start, tridentfb_fix.mmio_len);
framebuffer_release(info);
return err;
}
static void __devexit trident_pci_remove(struct pci_dev *dev)
{
struct fb_info *info = pci_get_drvdata(dev);
struct tridentfb_par *par = info->par;
unregister_framebuffer(info);
iounmap(par->io_virt);
iounmap(info->screen_base);
release_mem_region(tridentfb_fix.smem_start, tridentfb_fix.smem_len);
release_mem_region(tridentfb_fix.mmio_start, tridentfb_fix.mmio_len);
pci_set_drvdata(dev, NULL);
kfree(info->pixmap.addr);
fb_dealloc_cmap(&info->cmap);
framebuffer_release(info);
}
/* List of boards that we are trying to support */
static struct pci_device_id trident_devices[] = {
{PCI_VENDOR_ID_TRIDENT, BLADE3D, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{PCI_VENDOR_ID_TRIDENT, CYBERBLADEi7, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{PCI_VENDOR_ID_TRIDENT, CYBERBLADEi7D, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{PCI_VENDOR_ID_TRIDENT, CYBERBLADEi1, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{PCI_VENDOR_ID_TRIDENT, CYBERBLADEi1D, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{PCI_VENDOR_ID_TRIDENT, CYBERBLADEAi1, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{PCI_VENDOR_ID_TRIDENT, CYBERBLADEAi1D, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{PCI_VENDOR_ID_TRIDENT, CYBERBLADEE4, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{PCI_VENDOR_ID_TRIDENT, TGUI9440, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{PCI_VENDOR_ID_TRIDENT, TGUI9660, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{PCI_VENDOR_ID_TRIDENT, IMAGE975, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{PCI_VENDOR_ID_TRIDENT, IMAGE985, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{PCI_VENDOR_ID_TRIDENT, CYBER9320, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{PCI_VENDOR_ID_TRIDENT, CYBER9388, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{PCI_VENDOR_ID_TRIDENT, CYBER9520, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{PCI_VENDOR_ID_TRIDENT, CYBER9525DVD, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{PCI_VENDOR_ID_TRIDENT, CYBER9397, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{PCI_VENDOR_ID_TRIDENT, CYBER9397DVD, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{PCI_VENDOR_ID_TRIDENT, CYBERBLADEXPAi1, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{PCI_VENDOR_ID_TRIDENT, CYBERBLADEXPm8, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{PCI_VENDOR_ID_TRIDENT, CYBERBLADEXPm16, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{0,}
};
MODULE_DEVICE_TABLE(pci, trident_devices);
static struct pci_driver tridentfb_pci_driver = {
.name = "tridentfb",
.id_table = trident_devices,
.probe = trident_pci_probe,
.remove = __devexit_p(trident_pci_remove)
};
/*
* Parse user specified options (`video=trident:')
* example:
* video=trident:800x600,bpp=16,noaccel
*/
#ifndef MODULE
static int __init tridentfb_setup(char *options)
{
char *opt;
if (!options || !*options)
return 0;
while ((opt = strsep(&options, ",")) != NULL) {
if (!*opt)
continue;
if (!strncmp(opt, "noaccel", 7))
noaccel = 1;
else if (!strncmp(opt, "fp", 2))
fp = 1;
else if (!strncmp(opt, "crt", 3))
fp = 0;
else if (!strncmp(opt, "bpp=", 4))
bpp = simple_strtoul(opt + 4, NULL, 0);
else if (!strncmp(opt, "center", 6))
center = 1;
else if (!strncmp(opt, "stretch", 7))
stretch = 1;
else if (!strncmp(opt, "memsize=", 8))
memsize = simple_strtoul(opt + 8, NULL, 0);
else if (!strncmp(opt, "memdiff=", 8))
memdiff = simple_strtoul(opt + 8, NULL, 0);
else if (!strncmp(opt, "nativex=", 8))
nativex = simple_strtoul(opt + 8, NULL, 0);
else
mode_option = opt;
}
return 0;
}
#endif
static int __init tridentfb_init(void)
{
#ifndef MODULE
char *option = NULL;
if (fb_get_options("tridentfb", &option))
return -ENODEV;
tridentfb_setup(option);
#endif
return pci_register_driver(&tridentfb_pci_driver);
}
static void __exit tridentfb_exit(void)
{
pci_unregister_driver(&tridentfb_pci_driver);
}
module_init(tridentfb_init);
module_exit(tridentfb_exit);
MODULE_AUTHOR("Jani Monoses <jani@iv.ro>");
MODULE_DESCRIPTION("Framebuffer driver for Trident cards");
MODULE_LICENSE("GPL");
MODULE_ALIAS("cyblafb");
| gpl-2.0 |
Root-Box/kernel_samsung_smdk4412 | drivers/input/mouse/bcm5974.c | 868 | 27181 | /*
* Apple USB BCM5974 (Macbook Air and Penryn Macbook Pro) multitouch driver
*
* Copyright (C) 2008 Henrik Rydberg (rydberg@euromail.se)
*
* The USB initialization and package decoding was made by
* Scott Shawcroft as part of the touchd user-space driver project:
* Copyright (C) 2008 Scott Shawcroft (scott.shawcroft@gmail.com)
*
* The BCM5974 driver is based on the appletouch driver:
* Copyright (C) 2001-2004 Greg Kroah-Hartman (greg@kroah.com)
* Copyright (C) 2005 Johannes Berg (johannes@sipsolutions.net)
* Copyright (C) 2005 Stelian Pop (stelian@popies.net)
* Copyright (C) 2005 Frank Arnold (frank@scirocco-5v-turbo.de)
* Copyright (C) 2005 Peter Osterlund (petero2@telia.com)
* Copyright (C) 2005 Michael Hanselmann (linux-kernel@hansmi.ch)
* Copyright (C) 2006 Nicolas Boichat (nicolas@boichat.ch)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/usb/input.h>
#include <linux/hid.h>
#include <linux/mutex.h>
#define USB_VENDOR_ID_APPLE 0x05ac
/* MacbookAir, aka wellspring */
#define USB_DEVICE_ID_APPLE_WELLSPRING_ANSI 0x0223
#define USB_DEVICE_ID_APPLE_WELLSPRING_ISO 0x0224
#define USB_DEVICE_ID_APPLE_WELLSPRING_JIS 0x0225
/* MacbookProPenryn, aka wellspring2 */
#define USB_DEVICE_ID_APPLE_WELLSPRING2_ANSI 0x0230
#define USB_DEVICE_ID_APPLE_WELLSPRING2_ISO 0x0231
#define USB_DEVICE_ID_APPLE_WELLSPRING2_JIS 0x0232
/* Macbook5,1 (unibody), aka wellspring3 */
#define USB_DEVICE_ID_APPLE_WELLSPRING3_ANSI 0x0236
#define USB_DEVICE_ID_APPLE_WELLSPRING3_ISO 0x0237
#define USB_DEVICE_ID_APPLE_WELLSPRING3_JIS 0x0238
/* MacbookAir3,2 (unibody), aka wellspring5 */
#define USB_DEVICE_ID_APPLE_WELLSPRING4_ANSI 0x023f
#define USB_DEVICE_ID_APPLE_WELLSPRING4_ISO 0x0240
#define USB_DEVICE_ID_APPLE_WELLSPRING4_JIS 0x0241
/* MacbookAir3,1 (unibody), aka wellspring4 */
#define USB_DEVICE_ID_APPLE_WELLSPRING4A_ANSI 0x0242
#define USB_DEVICE_ID_APPLE_WELLSPRING4A_ISO 0x0243
#define USB_DEVICE_ID_APPLE_WELLSPRING4A_JIS 0x0244
/* Macbook8 (unibody, March 2011) */
#define USB_DEVICE_ID_APPLE_WELLSPRING5_ANSI 0x0245
#define USB_DEVICE_ID_APPLE_WELLSPRING5_ISO 0x0246
#define USB_DEVICE_ID_APPLE_WELLSPRING5_JIS 0x0247
#define BCM5974_DEVICE(prod) { \
.match_flags = (USB_DEVICE_ID_MATCH_DEVICE | \
USB_DEVICE_ID_MATCH_INT_CLASS | \
USB_DEVICE_ID_MATCH_INT_PROTOCOL), \
.idVendor = USB_VENDOR_ID_APPLE, \
.idProduct = (prod), \
.bInterfaceClass = USB_INTERFACE_CLASS_HID, \
.bInterfaceProtocol = USB_INTERFACE_PROTOCOL_MOUSE \
}
/* table of devices that work with this driver */
static const struct usb_device_id bcm5974_table[] = {
/* MacbookAir1.1 */
BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING_ANSI),
BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING_ISO),
BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING_JIS),
/* MacbookProPenryn */
BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING2_ANSI),
BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING2_ISO),
BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING2_JIS),
/* Macbook5,1 */
BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING3_ANSI),
BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING3_ISO),
BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING3_JIS),
/* MacbookAir3,2 */
BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING4_ANSI),
BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING4_ISO),
BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING4_JIS),
/* MacbookAir3,1 */
BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING4A_ANSI),
BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING4A_ISO),
BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING4A_JIS),
/* MacbookPro8 */
BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING5_ANSI),
BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING5_ISO),
BCM5974_DEVICE(USB_DEVICE_ID_APPLE_WELLSPRING5_JIS),
/* Terminating entry */
{}
};
MODULE_DEVICE_TABLE(usb, bcm5974_table);
MODULE_AUTHOR("Henrik Rydberg");
MODULE_DESCRIPTION("Apple USB BCM5974 multitouch driver");
MODULE_LICENSE("GPL");
#define dprintk(level, format, a...)\
{ if (debug >= level) printk(KERN_DEBUG format, ##a); }
static int debug = 1;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Activate debugging output");
/* button data structure */
struct bt_data {
u8 unknown1; /* constant */
u8 button; /* left button */
u8 rel_x; /* relative x coordinate */
u8 rel_y; /* relative y coordinate */
};
/* trackpad header types */
enum tp_type {
TYPE1, /* plain trackpad */
TYPE2 /* button integrated in trackpad */
};
/* trackpad finger data offsets, le16-aligned */
#define FINGER_TYPE1 (13 * sizeof(__le16))
#define FINGER_TYPE2 (15 * sizeof(__le16))
/* trackpad button data offsets */
#define BUTTON_TYPE2 15
/* list of device capability bits */
#define HAS_INTEGRATED_BUTTON 1
/* trackpad finger structure, le16-aligned */
struct tp_finger {
__le16 origin; /* zero when switching track finger */
__le16 abs_x; /* absolute x coodinate */
__le16 abs_y; /* absolute y coodinate */
__le16 rel_x; /* relative x coodinate */
__le16 rel_y; /* relative y coodinate */
__le16 size_major; /* finger size, major axis? */
__le16 size_minor; /* finger size, minor axis? */
__le16 orientation; /* 16384 when point, else 15 bit angle */
__le16 force_major; /* trackpad force, major axis? */
__le16 force_minor; /* trackpad force, minor axis? */
__le16 unused[3]; /* zeros */
__le16 multi; /* one finger: varies, more fingers: constant */
} __attribute__((packed,aligned(2)));
/* trackpad finger data size, empirically at least ten fingers */
#define SIZEOF_FINGER sizeof(struct tp_finger)
#define SIZEOF_ALL_FINGERS (16 * SIZEOF_FINGER)
#define MAX_FINGER_ORIENTATION 16384
/* device-specific parameters */
struct bcm5974_param {
int dim; /* logical dimension */
int fuzz; /* logical noise value */
int devmin; /* device minimum reading */
int devmax; /* device maximum reading */
};
/* device-specific configuration */
struct bcm5974_config {
int ansi, iso, jis; /* the product id of this device */
int caps; /* device capability bitmask */
int bt_ep; /* the endpoint of the button interface */
int bt_datalen; /* data length of the button interface */
int tp_ep; /* the endpoint of the trackpad interface */
enum tp_type tp_type; /* type of trackpad interface */
int tp_offset; /* offset to trackpad finger data */
int tp_datalen; /* data length of the trackpad interface */
struct bcm5974_param p; /* finger pressure limits */
struct bcm5974_param w; /* finger width limits */
struct bcm5974_param x; /* horizontal limits */
struct bcm5974_param y; /* vertical limits */
};
/* logical device structure */
struct bcm5974 {
char phys[64];
struct usb_device *udev; /* usb device */
struct usb_interface *intf; /* our interface */
struct input_dev *input; /* input dev */
struct bcm5974_config cfg; /* device configuration */
struct mutex pm_mutex; /* serialize access to open/suspend */
int opened; /* 1: opened, 0: closed */
struct urb *bt_urb; /* button usb request block */
struct bt_data *bt_data; /* button transferred data */
struct urb *tp_urb; /* trackpad usb request block */
u8 *tp_data; /* trackpad transferred data */
int fingers; /* number of fingers on trackpad */
};
/* logical dimensions */
#define DIM_PRESSURE 256 /* maximum finger pressure */
#define DIM_WIDTH 16 /* maximum finger width */
#define DIM_X 1280 /* maximum trackpad x value */
#define DIM_Y 800 /* maximum trackpad y value */
/* logical signal quality */
#define SN_PRESSURE 45 /* pressure signal-to-noise ratio */
#define SN_WIDTH 100 /* width signal-to-noise ratio */
#define SN_COORD 250 /* coordinate signal-to-noise ratio */
/* pressure thresholds */
#define PRESSURE_LOW (2 * DIM_PRESSURE / SN_PRESSURE)
#define PRESSURE_HIGH (3 * PRESSURE_LOW)
/* device constants */
static const struct bcm5974_config bcm5974_config_table[] = {
{
USB_DEVICE_ID_APPLE_WELLSPRING_ANSI,
USB_DEVICE_ID_APPLE_WELLSPRING_ISO,
USB_DEVICE_ID_APPLE_WELLSPRING_JIS,
0,
0x84, sizeof(struct bt_data),
0x81, TYPE1, FINGER_TYPE1, FINGER_TYPE1 + SIZEOF_ALL_FINGERS,
{ DIM_PRESSURE, DIM_PRESSURE / SN_PRESSURE, 0, 256 },
{ DIM_WIDTH, DIM_WIDTH / SN_WIDTH, 0, 2048 },
{ DIM_X, DIM_X / SN_COORD, -4824, 5342 },
{ DIM_Y, DIM_Y / SN_COORD, -172, 5820 }
},
{
USB_DEVICE_ID_APPLE_WELLSPRING2_ANSI,
USB_DEVICE_ID_APPLE_WELLSPRING2_ISO,
USB_DEVICE_ID_APPLE_WELLSPRING2_JIS,
0,
0x84, sizeof(struct bt_data),
0x81, TYPE1, FINGER_TYPE1, FINGER_TYPE1 + SIZEOF_ALL_FINGERS,
{ DIM_PRESSURE, DIM_PRESSURE / SN_PRESSURE, 0, 256 },
{ DIM_WIDTH, DIM_WIDTH / SN_WIDTH, 0, 2048 },
{ DIM_X, DIM_X / SN_COORD, -4824, 4824 },
{ DIM_Y, DIM_Y / SN_COORD, -172, 4290 }
},
{
USB_DEVICE_ID_APPLE_WELLSPRING3_ANSI,
USB_DEVICE_ID_APPLE_WELLSPRING3_ISO,
USB_DEVICE_ID_APPLE_WELLSPRING3_JIS,
HAS_INTEGRATED_BUTTON,
0x84, sizeof(struct bt_data),
0x81, TYPE2, FINGER_TYPE2, FINGER_TYPE2 + SIZEOF_ALL_FINGERS,
{ DIM_PRESSURE, DIM_PRESSURE / SN_PRESSURE, 0, 300 },
{ DIM_WIDTH, DIM_WIDTH / SN_WIDTH, 0, 2048 },
{ DIM_X, DIM_X / SN_COORD, -4460, 5166 },
{ DIM_Y, DIM_Y / SN_COORD, -75, 6700 }
},
{
USB_DEVICE_ID_APPLE_WELLSPRING4_ANSI,
USB_DEVICE_ID_APPLE_WELLSPRING4_ISO,
USB_DEVICE_ID_APPLE_WELLSPRING4_JIS,
HAS_INTEGRATED_BUTTON,
0x84, sizeof(struct bt_data),
0x81, TYPE2, FINGER_TYPE2, FINGER_TYPE2 + SIZEOF_ALL_FINGERS,
{ DIM_PRESSURE, DIM_PRESSURE / SN_PRESSURE, 0, 300 },
{ DIM_WIDTH, DIM_WIDTH / SN_WIDTH, 0, 2048 },
{ DIM_X, DIM_X / SN_COORD, -4620, 5140 },
{ DIM_Y, DIM_Y / SN_COORD, -150, 6600 }
},
{
USB_DEVICE_ID_APPLE_WELLSPRING4A_ANSI,
USB_DEVICE_ID_APPLE_WELLSPRING4A_ISO,
USB_DEVICE_ID_APPLE_WELLSPRING4A_JIS,
HAS_INTEGRATED_BUTTON,
0x84, sizeof(struct bt_data),
0x81, TYPE2, FINGER_TYPE2, FINGER_TYPE2 + SIZEOF_ALL_FINGERS,
{ DIM_PRESSURE, DIM_PRESSURE / SN_PRESSURE, 0, 300 },
{ DIM_WIDTH, DIM_WIDTH / SN_WIDTH, 0, 2048 },
{ DIM_X, DIM_X / SN_COORD, -4616, 5112 },
{ DIM_Y, DIM_Y / SN_COORD, -142, 5234 }
},
{
USB_DEVICE_ID_APPLE_WELLSPRING5_ANSI,
USB_DEVICE_ID_APPLE_WELLSPRING5_ISO,
USB_DEVICE_ID_APPLE_WELLSPRING5_JIS,
HAS_INTEGRATED_BUTTON,
0x84, sizeof(struct bt_data),
0x81, TYPE2, FINGER_TYPE2, FINGER_TYPE2 + SIZEOF_ALL_FINGERS,
{ DIM_PRESSURE, DIM_PRESSURE / SN_PRESSURE, 0, 300 },
{ DIM_WIDTH, DIM_WIDTH / SN_WIDTH, 0, 2048 },
{ DIM_X, DIM_X / SN_COORD, -4415, 5050 },
{ DIM_Y, DIM_Y / SN_COORD, -55, 6680 }
},
{}
};
/* return the device-specific configuration by device */
static const struct bcm5974_config *bcm5974_get_config(struct usb_device *udev)
{
u16 id = le16_to_cpu(udev->descriptor.idProduct);
const struct bcm5974_config *cfg;
for (cfg = bcm5974_config_table; cfg->ansi; ++cfg)
if (cfg->ansi == id || cfg->iso == id || cfg->jis == id)
return cfg;
return bcm5974_config_table;
}
/* convert 16-bit little endian to signed integer */
static inline int raw2int(__le16 x)
{
return (signed short)le16_to_cpu(x);
}
/* scale device data to logical dimensions (asserts devmin < devmax) */
static inline int int2scale(const struct bcm5974_param *p, int x)
{
return x * p->dim / (p->devmax - p->devmin);
}
/* all logical value ranges are [0,dim). */
static inline int int2bound(const struct bcm5974_param *p, int x)
{
int s = int2scale(p, x);
return clamp_val(s, 0, p->dim - 1);
}
/* setup which logical events to report */
static void setup_events_to_report(struct input_dev *input_dev,
const struct bcm5974_config *cfg)
{
__set_bit(EV_ABS, input_dev->evbit);
input_set_abs_params(input_dev, ABS_PRESSURE,
0, cfg->p.dim, cfg->p.fuzz, 0);
input_set_abs_params(input_dev, ABS_TOOL_WIDTH,
0, cfg->w.dim, cfg->w.fuzz, 0);
input_set_abs_params(input_dev, ABS_X,
0, cfg->x.dim, cfg->x.fuzz, 0);
input_set_abs_params(input_dev, ABS_Y,
0, cfg->y.dim, cfg->y.fuzz, 0);
/* finger touch area */
input_set_abs_params(input_dev, ABS_MT_TOUCH_MAJOR,
cfg->w.devmin, cfg->w.devmax, 0, 0);
input_set_abs_params(input_dev, ABS_MT_TOUCH_MINOR,
cfg->w.devmin, cfg->w.devmax, 0, 0);
/* finger approach area */
input_set_abs_params(input_dev, ABS_MT_WIDTH_MAJOR,
cfg->w.devmin, cfg->w.devmax, 0, 0);
input_set_abs_params(input_dev, ABS_MT_WIDTH_MINOR,
cfg->w.devmin, cfg->w.devmax, 0, 0);
/* finger orientation */
input_set_abs_params(input_dev, ABS_MT_ORIENTATION,
-MAX_FINGER_ORIENTATION,
MAX_FINGER_ORIENTATION, 0, 0);
/* finger position */
input_set_abs_params(input_dev, ABS_MT_POSITION_X,
cfg->x.devmin, cfg->x.devmax, 0, 0);
input_set_abs_params(input_dev, ABS_MT_POSITION_Y,
cfg->y.devmin, cfg->y.devmax, 0, 0);
__set_bit(EV_KEY, input_dev->evbit);
__set_bit(BTN_TOUCH, input_dev->keybit);
__set_bit(BTN_TOOL_FINGER, input_dev->keybit);
__set_bit(BTN_TOOL_DOUBLETAP, input_dev->keybit);
__set_bit(BTN_TOOL_TRIPLETAP, input_dev->keybit);
__set_bit(BTN_TOOL_QUADTAP, input_dev->keybit);
__set_bit(BTN_LEFT, input_dev->keybit);
if (cfg->caps & HAS_INTEGRATED_BUTTON)
__set_bit(INPUT_PROP_BUTTONPAD, input_dev->propbit);
input_set_events_per_packet(input_dev, 60);
}
/* report button data as logical button state */
static int report_bt_state(struct bcm5974 *dev, int size)
{
if (size != sizeof(struct bt_data))
return -EIO;
dprintk(7,
"bcm5974: button data: %x %x %x %x\n",
dev->bt_data->unknown1, dev->bt_data->button,
dev->bt_data->rel_x, dev->bt_data->rel_y);
input_report_key(dev->input, BTN_LEFT, dev->bt_data->button);
input_sync(dev->input);
return 0;
}
static void report_finger_data(struct input_dev *input,
const struct bcm5974_config *cfg,
const struct tp_finger *f)
{
input_report_abs(input, ABS_MT_TOUCH_MAJOR,
raw2int(f->force_major) << 1);
input_report_abs(input, ABS_MT_TOUCH_MINOR,
raw2int(f->force_minor) << 1);
input_report_abs(input, ABS_MT_WIDTH_MAJOR,
raw2int(f->size_major) << 1);
input_report_abs(input, ABS_MT_WIDTH_MINOR,
raw2int(f->size_minor) << 1);
input_report_abs(input, ABS_MT_ORIENTATION,
MAX_FINGER_ORIENTATION - raw2int(f->orientation));
input_report_abs(input, ABS_MT_POSITION_X, raw2int(f->abs_x));
input_report_abs(input, ABS_MT_POSITION_Y,
cfg->y.devmin + cfg->y.devmax - raw2int(f->abs_y));
input_mt_sync(input);
}
/* report trackpad data as logical trackpad state */
static int report_tp_state(struct bcm5974 *dev, int size)
{
const struct bcm5974_config *c = &dev->cfg;
const struct tp_finger *f;
struct input_dev *input = dev->input;
int raw_p, raw_w, raw_x, raw_y, raw_n, i;
int ptest, origin, ibt = 0, nmin = 0, nmax = 0;
int abs_p = 0, abs_w = 0, abs_x = 0, abs_y = 0;
if (size < c->tp_offset || (size - c->tp_offset) % SIZEOF_FINGER != 0)
return -EIO;
/* finger data, le16-aligned */
f = (const struct tp_finger *)(dev->tp_data + c->tp_offset);
raw_n = (size - c->tp_offset) / SIZEOF_FINGER;
/* always track the first finger; when detached, start over */
if (raw_n) {
/* report raw trackpad data */
for (i = 0; i < raw_n; i++)
report_finger_data(input, c, &f[i]);
raw_p = raw2int(f->force_major);
raw_w = raw2int(f->size_major);
raw_x = raw2int(f->abs_x);
raw_y = raw2int(f->abs_y);
dprintk(9,
"bcm5974: "
"raw: p: %+05d w: %+05d x: %+05d y: %+05d n: %d\n",
raw_p, raw_w, raw_x, raw_y, raw_n);
ptest = int2bound(&c->p, raw_p);
origin = raw2int(f->origin);
/* while tracking finger still valid, count all fingers */
if (ptest > PRESSURE_LOW && origin) {
abs_p = ptest;
abs_w = int2bound(&c->w, raw_w);
abs_x = int2bound(&c->x, raw_x - c->x.devmin);
abs_y = int2bound(&c->y, c->y.devmax - raw_y);
while (raw_n--) {
ptest = int2bound(&c->p,
raw2int(f->force_major));
if (ptest > PRESSURE_LOW)
nmax++;
if (ptest > PRESSURE_HIGH)
nmin++;
f++;
}
}
}
/* set the integrated button if applicable */
if (c->tp_type == TYPE2)
ibt = raw2int(dev->tp_data[BUTTON_TYPE2]);
if (dev->fingers < nmin)
dev->fingers = nmin;
if (dev->fingers > nmax)
dev->fingers = nmax;
input_report_key(input, BTN_TOUCH, dev->fingers > 0);
input_report_key(input, BTN_TOOL_FINGER, dev->fingers == 1);
input_report_key(input, BTN_TOOL_DOUBLETAP, dev->fingers == 2);
input_report_key(input, BTN_TOOL_TRIPLETAP, dev->fingers == 3);
input_report_key(input, BTN_TOOL_QUADTAP, dev->fingers > 3);
input_report_abs(input, ABS_PRESSURE, abs_p);
input_report_abs(input, ABS_TOOL_WIDTH, abs_w);
if (abs_p) {
input_report_abs(input, ABS_X, abs_x);
input_report_abs(input, ABS_Y, abs_y);
dprintk(8,
"bcm5974: abs: p: %+05d w: %+05d x: %+05d y: %+05d "
"nmin: %d nmax: %d n: %d ibt: %d\n", abs_p, abs_w,
abs_x, abs_y, nmin, nmax, dev->fingers, ibt);
}
/* type 2 reports button events via ibt only */
if (c->tp_type == TYPE2)
input_report_key(input, BTN_LEFT, ibt);
input_sync(input);
return 0;
}
/* Wellspring initialization constants */
#define BCM5974_WELLSPRING_MODE_READ_REQUEST_ID 1
#define BCM5974_WELLSPRING_MODE_WRITE_REQUEST_ID 9
#define BCM5974_WELLSPRING_MODE_REQUEST_VALUE 0x300
#define BCM5974_WELLSPRING_MODE_REQUEST_INDEX 0
#define BCM5974_WELLSPRING_MODE_VENDOR_VALUE 0x01
#define BCM5974_WELLSPRING_MODE_NORMAL_VALUE 0x08
static int bcm5974_wellspring_mode(struct bcm5974 *dev, bool on)
{
char *data = kmalloc(8, GFP_KERNEL);
int retval = 0, size;
if (!data) {
err("bcm5974: out of memory");
retval = -ENOMEM;
goto out;
}
/* read configuration */
size = usb_control_msg(dev->udev, usb_rcvctrlpipe(dev->udev, 0),
BCM5974_WELLSPRING_MODE_READ_REQUEST_ID,
USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
BCM5974_WELLSPRING_MODE_REQUEST_VALUE,
BCM5974_WELLSPRING_MODE_REQUEST_INDEX, data, 8, 5000);
if (size != 8) {
err("bcm5974: could not read from device");
retval = -EIO;
goto out;
}
/* apply the mode switch */
data[0] = on ?
BCM5974_WELLSPRING_MODE_VENDOR_VALUE :
BCM5974_WELLSPRING_MODE_NORMAL_VALUE;
/* write configuration */
size = usb_control_msg(dev->udev, usb_sndctrlpipe(dev->udev, 0),
BCM5974_WELLSPRING_MODE_WRITE_REQUEST_ID,
USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
BCM5974_WELLSPRING_MODE_REQUEST_VALUE,
BCM5974_WELLSPRING_MODE_REQUEST_INDEX, data, 8, 5000);
if (size != 8) {
err("bcm5974: could not write to device");
retval = -EIO;
goto out;
}
dprintk(2, "bcm5974: switched to %s mode.\n",
on ? "wellspring" : "normal");
out:
kfree(data);
return retval;
}
static void bcm5974_irq_button(struct urb *urb)
{
struct bcm5974 *dev = urb->context;
int error;
switch (urb->status) {
case 0:
break;
case -EOVERFLOW:
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
dbg("bcm5974: button urb shutting down: %d", urb->status);
return;
default:
dbg("bcm5974: button urb status: %d", urb->status);
goto exit;
}
if (report_bt_state(dev, dev->bt_urb->actual_length))
dprintk(1, "bcm5974: bad button package, length: %d\n",
dev->bt_urb->actual_length);
exit:
error = usb_submit_urb(dev->bt_urb, GFP_ATOMIC);
if (error)
err("bcm5974: button urb failed: %d", error);
}
static void bcm5974_irq_trackpad(struct urb *urb)
{
struct bcm5974 *dev = urb->context;
int error;
switch (urb->status) {
case 0:
break;
case -EOVERFLOW:
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
dbg("bcm5974: trackpad urb shutting down: %d", urb->status);
return;
default:
dbg("bcm5974: trackpad urb status: %d", urb->status);
goto exit;
}
/* control response ignored */
if (dev->tp_urb->actual_length == 2)
goto exit;
if (report_tp_state(dev, dev->tp_urb->actual_length))
dprintk(1, "bcm5974: bad trackpad package, length: %d\n",
dev->tp_urb->actual_length);
exit:
error = usb_submit_urb(dev->tp_urb, GFP_ATOMIC);
if (error)
err("bcm5974: trackpad urb failed: %d", error);
}
/*
* The Wellspring trackpad, like many recent Apple trackpads, share
* the usb device with the keyboard. Since keyboards are usually
* handled by the HID system, the device ends up being handled by two
* modules. Setting up the device therefore becomes slightly
* complicated. To enable multitouch features, a mode switch is
* required, which is usually applied via the control interface of the
* device. It can be argued where this switch should take place. In
* some drivers, like appletouch, the switch is made during
* probe. However, the hid module may also alter the state of the
* device, resulting in trackpad malfunction under certain
* circumstances. To get around this problem, there is at least one
* example that utilizes the USB_QUIRK_RESET_RESUME quirk in order to
* receive a reset_resume request rather than the normal resume.
* Since the implementation of reset_resume is equal to mode switch
* plus start_traffic, it seems easier to always do the switch when
* starting traffic on the device.
*/
static int bcm5974_start_traffic(struct bcm5974 *dev)
{
int error;
error = bcm5974_wellspring_mode(dev, true);
if (error) {
dprintk(1, "bcm5974: mode switch failed\n");
goto err_out;
}
error = usb_submit_urb(dev->bt_urb, GFP_KERNEL);
if (error)
goto err_reset_mode;
error = usb_submit_urb(dev->tp_urb, GFP_KERNEL);
if (error)
goto err_kill_bt;
return 0;
err_kill_bt:
usb_kill_urb(dev->bt_urb);
err_reset_mode:
bcm5974_wellspring_mode(dev, false);
err_out:
return error;
}
static void bcm5974_pause_traffic(struct bcm5974 *dev)
{
usb_kill_urb(dev->tp_urb);
usb_kill_urb(dev->bt_urb);
bcm5974_wellspring_mode(dev, false);
}
/*
* The code below implements open/close and manual suspend/resume.
* All functions may be called in random order.
*
* Opening a suspended device fails with EACCES - permission denied.
*
* Failing a resume leaves the device resumed but closed.
*/
static int bcm5974_open(struct input_dev *input)
{
struct bcm5974 *dev = input_get_drvdata(input);
int error;
error = usb_autopm_get_interface(dev->intf);
if (error)
return error;
mutex_lock(&dev->pm_mutex);
error = bcm5974_start_traffic(dev);
if (!error)
dev->opened = 1;
mutex_unlock(&dev->pm_mutex);
if (error)
usb_autopm_put_interface(dev->intf);
return error;
}
static void bcm5974_close(struct input_dev *input)
{
struct bcm5974 *dev = input_get_drvdata(input);
mutex_lock(&dev->pm_mutex);
bcm5974_pause_traffic(dev);
dev->opened = 0;
mutex_unlock(&dev->pm_mutex);
usb_autopm_put_interface(dev->intf);
}
static int bcm5974_suspend(struct usb_interface *iface, pm_message_t message)
{
struct bcm5974 *dev = usb_get_intfdata(iface);
mutex_lock(&dev->pm_mutex);
if (dev->opened)
bcm5974_pause_traffic(dev);
mutex_unlock(&dev->pm_mutex);
return 0;
}
static int bcm5974_resume(struct usb_interface *iface)
{
struct bcm5974 *dev = usb_get_intfdata(iface);
int error = 0;
mutex_lock(&dev->pm_mutex);
if (dev->opened)
error = bcm5974_start_traffic(dev);
mutex_unlock(&dev->pm_mutex);
return error;
}
static int bcm5974_probe(struct usb_interface *iface,
const struct usb_device_id *id)
{
struct usb_device *udev = interface_to_usbdev(iface);
const struct bcm5974_config *cfg;
struct bcm5974 *dev;
struct input_dev *input_dev;
int error = -ENOMEM;
/* find the product index */
cfg = bcm5974_get_config(udev);
/* allocate memory for our device state and initialize it */
dev = kzalloc(sizeof(struct bcm5974), GFP_KERNEL);
input_dev = input_allocate_device();
if (!dev || !input_dev) {
err("bcm5974: out of memory");
goto err_free_devs;
}
dev->udev = udev;
dev->intf = iface;
dev->input = input_dev;
dev->cfg = *cfg;
mutex_init(&dev->pm_mutex);
/* setup urbs */
dev->bt_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!dev->bt_urb)
goto err_free_devs;
dev->tp_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!dev->tp_urb)
goto err_free_bt_urb;
dev->bt_data = usb_alloc_coherent(dev->udev,
dev->cfg.bt_datalen, GFP_KERNEL,
&dev->bt_urb->transfer_dma);
if (!dev->bt_data)
goto err_free_urb;
dev->tp_data = usb_alloc_coherent(dev->udev,
dev->cfg.tp_datalen, GFP_KERNEL,
&dev->tp_urb->transfer_dma);
if (!dev->tp_data)
goto err_free_bt_buffer;
usb_fill_int_urb(dev->bt_urb, udev,
usb_rcvintpipe(udev, cfg->bt_ep),
dev->bt_data, dev->cfg.bt_datalen,
bcm5974_irq_button, dev, 1);
usb_fill_int_urb(dev->tp_urb, udev,
usb_rcvintpipe(udev, cfg->tp_ep),
dev->tp_data, dev->cfg.tp_datalen,
bcm5974_irq_trackpad, dev, 1);
/* create bcm5974 device */
usb_make_path(udev, dev->phys, sizeof(dev->phys));
strlcat(dev->phys, "/input0", sizeof(dev->phys));
input_dev->name = "bcm5974";
input_dev->phys = dev->phys;
usb_to_input_id(dev->udev, &input_dev->id);
/* report driver capabilities via the version field */
input_dev->id.version = cfg->caps;
input_dev->dev.parent = &iface->dev;
input_set_drvdata(input_dev, dev);
input_dev->open = bcm5974_open;
input_dev->close = bcm5974_close;
setup_events_to_report(input_dev, cfg);
error = input_register_device(dev->input);
if (error)
goto err_free_buffer;
/* save our data pointer in this interface device */
usb_set_intfdata(iface, dev);
return 0;
err_free_buffer:
usb_free_coherent(dev->udev, dev->cfg.tp_datalen,
dev->tp_data, dev->tp_urb->transfer_dma);
err_free_bt_buffer:
usb_free_coherent(dev->udev, dev->cfg.bt_datalen,
dev->bt_data, dev->bt_urb->transfer_dma);
err_free_urb:
usb_free_urb(dev->tp_urb);
err_free_bt_urb:
usb_free_urb(dev->bt_urb);
err_free_devs:
usb_set_intfdata(iface, NULL);
input_free_device(input_dev);
kfree(dev);
return error;
}
static void bcm5974_disconnect(struct usb_interface *iface)
{
struct bcm5974 *dev = usb_get_intfdata(iface);
usb_set_intfdata(iface, NULL);
input_unregister_device(dev->input);
usb_free_coherent(dev->udev, dev->cfg.tp_datalen,
dev->tp_data, dev->tp_urb->transfer_dma);
usb_free_coherent(dev->udev, dev->cfg.bt_datalen,
dev->bt_data, dev->bt_urb->transfer_dma);
usb_free_urb(dev->tp_urb);
usb_free_urb(dev->bt_urb);
kfree(dev);
}
static struct usb_driver bcm5974_driver = {
.name = "bcm5974",
.probe = bcm5974_probe,
.disconnect = bcm5974_disconnect,
.suspend = bcm5974_suspend,
.resume = bcm5974_resume,
.id_table = bcm5974_table,
.supports_autosuspend = 1,
};
static int __init bcm5974_init(void)
{
return usb_register(&bcm5974_driver);
}
static void __exit bcm5974_exit(void)
{
usb_deregister(&bcm5974_driver);
}
module_init(bcm5974_init);
module_exit(bcm5974_exit);
| gpl-2.0 |
Jackeagle/kernel_samsung_stock | fs/ext4/page-io.c | 1124 | 12252 | /*
* linux/fs/ext4/page-io.c
*
* This contains the new page_io functions for ext4
*
* Written by Theodore Ts'o, 2010.
*/
#include <linux/fs.h>
#include <linux/time.h>
#include <linux/jbd2.h>
#include <linux/highuid.h>
#include <linux/pagemap.h>
#include <linux/quotaops.h>
#include <linux/string.h>
#include <linux/buffer_head.h>
#include <linux/writeback.h>
#include <linux/pagevec.h>
#include <linux/mpage.h>
#include <linux/namei.h>
#include <linux/aio.h>
#include <linux/uio.h>
#include <linux/bio.h>
#include <linux/workqueue.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include "ext4_jbd2.h"
#include "xattr.h"
#include "acl.h"
static struct kmem_cache *io_end_cachep;
int __init ext4_init_pageio(void)
{
io_end_cachep = KMEM_CACHE(ext4_io_end, SLAB_RECLAIM_ACCOUNT);
if (io_end_cachep == NULL)
return -ENOMEM;
return 0;
}
void ext4_exit_pageio(void)
{
kmem_cache_destroy(io_end_cachep);
}
/*
* This function is called by ext4_evict_inode() to make sure there is
* no more pending I/O completion work left to do.
*/
void ext4_ioend_shutdown(struct inode *inode)
{
wait_queue_head_t *wq = ext4_ioend_wq(inode);
wait_event(*wq, (atomic_read(&EXT4_I(inode)->i_ioend_count) == 0));
/*
* We need to make sure the work structure is finished being
* used before we let the inode get destroyed.
*/
if (work_pending(&EXT4_I(inode)->i_unwritten_work))
cancel_work_sync(&EXT4_I(inode)->i_unwritten_work);
}
void ext4_free_io_end(ext4_io_end_t *io)
{
BUG_ON(!io);
BUG_ON(!list_empty(&io->list));
BUG_ON(io->flag & EXT4_IO_END_UNWRITTEN);
if (atomic_dec_and_test(&EXT4_I(io->inode)->i_ioend_count))
wake_up_all(ext4_ioend_wq(io->inode));
kmem_cache_free(io_end_cachep, io);
}
/* check a range of space and convert unwritten extents to written. */
static int ext4_end_io(ext4_io_end_t *io)
{
struct inode *inode = io->inode;
loff_t offset = io->offset;
ssize_t size = io->size;
int ret = 0;
ext4_debug("ext4_end_io_nolock: io 0x%p from inode %lu,list->next 0x%p,"
"list->prev 0x%p\n",
io, inode->i_ino, io->list.next, io->list.prev);
ret = ext4_convert_unwritten_extents(inode, offset, size);
if (ret < 0) {
ext4_msg(inode->i_sb, KERN_EMERG,
"failed to convert unwritten extents to written "
"extents -- potential data loss! "
"(inode %lu, offset %llu, size %zd, error %d)",
inode->i_ino, offset, size, ret);
}
/* Wake up anyone waiting on unwritten extent conversion */
if (atomic_dec_and_test(&EXT4_I(inode)->i_unwritten))
wake_up_all(ext4_ioend_wq(inode));
if (io->flag & EXT4_IO_END_DIRECT)
inode_dio_done(inode);
if (io->iocb)
aio_complete(io->iocb, io->result, 0);
return ret;
}
static void dump_completed_IO(struct inode *inode)
{
#ifdef EXT4FS_DEBUG
struct list_head *cur, *before, *after;
ext4_io_end_t *io, *io0, *io1;
if (list_empty(&EXT4_I(inode)->i_completed_io_list)) {
ext4_debug("inode %lu completed_io list is empty\n",
inode->i_ino);
return;
}
ext4_debug("Dump inode %lu completed_io list\n", inode->i_ino);
list_for_each_entry(io, &EXT4_I(inode)->i_completed_io_list, list) {
cur = &io->list;
before = cur->prev;
io0 = container_of(before, ext4_io_end_t, list);
after = cur->next;
io1 = container_of(after, ext4_io_end_t, list);
ext4_debug("io 0x%p from inode %lu,prev 0x%p,next 0x%p\n",
io, inode->i_ino, io0, io1);
}
#endif
}
/* Add the io_end to per-inode completed end_io list. */
void ext4_add_complete_io(ext4_io_end_t *io_end)
{
struct ext4_inode_info *ei = EXT4_I(io_end->inode);
struct workqueue_struct *wq;
unsigned long flags;
BUG_ON(!(io_end->flag & EXT4_IO_END_UNWRITTEN));
wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq;
spin_lock_irqsave(&ei->i_completed_io_lock, flags);
if (list_empty(&ei->i_completed_io_list))
queue_work(wq, &ei->i_unwritten_work);
list_add_tail(&io_end->list, &ei->i_completed_io_list);
spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
}
static int ext4_do_flush_completed_IO(struct inode *inode)
{
ext4_io_end_t *io;
struct list_head unwritten;
unsigned long flags;
struct ext4_inode_info *ei = EXT4_I(inode);
int err, ret = 0;
spin_lock_irqsave(&ei->i_completed_io_lock, flags);
dump_completed_IO(inode);
list_replace_init(&ei->i_completed_io_list, &unwritten);
spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
while (!list_empty(&unwritten)) {
io = list_entry(unwritten.next, ext4_io_end_t, list);
BUG_ON(!(io->flag & EXT4_IO_END_UNWRITTEN));
list_del_init(&io->list);
err = ext4_end_io(io);
if (unlikely(!ret && err))
ret = err;
io->flag &= ~EXT4_IO_END_UNWRITTEN;
ext4_free_io_end(io);
}
return ret;
}
/*
* work on completed aio dio IO, to convert unwritten extents to extents
*/
void ext4_end_io_work(struct work_struct *work)
{
struct ext4_inode_info *ei = container_of(work, struct ext4_inode_info,
i_unwritten_work);
ext4_do_flush_completed_IO(&ei->vfs_inode);
}
int ext4_flush_unwritten_io(struct inode *inode)
{
int ret;
WARN_ON_ONCE(!mutex_is_locked(&inode->i_mutex) &&
!(inode->i_state & I_FREEING));
ret = ext4_do_flush_completed_IO(inode);
ext4_unwritten_wait(inode);
return ret;
}
ext4_io_end_t *ext4_init_io_end(struct inode *inode, gfp_t flags)
{
ext4_io_end_t *io = kmem_cache_zalloc(io_end_cachep, flags);
if (io) {
atomic_inc(&EXT4_I(inode)->i_ioend_count);
io->inode = inode;
INIT_LIST_HEAD(&io->list);
}
return io;
}
/*
* Print an buffer I/O error compatible with the fs/buffer.c. This
* provides compatibility with dmesg scrapers that look for a specific
* buffer I/O error message. We really need a unified error reporting
* structure to userspace ala Digital Unix's uerf system, but it's
* probably not going to happen in my lifetime, due to LKML politics...
*/
static void buffer_io_error(struct buffer_head *bh)
{
char b[BDEVNAME_SIZE];
printk(KERN_ERR "Buffer I/O error on device %s, logical block %llu\n",
bdevname(bh->b_bdev, b),
(unsigned long long)bh->b_blocknr);
}
static void ext4_end_bio(struct bio *bio, int error)
{
ext4_io_end_t *io_end = bio->bi_private;
struct inode *inode;
int i;
int blocksize;
sector_t bi_sector = bio->bi_sector;
BUG_ON(!io_end);
inode = io_end->inode;
blocksize = 1 << inode->i_blkbits;
bio->bi_private = NULL;
bio->bi_end_io = NULL;
if (test_bit(BIO_UPTODATE, &bio->bi_flags))
error = 0;
for (i = 0; i < bio->bi_vcnt; i++) {
struct bio_vec *bvec = &bio->bi_io_vec[i];
struct page *page = bvec->bv_page;
struct buffer_head *bh, *head;
unsigned bio_start = bvec->bv_offset;
unsigned bio_end = bio_start + bvec->bv_len;
unsigned under_io = 0;
unsigned long flags;
if (!page)
continue;
if (error) {
SetPageError(page);
set_bit(AS_EIO, &page->mapping->flags);
}
bh = head = page_buffers(page);
/*
* We check all buffers in the page under BH_Uptodate_Lock
* to avoid races with other end io clearing async_write flags
*/
local_irq_save(flags);
bit_spin_lock(BH_Uptodate_Lock, &head->b_state);
do {
if (bh_offset(bh) < bio_start ||
bh_offset(bh) + blocksize > bio_end) {
if (buffer_async_write(bh))
under_io++;
continue;
}
clear_buffer_async_write(bh);
if (error)
buffer_io_error(bh);
} while ((bh = bh->b_this_page) != head);
bit_spin_unlock(BH_Uptodate_Lock, &head->b_state);
local_irq_restore(flags);
if (!under_io)
end_page_writeback(page);
}
bio_put(bio);
if (error) {
io_end->flag |= EXT4_IO_END_ERROR;
ext4_warning(inode->i_sb, "I/O error writing to inode %lu "
"(offset %llu size %ld starting block %llu)",
inode->i_ino,
(unsigned long long) io_end->offset,
(long) io_end->size,
(unsigned long long)
bi_sector >> (inode->i_blkbits - 9));
}
if (!(io_end->flag & EXT4_IO_END_UNWRITTEN)) {
ext4_free_io_end(io_end);
return;
}
ext4_add_complete_io(io_end);
}
void ext4_io_submit(struct ext4_io_submit *io)
{
struct bio *bio = io->io_bio;
if (bio) {
bio_get(io->io_bio);
submit_bio(io->io_op, io->io_bio);
BUG_ON(bio_flagged(io->io_bio, BIO_EOPNOTSUPP));
bio_put(io->io_bio);
}
io->io_bio = NULL;
io->io_op = 0;
io->io_end = NULL;
}
static int io_submit_init(struct ext4_io_submit *io,
struct inode *inode,
struct writeback_control *wbc,
struct buffer_head *bh)
{
ext4_io_end_t *io_end;
struct page *page = bh->b_page;
int nvecs = bio_get_nr_vecs(bh->b_bdev);
struct bio *bio;
io_end = ext4_init_io_end(inode, GFP_NOFS);
if (!io_end)
return -ENOMEM;
bio = bio_alloc(GFP_NOIO, min(nvecs, BIO_MAX_PAGES));
bio->bi_sector = bh->b_blocknr * (bh->b_size >> 9);
bio->bi_bdev = bh->b_bdev;
bio->bi_private = io->io_end = io_end;
bio->bi_end_io = ext4_end_bio;
io_end->offset = (page->index << PAGE_CACHE_SHIFT) + bh_offset(bh);
io->io_bio = bio;
io->io_op = (wbc->sync_mode == WB_SYNC_ALL ? WRITE_SYNC : WRITE);
io->io_next_block = bh->b_blocknr;
return 0;
}
static int io_submit_add_bh(struct ext4_io_submit *io,
struct inode *inode,
struct writeback_control *wbc,
struct buffer_head *bh)
{
ext4_io_end_t *io_end;
int ret;
if (io->io_bio && bh->b_blocknr != io->io_next_block) {
submit_and_retry:
ext4_io_submit(io);
}
if (io->io_bio == NULL) {
ret = io_submit_init(io, inode, wbc, bh);
if (ret)
return ret;
}
io_end = io->io_end;
if (test_clear_buffer_uninit(bh))
ext4_set_io_unwritten_flag(inode, io_end);
io->io_end->size += bh->b_size;
io->io_next_block++;
ret = bio_add_page(io->io_bio, bh->b_page, bh->b_size, bh_offset(bh));
if (ret != bh->b_size)
goto submit_and_retry;
return 0;
}
int ext4_bio_write_page(struct ext4_io_submit *io,
struct page *page,
int len,
struct writeback_control *wbc)
{
struct inode *inode = page->mapping->host;
unsigned block_start, blocksize;
struct buffer_head *bh, *head;
int ret = 0;
int nr_submitted = 0;
blocksize = 1 << inode->i_blkbits;
BUG_ON(!PageLocked(page));
BUG_ON(PageWriteback(page));
set_page_writeback(page);
ClearPageError(page);
/*
* Comments copied from block_write_full_page_endio:
*
* The page straddles i_size. It must be zeroed out on each and every
* writepage invocation because it may be mmapped. "A file is mapped
* in multiples of the page size. For a file that is not a multiple of
* the page size, the remaining memory is zeroed when mapped, and
* writes to that region are not written out to the file."
*/
if (len < PAGE_CACHE_SIZE)
zero_user_segment(page, len, PAGE_CACHE_SIZE);
/*
* In the first loop we prepare and mark buffers to submit. We have to
* mark all buffers in the page before submitting so that
* end_page_writeback() cannot be called from ext4_bio_end_io() when IO
* on the first buffer finishes and we are still working on submitting
* the second buffer.
*/
bh = head = page_buffers(page);
do {
block_start = bh_offset(bh);
if (block_start >= len) {
clear_buffer_dirty(bh);
set_buffer_uptodate(bh);
continue;
}
if (!buffer_dirty(bh) || buffer_delay(bh) ||
!buffer_mapped(bh) || buffer_unwritten(bh)) {
/* A hole? We can safely clear the dirty bit */
if (!buffer_mapped(bh))
clear_buffer_dirty(bh);
if (io->io_bio)
ext4_io_submit(io);
continue;
}
if (buffer_new(bh)) {
clear_buffer_new(bh);
unmap_underlying_metadata(bh->b_bdev, bh->b_blocknr);
}
set_buffer_async_write(bh);
} while ((bh = bh->b_this_page) != head);
/* Now submit buffers to write */
bh = head = page_buffers(page);
do {
if (!buffer_async_write(bh))
continue;
ret = io_submit_add_bh(io, inode, wbc, bh);
if (ret) {
/*
* We only get here on ENOMEM. Not much else
* we can do but mark the page as dirty, and
* better luck next time.
*/
redirty_page_for_writepage(wbc, page);
break;
}
nr_submitted++;
clear_buffer_dirty(bh);
} while ((bh = bh->b_this_page) != head);
/* Error stopped previous loop? Clean up buffers... */
if (ret) {
do {
clear_buffer_async_write(bh);
bh = bh->b_this_page;
} while (bh != head);
}
unlock_page(page);
/* Nothing submitted - we have to end page writeback */
if (!nr_submitted)
end_page_writeback(page);
return ret;
}
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.