repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
xtrymind/android_kernel_msm | drivers/video/backlight/generic_bl.c | 4594 | 3482 | /*
* Generic Backlight Driver
*
* Copyright (c) 2004-2008 Richard Purdie
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/mutex.h>
#include <linux/fb.h>
#include <linux/backlight.h>
static int genericbl_intensity;
static struct backlight_device *generic_backlight_device;
static struct generic_bl_info *bl_machinfo;
/* Flag to signal when the battery is low */
#define GENERICBL_BATTLOW BL_CORE_DRIVER1
static int genericbl_send_intensity(struct backlight_device *bd)
{
int intensity = bd->props.brightness;
if (bd->props.power != FB_BLANK_UNBLANK)
intensity = 0;
if (bd->props.state & BL_CORE_FBBLANK)
intensity = 0;
if (bd->props.state & BL_CORE_SUSPENDED)
intensity = 0;
if (bd->props.state & GENERICBL_BATTLOW)
intensity &= bl_machinfo->limit_mask;
bl_machinfo->set_bl_intensity(intensity);
genericbl_intensity = intensity;
if (bl_machinfo->kick_battery)
bl_machinfo->kick_battery();
return 0;
}
static int genericbl_get_intensity(struct backlight_device *bd)
{
return genericbl_intensity;
}
/*
* Called when the battery is low to limit the backlight intensity.
* If limit==0 clear any limit, otherwise limit the intensity
*/
void genericbl_limit_intensity(int limit)
{
struct backlight_device *bd = generic_backlight_device;
mutex_lock(&bd->ops_lock);
if (limit)
bd->props.state |= GENERICBL_BATTLOW;
else
bd->props.state &= ~GENERICBL_BATTLOW;
backlight_update_status(generic_backlight_device);
mutex_unlock(&bd->ops_lock);
}
EXPORT_SYMBOL(genericbl_limit_intensity);
static const struct backlight_ops genericbl_ops = {
.options = BL_CORE_SUSPENDRESUME,
.get_brightness = genericbl_get_intensity,
.update_status = genericbl_send_intensity,
};
static int genericbl_probe(struct platform_device *pdev)
{
struct backlight_properties props;
struct generic_bl_info *machinfo = pdev->dev.platform_data;
const char *name = "generic-bl";
struct backlight_device *bd;
bl_machinfo = machinfo;
if (!machinfo->limit_mask)
machinfo->limit_mask = -1;
if (machinfo->name)
name = machinfo->name;
memset(&props, 0, sizeof(struct backlight_properties));
props.type = BACKLIGHT_RAW;
props.max_brightness = machinfo->max_intensity;
bd = backlight_device_register(name, &pdev->dev, NULL, &genericbl_ops,
&props);
if (IS_ERR (bd))
return PTR_ERR (bd);
platform_set_drvdata(pdev, bd);
bd->props.power = FB_BLANK_UNBLANK;
bd->props.brightness = machinfo->default_intensity;
backlight_update_status(bd);
generic_backlight_device = bd;
printk("Generic Backlight Driver Initialized.\n");
return 0;
}
static int genericbl_remove(struct platform_device *pdev)
{
struct backlight_device *bd = platform_get_drvdata(pdev);
bd->props.power = 0;
bd->props.brightness = 0;
backlight_update_status(bd);
backlight_device_unregister(bd);
printk("Generic Backlight Driver Unloaded\n");
return 0;
}
static struct platform_driver genericbl_driver = {
.probe = genericbl_probe,
.remove = genericbl_remove,
.driver = {
.name = "generic-bl",
},
};
module_platform_driver(genericbl_driver);
MODULE_AUTHOR("Richard Purdie <rpurdie@rpsys.net>");
MODULE_DESCRIPTION("Generic Backlight Driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
95A31/android_kernel_msm | drivers/w1/w1_family.c | 7154 | 3107 | /*
* w1_family.c
*
* Copyright (c) 2004 Evgeniy Polyakov <zbr@ioremap.net>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/spinlock.h>
#include <linux/list.h>
#include <linux/sched.h> /* schedule_timeout() */
#include <linux/delay.h>
#include <linux/export.h>
#include "w1_family.h"
#include "w1.h"
DEFINE_SPINLOCK(w1_flock);
static LIST_HEAD(w1_families);
int w1_register_family(struct w1_family *newf)
{
struct list_head *ent, *n;
struct w1_family *f;
int ret = 0;
spin_lock(&w1_flock);
list_for_each_safe(ent, n, &w1_families) {
f = list_entry(ent, struct w1_family, family_entry);
if (f->fid == newf->fid) {
ret = -EEXIST;
break;
}
}
if (!ret) {
atomic_set(&newf->refcnt, 0);
list_add_tail(&newf->family_entry, &w1_families);
}
spin_unlock(&w1_flock);
/* check default devices against the new set of drivers */
w1_reconnect_slaves(newf, 1);
return ret;
}
void w1_unregister_family(struct w1_family *fent)
{
struct list_head *ent, *n;
struct w1_family *f;
spin_lock(&w1_flock);
list_for_each_safe(ent, n, &w1_families) {
f = list_entry(ent, struct w1_family, family_entry);
if (f->fid == fent->fid) {
list_del(&fent->family_entry);
break;
}
}
spin_unlock(&w1_flock);
/* deatch devices using this family code */
w1_reconnect_slaves(fent, 0);
while (atomic_read(&fent->refcnt)) {
printk(KERN_INFO "Waiting for family %u to become free: refcnt=%d.\n",
fent->fid, atomic_read(&fent->refcnt));
if (msleep_interruptible(1000))
flush_signals(current);
}
}
/*
* Should be called under w1_flock held.
*/
struct w1_family * w1_family_registered(u8 fid)
{
struct list_head *ent, *n;
struct w1_family *f = NULL;
int ret = 0;
list_for_each_safe(ent, n, &w1_families) {
f = list_entry(ent, struct w1_family, family_entry);
if (f->fid == fid) {
ret = 1;
break;
}
}
return (ret) ? f : NULL;
}
static void __w1_family_put(struct w1_family *f)
{
atomic_dec(&f->refcnt);
}
void w1_family_put(struct w1_family *f)
{
spin_lock(&w1_flock);
__w1_family_put(f);
spin_unlock(&w1_flock);
}
#if 0
void w1_family_get(struct w1_family *f)
{
spin_lock(&w1_flock);
__w1_family_get(f);
spin_unlock(&w1_flock);
}
#endif /* 0 */
void __w1_family_get(struct w1_family *f)
{
smp_mb__before_atomic_inc();
atomic_inc(&f->refcnt);
smp_mb__after_atomic_inc();
}
EXPORT_SYMBOL(w1_unregister_family);
EXPORT_SYMBOL(w1_register_family);
| gpl-2.0 |
AOKP/kernel_sony_msm8960t | drivers/scsi/eata.c | 10738 | 78298 | /*
* eata.c - Low-level driver for EATA/DMA SCSI host adapters.
*
* 03 Jun 2003 Rev. 8.10 for linux-2.5.70
* + Update for new IRQ API.
* + Use "goto" when appropriate.
* + Drop eata.h.
* + Update for new module_param API.
* + Module parameters can now be specified only in the
* same format as the kernel boot options.
*
* boot option old module param
* ----------- ------------------
* addr,... io_port=addr,...
* lc:[y|n] linked_comm=[1|0]
* mq:xx max_queue_depth=xx
* tm:[0|1|2] tag_mode=[0|1|2]
* et:[y|n] ext_tran=[1|0]
* rs:[y|n] rev_scan=[1|0]
* ip:[y|n] isa_probe=[1|0]
* ep:[y|n] eisa_probe=[1|0]
* pp:[y|n] pci_probe=[1|0]
*
* A valid example using the new parameter format is:
* modprobe eata "eata=0x7410,0x230,lc:y,tm:0,mq:4,ep:n"
*
* which is equivalent to the old format:
* modprobe eata io_port=0x7410,0x230 linked_comm=1 tag_mode=0 \
* max_queue_depth=4 eisa_probe=0
*
* 12 Feb 2003 Rev. 8.04 for linux 2.5.60
* + Release irq before calling scsi_register.
*
* 12 Nov 2002 Rev. 8.02 for linux 2.5.47
* + Release driver_lock before calling scsi_register.
*
* 11 Nov 2002 Rev. 8.01 for linux 2.5.47
* + Fixed bios_param and scsicam_bios_param calling parameters.
*
* 28 Oct 2002 Rev. 8.00 for linux 2.5.44-ac4
* + Use new tcq and adjust_queue_depth api.
* + New command line option (tm:[0-2]) to choose the type of tags:
* 0 -> disable tagging ; 1 -> simple tags ; 2 -> ordered tags.
* Default is tm:0 (tagged commands disabled).
* For compatibility the "tc:" option is an alias of the "tm:"
* option; tc:n is equivalent to tm:0 and tc:y is equivalent to
* tm:1.
* + The tagged_comm module parameter has been removed, use tag_mode
* instead, equivalent to the "tm:" boot option.
*
* 10 Oct 2002 Rev. 7.70 for linux 2.5.42
* + Foreport from revision 6.70.
*
* 25 Jun 2002 Rev. 6.70 for linux 2.4.19
* + This release is the first one tested on a Big Endian platform:
* fixed endian-ness problem due to bitfields;
* fixed endian-ness problem in read_pio.
* + Added new options for selectively probing ISA, EISA and PCI bus:
*
* Boot option Parameter name Default according to
*
* ip:[y|n] isa_probe=[1|0] CONFIG_ISA defined
* ep:[y|n] eisa_probe=[1|0] CONFIG_EISA defined
* pp:[y|n] pci_probe=[1|0] CONFIG_PCI defined
*
* The default action is to perform probing if the corresponding
* bus is configured and to skip probing otherwise.
*
* + If pci_probe is in effect and a list of I/O ports is specified
* as parameter or boot option, pci_enable_device() is performed
* on all pci devices matching PCI_CLASS_STORAGE_SCSI.
*
* 21 Feb 2002 Rev. 6.52 for linux 2.4.18
* + Backport from rev. 7.22 (use io_request_lock).
*
* 20 Feb 2002 Rev. 7.22 for linux 2.5.5
* + Remove any reference to virt_to_bus().
* + Fix pio hang while detecting multiple HBAs.
* + Fixed a board detection bug: in a system with
* multiple ISA/EISA boards, all but the first one
* were erroneously detected as PCI.
*
* 01 Jan 2002 Rev. 7.20 for linux 2.5.1
* + Use the dynamic DMA mapping API.
*
* 19 Dec 2001 Rev. 7.02 for linux 2.5.1
* + Use SCpnt->sc_data_direction if set.
* + Use sglist.page instead of sglist.address.
*
* 11 Dec 2001 Rev. 7.00 for linux 2.5.1
* + Use host->host_lock instead of io_request_lock.
*
* 1 May 2001 Rev. 6.05 for linux 2.4.4
* + Clean up all pci related routines.
* + Fix data transfer direction for opcode SEND_CUE_SHEET (0x5d)
*
* 30 Jan 2001 Rev. 6.04 for linux 2.4.1
* + Call pci_resource_start after pci_enable_device.
*
* 25 Jan 2001 Rev. 6.03 for linux 2.4.0
* + "check_region" call replaced by "request_region".
*
* 22 Nov 2000 Rev. 6.02 for linux 2.4.0-test11
* + Return code checked when calling pci_enable_device.
* + Removed old scsi error handling support.
* + The obsolete boot option flag eh:n is silently ignored.
* + Removed error messages while a disk drive is powered up at
* boot time.
* + Improved boot messages: all tagged capable device are
* indicated as "tagged" or "soft-tagged" :
* - "soft-tagged" means that the driver is trying to do its
* own tagging (i.e. the tc:y option is in effect);
* - "tagged" means that the device supports tagged commands,
* but the driver lets the HBA be responsible for tagging
* support.
*
* 16 Sep 1999 Rev. 5.11 for linux 2.2.12 and 2.3.18
* + Updated to the new __setup interface for boot command line options.
* + When loaded as a module, accepts the new parameter boot_options
* which value is a string with the same format of the kernel boot
* command line options. A valid example is:
* modprobe eata 'boot_options="0x7410,0x230,lc:y,tc:n,mq:4"'
*
* 9 Sep 1999 Rev. 5.10 for linux 2.2.12 and 2.3.17
* + 64bit cleanup for Linux/Alpha platform support
* (contribution from H.J. Lu).
*
* 22 Jul 1999 Rev. 5.00 for linux 2.2.10 and 2.3.11
* + Removed pre-2.2 source code compatibility.
* + Added call to pci_set_master.
*
* 26 Jul 1998 Rev. 4.33 for linux 2.0.35 and 2.1.111
* + Added command line option (rs:[y|n]) to reverse the scan order
* of PCI boards. The default is rs:y, which reverses the BIOS order
* while registering PCI boards. The default value rs:y generates
* the same order of all previous revisions of this driver.
* Pls. note that "BIOS order" might have been reversed itself
* after the 2.1.9x PCI modifications in the linux kernel.
* The rs value is ignored when the explicit list of addresses
* is used by the "eata=port0,port1,..." command line option.
* + Added command line option (et:[y|n]) to force use of extended
* translation (255 heads, 63 sectors) as disk geometry.
* The default is et:n, which uses the disk geometry returned
* by scsicam_bios_param. The default value et:n is compatible with
* all previous revisions of this driver.
*
* 28 May 1998 Rev. 4.32 for linux 2.0.33 and 2.1.104
* Increased busy timeout from 10 msec. to 200 msec. while
* processing interrupts.
*
* 16 May 1998 Rev. 4.31 for linux 2.0.33 and 2.1.102
* Improved abort handling during the eh recovery process.
*
* 13 May 1998 Rev. 4.30 for linux 2.0.33 and 2.1.101
* The driver is now fully SMP safe, including the
* abort and reset routines.
* Added command line options (eh:[y|n]) to choose between
* new_eh_code and the old scsi code.
* If linux version >= 2.1.101 the default is eh:y, while the eh
* option is ignored for previous releases and the old scsi code
* is used.
*
* 18 Apr 1998 Rev. 4.20 for linux 2.0.33 and 2.1.97
* Reworked interrupt handler.
*
* 11 Apr 1998 rev. 4.05 for linux 2.0.33 and 2.1.95
* Major reliability improvement: when a batch with overlapping
* requests is detected, requests are queued one at a time
* eliminating any possible board or drive reordering.
*
* 10 Apr 1998 rev. 4.04 for linux 2.0.33 and 2.1.95
* Improved SMP support (if linux version >= 2.1.95).
*
* 9 Apr 1998 rev. 4.03 for linux 2.0.33 and 2.1.94
* Added support for new PCI code and IO-APIC remapping of irqs.
* Performance improvement: when sequential i/o is detected,
* always use direct sort instead of reverse sort.
*
* 4 Apr 1998 rev. 4.02 for linux 2.0.33 and 2.1.92
* io_port is now unsigned long.
*
* 17 Mar 1998 rev. 4.01 for linux 2.0.33 and 2.1.88
* Use new scsi error handling code (if linux version >= 2.1.88).
* Use new interrupt code.
*
* 12 Sep 1997 rev. 3.11 for linux 2.0.30 and 2.1.55
* Use of udelay inside the wait loops to avoid timeout
* problems with fast cpus.
* Removed check about useless calls to the interrupt service
* routine (reported on SMP systems only).
* At initialization time "sorted/unsorted" is displayed instead
* of "linked/unlinked" to reinforce the fact that "linking" is
* nothing but "elevator sorting" in the actual implementation.
*
* 17 May 1997 rev. 3.10 for linux 2.0.30 and 2.1.38
* Use of serial_number_at_timeout in abort and reset processing.
* Use of the __initfunc and __initdata macro in setup code.
* Minor cleanups in the list_statistics code.
* Increased controller busy timeout in order to better support
* slow SCSI devices.
*
* 24 Feb 1997 rev. 3.00 for linux 2.0.29 and 2.1.26
* When loading as a module, parameter passing is now supported
* both in 2.0 and in 2.1 style.
* Fixed data transfer direction for some SCSI opcodes.
* Immediate acknowledge to request sense commands.
* Linked commands to each disk device are now reordered by elevator
* sorting. Rare cases in which reordering of write requests could
* cause wrong results are managed.
* Fixed spurious timeouts caused by long simple queue tag sequences.
* New command line option (tm:[0-3]) to choose the type of tags:
* 0 -> mixed (default); 1 -> simple; 2 -> head; 3 -> ordered.
*
* 18 Jan 1997 rev. 2.60 for linux 2.1.21 and 2.0.28
* Added command line options to enable/disable linked commands
* (lc:[y|n]), tagged commands (tc:[y|n]) and to set the max queue
* depth (mq:xx). Default is "eata=lc:n,tc:n,mq:16".
* Improved command linking.
* Documented how to setup RAID-0 with DPT SmartRAID boards.
*
* 8 Jan 1997 rev. 2.50 for linux 2.1.20 and 2.0.27
* Added linked command support.
* Improved detection of PCI boards using ISA base addresses.
*
* 3 Dec 1996 rev. 2.40 for linux 2.1.14 and 2.0.27
* Added support for tagged commands and queue depth adjustment.
*
* 22 Nov 1996 rev. 2.30 for linux 2.1.12 and 2.0.26
* When CONFIG_PCI is defined, BIOS32 is used to include in the
* list of i/o ports to be probed all the PCI SCSI controllers.
* The list of i/o ports to be probed can be overwritten by the
* "eata=port0,port1,...." boot command line option.
* Scatter/gather lists are now allocated by a number of kmalloc
* calls, in order to avoid the previous size limit of 64Kb.
*
* 16 Nov 1996 rev. 2.20 for linux 2.1.10 and 2.0.25
* Added support for EATA 2.0C, PCI, multichannel and wide SCSI.
*
* 27 Sep 1996 rev. 2.12 for linux 2.1.0
* Portability cleanups (virtual/bus addressing, little/big endian
* support).
*
* 09 Jul 1996 rev. 2.11 for linux 2.0.4
* Number of internal retries is now limited.
*
* 16 Apr 1996 rev. 2.10 for linux 1.3.90
* New argument "reset_flags" to the reset routine.
*
* 6 Jul 1995 rev. 2.01 for linux 1.3.7
* Update required by the new /proc/scsi support.
*
* 11 Mar 1995 rev. 2.00 for linux 1.2.0
* Fixed a bug which prevented media change detection for removable
* disk drives.
*
* 23 Feb 1995 rev. 1.18 for linux 1.1.94
* Added a check for scsi_register returning NULL.
*
* 11 Feb 1995 rev. 1.17 for linux 1.1.91
* Now DEBUG_RESET is disabled by default.
* Register a board even if it does not assert DMA protocol support
* (DPT SK2011B does not report correctly the dmasup bit).
*
* 9 Feb 1995 rev. 1.16 for linux 1.1.90
* Use host->wish_block instead of host->block.
* New list of Data Out SCSI commands.
*
* 8 Feb 1995 rev. 1.15 for linux 1.1.89
* Cleared target_time_out counter while performing a reset.
* All external symbols renamed to avoid possible name conflicts.
*
* 28 Jan 1995 rev. 1.14 for linux 1.1.86
* Added module support.
* Log and do a retry when a disk drive returns a target status
* different from zero on a recovered error.
*
* 24 Jan 1995 rev. 1.13 for linux 1.1.85
* Use optimized board configuration, with a measured performance
* increase in the range 10%-20% on i/o throughput.
*
* 16 Jan 1995 rev. 1.12 for linux 1.1.81
* Fix mscp structure comments (no functional change).
* Display a message if check_region detects a port address
* already in use.
*
* 17 Dec 1994 rev. 1.11 for linux 1.1.74
* Use the scsicam_bios_param routine. This allows an easy
* migration path from disk partition tables created using
* different SCSI drivers and non optimal disk geometry.
*
* 15 Dec 1994 rev. 1.10 for linux 1.1.74
* Added support for ISA EATA boards (DPT PM2011, DPT PM2021).
* The host->block flag is set for all the detected ISA boards.
* The detect routine no longer enforces LEVEL triggering
* for EISA boards, it just prints a warning message.
*
* 30 Nov 1994 rev. 1.09 for linux 1.1.68
* Redo i/o on target status CHECK_CONDITION for TYPE_DISK only.
* Added optional support for using a single board at a time.
*
* 18 Nov 1994 rev. 1.08 for linux 1.1.64
* Forces sg_tablesize = 64 and can_queue = 64 if these
* values are not correctly detected (DPT PM2012).
*
* 14 Nov 1994 rev. 1.07 for linux 1.1.63 Final BETA release.
* 04 Aug 1994 rev. 1.00 for linux 1.1.39 First BETA release.
*
*
* This driver is based on the CAM (Common Access Method Committee)
* EATA (Enhanced AT Bus Attachment) rev. 2.0A, using DMA protocol.
*
* Copyright (C) 1994-2003 Dario Ballabio (ballabio_dario@emc.com)
*
* Alternate email: dario.ballabio@inwind.it, dario.ballabio@tiscalinet.it
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that redistributions of source
* code retain the above copyright notice and this comment without
* modification.
*
*/
/*
*
* Here is a brief description of the DPT SCSI host adapters.
* All these boards provide an EATA/DMA compatible programming interface
* and are fully supported by this driver in any configuration, including
* multiple SCSI channels:
*
* PM2011B/9X - Entry Level ISA
* PM2021A/9X - High Performance ISA
* PM2012A Old EISA
* PM2012B Old EISA
* PM2022A/9X - Entry Level EISA
* PM2122A/9X - High Performance EISA
* PM2322A/9X - Extra High Performance EISA
* PM3021 - SmartRAID Adapter for ISA
* PM3222 - SmartRAID Adapter for EISA (PM3222W is 16-bit wide SCSI)
* PM3224 - SmartRAID Adapter for PCI (PM3224W is 16-bit wide SCSI)
* PM33340UW - SmartRAID Adapter for PCI ultra wide multichannel
*
* The above list is just an indication: as a matter of fact all DPT
* boards using the EATA/DMA protocol are supported by this driver,
* since they use exactely the same programming interface.
*
* The DPT PM2001 provides only the EATA/PIO interface and hence is not
* supported by this driver.
*
* This code has been tested with up to 3 Distributed Processing Technology
* PM2122A/9X (DPT SCSI BIOS v002.D1, firmware v05E.0) EISA controllers,
* in any combination of private and shared IRQ.
* PCI support has been tested using up to 2 DPT PM3224W (DPT SCSI BIOS
* v003.D0, firmware v07G.0).
*
* DPT SmartRAID boards support "Hardware Array" - a group of disk drives
* which are all members of the same RAID-0, RAID-1 or RAID-5 array implemented
* in host adapter hardware. Hardware Arrays are fully compatible with this
* driver, since they look to it as a single disk drive.
*
* WARNING: to create a RAID-0 "Hardware Array" you must select "Other Unix"
* as the current OS in the DPTMGR "Initial System Installation" menu.
* Otherwise RAID-0 is generated as an "Array Group" (i.e. software RAID-0),
* which is not supported by the actual SCSI subsystem.
* To get the "Array Group" functionality, the Linux MD driver must be used
* instead of the DPT "Array Group" feature.
*
* Multiple ISA, EISA and PCI boards can be configured in the same system.
* It is suggested to put all the EISA boards on the same IRQ level, all
* the PCI boards on another IRQ level, while ISA boards cannot share
* interrupts.
*
* If you configure multiple boards on the same IRQ, the interrupt must
* be _level_ triggered (not _edge_ triggered).
*
* This driver detects EATA boards by probes at fixed port addresses,
* so no BIOS32 or PCI BIOS support is required.
* The suggested way to detect a generic EATA PCI board is to force on it
* any unused EISA address, even if there are other controllers on the EISA
* bus, or even if you system has no EISA bus at all.
* Do not force any ISA address on EATA PCI boards.
*
* If PCI bios support is configured into the kernel, BIOS32 is used to
* include in the list of i/o ports to be probed all the PCI SCSI controllers.
*
* Due to a DPT BIOS "feature", it might not be possible to force an EISA
* address on more than a single DPT PCI board, so in this case you have to
* let the PCI BIOS assign the addresses.
*
* The sequence of detection probes is:
*
* - ISA 0x1F0;
* - PCI SCSI controllers (only if BIOS32 is available);
* - EISA/PCI 0x1C88 through 0xFC88 (corresponding to EISA slots 1 to 15);
* - ISA 0x170, 0x230, 0x330.
*
* The above list of detection probes can be totally replaced by the
* boot command line option: "eata=port0,port1,port2,...", where the
* port0, port1... arguments are ISA/EISA/PCI addresses to be probed.
* For example using "eata=0x7410,0x7450,0x230", the driver probes
* only the two PCI addresses 0x7410 and 0x7450 and the ISA address 0x230,
* in this order; "eata=0" totally disables this driver.
*
* After the optional list of detection probes, other possible command line
* options are:
*
* et:y force use of extended translation (255 heads, 63 sectors);
* et:n use disk geometry detected by scsicam_bios_param;
* rs:y reverse scan order while detecting PCI boards;
* rs:n use BIOS order while detecting PCI boards;
* lc:y enables linked commands;
* lc:n disables linked commands;
* tm:0 disables tagged commands (same as tc:n);
* tm:1 use simple queue tags (same as tc:y);
* tm:2 use ordered queue tags (same as tc:2);
* mq:xx set the max queue depth to the value xx (2 <= xx <= 32).
*
* The default value is: "eata=lc:n,mq:16,tm:0,et:n,rs:n".
* An example using the list of detection probes could be:
* "eata=0x7410,0x230,lc:y,tm:2,mq:4,et:n".
*
* When loading as a module, parameters can be specified as well.
* The above example would be (use 1 in place of y and 0 in place of n):
*
* modprobe eata io_port=0x7410,0x230 linked_comm=1 \
* max_queue_depth=4 ext_tran=0 tag_mode=2 \
* rev_scan=1
*
* ----------------------------------------------------------------------------
* In this implementation, linked commands are designed to work with any DISK
* or CD-ROM, since this linking has only the intent of clustering (time-wise)
* and reordering by elevator sorting commands directed to each device,
* without any relation with the actual SCSI protocol between the controller
* and the device.
* If Q is the queue depth reported at boot time for each device (also named
* cmds/lun) and Q > 2, whenever there is already an active command to the
* device all other commands to the same device (up to Q-1) are kept waiting
* in the elevator sorting queue. When the active command completes, the
* commands in this queue are sorted by sector address. The sort is chosen
* between increasing or decreasing by minimizing the seek distance between
* the sector of the commands just completed and the sector of the first
* command in the list to be sorted.
* Trivial math assures that the unsorted average seek distance when doing
* random seeks over S sectors is S/3.
* When (Q-1) requests are uniformly distributed over S sectors, the average
* distance between two adjacent requests is S/((Q-1) + 1), so the sorted
* average seek distance for (Q-1) random requests over S sectors is S/Q.
* The elevator sorting hence divides the seek distance by a factor Q/3.
* The above pure geometric remarks are valid in all cases and the
* driver effectively reduces the seek distance by the predicted factor
* when there are Q concurrent read i/o operations on the device, but this
* does not necessarily results in a noticeable performance improvement:
* your mileage may vary....
*
* Note: command reordering inside a batch of queued commands could cause
* wrong results only if there is at least one write request and the
* intersection (sector-wise) of all requests is not empty.
* When the driver detects a batch including overlapping requests
* (a really rare event) strict serial (pid) order is enforced.
* ----------------------------------------------------------------------------
* The extended translation option (et:y) is useful when using large physical
* disks/arrays. It could also be useful when switching between Adaptec boards
* and DPT boards without reformatting the disk.
* When a boot disk is partitioned with extended translation, in order to
* be able to boot it with a DPT board is could be necessary to add to
* lilo.conf additional commands as in the following example:
*
* fix-table
* disk=/dev/sda bios=0x80 sectors=63 heads=128 cylindres=546
*
* where the above geometry should be replaced with the one reported at
* power up by the DPT controller.
* ----------------------------------------------------------------------------
*
* The boards are named EATA0, EATA1,... according to the detection order.
*
* In order to support multiple ISA boards in a reliable way,
* the driver sets host->wish_block = 1 for all ISA boards.
*/
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/ioport.h>
#include <linux/delay.h>
#include <linux/proc_fs.h>
#include <linux/blkdev.h>
#include <linux/interrupt.h>
#include <linux/stat.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/ctype.h>
#include <linux/spinlock.h>
#include <linux/dma-mapping.h>
#include <linux/slab.h>
#include <asm/byteorder.h>
#include <asm/dma.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_tcq.h>
#include <scsi/scsicam.h>
static int eata2x_detect(struct scsi_host_template *);
static int eata2x_release(struct Scsi_Host *);
static int eata2x_queuecommand(struct Scsi_Host *, struct scsi_cmnd *);
static int eata2x_eh_abort(struct scsi_cmnd *);
static int eata2x_eh_host_reset(struct scsi_cmnd *);
static int eata2x_bios_param(struct scsi_device *, struct block_device *,
sector_t, int *);
static int eata2x_slave_configure(struct scsi_device *);
static struct scsi_host_template driver_template = {
.name = "EATA/DMA 2.0x rev. 8.10.00 ",
.detect = eata2x_detect,
.release = eata2x_release,
.queuecommand = eata2x_queuecommand,
.eh_abort_handler = eata2x_eh_abort,
.eh_host_reset_handler = eata2x_eh_host_reset,
.bios_param = eata2x_bios_param,
.slave_configure = eata2x_slave_configure,
.this_id = 7,
.unchecked_isa_dma = 1,
.use_clustering = ENABLE_CLUSTERING,
};
#if !defined(__BIG_ENDIAN_BITFIELD) && !defined(__LITTLE_ENDIAN_BITFIELD)
#error "Adjust your <asm/byteorder.h> defines"
#endif
/* Subversion values */
#define ISA 0
#define ESA 1
#undef FORCE_CONFIG
#undef DEBUG_LINKED_COMMANDS
#undef DEBUG_DETECT
#undef DEBUG_PCI_DETECT
#undef DEBUG_INTERRUPT
#undef DEBUG_RESET
#undef DEBUG_GENERATE_ERRORS
#undef DEBUG_GENERATE_ABORTS
#undef DEBUG_GEOMETRY
#define MAX_ISA 4
#define MAX_VESA 0
#define MAX_EISA 15
#define MAX_PCI 16
#define MAX_BOARDS (MAX_ISA + MAX_VESA + MAX_EISA + MAX_PCI)
#define MAX_CHANNEL 4
#define MAX_LUN 32
#define MAX_TARGET 32
#define MAX_MAILBOXES 64
#define MAX_SGLIST 64
#define MAX_LARGE_SGLIST 122
#define MAX_INTERNAL_RETRIES 64
#define MAX_CMD_PER_LUN 2
#define MAX_TAGGED_CMD_PER_LUN (MAX_MAILBOXES - MAX_CMD_PER_LUN)
#define SKIP ULONG_MAX
#define FREE 0
#define IN_USE 1
#define LOCKED 2
#define IN_RESET 3
#define IGNORE 4
#define READY 5
#define ABORTING 6
#define NO_DMA 0xff
#define MAXLOOP 10000
#define TAG_DISABLED 0
#define TAG_SIMPLE 1
#define TAG_ORDERED 2
#define REG_CMD 7
#define REG_STATUS 7
#define REG_AUX_STATUS 8
#define REG_DATA 0
#define REG_DATA2 1
#define REG_SEE 6
#define REG_LOW 2
#define REG_LM 3
#define REG_MID 4
#define REG_MSB 5
#define REGION_SIZE 9UL
#define MAX_ISA_ADDR 0x03ff
#define MIN_EISA_ADDR 0x1c88
#define MAX_EISA_ADDR 0xfc88
#define BSY_ASSERTED 0x80
#define DRQ_ASSERTED 0x08
#define ABSY_ASSERTED 0x01
#define IRQ_ASSERTED 0x02
#define READ_CONFIG_PIO 0xf0
#define SET_CONFIG_PIO 0xf1
#define SEND_CP_PIO 0xf2
#define RECEIVE_SP_PIO 0xf3
#define TRUNCATE_XFR_PIO 0xf4
#define RESET_PIO 0xf9
#define READ_CONFIG_DMA 0xfd
#define SET_CONFIG_DMA 0xfe
#define SEND_CP_DMA 0xff
#define ASOK 0x00
#define ASST 0x01
#define YESNO(a) ((a) ? 'y' : 'n')
#define TLDEV(type) ((type) == TYPE_DISK || (type) == TYPE_ROM)
/* "EATA", in Big Endian format */
#define EATA_SIG_BE 0x45415441
/* Number of valid bytes in the board config structure for EATA 2.0x */
#define EATA_2_0A_SIZE 28
#define EATA_2_0B_SIZE 30
#define EATA_2_0C_SIZE 34
/* Board info structure */
struct eata_info {
u_int32_t data_len; /* Number of valid bytes after this field */
u_int32_t sign; /* ASCII "EATA" signature */
#if defined(__BIG_ENDIAN_BITFIELD)
unchar version : 4,
: 4;
unchar haaval : 1,
ata : 1,
drqvld : 1,
dmasup : 1,
morsup : 1,
trnxfr : 1,
tarsup : 1,
ocsena : 1;
#else
unchar : 4, /* unused low nibble */
version : 4; /* EATA version, should be 0x1 */
unchar ocsena : 1, /* Overlap Command Support Enabled */
tarsup : 1, /* Target Mode Supported */
trnxfr : 1, /* Truncate Transfer Cmd NOT Necessary */
morsup : 1, /* More Supported */
dmasup : 1, /* DMA Supported */
drqvld : 1, /* DRQ Index (DRQX) is valid */
ata : 1, /* This is an ATA device */
haaval : 1; /* Host Adapter Address Valid */
#endif
ushort cp_pad_len; /* Number of pad bytes after cp_len */
unchar host_addr[4]; /* Host Adapter SCSI ID for channels 3, 2, 1, 0 */
u_int32_t cp_len; /* Number of valid bytes in cp */
u_int32_t sp_len; /* Number of valid bytes in sp */
ushort queue_size; /* Max number of cp that can be queued */
ushort unused;
ushort scatt_size; /* Max number of entries in scatter/gather table */
#if defined(__BIG_ENDIAN_BITFIELD)
unchar drqx : 2,
second : 1,
irq_tr : 1,
irq : 4;
unchar sync;
unchar : 4,
res1 : 1,
large_sg : 1,
forcaddr : 1,
isaena : 1;
unchar max_chan : 3,
max_id : 5;
unchar max_lun;
unchar eisa : 1,
pci : 1,
idquest : 1,
m1 : 1,
: 4;
#else
unchar irq : 4, /* Interrupt Request assigned to this controller */
irq_tr : 1, /* 0 for edge triggered, 1 for level triggered */
second : 1, /* 1 if this is a secondary (not primary) controller */
drqx : 2; /* DRQ Index (0=DMA0, 1=DMA7, 2=DMA6, 3=DMA5) */
unchar sync; /* 1 if scsi target id 7...0 is running sync scsi */
/* Structure extension defined in EATA 2.0B */
unchar isaena : 1, /* ISA i/o addressing is disabled/enabled */
forcaddr : 1, /* Port address has been forced */
large_sg : 1, /* 1 if large SG lists are supported */
res1 : 1,
: 4;
unchar max_id : 5, /* Max SCSI target ID number */
max_chan : 3; /* Max SCSI channel number on this board */
/* Structure extension defined in EATA 2.0C */
unchar max_lun; /* Max SCSI LUN number */
unchar
: 4,
m1 : 1, /* This is a PCI with an M1 chip installed */
idquest : 1, /* RAIDNUM returned is questionable */
pci : 1, /* This board is PCI */
eisa : 1; /* This board is EISA */
#endif
unchar raidnum; /* Uniquely identifies this HBA in a system */
unchar notused;
ushort ipad[247];
};
/* Board config structure */
struct eata_config {
ushort len; /* Number of bytes following this field */
#if defined(__BIG_ENDIAN_BITFIELD)
unchar : 4,
tarena : 1,
mdpena : 1,
ocena : 1,
edis : 1;
#else
unchar edis : 1, /* Disable EATA interface after config command */
ocena : 1, /* Overlapped Commands Enabled */
mdpena : 1, /* Transfer all Modified Data Pointer Messages */
tarena : 1, /* Target Mode Enabled for this controller */
: 4;
#endif
unchar cpad[511];
};
/* Returned status packet structure */
struct mssp {
#if defined(__BIG_ENDIAN_BITFIELD)
unchar eoc : 1,
adapter_status : 7;
#else
unchar adapter_status : 7, /* State related to current command */
eoc : 1; /* End Of Command (1 = command completed) */
#endif
unchar target_status; /* SCSI status received after data transfer */
unchar unused[2];
u_int32_t inv_res_len; /* Number of bytes not transferred */
u_int32_t cpp_index; /* Index of address set in cp */
char mess[12];
};
struct sg_list {
unsigned int address; /* Segment Address */
unsigned int num_bytes; /* Segment Length */
};
/* MailBox SCSI Command Packet */
struct mscp {
#if defined(__BIG_ENDIAN_BITFIELD)
unchar din : 1,
dout : 1,
interp : 1,
: 1,
sg : 1,
reqsen :1,
init : 1,
sreset : 1;
unchar sense_len;
unchar unused[3];
unchar : 7,
fwnest : 1;
unchar : 5,
hbaci : 1,
iat : 1,
phsunit : 1;
unchar channel : 3,
target : 5;
unchar one : 1,
dispri : 1,
luntar : 1,
lun : 5;
#else
unchar sreset :1, /* SCSI Bus Reset Signal should be asserted */
init :1, /* Re-initialize controller and self test */
reqsen :1, /* Transfer Request Sense Data to addr using DMA */
sg :1, /* Use Scatter/Gather */
:1,
interp :1, /* The controller interprets cp, not the target */
dout :1, /* Direction of Transfer is Out (Host to Target) */
din :1; /* Direction of Transfer is In (Target to Host) */
unchar sense_len; /* Request Sense Length */
unchar unused[3];
unchar fwnest : 1, /* Send command to a component of an Array Group */
: 7;
unchar phsunit : 1, /* Send to Target Physical Unit (bypass RAID) */
iat : 1, /* Inhibit Address Translation */
hbaci : 1, /* Inhibit HBA Caching for this command */
: 5;
unchar target : 5, /* SCSI target ID */
channel : 3; /* SCSI channel number */
unchar lun : 5, /* SCSI logical unit number */
luntar : 1, /* This cp is for Target (not LUN) */
dispri : 1, /* Disconnect Privilege granted */
one : 1; /* 1 */
#endif
unchar mess[3]; /* Massage to/from Target */
unchar cdb[12]; /* Command Descriptor Block */
u_int32_t data_len; /* If sg=0 Data Length, if sg=1 sglist length */
u_int32_t cpp_index; /* Index of address to be returned in sp */
u_int32_t data_address; /* If sg=0 Data Address, if sg=1 sglist address */
u_int32_t sp_dma_addr; /* Address where sp is DMA'ed when cp completes */
u_int32_t sense_addr; /* Address where Sense Data is DMA'ed on error */
/* Additional fields begin here. */
struct scsi_cmnd *SCpnt;
/* All the cp structure is zero filled by queuecommand except the
following CP_TAIL_SIZE bytes, initialized by detect */
dma_addr_t cp_dma_addr; /* dma handle for this cp structure */
struct sg_list *sglist; /* pointer to the allocated SG list */
};
#define CP_TAIL_SIZE (sizeof(struct sglist *) + sizeof(dma_addr_t))
struct hostdata {
struct mscp cp[MAX_MAILBOXES]; /* Mailboxes for this board */
unsigned int cp_stat[MAX_MAILBOXES]; /* FREE, IN_USE, LOCKED, IN_RESET */
unsigned int last_cp_used; /* Index of last mailbox used */
unsigned int iocount; /* Total i/o done for this board */
int board_number; /* Number of this board */
char board_name[16]; /* Name of this board */
int in_reset; /* True if board is doing a reset */
int target_to[MAX_TARGET][MAX_CHANNEL]; /* N. of timeout errors on target */
int target_redo[MAX_TARGET][MAX_CHANNEL]; /* If 1 redo i/o on target */
unsigned int retries; /* Number of internal retries */
unsigned long last_retried_pid; /* Pid of last retried command */
unsigned char subversion; /* Bus type, either ISA or EISA/PCI */
unsigned char protocol_rev; /* EATA 2.0 rev., 'A' or 'B' or 'C' */
unsigned char is_pci; /* 1 is bus type is PCI */
struct pci_dev *pdev; /* pdev for PCI bus, NULL otherwise */
struct mssp *sp_cpu_addr; /* cpu addr for DMA buffer sp */
dma_addr_t sp_dma_addr; /* dma handle for DMA buffer sp */
struct mssp sp; /* Local copy of sp buffer */
};
static struct Scsi_Host *sh[MAX_BOARDS];
static const char *driver_name = "EATA";
static char sha[MAX_BOARDS];
static DEFINE_SPINLOCK(driver_lock);
/* Initialize num_boards so that ihdlr can work while detect is in progress */
static unsigned int num_boards = MAX_BOARDS;
static unsigned long io_port[] = {
/* Space for MAX_INT_PARAM ports usable while loading as a module */
SKIP, SKIP, SKIP, SKIP, SKIP, SKIP, SKIP, SKIP,
SKIP, SKIP,
/* First ISA */
0x1f0,
/* Space for MAX_PCI ports possibly reported by PCI_BIOS */
SKIP, SKIP, SKIP, SKIP, SKIP, SKIP, SKIP, SKIP,
SKIP, SKIP, SKIP, SKIP, SKIP, SKIP, SKIP, SKIP,
/* MAX_EISA ports */
0x1c88, 0x2c88, 0x3c88, 0x4c88, 0x5c88, 0x6c88, 0x7c88, 0x8c88,
0x9c88, 0xac88, 0xbc88, 0xcc88, 0xdc88, 0xec88, 0xfc88,
/* Other (MAX_ISA - 1) ports */
0x170, 0x230, 0x330,
/* End of list */
0x0
};
/* Device is Big Endian */
#define H2DEV(x) cpu_to_be32(x)
#define DEV2H(x) be32_to_cpu(x)
#define H2DEV16(x) cpu_to_be16(x)
#define DEV2H16(x) be16_to_cpu(x)
/* But transfer orientation from the 16 bit data register is Little Endian */
#define REG2H(x) le16_to_cpu(x)
static irqreturn_t do_interrupt_handler(int, void *);
static void flush_dev(struct scsi_device *, unsigned long, struct hostdata *,
unsigned int);
static int do_trace = 0;
static int setup_done = 0;
static int link_statistics;
static int ext_tran = 0;
static int rev_scan = 1;
#if defined(CONFIG_SCSI_EATA_TAGGED_QUEUE)
static int tag_mode = TAG_SIMPLE;
#else
static int tag_mode = TAG_DISABLED;
#endif
#if defined(CONFIG_SCSI_EATA_LINKED_COMMANDS)
static int linked_comm = 1;
#else
static int linked_comm = 0;
#endif
#if defined(CONFIG_SCSI_EATA_MAX_TAGS)
static int max_queue_depth = CONFIG_SCSI_EATA_MAX_TAGS;
#else
static int max_queue_depth = MAX_CMD_PER_LUN;
#endif
#if defined(CONFIG_ISA)
static int isa_probe = 1;
#else
static int isa_probe = 0;
#endif
#if defined(CONFIG_EISA)
static int eisa_probe = 1;
#else
static int eisa_probe = 0;
#endif
#if defined(CONFIG_PCI)
static int pci_probe = 1;
#else
static int pci_probe = 0;
#endif
#define MAX_INT_PARAM 10
#define MAX_BOOT_OPTIONS_SIZE 256
static char boot_options[MAX_BOOT_OPTIONS_SIZE];
#if defined(MODULE)
#include <linux/module.h>
#include <linux/moduleparam.h>
module_param_string(eata, boot_options, MAX_BOOT_OPTIONS_SIZE, 0);
MODULE_PARM_DESC(eata, " equivalent to the \"eata=...\" kernel boot option."
" Example: modprobe eata \"eata=0x7410,0x230,lc:y,tm:0,mq:4,ep:n\"");
MODULE_AUTHOR("Dario Ballabio");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("EATA/DMA SCSI Driver");
#endif
static int eata2x_slave_configure(struct scsi_device *dev)
{
int tqd, utqd;
char *tag_suffix, *link_suffix;
utqd = MAX_CMD_PER_LUN;
tqd = max_queue_depth;
if (TLDEV(dev->type) && dev->tagged_supported) {
if (tag_mode == TAG_SIMPLE) {
scsi_adjust_queue_depth(dev, MSG_SIMPLE_TAG, tqd);
tag_suffix = ", simple tags";
} else if (tag_mode == TAG_ORDERED) {
scsi_adjust_queue_depth(dev, MSG_ORDERED_TAG, tqd);
tag_suffix = ", ordered tags";
} else {
scsi_adjust_queue_depth(dev, 0, tqd);
tag_suffix = ", no tags";
}
} else if (TLDEV(dev->type) && linked_comm) {
scsi_adjust_queue_depth(dev, 0, tqd);
tag_suffix = ", untagged";
} else {
scsi_adjust_queue_depth(dev, 0, utqd);
tag_suffix = "";
}
if (TLDEV(dev->type) && linked_comm && dev->queue_depth > 2)
link_suffix = ", sorted";
else if (TLDEV(dev->type))
link_suffix = ", unsorted";
else
link_suffix = "";
sdev_printk(KERN_INFO, dev,
"cmds/lun %d%s%s.\n",
dev->queue_depth, link_suffix, tag_suffix);
return 0;
}
static int wait_on_busy(unsigned long iobase, unsigned int loop)
{
while (inb(iobase + REG_AUX_STATUS) & ABSY_ASSERTED) {
udelay(1L);
if (--loop == 0)
return 1;
}
return 0;
}
static int do_dma(unsigned long iobase, unsigned long addr, unchar cmd)
{
unsigned char *byaddr;
unsigned long devaddr;
if (wait_on_busy(iobase, (addr ? MAXLOOP * 100 : MAXLOOP)))
return 1;
if (addr) {
devaddr = H2DEV(addr);
byaddr = (unsigned char *)&devaddr;
outb(byaddr[3], iobase + REG_LOW);
outb(byaddr[2], iobase + REG_LM);
outb(byaddr[1], iobase + REG_MID);
outb(byaddr[0], iobase + REG_MSB);
}
outb(cmd, iobase + REG_CMD);
return 0;
}
static int read_pio(unsigned long iobase, ushort * start, ushort * end)
{
unsigned int loop = MAXLOOP;
ushort *p;
for (p = start; p <= end; p++) {
while (!(inb(iobase + REG_STATUS) & DRQ_ASSERTED)) {
udelay(1L);
if (--loop == 0)
return 1;
}
loop = MAXLOOP;
*p = REG2H(inw(iobase));
}
return 0;
}
static struct pci_dev *get_pci_dev(unsigned long port_base)
{
#if defined(CONFIG_PCI)
unsigned int addr;
struct pci_dev *dev = NULL;
while ((dev = pci_get_class(PCI_CLASS_STORAGE_SCSI << 8, dev))) {
addr = pci_resource_start(dev, 0);
#if defined(DEBUG_PCI_DETECT)
printk("%s: get_pci_dev, bus %d, devfn 0x%x, addr 0x%x.\n",
driver_name, dev->bus->number, dev->devfn, addr);
#endif
/* we are in so much trouble for a pci hotplug system with this driver
* anyway, so doing this at least lets people unload the driver and not
* cause memory problems, but in general this is a bad thing to do (this
* driver needs to be converted to the proper PCI api someday... */
pci_dev_put(dev);
if (addr + PCI_BASE_ADDRESS_0 == port_base)
return dev;
}
#endif /* end CONFIG_PCI */
return NULL;
}
static void enable_pci_ports(void)
{
#if defined(CONFIG_PCI)
struct pci_dev *dev = NULL;
while ((dev = pci_get_class(PCI_CLASS_STORAGE_SCSI << 8, dev))) {
#if defined(DEBUG_PCI_DETECT)
printk("%s: enable_pci_ports, bus %d, devfn 0x%x.\n",
driver_name, dev->bus->number, dev->devfn);
#endif
if (pci_enable_device(dev))
printk
("%s: warning, pci_enable_device failed, bus %d devfn 0x%x.\n",
driver_name, dev->bus->number, dev->devfn);
}
#endif /* end CONFIG_PCI */
}
static int port_detect(unsigned long port_base, unsigned int j,
struct scsi_host_template *tpnt)
{
unsigned char irq, dma_channel, subversion, i, is_pci = 0;
unsigned char protocol_rev;
struct eata_info info;
char *bus_type, dma_name[16];
struct pci_dev *pdev;
/* Allowed DMA channels for ISA (0 indicates reserved) */
unsigned char dma_channel_table[4] = { 5, 6, 7, 0 };
struct Scsi_Host *shost;
struct hostdata *ha;
char name[16];
sprintf(name, "%s%d", driver_name, j);
if (!request_region(port_base, REGION_SIZE, driver_name)) {
#if defined(DEBUG_DETECT)
printk("%s: address 0x%03lx in use, skipping probe.\n", name,
port_base);
#endif
goto fail;
}
spin_lock_irq(&driver_lock);
if (do_dma(port_base, 0, READ_CONFIG_PIO)) {
#if defined(DEBUG_DETECT)
printk("%s: detect, do_dma failed at 0x%03lx.\n", name,
port_base);
#endif
goto freelock;
}
/* Read the info structure */
if (read_pio(port_base, (ushort *) & info, (ushort *) & info.ipad[0])) {
#if defined(DEBUG_DETECT)
printk("%s: detect, read_pio failed at 0x%03lx.\n", name,
port_base);
#endif
goto freelock;
}
info.data_len = DEV2H(info.data_len);
info.sign = DEV2H(info.sign);
info.cp_pad_len = DEV2H16(info.cp_pad_len);
info.cp_len = DEV2H(info.cp_len);
info.sp_len = DEV2H(info.sp_len);
info.scatt_size = DEV2H16(info.scatt_size);
info.queue_size = DEV2H16(info.queue_size);
/* Check the controller "EATA" signature */
if (info.sign != EATA_SIG_BE) {
#if defined(DEBUG_DETECT)
printk("%s: signature 0x%04x discarded.\n", name, info.sign);
#endif
goto freelock;
}
if (info.data_len < EATA_2_0A_SIZE) {
printk
("%s: config structure size (%d bytes) too short, detaching.\n",
name, info.data_len);
goto freelock;
} else if (info.data_len == EATA_2_0A_SIZE)
protocol_rev = 'A';
else if (info.data_len == EATA_2_0B_SIZE)
protocol_rev = 'B';
else
protocol_rev = 'C';
if (protocol_rev != 'A' && info.forcaddr) {
printk("%s: warning, port address has been forced.\n", name);
bus_type = "PCI";
is_pci = 1;
subversion = ESA;
} else if (port_base > MAX_EISA_ADDR
|| (protocol_rev == 'C' && info.pci)) {
bus_type = "PCI";
is_pci = 1;
subversion = ESA;
} else if (port_base >= MIN_EISA_ADDR
|| (protocol_rev == 'C' && info.eisa)) {
bus_type = "EISA";
subversion = ESA;
} else if (protocol_rev == 'C' && !info.eisa && !info.pci) {
bus_type = "ISA";
subversion = ISA;
} else if (port_base > MAX_ISA_ADDR) {
bus_type = "PCI";
is_pci = 1;
subversion = ESA;
} else {
bus_type = "ISA";
subversion = ISA;
}
if (!info.haaval || info.ata) {
printk
("%s: address 0x%03lx, unusable %s board (%d%d), detaching.\n",
name, port_base, bus_type, info.haaval, info.ata);
goto freelock;
}
if (info.drqvld) {
if (subversion == ESA)
printk("%s: warning, weird %s board using DMA.\n", name,
bus_type);
subversion = ISA;
dma_channel = dma_channel_table[3 - info.drqx];
} else {
if (subversion == ISA)
printk("%s: warning, weird %s board not using DMA.\n",
name, bus_type);
subversion = ESA;
dma_channel = NO_DMA;
}
if (!info.dmasup)
printk("%s: warning, DMA protocol support not asserted.\n",
name);
irq = info.irq;
if (subversion == ESA && !info.irq_tr)
printk
("%s: warning, LEVEL triggering is suggested for IRQ %u.\n",
name, irq);
if (is_pci) {
pdev = get_pci_dev(port_base);
if (!pdev)
printk
("%s: warning, failed to get pci_dev structure.\n",
name);
} else
pdev = NULL;
if (pdev && (irq != pdev->irq)) {
printk("%s: IRQ %u mapped to IO-APIC IRQ %u.\n", name, irq,
pdev->irq);
irq = pdev->irq;
}
/* Board detected, allocate its IRQ */
if (request_irq(irq, do_interrupt_handler,
IRQF_DISABLED | ((subversion == ESA) ? IRQF_SHARED : 0),
driver_name, (void *)&sha[j])) {
printk("%s: unable to allocate IRQ %u, detaching.\n", name,
irq);
goto freelock;
}
if (subversion == ISA && request_dma(dma_channel, driver_name)) {
printk("%s: unable to allocate DMA channel %u, detaching.\n",
name, dma_channel);
goto freeirq;
}
#if defined(FORCE_CONFIG)
{
struct eata_config *cf;
dma_addr_t cf_dma_addr;
cf = pci_alloc_consistent(pdev, sizeof(struct eata_config),
&cf_dma_addr);
if (!cf) {
printk
("%s: config, pci_alloc_consistent failed, detaching.\n",
name);
goto freedma;
}
/* Set board configuration */
memset((char *)cf, 0, sizeof(struct eata_config));
cf->len = (ushort) H2DEV16((ushort) 510);
cf->ocena = 1;
if (do_dma(port_base, cf_dma_addr, SET_CONFIG_DMA)) {
printk
("%s: busy timeout sending configuration, detaching.\n",
name);
pci_free_consistent(pdev, sizeof(struct eata_config),
cf, cf_dma_addr);
goto freedma;
}
}
#endif
spin_unlock_irq(&driver_lock);
sh[j] = shost = scsi_register(tpnt, sizeof(struct hostdata));
spin_lock_irq(&driver_lock);
if (shost == NULL) {
printk("%s: unable to register host, detaching.\n", name);
goto freedma;
}
shost->io_port = port_base;
shost->unique_id = port_base;
shost->n_io_port = REGION_SIZE;
shost->dma_channel = dma_channel;
shost->irq = irq;
shost->sg_tablesize = (ushort) info.scatt_size;
shost->this_id = (ushort) info.host_addr[3];
shost->can_queue = (ushort) info.queue_size;
shost->cmd_per_lun = MAX_CMD_PER_LUN;
ha = (struct hostdata *)shost->hostdata;
memset(ha, 0, sizeof(struct hostdata));
ha->subversion = subversion;
ha->protocol_rev = protocol_rev;
ha->is_pci = is_pci;
ha->pdev = pdev;
ha->board_number = j;
if (ha->subversion == ESA)
shost->unchecked_isa_dma = 0;
else {
unsigned long flags;
shost->unchecked_isa_dma = 1;
flags = claim_dma_lock();
disable_dma(dma_channel);
clear_dma_ff(dma_channel);
set_dma_mode(dma_channel, DMA_MODE_CASCADE);
enable_dma(dma_channel);
release_dma_lock(flags);
}
strcpy(ha->board_name, name);
/* DPT PM2012 does not allow to detect sg_tablesize correctly */
if (shost->sg_tablesize > MAX_SGLIST || shost->sg_tablesize < 2) {
printk("%s: detect, wrong n. of SG lists %d, fixed.\n",
ha->board_name, shost->sg_tablesize);
shost->sg_tablesize = MAX_SGLIST;
}
/* DPT PM2012 does not allow to detect can_queue correctly */
if (shost->can_queue > MAX_MAILBOXES || shost->can_queue < 2) {
printk("%s: detect, wrong n. of mbox %d, fixed.\n",
ha->board_name, shost->can_queue);
shost->can_queue = MAX_MAILBOXES;
}
if (protocol_rev != 'A') {
if (info.max_chan > 0 && info.max_chan < MAX_CHANNEL)
shost->max_channel = info.max_chan;
if (info.max_id > 7 && info.max_id < MAX_TARGET)
shost->max_id = info.max_id + 1;
if (info.large_sg && shost->sg_tablesize == MAX_SGLIST)
shost->sg_tablesize = MAX_LARGE_SGLIST;
}
if (protocol_rev == 'C') {
if (info.max_lun > 7 && info.max_lun < MAX_LUN)
shost->max_lun = info.max_lun + 1;
}
if (dma_channel == NO_DMA)
sprintf(dma_name, "%s", "BMST");
else
sprintf(dma_name, "DMA %u", dma_channel);
spin_unlock_irq(&driver_lock);
for (i = 0; i < shost->can_queue; i++)
ha->cp[i].cp_dma_addr = pci_map_single(ha->pdev,
&ha->cp[i],
sizeof(struct mscp),
PCI_DMA_BIDIRECTIONAL);
for (i = 0; i < shost->can_queue; i++) {
size_t sz = shost->sg_tablesize *sizeof(struct sg_list);
gfp_t gfp_mask = (shost->unchecked_isa_dma ? GFP_DMA : 0) | GFP_ATOMIC;
ha->cp[i].sglist = kmalloc(sz, gfp_mask);
if (!ha->cp[i].sglist) {
printk
("%s: kmalloc SGlist failed, mbox %d, detaching.\n",
ha->board_name, i);
goto release;
}
}
if (!(ha->sp_cpu_addr = pci_alloc_consistent(ha->pdev,
sizeof(struct mssp),
&ha->sp_dma_addr))) {
printk("%s: pci_alloc_consistent failed, detaching.\n", ha->board_name);
goto release;
}
if (max_queue_depth > MAX_TAGGED_CMD_PER_LUN)
max_queue_depth = MAX_TAGGED_CMD_PER_LUN;
if (max_queue_depth < MAX_CMD_PER_LUN)
max_queue_depth = MAX_CMD_PER_LUN;
if (tag_mode != TAG_DISABLED && tag_mode != TAG_SIMPLE)
tag_mode = TAG_ORDERED;
if (j == 0) {
printk
("EATA/DMA 2.0x: Copyright (C) 1994-2003 Dario Ballabio.\n");
printk
("%s config options -> tm:%d, lc:%c, mq:%d, rs:%c, et:%c, "
"ip:%c, ep:%c, pp:%c.\n", driver_name, tag_mode,
YESNO(linked_comm), max_queue_depth, YESNO(rev_scan),
YESNO(ext_tran), YESNO(isa_probe), YESNO(eisa_probe),
YESNO(pci_probe));
}
printk("%s: 2.0%c, %s 0x%03lx, IRQ %u, %s, SG %d, MB %d.\n",
ha->board_name, ha->protocol_rev, bus_type,
(unsigned long)shost->io_port, shost->irq, dma_name,
shost->sg_tablesize, shost->can_queue);
if (shost->max_id > 8 || shost->max_lun > 8)
printk
("%s: wide SCSI support enabled, max_id %u, max_lun %u.\n",
ha->board_name, shost->max_id, shost->max_lun);
for (i = 0; i <= shost->max_channel; i++)
printk("%s: SCSI channel %u enabled, host target ID %d.\n",
ha->board_name, i, info.host_addr[3 - i]);
#if defined(DEBUG_DETECT)
printk("%s: Vers. 0x%x, ocs %u, tar %u, trnxfr %u, more %u, SYNC 0x%x, "
"sec. %u, infol %d, cpl %d spl %d.\n", name, info.version,
info.ocsena, info.tarsup, info.trnxfr, info.morsup, info.sync,
info.second, info.data_len, info.cp_len, info.sp_len);
if (protocol_rev == 'B' || protocol_rev == 'C')
printk("%s: isaena %u, forcaddr %u, max_id %u, max_chan %u, "
"large_sg %u, res1 %u.\n", name, info.isaena,
info.forcaddr, info.max_id, info.max_chan, info.large_sg,
info.res1);
if (protocol_rev == 'C')
printk("%s: max_lun %u, m1 %u, idquest %u, pci %u, eisa %u, "
"raidnum %u.\n", name, info.max_lun, info.m1,
info.idquest, info.pci, info.eisa, info.raidnum);
#endif
if (ha->pdev) {
pci_set_master(ha->pdev);
if (pci_set_dma_mask(ha->pdev, DMA_BIT_MASK(32)))
printk("%s: warning, pci_set_dma_mask failed.\n",
ha->board_name);
}
return 1;
freedma:
if (subversion == ISA)
free_dma(dma_channel);
freeirq:
free_irq(irq, &sha[j]);
freelock:
spin_unlock_irq(&driver_lock);
release_region(port_base, REGION_SIZE);
fail:
return 0;
release:
eata2x_release(shost);
return 0;
}
static void internal_setup(char *str, int *ints)
{
int i, argc = ints[0];
char *cur = str, *pc;
if (argc > 0) {
if (argc > MAX_INT_PARAM)
argc = MAX_INT_PARAM;
for (i = 0; i < argc; i++)
io_port[i] = ints[i + 1];
io_port[i] = 0;
setup_done = 1;
}
while (cur && (pc = strchr(cur, ':'))) {
int val = 0, c = *++pc;
if (c == 'n' || c == 'N')
val = 0;
else if (c == 'y' || c == 'Y')
val = 1;
else
val = (int)simple_strtoul(pc, NULL, 0);
if (!strncmp(cur, "lc:", 3))
linked_comm = val;
else if (!strncmp(cur, "tm:", 3))
tag_mode = val;
else if (!strncmp(cur, "tc:", 3))
tag_mode = val;
else if (!strncmp(cur, "mq:", 3))
max_queue_depth = val;
else if (!strncmp(cur, "ls:", 3))
link_statistics = val;
else if (!strncmp(cur, "et:", 3))
ext_tran = val;
else if (!strncmp(cur, "rs:", 3))
rev_scan = val;
else if (!strncmp(cur, "ip:", 3))
isa_probe = val;
else if (!strncmp(cur, "ep:", 3))
eisa_probe = val;
else if (!strncmp(cur, "pp:", 3))
pci_probe = val;
if ((cur = strchr(cur, ',')))
++cur;
}
return;
}
static int option_setup(char *str)
{
int ints[MAX_INT_PARAM];
char *cur = str;
int i = 1;
while (cur && isdigit(*cur) && i < MAX_INT_PARAM) {
ints[i++] = simple_strtoul(cur, NULL, 0);
if ((cur = strchr(cur, ',')) != NULL)
cur++;
}
ints[0] = i - 1;
internal_setup(cur, ints);
return 1;
}
static void add_pci_ports(void)
{
#if defined(CONFIG_PCI)
unsigned int addr, k;
struct pci_dev *dev = NULL;
for (k = 0; k < MAX_PCI; k++) {
if (!(dev = pci_get_class(PCI_CLASS_STORAGE_SCSI << 8, dev)))
break;
if (pci_enable_device(dev)) {
#if defined(DEBUG_PCI_DETECT)
printk
("%s: detect, bus %d, devfn 0x%x, pci_enable_device failed.\n",
driver_name, dev->bus->number, dev->devfn);
#endif
continue;
}
addr = pci_resource_start(dev, 0);
#if defined(DEBUG_PCI_DETECT)
printk("%s: detect, seq. %d, bus %d, devfn 0x%x, addr 0x%x.\n",
driver_name, k, dev->bus->number, dev->devfn, addr);
#endif
/* Order addresses according to rev_scan value */
io_port[MAX_INT_PARAM + (rev_scan ? (MAX_PCI - k) : (1 + k))] =
addr + PCI_BASE_ADDRESS_0;
}
pci_dev_put(dev);
#endif /* end CONFIG_PCI */
}
static int eata2x_detect(struct scsi_host_template *tpnt)
{
unsigned int j = 0, k;
tpnt->proc_name = "eata2x";
if (strlen(boot_options))
option_setup(boot_options);
#if defined(MODULE)
/* io_port could have been modified when loading as a module */
if (io_port[0] != SKIP) {
setup_done = 1;
io_port[MAX_INT_PARAM] = 0;
}
#endif
for (k = MAX_INT_PARAM; io_port[k]; k++)
if (io_port[k] == SKIP)
continue;
else if (io_port[k] <= MAX_ISA_ADDR) {
if (!isa_probe)
io_port[k] = SKIP;
} else if (io_port[k] >= MIN_EISA_ADDR
&& io_port[k] <= MAX_EISA_ADDR) {
if (!eisa_probe)
io_port[k] = SKIP;
}
if (pci_probe) {
if (!setup_done)
add_pci_ports();
else
enable_pci_ports();
}
for (k = 0; io_port[k]; k++) {
if (io_port[k] == SKIP)
continue;
if (j < MAX_BOARDS && port_detect(io_port[k], j, tpnt))
j++;
}
num_boards = j;
return j;
}
static void map_dma(unsigned int i, struct hostdata *ha)
{
unsigned int k, pci_dir;
int count;
struct scatterlist *sg;
struct mscp *cpp;
struct scsi_cmnd *SCpnt;
cpp = &ha->cp[i];
SCpnt = cpp->SCpnt;
pci_dir = SCpnt->sc_data_direction;
if (SCpnt->sense_buffer)
cpp->sense_addr =
H2DEV(pci_map_single(ha->pdev, SCpnt->sense_buffer,
SCSI_SENSE_BUFFERSIZE, PCI_DMA_FROMDEVICE));
cpp->sense_len = SCSI_SENSE_BUFFERSIZE;
if (!scsi_sg_count(SCpnt)) {
cpp->data_len = 0;
return;
}
count = pci_map_sg(ha->pdev, scsi_sglist(SCpnt), scsi_sg_count(SCpnt),
pci_dir);
BUG_ON(!count);
scsi_for_each_sg(SCpnt, sg, count, k) {
cpp->sglist[k].address = H2DEV(sg_dma_address(sg));
cpp->sglist[k].num_bytes = H2DEV(sg_dma_len(sg));
}
cpp->sg = 1;
cpp->data_address = H2DEV(pci_map_single(ha->pdev, cpp->sglist,
scsi_sg_count(SCpnt) *
sizeof(struct sg_list),
pci_dir));
cpp->data_len = H2DEV((scsi_sg_count(SCpnt) * sizeof(struct sg_list)));
}
static void unmap_dma(unsigned int i, struct hostdata *ha)
{
unsigned int pci_dir;
struct mscp *cpp;
struct scsi_cmnd *SCpnt;
cpp = &ha->cp[i];
SCpnt = cpp->SCpnt;
pci_dir = SCpnt->sc_data_direction;
if (DEV2H(cpp->sense_addr))
pci_unmap_single(ha->pdev, DEV2H(cpp->sense_addr),
DEV2H(cpp->sense_len), PCI_DMA_FROMDEVICE);
if (scsi_sg_count(SCpnt))
pci_unmap_sg(ha->pdev, scsi_sglist(SCpnt), scsi_sg_count(SCpnt),
pci_dir);
if (!DEV2H(cpp->data_len))
pci_dir = PCI_DMA_BIDIRECTIONAL;
if (DEV2H(cpp->data_address))
pci_unmap_single(ha->pdev, DEV2H(cpp->data_address),
DEV2H(cpp->data_len), pci_dir);
}
static void sync_dma(unsigned int i, struct hostdata *ha)
{
unsigned int pci_dir;
struct mscp *cpp;
struct scsi_cmnd *SCpnt;
cpp = &ha->cp[i];
SCpnt = cpp->SCpnt;
pci_dir = SCpnt->sc_data_direction;
if (DEV2H(cpp->sense_addr))
pci_dma_sync_single_for_cpu(ha->pdev, DEV2H(cpp->sense_addr),
DEV2H(cpp->sense_len),
PCI_DMA_FROMDEVICE);
if (scsi_sg_count(SCpnt))
pci_dma_sync_sg_for_cpu(ha->pdev, scsi_sglist(SCpnt),
scsi_sg_count(SCpnt), pci_dir);
if (!DEV2H(cpp->data_len))
pci_dir = PCI_DMA_BIDIRECTIONAL;
if (DEV2H(cpp->data_address))
pci_dma_sync_single_for_cpu(ha->pdev,
DEV2H(cpp->data_address),
DEV2H(cpp->data_len), pci_dir);
}
static void scsi_to_dev_dir(unsigned int i, struct hostdata *ha)
{
unsigned int k;
static const unsigned char data_out_cmds[] = {
0x0a, 0x2a, 0x15, 0x55, 0x04, 0x07, 0x18, 0x1d, 0x24, 0x2e,
0x30, 0x31, 0x32, 0x38, 0x39, 0x3a, 0x3b, 0x3d, 0x3f, 0x40,
0x41, 0x4c, 0xaa, 0xae, 0xb0, 0xb1, 0xb2, 0xb6, 0xea, 0x1b, 0x5d
};
static const unsigned char data_none_cmds[] = {
0x01, 0x0b, 0x10, 0x11, 0x13, 0x16, 0x17, 0x19, 0x2b, 0x1e,
0x2c, 0xac, 0x2f, 0xaf, 0x33, 0xb3, 0x35, 0x36, 0x45, 0x47,
0x48, 0x49, 0xa9, 0x4b, 0xa5, 0xa6, 0xb5, 0x00
};
struct mscp *cpp;
struct scsi_cmnd *SCpnt;
cpp = &ha->cp[i];
SCpnt = cpp->SCpnt;
if (SCpnt->sc_data_direction == DMA_FROM_DEVICE) {
cpp->din = 1;
cpp->dout = 0;
return;
} else if (SCpnt->sc_data_direction == DMA_TO_DEVICE) {
cpp->din = 0;
cpp->dout = 1;
return;
} else if (SCpnt->sc_data_direction == DMA_NONE) {
cpp->din = 0;
cpp->dout = 0;
return;
}
if (SCpnt->sc_data_direction != DMA_BIDIRECTIONAL)
panic("%s: qcomm, invalid SCpnt->sc_data_direction.\n",
ha->board_name);
for (k = 0; k < ARRAY_SIZE(data_out_cmds); k++)
if (SCpnt->cmnd[0] == data_out_cmds[k]) {
cpp->dout = 1;
break;
}
if ((cpp->din = !cpp->dout))
for (k = 0; k < ARRAY_SIZE(data_none_cmds); k++)
if (SCpnt->cmnd[0] == data_none_cmds[k]) {
cpp->din = 0;
break;
}
}
static int eata2x_queuecommand_lck(struct scsi_cmnd *SCpnt,
void (*done) (struct scsi_cmnd *))
{
struct Scsi_Host *shost = SCpnt->device->host;
struct hostdata *ha = (struct hostdata *)shost->hostdata;
unsigned int i, k;
struct mscp *cpp;
if (SCpnt->host_scribble)
panic("%s: qcomm, SCpnt %p already active.\n",
ha->board_name, SCpnt);
/* i is the mailbox number, look for the first free mailbox
starting from last_cp_used */
i = ha->last_cp_used + 1;
for (k = 0; k < shost->can_queue; k++, i++) {
if (i >= shost->can_queue)
i = 0;
if (ha->cp_stat[i] == FREE) {
ha->last_cp_used = i;
break;
}
}
if (k == shost->can_queue) {
printk("%s: qcomm, no free mailbox.\n", ha->board_name);
return 1;
}
/* Set pointer to control packet structure */
cpp = &ha->cp[i];
memset(cpp, 0, sizeof(struct mscp) - CP_TAIL_SIZE);
/* Set pointer to status packet structure, Big Endian format */
cpp->sp_dma_addr = H2DEV(ha->sp_dma_addr);
SCpnt->scsi_done = done;
cpp->cpp_index = i;
SCpnt->host_scribble = (unsigned char *)&cpp->cpp_index;
if (do_trace)
scmd_printk(KERN_INFO, SCpnt,
"qcomm, mbox %d.\n", i);
cpp->reqsen = 1;
cpp->dispri = 1;
#if 0
if (SCpnt->device->type == TYPE_TAPE)
cpp->hbaci = 1;
#endif
cpp->one = 1;
cpp->channel = SCpnt->device->channel;
cpp->target = SCpnt->device->id;
cpp->lun = SCpnt->device->lun;
cpp->SCpnt = SCpnt;
memcpy(cpp->cdb, SCpnt->cmnd, SCpnt->cmd_len);
/* Use data transfer direction SCpnt->sc_data_direction */
scsi_to_dev_dir(i, ha);
/* Map DMA buffers and SG list */
map_dma(i, ha);
if (linked_comm && SCpnt->device->queue_depth > 2
&& TLDEV(SCpnt->device->type)) {
ha->cp_stat[i] = READY;
flush_dev(SCpnt->device, blk_rq_pos(SCpnt->request), ha, 0);
return 0;
}
/* Send control packet to the board */
if (do_dma(shost->io_port, cpp->cp_dma_addr, SEND_CP_DMA)) {
unmap_dma(i, ha);
SCpnt->host_scribble = NULL;
scmd_printk(KERN_INFO, SCpnt, "qcomm, adapter busy.\n");
return 1;
}
ha->cp_stat[i] = IN_USE;
return 0;
}
static DEF_SCSI_QCMD(eata2x_queuecommand)
static int eata2x_eh_abort(struct scsi_cmnd *SCarg)
{
struct Scsi_Host *shost = SCarg->device->host;
struct hostdata *ha = (struct hostdata *)shost->hostdata;
unsigned int i;
if (SCarg->host_scribble == NULL) {
scmd_printk(KERN_INFO, SCarg, "abort, cmd inactive.\n");
return SUCCESS;
}
i = *(unsigned int *)SCarg->host_scribble;
scmd_printk(KERN_WARNING, SCarg, "abort, mbox %d.\n", i);
if (i >= shost->can_queue)
panic("%s: abort, invalid SCarg->host_scribble.\n", ha->board_name);
if (wait_on_busy(shost->io_port, MAXLOOP)) {
printk("%s: abort, timeout error.\n", ha->board_name);
return FAILED;
}
if (ha->cp_stat[i] == FREE) {
printk("%s: abort, mbox %d is free.\n", ha->board_name, i);
return SUCCESS;
}
if (ha->cp_stat[i] == IN_USE) {
printk("%s: abort, mbox %d is in use.\n", ha->board_name, i);
if (SCarg != ha->cp[i].SCpnt)
panic("%s: abort, mbox %d, SCarg %p, cp SCpnt %p.\n",
ha->board_name, i, SCarg, ha->cp[i].SCpnt);
if (inb(shost->io_port + REG_AUX_STATUS) & IRQ_ASSERTED)
printk("%s: abort, mbox %d, interrupt pending.\n",
ha->board_name, i);
return FAILED;
}
if (ha->cp_stat[i] == IN_RESET) {
printk("%s: abort, mbox %d is in reset.\n", ha->board_name, i);
return FAILED;
}
if (ha->cp_stat[i] == LOCKED) {
printk("%s: abort, mbox %d is locked.\n", ha->board_name, i);
return SUCCESS;
}
if (ha->cp_stat[i] == READY || ha->cp_stat[i] == ABORTING) {
unmap_dma(i, ha);
SCarg->result = DID_ABORT << 16;
SCarg->host_scribble = NULL;
ha->cp_stat[i] = FREE;
printk("%s, abort, mbox %d ready, DID_ABORT, done.\n",
ha->board_name, i);
SCarg->scsi_done(SCarg);
return SUCCESS;
}
panic("%s: abort, mbox %d, invalid cp_stat.\n", ha->board_name, i);
}
static int eata2x_eh_host_reset(struct scsi_cmnd *SCarg)
{
unsigned int i, time, k, c, limit = 0;
int arg_done = 0;
struct scsi_cmnd *SCpnt;
struct Scsi_Host *shost = SCarg->device->host;
struct hostdata *ha = (struct hostdata *)shost->hostdata;
scmd_printk(KERN_INFO, SCarg, "reset, enter.\n");
spin_lock_irq(shost->host_lock);
if (SCarg->host_scribble == NULL)
printk("%s: reset, inactive.\n", ha->board_name);
if (ha->in_reset) {
printk("%s: reset, exit, already in reset.\n", ha->board_name);
spin_unlock_irq(shost->host_lock);
return FAILED;
}
if (wait_on_busy(shost->io_port, MAXLOOP)) {
printk("%s: reset, exit, timeout error.\n", ha->board_name);
spin_unlock_irq(shost->host_lock);
return FAILED;
}
ha->retries = 0;
for (c = 0; c <= shost->max_channel; c++)
for (k = 0; k < shost->max_id; k++) {
ha->target_redo[k][c] = 1;
ha->target_to[k][c] = 0;
}
for (i = 0; i < shost->can_queue; i++) {
if (ha->cp_stat[i] == FREE)
continue;
if (ha->cp_stat[i] == LOCKED) {
ha->cp_stat[i] = FREE;
printk("%s: reset, locked mbox %d forced free.\n",
ha->board_name, i);
continue;
}
if (!(SCpnt = ha->cp[i].SCpnt))
panic("%s: reset, mbox %d, SCpnt == NULL.\n", ha->board_name, i);
if (ha->cp_stat[i] == READY || ha->cp_stat[i] == ABORTING) {
ha->cp_stat[i] = ABORTING;
printk("%s: reset, mbox %d aborting.\n",
ha->board_name, i);
}
else {
ha->cp_stat[i] = IN_RESET;
printk("%s: reset, mbox %d in reset.\n",
ha->board_name, i);
}
if (SCpnt->host_scribble == NULL)
panic("%s: reset, mbox %d, garbled SCpnt.\n", ha->board_name, i);
if (*(unsigned int *)SCpnt->host_scribble != i)
panic("%s: reset, mbox %d, index mismatch.\n", ha->board_name, i);
if (SCpnt->scsi_done == NULL)
panic("%s: reset, mbox %d, SCpnt->scsi_done == NULL.\n",
ha->board_name, i);
if (SCpnt == SCarg)
arg_done = 1;
}
if (do_dma(shost->io_port, 0, RESET_PIO)) {
printk("%s: reset, cannot reset, timeout error.\n", ha->board_name);
spin_unlock_irq(shost->host_lock);
return FAILED;
}
printk("%s: reset, board reset done, enabling interrupts.\n", ha->board_name);
#if defined(DEBUG_RESET)
do_trace = 1;
#endif
ha->in_reset = 1;
spin_unlock_irq(shost->host_lock);
/* FIXME: use a sleep instead */
time = jiffies;
while ((jiffies - time) < (10 * HZ) && limit++ < 200000)
udelay(100L);
spin_lock_irq(shost->host_lock);
printk("%s: reset, interrupts disabled, loops %d.\n", ha->board_name, limit);
for (i = 0; i < shost->can_queue; i++) {
if (ha->cp_stat[i] == IN_RESET) {
SCpnt = ha->cp[i].SCpnt;
unmap_dma(i, ha);
SCpnt->result = DID_RESET << 16;
SCpnt->host_scribble = NULL;
/* This mailbox is still waiting for its interrupt */
ha->cp_stat[i] = LOCKED;
printk
("%s, reset, mbox %d locked, DID_RESET, done.\n",
ha->board_name, i);
}
else if (ha->cp_stat[i] == ABORTING) {
SCpnt = ha->cp[i].SCpnt;
unmap_dma(i, ha);
SCpnt->result = DID_RESET << 16;
SCpnt->host_scribble = NULL;
/* This mailbox was never queued to the adapter */
ha->cp_stat[i] = FREE;
printk
("%s, reset, mbox %d aborting, DID_RESET, done.\n",
ha->board_name, i);
}
else
/* Any other mailbox has already been set free by interrupt */
continue;
SCpnt->scsi_done(SCpnt);
}
ha->in_reset = 0;
do_trace = 0;
if (arg_done)
printk("%s: reset, exit, done.\n", ha->board_name);
else
printk("%s: reset, exit.\n", ha->board_name);
spin_unlock_irq(shost->host_lock);
return SUCCESS;
}
int eata2x_bios_param(struct scsi_device *sdev, struct block_device *bdev,
sector_t capacity, int *dkinfo)
{
unsigned int size = capacity;
if (ext_tran || (scsicam_bios_param(bdev, capacity, dkinfo) < 0)) {
dkinfo[0] = 255;
dkinfo[1] = 63;
dkinfo[2] = size / (dkinfo[0] * dkinfo[1]);
}
#if defined (DEBUG_GEOMETRY)
printk("%s: bios_param, head=%d, sec=%d, cyl=%d.\n", driver_name,
dkinfo[0], dkinfo[1], dkinfo[2]);
#endif
return 0;
}
static void sort(unsigned long sk[], unsigned int da[], unsigned int n,
unsigned int rev)
{
unsigned int i, j, k, y;
unsigned long x;
for (i = 0; i < n - 1; i++) {
k = i;
for (j = k + 1; j < n; j++)
if (rev) {
if (sk[j] > sk[k])
k = j;
} else {
if (sk[j] < sk[k])
k = j;
}
if (k != i) {
x = sk[k];
sk[k] = sk[i];
sk[i] = x;
y = da[k];
da[k] = da[i];
da[i] = y;
}
}
return;
}
static int reorder(struct hostdata *ha, unsigned long cursec,
unsigned int ihdlr, unsigned int il[], unsigned int n_ready)
{
struct scsi_cmnd *SCpnt;
struct mscp *cpp;
unsigned int k, n;
unsigned int rev = 0, s = 1, r = 1;
unsigned int input_only = 1, overlap = 0;
unsigned long sl[n_ready], pl[n_ready], ll[n_ready];
unsigned long maxsec = 0, minsec = ULONG_MAX, seek = 0, iseek = 0;
unsigned long ioseek = 0;
static unsigned int flushcount = 0, batchcount = 0, sortcount = 0;
static unsigned int readycount = 0, ovlcount = 0, inputcount = 0;
static unsigned int readysorted = 0, revcount = 0;
static unsigned long seeksorted = 0, seeknosort = 0;
if (link_statistics && !(++flushcount % link_statistics))
printk("fc %d bc %d ic %d oc %d rc %d rs %d sc %d re %d"
" av %ldK as %ldK.\n", flushcount, batchcount,
inputcount, ovlcount, readycount, readysorted, sortcount,
revcount, seeknosort / (readycount + 1),
seeksorted / (readycount + 1));
if (n_ready <= 1)
return 0;
for (n = 0; n < n_ready; n++) {
k = il[n];
cpp = &ha->cp[k];
SCpnt = cpp->SCpnt;
if (!cpp->din)
input_only = 0;
if (blk_rq_pos(SCpnt->request) < minsec)
minsec = blk_rq_pos(SCpnt->request);
if (blk_rq_pos(SCpnt->request) > maxsec)
maxsec = blk_rq_pos(SCpnt->request);
sl[n] = blk_rq_pos(SCpnt->request);
ioseek += blk_rq_sectors(SCpnt->request);
if (!n)
continue;
if (sl[n] < sl[n - 1])
s = 0;
if (sl[n] > sl[n - 1])
r = 0;
if (link_statistics) {
if (sl[n] > sl[n - 1])
seek += sl[n] - sl[n - 1];
else
seek += sl[n - 1] - sl[n];
}
}
if (link_statistics) {
if (cursec > sl[0])
seek += cursec - sl[0];
else
seek += sl[0] - cursec;
}
if (cursec > ((maxsec + minsec) / 2))
rev = 1;
if (ioseek > ((maxsec - minsec) / 2))
rev = 0;
if (!((rev && r) || (!rev && s)))
sort(sl, il, n_ready, rev);
if (!input_only)
for (n = 0; n < n_ready; n++) {
k = il[n];
cpp = &ha->cp[k];
SCpnt = cpp->SCpnt;
ll[n] = blk_rq_sectors(SCpnt->request);
pl[n] = SCpnt->serial_number;
if (!n)
continue;
if ((sl[n] == sl[n - 1])
|| (!rev && ((sl[n - 1] + ll[n - 1]) > sl[n]))
|| (rev && ((sl[n] + ll[n]) > sl[n - 1])))
overlap = 1;
}
if (overlap)
sort(pl, il, n_ready, 0);
if (link_statistics) {
if (cursec > sl[0])
iseek = cursec - sl[0];
else
iseek = sl[0] - cursec;
batchcount++;
readycount += n_ready;
seeknosort += seek / 1024;
if (input_only)
inputcount++;
if (overlap) {
ovlcount++;
seeksorted += iseek / 1024;
} else
seeksorted += (iseek + maxsec - minsec) / 1024;
if (rev && !r) {
revcount++;
readysorted += n_ready;
}
if (!rev && !s) {
sortcount++;
readysorted += n_ready;
}
}
#if defined(DEBUG_LINKED_COMMANDS)
if (link_statistics && (overlap || !(flushcount % link_statistics)))
for (n = 0; n < n_ready; n++) {
k = il[n];
cpp = &ha->cp[k];
SCpnt = cpp->SCpnt;
scmd_printk(KERN_INFO, SCpnt,
"%s mb %d fc %d nr %d sec %ld ns %u"
" cur %ld s:%c r:%c rev:%c in:%c ov:%c xd %d.\n",
(ihdlr ? "ihdlr" : "qcomm"),
k, flushcount,
n_ready, blk_rq_pos(SCpnt->request),
blk_rq_sectors(SCpnt->request), cursec, YESNO(s),
YESNO(r), YESNO(rev), YESNO(input_only),
YESNO(overlap), cpp->din);
}
#endif
return overlap;
}
static void flush_dev(struct scsi_device *dev, unsigned long cursec,
struct hostdata *ha, unsigned int ihdlr)
{
struct scsi_cmnd *SCpnt;
struct mscp *cpp;
unsigned int k, n, n_ready = 0, il[MAX_MAILBOXES];
for (k = 0; k < dev->host->can_queue; k++) {
if (ha->cp_stat[k] != READY && ha->cp_stat[k] != IN_USE)
continue;
cpp = &ha->cp[k];
SCpnt = cpp->SCpnt;
if (SCpnt->device != dev)
continue;
if (ha->cp_stat[k] == IN_USE)
return;
il[n_ready++] = k;
}
if (reorder(ha, cursec, ihdlr, il, n_ready))
n_ready = 1;
for (n = 0; n < n_ready; n++) {
k = il[n];
cpp = &ha->cp[k];
SCpnt = cpp->SCpnt;
if (do_dma(dev->host->io_port, cpp->cp_dma_addr, SEND_CP_DMA)) {
scmd_printk(KERN_INFO, SCpnt,
"%s, mbox %d, adapter"
" busy, will abort.\n",
(ihdlr ? "ihdlr" : "qcomm"),
k);
ha->cp_stat[k] = ABORTING;
continue;
}
ha->cp_stat[k] = IN_USE;
}
}
static irqreturn_t ihdlr(struct Scsi_Host *shost)
{
struct scsi_cmnd *SCpnt;
unsigned int i, k, c, status, tstatus, reg;
struct mssp *spp;
struct mscp *cpp;
struct hostdata *ha = (struct hostdata *)shost->hostdata;
int irq = shost->irq;
/* Check if this board need to be serviced */
if (!(inb(shost->io_port + REG_AUX_STATUS) & IRQ_ASSERTED))
goto none;
ha->iocount++;
if (do_trace)
printk("%s: ihdlr, enter, irq %d, count %d.\n", ha->board_name, irq,
ha->iocount);
/* Check if this board is still busy */
if (wait_on_busy(shost->io_port, 20 * MAXLOOP)) {
reg = inb(shost->io_port + REG_STATUS);
printk
("%s: ihdlr, busy timeout error, irq %d, reg 0x%x, count %d.\n",
ha->board_name, irq, reg, ha->iocount);
goto none;
}
spp = &ha->sp;
/* Make a local copy just before clearing the interrupt indication */
memcpy(spp, ha->sp_cpu_addr, sizeof(struct mssp));
/* Clear the completion flag and cp pointer on the dynamic copy of sp */
memset(ha->sp_cpu_addr, 0, sizeof(struct mssp));
/* Read the status register to clear the interrupt indication */
reg = inb(shost->io_port + REG_STATUS);
#if defined (DEBUG_INTERRUPT)
{
unsigned char *bytesp;
int cnt;
bytesp = (unsigned char *)spp;
if (ha->iocount < 200) {
printk("sp[] =");
for (cnt = 0; cnt < 15; cnt++)
printk(" 0x%x", bytesp[cnt]);
printk("\n");
}
}
#endif
/* Reject any sp with supspect data */
if (spp->eoc == 0 && ha->iocount > 1)
printk
("%s: ihdlr, spp->eoc == 0, irq %d, reg 0x%x, count %d.\n",
ha->board_name, irq, reg, ha->iocount);
if (spp->cpp_index < 0 || spp->cpp_index >= shost->can_queue)
printk
("%s: ihdlr, bad spp->cpp_index %d, irq %d, reg 0x%x, count %d.\n",
ha->board_name, spp->cpp_index, irq, reg, ha->iocount);
if (spp->eoc == 0 || spp->cpp_index < 0
|| spp->cpp_index >= shost->can_queue)
goto handled;
/* Find the mailbox to be serviced on this board */
i = spp->cpp_index;
cpp = &(ha->cp[i]);
#if defined(DEBUG_GENERATE_ABORTS)
if ((ha->iocount > 500) && ((ha->iocount % 500) < 3))
goto handled;
#endif
if (ha->cp_stat[i] == IGNORE) {
ha->cp_stat[i] = FREE;
goto handled;
} else if (ha->cp_stat[i] == LOCKED) {
ha->cp_stat[i] = FREE;
printk("%s: ihdlr, mbox %d unlocked, count %d.\n", ha->board_name, i,
ha->iocount);
goto handled;
} else if (ha->cp_stat[i] == FREE) {
printk("%s: ihdlr, mbox %d is free, count %d.\n", ha->board_name, i,
ha->iocount);
goto handled;
} else if (ha->cp_stat[i] == IN_RESET)
printk("%s: ihdlr, mbox %d is in reset.\n", ha->board_name, i);
else if (ha->cp_stat[i] != IN_USE)
panic("%s: ihdlr, mbox %d, invalid cp_stat: %d.\n",
ha->board_name, i, ha->cp_stat[i]);
ha->cp_stat[i] = FREE;
SCpnt = cpp->SCpnt;
if (SCpnt == NULL)
panic("%s: ihdlr, mbox %d, SCpnt == NULL.\n", ha->board_name, i);
if (SCpnt->host_scribble == NULL)
panic("%s: ihdlr, mbox %d, SCpnt %p garbled.\n", ha->board_name,
i, SCpnt);
if (*(unsigned int *)SCpnt->host_scribble != i)
panic("%s: ihdlr, mbox %d, index mismatch %d.\n",
ha->board_name, i,
*(unsigned int *)SCpnt->host_scribble);
sync_dma(i, ha);
if (linked_comm && SCpnt->device->queue_depth > 2
&& TLDEV(SCpnt->device->type))
flush_dev(SCpnt->device, blk_rq_pos(SCpnt->request), ha, 1);
tstatus = status_byte(spp->target_status);
#if defined(DEBUG_GENERATE_ERRORS)
if ((ha->iocount > 500) && ((ha->iocount % 200) < 2))
spp->adapter_status = 0x01;
#endif
switch (spp->adapter_status) {
case ASOK: /* status OK */
/* Forces a reset if a disk drive keeps returning BUSY */
if (tstatus == BUSY && SCpnt->device->type != TYPE_TAPE)
status = DID_ERROR << 16;
/* If there was a bus reset, redo operation on each target */
else if (tstatus != GOOD && SCpnt->device->type == TYPE_DISK
&& ha->target_redo[SCpnt->device->id][SCpnt->
device->
channel])
status = DID_BUS_BUSY << 16;
/* Works around a flaw in scsi.c */
else if (tstatus == CHECK_CONDITION
&& SCpnt->device->type == TYPE_DISK
&& (SCpnt->sense_buffer[2] & 0xf) == RECOVERED_ERROR)
status = DID_BUS_BUSY << 16;
else
status = DID_OK << 16;
if (tstatus == GOOD)
ha->target_redo[SCpnt->device->id][SCpnt->device->
channel] = 0;
if (spp->target_status && SCpnt->device->type == TYPE_DISK &&
(!(tstatus == CHECK_CONDITION && ha->iocount <= 1000 &&
(SCpnt->sense_buffer[2] & 0xf) == NOT_READY)))
printk("%s: ihdlr, target %d.%d:%d, "
"target_status 0x%x, sense key 0x%x.\n",
ha->board_name,
SCpnt->device->channel, SCpnt->device->id,
SCpnt->device->lun,
spp->target_status, SCpnt->sense_buffer[2]);
ha->target_to[SCpnt->device->id][SCpnt->device->channel] = 0;
if (ha->last_retried_pid == SCpnt->serial_number)
ha->retries = 0;
break;
case ASST: /* Selection Time Out */
case 0x02: /* Command Time Out */
if (ha->target_to[SCpnt->device->id][SCpnt->device->channel] > 1)
status = DID_ERROR << 16;
else {
status = DID_TIME_OUT << 16;
ha->target_to[SCpnt->device->id][SCpnt->device->
channel]++;
}
break;
/* Perform a limited number of internal retries */
case 0x03: /* SCSI Bus Reset Received */
case 0x04: /* Initial Controller Power-up */
for (c = 0; c <= shost->max_channel; c++)
for (k = 0; k < shost->max_id; k++)
ha->target_redo[k][c] = 1;
if (SCpnt->device->type != TYPE_TAPE
&& ha->retries < MAX_INTERNAL_RETRIES) {
#if defined(DID_SOFT_ERROR)
status = DID_SOFT_ERROR << 16;
#else
status = DID_BUS_BUSY << 16;
#endif
ha->retries++;
ha->last_retried_pid = SCpnt->serial_number;
} else
status = DID_ERROR << 16;
break;
case 0x05: /* Unexpected Bus Phase */
case 0x06: /* Unexpected Bus Free */
case 0x07: /* Bus Parity Error */
case 0x08: /* SCSI Hung */
case 0x09: /* Unexpected Message Reject */
case 0x0a: /* SCSI Bus Reset Stuck */
case 0x0b: /* Auto Request-Sense Failed */
case 0x0c: /* Controller Ram Parity Error */
default:
status = DID_ERROR << 16;
break;
}
SCpnt->result = status | spp->target_status;
#if defined(DEBUG_INTERRUPT)
if (SCpnt->result || do_trace)
#else
if ((spp->adapter_status != ASOK && ha->iocount > 1000) ||
(spp->adapter_status != ASOK &&
spp->adapter_status != ASST && ha->iocount <= 1000) ||
do_trace || msg_byte(spp->target_status))
#endif
scmd_printk(KERN_INFO, SCpnt, "ihdlr, mbox %2d, err 0x%x:%x,"
" reg 0x%x, count %d.\n",
i, spp->adapter_status, spp->target_status,
reg, ha->iocount);
unmap_dma(i, ha);
/* Set the command state to inactive */
SCpnt->host_scribble = NULL;
SCpnt->scsi_done(SCpnt);
if (do_trace)
printk("%s: ihdlr, exit, irq %d, count %d.\n", ha->board_name,
irq, ha->iocount);
handled:
return IRQ_HANDLED;
none:
return IRQ_NONE;
}
static irqreturn_t do_interrupt_handler(int dummy, void *shap)
{
struct Scsi_Host *shost;
unsigned int j;
unsigned long spin_flags;
irqreturn_t ret;
/* Check if the interrupt must be processed by this handler */
if ((j = (unsigned int)((char *)shap - sha)) >= num_boards)
return IRQ_NONE;
shost = sh[j];
spin_lock_irqsave(shost->host_lock, spin_flags);
ret = ihdlr(shost);
spin_unlock_irqrestore(shost->host_lock, spin_flags);
return ret;
}
static int eata2x_release(struct Scsi_Host *shost)
{
struct hostdata *ha = (struct hostdata *)shost->hostdata;
unsigned int i;
for (i = 0; i < shost->can_queue; i++)
kfree((&ha->cp[i])->sglist);
for (i = 0; i < shost->can_queue; i++)
pci_unmap_single(ha->pdev, ha->cp[i].cp_dma_addr,
sizeof(struct mscp), PCI_DMA_BIDIRECTIONAL);
if (ha->sp_cpu_addr)
pci_free_consistent(ha->pdev, sizeof(struct mssp),
ha->sp_cpu_addr, ha->sp_dma_addr);
free_irq(shost->irq, &sha[ha->board_number]);
if (shost->dma_channel != NO_DMA)
free_dma(shost->dma_channel);
release_region(shost->io_port, shost->n_io_port);
scsi_unregister(shost);
return 0;
}
#include "scsi_module.c"
#ifndef MODULE
__setup("eata=", option_setup);
#endif /* end MODULE */
| gpl-2.0 |
gokhanmoral/siyah-xt | drivers/scsi/eata.c | 10738 | 78298 | /*
* eata.c - Low-level driver for EATA/DMA SCSI host adapters.
*
* 03 Jun 2003 Rev. 8.10 for linux-2.5.70
* + Update for new IRQ API.
* + Use "goto" when appropriate.
* + Drop eata.h.
* + Update for new module_param API.
* + Module parameters can now be specified only in the
* same format as the kernel boot options.
*
* boot option old module param
* ----------- ------------------
* addr,... io_port=addr,...
* lc:[y|n] linked_comm=[1|0]
* mq:xx max_queue_depth=xx
* tm:[0|1|2] tag_mode=[0|1|2]
* et:[y|n] ext_tran=[1|0]
* rs:[y|n] rev_scan=[1|0]
* ip:[y|n] isa_probe=[1|0]
* ep:[y|n] eisa_probe=[1|0]
* pp:[y|n] pci_probe=[1|0]
*
* A valid example using the new parameter format is:
* modprobe eata "eata=0x7410,0x230,lc:y,tm:0,mq:4,ep:n"
*
* which is equivalent to the old format:
* modprobe eata io_port=0x7410,0x230 linked_comm=1 tag_mode=0 \
* max_queue_depth=4 eisa_probe=0
*
* 12 Feb 2003 Rev. 8.04 for linux 2.5.60
* + Release irq before calling scsi_register.
*
* 12 Nov 2002 Rev. 8.02 for linux 2.5.47
* + Release driver_lock before calling scsi_register.
*
* 11 Nov 2002 Rev. 8.01 for linux 2.5.47
* + Fixed bios_param and scsicam_bios_param calling parameters.
*
* 28 Oct 2002 Rev. 8.00 for linux 2.5.44-ac4
* + Use new tcq and adjust_queue_depth api.
* + New command line option (tm:[0-2]) to choose the type of tags:
* 0 -> disable tagging ; 1 -> simple tags ; 2 -> ordered tags.
* Default is tm:0 (tagged commands disabled).
* For compatibility the "tc:" option is an alias of the "tm:"
* option; tc:n is equivalent to tm:0 and tc:y is equivalent to
* tm:1.
* + The tagged_comm module parameter has been removed, use tag_mode
* instead, equivalent to the "tm:" boot option.
*
* 10 Oct 2002 Rev. 7.70 for linux 2.5.42
* + Foreport from revision 6.70.
*
* 25 Jun 2002 Rev. 6.70 for linux 2.4.19
* + This release is the first one tested on a Big Endian platform:
* fixed endian-ness problem due to bitfields;
* fixed endian-ness problem in read_pio.
* + Added new options for selectively probing ISA, EISA and PCI bus:
*
* Boot option Parameter name Default according to
*
* ip:[y|n] isa_probe=[1|0] CONFIG_ISA defined
* ep:[y|n] eisa_probe=[1|0] CONFIG_EISA defined
* pp:[y|n] pci_probe=[1|0] CONFIG_PCI defined
*
* The default action is to perform probing if the corresponding
* bus is configured and to skip probing otherwise.
*
* + If pci_probe is in effect and a list of I/O ports is specified
* as parameter or boot option, pci_enable_device() is performed
* on all pci devices matching PCI_CLASS_STORAGE_SCSI.
*
* 21 Feb 2002 Rev. 6.52 for linux 2.4.18
* + Backport from rev. 7.22 (use io_request_lock).
*
* 20 Feb 2002 Rev. 7.22 for linux 2.5.5
* + Remove any reference to virt_to_bus().
* + Fix pio hang while detecting multiple HBAs.
* + Fixed a board detection bug: in a system with
* multiple ISA/EISA boards, all but the first one
* were erroneously detected as PCI.
*
* 01 Jan 2002 Rev. 7.20 for linux 2.5.1
* + Use the dynamic DMA mapping API.
*
* 19 Dec 2001 Rev. 7.02 for linux 2.5.1
* + Use SCpnt->sc_data_direction if set.
* + Use sglist.page instead of sglist.address.
*
* 11 Dec 2001 Rev. 7.00 for linux 2.5.1
* + Use host->host_lock instead of io_request_lock.
*
* 1 May 2001 Rev. 6.05 for linux 2.4.4
* + Clean up all pci related routines.
* + Fix data transfer direction for opcode SEND_CUE_SHEET (0x5d)
*
* 30 Jan 2001 Rev. 6.04 for linux 2.4.1
* + Call pci_resource_start after pci_enable_device.
*
* 25 Jan 2001 Rev. 6.03 for linux 2.4.0
* + "check_region" call replaced by "request_region".
*
* 22 Nov 2000 Rev. 6.02 for linux 2.4.0-test11
* + Return code checked when calling pci_enable_device.
* + Removed old scsi error handling support.
* + The obsolete boot option flag eh:n is silently ignored.
* + Removed error messages while a disk drive is powered up at
* boot time.
* + Improved boot messages: all tagged capable device are
* indicated as "tagged" or "soft-tagged" :
* - "soft-tagged" means that the driver is trying to do its
* own tagging (i.e. the tc:y option is in effect);
* - "tagged" means that the device supports tagged commands,
* but the driver lets the HBA be responsible for tagging
* support.
*
* 16 Sep 1999 Rev. 5.11 for linux 2.2.12 and 2.3.18
* + Updated to the new __setup interface for boot command line options.
* + When loaded as a module, accepts the new parameter boot_options
* which value is a string with the same format of the kernel boot
* command line options. A valid example is:
* modprobe eata 'boot_options="0x7410,0x230,lc:y,tc:n,mq:4"'
*
* 9 Sep 1999 Rev. 5.10 for linux 2.2.12 and 2.3.17
* + 64bit cleanup for Linux/Alpha platform support
* (contribution from H.J. Lu).
*
* 22 Jul 1999 Rev. 5.00 for linux 2.2.10 and 2.3.11
* + Removed pre-2.2 source code compatibility.
* + Added call to pci_set_master.
*
* 26 Jul 1998 Rev. 4.33 for linux 2.0.35 and 2.1.111
* + Added command line option (rs:[y|n]) to reverse the scan order
* of PCI boards. The default is rs:y, which reverses the BIOS order
* while registering PCI boards. The default value rs:y generates
* the same order of all previous revisions of this driver.
* Pls. note that "BIOS order" might have been reversed itself
* after the 2.1.9x PCI modifications in the linux kernel.
* The rs value is ignored when the explicit list of addresses
* is used by the "eata=port0,port1,..." command line option.
* + Added command line option (et:[y|n]) to force use of extended
* translation (255 heads, 63 sectors) as disk geometry.
* The default is et:n, which uses the disk geometry returned
* by scsicam_bios_param. The default value et:n is compatible with
* all previous revisions of this driver.
*
* 28 May 1998 Rev. 4.32 for linux 2.0.33 and 2.1.104
* Increased busy timeout from 10 msec. to 200 msec. while
* processing interrupts.
*
* 16 May 1998 Rev. 4.31 for linux 2.0.33 and 2.1.102
* Improved abort handling during the eh recovery process.
*
* 13 May 1998 Rev. 4.30 for linux 2.0.33 and 2.1.101
* The driver is now fully SMP safe, including the
* abort and reset routines.
* Added command line options (eh:[y|n]) to choose between
* new_eh_code and the old scsi code.
* If linux version >= 2.1.101 the default is eh:y, while the eh
* option is ignored for previous releases and the old scsi code
* is used.
*
* 18 Apr 1998 Rev. 4.20 for linux 2.0.33 and 2.1.97
* Reworked interrupt handler.
*
* 11 Apr 1998 rev. 4.05 for linux 2.0.33 and 2.1.95
* Major reliability improvement: when a batch with overlapping
* requests is detected, requests are queued one at a time
* eliminating any possible board or drive reordering.
*
* 10 Apr 1998 rev. 4.04 for linux 2.0.33 and 2.1.95
* Improved SMP support (if linux version >= 2.1.95).
*
* 9 Apr 1998 rev. 4.03 for linux 2.0.33 and 2.1.94
* Added support for new PCI code and IO-APIC remapping of irqs.
* Performance improvement: when sequential i/o is detected,
* always use direct sort instead of reverse sort.
*
* 4 Apr 1998 rev. 4.02 for linux 2.0.33 and 2.1.92
* io_port is now unsigned long.
*
* 17 Mar 1998 rev. 4.01 for linux 2.0.33 and 2.1.88
* Use new scsi error handling code (if linux version >= 2.1.88).
* Use new interrupt code.
*
* 12 Sep 1997 rev. 3.11 for linux 2.0.30 and 2.1.55
* Use of udelay inside the wait loops to avoid timeout
* problems with fast cpus.
* Removed check about useless calls to the interrupt service
* routine (reported on SMP systems only).
* At initialization time "sorted/unsorted" is displayed instead
* of "linked/unlinked" to reinforce the fact that "linking" is
* nothing but "elevator sorting" in the actual implementation.
*
* 17 May 1997 rev. 3.10 for linux 2.0.30 and 2.1.38
* Use of serial_number_at_timeout in abort and reset processing.
* Use of the __initfunc and __initdata macro in setup code.
* Minor cleanups in the list_statistics code.
* Increased controller busy timeout in order to better support
* slow SCSI devices.
*
* 24 Feb 1997 rev. 3.00 for linux 2.0.29 and 2.1.26
* When loading as a module, parameter passing is now supported
* both in 2.0 and in 2.1 style.
* Fixed data transfer direction for some SCSI opcodes.
* Immediate acknowledge to request sense commands.
* Linked commands to each disk device are now reordered by elevator
* sorting. Rare cases in which reordering of write requests could
* cause wrong results are managed.
* Fixed spurious timeouts caused by long simple queue tag sequences.
* New command line option (tm:[0-3]) to choose the type of tags:
* 0 -> mixed (default); 1 -> simple; 2 -> head; 3 -> ordered.
*
* 18 Jan 1997 rev. 2.60 for linux 2.1.21 and 2.0.28
* Added command line options to enable/disable linked commands
* (lc:[y|n]), tagged commands (tc:[y|n]) and to set the max queue
* depth (mq:xx). Default is "eata=lc:n,tc:n,mq:16".
* Improved command linking.
* Documented how to setup RAID-0 with DPT SmartRAID boards.
*
* 8 Jan 1997 rev. 2.50 for linux 2.1.20 and 2.0.27
* Added linked command support.
* Improved detection of PCI boards using ISA base addresses.
*
* 3 Dec 1996 rev. 2.40 for linux 2.1.14 and 2.0.27
* Added support for tagged commands and queue depth adjustment.
*
* 22 Nov 1996 rev. 2.30 for linux 2.1.12 and 2.0.26
* When CONFIG_PCI is defined, BIOS32 is used to include in the
* list of i/o ports to be probed all the PCI SCSI controllers.
* The list of i/o ports to be probed can be overwritten by the
* "eata=port0,port1,...." boot command line option.
* Scatter/gather lists are now allocated by a number of kmalloc
* calls, in order to avoid the previous size limit of 64Kb.
*
* 16 Nov 1996 rev. 2.20 for linux 2.1.10 and 2.0.25
* Added support for EATA 2.0C, PCI, multichannel and wide SCSI.
*
* 27 Sep 1996 rev. 2.12 for linux 2.1.0
* Portability cleanups (virtual/bus addressing, little/big endian
* support).
*
* 09 Jul 1996 rev. 2.11 for linux 2.0.4
* Number of internal retries is now limited.
*
* 16 Apr 1996 rev. 2.10 for linux 1.3.90
* New argument "reset_flags" to the reset routine.
*
* 6 Jul 1995 rev. 2.01 for linux 1.3.7
* Update required by the new /proc/scsi support.
*
* 11 Mar 1995 rev. 2.00 for linux 1.2.0
* Fixed a bug which prevented media change detection for removable
* disk drives.
*
* 23 Feb 1995 rev. 1.18 for linux 1.1.94
* Added a check for scsi_register returning NULL.
*
* 11 Feb 1995 rev. 1.17 for linux 1.1.91
* Now DEBUG_RESET is disabled by default.
* Register a board even if it does not assert DMA protocol support
* (DPT SK2011B does not report correctly the dmasup bit).
*
* 9 Feb 1995 rev. 1.16 for linux 1.1.90
* Use host->wish_block instead of host->block.
* New list of Data Out SCSI commands.
*
* 8 Feb 1995 rev. 1.15 for linux 1.1.89
* Cleared target_time_out counter while performing a reset.
* All external symbols renamed to avoid possible name conflicts.
*
* 28 Jan 1995 rev. 1.14 for linux 1.1.86
* Added module support.
* Log and do a retry when a disk drive returns a target status
* different from zero on a recovered error.
*
* 24 Jan 1995 rev. 1.13 for linux 1.1.85
* Use optimized board configuration, with a measured performance
* increase in the range 10%-20% on i/o throughput.
*
* 16 Jan 1995 rev. 1.12 for linux 1.1.81
* Fix mscp structure comments (no functional change).
* Display a message if check_region detects a port address
* already in use.
*
* 17 Dec 1994 rev. 1.11 for linux 1.1.74
* Use the scsicam_bios_param routine. This allows an easy
* migration path from disk partition tables created using
* different SCSI drivers and non optimal disk geometry.
*
* 15 Dec 1994 rev. 1.10 for linux 1.1.74
* Added support for ISA EATA boards (DPT PM2011, DPT PM2021).
* The host->block flag is set for all the detected ISA boards.
* The detect routine no longer enforces LEVEL triggering
* for EISA boards, it just prints a warning message.
*
* 30 Nov 1994 rev. 1.09 for linux 1.1.68
* Redo i/o on target status CHECK_CONDITION for TYPE_DISK only.
* Added optional support for using a single board at a time.
*
* 18 Nov 1994 rev. 1.08 for linux 1.1.64
* Forces sg_tablesize = 64 and can_queue = 64 if these
* values are not correctly detected (DPT PM2012).
*
* 14 Nov 1994 rev. 1.07 for linux 1.1.63 Final BETA release.
* 04 Aug 1994 rev. 1.00 for linux 1.1.39 First BETA release.
*
*
* This driver is based on the CAM (Common Access Method Committee)
* EATA (Enhanced AT Bus Attachment) rev. 2.0A, using DMA protocol.
*
* Copyright (C) 1994-2003 Dario Ballabio (ballabio_dario@emc.com)
*
* Alternate email: dario.ballabio@inwind.it, dario.ballabio@tiscalinet.it
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that redistributions of source
* code retain the above copyright notice and this comment without
* modification.
*
*/
/*
*
* Here is a brief description of the DPT SCSI host adapters.
* All these boards provide an EATA/DMA compatible programming interface
* and are fully supported by this driver in any configuration, including
* multiple SCSI channels:
*
* PM2011B/9X - Entry Level ISA
* PM2021A/9X - High Performance ISA
* PM2012A Old EISA
* PM2012B Old EISA
* PM2022A/9X - Entry Level EISA
* PM2122A/9X - High Performance EISA
* PM2322A/9X - Extra High Performance EISA
* PM3021 - SmartRAID Adapter for ISA
* PM3222 - SmartRAID Adapter for EISA (PM3222W is 16-bit wide SCSI)
* PM3224 - SmartRAID Adapter for PCI (PM3224W is 16-bit wide SCSI)
* PM33340UW - SmartRAID Adapter for PCI ultra wide multichannel
*
* The above list is just an indication: as a matter of fact all DPT
* boards using the EATA/DMA protocol are supported by this driver,
* since they use exactely the same programming interface.
*
* The DPT PM2001 provides only the EATA/PIO interface and hence is not
* supported by this driver.
*
* This code has been tested with up to 3 Distributed Processing Technology
* PM2122A/9X (DPT SCSI BIOS v002.D1, firmware v05E.0) EISA controllers,
* in any combination of private and shared IRQ.
* PCI support has been tested using up to 2 DPT PM3224W (DPT SCSI BIOS
* v003.D0, firmware v07G.0).
*
* DPT SmartRAID boards support "Hardware Array" - a group of disk drives
* which are all members of the same RAID-0, RAID-1 or RAID-5 array implemented
* in host adapter hardware. Hardware Arrays are fully compatible with this
* driver, since they look to it as a single disk drive.
*
* WARNING: to create a RAID-0 "Hardware Array" you must select "Other Unix"
* as the current OS in the DPTMGR "Initial System Installation" menu.
* Otherwise RAID-0 is generated as an "Array Group" (i.e. software RAID-0),
* which is not supported by the actual SCSI subsystem.
* To get the "Array Group" functionality, the Linux MD driver must be used
* instead of the DPT "Array Group" feature.
*
* Multiple ISA, EISA and PCI boards can be configured in the same system.
* It is suggested to put all the EISA boards on the same IRQ level, all
* the PCI boards on another IRQ level, while ISA boards cannot share
* interrupts.
*
* If you configure multiple boards on the same IRQ, the interrupt must
* be _level_ triggered (not _edge_ triggered).
*
* This driver detects EATA boards by probes at fixed port addresses,
* so no BIOS32 or PCI BIOS support is required.
* The suggested way to detect a generic EATA PCI board is to force on it
* any unused EISA address, even if there are other controllers on the EISA
* bus, or even if you system has no EISA bus at all.
* Do not force any ISA address on EATA PCI boards.
*
* If PCI bios support is configured into the kernel, BIOS32 is used to
* include in the list of i/o ports to be probed all the PCI SCSI controllers.
*
* Due to a DPT BIOS "feature", it might not be possible to force an EISA
* address on more than a single DPT PCI board, so in this case you have to
* let the PCI BIOS assign the addresses.
*
* The sequence of detection probes is:
*
* - ISA 0x1F0;
* - PCI SCSI controllers (only if BIOS32 is available);
* - EISA/PCI 0x1C88 through 0xFC88 (corresponding to EISA slots 1 to 15);
* - ISA 0x170, 0x230, 0x330.
*
* The above list of detection probes can be totally replaced by the
* boot command line option: "eata=port0,port1,port2,...", where the
* port0, port1... arguments are ISA/EISA/PCI addresses to be probed.
* For example using "eata=0x7410,0x7450,0x230", the driver probes
* only the two PCI addresses 0x7410 and 0x7450 and the ISA address 0x230,
* in this order; "eata=0" totally disables this driver.
*
* After the optional list of detection probes, other possible command line
* options are:
*
* et:y force use of extended translation (255 heads, 63 sectors);
* et:n use disk geometry detected by scsicam_bios_param;
* rs:y reverse scan order while detecting PCI boards;
* rs:n use BIOS order while detecting PCI boards;
* lc:y enables linked commands;
* lc:n disables linked commands;
* tm:0 disables tagged commands (same as tc:n);
* tm:1 use simple queue tags (same as tc:y);
* tm:2 use ordered queue tags (same as tc:2);
* mq:xx set the max queue depth to the value xx (2 <= xx <= 32).
*
* The default value is: "eata=lc:n,mq:16,tm:0,et:n,rs:n".
* An example using the list of detection probes could be:
* "eata=0x7410,0x230,lc:y,tm:2,mq:4,et:n".
*
* When loading as a module, parameters can be specified as well.
* The above example would be (use 1 in place of y and 0 in place of n):
*
* modprobe eata io_port=0x7410,0x230 linked_comm=1 \
* max_queue_depth=4 ext_tran=0 tag_mode=2 \
* rev_scan=1
*
* ----------------------------------------------------------------------------
* In this implementation, linked commands are designed to work with any DISK
* or CD-ROM, since this linking has only the intent of clustering (time-wise)
* and reordering by elevator sorting commands directed to each device,
* without any relation with the actual SCSI protocol between the controller
* and the device.
* If Q is the queue depth reported at boot time for each device (also named
* cmds/lun) and Q > 2, whenever there is already an active command to the
* device all other commands to the same device (up to Q-1) are kept waiting
* in the elevator sorting queue. When the active command completes, the
* commands in this queue are sorted by sector address. The sort is chosen
* between increasing or decreasing by minimizing the seek distance between
* the sector of the commands just completed and the sector of the first
* command in the list to be sorted.
* Trivial math assures that the unsorted average seek distance when doing
* random seeks over S sectors is S/3.
* When (Q-1) requests are uniformly distributed over S sectors, the average
* distance between two adjacent requests is S/((Q-1) + 1), so the sorted
* average seek distance for (Q-1) random requests over S sectors is S/Q.
* The elevator sorting hence divides the seek distance by a factor Q/3.
* The above pure geometric remarks are valid in all cases and the
* driver effectively reduces the seek distance by the predicted factor
* when there are Q concurrent read i/o operations on the device, but this
* does not necessarily results in a noticeable performance improvement:
* your mileage may vary....
*
* Note: command reordering inside a batch of queued commands could cause
* wrong results only if there is at least one write request and the
* intersection (sector-wise) of all requests is not empty.
* When the driver detects a batch including overlapping requests
* (a really rare event) strict serial (pid) order is enforced.
* ----------------------------------------------------------------------------
* The extended translation option (et:y) is useful when using large physical
* disks/arrays. It could also be useful when switching between Adaptec boards
* and DPT boards without reformatting the disk.
* When a boot disk is partitioned with extended translation, in order to
* be able to boot it with a DPT board is could be necessary to add to
* lilo.conf additional commands as in the following example:
*
* fix-table
* disk=/dev/sda bios=0x80 sectors=63 heads=128 cylindres=546
*
* where the above geometry should be replaced with the one reported at
* power up by the DPT controller.
* ----------------------------------------------------------------------------
*
* The boards are named EATA0, EATA1,... according to the detection order.
*
* In order to support multiple ISA boards in a reliable way,
* the driver sets host->wish_block = 1 for all ISA boards.
*/
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/ioport.h>
#include <linux/delay.h>
#include <linux/proc_fs.h>
#include <linux/blkdev.h>
#include <linux/interrupt.h>
#include <linux/stat.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/ctype.h>
#include <linux/spinlock.h>
#include <linux/dma-mapping.h>
#include <linux/slab.h>
#include <asm/byteorder.h>
#include <asm/dma.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_tcq.h>
#include <scsi/scsicam.h>
static int eata2x_detect(struct scsi_host_template *);
static int eata2x_release(struct Scsi_Host *);
static int eata2x_queuecommand(struct Scsi_Host *, struct scsi_cmnd *);
static int eata2x_eh_abort(struct scsi_cmnd *);
static int eata2x_eh_host_reset(struct scsi_cmnd *);
static int eata2x_bios_param(struct scsi_device *, struct block_device *,
sector_t, int *);
static int eata2x_slave_configure(struct scsi_device *);
static struct scsi_host_template driver_template = {
.name = "EATA/DMA 2.0x rev. 8.10.00 ",
.detect = eata2x_detect,
.release = eata2x_release,
.queuecommand = eata2x_queuecommand,
.eh_abort_handler = eata2x_eh_abort,
.eh_host_reset_handler = eata2x_eh_host_reset,
.bios_param = eata2x_bios_param,
.slave_configure = eata2x_slave_configure,
.this_id = 7,
.unchecked_isa_dma = 1,
.use_clustering = ENABLE_CLUSTERING,
};
#if !defined(__BIG_ENDIAN_BITFIELD) && !defined(__LITTLE_ENDIAN_BITFIELD)
#error "Adjust your <asm/byteorder.h> defines"
#endif
/* Subversion values */
#define ISA 0
#define ESA 1
#undef FORCE_CONFIG
#undef DEBUG_LINKED_COMMANDS
#undef DEBUG_DETECT
#undef DEBUG_PCI_DETECT
#undef DEBUG_INTERRUPT
#undef DEBUG_RESET
#undef DEBUG_GENERATE_ERRORS
#undef DEBUG_GENERATE_ABORTS
#undef DEBUG_GEOMETRY
#define MAX_ISA 4
#define MAX_VESA 0
#define MAX_EISA 15
#define MAX_PCI 16
#define MAX_BOARDS (MAX_ISA + MAX_VESA + MAX_EISA + MAX_PCI)
#define MAX_CHANNEL 4
#define MAX_LUN 32
#define MAX_TARGET 32
#define MAX_MAILBOXES 64
#define MAX_SGLIST 64
#define MAX_LARGE_SGLIST 122
#define MAX_INTERNAL_RETRIES 64
#define MAX_CMD_PER_LUN 2
#define MAX_TAGGED_CMD_PER_LUN (MAX_MAILBOXES - MAX_CMD_PER_LUN)
#define SKIP ULONG_MAX
#define FREE 0
#define IN_USE 1
#define LOCKED 2
#define IN_RESET 3
#define IGNORE 4
#define READY 5
#define ABORTING 6
#define NO_DMA 0xff
#define MAXLOOP 10000
#define TAG_DISABLED 0
#define TAG_SIMPLE 1
#define TAG_ORDERED 2
#define REG_CMD 7
#define REG_STATUS 7
#define REG_AUX_STATUS 8
#define REG_DATA 0
#define REG_DATA2 1
#define REG_SEE 6
#define REG_LOW 2
#define REG_LM 3
#define REG_MID 4
#define REG_MSB 5
#define REGION_SIZE 9UL
#define MAX_ISA_ADDR 0x03ff
#define MIN_EISA_ADDR 0x1c88
#define MAX_EISA_ADDR 0xfc88
#define BSY_ASSERTED 0x80
#define DRQ_ASSERTED 0x08
#define ABSY_ASSERTED 0x01
#define IRQ_ASSERTED 0x02
#define READ_CONFIG_PIO 0xf0
#define SET_CONFIG_PIO 0xf1
#define SEND_CP_PIO 0xf2
#define RECEIVE_SP_PIO 0xf3
#define TRUNCATE_XFR_PIO 0xf4
#define RESET_PIO 0xf9
#define READ_CONFIG_DMA 0xfd
#define SET_CONFIG_DMA 0xfe
#define SEND_CP_DMA 0xff
#define ASOK 0x00
#define ASST 0x01
#define YESNO(a) ((a) ? 'y' : 'n')
#define TLDEV(type) ((type) == TYPE_DISK || (type) == TYPE_ROM)
/* "EATA", in Big Endian format */
#define EATA_SIG_BE 0x45415441
/* Number of valid bytes in the board config structure for EATA 2.0x */
#define EATA_2_0A_SIZE 28
#define EATA_2_0B_SIZE 30
#define EATA_2_0C_SIZE 34
/* Board info structure */
struct eata_info {
u_int32_t data_len; /* Number of valid bytes after this field */
u_int32_t sign; /* ASCII "EATA" signature */
#if defined(__BIG_ENDIAN_BITFIELD)
unchar version : 4,
: 4;
unchar haaval : 1,
ata : 1,
drqvld : 1,
dmasup : 1,
morsup : 1,
trnxfr : 1,
tarsup : 1,
ocsena : 1;
#else
unchar : 4, /* unused low nibble */
version : 4; /* EATA version, should be 0x1 */
unchar ocsena : 1, /* Overlap Command Support Enabled */
tarsup : 1, /* Target Mode Supported */
trnxfr : 1, /* Truncate Transfer Cmd NOT Necessary */
morsup : 1, /* More Supported */
dmasup : 1, /* DMA Supported */
drqvld : 1, /* DRQ Index (DRQX) is valid */
ata : 1, /* This is an ATA device */
haaval : 1; /* Host Adapter Address Valid */
#endif
ushort cp_pad_len; /* Number of pad bytes after cp_len */
unchar host_addr[4]; /* Host Adapter SCSI ID for channels 3, 2, 1, 0 */
u_int32_t cp_len; /* Number of valid bytes in cp */
u_int32_t sp_len; /* Number of valid bytes in sp */
ushort queue_size; /* Max number of cp that can be queued */
ushort unused;
ushort scatt_size; /* Max number of entries in scatter/gather table */
#if defined(__BIG_ENDIAN_BITFIELD)
unchar drqx : 2,
second : 1,
irq_tr : 1,
irq : 4;
unchar sync;
unchar : 4,
res1 : 1,
large_sg : 1,
forcaddr : 1,
isaena : 1;
unchar max_chan : 3,
max_id : 5;
unchar max_lun;
unchar eisa : 1,
pci : 1,
idquest : 1,
m1 : 1,
: 4;
#else
unchar irq : 4, /* Interrupt Request assigned to this controller */
irq_tr : 1, /* 0 for edge triggered, 1 for level triggered */
second : 1, /* 1 if this is a secondary (not primary) controller */
drqx : 2; /* DRQ Index (0=DMA0, 1=DMA7, 2=DMA6, 3=DMA5) */
unchar sync; /* 1 if scsi target id 7...0 is running sync scsi */
/* Structure extension defined in EATA 2.0B */
unchar isaena : 1, /* ISA i/o addressing is disabled/enabled */
forcaddr : 1, /* Port address has been forced */
large_sg : 1, /* 1 if large SG lists are supported */
res1 : 1,
: 4;
unchar max_id : 5, /* Max SCSI target ID number */
max_chan : 3; /* Max SCSI channel number on this board */
/* Structure extension defined in EATA 2.0C */
unchar max_lun; /* Max SCSI LUN number */
unchar
: 4,
m1 : 1, /* This is a PCI with an M1 chip installed */
idquest : 1, /* RAIDNUM returned is questionable */
pci : 1, /* This board is PCI */
eisa : 1; /* This board is EISA */
#endif
unchar raidnum; /* Uniquely identifies this HBA in a system */
unchar notused;
ushort ipad[247];
};
/* Board config structure */
struct eata_config {
ushort len; /* Number of bytes following this field */
#if defined(__BIG_ENDIAN_BITFIELD)
unchar : 4,
tarena : 1,
mdpena : 1,
ocena : 1,
edis : 1;
#else
unchar edis : 1, /* Disable EATA interface after config command */
ocena : 1, /* Overlapped Commands Enabled */
mdpena : 1, /* Transfer all Modified Data Pointer Messages */
tarena : 1, /* Target Mode Enabled for this controller */
: 4;
#endif
unchar cpad[511];
};
/* Returned status packet structure */
struct mssp {
#if defined(__BIG_ENDIAN_BITFIELD)
unchar eoc : 1,
adapter_status : 7;
#else
unchar adapter_status : 7, /* State related to current command */
eoc : 1; /* End Of Command (1 = command completed) */
#endif
unchar target_status; /* SCSI status received after data transfer */
unchar unused[2];
u_int32_t inv_res_len; /* Number of bytes not transferred */
u_int32_t cpp_index; /* Index of address set in cp */
char mess[12];
};
struct sg_list {
unsigned int address; /* Segment Address */
unsigned int num_bytes; /* Segment Length */
};
/* MailBox SCSI Command Packet */
struct mscp {
#if defined(__BIG_ENDIAN_BITFIELD)
unchar din : 1,
dout : 1,
interp : 1,
: 1,
sg : 1,
reqsen :1,
init : 1,
sreset : 1;
unchar sense_len;
unchar unused[3];
unchar : 7,
fwnest : 1;
unchar : 5,
hbaci : 1,
iat : 1,
phsunit : 1;
unchar channel : 3,
target : 5;
unchar one : 1,
dispri : 1,
luntar : 1,
lun : 5;
#else
unchar sreset :1, /* SCSI Bus Reset Signal should be asserted */
init :1, /* Re-initialize controller and self test */
reqsen :1, /* Transfer Request Sense Data to addr using DMA */
sg :1, /* Use Scatter/Gather */
:1,
interp :1, /* The controller interprets cp, not the target */
dout :1, /* Direction of Transfer is Out (Host to Target) */
din :1; /* Direction of Transfer is In (Target to Host) */
unchar sense_len; /* Request Sense Length */
unchar unused[3];
unchar fwnest : 1, /* Send command to a component of an Array Group */
: 7;
unchar phsunit : 1, /* Send to Target Physical Unit (bypass RAID) */
iat : 1, /* Inhibit Address Translation */
hbaci : 1, /* Inhibit HBA Caching for this command */
: 5;
unchar target : 5, /* SCSI target ID */
channel : 3; /* SCSI channel number */
unchar lun : 5, /* SCSI logical unit number */
luntar : 1, /* This cp is for Target (not LUN) */
dispri : 1, /* Disconnect Privilege granted */
one : 1; /* 1 */
#endif
unchar mess[3]; /* Massage to/from Target */
unchar cdb[12]; /* Command Descriptor Block */
u_int32_t data_len; /* If sg=0 Data Length, if sg=1 sglist length */
u_int32_t cpp_index; /* Index of address to be returned in sp */
u_int32_t data_address; /* If sg=0 Data Address, if sg=1 sglist address */
u_int32_t sp_dma_addr; /* Address where sp is DMA'ed when cp completes */
u_int32_t sense_addr; /* Address where Sense Data is DMA'ed on error */
/* Additional fields begin here. */
struct scsi_cmnd *SCpnt;
/* All the cp structure is zero filled by queuecommand except the
following CP_TAIL_SIZE bytes, initialized by detect */
dma_addr_t cp_dma_addr; /* dma handle for this cp structure */
struct sg_list *sglist; /* pointer to the allocated SG list */
};
#define CP_TAIL_SIZE (sizeof(struct sglist *) + sizeof(dma_addr_t))
struct hostdata {
struct mscp cp[MAX_MAILBOXES]; /* Mailboxes for this board */
unsigned int cp_stat[MAX_MAILBOXES]; /* FREE, IN_USE, LOCKED, IN_RESET */
unsigned int last_cp_used; /* Index of last mailbox used */
unsigned int iocount; /* Total i/o done for this board */
int board_number; /* Number of this board */
char board_name[16]; /* Name of this board */
int in_reset; /* True if board is doing a reset */
int target_to[MAX_TARGET][MAX_CHANNEL]; /* N. of timeout errors on target */
int target_redo[MAX_TARGET][MAX_CHANNEL]; /* If 1 redo i/o on target */
unsigned int retries; /* Number of internal retries */
unsigned long last_retried_pid; /* Pid of last retried command */
unsigned char subversion; /* Bus type, either ISA or EISA/PCI */
unsigned char protocol_rev; /* EATA 2.0 rev., 'A' or 'B' or 'C' */
unsigned char is_pci; /* 1 is bus type is PCI */
struct pci_dev *pdev; /* pdev for PCI bus, NULL otherwise */
struct mssp *sp_cpu_addr; /* cpu addr for DMA buffer sp */
dma_addr_t sp_dma_addr; /* dma handle for DMA buffer sp */
struct mssp sp; /* Local copy of sp buffer */
};
static struct Scsi_Host *sh[MAX_BOARDS];
static const char *driver_name = "EATA";
static char sha[MAX_BOARDS];
static DEFINE_SPINLOCK(driver_lock);
/* Initialize num_boards so that ihdlr can work while detect is in progress */
static unsigned int num_boards = MAX_BOARDS;
static unsigned long io_port[] = {
/* Space for MAX_INT_PARAM ports usable while loading as a module */
SKIP, SKIP, SKIP, SKIP, SKIP, SKIP, SKIP, SKIP,
SKIP, SKIP,
/* First ISA */
0x1f0,
/* Space for MAX_PCI ports possibly reported by PCI_BIOS */
SKIP, SKIP, SKIP, SKIP, SKIP, SKIP, SKIP, SKIP,
SKIP, SKIP, SKIP, SKIP, SKIP, SKIP, SKIP, SKIP,
/* MAX_EISA ports */
0x1c88, 0x2c88, 0x3c88, 0x4c88, 0x5c88, 0x6c88, 0x7c88, 0x8c88,
0x9c88, 0xac88, 0xbc88, 0xcc88, 0xdc88, 0xec88, 0xfc88,
/* Other (MAX_ISA - 1) ports */
0x170, 0x230, 0x330,
/* End of list */
0x0
};
/* Device is Big Endian */
#define H2DEV(x) cpu_to_be32(x)
#define DEV2H(x) be32_to_cpu(x)
#define H2DEV16(x) cpu_to_be16(x)
#define DEV2H16(x) be16_to_cpu(x)
/* But transfer orientation from the 16 bit data register is Little Endian */
#define REG2H(x) le16_to_cpu(x)
static irqreturn_t do_interrupt_handler(int, void *);
static void flush_dev(struct scsi_device *, unsigned long, struct hostdata *,
unsigned int);
static int do_trace = 0;
static int setup_done = 0;
static int link_statistics;
static int ext_tran = 0;
static int rev_scan = 1;
#if defined(CONFIG_SCSI_EATA_TAGGED_QUEUE)
static int tag_mode = TAG_SIMPLE;
#else
static int tag_mode = TAG_DISABLED;
#endif
#if defined(CONFIG_SCSI_EATA_LINKED_COMMANDS)
static int linked_comm = 1;
#else
static int linked_comm = 0;
#endif
#if defined(CONFIG_SCSI_EATA_MAX_TAGS)
static int max_queue_depth = CONFIG_SCSI_EATA_MAX_TAGS;
#else
static int max_queue_depth = MAX_CMD_PER_LUN;
#endif
#if defined(CONFIG_ISA)
static int isa_probe = 1;
#else
static int isa_probe = 0;
#endif
#if defined(CONFIG_EISA)
static int eisa_probe = 1;
#else
static int eisa_probe = 0;
#endif
#if defined(CONFIG_PCI)
static int pci_probe = 1;
#else
static int pci_probe = 0;
#endif
#define MAX_INT_PARAM 10
#define MAX_BOOT_OPTIONS_SIZE 256
static char boot_options[MAX_BOOT_OPTIONS_SIZE];
#if defined(MODULE)
#include <linux/module.h>
#include <linux/moduleparam.h>
module_param_string(eata, boot_options, MAX_BOOT_OPTIONS_SIZE, 0);
MODULE_PARM_DESC(eata, " equivalent to the \"eata=...\" kernel boot option."
" Example: modprobe eata \"eata=0x7410,0x230,lc:y,tm:0,mq:4,ep:n\"");
MODULE_AUTHOR("Dario Ballabio");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("EATA/DMA SCSI Driver");
#endif
static int eata2x_slave_configure(struct scsi_device *dev)
{
int tqd, utqd;
char *tag_suffix, *link_suffix;
utqd = MAX_CMD_PER_LUN;
tqd = max_queue_depth;
if (TLDEV(dev->type) && dev->tagged_supported) {
if (tag_mode == TAG_SIMPLE) {
scsi_adjust_queue_depth(dev, MSG_SIMPLE_TAG, tqd);
tag_suffix = ", simple tags";
} else if (tag_mode == TAG_ORDERED) {
scsi_adjust_queue_depth(dev, MSG_ORDERED_TAG, tqd);
tag_suffix = ", ordered tags";
} else {
scsi_adjust_queue_depth(dev, 0, tqd);
tag_suffix = ", no tags";
}
} else if (TLDEV(dev->type) && linked_comm) {
scsi_adjust_queue_depth(dev, 0, tqd);
tag_suffix = ", untagged";
} else {
scsi_adjust_queue_depth(dev, 0, utqd);
tag_suffix = "";
}
if (TLDEV(dev->type) && linked_comm && dev->queue_depth > 2)
link_suffix = ", sorted";
else if (TLDEV(dev->type))
link_suffix = ", unsorted";
else
link_suffix = "";
sdev_printk(KERN_INFO, dev,
"cmds/lun %d%s%s.\n",
dev->queue_depth, link_suffix, tag_suffix);
return 0;
}
static int wait_on_busy(unsigned long iobase, unsigned int loop)
{
while (inb(iobase + REG_AUX_STATUS) & ABSY_ASSERTED) {
udelay(1L);
if (--loop == 0)
return 1;
}
return 0;
}
static int do_dma(unsigned long iobase, unsigned long addr, unchar cmd)
{
unsigned char *byaddr;
unsigned long devaddr;
if (wait_on_busy(iobase, (addr ? MAXLOOP * 100 : MAXLOOP)))
return 1;
if (addr) {
devaddr = H2DEV(addr);
byaddr = (unsigned char *)&devaddr;
outb(byaddr[3], iobase + REG_LOW);
outb(byaddr[2], iobase + REG_LM);
outb(byaddr[1], iobase + REG_MID);
outb(byaddr[0], iobase + REG_MSB);
}
outb(cmd, iobase + REG_CMD);
return 0;
}
static int read_pio(unsigned long iobase, ushort * start, ushort * end)
{
unsigned int loop = MAXLOOP;
ushort *p;
for (p = start; p <= end; p++) {
while (!(inb(iobase + REG_STATUS) & DRQ_ASSERTED)) {
udelay(1L);
if (--loop == 0)
return 1;
}
loop = MAXLOOP;
*p = REG2H(inw(iobase));
}
return 0;
}
static struct pci_dev *get_pci_dev(unsigned long port_base)
{
#if defined(CONFIG_PCI)
unsigned int addr;
struct pci_dev *dev = NULL;
while ((dev = pci_get_class(PCI_CLASS_STORAGE_SCSI << 8, dev))) {
addr = pci_resource_start(dev, 0);
#if defined(DEBUG_PCI_DETECT)
printk("%s: get_pci_dev, bus %d, devfn 0x%x, addr 0x%x.\n",
driver_name, dev->bus->number, dev->devfn, addr);
#endif
/* we are in so much trouble for a pci hotplug system with this driver
* anyway, so doing this at least lets people unload the driver and not
* cause memory problems, but in general this is a bad thing to do (this
* driver needs to be converted to the proper PCI api someday... */
pci_dev_put(dev);
if (addr + PCI_BASE_ADDRESS_0 == port_base)
return dev;
}
#endif /* end CONFIG_PCI */
return NULL;
}
static void enable_pci_ports(void)
{
#if defined(CONFIG_PCI)
struct pci_dev *dev = NULL;
while ((dev = pci_get_class(PCI_CLASS_STORAGE_SCSI << 8, dev))) {
#if defined(DEBUG_PCI_DETECT)
printk("%s: enable_pci_ports, bus %d, devfn 0x%x.\n",
driver_name, dev->bus->number, dev->devfn);
#endif
if (pci_enable_device(dev))
printk
("%s: warning, pci_enable_device failed, bus %d devfn 0x%x.\n",
driver_name, dev->bus->number, dev->devfn);
}
#endif /* end CONFIG_PCI */
}
static int port_detect(unsigned long port_base, unsigned int j,
struct scsi_host_template *tpnt)
{
unsigned char irq, dma_channel, subversion, i, is_pci = 0;
unsigned char protocol_rev;
struct eata_info info;
char *bus_type, dma_name[16];
struct pci_dev *pdev;
/* Allowed DMA channels for ISA (0 indicates reserved) */
unsigned char dma_channel_table[4] = { 5, 6, 7, 0 };
struct Scsi_Host *shost;
struct hostdata *ha;
char name[16];
sprintf(name, "%s%d", driver_name, j);
if (!request_region(port_base, REGION_SIZE, driver_name)) {
#if defined(DEBUG_DETECT)
printk("%s: address 0x%03lx in use, skipping probe.\n", name,
port_base);
#endif
goto fail;
}
spin_lock_irq(&driver_lock);
if (do_dma(port_base, 0, READ_CONFIG_PIO)) {
#if defined(DEBUG_DETECT)
printk("%s: detect, do_dma failed at 0x%03lx.\n", name,
port_base);
#endif
goto freelock;
}
/* Read the info structure */
if (read_pio(port_base, (ushort *) & info, (ushort *) & info.ipad[0])) {
#if defined(DEBUG_DETECT)
printk("%s: detect, read_pio failed at 0x%03lx.\n", name,
port_base);
#endif
goto freelock;
}
info.data_len = DEV2H(info.data_len);
info.sign = DEV2H(info.sign);
info.cp_pad_len = DEV2H16(info.cp_pad_len);
info.cp_len = DEV2H(info.cp_len);
info.sp_len = DEV2H(info.sp_len);
info.scatt_size = DEV2H16(info.scatt_size);
info.queue_size = DEV2H16(info.queue_size);
/* Check the controller "EATA" signature */
if (info.sign != EATA_SIG_BE) {
#if defined(DEBUG_DETECT)
printk("%s: signature 0x%04x discarded.\n", name, info.sign);
#endif
goto freelock;
}
if (info.data_len < EATA_2_0A_SIZE) {
printk
("%s: config structure size (%d bytes) too short, detaching.\n",
name, info.data_len);
goto freelock;
} else if (info.data_len == EATA_2_0A_SIZE)
protocol_rev = 'A';
else if (info.data_len == EATA_2_0B_SIZE)
protocol_rev = 'B';
else
protocol_rev = 'C';
if (protocol_rev != 'A' && info.forcaddr) {
printk("%s: warning, port address has been forced.\n", name);
bus_type = "PCI";
is_pci = 1;
subversion = ESA;
} else if (port_base > MAX_EISA_ADDR
|| (protocol_rev == 'C' && info.pci)) {
bus_type = "PCI";
is_pci = 1;
subversion = ESA;
} else if (port_base >= MIN_EISA_ADDR
|| (protocol_rev == 'C' && info.eisa)) {
bus_type = "EISA";
subversion = ESA;
} else if (protocol_rev == 'C' && !info.eisa && !info.pci) {
bus_type = "ISA";
subversion = ISA;
} else if (port_base > MAX_ISA_ADDR) {
bus_type = "PCI";
is_pci = 1;
subversion = ESA;
} else {
bus_type = "ISA";
subversion = ISA;
}
if (!info.haaval || info.ata) {
printk
("%s: address 0x%03lx, unusable %s board (%d%d), detaching.\n",
name, port_base, bus_type, info.haaval, info.ata);
goto freelock;
}
if (info.drqvld) {
if (subversion == ESA)
printk("%s: warning, weird %s board using DMA.\n", name,
bus_type);
subversion = ISA;
dma_channel = dma_channel_table[3 - info.drqx];
} else {
if (subversion == ISA)
printk("%s: warning, weird %s board not using DMA.\n",
name, bus_type);
subversion = ESA;
dma_channel = NO_DMA;
}
if (!info.dmasup)
printk("%s: warning, DMA protocol support not asserted.\n",
name);
irq = info.irq;
if (subversion == ESA && !info.irq_tr)
printk
("%s: warning, LEVEL triggering is suggested for IRQ %u.\n",
name, irq);
if (is_pci) {
pdev = get_pci_dev(port_base);
if (!pdev)
printk
("%s: warning, failed to get pci_dev structure.\n",
name);
} else
pdev = NULL;
if (pdev && (irq != pdev->irq)) {
printk("%s: IRQ %u mapped to IO-APIC IRQ %u.\n", name, irq,
pdev->irq);
irq = pdev->irq;
}
/* Board detected, allocate its IRQ */
if (request_irq(irq, do_interrupt_handler,
IRQF_DISABLED | ((subversion == ESA) ? IRQF_SHARED : 0),
driver_name, (void *)&sha[j])) {
printk("%s: unable to allocate IRQ %u, detaching.\n", name,
irq);
goto freelock;
}
if (subversion == ISA && request_dma(dma_channel, driver_name)) {
printk("%s: unable to allocate DMA channel %u, detaching.\n",
name, dma_channel);
goto freeirq;
}
#if defined(FORCE_CONFIG)
{
struct eata_config *cf;
dma_addr_t cf_dma_addr;
cf = pci_alloc_consistent(pdev, sizeof(struct eata_config),
&cf_dma_addr);
if (!cf) {
printk
("%s: config, pci_alloc_consistent failed, detaching.\n",
name);
goto freedma;
}
/* Set board configuration */
memset((char *)cf, 0, sizeof(struct eata_config));
cf->len = (ushort) H2DEV16((ushort) 510);
cf->ocena = 1;
if (do_dma(port_base, cf_dma_addr, SET_CONFIG_DMA)) {
printk
("%s: busy timeout sending configuration, detaching.\n",
name);
pci_free_consistent(pdev, sizeof(struct eata_config),
cf, cf_dma_addr);
goto freedma;
}
}
#endif
spin_unlock_irq(&driver_lock);
sh[j] = shost = scsi_register(tpnt, sizeof(struct hostdata));
spin_lock_irq(&driver_lock);
if (shost == NULL) {
printk("%s: unable to register host, detaching.\n", name);
goto freedma;
}
shost->io_port = port_base;
shost->unique_id = port_base;
shost->n_io_port = REGION_SIZE;
shost->dma_channel = dma_channel;
shost->irq = irq;
shost->sg_tablesize = (ushort) info.scatt_size;
shost->this_id = (ushort) info.host_addr[3];
shost->can_queue = (ushort) info.queue_size;
shost->cmd_per_lun = MAX_CMD_PER_LUN;
ha = (struct hostdata *)shost->hostdata;
memset(ha, 0, sizeof(struct hostdata));
ha->subversion = subversion;
ha->protocol_rev = protocol_rev;
ha->is_pci = is_pci;
ha->pdev = pdev;
ha->board_number = j;
if (ha->subversion == ESA)
shost->unchecked_isa_dma = 0;
else {
unsigned long flags;
shost->unchecked_isa_dma = 1;
flags = claim_dma_lock();
disable_dma(dma_channel);
clear_dma_ff(dma_channel);
set_dma_mode(dma_channel, DMA_MODE_CASCADE);
enable_dma(dma_channel);
release_dma_lock(flags);
}
strcpy(ha->board_name, name);
/* DPT PM2012 does not allow to detect sg_tablesize correctly */
if (shost->sg_tablesize > MAX_SGLIST || shost->sg_tablesize < 2) {
printk("%s: detect, wrong n. of SG lists %d, fixed.\n",
ha->board_name, shost->sg_tablesize);
shost->sg_tablesize = MAX_SGLIST;
}
/* DPT PM2012 does not allow to detect can_queue correctly */
if (shost->can_queue > MAX_MAILBOXES || shost->can_queue < 2) {
printk("%s: detect, wrong n. of mbox %d, fixed.\n",
ha->board_name, shost->can_queue);
shost->can_queue = MAX_MAILBOXES;
}
if (protocol_rev != 'A') {
if (info.max_chan > 0 && info.max_chan < MAX_CHANNEL)
shost->max_channel = info.max_chan;
if (info.max_id > 7 && info.max_id < MAX_TARGET)
shost->max_id = info.max_id + 1;
if (info.large_sg && shost->sg_tablesize == MAX_SGLIST)
shost->sg_tablesize = MAX_LARGE_SGLIST;
}
if (protocol_rev == 'C') {
if (info.max_lun > 7 && info.max_lun < MAX_LUN)
shost->max_lun = info.max_lun + 1;
}
if (dma_channel == NO_DMA)
sprintf(dma_name, "%s", "BMST");
else
sprintf(dma_name, "DMA %u", dma_channel);
spin_unlock_irq(&driver_lock);
for (i = 0; i < shost->can_queue; i++)
ha->cp[i].cp_dma_addr = pci_map_single(ha->pdev,
&ha->cp[i],
sizeof(struct mscp),
PCI_DMA_BIDIRECTIONAL);
for (i = 0; i < shost->can_queue; i++) {
size_t sz = shost->sg_tablesize *sizeof(struct sg_list);
gfp_t gfp_mask = (shost->unchecked_isa_dma ? GFP_DMA : 0) | GFP_ATOMIC;
ha->cp[i].sglist = kmalloc(sz, gfp_mask);
if (!ha->cp[i].sglist) {
printk
("%s: kmalloc SGlist failed, mbox %d, detaching.\n",
ha->board_name, i);
goto release;
}
}
if (!(ha->sp_cpu_addr = pci_alloc_consistent(ha->pdev,
sizeof(struct mssp),
&ha->sp_dma_addr))) {
printk("%s: pci_alloc_consistent failed, detaching.\n", ha->board_name);
goto release;
}
if (max_queue_depth > MAX_TAGGED_CMD_PER_LUN)
max_queue_depth = MAX_TAGGED_CMD_PER_LUN;
if (max_queue_depth < MAX_CMD_PER_LUN)
max_queue_depth = MAX_CMD_PER_LUN;
if (tag_mode != TAG_DISABLED && tag_mode != TAG_SIMPLE)
tag_mode = TAG_ORDERED;
if (j == 0) {
printk
("EATA/DMA 2.0x: Copyright (C) 1994-2003 Dario Ballabio.\n");
printk
("%s config options -> tm:%d, lc:%c, mq:%d, rs:%c, et:%c, "
"ip:%c, ep:%c, pp:%c.\n", driver_name, tag_mode,
YESNO(linked_comm), max_queue_depth, YESNO(rev_scan),
YESNO(ext_tran), YESNO(isa_probe), YESNO(eisa_probe),
YESNO(pci_probe));
}
printk("%s: 2.0%c, %s 0x%03lx, IRQ %u, %s, SG %d, MB %d.\n",
ha->board_name, ha->protocol_rev, bus_type,
(unsigned long)shost->io_port, shost->irq, dma_name,
shost->sg_tablesize, shost->can_queue);
if (shost->max_id > 8 || shost->max_lun > 8)
printk
("%s: wide SCSI support enabled, max_id %u, max_lun %u.\n",
ha->board_name, shost->max_id, shost->max_lun);
for (i = 0; i <= shost->max_channel; i++)
printk("%s: SCSI channel %u enabled, host target ID %d.\n",
ha->board_name, i, info.host_addr[3 - i]);
#if defined(DEBUG_DETECT)
printk("%s: Vers. 0x%x, ocs %u, tar %u, trnxfr %u, more %u, SYNC 0x%x, "
"sec. %u, infol %d, cpl %d spl %d.\n", name, info.version,
info.ocsena, info.tarsup, info.trnxfr, info.morsup, info.sync,
info.second, info.data_len, info.cp_len, info.sp_len);
if (protocol_rev == 'B' || protocol_rev == 'C')
printk("%s: isaena %u, forcaddr %u, max_id %u, max_chan %u, "
"large_sg %u, res1 %u.\n", name, info.isaena,
info.forcaddr, info.max_id, info.max_chan, info.large_sg,
info.res1);
if (protocol_rev == 'C')
printk("%s: max_lun %u, m1 %u, idquest %u, pci %u, eisa %u, "
"raidnum %u.\n", name, info.max_lun, info.m1,
info.idquest, info.pci, info.eisa, info.raidnum);
#endif
if (ha->pdev) {
pci_set_master(ha->pdev);
if (pci_set_dma_mask(ha->pdev, DMA_BIT_MASK(32)))
printk("%s: warning, pci_set_dma_mask failed.\n",
ha->board_name);
}
return 1;
freedma:
if (subversion == ISA)
free_dma(dma_channel);
freeirq:
free_irq(irq, &sha[j]);
freelock:
spin_unlock_irq(&driver_lock);
release_region(port_base, REGION_SIZE);
fail:
return 0;
release:
eata2x_release(shost);
return 0;
}
static void internal_setup(char *str, int *ints)
{
int i, argc = ints[0];
char *cur = str, *pc;
if (argc > 0) {
if (argc > MAX_INT_PARAM)
argc = MAX_INT_PARAM;
for (i = 0; i < argc; i++)
io_port[i] = ints[i + 1];
io_port[i] = 0;
setup_done = 1;
}
while (cur && (pc = strchr(cur, ':'))) {
int val = 0, c = *++pc;
if (c == 'n' || c == 'N')
val = 0;
else if (c == 'y' || c == 'Y')
val = 1;
else
val = (int)simple_strtoul(pc, NULL, 0);
if (!strncmp(cur, "lc:", 3))
linked_comm = val;
else if (!strncmp(cur, "tm:", 3))
tag_mode = val;
else if (!strncmp(cur, "tc:", 3))
tag_mode = val;
else if (!strncmp(cur, "mq:", 3))
max_queue_depth = val;
else if (!strncmp(cur, "ls:", 3))
link_statistics = val;
else if (!strncmp(cur, "et:", 3))
ext_tran = val;
else if (!strncmp(cur, "rs:", 3))
rev_scan = val;
else if (!strncmp(cur, "ip:", 3))
isa_probe = val;
else if (!strncmp(cur, "ep:", 3))
eisa_probe = val;
else if (!strncmp(cur, "pp:", 3))
pci_probe = val;
if ((cur = strchr(cur, ',')))
++cur;
}
return;
}
static int option_setup(char *str)
{
int ints[MAX_INT_PARAM];
char *cur = str;
int i = 1;
while (cur && isdigit(*cur) && i < MAX_INT_PARAM) {
ints[i++] = simple_strtoul(cur, NULL, 0);
if ((cur = strchr(cur, ',')) != NULL)
cur++;
}
ints[0] = i - 1;
internal_setup(cur, ints);
return 1;
}
static void add_pci_ports(void)
{
#if defined(CONFIG_PCI)
unsigned int addr, k;
struct pci_dev *dev = NULL;
for (k = 0; k < MAX_PCI; k++) {
if (!(dev = pci_get_class(PCI_CLASS_STORAGE_SCSI << 8, dev)))
break;
if (pci_enable_device(dev)) {
#if defined(DEBUG_PCI_DETECT)
printk
("%s: detect, bus %d, devfn 0x%x, pci_enable_device failed.\n",
driver_name, dev->bus->number, dev->devfn);
#endif
continue;
}
addr = pci_resource_start(dev, 0);
#if defined(DEBUG_PCI_DETECT)
printk("%s: detect, seq. %d, bus %d, devfn 0x%x, addr 0x%x.\n",
driver_name, k, dev->bus->number, dev->devfn, addr);
#endif
/* Order addresses according to rev_scan value */
io_port[MAX_INT_PARAM + (rev_scan ? (MAX_PCI - k) : (1 + k))] =
addr + PCI_BASE_ADDRESS_0;
}
pci_dev_put(dev);
#endif /* end CONFIG_PCI */
}
static int eata2x_detect(struct scsi_host_template *tpnt)
{
unsigned int j = 0, k;
tpnt->proc_name = "eata2x";
if (strlen(boot_options))
option_setup(boot_options);
#if defined(MODULE)
/* io_port could have been modified when loading as a module */
if (io_port[0] != SKIP) {
setup_done = 1;
io_port[MAX_INT_PARAM] = 0;
}
#endif
for (k = MAX_INT_PARAM; io_port[k]; k++)
if (io_port[k] == SKIP)
continue;
else if (io_port[k] <= MAX_ISA_ADDR) {
if (!isa_probe)
io_port[k] = SKIP;
} else if (io_port[k] >= MIN_EISA_ADDR
&& io_port[k] <= MAX_EISA_ADDR) {
if (!eisa_probe)
io_port[k] = SKIP;
}
if (pci_probe) {
if (!setup_done)
add_pci_ports();
else
enable_pci_ports();
}
for (k = 0; io_port[k]; k++) {
if (io_port[k] == SKIP)
continue;
if (j < MAX_BOARDS && port_detect(io_port[k], j, tpnt))
j++;
}
num_boards = j;
return j;
}
static void map_dma(unsigned int i, struct hostdata *ha)
{
unsigned int k, pci_dir;
int count;
struct scatterlist *sg;
struct mscp *cpp;
struct scsi_cmnd *SCpnt;
cpp = &ha->cp[i];
SCpnt = cpp->SCpnt;
pci_dir = SCpnt->sc_data_direction;
if (SCpnt->sense_buffer)
cpp->sense_addr =
H2DEV(pci_map_single(ha->pdev, SCpnt->sense_buffer,
SCSI_SENSE_BUFFERSIZE, PCI_DMA_FROMDEVICE));
cpp->sense_len = SCSI_SENSE_BUFFERSIZE;
if (!scsi_sg_count(SCpnt)) {
cpp->data_len = 0;
return;
}
count = pci_map_sg(ha->pdev, scsi_sglist(SCpnt), scsi_sg_count(SCpnt),
pci_dir);
BUG_ON(!count);
scsi_for_each_sg(SCpnt, sg, count, k) {
cpp->sglist[k].address = H2DEV(sg_dma_address(sg));
cpp->sglist[k].num_bytes = H2DEV(sg_dma_len(sg));
}
cpp->sg = 1;
cpp->data_address = H2DEV(pci_map_single(ha->pdev, cpp->sglist,
scsi_sg_count(SCpnt) *
sizeof(struct sg_list),
pci_dir));
cpp->data_len = H2DEV((scsi_sg_count(SCpnt) * sizeof(struct sg_list)));
}
static void unmap_dma(unsigned int i, struct hostdata *ha)
{
unsigned int pci_dir;
struct mscp *cpp;
struct scsi_cmnd *SCpnt;
cpp = &ha->cp[i];
SCpnt = cpp->SCpnt;
pci_dir = SCpnt->sc_data_direction;
if (DEV2H(cpp->sense_addr))
pci_unmap_single(ha->pdev, DEV2H(cpp->sense_addr),
DEV2H(cpp->sense_len), PCI_DMA_FROMDEVICE);
if (scsi_sg_count(SCpnt))
pci_unmap_sg(ha->pdev, scsi_sglist(SCpnt), scsi_sg_count(SCpnt),
pci_dir);
if (!DEV2H(cpp->data_len))
pci_dir = PCI_DMA_BIDIRECTIONAL;
if (DEV2H(cpp->data_address))
pci_unmap_single(ha->pdev, DEV2H(cpp->data_address),
DEV2H(cpp->data_len), pci_dir);
}
static void sync_dma(unsigned int i, struct hostdata *ha)
{
unsigned int pci_dir;
struct mscp *cpp;
struct scsi_cmnd *SCpnt;
cpp = &ha->cp[i];
SCpnt = cpp->SCpnt;
pci_dir = SCpnt->sc_data_direction;
if (DEV2H(cpp->sense_addr))
pci_dma_sync_single_for_cpu(ha->pdev, DEV2H(cpp->sense_addr),
DEV2H(cpp->sense_len),
PCI_DMA_FROMDEVICE);
if (scsi_sg_count(SCpnt))
pci_dma_sync_sg_for_cpu(ha->pdev, scsi_sglist(SCpnt),
scsi_sg_count(SCpnt), pci_dir);
if (!DEV2H(cpp->data_len))
pci_dir = PCI_DMA_BIDIRECTIONAL;
if (DEV2H(cpp->data_address))
pci_dma_sync_single_for_cpu(ha->pdev,
DEV2H(cpp->data_address),
DEV2H(cpp->data_len), pci_dir);
}
static void scsi_to_dev_dir(unsigned int i, struct hostdata *ha)
{
unsigned int k;
static const unsigned char data_out_cmds[] = {
0x0a, 0x2a, 0x15, 0x55, 0x04, 0x07, 0x18, 0x1d, 0x24, 0x2e,
0x30, 0x31, 0x32, 0x38, 0x39, 0x3a, 0x3b, 0x3d, 0x3f, 0x40,
0x41, 0x4c, 0xaa, 0xae, 0xb0, 0xb1, 0xb2, 0xb6, 0xea, 0x1b, 0x5d
};
static const unsigned char data_none_cmds[] = {
0x01, 0x0b, 0x10, 0x11, 0x13, 0x16, 0x17, 0x19, 0x2b, 0x1e,
0x2c, 0xac, 0x2f, 0xaf, 0x33, 0xb3, 0x35, 0x36, 0x45, 0x47,
0x48, 0x49, 0xa9, 0x4b, 0xa5, 0xa6, 0xb5, 0x00
};
struct mscp *cpp;
struct scsi_cmnd *SCpnt;
cpp = &ha->cp[i];
SCpnt = cpp->SCpnt;
if (SCpnt->sc_data_direction == DMA_FROM_DEVICE) {
cpp->din = 1;
cpp->dout = 0;
return;
} else if (SCpnt->sc_data_direction == DMA_TO_DEVICE) {
cpp->din = 0;
cpp->dout = 1;
return;
} else if (SCpnt->sc_data_direction == DMA_NONE) {
cpp->din = 0;
cpp->dout = 0;
return;
}
if (SCpnt->sc_data_direction != DMA_BIDIRECTIONAL)
panic("%s: qcomm, invalid SCpnt->sc_data_direction.\n",
ha->board_name);
for (k = 0; k < ARRAY_SIZE(data_out_cmds); k++)
if (SCpnt->cmnd[0] == data_out_cmds[k]) {
cpp->dout = 1;
break;
}
if ((cpp->din = !cpp->dout))
for (k = 0; k < ARRAY_SIZE(data_none_cmds); k++)
if (SCpnt->cmnd[0] == data_none_cmds[k]) {
cpp->din = 0;
break;
}
}
static int eata2x_queuecommand_lck(struct scsi_cmnd *SCpnt,
void (*done) (struct scsi_cmnd *))
{
struct Scsi_Host *shost = SCpnt->device->host;
struct hostdata *ha = (struct hostdata *)shost->hostdata;
unsigned int i, k;
struct mscp *cpp;
if (SCpnt->host_scribble)
panic("%s: qcomm, SCpnt %p already active.\n",
ha->board_name, SCpnt);
/* i is the mailbox number, look for the first free mailbox
starting from last_cp_used */
i = ha->last_cp_used + 1;
for (k = 0; k < shost->can_queue; k++, i++) {
if (i >= shost->can_queue)
i = 0;
if (ha->cp_stat[i] == FREE) {
ha->last_cp_used = i;
break;
}
}
if (k == shost->can_queue) {
printk("%s: qcomm, no free mailbox.\n", ha->board_name);
return 1;
}
/* Set pointer to control packet structure */
cpp = &ha->cp[i];
memset(cpp, 0, sizeof(struct mscp) - CP_TAIL_SIZE);
/* Set pointer to status packet structure, Big Endian format */
cpp->sp_dma_addr = H2DEV(ha->sp_dma_addr);
SCpnt->scsi_done = done;
cpp->cpp_index = i;
SCpnt->host_scribble = (unsigned char *)&cpp->cpp_index;
if (do_trace)
scmd_printk(KERN_INFO, SCpnt,
"qcomm, mbox %d.\n", i);
cpp->reqsen = 1;
cpp->dispri = 1;
#if 0
if (SCpnt->device->type == TYPE_TAPE)
cpp->hbaci = 1;
#endif
cpp->one = 1;
cpp->channel = SCpnt->device->channel;
cpp->target = SCpnt->device->id;
cpp->lun = SCpnt->device->lun;
cpp->SCpnt = SCpnt;
memcpy(cpp->cdb, SCpnt->cmnd, SCpnt->cmd_len);
/* Use data transfer direction SCpnt->sc_data_direction */
scsi_to_dev_dir(i, ha);
/* Map DMA buffers and SG list */
map_dma(i, ha);
if (linked_comm && SCpnt->device->queue_depth > 2
&& TLDEV(SCpnt->device->type)) {
ha->cp_stat[i] = READY;
flush_dev(SCpnt->device, blk_rq_pos(SCpnt->request), ha, 0);
return 0;
}
/* Send control packet to the board */
if (do_dma(shost->io_port, cpp->cp_dma_addr, SEND_CP_DMA)) {
unmap_dma(i, ha);
SCpnt->host_scribble = NULL;
scmd_printk(KERN_INFO, SCpnt, "qcomm, adapter busy.\n");
return 1;
}
ha->cp_stat[i] = IN_USE;
return 0;
}
static DEF_SCSI_QCMD(eata2x_queuecommand)
static int eata2x_eh_abort(struct scsi_cmnd *SCarg)
{
struct Scsi_Host *shost = SCarg->device->host;
struct hostdata *ha = (struct hostdata *)shost->hostdata;
unsigned int i;
if (SCarg->host_scribble == NULL) {
scmd_printk(KERN_INFO, SCarg, "abort, cmd inactive.\n");
return SUCCESS;
}
i = *(unsigned int *)SCarg->host_scribble;
scmd_printk(KERN_WARNING, SCarg, "abort, mbox %d.\n", i);
if (i >= shost->can_queue)
panic("%s: abort, invalid SCarg->host_scribble.\n", ha->board_name);
if (wait_on_busy(shost->io_port, MAXLOOP)) {
printk("%s: abort, timeout error.\n", ha->board_name);
return FAILED;
}
if (ha->cp_stat[i] == FREE) {
printk("%s: abort, mbox %d is free.\n", ha->board_name, i);
return SUCCESS;
}
if (ha->cp_stat[i] == IN_USE) {
printk("%s: abort, mbox %d is in use.\n", ha->board_name, i);
if (SCarg != ha->cp[i].SCpnt)
panic("%s: abort, mbox %d, SCarg %p, cp SCpnt %p.\n",
ha->board_name, i, SCarg, ha->cp[i].SCpnt);
if (inb(shost->io_port + REG_AUX_STATUS) & IRQ_ASSERTED)
printk("%s: abort, mbox %d, interrupt pending.\n",
ha->board_name, i);
return FAILED;
}
if (ha->cp_stat[i] == IN_RESET) {
printk("%s: abort, mbox %d is in reset.\n", ha->board_name, i);
return FAILED;
}
if (ha->cp_stat[i] == LOCKED) {
printk("%s: abort, mbox %d is locked.\n", ha->board_name, i);
return SUCCESS;
}
if (ha->cp_stat[i] == READY || ha->cp_stat[i] == ABORTING) {
unmap_dma(i, ha);
SCarg->result = DID_ABORT << 16;
SCarg->host_scribble = NULL;
ha->cp_stat[i] = FREE;
printk("%s, abort, mbox %d ready, DID_ABORT, done.\n",
ha->board_name, i);
SCarg->scsi_done(SCarg);
return SUCCESS;
}
panic("%s: abort, mbox %d, invalid cp_stat.\n", ha->board_name, i);
}
static int eata2x_eh_host_reset(struct scsi_cmnd *SCarg)
{
unsigned int i, time, k, c, limit = 0;
int arg_done = 0;
struct scsi_cmnd *SCpnt;
struct Scsi_Host *shost = SCarg->device->host;
struct hostdata *ha = (struct hostdata *)shost->hostdata;
scmd_printk(KERN_INFO, SCarg, "reset, enter.\n");
spin_lock_irq(shost->host_lock);
if (SCarg->host_scribble == NULL)
printk("%s: reset, inactive.\n", ha->board_name);
if (ha->in_reset) {
printk("%s: reset, exit, already in reset.\n", ha->board_name);
spin_unlock_irq(shost->host_lock);
return FAILED;
}
if (wait_on_busy(shost->io_port, MAXLOOP)) {
printk("%s: reset, exit, timeout error.\n", ha->board_name);
spin_unlock_irq(shost->host_lock);
return FAILED;
}
ha->retries = 0;
for (c = 0; c <= shost->max_channel; c++)
for (k = 0; k < shost->max_id; k++) {
ha->target_redo[k][c] = 1;
ha->target_to[k][c] = 0;
}
for (i = 0; i < shost->can_queue; i++) {
if (ha->cp_stat[i] == FREE)
continue;
if (ha->cp_stat[i] == LOCKED) {
ha->cp_stat[i] = FREE;
printk("%s: reset, locked mbox %d forced free.\n",
ha->board_name, i);
continue;
}
if (!(SCpnt = ha->cp[i].SCpnt))
panic("%s: reset, mbox %d, SCpnt == NULL.\n", ha->board_name, i);
if (ha->cp_stat[i] == READY || ha->cp_stat[i] == ABORTING) {
ha->cp_stat[i] = ABORTING;
printk("%s: reset, mbox %d aborting.\n",
ha->board_name, i);
}
else {
ha->cp_stat[i] = IN_RESET;
printk("%s: reset, mbox %d in reset.\n",
ha->board_name, i);
}
if (SCpnt->host_scribble == NULL)
panic("%s: reset, mbox %d, garbled SCpnt.\n", ha->board_name, i);
if (*(unsigned int *)SCpnt->host_scribble != i)
panic("%s: reset, mbox %d, index mismatch.\n", ha->board_name, i);
if (SCpnt->scsi_done == NULL)
panic("%s: reset, mbox %d, SCpnt->scsi_done == NULL.\n",
ha->board_name, i);
if (SCpnt == SCarg)
arg_done = 1;
}
if (do_dma(shost->io_port, 0, RESET_PIO)) {
printk("%s: reset, cannot reset, timeout error.\n", ha->board_name);
spin_unlock_irq(shost->host_lock);
return FAILED;
}
printk("%s: reset, board reset done, enabling interrupts.\n", ha->board_name);
#if defined(DEBUG_RESET)
do_trace = 1;
#endif
ha->in_reset = 1;
spin_unlock_irq(shost->host_lock);
/* FIXME: use a sleep instead */
time = jiffies;
while ((jiffies - time) < (10 * HZ) && limit++ < 200000)
udelay(100L);
spin_lock_irq(shost->host_lock);
printk("%s: reset, interrupts disabled, loops %d.\n", ha->board_name, limit);
for (i = 0; i < shost->can_queue; i++) {
if (ha->cp_stat[i] == IN_RESET) {
SCpnt = ha->cp[i].SCpnt;
unmap_dma(i, ha);
SCpnt->result = DID_RESET << 16;
SCpnt->host_scribble = NULL;
/* This mailbox is still waiting for its interrupt */
ha->cp_stat[i] = LOCKED;
printk
("%s, reset, mbox %d locked, DID_RESET, done.\n",
ha->board_name, i);
}
else if (ha->cp_stat[i] == ABORTING) {
SCpnt = ha->cp[i].SCpnt;
unmap_dma(i, ha);
SCpnt->result = DID_RESET << 16;
SCpnt->host_scribble = NULL;
/* This mailbox was never queued to the adapter */
ha->cp_stat[i] = FREE;
printk
("%s, reset, mbox %d aborting, DID_RESET, done.\n",
ha->board_name, i);
}
else
/* Any other mailbox has already been set free by interrupt */
continue;
SCpnt->scsi_done(SCpnt);
}
ha->in_reset = 0;
do_trace = 0;
if (arg_done)
printk("%s: reset, exit, done.\n", ha->board_name);
else
printk("%s: reset, exit.\n", ha->board_name);
spin_unlock_irq(shost->host_lock);
return SUCCESS;
}
int eata2x_bios_param(struct scsi_device *sdev, struct block_device *bdev,
sector_t capacity, int *dkinfo)
{
unsigned int size = capacity;
if (ext_tran || (scsicam_bios_param(bdev, capacity, dkinfo) < 0)) {
dkinfo[0] = 255;
dkinfo[1] = 63;
dkinfo[2] = size / (dkinfo[0] * dkinfo[1]);
}
#if defined (DEBUG_GEOMETRY)
printk("%s: bios_param, head=%d, sec=%d, cyl=%d.\n", driver_name,
dkinfo[0], dkinfo[1], dkinfo[2]);
#endif
return 0;
}
static void sort(unsigned long sk[], unsigned int da[], unsigned int n,
unsigned int rev)
{
unsigned int i, j, k, y;
unsigned long x;
for (i = 0; i < n - 1; i++) {
k = i;
for (j = k + 1; j < n; j++)
if (rev) {
if (sk[j] > sk[k])
k = j;
} else {
if (sk[j] < sk[k])
k = j;
}
if (k != i) {
x = sk[k];
sk[k] = sk[i];
sk[i] = x;
y = da[k];
da[k] = da[i];
da[i] = y;
}
}
return;
}
static int reorder(struct hostdata *ha, unsigned long cursec,
unsigned int ihdlr, unsigned int il[], unsigned int n_ready)
{
struct scsi_cmnd *SCpnt;
struct mscp *cpp;
unsigned int k, n;
unsigned int rev = 0, s = 1, r = 1;
unsigned int input_only = 1, overlap = 0;
unsigned long sl[n_ready], pl[n_ready], ll[n_ready];
unsigned long maxsec = 0, minsec = ULONG_MAX, seek = 0, iseek = 0;
unsigned long ioseek = 0;
static unsigned int flushcount = 0, batchcount = 0, sortcount = 0;
static unsigned int readycount = 0, ovlcount = 0, inputcount = 0;
static unsigned int readysorted = 0, revcount = 0;
static unsigned long seeksorted = 0, seeknosort = 0;
if (link_statistics && !(++flushcount % link_statistics))
printk("fc %d bc %d ic %d oc %d rc %d rs %d sc %d re %d"
" av %ldK as %ldK.\n", flushcount, batchcount,
inputcount, ovlcount, readycount, readysorted, sortcount,
revcount, seeknosort / (readycount + 1),
seeksorted / (readycount + 1));
if (n_ready <= 1)
return 0;
for (n = 0; n < n_ready; n++) {
k = il[n];
cpp = &ha->cp[k];
SCpnt = cpp->SCpnt;
if (!cpp->din)
input_only = 0;
if (blk_rq_pos(SCpnt->request) < minsec)
minsec = blk_rq_pos(SCpnt->request);
if (blk_rq_pos(SCpnt->request) > maxsec)
maxsec = blk_rq_pos(SCpnt->request);
sl[n] = blk_rq_pos(SCpnt->request);
ioseek += blk_rq_sectors(SCpnt->request);
if (!n)
continue;
if (sl[n] < sl[n - 1])
s = 0;
if (sl[n] > sl[n - 1])
r = 0;
if (link_statistics) {
if (sl[n] > sl[n - 1])
seek += sl[n] - sl[n - 1];
else
seek += sl[n - 1] - sl[n];
}
}
if (link_statistics) {
if (cursec > sl[0])
seek += cursec - sl[0];
else
seek += sl[0] - cursec;
}
if (cursec > ((maxsec + minsec) / 2))
rev = 1;
if (ioseek > ((maxsec - minsec) / 2))
rev = 0;
if (!((rev && r) || (!rev && s)))
sort(sl, il, n_ready, rev);
if (!input_only)
for (n = 0; n < n_ready; n++) {
k = il[n];
cpp = &ha->cp[k];
SCpnt = cpp->SCpnt;
ll[n] = blk_rq_sectors(SCpnt->request);
pl[n] = SCpnt->serial_number;
if (!n)
continue;
if ((sl[n] == sl[n - 1])
|| (!rev && ((sl[n - 1] + ll[n - 1]) > sl[n]))
|| (rev && ((sl[n] + ll[n]) > sl[n - 1])))
overlap = 1;
}
if (overlap)
sort(pl, il, n_ready, 0);
if (link_statistics) {
if (cursec > sl[0])
iseek = cursec - sl[0];
else
iseek = sl[0] - cursec;
batchcount++;
readycount += n_ready;
seeknosort += seek / 1024;
if (input_only)
inputcount++;
if (overlap) {
ovlcount++;
seeksorted += iseek / 1024;
} else
seeksorted += (iseek + maxsec - minsec) / 1024;
if (rev && !r) {
revcount++;
readysorted += n_ready;
}
if (!rev && !s) {
sortcount++;
readysorted += n_ready;
}
}
#if defined(DEBUG_LINKED_COMMANDS)
if (link_statistics && (overlap || !(flushcount % link_statistics)))
for (n = 0; n < n_ready; n++) {
k = il[n];
cpp = &ha->cp[k];
SCpnt = cpp->SCpnt;
scmd_printk(KERN_INFO, SCpnt,
"%s mb %d fc %d nr %d sec %ld ns %u"
" cur %ld s:%c r:%c rev:%c in:%c ov:%c xd %d.\n",
(ihdlr ? "ihdlr" : "qcomm"),
k, flushcount,
n_ready, blk_rq_pos(SCpnt->request),
blk_rq_sectors(SCpnt->request), cursec, YESNO(s),
YESNO(r), YESNO(rev), YESNO(input_only),
YESNO(overlap), cpp->din);
}
#endif
return overlap;
}
static void flush_dev(struct scsi_device *dev, unsigned long cursec,
struct hostdata *ha, unsigned int ihdlr)
{
struct scsi_cmnd *SCpnt;
struct mscp *cpp;
unsigned int k, n, n_ready = 0, il[MAX_MAILBOXES];
for (k = 0; k < dev->host->can_queue; k++) {
if (ha->cp_stat[k] != READY && ha->cp_stat[k] != IN_USE)
continue;
cpp = &ha->cp[k];
SCpnt = cpp->SCpnt;
if (SCpnt->device != dev)
continue;
if (ha->cp_stat[k] == IN_USE)
return;
il[n_ready++] = k;
}
if (reorder(ha, cursec, ihdlr, il, n_ready))
n_ready = 1;
for (n = 0; n < n_ready; n++) {
k = il[n];
cpp = &ha->cp[k];
SCpnt = cpp->SCpnt;
if (do_dma(dev->host->io_port, cpp->cp_dma_addr, SEND_CP_DMA)) {
scmd_printk(KERN_INFO, SCpnt,
"%s, mbox %d, adapter"
" busy, will abort.\n",
(ihdlr ? "ihdlr" : "qcomm"),
k);
ha->cp_stat[k] = ABORTING;
continue;
}
ha->cp_stat[k] = IN_USE;
}
}
static irqreturn_t ihdlr(struct Scsi_Host *shost)
{
struct scsi_cmnd *SCpnt;
unsigned int i, k, c, status, tstatus, reg;
struct mssp *spp;
struct mscp *cpp;
struct hostdata *ha = (struct hostdata *)shost->hostdata;
int irq = shost->irq;
/* Check if this board need to be serviced */
if (!(inb(shost->io_port + REG_AUX_STATUS) & IRQ_ASSERTED))
goto none;
ha->iocount++;
if (do_trace)
printk("%s: ihdlr, enter, irq %d, count %d.\n", ha->board_name, irq,
ha->iocount);
/* Check if this board is still busy */
if (wait_on_busy(shost->io_port, 20 * MAXLOOP)) {
reg = inb(shost->io_port + REG_STATUS);
printk
("%s: ihdlr, busy timeout error, irq %d, reg 0x%x, count %d.\n",
ha->board_name, irq, reg, ha->iocount);
goto none;
}
spp = &ha->sp;
/* Make a local copy just before clearing the interrupt indication */
memcpy(spp, ha->sp_cpu_addr, sizeof(struct mssp));
/* Clear the completion flag and cp pointer on the dynamic copy of sp */
memset(ha->sp_cpu_addr, 0, sizeof(struct mssp));
/* Read the status register to clear the interrupt indication */
reg = inb(shost->io_port + REG_STATUS);
#if defined (DEBUG_INTERRUPT)
{
unsigned char *bytesp;
int cnt;
bytesp = (unsigned char *)spp;
if (ha->iocount < 200) {
printk("sp[] =");
for (cnt = 0; cnt < 15; cnt++)
printk(" 0x%x", bytesp[cnt]);
printk("\n");
}
}
#endif
/* Reject any sp with supspect data */
if (spp->eoc == 0 && ha->iocount > 1)
printk
("%s: ihdlr, spp->eoc == 0, irq %d, reg 0x%x, count %d.\n",
ha->board_name, irq, reg, ha->iocount);
if (spp->cpp_index < 0 || spp->cpp_index >= shost->can_queue)
printk
("%s: ihdlr, bad spp->cpp_index %d, irq %d, reg 0x%x, count %d.\n",
ha->board_name, spp->cpp_index, irq, reg, ha->iocount);
if (spp->eoc == 0 || spp->cpp_index < 0
|| spp->cpp_index >= shost->can_queue)
goto handled;
/* Find the mailbox to be serviced on this board */
i = spp->cpp_index;
cpp = &(ha->cp[i]);
#if defined(DEBUG_GENERATE_ABORTS)
if ((ha->iocount > 500) && ((ha->iocount % 500) < 3))
goto handled;
#endif
if (ha->cp_stat[i] == IGNORE) {
ha->cp_stat[i] = FREE;
goto handled;
} else if (ha->cp_stat[i] == LOCKED) {
ha->cp_stat[i] = FREE;
printk("%s: ihdlr, mbox %d unlocked, count %d.\n", ha->board_name, i,
ha->iocount);
goto handled;
} else if (ha->cp_stat[i] == FREE) {
printk("%s: ihdlr, mbox %d is free, count %d.\n", ha->board_name, i,
ha->iocount);
goto handled;
} else if (ha->cp_stat[i] == IN_RESET)
printk("%s: ihdlr, mbox %d is in reset.\n", ha->board_name, i);
else if (ha->cp_stat[i] != IN_USE)
panic("%s: ihdlr, mbox %d, invalid cp_stat: %d.\n",
ha->board_name, i, ha->cp_stat[i]);
ha->cp_stat[i] = FREE;
SCpnt = cpp->SCpnt;
if (SCpnt == NULL)
panic("%s: ihdlr, mbox %d, SCpnt == NULL.\n", ha->board_name, i);
if (SCpnt->host_scribble == NULL)
panic("%s: ihdlr, mbox %d, SCpnt %p garbled.\n", ha->board_name,
i, SCpnt);
if (*(unsigned int *)SCpnt->host_scribble != i)
panic("%s: ihdlr, mbox %d, index mismatch %d.\n",
ha->board_name, i,
*(unsigned int *)SCpnt->host_scribble);
sync_dma(i, ha);
if (linked_comm && SCpnt->device->queue_depth > 2
&& TLDEV(SCpnt->device->type))
flush_dev(SCpnt->device, blk_rq_pos(SCpnt->request), ha, 1);
tstatus = status_byte(spp->target_status);
#if defined(DEBUG_GENERATE_ERRORS)
if ((ha->iocount > 500) && ((ha->iocount % 200) < 2))
spp->adapter_status = 0x01;
#endif
switch (spp->adapter_status) {
case ASOK: /* status OK */
/* Forces a reset if a disk drive keeps returning BUSY */
if (tstatus == BUSY && SCpnt->device->type != TYPE_TAPE)
status = DID_ERROR << 16;
/* If there was a bus reset, redo operation on each target */
else if (tstatus != GOOD && SCpnt->device->type == TYPE_DISK
&& ha->target_redo[SCpnt->device->id][SCpnt->
device->
channel])
status = DID_BUS_BUSY << 16;
/* Works around a flaw in scsi.c */
else if (tstatus == CHECK_CONDITION
&& SCpnt->device->type == TYPE_DISK
&& (SCpnt->sense_buffer[2] & 0xf) == RECOVERED_ERROR)
status = DID_BUS_BUSY << 16;
else
status = DID_OK << 16;
if (tstatus == GOOD)
ha->target_redo[SCpnt->device->id][SCpnt->device->
channel] = 0;
if (spp->target_status && SCpnt->device->type == TYPE_DISK &&
(!(tstatus == CHECK_CONDITION && ha->iocount <= 1000 &&
(SCpnt->sense_buffer[2] & 0xf) == NOT_READY)))
printk("%s: ihdlr, target %d.%d:%d, "
"target_status 0x%x, sense key 0x%x.\n",
ha->board_name,
SCpnt->device->channel, SCpnt->device->id,
SCpnt->device->lun,
spp->target_status, SCpnt->sense_buffer[2]);
ha->target_to[SCpnt->device->id][SCpnt->device->channel] = 0;
if (ha->last_retried_pid == SCpnt->serial_number)
ha->retries = 0;
break;
case ASST: /* Selection Time Out */
case 0x02: /* Command Time Out */
if (ha->target_to[SCpnt->device->id][SCpnt->device->channel] > 1)
status = DID_ERROR << 16;
else {
status = DID_TIME_OUT << 16;
ha->target_to[SCpnt->device->id][SCpnt->device->
channel]++;
}
break;
/* Perform a limited number of internal retries */
case 0x03: /* SCSI Bus Reset Received */
case 0x04: /* Initial Controller Power-up */
for (c = 0; c <= shost->max_channel; c++)
for (k = 0; k < shost->max_id; k++)
ha->target_redo[k][c] = 1;
if (SCpnt->device->type != TYPE_TAPE
&& ha->retries < MAX_INTERNAL_RETRIES) {
#if defined(DID_SOFT_ERROR)
status = DID_SOFT_ERROR << 16;
#else
status = DID_BUS_BUSY << 16;
#endif
ha->retries++;
ha->last_retried_pid = SCpnt->serial_number;
} else
status = DID_ERROR << 16;
break;
case 0x05: /* Unexpected Bus Phase */
case 0x06: /* Unexpected Bus Free */
case 0x07: /* Bus Parity Error */
case 0x08: /* SCSI Hung */
case 0x09: /* Unexpected Message Reject */
case 0x0a: /* SCSI Bus Reset Stuck */
case 0x0b: /* Auto Request-Sense Failed */
case 0x0c: /* Controller Ram Parity Error */
default:
status = DID_ERROR << 16;
break;
}
SCpnt->result = status | spp->target_status;
#if defined(DEBUG_INTERRUPT)
if (SCpnt->result || do_trace)
#else
if ((spp->adapter_status != ASOK && ha->iocount > 1000) ||
(spp->adapter_status != ASOK &&
spp->adapter_status != ASST && ha->iocount <= 1000) ||
do_trace || msg_byte(spp->target_status))
#endif
scmd_printk(KERN_INFO, SCpnt, "ihdlr, mbox %2d, err 0x%x:%x,"
" reg 0x%x, count %d.\n",
i, spp->adapter_status, spp->target_status,
reg, ha->iocount);
unmap_dma(i, ha);
/* Set the command state to inactive */
SCpnt->host_scribble = NULL;
SCpnt->scsi_done(SCpnt);
if (do_trace)
printk("%s: ihdlr, exit, irq %d, count %d.\n", ha->board_name,
irq, ha->iocount);
handled:
return IRQ_HANDLED;
none:
return IRQ_NONE;
}
static irqreturn_t do_interrupt_handler(int dummy, void *shap)
{
struct Scsi_Host *shost;
unsigned int j;
unsigned long spin_flags;
irqreturn_t ret;
/* Check if the interrupt must be processed by this handler */
if ((j = (unsigned int)((char *)shap - sha)) >= num_boards)
return IRQ_NONE;
shost = sh[j];
spin_lock_irqsave(shost->host_lock, spin_flags);
ret = ihdlr(shost);
spin_unlock_irqrestore(shost->host_lock, spin_flags);
return ret;
}
static int eata2x_release(struct Scsi_Host *shost)
{
struct hostdata *ha = (struct hostdata *)shost->hostdata;
unsigned int i;
for (i = 0; i < shost->can_queue; i++)
kfree((&ha->cp[i])->sglist);
for (i = 0; i < shost->can_queue; i++)
pci_unmap_single(ha->pdev, ha->cp[i].cp_dma_addr,
sizeof(struct mscp), PCI_DMA_BIDIRECTIONAL);
if (ha->sp_cpu_addr)
pci_free_consistent(ha->pdev, sizeof(struct mssp),
ha->sp_cpu_addr, ha->sp_dma_addr);
free_irq(shost->irq, &sha[ha->board_number]);
if (shost->dma_channel != NO_DMA)
free_dma(shost->dma_channel);
release_region(shost->io_port, shost->n_io_port);
scsi_unregister(shost);
return 0;
}
#include "scsi_module.c"
#ifndef MODULE
__setup("eata=", option_setup);
#endif /* end MODULE */
| gpl-2.0 |
JustAkan/jolla-kernel_bullhead | arch/powerpc/platforms/cell/beat_iommu.c | 10994 | 3084 | /*
* Support for IOMMU on Celleb platform.
*
* (C) Copyright 2006-2007 TOSHIBA CORPORATION
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/dma-mapping.h>
#include <linux/pci.h>
#include <linux/of_platform.h>
#include <asm/machdep.h>
#include "beat_wrapper.h"
#define DMA_FLAGS 0xf800000000000000UL /* r/w permitted, coherency required,
strongest order */
static int __init find_dma_window(u64 *io_space_id, u64 *ioid,
u64 *base, u64 *size, u64 *io_page_size)
{
struct device_node *dn;
const unsigned long *dma_window;
for_each_node_by_type(dn, "ioif") {
dma_window = of_get_property(dn, "toshiba,dma-window", NULL);
if (dma_window) {
*io_space_id = (dma_window[0] >> 32) & 0xffffffffUL;
*ioid = dma_window[0] & 0x7ffUL;
*base = dma_window[1];
*size = dma_window[2];
*io_page_size = 1 << dma_window[3];
of_node_put(dn);
return 1;
}
}
return 0;
}
static unsigned long celleb_dma_direct_offset;
static void __init celleb_init_direct_mapping(void)
{
u64 lpar_addr, io_addr;
u64 io_space_id, ioid, dma_base, dma_size, io_page_size;
if (!find_dma_window(&io_space_id, &ioid, &dma_base, &dma_size,
&io_page_size)) {
pr_info("No dma window found !\n");
return;
}
for (lpar_addr = 0; lpar_addr < dma_size; lpar_addr += io_page_size) {
io_addr = lpar_addr + dma_base;
(void)beat_put_iopte(io_space_id, io_addr, lpar_addr,
ioid, DMA_FLAGS);
}
celleb_dma_direct_offset = dma_base;
}
static void celleb_dma_dev_setup(struct device *dev)
{
set_dma_ops(dev, &dma_direct_ops);
set_dma_offset(dev, celleb_dma_direct_offset);
}
static void celleb_pci_dma_dev_setup(struct pci_dev *pdev)
{
celleb_dma_dev_setup(&pdev->dev);
}
static int celleb_of_bus_notify(struct notifier_block *nb,
unsigned long action, void *data)
{
struct device *dev = data;
/* We are only intereted in device addition */
if (action != BUS_NOTIFY_ADD_DEVICE)
return 0;
celleb_dma_dev_setup(dev);
return 0;
}
static struct notifier_block celleb_of_bus_notifier = {
.notifier_call = celleb_of_bus_notify
};
static int __init celleb_init_iommu(void)
{
celleb_init_direct_mapping();
ppc_md.pci_dma_dev_setup = celleb_pci_dma_dev_setup;
bus_register_notifier(&platform_bus_type, &celleb_of_bus_notifier);
return 0;
}
machine_arch_initcall(celleb_beat, celleb_init_iommu);
| gpl-2.0 |
aditisstillalive/android_kernel_lge_hammerhead | drivers/xen/xencomm.c | 11506 | 5560 | /*
* 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
*
* Copyright (C) IBM Corp. 2006
*
* Authors: Hollis Blanchard <hollisb@us.ibm.com>
*/
#include <linux/mm.h>
#include <linux/slab.h>
#include <asm/page.h>
#include <xen/xencomm.h>
#include <xen/interface/xen.h>
#include <asm/xen/xencomm.h> /* for xencomm_is_phys_contiguous() */
static int xencomm_init(struct xencomm_desc *desc,
void *buffer, unsigned long bytes)
{
unsigned long recorded = 0;
int i = 0;
while ((recorded < bytes) && (i < desc->nr_addrs)) {
unsigned long vaddr = (unsigned long)buffer + recorded;
unsigned long paddr;
int offset;
int chunksz;
offset = vaddr % PAGE_SIZE; /* handle partial pages */
chunksz = min(PAGE_SIZE - offset, bytes - recorded);
paddr = xencomm_vtop(vaddr);
if (paddr == ~0UL) {
printk(KERN_DEBUG "%s: couldn't translate vaddr %lx\n",
__func__, vaddr);
return -EINVAL;
}
desc->address[i++] = paddr;
recorded += chunksz;
}
if (recorded < bytes) {
printk(KERN_DEBUG
"%s: could only translate %ld of %ld bytes\n",
__func__, recorded, bytes);
return -ENOSPC;
}
/* mark remaining addresses invalid (just for safety) */
while (i < desc->nr_addrs)
desc->address[i++] = XENCOMM_INVALID;
desc->magic = XENCOMM_MAGIC;
return 0;
}
static struct xencomm_desc *xencomm_alloc(gfp_t gfp_mask,
void *buffer, unsigned long bytes)
{
struct xencomm_desc *desc;
unsigned long buffer_ulong = (unsigned long)buffer;
unsigned long start = buffer_ulong & PAGE_MASK;
unsigned long end = (buffer_ulong + bytes) | ~PAGE_MASK;
unsigned long nr_addrs = (end - start + 1) >> PAGE_SHIFT;
unsigned long size = sizeof(*desc) +
sizeof(desc->address[0]) * nr_addrs;
/*
* slab allocator returns at least sizeof(void*) aligned pointer.
* When sizeof(*desc) > sizeof(void*), struct xencomm_desc might
* cross page boundary.
*/
if (sizeof(*desc) > sizeof(void *)) {
unsigned long order = get_order(size);
desc = (struct xencomm_desc *)__get_free_pages(gfp_mask,
order);
if (desc == NULL)
return NULL;
desc->nr_addrs =
((PAGE_SIZE << order) - sizeof(struct xencomm_desc)) /
sizeof(*desc->address);
} else {
desc = kmalloc(size, gfp_mask);
if (desc == NULL)
return NULL;
desc->nr_addrs = nr_addrs;
}
return desc;
}
void xencomm_free(struct xencomm_handle *desc)
{
if (desc && !((ulong)desc & XENCOMM_INLINE_FLAG)) {
struct xencomm_desc *desc__ = (struct xencomm_desc *)desc;
if (sizeof(*desc__) > sizeof(void *)) {
unsigned long size = sizeof(*desc__) +
sizeof(desc__->address[0]) * desc__->nr_addrs;
unsigned long order = get_order(size);
free_pages((unsigned long)__va(desc), order);
} else
kfree(__va(desc));
}
}
static int xencomm_create(void *buffer, unsigned long bytes,
struct xencomm_desc **ret, gfp_t gfp_mask)
{
struct xencomm_desc *desc;
int rc;
pr_debug("%s: %p[%ld]\n", __func__, buffer, bytes);
if (bytes == 0) {
/* don't create a descriptor; Xen recognizes NULL. */
BUG_ON(buffer != NULL);
*ret = NULL;
return 0;
}
BUG_ON(buffer == NULL); /* 'bytes' is non-zero */
desc = xencomm_alloc(gfp_mask, buffer, bytes);
if (!desc) {
printk(KERN_DEBUG "%s failure\n", "xencomm_alloc");
return -ENOMEM;
}
rc = xencomm_init(desc, buffer, bytes);
if (rc) {
printk(KERN_DEBUG "%s failure: %d\n", "xencomm_init", rc);
xencomm_free((struct xencomm_handle *)__pa(desc));
return rc;
}
*ret = desc;
return 0;
}
static struct xencomm_handle *xencomm_create_inline(void *ptr)
{
unsigned long paddr;
BUG_ON(!xencomm_is_phys_contiguous((unsigned long)ptr));
paddr = (unsigned long)xencomm_pa(ptr);
BUG_ON(paddr & XENCOMM_INLINE_FLAG);
return (struct xencomm_handle *)(paddr | XENCOMM_INLINE_FLAG);
}
/* "mini" routine, for stack-based communications: */
static int xencomm_create_mini(void *buffer,
unsigned long bytes, struct xencomm_mini *xc_desc,
struct xencomm_desc **ret)
{
int rc = 0;
struct xencomm_desc *desc;
BUG_ON(((unsigned long)xc_desc) % sizeof(*xc_desc) != 0);
desc = (void *)xc_desc;
desc->nr_addrs = XENCOMM_MINI_ADDRS;
rc = xencomm_init(desc, buffer, bytes);
if (!rc)
*ret = desc;
return rc;
}
struct xencomm_handle *xencomm_map(void *ptr, unsigned long bytes)
{
int rc;
struct xencomm_desc *desc;
if (xencomm_is_phys_contiguous((unsigned long)ptr))
return xencomm_create_inline(ptr);
rc = xencomm_create(ptr, bytes, &desc, GFP_KERNEL);
if (rc || desc == NULL)
return NULL;
return xencomm_pa(desc);
}
struct xencomm_handle *__xencomm_map_no_alloc(void *ptr, unsigned long bytes,
struct xencomm_mini *xc_desc)
{
int rc;
struct xencomm_desc *desc = NULL;
if (xencomm_is_phys_contiguous((unsigned long)ptr))
return xencomm_create_inline(ptr);
rc = xencomm_create_mini(ptr, bytes, xc_desc,
&desc);
if (rc)
return NULL;
return xencomm_pa(desc);
}
| gpl-2.0 |
AccentureMobilityServices/kernel | arch/x86/boot/video-vesa.c | 12274 | 6833 | /* -*- linux-c -*- ------------------------------------------------------- *
*
* Copyright (C) 1991, 1992 Linus Torvalds
* Copyright 2007 rPath, Inc. - All Rights Reserved
* Copyright 2009 Intel Corporation; author H. Peter Anvin
*
* This file is part of the Linux kernel, and is made available under
* the terms of the GNU General Public License version 2.
*
* ----------------------------------------------------------------------- */
/*
* VESA text modes
*/
#include "boot.h"
#include "video.h"
#include "vesa.h"
/* VESA information */
static struct vesa_general_info vginfo;
static struct vesa_mode_info vminfo;
static __videocard video_vesa;
#ifndef _WAKEUP
static void vesa_store_mode_params_graphics(void);
#else /* _WAKEUP */
static inline void vesa_store_mode_params_graphics(void) {}
#endif /* _WAKEUP */
static int vesa_probe(void)
{
struct biosregs ireg, oreg;
u16 mode;
addr_t mode_ptr;
struct mode_info *mi;
int nmodes = 0;
video_vesa.modes = GET_HEAP(struct mode_info, 0);
initregs(&ireg);
ireg.ax = 0x4f00;
ireg.di = (size_t)&vginfo;
intcall(0x10, &ireg, &oreg);
if (oreg.ax != 0x004f ||
vginfo.signature != VESA_MAGIC ||
vginfo.version < 0x0102)
return 0; /* Not present */
set_fs(vginfo.video_mode_ptr.seg);
mode_ptr = vginfo.video_mode_ptr.off;
while ((mode = rdfs16(mode_ptr)) != 0xffff) {
mode_ptr += 2;
if (!heap_free(sizeof(struct mode_info)))
break; /* Heap full, can't save mode info */
if (mode & ~0x1ff)
continue;
memset(&vminfo, 0, sizeof vminfo); /* Just in case... */
ireg.ax = 0x4f01;
ireg.cx = mode;
ireg.di = (size_t)&vminfo;
intcall(0x10, &ireg, &oreg);
if (oreg.ax != 0x004f)
continue;
if ((vminfo.mode_attr & 0x15) == 0x05) {
/* Text Mode, TTY BIOS supported,
supported by hardware */
mi = GET_HEAP(struct mode_info, 1);
mi->mode = mode + VIDEO_FIRST_VESA;
mi->depth = 0; /* text */
mi->x = vminfo.h_res;
mi->y = vminfo.v_res;
nmodes++;
} else if ((vminfo.mode_attr & 0x99) == 0x99 &&
(vminfo.memory_layout == 4 ||
vminfo.memory_layout == 6) &&
vminfo.memory_planes == 1) {
#ifdef CONFIG_FB_BOOT_VESA_SUPPORT
/* Graphics mode, color, linear frame buffer
supported. Only register the mode if
if framebuffer is configured, however,
otherwise the user will be left without a screen. */
mi = GET_HEAP(struct mode_info, 1);
mi->mode = mode + VIDEO_FIRST_VESA;
mi->depth = vminfo.bpp;
mi->x = vminfo.h_res;
mi->y = vminfo.v_res;
nmodes++;
#endif
}
}
return nmodes;
}
static int vesa_set_mode(struct mode_info *mode)
{
struct biosregs ireg, oreg;
int is_graphic;
u16 vesa_mode = mode->mode - VIDEO_FIRST_VESA;
memset(&vminfo, 0, sizeof vminfo); /* Just in case... */
initregs(&ireg);
ireg.ax = 0x4f01;
ireg.cx = vesa_mode;
ireg.di = (size_t)&vminfo;
intcall(0x10, &ireg, &oreg);
if (oreg.ax != 0x004f)
return -1;
if ((vminfo.mode_attr & 0x15) == 0x05) {
/* It's a supported text mode */
is_graphic = 0;
#ifdef CONFIG_FB_BOOT_VESA_SUPPORT
} else if ((vminfo.mode_attr & 0x99) == 0x99) {
/* It's a graphics mode with linear frame buffer */
is_graphic = 1;
vesa_mode |= 0x4000; /* Request linear frame buffer */
#endif
} else {
return -1; /* Invalid mode */
}
initregs(&ireg);
ireg.ax = 0x4f02;
ireg.bx = vesa_mode;
intcall(0x10, &ireg, &oreg);
if (oreg.ax != 0x004f)
return -1;
graphic_mode = is_graphic;
if (!is_graphic) {
/* Text mode */
force_x = mode->x;
force_y = mode->y;
do_restore = 1;
} else {
/* Graphics mode */
vesa_store_mode_params_graphics();
}
return 0;
}
#ifndef _WAKEUP
/* Switch DAC to 8-bit mode */
static void vesa_dac_set_8bits(void)
{
struct biosregs ireg, oreg;
u8 dac_size = 6;
/* If possible, switch the DAC to 8-bit mode */
if (vginfo.capabilities & 1) {
initregs(&ireg);
ireg.ax = 0x4f08;
ireg.bh = 0x08;
intcall(0x10, &ireg, &oreg);
if (oreg.ax == 0x004f)
dac_size = oreg.bh;
}
/* Set the color sizes to the DAC size, and offsets to 0 */
boot_params.screen_info.red_size = dac_size;
boot_params.screen_info.green_size = dac_size;
boot_params.screen_info.blue_size = dac_size;
boot_params.screen_info.rsvd_size = dac_size;
boot_params.screen_info.red_pos = 0;
boot_params.screen_info.green_pos = 0;
boot_params.screen_info.blue_pos = 0;
boot_params.screen_info.rsvd_pos = 0;
}
/* Save the VESA protected mode info */
static void vesa_store_pm_info(void)
{
struct biosregs ireg, oreg;
initregs(&ireg);
ireg.ax = 0x4f0a;
intcall(0x10, &ireg, &oreg);
if (oreg.ax != 0x004f)
return;
boot_params.screen_info.vesapm_seg = oreg.es;
boot_params.screen_info.vesapm_off = oreg.di;
}
/*
* Save video mode parameters for graphics mode
*/
static void vesa_store_mode_params_graphics(void)
{
/* Tell the kernel we're in VESA graphics mode */
boot_params.screen_info.orig_video_isVGA = VIDEO_TYPE_VLFB;
/* Mode parameters */
boot_params.screen_info.vesa_attributes = vminfo.mode_attr;
boot_params.screen_info.lfb_linelength = vminfo.logical_scan;
boot_params.screen_info.lfb_width = vminfo.h_res;
boot_params.screen_info.lfb_height = vminfo.v_res;
boot_params.screen_info.lfb_depth = vminfo.bpp;
boot_params.screen_info.pages = vminfo.image_planes;
boot_params.screen_info.lfb_base = vminfo.lfb_ptr;
memcpy(&boot_params.screen_info.red_size,
&vminfo.rmask, 8);
/* General parameters */
boot_params.screen_info.lfb_size = vginfo.total_memory;
if (vminfo.bpp <= 8)
vesa_dac_set_8bits();
vesa_store_pm_info();
}
/*
* Save EDID information for the kernel; this is invoked, separately,
* after mode-setting.
*/
void vesa_store_edid(void)
{
#ifdef CONFIG_FIRMWARE_EDID
struct biosregs ireg, oreg;
/* Apparently used as a nonsense token... */
memset(&boot_params.edid_info, 0x13, sizeof boot_params.edid_info);
if (vginfo.version < 0x0200)
return; /* EDID requires VBE 2.0+ */
initregs(&ireg);
ireg.ax = 0x4f15; /* VBE DDC */
/* ireg.bx = 0x0000; */ /* Report DDC capabilities */
/* ireg.cx = 0; */ /* Controller 0 */
ireg.es = 0; /* ES:DI must be 0 by spec */
intcall(0x10, &ireg, &oreg);
if (oreg.ax != 0x004f)
return; /* No EDID */
/* BH = time in seconds to transfer EDD information */
/* BL = DDC level supported */
ireg.ax = 0x4f15; /* VBE DDC */
ireg.bx = 0x0001; /* Read EDID */
/* ireg.cx = 0; */ /* Controller 0 */
/* ireg.dx = 0; */ /* EDID block number */
ireg.es = ds();
ireg.di =(size_t)&boot_params.edid_info; /* (ES:)Pointer to block */
intcall(0x10, &ireg, &oreg);
#endif /* CONFIG_FIRMWARE_EDID */
}
#endif /* not _WAKEUP */
static __videocard video_vesa =
{
.card_name = "VESA",
.probe = vesa_probe,
.set_mode = vesa_set_mode,
.xmode_first = VIDEO_FIRST_VESA,
.xmode_n = 0x200,
};
| gpl-2.0 |
joeduong/bideas-openrex-linux-3.14 | drivers/net/wireless/ath/wcn36xx/smd.c | 243 | 59455 | /*
* Copyright (c) 2013 Eugene Krasnikov <k.eugene.e@gmail.com>
*
* 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.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/etherdevice.h>
#include <linux/firmware.h>
#include <linux/bitops.h>
#include "smd.h"
static int put_cfg_tlv_u32(struct wcn36xx *wcn, size_t *len, u32 id, u32 value)
{
struct wcn36xx_hal_cfg *entry;
u32 *val;
if (*len + sizeof(*entry) + sizeof(u32) >= WCN36XX_HAL_BUF_SIZE) {
wcn36xx_err("Not enough room for TLV entry\n");
return -ENOMEM;
}
entry = (struct wcn36xx_hal_cfg *) (wcn->hal_buf + *len);
entry->id = id;
entry->len = sizeof(u32);
entry->pad_bytes = 0;
entry->reserve = 0;
val = (u32 *) (entry + 1);
*val = value;
*len += sizeof(*entry) + sizeof(u32);
return 0;
}
static void wcn36xx_smd_set_bss_nw_type(struct wcn36xx *wcn,
struct ieee80211_sta *sta,
struct wcn36xx_hal_config_bss_params *bss_params)
{
if (IEEE80211_BAND_5GHZ == WCN36XX_BAND(wcn))
bss_params->nw_type = WCN36XX_HAL_11A_NW_TYPE;
else if (sta && sta->ht_cap.ht_supported)
bss_params->nw_type = WCN36XX_HAL_11N_NW_TYPE;
else if (sta && (sta->supp_rates[IEEE80211_BAND_2GHZ] & 0x7f))
bss_params->nw_type = WCN36XX_HAL_11G_NW_TYPE;
else
bss_params->nw_type = WCN36XX_HAL_11B_NW_TYPE;
}
static inline u8 is_cap_supported(unsigned long caps, unsigned long flag)
{
return caps & flag ? 1 : 0;
}
static void wcn36xx_smd_set_bss_ht_params(struct ieee80211_vif *vif,
struct ieee80211_sta *sta,
struct wcn36xx_hal_config_bss_params *bss_params)
{
if (sta && sta->ht_cap.ht_supported) {
unsigned long caps = sta->ht_cap.cap;
bss_params->ht = sta->ht_cap.ht_supported;
bss_params->tx_channel_width_set = is_cap_supported(caps,
IEEE80211_HT_CAP_SUP_WIDTH_20_40);
bss_params->lsig_tx_op_protection_full_support =
is_cap_supported(caps,
IEEE80211_HT_CAP_LSIG_TXOP_PROT);
bss_params->ht_oper_mode = vif->bss_conf.ht_operation_mode;
bss_params->lln_non_gf_coexist =
!!(vif->bss_conf.ht_operation_mode &
IEEE80211_HT_OP_MODE_NON_GF_STA_PRSNT);
/* IEEE80211_HT_STBC_PARAM_DUAL_CTS_PROT */
bss_params->dual_cts_protection = 0;
/* IEEE80211_HT_OP_MODE_PROTECTION_20MHZ */
bss_params->ht20_coexist = 0;
}
}
static void wcn36xx_smd_set_sta_ht_params(struct ieee80211_sta *sta,
struct wcn36xx_hal_config_sta_params *sta_params)
{
if (sta->ht_cap.ht_supported) {
unsigned long caps = sta->ht_cap.cap;
sta_params->ht_capable = sta->ht_cap.ht_supported;
sta_params->tx_channel_width_set = is_cap_supported(caps,
IEEE80211_HT_CAP_SUP_WIDTH_20_40);
sta_params->lsig_txop_protection = is_cap_supported(caps,
IEEE80211_HT_CAP_LSIG_TXOP_PROT);
sta_params->max_ampdu_size = sta->ht_cap.ampdu_factor;
sta_params->max_ampdu_density = sta->ht_cap.ampdu_density;
sta_params->max_amsdu_size = is_cap_supported(caps,
IEEE80211_HT_CAP_MAX_AMSDU);
sta_params->sgi_20Mhz = is_cap_supported(caps,
IEEE80211_HT_CAP_SGI_20);
sta_params->sgi_40mhz = is_cap_supported(caps,
IEEE80211_HT_CAP_SGI_40);
sta_params->green_field_capable = is_cap_supported(caps,
IEEE80211_HT_CAP_GRN_FLD);
sta_params->delayed_ba_support = is_cap_supported(caps,
IEEE80211_HT_CAP_DELAY_BA);
sta_params->dsss_cck_mode_40mhz = is_cap_supported(caps,
IEEE80211_HT_CAP_DSSSCCK40);
}
}
static void wcn36xx_smd_set_sta_default_ht_params(
struct wcn36xx_hal_config_sta_params *sta_params)
{
sta_params->ht_capable = 1;
sta_params->tx_channel_width_set = 1;
sta_params->lsig_txop_protection = 1;
sta_params->max_ampdu_size = 3;
sta_params->max_ampdu_density = 5;
sta_params->max_amsdu_size = 0;
sta_params->sgi_20Mhz = 1;
sta_params->sgi_40mhz = 1;
sta_params->green_field_capable = 1;
sta_params->delayed_ba_support = 0;
sta_params->dsss_cck_mode_40mhz = 1;
}
static void wcn36xx_smd_set_sta_params(struct wcn36xx *wcn,
struct ieee80211_vif *vif,
struct ieee80211_sta *sta,
struct wcn36xx_hal_config_sta_params *sta_params)
{
struct wcn36xx_vif *priv_vif = (struct wcn36xx_vif *)vif->drv_priv;
struct wcn36xx_sta *priv_sta = NULL;
if (vif->type == NL80211_IFTYPE_ADHOC ||
vif->type == NL80211_IFTYPE_AP ||
vif->type == NL80211_IFTYPE_MESH_POINT) {
sta_params->type = 1;
sta_params->sta_index = 0xFF;
} else {
sta_params->type = 0;
sta_params->sta_index = 1;
}
sta_params->listen_interval = WCN36XX_LISTEN_INTERVAL(wcn);
/*
* In STA mode ieee80211_sta contains bssid and ieee80211_vif
* contains our mac address. In AP mode we are bssid so vif
* contains bssid and ieee80211_sta contains mac.
*/
if (NL80211_IFTYPE_STATION == vif->type)
memcpy(&sta_params->mac, vif->addr, ETH_ALEN);
else
memcpy(&sta_params->bssid, vif->addr, ETH_ALEN);
sta_params->encrypt_type = priv_vif->encrypt_type;
sta_params->short_preamble_supported =
!(WCN36XX_FLAGS(wcn) &
IEEE80211_HW_2GHZ_SHORT_PREAMBLE_INCAPABLE);
sta_params->rifs_mode = 0;
sta_params->rmf = 0;
sta_params->action = 0;
sta_params->uapsd = 0;
sta_params->mimo_ps = WCN36XX_HAL_HT_MIMO_PS_STATIC;
sta_params->max_ampdu_duration = 0;
sta_params->bssid_index = priv_vif->bss_index;
sta_params->p2p = 0;
if (sta) {
priv_sta = (struct wcn36xx_sta *)sta->drv_priv;
if (NL80211_IFTYPE_STATION == vif->type)
memcpy(&sta_params->bssid, sta->addr, ETH_ALEN);
else
memcpy(&sta_params->mac, sta->addr, ETH_ALEN);
sta_params->wmm_enabled = sta->wme;
sta_params->max_sp_len = sta->max_sp;
sta_params->aid = priv_sta->aid;
wcn36xx_smd_set_sta_ht_params(sta, sta_params);
memcpy(&sta_params->supported_rates, &priv_sta->supported_rates,
sizeof(priv_sta->supported_rates));
} else {
wcn36xx_set_default_rates(&sta_params->supported_rates);
wcn36xx_smd_set_sta_default_ht_params(sta_params);
}
}
static int wcn36xx_smd_send_and_wait(struct wcn36xx *wcn, size_t len)
{
int ret = 0;
wcn36xx_dbg_dump(WCN36XX_DBG_SMD_DUMP, "HAL >>> ", wcn->hal_buf, len);
init_completion(&wcn->hal_rsp_compl);
ret = wcn->ctrl_ops->tx(wcn->hal_buf, len);
if (ret) {
wcn36xx_err("HAL TX failed\n");
goto out;
}
if (wait_for_completion_timeout(&wcn->hal_rsp_compl,
msecs_to_jiffies(HAL_MSG_TIMEOUT)) <= 0) {
wcn36xx_err("Timeout while waiting SMD response\n");
ret = -ETIME;
goto out;
}
out:
return ret;
}
#define INIT_HAL_MSG(msg_body, type) \
do { \
memset(&msg_body, 0, sizeof(msg_body)); \
msg_body.header.msg_type = type; \
msg_body.header.msg_version = WCN36XX_HAL_MSG_VERSION0; \
msg_body.header.len = sizeof(msg_body); \
} while (0) \
#define PREPARE_HAL_BUF(send_buf, msg_body) \
do { \
memset(send_buf, 0, msg_body.header.len); \
memcpy(send_buf, &msg_body, sizeof(msg_body)); \
} while (0) \
static int wcn36xx_smd_rsp_status_check(void *buf, size_t len)
{
struct wcn36xx_fw_msg_status_rsp *rsp;
if (len < sizeof(struct wcn36xx_hal_msg_header) +
sizeof(struct wcn36xx_fw_msg_status_rsp))
return -EIO;
rsp = (struct wcn36xx_fw_msg_status_rsp *)
(buf + sizeof(struct wcn36xx_hal_msg_header));
if (WCN36XX_FW_MSG_RESULT_SUCCESS != rsp->status)
return rsp->status;
return 0;
}
int wcn36xx_smd_load_nv(struct wcn36xx *wcn)
{
const struct firmware *nv;
struct nv_data *nv_d;
struct wcn36xx_hal_nv_img_download_req_msg msg_body;
int fw_bytes_left;
int ret;
u16 fm_offset = 0;
ret = request_firmware(&nv, WLAN_NV_FILE, wcn->dev);
if (ret) {
wcn36xx_err("Failed to load nv file %s: %d\n",
WLAN_NV_FILE, ret);
goto out_free_nv;
}
nv_d = (struct nv_data *)nv->data;
INIT_HAL_MSG(msg_body, WCN36XX_HAL_DOWNLOAD_NV_REQ);
msg_body.header.len += WCN36XX_NV_FRAGMENT_SIZE;
msg_body.frag_number = 0;
/* hal_buf must be protected with mutex */
mutex_lock(&wcn->hal_mutex);
do {
fw_bytes_left = nv->size - fm_offset - 4;
if (fw_bytes_left > WCN36XX_NV_FRAGMENT_SIZE) {
msg_body.last_fragment = 0;
msg_body.nv_img_buffer_size = WCN36XX_NV_FRAGMENT_SIZE;
} else {
msg_body.last_fragment = 1;
msg_body.nv_img_buffer_size = fw_bytes_left;
/* Do not forget update general message len */
msg_body.header.len = sizeof(msg_body) + fw_bytes_left;
}
/* Add load NV request message header */
memcpy(wcn->hal_buf, &msg_body, sizeof(msg_body));
/* Add NV body itself */
memcpy(wcn->hal_buf + sizeof(msg_body),
&nv_d->table + fm_offset,
msg_body.nv_img_buffer_size);
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret)
goto out_unlock;
ret = wcn36xx_smd_rsp_status_check(wcn->hal_buf,
wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_load_nv response failed err=%d\n",
ret);
goto out_unlock;
}
msg_body.frag_number++;
fm_offset += WCN36XX_NV_FRAGMENT_SIZE;
} while (msg_body.last_fragment != 1);
out_unlock:
mutex_unlock(&wcn->hal_mutex);
out_free_nv:
release_firmware(nv);
return ret;
}
static int wcn36xx_smd_start_rsp(struct wcn36xx *wcn, void *buf, size_t len)
{
struct wcn36xx_hal_mac_start_rsp_msg *rsp;
if (len < sizeof(*rsp))
return -EIO;
rsp = (struct wcn36xx_hal_mac_start_rsp_msg *)buf;
if (WCN36XX_FW_MSG_RESULT_SUCCESS != rsp->start_rsp_params.status)
return -EIO;
memcpy(wcn->crm_version, rsp->start_rsp_params.crm_version,
WCN36XX_HAL_VERSION_LENGTH);
memcpy(wcn->wlan_version, rsp->start_rsp_params.wlan_version,
WCN36XX_HAL_VERSION_LENGTH);
/* null terminate the strings, just in case */
wcn->crm_version[WCN36XX_HAL_VERSION_LENGTH] = '\0';
wcn->wlan_version[WCN36XX_HAL_VERSION_LENGTH] = '\0';
wcn->fw_revision = rsp->start_rsp_params.version.revision;
wcn->fw_version = rsp->start_rsp_params.version.version;
wcn->fw_minor = rsp->start_rsp_params.version.minor;
wcn->fw_major = rsp->start_rsp_params.version.major;
wcn36xx_info("firmware WLAN version '%s' and CRM version '%s'\n",
wcn->wlan_version, wcn->crm_version);
wcn36xx_info("firmware API %u.%u.%u.%u, %u stations, %u bssids\n",
wcn->fw_major, wcn->fw_minor,
wcn->fw_version, wcn->fw_revision,
rsp->start_rsp_params.stations,
rsp->start_rsp_params.bssids);
return 0;
}
int wcn36xx_smd_start(struct wcn36xx *wcn)
{
struct wcn36xx_hal_mac_start_req_msg msg_body;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_START_REQ);
msg_body.params.type = DRIVER_TYPE_PRODUCTION;
msg_body.params.len = 0;
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
wcn36xx_dbg(WCN36XX_DBG_HAL, "hal start type %d\n",
msg_body.params.type);
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret) {
wcn36xx_err("Sending hal_start failed\n");
goto out;
}
ret = wcn36xx_smd_start_rsp(wcn, wcn->hal_buf, wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_start response failed err=%d\n", ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
int wcn36xx_smd_stop(struct wcn36xx *wcn)
{
struct wcn36xx_hal_mac_stop_req_msg msg_body;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_STOP_REQ);
msg_body.stop_req_params.reason = HAL_STOP_TYPE_RF_KILL;
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret) {
wcn36xx_err("Sending hal_stop failed\n");
goto out;
}
ret = wcn36xx_smd_rsp_status_check(wcn->hal_buf, wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_stop response failed err=%d\n", ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
int wcn36xx_smd_init_scan(struct wcn36xx *wcn, enum wcn36xx_hal_sys_mode mode)
{
struct wcn36xx_hal_init_scan_req_msg msg_body;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_INIT_SCAN_REQ);
msg_body.mode = mode;
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
wcn36xx_dbg(WCN36XX_DBG_HAL, "hal init scan mode %d\n", msg_body.mode);
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret) {
wcn36xx_err("Sending hal_init_scan failed\n");
goto out;
}
ret = wcn36xx_smd_rsp_status_check(wcn->hal_buf, wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_init_scan response failed err=%d\n", ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
int wcn36xx_smd_start_scan(struct wcn36xx *wcn)
{
struct wcn36xx_hal_start_scan_req_msg msg_body;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_START_SCAN_REQ);
msg_body.scan_channel = WCN36XX_HW_CHANNEL(wcn);
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
wcn36xx_dbg(WCN36XX_DBG_HAL, "hal start scan channel %d\n",
msg_body.scan_channel);
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret) {
wcn36xx_err("Sending hal_start_scan failed\n");
goto out;
}
ret = wcn36xx_smd_rsp_status_check(wcn->hal_buf, wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_start_scan response failed err=%d\n", ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
int wcn36xx_smd_end_scan(struct wcn36xx *wcn)
{
struct wcn36xx_hal_end_scan_req_msg msg_body;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_END_SCAN_REQ);
msg_body.scan_channel = WCN36XX_HW_CHANNEL(wcn);
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
wcn36xx_dbg(WCN36XX_DBG_HAL, "hal end scan channel %d\n",
msg_body.scan_channel);
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret) {
wcn36xx_err("Sending hal_end_scan failed\n");
goto out;
}
ret = wcn36xx_smd_rsp_status_check(wcn->hal_buf, wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_end_scan response failed err=%d\n", ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
int wcn36xx_smd_finish_scan(struct wcn36xx *wcn,
enum wcn36xx_hal_sys_mode mode)
{
struct wcn36xx_hal_finish_scan_req_msg msg_body;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_FINISH_SCAN_REQ);
msg_body.mode = mode;
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
wcn36xx_dbg(WCN36XX_DBG_HAL, "hal finish scan mode %d\n",
msg_body.mode);
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret) {
wcn36xx_err("Sending hal_finish_scan failed\n");
goto out;
}
ret = wcn36xx_smd_rsp_status_check(wcn->hal_buf, wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_finish_scan response failed err=%d\n", ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
static int wcn36xx_smd_switch_channel_rsp(void *buf, size_t len)
{
struct wcn36xx_hal_switch_channel_rsp_msg *rsp;
int ret = 0;
ret = wcn36xx_smd_rsp_status_check(buf, len);
if (ret)
return ret;
rsp = (struct wcn36xx_hal_switch_channel_rsp_msg *)buf;
wcn36xx_dbg(WCN36XX_DBG_HAL, "channel switched to: %d, status: %d\n",
rsp->channel_number, rsp->status);
return ret;
}
int wcn36xx_smd_switch_channel(struct wcn36xx *wcn,
struct ieee80211_vif *vif, int ch)
{
struct wcn36xx_hal_switch_channel_req_msg msg_body;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_CH_SWITCH_REQ);
msg_body.channel_number = (u8)ch;
msg_body.tx_mgmt_power = 0xbf;
msg_body.max_tx_power = 0xbf;
memcpy(msg_body.self_sta_mac_addr, vif->addr, ETH_ALEN);
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret) {
wcn36xx_err("Sending hal_switch_channel failed\n");
goto out;
}
ret = wcn36xx_smd_switch_channel_rsp(wcn->hal_buf, wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_switch_channel response failed err=%d\n", ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
static int wcn36xx_smd_update_scan_params_rsp(void *buf, size_t len)
{
struct wcn36xx_hal_update_scan_params_resp *rsp;
rsp = (struct wcn36xx_hal_update_scan_params_resp *)buf;
/* Remove the PNO version bit */
rsp->status &= (~(WCN36XX_FW_MSG_PNO_VERSION_MASK));
if (WCN36XX_FW_MSG_RESULT_SUCCESS != rsp->status) {
wcn36xx_warn("error response from update scan\n");
return rsp->status;
}
return 0;
}
int wcn36xx_smd_update_scan_params(struct wcn36xx *wcn)
{
struct wcn36xx_hal_update_scan_params_req msg_body;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_UPDATE_SCAN_PARAM_REQ);
msg_body.dot11d_enabled = 0;
msg_body.dot11d_resolved = 0;
msg_body.channel_count = 26;
msg_body.active_min_ch_time = 60;
msg_body.active_max_ch_time = 120;
msg_body.passive_min_ch_time = 60;
msg_body.passive_max_ch_time = 110;
msg_body.state = 0;
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
wcn36xx_dbg(WCN36XX_DBG_HAL,
"hal update scan params channel_count %d\n",
msg_body.channel_count);
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret) {
wcn36xx_err("Sending hal_update_scan_params failed\n");
goto out;
}
ret = wcn36xx_smd_update_scan_params_rsp(wcn->hal_buf,
wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_update_scan_params response failed err=%d\n",
ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
static int wcn36xx_smd_add_sta_self_rsp(struct wcn36xx *wcn,
struct ieee80211_vif *vif,
void *buf,
size_t len)
{
struct wcn36xx_hal_add_sta_self_rsp_msg *rsp;
struct wcn36xx_vif *priv_vif = (struct wcn36xx_vif *)vif->drv_priv;
if (len < sizeof(*rsp))
return -EINVAL;
rsp = (struct wcn36xx_hal_add_sta_self_rsp_msg *)buf;
if (rsp->status != WCN36XX_FW_MSG_RESULT_SUCCESS) {
wcn36xx_warn("hal add sta self failure: %d\n",
rsp->status);
return rsp->status;
}
wcn36xx_dbg(WCN36XX_DBG_HAL,
"hal add sta self status %d self_sta_index %d dpu_index %d\n",
rsp->status, rsp->self_sta_index, rsp->dpu_index);
priv_vif->self_sta_index = rsp->self_sta_index;
priv_vif->self_dpu_desc_index = rsp->dpu_index;
return 0;
}
int wcn36xx_smd_add_sta_self(struct wcn36xx *wcn, struct ieee80211_vif *vif)
{
struct wcn36xx_hal_add_sta_self_req msg_body;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_ADD_STA_SELF_REQ);
memcpy(&msg_body.self_addr, vif->addr, ETH_ALEN);
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
wcn36xx_dbg(WCN36XX_DBG_HAL,
"hal add sta self self_addr %pM status %d\n",
msg_body.self_addr, msg_body.status);
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret) {
wcn36xx_err("Sending hal_add_sta_self failed\n");
goto out;
}
ret = wcn36xx_smd_add_sta_self_rsp(wcn,
vif,
wcn->hal_buf,
wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_add_sta_self response failed err=%d\n", ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
int wcn36xx_smd_delete_sta_self(struct wcn36xx *wcn, u8 *addr)
{
struct wcn36xx_hal_del_sta_self_req_msg msg_body;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_DEL_STA_SELF_REQ);
memcpy(&msg_body.self_addr, addr, ETH_ALEN);
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret) {
wcn36xx_err("Sending hal_delete_sta_self failed\n");
goto out;
}
ret = wcn36xx_smd_rsp_status_check(wcn->hal_buf, wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_delete_sta_self response failed err=%d\n",
ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
int wcn36xx_smd_delete_sta(struct wcn36xx *wcn, u8 sta_index)
{
struct wcn36xx_hal_delete_sta_req_msg msg_body;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_DELETE_STA_REQ);
msg_body.sta_index = sta_index;
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
wcn36xx_dbg(WCN36XX_DBG_HAL,
"hal delete sta sta_index %d\n",
msg_body.sta_index);
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret) {
wcn36xx_err("Sending hal_delete_sta failed\n");
goto out;
}
ret = wcn36xx_smd_rsp_status_check(wcn->hal_buf, wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_delete_sta response failed err=%d\n", ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
static int wcn36xx_smd_join_rsp(void *buf, size_t len)
{
struct wcn36xx_hal_join_rsp_msg *rsp;
if (wcn36xx_smd_rsp_status_check(buf, len))
return -EIO;
rsp = (struct wcn36xx_hal_join_rsp_msg *)buf;
wcn36xx_dbg(WCN36XX_DBG_HAL,
"hal rsp join status %d tx_mgmt_power %d\n",
rsp->status, rsp->tx_mgmt_power);
return 0;
}
int wcn36xx_smd_join(struct wcn36xx *wcn, const u8 *bssid, u8 *vif, u8 ch)
{
struct wcn36xx_hal_join_req_msg msg_body;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_JOIN_REQ);
memcpy(&msg_body.bssid, bssid, ETH_ALEN);
memcpy(&msg_body.self_sta_mac_addr, vif, ETH_ALEN);
msg_body.channel = ch;
if (conf_is_ht40_minus(&wcn->hw->conf))
msg_body.secondary_channel_offset =
PHY_DOUBLE_CHANNEL_HIGH_PRIMARY;
else if (conf_is_ht40_plus(&wcn->hw->conf))
msg_body.secondary_channel_offset =
PHY_DOUBLE_CHANNEL_LOW_PRIMARY;
else
msg_body.secondary_channel_offset =
PHY_SINGLE_CHANNEL_CENTERED;
msg_body.link_state = WCN36XX_HAL_LINK_PREASSOC_STATE;
msg_body.max_tx_power = 0xbf;
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
wcn36xx_dbg(WCN36XX_DBG_HAL,
"hal join req bssid %pM self_sta_mac_addr %pM channel %d link_state %d\n",
msg_body.bssid, msg_body.self_sta_mac_addr,
msg_body.channel, msg_body.link_state);
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret) {
wcn36xx_err("Sending hal_join failed\n");
goto out;
}
ret = wcn36xx_smd_join_rsp(wcn->hal_buf, wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_join response failed err=%d\n", ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
int wcn36xx_smd_set_link_st(struct wcn36xx *wcn, const u8 *bssid,
const u8 *sta_mac,
enum wcn36xx_hal_link_state state)
{
struct wcn36xx_hal_set_link_state_req_msg msg_body;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_SET_LINK_ST_REQ);
memcpy(&msg_body.bssid, bssid, ETH_ALEN);
memcpy(&msg_body.self_mac_addr, sta_mac, ETH_ALEN);
msg_body.state = state;
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
wcn36xx_dbg(WCN36XX_DBG_HAL,
"hal set link state bssid %pM self_mac_addr %pM state %d\n",
msg_body.bssid, msg_body.self_mac_addr, msg_body.state);
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret) {
wcn36xx_err("Sending hal_set_link_st failed\n");
goto out;
}
ret = wcn36xx_smd_rsp_status_check(wcn->hal_buf, wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_set_link_st response failed err=%d\n", ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
static void wcn36xx_smd_convert_sta_to_v1(struct wcn36xx *wcn,
const struct wcn36xx_hal_config_sta_params *orig,
struct wcn36xx_hal_config_sta_params_v1 *v1)
{
/* convert orig to v1 format */
memcpy(&v1->bssid, orig->bssid, ETH_ALEN);
memcpy(&v1->mac, orig->mac, ETH_ALEN);
v1->aid = orig->aid;
v1->type = orig->type;
v1->listen_interval = orig->listen_interval;
v1->ht_capable = orig->ht_capable;
v1->max_ampdu_size = orig->max_ampdu_size;
v1->max_ampdu_density = orig->max_ampdu_density;
v1->sgi_40mhz = orig->sgi_40mhz;
v1->sgi_20Mhz = orig->sgi_20Mhz;
memcpy(&v1->supported_rates, &orig->supported_rates,
sizeof(orig->supported_rates));
v1->sta_index = orig->sta_index;
}
static int wcn36xx_smd_config_sta_rsp(struct wcn36xx *wcn,
struct ieee80211_sta *sta,
void *buf,
size_t len)
{
struct wcn36xx_hal_config_sta_rsp_msg *rsp;
struct config_sta_rsp_params *params;
struct wcn36xx_sta *sta_priv = (struct wcn36xx_sta *)sta->drv_priv;
if (len < sizeof(*rsp))
return -EINVAL;
rsp = (struct wcn36xx_hal_config_sta_rsp_msg *)buf;
params = &rsp->params;
if (params->status != WCN36XX_FW_MSG_RESULT_SUCCESS) {
wcn36xx_warn("hal config sta response failure: %d\n",
params->status);
return -EIO;
}
sta_priv->sta_index = params->sta_index;
sta_priv->dpu_desc_index = params->dpu_index;
wcn36xx_dbg(WCN36XX_DBG_HAL,
"hal config sta rsp status %d sta_index %d bssid_index %d p2p %d\n",
params->status, params->sta_index, params->bssid_index,
params->p2p);
return 0;
}
static int wcn36xx_smd_config_sta_v1(struct wcn36xx *wcn,
const struct wcn36xx_hal_config_sta_req_msg *orig)
{
struct wcn36xx_hal_config_sta_req_msg_v1 msg_body;
struct wcn36xx_hal_config_sta_params_v1 *sta = &msg_body.sta_params;
INIT_HAL_MSG(msg_body, WCN36XX_HAL_CONFIG_STA_REQ);
wcn36xx_smd_convert_sta_to_v1(wcn, &orig->sta_params,
&msg_body.sta_params);
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
wcn36xx_dbg(WCN36XX_DBG_HAL,
"hal config sta v1 action %d sta_index %d bssid_index %d bssid %pM type %d mac %pM aid %d\n",
sta->action, sta->sta_index, sta->bssid_index,
sta->bssid, sta->type, sta->mac, sta->aid);
return wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
}
int wcn36xx_smd_config_sta(struct wcn36xx *wcn, struct ieee80211_vif *vif,
struct ieee80211_sta *sta)
{
struct wcn36xx_hal_config_sta_req_msg msg;
struct wcn36xx_hal_config_sta_params *sta_params;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg, WCN36XX_HAL_CONFIG_STA_REQ);
sta_params = &msg.sta_params;
wcn36xx_smd_set_sta_params(wcn, vif, sta, sta_params);
if (!wcn36xx_is_fw_version(wcn, 1, 2, 2, 24)) {
ret = wcn36xx_smd_config_sta_v1(wcn, &msg);
} else {
PREPARE_HAL_BUF(wcn->hal_buf, msg);
wcn36xx_dbg(WCN36XX_DBG_HAL,
"hal config sta action %d sta_index %d bssid_index %d bssid %pM type %d mac %pM aid %d\n",
sta_params->action, sta_params->sta_index,
sta_params->bssid_index, sta_params->bssid,
sta_params->type, sta_params->mac, sta_params->aid);
ret = wcn36xx_smd_send_and_wait(wcn, msg.header.len);
}
if (ret) {
wcn36xx_err("Sending hal_config_sta failed\n");
goto out;
}
ret = wcn36xx_smd_config_sta_rsp(wcn,
sta,
wcn->hal_buf,
wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_config_sta response failed err=%d\n", ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
static int wcn36xx_smd_config_bss_v1(struct wcn36xx *wcn,
const struct wcn36xx_hal_config_bss_req_msg *orig)
{
struct wcn36xx_hal_config_bss_req_msg_v1 msg_body;
struct wcn36xx_hal_config_bss_params_v1 *bss = &msg_body.bss_params;
struct wcn36xx_hal_config_sta_params_v1 *sta = &bss->sta;
INIT_HAL_MSG(msg_body, WCN36XX_HAL_CONFIG_BSS_REQ);
/* convert orig to v1 */
memcpy(&msg_body.bss_params.bssid,
&orig->bss_params.bssid, ETH_ALEN);
memcpy(&msg_body.bss_params.self_mac_addr,
&orig->bss_params.self_mac_addr, ETH_ALEN);
msg_body.bss_params.bss_type = orig->bss_params.bss_type;
msg_body.bss_params.oper_mode = orig->bss_params.oper_mode;
msg_body.bss_params.nw_type = orig->bss_params.nw_type;
msg_body.bss_params.short_slot_time_supported =
orig->bss_params.short_slot_time_supported;
msg_body.bss_params.lla_coexist = orig->bss_params.lla_coexist;
msg_body.bss_params.llb_coexist = orig->bss_params.llb_coexist;
msg_body.bss_params.llg_coexist = orig->bss_params.llg_coexist;
msg_body.bss_params.ht20_coexist = orig->bss_params.ht20_coexist;
msg_body.bss_params.lln_non_gf_coexist =
orig->bss_params.lln_non_gf_coexist;
msg_body.bss_params.lsig_tx_op_protection_full_support =
orig->bss_params.lsig_tx_op_protection_full_support;
msg_body.bss_params.rifs_mode = orig->bss_params.rifs_mode;
msg_body.bss_params.beacon_interval = orig->bss_params.beacon_interval;
msg_body.bss_params.dtim_period = orig->bss_params.dtim_period;
msg_body.bss_params.tx_channel_width_set =
orig->bss_params.tx_channel_width_set;
msg_body.bss_params.oper_channel = orig->bss_params.oper_channel;
msg_body.bss_params.ext_channel = orig->bss_params.ext_channel;
msg_body.bss_params.reserved = orig->bss_params.reserved;
memcpy(&msg_body.bss_params.ssid,
&orig->bss_params.ssid,
sizeof(orig->bss_params.ssid));
msg_body.bss_params.action = orig->bss_params.action;
msg_body.bss_params.rateset = orig->bss_params.rateset;
msg_body.bss_params.ht = orig->bss_params.ht;
msg_body.bss_params.obss_prot_enabled =
orig->bss_params.obss_prot_enabled;
msg_body.bss_params.rmf = orig->bss_params.rmf;
msg_body.bss_params.ht_oper_mode = orig->bss_params.ht_oper_mode;
msg_body.bss_params.dual_cts_protection =
orig->bss_params.dual_cts_protection;
msg_body.bss_params.max_probe_resp_retry_limit =
orig->bss_params.max_probe_resp_retry_limit;
msg_body.bss_params.hidden_ssid = orig->bss_params.hidden_ssid;
msg_body.bss_params.proxy_probe_resp =
orig->bss_params.proxy_probe_resp;
msg_body.bss_params.edca_params_valid =
orig->bss_params.edca_params_valid;
memcpy(&msg_body.bss_params.acbe,
&orig->bss_params.acbe,
sizeof(orig->bss_params.acbe));
memcpy(&msg_body.bss_params.acbk,
&orig->bss_params.acbk,
sizeof(orig->bss_params.acbk));
memcpy(&msg_body.bss_params.acvi,
&orig->bss_params.acvi,
sizeof(orig->bss_params.acvi));
memcpy(&msg_body.bss_params.acvo,
&orig->bss_params.acvo,
sizeof(orig->bss_params.acvo));
msg_body.bss_params.ext_set_sta_key_param_valid =
orig->bss_params.ext_set_sta_key_param_valid;
memcpy(&msg_body.bss_params.ext_set_sta_key_param,
&orig->bss_params.ext_set_sta_key_param,
sizeof(orig->bss_params.acvo));
msg_body.bss_params.wcn36xx_hal_persona =
orig->bss_params.wcn36xx_hal_persona;
msg_body.bss_params.spectrum_mgt_enable =
orig->bss_params.spectrum_mgt_enable;
msg_body.bss_params.tx_mgmt_power = orig->bss_params.tx_mgmt_power;
msg_body.bss_params.max_tx_power = orig->bss_params.max_tx_power;
wcn36xx_smd_convert_sta_to_v1(wcn, &orig->bss_params.sta,
&msg_body.bss_params.sta);
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
wcn36xx_dbg(WCN36XX_DBG_HAL,
"hal config bss v1 bssid %pM self_mac_addr %pM bss_type %d oper_mode %d nw_type %d\n",
bss->bssid, bss->self_mac_addr, bss->bss_type,
bss->oper_mode, bss->nw_type);
wcn36xx_dbg(WCN36XX_DBG_HAL,
"- sta bssid %pM action %d sta_index %d bssid_index %d aid %d type %d mac %pM\n",
sta->bssid, sta->action, sta->sta_index,
sta->bssid_index, sta->aid, sta->type, sta->mac);
return wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
}
static int wcn36xx_smd_config_bss_rsp(struct wcn36xx *wcn,
struct ieee80211_vif *vif,
void *buf,
size_t len)
{
struct wcn36xx_hal_config_bss_rsp_msg *rsp;
struct wcn36xx_hal_config_bss_rsp_params *params;
struct wcn36xx_vif *priv_vif = (struct wcn36xx_vif *)vif->drv_priv;
if (len < sizeof(*rsp))
return -EINVAL;
rsp = (struct wcn36xx_hal_config_bss_rsp_msg *)buf;
params = &rsp->bss_rsp_params;
if (params->status != WCN36XX_FW_MSG_RESULT_SUCCESS) {
wcn36xx_warn("hal config bss response failure: %d\n",
params->status);
return -EIO;
}
wcn36xx_dbg(WCN36XX_DBG_HAL,
"hal config bss rsp status %d bss_idx %d dpu_desc_index %d"
" sta_idx %d self_idx %d bcast_idx %d mac %pM"
" power %d ucast_dpu_signature %d\n",
params->status, params->bss_index, params->dpu_desc_index,
params->bss_sta_index, params->bss_self_sta_index,
params->bss_bcast_sta_idx, params->mac,
params->tx_mgmt_power, params->ucast_dpu_signature);
priv_vif->bss_index = params->bss_index;
if (priv_vif->sta) {
priv_vif->sta->bss_sta_index = params->bss_sta_index;
priv_vif->sta->bss_dpu_desc_index = params->dpu_desc_index;
}
priv_vif->ucast_dpu_signature = params->ucast_dpu_signature;
return 0;
}
int wcn36xx_smd_config_bss(struct wcn36xx *wcn, struct ieee80211_vif *vif,
struct ieee80211_sta *sta, const u8 *bssid,
bool update)
{
struct wcn36xx_hal_config_bss_req_msg msg;
struct wcn36xx_hal_config_bss_params *bss;
struct wcn36xx_hal_config_sta_params *sta_params;
struct wcn36xx_vif *vif_priv = (struct wcn36xx_vif *)vif->drv_priv;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg, WCN36XX_HAL_CONFIG_BSS_REQ);
bss = &msg.bss_params;
sta_params = &bss->sta;
WARN_ON(is_zero_ether_addr(bssid));
memcpy(&bss->bssid, bssid, ETH_ALEN);
memcpy(bss->self_mac_addr, vif->addr, ETH_ALEN);
if (vif->type == NL80211_IFTYPE_STATION) {
bss->bss_type = WCN36XX_HAL_INFRASTRUCTURE_MODE;
/* STA */
bss->oper_mode = 1;
bss->wcn36xx_hal_persona = WCN36XX_HAL_STA_MODE;
} else if (vif->type == NL80211_IFTYPE_AP ||
vif->type == NL80211_IFTYPE_MESH_POINT) {
bss->bss_type = WCN36XX_HAL_INFRA_AP_MODE;
/* AP */
bss->oper_mode = 0;
bss->wcn36xx_hal_persona = WCN36XX_HAL_STA_SAP_MODE;
} else if (vif->type == NL80211_IFTYPE_ADHOC) {
bss->bss_type = WCN36XX_HAL_IBSS_MODE;
/* STA */
bss->oper_mode = 1;
} else {
wcn36xx_warn("Unknown type for bss config: %d\n", vif->type);
}
if (vif->type == NL80211_IFTYPE_STATION)
wcn36xx_smd_set_bss_nw_type(wcn, sta, bss);
else
bss->nw_type = WCN36XX_HAL_11N_NW_TYPE;
bss->short_slot_time_supported = vif->bss_conf.use_short_slot;
bss->lla_coexist = 0;
bss->llb_coexist = 0;
bss->llg_coexist = 0;
bss->rifs_mode = 0;
bss->beacon_interval = vif->bss_conf.beacon_int;
bss->dtim_period = vif_priv->dtim_period;
wcn36xx_smd_set_bss_ht_params(vif, sta, bss);
bss->oper_channel = WCN36XX_HW_CHANNEL(wcn);
if (conf_is_ht40_minus(&wcn->hw->conf))
bss->ext_channel = IEEE80211_HT_PARAM_CHA_SEC_BELOW;
else if (conf_is_ht40_plus(&wcn->hw->conf))
bss->ext_channel = IEEE80211_HT_PARAM_CHA_SEC_ABOVE;
else
bss->ext_channel = IEEE80211_HT_PARAM_CHA_SEC_NONE;
bss->reserved = 0;
wcn36xx_smd_set_sta_params(wcn, vif, sta, sta_params);
/* wcn->ssid is only valid in AP and IBSS mode */
bss->ssid.length = vif_priv->ssid.length;
memcpy(bss->ssid.ssid, vif_priv->ssid.ssid, vif_priv->ssid.length);
bss->obss_prot_enabled = 0;
bss->rmf = 0;
bss->max_probe_resp_retry_limit = 0;
bss->hidden_ssid = vif->bss_conf.hidden_ssid;
bss->proxy_probe_resp = 0;
bss->edca_params_valid = 0;
/* FIXME: set acbe, acbk, acvi and acvo */
bss->ext_set_sta_key_param_valid = 0;
/* FIXME: set ext_set_sta_key_param */
bss->spectrum_mgt_enable = 0;
bss->tx_mgmt_power = 0;
bss->max_tx_power = WCN36XX_MAX_POWER(wcn);
bss->action = update;
wcn36xx_dbg(WCN36XX_DBG_HAL,
"hal config bss bssid %pM self_mac_addr %pM bss_type %d oper_mode %d nw_type %d\n",
bss->bssid, bss->self_mac_addr, bss->bss_type,
bss->oper_mode, bss->nw_type);
wcn36xx_dbg(WCN36XX_DBG_HAL,
"- sta bssid %pM action %d sta_index %d bssid_index %d aid %d type %d mac %pM\n",
sta_params->bssid, sta_params->action,
sta_params->sta_index, sta_params->bssid_index,
sta_params->aid, sta_params->type,
sta_params->mac);
if (!wcn36xx_is_fw_version(wcn, 1, 2, 2, 24)) {
ret = wcn36xx_smd_config_bss_v1(wcn, &msg);
} else {
PREPARE_HAL_BUF(wcn->hal_buf, msg);
ret = wcn36xx_smd_send_and_wait(wcn, msg.header.len);
}
if (ret) {
wcn36xx_err("Sending hal_config_bss failed\n");
goto out;
}
ret = wcn36xx_smd_config_bss_rsp(wcn,
vif,
wcn->hal_buf,
wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_config_bss response failed err=%d\n", ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
int wcn36xx_smd_delete_bss(struct wcn36xx *wcn, struct ieee80211_vif *vif)
{
struct wcn36xx_hal_delete_bss_req_msg msg_body;
struct wcn36xx_vif *priv_vif = (struct wcn36xx_vif *)vif->drv_priv;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_DELETE_BSS_REQ);
msg_body.bss_index = priv_vif->bss_index;
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
wcn36xx_dbg(WCN36XX_DBG_HAL, "hal delete bss %d\n", msg_body.bss_index);
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret) {
wcn36xx_err("Sending hal_delete_bss failed\n");
goto out;
}
ret = wcn36xx_smd_rsp_status_check(wcn->hal_buf, wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_delete_bss response failed err=%d\n", ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
int wcn36xx_smd_send_beacon(struct wcn36xx *wcn, struct ieee80211_vif *vif,
struct sk_buff *skb_beacon, u16 tim_off,
u16 p2p_off)
{
struct wcn36xx_hal_send_beacon_req_msg msg_body;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_SEND_BEACON_REQ);
/* TODO need to find out why this is needed? */
msg_body.beacon_length = skb_beacon->len + 6;
if (BEACON_TEMPLATE_SIZE > msg_body.beacon_length) {
memcpy(&msg_body.beacon, &skb_beacon->len, sizeof(u32));
memcpy(&(msg_body.beacon[4]), skb_beacon->data,
skb_beacon->len);
} else {
wcn36xx_err("Beacon is to big: beacon size=%d\n",
msg_body.beacon_length);
ret = -ENOMEM;
goto out;
}
memcpy(msg_body.bssid, vif->addr, ETH_ALEN);
/* TODO need to find out why this is needed? */
if (vif->type == NL80211_IFTYPE_MESH_POINT)
/* mesh beacon don't need this, so push further down */
msg_body.tim_ie_offset = 256;
else
msg_body.tim_ie_offset = tim_off+4;
msg_body.p2p_ie_offset = p2p_off;
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
wcn36xx_dbg(WCN36XX_DBG_HAL,
"hal send beacon beacon_length %d\n",
msg_body.beacon_length);
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret) {
wcn36xx_err("Sending hal_send_beacon failed\n");
goto out;
}
ret = wcn36xx_smd_rsp_status_check(wcn->hal_buf, wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_send_beacon response failed err=%d\n", ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
int wcn36xx_smd_update_proberesp_tmpl(struct wcn36xx *wcn,
struct ieee80211_vif *vif,
struct sk_buff *skb)
{
struct wcn36xx_hal_send_probe_resp_req_msg msg;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg, WCN36XX_HAL_UPDATE_PROBE_RSP_TEMPLATE_REQ);
if (skb->len > BEACON_TEMPLATE_SIZE) {
wcn36xx_warn("probe response template is too big: %d\n",
skb->len);
ret = -E2BIG;
goto out;
}
msg.probe_resp_template_len = skb->len;
memcpy(&msg.probe_resp_template, skb->data, skb->len);
memcpy(msg.bssid, vif->addr, ETH_ALEN);
PREPARE_HAL_BUF(wcn->hal_buf, msg);
wcn36xx_dbg(WCN36XX_DBG_HAL,
"hal update probe rsp len %d bssid %pM\n",
msg.probe_resp_template_len, msg.bssid);
ret = wcn36xx_smd_send_and_wait(wcn, msg.header.len);
if (ret) {
wcn36xx_err("Sending hal_update_proberesp_tmpl failed\n");
goto out;
}
ret = wcn36xx_smd_rsp_status_check(wcn->hal_buf, wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_update_proberesp_tmpl response failed err=%d\n",
ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
int wcn36xx_smd_set_stakey(struct wcn36xx *wcn,
enum ani_ed_type enc_type,
u8 keyidx,
u8 keylen,
u8 *key,
u8 sta_index)
{
struct wcn36xx_hal_set_sta_key_req_msg msg_body;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_SET_STAKEY_REQ);
msg_body.set_sta_key_params.sta_index = sta_index;
msg_body.set_sta_key_params.enc_type = enc_type;
msg_body.set_sta_key_params.key[0].id = keyidx;
msg_body.set_sta_key_params.key[0].unicast = 1;
msg_body.set_sta_key_params.key[0].direction = WCN36XX_HAL_TX_RX;
msg_body.set_sta_key_params.key[0].pae_role = 0;
msg_body.set_sta_key_params.key[0].length = keylen;
memcpy(msg_body.set_sta_key_params.key[0].key, key, keylen);
msg_body.set_sta_key_params.single_tid_rc = 1;
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret) {
wcn36xx_err("Sending hal_set_stakey failed\n");
goto out;
}
ret = wcn36xx_smd_rsp_status_check(wcn->hal_buf, wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_set_stakey response failed err=%d\n", ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
int wcn36xx_smd_set_bsskey(struct wcn36xx *wcn,
enum ani_ed_type enc_type,
u8 keyidx,
u8 keylen,
u8 *key)
{
struct wcn36xx_hal_set_bss_key_req_msg msg_body;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_SET_BSSKEY_REQ);
msg_body.bss_idx = 0;
msg_body.enc_type = enc_type;
msg_body.num_keys = 1;
msg_body.keys[0].id = keyidx;
msg_body.keys[0].unicast = 0;
msg_body.keys[0].direction = WCN36XX_HAL_RX_ONLY;
msg_body.keys[0].pae_role = 0;
msg_body.keys[0].length = keylen;
memcpy(msg_body.keys[0].key, key, keylen);
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret) {
wcn36xx_err("Sending hal_set_bsskey failed\n");
goto out;
}
ret = wcn36xx_smd_rsp_status_check(wcn->hal_buf, wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_set_bsskey response failed err=%d\n", ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
int wcn36xx_smd_remove_stakey(struct wcn36xx *wcn,
enum ani_ed_type enc_type,
u8 keyidx,
u8 sta_index)
{
struct wcn36xx_hal_remove_sta_key_req_msg msg_body;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_RMV_STAKEY_REQ);
msg_body.sta_idx = sta_index;
msg_body.enc_type = enc_type;
msg_body.key_id = keyidx;
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret) {
wcn36xx_err("Sending hal_remove_stakey failed\n");
goto out;
}
ret = wcn36xx_smd_rsp_status_check(wcn->hal_buf, wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_remove_stakey response failed err=%d\n", ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
int wcn36xx_smd_remove_bsskey(struct wcn36xx *wcn,
enum ani_ed_type enc_type,
u8 keyidx)
{
struct wcn36xx_hal_remove_bss_key_req_msg msg_body;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_RMV_BSSKEY_REQ);
msg_body.bss_idx = 0;
msg_body.enc_type = enc_type;
msg_body.key_id = keyidx;
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret) {
wcn36xx_err("Sending hal_remove_bsskey failed\n");
goto out;
}
ret = wcn36xx_smd_rsp_status_check(wcn->hal_buf, wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_remove_bsskey response failed err=%d\n", ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
int wcn36xx_smd_enter_bmps(struct wcn36xx *wcn, struct ieee80211_vif *vif)
{
struct wcn36xx_hal_enter_bmps_req_msg msg_body;
struct wcn36xx_vif *vif_priv = (struct wcn36xx_vif *)vif->drv_priv;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_ENTER_BMPS_REQ);
msg_body.bss_index = vif_priv->bss_index;
msg_body.tbtt = vif->bss_conf.sync_tsf;
msg_body.dtim_period = vif_priv->dtim_period;
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret) {
wcn36xx_err("Sending hal_enter_bmps failed\n");
goto out;
}
ret = wcn36xx_smd_rsp_status_check(wcn->hal_buf, wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_enter_bmps response failed err=%d\n", ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
int wcn36xx_smd_exit_bmps(struct wcn36xx *wcn, struct ieee80211_vif *vif)
{
struct wcn36xx_hal_enter_bmps_req_msg msg_body;
struct wcn36xx_vif *vif_priv = (struct wcn36xx_vif *)vif->drv_priv;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_EXIT_BMPS_REQ);
msg_body.bss_index = vif_priv->bss_index;
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret) {
wcn36xx_err("Sending hal_exit_bmps failed\n");
goto out;
}
ret = wcn36xx_smd_rsp_status_check(wcn->hal_buf, wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_exit_bmps response failed err=%d\n", ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
int wcn36xx_smd_set_power_params(struct wcn36xx *wcn, bool ignore_dtim)
{
struct wcn36xx_hal_set_power_params_req_msg msg_body;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_SET_POWER_PARAMS_REQ);
/*
* When host is down ignore every second dtim
*/
if (ignore_dtim) {
msg_body.ignore_dtim = 1;
msg_body.dtim_period = 2;
}
msg_body.listen_interval = WCN36XX_LISTEN_INTERVAL(wcn);
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret) {
wcn36xx_err("Sending hal_set_power_params failed\n");
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
/* Notice: This function should be called after associated, or else it
* will be invalid
*/
int wcn36xx_smd_keep_alive_req(struct wcn36xx *wcn,
struct ieee80211_vif *vif,
int packet_type)
{
struct wcn36xx_hal_keep_alive_req_msg msg_body;
struct wcn36xx_vif *vif_priv = (struct wcn36xx_vif *)vif->drv_priv;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_KEEP_ALIVE_REQ);
if (packet_type == WCN36XX_HAL_KEEP_ALIVE_NULL_PKT) {
msg_body.bss_index = vif_priv->bss_index;
msg_body.packet_type = WCN36XX_HAL_KEEP_ALIVE_NULL_PKT;
msg_body.time_period = WCN36XX_KEEP_ALIVE_TIME_PERIOD;
} else if (packet_type == WCN36XX_HAL_KEEP_ALIVE_UNSOLICIT_ARP_RSP) {
/* TODO: it also support ARP response type */
} else {
wcn36xx_warn("unknow keep alive packet type %d\n", packet_type);
ret = -EINVAL;
goto out;
}
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret) {
wcn36xx_err("Sending hal_exit_bmps failed\n");
goto out;
}
ret = wcn36xx_smd_rsp_status_check(wcn->hal_buf, wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_exit_bmps response failed err=%d\n", ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
int wcn36xx_smd_dump_cmd_req(struct wcn36xx *wcn, u32 arg1, u32 arg2,
u32 arg3, u32 arg4, u32 arg5)
{
struct wcn36xx_hal_dump_cmd_req_msg msg_body;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_DUMP_COMMAND_REQ);
msg_body.arg1 = arg1;
msg_body.arg2 = arg2;
msg_body.arg3 = arg3;
msg_body.arg4 = arg4;
msg_body.arg5 = arg5;
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret) {
wcn36xx_err("Sending hal_dump_cmd failed\n");
goto out;
}
ret = wcn36xx_smd_rsp_status_check(wcn->hal_buf, wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_dump_cmd response failed err=%d\n", ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
static inline void set_feat_caps(u32 *bitmap,
enum place_holder_in_cap_bitmap cap)
{
int arr_idx, bit_idx;
if (cap < 0 || cap > 127) {
wcn36xx_warn("error cap idx %d\n", cap);
return;
}
arr_idx = cap / 32;
bit_idx = cap % 32;
bitmap[arr_idx] |= (1 << bit_idx);
}
static inline int get_feat_caps(u32 *bitmap,
enum place_holder_in_cap_bitmap cap)
{
int arr_idx, bit_idx;
int ret = 0;
if (cap < 0 || cap > 127) {
wcn36xx_warn("error cap idx %d\n", cap);
return -EINVAL;
}
arr_idx = cap / 32;
bit_idx = cap % 32;
ret = (bitmap[arr_idx] & (1 << bit_idx)) ? 1 : 0;
return ret;
}
static inline void clear_feat_caps(u32 *bitmap,
enum place_holder_in_cap_bitmap cap)
{
int arr_idx, bit_idx;
if (cap < 0 || cap > 127) {
wcn36xx_warn("error cap idx %d\n", cap);
return;
}
arr_idx = cap / 32;
bit_idx = cap % 32;
bitmap[arr_idx] &= ~(1 << bit_idx);
}
int wcn36xx_smd_feature_caps_exchange(struct wcn36xx *wcn)
{
struct wcn36xx_hal_feat_caps_msg msg_body;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_FEATURE_CAPS_EXCHANGE_REQ);
set_feat_caps(msg_body.feat_caps, STA_POWERSAVE);
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret) {
wcn36xx_err("Sending hal_feature_caps_exchange failed\n");
goto out;
}
ret = wcn36xx_smd_rsp_status_check(wcn->hal_buf, wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_feature_caps_exchange response failed err=%d\n",
ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
int wcn36xx_smd_add_ba_session(struct wcn36xx *wcn,
struct ieee80211_sta *sta,
u16 tid,
u16 *ssn,
u8 direction,
u8 sta_index)
{
struct wcn36xx_hal_add_ba_session_req_msg msg_body;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_ADD_BA_SESSION_REQ);
msg_body.sta_index = sta_index;
memcpy(&msg_body.mac_addr, sta->addr, ETH_ALEN);
msg_body.dialog_token = 0x10;
msg_body.tid = tid;
/* Immediate BA because Delayed BA is not supported */
msg_body.policy = 1;
msg_body.buffer_size = WCN36XX_AGGR_BUFFER_SIZE;
msg_body.timeout = 0;
if (ssn)
msg_body.ssn = *ssn;
msg_body.direction = direction;
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret) {
wcn36xx_err("Sending hal_add_ba_session failed\n");
goto out;
}
ret = wcn36xx_smd_rsp_status_check(wcn->hal_buf, wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_add_ba_session response failed err=%d\n", ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
int wcn36xx_smd_add_ba(struct wcn36xx *wcn)
{
struct wcn36xx_hal_add_ba_req_msg msg_body;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_ADD_BA_REQ);
msg_body.session_id = 0;
msg_body.win_size = WCN36XX_AGGR_BUFFER_SIZE;
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret) {
wcn36xx_err("Sending hal_add_ba failed\n");
goto out;
}
ret = wcn36xx_smd_rsp_status_check(wcn->hal_buf, wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_add_ba response failed err=%d\n", ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
int wcn36xx_smd_del_ba(struct wcn36xx *wcn, u16 tid, u8 sta_index)
{
struct wcn36xx_hal_del_ba_req_msg msg_body;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_DEL_BA_REQ);
msg_body.sta_index = sta_index;
msg_body.tid = tid;
msg_body.direction = 0;
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret) {
wcn36xx_err("Sending hal_del_ba failed\n");
goto out;
}
ret = wcn36xx_smd_rsp_status_check(wcn->hal_buf, wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_del_ba response failed err=%d\n", ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
int wcn36xx_smd_trigger_ba(struct wcn36xx *wcn, u8 sta_index)
{
struct wcn36xx_hal_trigger_ba_req_msg msg_body;
struct wcn36xx_hal_trigger_ba_req_candidate *candidate;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_TRIGGER_BA_REQ);
msg_body.session_id = 0;
msg_body.candidate_cnt = 1;
msg_body.header.len += sizeof(*candidate);
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
candidate = (struct wcn36xx_hal_trigger_ba_req_candidate *)
(wcn->hal_buf + sizeof(msg_body));
candidate->sta_index = sta_index;
candidate->tid_bitmap = 1;
ret = wcn36xx_smd_send_and_wait(wcn, msg_body.header.len);
if (ret) {
wcn36xx_err("Sending hal_trigger_ba failed\n");
goto out;
}
ret = wcn36xx_smd_rsp_status_check(wcn->hal_buf, wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_trigger_ba response failed err=%d\n", ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
static int wcn36xx_smd_tx_compl_ind(struct wcn36xx *wcn, void *buf, size_t len)
{
struct wcn36xx_hal_tx_compl_ind_msg *rsp = buf;
if (len != sizeof(*rsp)) {
wcn36xx_warn("Bad TX complete indication\n");
return -EIO;
}
wcn36xx_dxe_tx_ack_ind(wcn, rsp->status);
return 0;
}
static int wcn36xx_smd_missed_beacon_ind(struct wcn36xx *wcn,
void *buf,
size_t len)
{
struct wcn36xx_hal_missed_beacon_ind_msg *rsp = buf;
struct ieee80211_vif *vif = NULL;
struct wcn36xx_vif *tmp;
/* Old FW does not have bss index */
if (wcn36xx_is_fw_version(wcn, 1, 2, 2, 24)) {
list_for_each_entry(tmp, &wcn->vif_list, list) {
wcn36xx_dbg(WCN36XX_DBG_HAL, "beacon missed bss_index %d\n",
tmp->bss_index);
vif = container_of((void *)tmp,
struct ieee80211_vif,
drv_priv);
ieee80211_connection_loss(vif);
}
return 0;
}
if (len != sizeof(*rsp)) {
wcn36xx_warn("Corrupted missed beacon indication\n");
return -EIO;
}
list_for_each_entry(tmp, &wcn->vif_list, list) {
if (tmp->bss_index == rsp->bss_index) {
wcn36xx_dbg(WCN36XX_DBG_HAL, "beacon missed bss_index %d\n",
rsp->bss_index);
vif = container_of((void *)tmp,
struct ieee80211_vif,
drv_priv);
ieee80211_connection_loss(vif);
return 0;
}
}
wcn36xx_warn("BSS index %d not found\n", rsp->bss_index);
return -ENOENT;
}
static int wcn36xx_smd_delete_sta_context_ind(struct wcn36xx *wcn,
void *buf,
size_t len)
{
struct wcn36xx_hal_delete_sta_context_ind_msg *rsp = buf;
struct wcn36xx_vif *tmp;
struct ieee80211_sta *sta = NULL;
if (len != sizeof(*rsp)) {
wcn36xx_warn("Corrupted delete sta indication\n");
return -EIO;
}
list_for_each_entry(tmp, &wcn->vif_list, list) {
if (sta && (tmp->sta->sta_index == rsp->sta_id)) {
sta = container_of((void *)tmp->sta,
struct ieee80211_sta,
drv_priv);
wcn36xx_dbg(WCN36XX_DBG_HAL,
"delete station indication %pM index %d\n",
rsp->addr2,
rsp->sta_id);
ieee80211_report_low_ack(sta, 0);
return 0;
}
}
wcn36xx_warn("STA with addr %pM and index %d not found\n",
rsp->addr2,
rsp->sta_id);
return -ENOENT;
}
int wcn36xx_smd_update_cfg(struct wcn36xx *wcn, u32 cfg_id, u32 value)
{
struct wcn36xx_hal_update_cfg_req_msg msg_body, *body;
size_t len;
int ret = 0;
mutex_lock(&wcn->hal_mutex);
INIT_HAL_MSG(msg_body, WCN36XX_HAL_UPDATE_CFG_REQ);
PREPARE_HAL_BUF(wcn->hal_buf, msg_body);
body = (struct wcn36xx_hal_update_cfg_req_msg *) wcn->hal_buf;
len = msg_body.header.len;
put_cfg_tlv_u32(wcn, &len, cfg_id, value);
body->header.len = len;
body->len = len - sizeof(*body);
ret = wcn36xx_smd_send_and_wait(wcn, body->header.len);
if (ret) {
wcn36xx_err("Sending hal_update_cfg failed\n");
goto out;
}
ret = wcn36xx_smd_rsp_status_check(wcn->hal_buf, wcn->hal_rsp_len);
if (ret) {
wcn36xx_err("hal_update_cfg response failed err=%d\n", ret);
goto out;
}
out:
mutex_unlock(&wcn->hal_mutex);
return ret;
}
static void wcn36xx_smd_rsp_process(struct wcn36xx *wcn, void *buf, size_t len)
{
struct wcn36xx_hal_msg_header *msg_header = buf;
struct wcn36xx_hal_ind_msg *msg_ind;
wcn36xx_dbg_dump(WCN36XX_DBG_SMD_DUMP, "SMD <<< ", buf, len);
switch (msg_header->msg_type) {
case WCN36XX_HAL_START_RSP:
case WCN36XX_HAL_CONFIG_STA_RSP:
case WCN36XX_HAL_CONFIG_BSS_RSP:
case WCN36XX_HAL_ADD_STA_SELF_RSP:
case WCN36XX_HAL_STOP_RSP:
case WCN36XX_HAL_DEL_STA_SELF_RSP:
case WCN36XX_HAL_DELETE_STA_RSP:
case WCN36XX_HAL_INIT_SCAN_RSP:
case WCN36XX_HAL_START_SCAN_RSP:
case WCN36XX_HAL_END_SCAN_RSP:
case WCN36XX_HAL_FINISH_SCAN_RSP:
case WCN36XX_HAL_DOWNLOAD_NV_RSP:
case WCN36XX_HAL_DELETE_BSS_RSP:
case WCN36XX_HAL_SEND_BEACON_RSP:
case WCN36XX_HAL_SET_LINK_ST_RSP:
case WCN36XX_HAL_UPDATE_PROBE_RSP_TEMPLATE_RSP:
case WCN36XX_HAL_SET_BSSKEY_RSP:
case WCN36XX_HAL_SET_STAKEY_RSP:
case WCN36XX_HAL_RMV_STAKEY_RSP:
case WCN36XX_HAL_RMV_BSSKEY_RSP:
case WCN36XX_HAL_ENTER_BMPS_RSP:
case WCN36XX_HAL_SET_POWER_PARAMS_RSP:
case WCN36XX_HAL_EXIT_BMPS_RSP:
case WCN36XX_HAL_KEEP_ALIVE_RSP:
case WCN36XX_HAL_DUMP_COMMAND_RSP:
case WCN36XX_HAL_ADD_BA_SESSION_RSP:
case WCN36XX_HAL_ADD_BA_RSP:
case WCN36XX_HAL_DEL_BA_RSP:
case WCN36XX_HAL_TRIGGER_BA_RSP:
case WCN36XX_HAL_UPDATE_CFG_RSP:
case WCN36XX_HAL_JOIN_RSP:
case WCN36XX_HAL_UPDATE_SCAN_PARAM_RSP:
case WCN36XX_HAL_CH_SWITCH_RSP:
case WCN36XX_HAL_FEATURE_CAPS_EXCHANGE_RSP:
memcpy(wcn->hal_buf, buf, len);
wcn->hal_rsp_len = len;
complete(&wcn->hal_rsp_compl);
break;
case WCN36XX_HAL_OTA_TX_COMPL_IND:
case WCN36XX_HAL_MISSED_BEACON_IND:
case WCN36XX_HAL_DELETE_STA_CONTEXT_IND:
msg_ind = kmalloc(sizeof(*msg_ind), GFP_KERNEL);
if (!msg_ind)
goto nomem;
msg_ind->msg_len = len;
msg_ind->msg = kmalloc(len, GFP_KERNEL);
if (!msg_ind->msg) {
kfree(msg_ind);
nomem:
/*
* FIXME: Do something smarter then just
* printing an error.
*/
wcn36xx_err("Run out of memory while handling SMD_EVENT (%d)\n",
msg_header->msg_type);
break;
}
memcpy(msg_ind->msg, buf, len);
mutex_lock(&wcn->hal_ind_mutex);
list_add_tail(&msg_ind->list, &wcn->hal_ind_queue);
queue_work(wcn->hal_ind_wq, &wcn->hal_ind_work);
mutex_unlock(&wcn->hal_ind_mutex);
wcn36xx_dbg(WCN36XX_DBG_HAL, "indication arrived\n");
break;
default:
wcn36xx_err("SMD_EVENT (%d) not supported\n",
msg_header->msg_type);
}
}
static void wcn36xx_ind_smd_work(struct work_struct *work)
{
struct wcn36xx *wcn =
container_of(work, struct wcn36xx, hal_ind_work);
struct wcn36xx_hal_msg_header *msg_header;
struct wcn36xx_hal_ind_msg *hal_ind_msg;
mutex_lock(&wcn->hal_ind_mutex);
hal_ind_msg = list_first_entry(&wcn->hal_ind_queue,
struct wcn36xx_hal_ind_msg,
list);
msg_header = (struct wcn36xx_hal_msg_header *)hal_ind_msg->msg;
switch (msg_header->msg_type) {
case WCN36XX_HAL_OTA_TX_COMPL_IND:
wcn36xx_smd_tx_compl_ind(wcn,
hal_ind_msg->msg,
hal_ind_msg->msg_len);
break;
case WCN36XX_HAL_MISSED_BEACON_IND:
wcn36xx_smd_missed_beacon_ind(wcn,
hal_ind_msg->msg,
hal_ind_msg->msg_len);
break;
case WCN36XX_HAL_DELETE_STA_CONTEXT_IND:
wcn36xx_smd_delete_sta_context_ind(wcn,
hal_ind_msg->msg,
hal_ind_msg->msg_len);
break;
default:
wcn36xx_err("SMD_EVENT (%d) not supported\n",
msg_header->msg_type);
}
list_del(wcn->hal_ind_queue.next);
kfree(hal_ind_msg->msg);
kfree(hal_ind_msg);
mutex_unlock(&wcn->hal_ind_mutex);
}
int wcn36xx_smd_open(struct wcn36xx *wcn)
{
int ret = 0;
wcn->hal_ind_wq = create_freezable_workqueue("wcn36xx_smd_ind");
if (!wcn->hal_ind_wq) {
wcn36xx_err("failed to allocate wq\n");
ret = -ENOMEM;
goto out;
}
INIT_WORK(&wcn->hal_ind_work, wcn36xx_ind_smd_work);
INIT_LIST_HEAD(&wcn->hal_ind_queue);
mutex_init(&wcn->hal_ind_mutex);
ret = wcn->ctrl_ops->open(wcn, wcn36xx_smd_rsp_process);
if (ret) {
wcn36xx_err("failed to open control channel\n");
goto free_wq;
}
return ret;
free_wq:
destroy_workqueue(wcn->hal_ind_wq);
out:
return ret;
}
void wcn36xx_smd_close(struct wcn36xx *wcn)
{
wcn->ctrl_ops->close();
destroy_workqueue(wcn->hal_ind_wq);
mutex_destroy(&wcn->hal_ind_mutex);
}
| gpl-2.0 |
CyanogenMod/android_kernel_samsung_trelte | drivers/gpu/arm/midgard/mali_kbase_config.c | 243 | 20372 | /*
*
* (C) COPYRIGHT ARM Limited. All rights reserved.
*
* This program is free software and is provided to you under the terms of the
* GNU General Public License version 2 as published by the Free Software
* Foundation, and any use by you of this program is subject to the terms
* of such GNU licence.
*
* A copy of the licence is included with the program, and can also be obtained
* from Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include <mali_kbase.h>
#include <mali_kbase_defs.h>
#include <mali_kbase_cpuprops.h>
#ifdef CONFIG_UMP
#include <linux/ump-common.h>
#endif /* CONFIG_UMP */
/* Specifies how many attributes are permitted in the config (excluding terminating attribute).
* This is used in validation function so we can detect if configuration is properly terminated. This value can be
* changed if we need to introduce more attributes or many memory regions need to be defined */
#define ATTRIBUTE_COUNT_MAX 32
/* right now we allow only 2 memory attributes (excluding termination attribute) */
#define MEMORY_ATTRIBUTE_COUNT_MAX 2
/* Limits for gpu frequency configuration parameters. These will use for config validation. */
#define MAX_GPU_ALLOWED_FREQ_KHZ 1000000
#define MIN_GPU_ALLOWED_FREQ_KHZ 1
/* Default irq throttle time. This is the default desired minimum time in between two consecutive
* interrupts from the gpu. The irq throttle gpu register is set after this value. */
#define DEFAULT_IRQ_THROTTLE_TIME_US 20
/*** Begin Scheduling defaults ***/
/**
* Default scheduling tick granuality, in nanoseconds
*/
#define DEFAULT_JS_SCHEDULING_TICK_NS 100000000u /* 100ms */
/**
* Default minimum number of scheduling ticks before jobs are soft-stopped.
*
* This defines the time-slice for a job (which may be different from that of a context)
*/
#define DEFAULT_JS_SOFT_STOP_TICKS 1 /* Between 0.1 and 0.2s before soft-stop */
/**
* Default minimum number of scheduling ticks before jobs are hard-stopped
*/
#define DEFAULT_JS_HARD_STOP_TICKS_SS_HW_ISSUE_8408 12 /* 1.2s before hard-stop, for a certain GLES2 test at 128x128 (bound by combined vertex+tiler job) */
#define DEFAULT_JS_HARD_STOP_TICKS_SS 2 /* Between 0.2 and 0.3s before hard-stop */
/**
* Default minimum number of scheduling ticks before jobs are hard-stopped
* during dumping
*/
#define DEFAULT_JS_HARD_STOP_TICKS_NSS 600 /* 60s @ 100ms tick */
/**
* Default minimum number of scheduling ticks before the GPU is reset
* to clear a "stuck" job
*/
#define DEFAULT_JS_RESET_TICKS_SS_HW_ISSUE_8408 18 /* 1.8s before resetting GPU, for a certain GLES2 test at 128x128 (bound by combined vertex+tiler job) */
#define DEFAULT_JS_RESET_TICKS_SS 3 /* 0.3-0.4s before GPU is reset */
/**
* Default minimum number of scheduling ticks before the GPU is reset
* to clear a "stuck" job during dumping.
*/
#define DEFAULT_JS_RESET_TICKS_NSS 601 /* 60.1s @ 100ms tick */
/**
* Number of milliseconds given for other jobs on the GPU to be
* soft-stopped when the GPU needs to be reset.
*/
#define DEFAULT_JS_RESET_TIMEOUT_MS 3000
/**
* Default timeslice that a context is scheduled in for, in nanoseconds.
*
* When a context has used up this amount of time across its jobs, it is
* scheduled out to let another run.
*
* @note the resolution is nanoseconds (ns) here, because that's the format
* often used by the OS.
*/
#define DEFAULT_JS_CTX_TIMESLICE_NS 50000000 /* 0.05s - at 20fps a ctx does at least 1 frame before being scheduled out. At 40fps, 2 frames, etc */
/**
* Default initial runtime of a context for CFS, in ticks.
*
* This value is relative to that of the least-run context, and defines where
* in the CFS queue a new context is added.
*/
#define DEFAULT_JS_CFS_CTX_RUNTIME_INIT_SLICES 1
/**
* Default minimum runtime value of a context for CFS, in ticks.
*
* This value is relative to that of the least-run context. This prevents
* "stored-up timeslices" DoS attacks.
*/
#define DEFAULT_JS_CFS_CTX_RUNTIME_MIN_SLICES 2
/**
* Default setting for whether to prefer security or performance.
*
* Currently affects only r0p0-15dev0 HW and earlier.
*/
#define DEFAULT_SECURE_BUT_LOSS_OF_PERFORMANCE MALI_FALSE
/**
* Default setting for read Address ID limiting on AXI.
*/
#define DEFAULT_ARID_LIMIT KBASE_AID_32
/**
* Default setting for write Address ID limiting on AXI.
*/
#define DEFAULT_AWID_LIMIT KBASE_AID_32
/**
* Default setting for using alternative hardware counters.
*/
#define DEFAULT_ALTERNATIVE_HWC MALI_FALSE
/*** End Scheduling defaults ***/
/*** Begin Power Manager defaults */
#define DEFAULT_PM_DVFS_FREQ 500 /* Milliseconds */
/**
* Default poweroff tick granuality, in nanoseconds
*/
#define DEFAULT_PM_SHADER_POWEROFF_TIME 400 /* 400us */
/**
* Default number of poweroff ticks before shader cores are powered off
*/
#define DEFAULT_PM_GPU_POWEROFF_TIME 2 /* 400-800us */
/**
* Default number of poweroff ticks before GPU is powered off
*/
#define DEFAULT_PM_POWEROFF_TICK_GPU 2 /* 400-800us */
/*** End Power Manager defaults ***/
/**
* Default value for KBASE_CONFIG_ATTR_CPU_SPEED_FUNC.
* Points to @ref kbase_cpuprops_get_default_clock_speed.
*/
#define DEFAULT_CPU_SPEED_FUNC ((uintptr_t)kbase_cpuprops_get_default_clock_speed)
int kbasep_get_config_attribute_count(const kbase_attribute *attributes)
{
int count = 1;
if (!attributes)
return -EINVAL;
while (attributes->id != KBASE_CONFIG_ATTR_END) {
attributes++;
count++;
}
return count;
}
const kbase_attribute *kbasep_get_next_attribute(const kbase_attribute *attributes, int attribute_id)
{
KBASE_DEBUG_ASSERT(attributes != NULL);
while (attributes->id != KBASE_CONFIG_ATTR_END) {
if (attributes->id == attribute_id)
return attributes;
attributes++;
}
return NULL;
}
KBASE_EXPORT_TEST_API(kbasep_get_next_attribute)
uintptr_t kbasep_get_config_value(struct kbase_device *kbdev, const kbase_attribute *attributes, int attribute_id)
{
const kbase_attribute *attr;
KBASE_DEBUG_ASSERT(attributes != NULL);
attr = kbasep_get_next_attribute(attributes, attribute_id);
if (attr != NULL)
return attr->data;
/* default values */
switch (attribute_id) {
case KBASE_CONFIG_ATTR_MEMORY_PER_PROCESS_LIMIT:
return (uintptr_t) -1;
#ifdef CONFIG_UMP
case KBASE_CONFIG_ATTR_UMP_DEVICE:
return UMP_DEVICE_W_SHIFT;
#endif /* CONFIG_UMP */
case KBASE_CONFIG_ATTR_MEMORY_OS_SHARED_MAX:
return (uintptr_t) -1;
case KBASE_CONFIG_ATTR_MEMORY_OS_SHARED_PERF_GPU:
return KBASE_MEM_PERF_NORMAL;
case KBASE_CONFIG_ATTR_GPU_IRQ_THROTTLE_TIME_US:
return DEFAULT_IRQ_THROTTLE_TIME_US;
/* Begin scheduling defaults */
case KBASE_CONFIG_ATTR_JS_SCHEDULING_TICK_NS:
return DEFAULT_JS_SCHEDULING_TICK_NS;
case KBASE_CONFIG_ATTR_JS_SOFT_STOP_TICKS:
return DEFAULT_JS_SOFT_STOP_TICKS;
case KBASE_CONFIG_ATTR_JS_HARD_STOP_TICKS_SS:
if (kbase_hw_has_issue(kbdev, BASE_HW_ISSUE_8408))
return DEFAULT_JS_HARD_STOP_TICKS_SS_HW_ISSUE_8408;
else
return DEFAULT_JS_HARD_STOP_TICKS_SS;
case KBASE_CONFIG_ATTR_JS_HARD_STOP_TICKS_NSS:
return DEFAULT_JS_HARD_STOP_TICKS_NSS;
case KBASE_CONFIG_ATTR_JS_CTX_TIMESLICE_NS:
return DEFAULT_JS_CTX_TIMESLICE_NS;
case KBASE_CONFIG_ATTR_JS_CFS_CTX_RUNTIME_INIT_SLICES:
return DEFAULT_JS_CFS_CTX_RUNTIME_INIT_SLICES;
case KBASE_CONFIG_ATTR_JS_CFS_CTX_RUNTIME_MIN_SLICES:
return DEFAULT_JS_CFS_CTX_RUNTIME_MIN_SLICES;
case KBASE_CONFIG_ATTR_JS_RESET_TICKS_SS:
if (kbase_hw_has_issue(kbdev, BASE_HW_ISSUE_8408))
return DEFAULT_JS_RESET_TICKS_SS_HW_ISSUE_8408;
else
return DEFAULT_JS_RESET_TICKS_SS;
case KBASE_CONFIG_ATTR_JS_RESET_TICKS_NSS:
return DEFAULT_JS_RESET_TICKS_NSS;
case KBASE_CONFIG_ATTR_JS_RESET_TIMEOUT_MS:
return DEFAULT_JS_RESET_TIMEOUT_MS;
/* End scheduling defaults */
case KBASE_CONFIG_ATTR_POWER_MANAGEMENT_CALLBACKS:
return 0;
case KBASE_CONFIG_ATTR_PLATFORM_FUNCS:
return 0;
case KBASE_CONFIG_ATTR_SECURE_BUT_LOSS_OF_PERFORMANCE:
return DEFAULT_SECURE_BUT_LOSS_OF_PERFORMANCE;
case KBASE_CONFIG_ATTR_CPU_SPEED_FUNC:
return DEFAULT_CPU_SPEED_FUNC;
case KBASE_CONFIG_ATTR_GPU_SPEED_FUNC:
return 0;
case KBASE_CONFIG_ATTR_ARID_LIMIT:
return DEFAULT_ARID_LIMIT;
case KBASE_CONFIG_ATTR_AWID_LIMIT:
return DEFAULT_AWID_LIMIT;
case KBASE_CONFIG_ATTR_ALTERNATIVE_HWC:
return DEFAULT_ALTERNATIVE_HWC;
case KBASE_CONFIG_ATTR_POWER_MANAGEMENT_DVFS_FREQ:
return DEFAULT_PM_DVFS_FREQ;
case KBASE_CONFIG_ATTR_PM_SHADER_POWEROFF_TIME:
return DEFAULT_PM_SHADER_POWEROFF_TIME;
default:
KBASE_DEBUG_PRINT_ERROR(KBASE_CORE, "kbasep_get_config_value. Cannot get value of attribute with id=%d and no default value defined", attribute_id);
return 0;
}
}
KBASE_EXPORT_TEST_API(kbasep_get_config_value)
mali_bool kbasep_platform_device_init(kbase_device *kbdev)
{
kbase_platform_funcs_conf *platform_funcs;
platform_funcs = (kbase_platform_funcs_conf *) kbasep_get_config_value(kbdev, kbdev->config_attributes, KBASE_CONFIG_ATTR_PLATFORM_FUNCS);
if (platform_funcs) {
if (platform_funcs->platform_init_func)
return platform_funcs->platform_init_func(kbdev);
}
return MALI_TRUE;
}
void kbasep_platform_device_term(kbase_device *kbdev)
{
kbase_platform_funcs_conf *platform_funcs;
platform_funcs = (kbase_platform_funcs_conf *) kbasep_get_config_value(kbdev, kbdev->config_attributes, KBASE_CONFIG_ATTR_PLATFORM_FUNCS);
if (platform_funcs) {
if (platform_funcs->platform_term_func)
platform_funcs->platform_term_func(kbdev);
}
}
#ifdef CONFIG_UMP
static mali_bool kbasep_validate_ump_device(int ump_device)
{
mali_bool valid;
switch (ump_device) {
case UMP_DEVICE_W_SHIFT:
case UMP_DEVICE_X_SHIFT:
case UMP_DEVICE_Y_SHIFT:
case UMP_DEVICE_Z_SHIFT:
valid = MALI_TRUE;
break;
default:
valid = MALI_FALSE;
break;
}
return valid;
}
#endif /* CONFIG_UMP */
static mali_bool kbasep_validate_memory_performance(kbase_memory_performance performance)
{
return performance <= KBASE_MEM_PERF_MAX_VALUE;
}
static mali_bool kbasep_validate_memory_resource(const kbase_memory_resource *memory_resource)
{
KBASE_DEBUG_ASSERT(memory_resource != NULL);
if (memory_resource->name == NULL) {
KBASE_DEBUG_PRINT_WARN(KBASE_CORE, "Unnamed memory region found");
return MALI_FALSE;
}
if (memory_resource->base & ((1 << PAGE_SHIFT) - 1)) {
KBASE_DEBUG_PRINT_WARN(KBASE_CORE, "Base address of \"%s\" memory region is not page aligned", memory_resource->name);
return MALI_FALSE;
}
if (memory_resource->size & ((1 << PAGE_SHIFT) - 1)) {
KBASE_DEBUG_PRINT_WARN(KBASE_CORE, "Size of \"%s\" memory region is not a multiple of page size", memory_resource->name);
return MALI_FALSE;
}
if (memory_resource->attributes != NULL) { /* we allow NULL attribute list */
int i;
for (i = 0; memory_resource->attributes[i].id != KBASE_MEM_ATTR_END; i++) {
if (i >= MEMORY_ATTRIBUTE_COUNT_MAX) {
KBASE_DEBUG_PRINT_WARN(KBASE_CORE, "More than MEMORY_ATTRIBUTE_COUNT_MAX=%d configuration attributes defined. Is memory attribute list properly terminated?", MEMORY_ATTRIBUTE_COUNT_MAX);
return MALI_FALSE;
}
switch (memory_resource->attributes[i].id) {
case KBASE_MEM_ATTR_PERF_CPU:
if (MALI_TRUE != kbasep_validate_memory_performance((kbase_memory_performance) memory_resource->attributes[i].data)) {
KBASE_DEBUG_PRINT_WARN(KBASE_CORE, "CPU performance of \"%s\" region is invalid: %d", memory_resource->name, (kbase_memory_performance) memory_resource->attributes[i].data);
return MALI_FALSE;
}
break;
case KBASE_MEM_ATTR_PERF_GPU:
if (MALI_TRUE != kbasep_validate_memory_performance((kbase_memory_performance) memory_resource->attributes[i].data)) {
KBASE_DEBUG_PRINT_WARN(KBASE_CORE, "GPU performance of \"%s\" region is invalid: %d", memory_resource->name, (kbase_memory_performance) memory_resource->attributes[i].data);
return MALI_FALSE;
}
break;
default:
KBASE_DEBUG_PRINT_WARN(KBASE_CORE, "Invalid memory attribute found in \"%s\" memory region: %d", memory_resource->name, memory_resource->attributes[i].id);
return MALI_FALSE;
}
}
}
return MALI_TRUE;
}
static mali_bool kbasep_validate_gpu_clock_freq(kbase_device *kbdev, const kbase_attribute *attributes)
{
uintptr_t freq_min = kbasep_get_config_value(kbdev, attributes, KBASE_CONFIG_ATTR_GPU_FREQ_KHZ_MIN);
uintptr_t freq_max = kbasep_get_config_value(kbdev, attributes, KBASE_CONFIG_ATTR_GPU_FREQ_KHZ_MAX);
if ((freq_min > MAX_GPU_ALLOWED_FREQ_KHZ) || (freq_min < MIN_GPU_ALLOWED_FREQ_KHZ) || (freq_max > MAX_GPU_ALLOWED_FREQ_KHZ) || (freq_max < MIN_GPU_ALLOWED_FREQ_KHZ) || (freq_min > freq_max)) {
KBASE_DEBUG_PRINT_WARN(KBASE_CORE, "Invalid GPU frequencies found in configuration: min=%ldkHz, max=%ldkHz.", freq_min, freq_max);
return MALI_FALSE;
}
return MALI_TRUE;
}
static mali_bool kbasep_validate_pm_callback(const kbase_pm_callback_conf *callbacks)
{
if (callbacks == NULL) {
/* Having no callbacks is valid */
return MALI_TRUE;
}
if ((callbacks->power_off_callback != NULL && callbacks->power_on_callback == NULL) || (callbacks->power_off_callback == NULL && callbacks->power_on_callback != NULL)) {
KBASE_DEBUG_PRINT_WARN(KBASE_CORE, "Invalid power management callbacks: Only one of power_off_callback and power_on_callback was specified");
return MALI_FALSE;
}
return MALI_TRUE;
}
static mali_bool kbasep_validate_cpu_speed_func(kbase_cpuprops_clock_speed_function fcn)
{
return fcn != NULL;
}
mali_bool kbasep_validate_configuration_attributes(kbase_device *kbdev, const kbase_attribute *attributes)
{
int i;
mali_bool had_gpu_freq_min = MALI_FALSE, had_gpu_freq_max = MALI_FALSE;
KBASE_DEBUG_ASSERT(attributes);
for (i = 0; attributes[i].id != KBASE_CONFIG_ATTR_END; i++) {
if (i >= ATTRIBUTE_COUNT_MAX) {
KBASE_DEBUG_PRINT_WARN(KBASE_CORE, "More than ATTRIBUTE_COUNT_MAX=%d configuration attributes defined. Is attribute list properly terminated?", ATTRIBUTE_COUNT_MAX);
return MALI_FALSE;
}
switch (attributes[i].id) {
case KBASE_CONFIG_ATTR_MEMORY_RESOURCE:
if (MALI_FALSE == kbasep_validate_memory_resource((kbase_memory_resource *) attributes[i].data)) {
KBASE_DEBUG_PRINT_WARN(KBASE_CORE, "Invalid memory region found in configuration");
return MALI_FALSE;
}
break;
case KBASE_CONFIG_ATTR_MEMORY_OS_SHARED_MAX:
/* Some shared memory is required for GPU page tables, see MIDBASE-1534 */
if (0 == attributes[i].data) {
KBASE_DEBUG_PRINT_WARN(KBASE_CORE, "Maximum OS Shared Memory Maximum is set to 0 which is not supported");
return MALI_FALSE;
}
break;
case KBASE_CONFIG_ATTR_MEMORY_OS_SHARED_PERF_GPU:
if (MALI_FALSE == kbasep_validate_memory_performance((kbase_memory_performance) attributes[i].data)) {
KBASE_DEBUG_PRINT_WARN(KBASE_CORE, "Shared OS memory GPU performance attribute has invalid value: %d", (kbase_memory_performance) attributes[i].data);
return MALI_FALSE;
}
break;
case KBASE_CONFIG_ATTR_MEMORY_PER_PROCESS_LIMIT:
/* any value is allowed */
break;
#ifdef CONFIG_UMP
case KBASE_CONFIG_ATTR_UMP_DEVICE:
if (MALI_FALSE == kbasep_validate_ump_device(attributes[i].data)) {
KBASE_DEBUG_PRINT_WARN(KBASE_CORE, "Unknown UMP device found in configuration: %d", (int)attributes[i].data);
return MALI_FALSE;
}
break;
#endif /* CONFIG_UMP */
case KBASE_CONFIG_ATTR_GPU_FREQ_KHZ_MIN:
had_gpu_freq_min = MALI_TRUE;
if (MALI_FALSE == kbasep_validate_gpu_clock_freq(kbdev, attributes)) {
/* Warning message handled by kbasep_validate_gpu_clock_freq() */
return MALI_FALSE;
}
break;
case KBASE_CONFIG_ATTR_GPU_FREQ_KHZ_MAX:
had_gpu_freq_max = MALI_TRUE;
if (MALI_FALSE == kbasep_validate_gpu_clock_freq(kbdev, attributes)) {
/* Warning message handled by kbasep_validate_gpu_clock_freq() */
return MALI_FALSE;
}
break;
/* Only non-zero unsigned 32-bit values accepted */
case KBASE_CONFIG_ATTR_JS_SCHEDULING_TICK_NS:
#if CSTD_CPU_64BIT
if (attributes[i].data == 0u || (u64) attributes[i].data > (u64) U32_MAX)
#else
if (attributes[i].data == 0u)
#endif
{
KBASE_DEBUG_PRINT_WARN(KBASE_CORE, "Invalid Job Scheduling Configuration attribute for " "KBASE_CONFIG_ATTR_JS_SCHEDULING_TICKS_NS: %d", (int)attributes[i].data);
return MALI_FALSE;
}
break;
/* All these Job Scheduling attributes are FALLTHROUGH: only unsigned 32-bit values accepted */
case KBASE_CONFIG_ATTR_JS_SOFT_STOP_TICKS:
case KBASE_CONFIG_ATTR_JS_HARD_STOP_TICKS_SS:
case KBASE_CONFIG_ATTR_JS_HARD_STOP_TICKS_NSS:
case KBASE_CONFIG_ATTR_JS_RESET_TICKS_SS:
case KBASE_CONFIG_ATTR_JS_RESET_TICKS_NSS:
case KBASE_CONFIG_ATTR_JS_RESET_TIMEOUT_MS:
case KBASE_CONFIG_ATTR_JS_CTX_TIMESLICE_NS:
case KBASE_CONFIG_ATTR_JS_CFS_CTX_RUNTIME_INIT_SLICES:
case KBASE_CONFIG_ATTR_JS_CFS_CTX_RUNTIME_MIN_SLICES:
#if CSTD_CPU_64BIT
if ((u64) attributes[i].data > (u64) U32_MAX) {
KBASE_DEBUG_PRINT_WARN(KBASE_CORE, "Job Scheduling Configuration attribute exceeds 32-bits: " "id==%d val==%d", attributes[i].id, (int)attributes[i].data);
return MALI_FALSE;
}
#endif
break;
case KBASE_CONFIG_ATTR_GPU_IRQ_THROTTLE_TIME_US:
#if CSTD_CPU_64BIT
if ((u64) attributes[i].data > (u64) U32_MAX) {
KBASE_DEBUG_PRINT_WARN(KBASE_CORE, "IRQ throttle time attribute exceeds 32-bits: " "id==%d val==%d", attributes[i].id, (int)attributes[i].data);
return MALI_FALSE;
}
#endif
break;
case KBASE_CONFIG_ATTR_POWER_MANAGEMENT_CALLBACKS:
if (MALI_FALSE == kbasep_validate_pm_callback((kbase_pm_callback_conf *) attributes[i].data)) {
/* Warning message handled by kbasep_validate_pm_callback() */
return MALI_FALSE;
}
break;
case KBASE_CONFIG_ATTR_SECURE_BUT_LOSS_OF_PERFORMANCE:
if (attributes[i].data != MALI_TRUE && attributes[i].data != MALI_FALSE) {
KBASE_DEBUG_PRINT_WARN(KBASE_CORE, "Value for KBASE_CONFIG_ATTR_SECURE_BUT_LOSS_OF_PERFORMANCE was not " "MALI_TRUE or MALI_FALSE: %u", (unsigned int)attributes[i].data);
return MALI_FALSE;
}
break;
case KBASE_CONFIG_ATTR_CPU_SPEED_FUNC:
if (MALI_FALSE == kbasep_validate_cpu_speed_func((kbase_cpuprops_clock_speed_function) attributes[i].data)) {
KBASE_DEBUG_PRINT_WARN(KBASE_CORE, "Invalid function pointer in KBASE_CONFIG_ATTR_CPU_SPEED_FUNC");
return MALI_FALSE;
}
break;
case KBASE_CONFIG_ATTR_GPU_SPEED_FUNC:
if (0 == attributes[i].data) {
KBASE_DEBUG_PRINT_WARN(KBASE_CORE, "Invalid function pointer in KBASE_CONFIG_ATTR_GPU_SPEED_FUNC");
return MALI_FALSE;
}
break;
case KBASE_CONFIG_ATTR_PLATFORM_FUNCS:
/* any value is allowed */
break;
case KBASE_CONFIG_ATTR_AWID_LIMIT:
case KBASE_CONFIG_ATTR_ARID_LIMIT:
if ((u32) attributes[i].data > 0x3) {
KBASE_DEBUG_PRINT_WARN(KBASE_CORE, "Invalid AWID or ARID limit");
return MALI_FALSE;
}
break;
case KBASE_CONFIG_ATTR_ALTERNATIVE_HWC:
if (attributes[i].data != MALI_TRUE && attributes[i].data != MALI_FALSE) {
KBASE_DEBUG_PRINT_WARN(KBASE_CORE, "Value for KBASE_CONFIG_ATTR_ALTERNATIVE_HWC was not " "MALI_TRUE or MALI_FALSE: %u", (unsigned int)attributes[i].data);
return MALI_FALSE;
}
break;
case KBASE_CONFIG_ATTR_POWER_MANAGEMENT_DVFS_FREQ:
#if CSTD_CPU_64BIT
if ((u64) attributes[i].data > (u64) U32_MAX) {
KBASE_DEBUG_PRINT_WARN(KBASE_CORE, "PM DVFS interval exceeds 32-bits: " "id==%d val==%d", attributes[i].id, (int)attributes[i].data);
return MALI_FALSE;
}
#endif
break;
case KBASE_CONFIG_ATTR_PM_SHADER_POWEROFF_TIME:
#if CSTD_CPU_64BIT
if ((u64) attributes[i].data > (u64) U32_MAX) {
KBASE_DEBUG_PRINT_WARN(KBASE_CORE, "PM shader poweroff time exceeds 32-bits: " "id==%d val==%d", attributes[i].id, (int)attributes[i].data);
return MALI_FALSE;
}
#endif
break;
default:
KBASE_DEBUG_PRINT_WARN(KBASE_CORE, "Invalid attribute found in configuration: %d", attributes[i].id);
return MALI_FALSE;
}
}
if (!had_gpu_freq_min) {
KBASE_DEBUG_PRINT_WARN(KBASE_CORE, "Configuration does not include mandatory attribute KBASE_CONFIG_ATTR_GPU_FREQ_KHZ_MIN");
return MALI_FALSE;
}
if (!had_gpu_freq_max) {
KBASE_DEBUG_PRINT_WARN(KBASE_CORE, "Configuration does not include mandatory attribute KBASE_CONFIG_ATTR_GPU_FREQ_KHZ_MAX");
return MALI_FALSE;
}
return MALI_TRUE;
}
| gpl-2.0 |
arunov/Goldeneye-Bufflehead | drivers/i2c/busses/i2c-amd756.c | 243 | 11391 | /*
Copyright (c) 1999-2002 Merlin Hughes <merlin@merlin.org>
Shamelessly ripped from i2c-piix4.c:
Copyright (c) 1998, 1999 Frodo Looijaard <frodol@dds.nl> and
Philip Edelbrock <phil@netroedge.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
2002-04-08: Added nForce support. (Csaba Halasz)
2002-10-03: Fixed nForce PnP I/O port. (Michael Steil)
2002-12-28: Rewritten into something that resembles a Linux driver (hch)
2003-11-29: Added back AMD8111 removed by the previous rewrite.
(Philip Pokorny)
*/
/*
Supports AMD756, AMD766, AMD768, AMD8111 and nVidia nForce
Note: we assume there can only be one device, with one SMBus interface.
*/
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/stddef.h>
#include <linux/ioport.h>
#include <linux/i2c.h>
#include <linux/acpi.h>
#include <linux/io.h>
/* AMD756 SMBus address offsets */
#define SMB_ADDR_OFFSET 0xE0
#define SMB_IOSIZE 16
#define SMB_GLOBAL_STATUS (0x0 + amd756_ioport)
#define SMB_GLOBAL_ENABLE (0x2 + amd756_ioport)
#define SMB_HOST_ADDRESS (0x4 + amd756_ioport)
#define SMB_HOST_DATA (0x6 + amd756_ioport)
#define SMB_HOST_COMMAND (0x8 + amd756_ioport)
#define SMB_HOST_BLOCK_DATA (0x9 + amd756_ioport)
#define SMB_HAS_DATA (0xA + amd756_ioport)
#define SMB_HAS_DEVICE_ADDRESS (0xC + amd756_ioport)
#define SMB_HAS_HOST_ADDRESS (0xE + amd756_ioport)
#define SMB_SNOOP_ADDRESS (0xF + amd756_ioport)
/* PCI Address Constants */
/* address of I/O space */
#define SMBBA 0x058 /* mh */
#define SMBBANFORCE 0x014
/* general configuration */
#define SMBGCFG 0x041 /* mh */
/* silicon revision code */
#define SMBREV 0x008
/* Other settings */
#define MAX_TIMEOUT 500
/* AMD756 constants */
#define AMD756_QUICK 0x00
#define AMD756_BYTE 0x01
#define AMD756_BYTE_DATA 0x02
#define AMD756_WORD_DATA 0x03
#define AMD756_PROCESS_CALL 0x04
#define AMD756_BLOCK_DATA 0x05
static struct pci_driver amd756_driver;
static unsigned short amd756_ioport;
/*
SMBUS event = I/O 28-29 bit 11
see E0 for the status bits and enabled in E2
*/
#define GS_ABRT_STS (1 << 0)
#define GS_COL_STS (1 << 1)
#define GS_PRERR_STS (1 << 2)
#define GS_HST_STS (1 << 3)
#define GS_HCYC_STS (1 << 4)
#define GS_TO_STS (1 << 5)
#define GS_SMB_STS (1 << 11)
#define GS_CLEAR_STS (GS_ABRT_STS | GS_COL_STS | GS_PRERR_STS | \
GS_HCYC_STS | GS_TO_STS )
#define GE_CYC_TYPE_MASK (7)
#define GE_HOST_STC (1 << 3)
#define GE_ABORT (1 << 5)
static int amd756_transaction(struct i2c_adapter *adap)
{
int temp;
int result = 0;
int timeout = 0;
dev_dbg(&adap->dev, "Transaction (pre): GS=%04x, GE=%04x, ADD=%04x, "
"DAT=%04x\n", inw_p(SMB_GLOBAL_STATUS),
inw_p(SMB_GLOBAL_ENABLE), inw_p(SMB_HOST_ADDRESS),
inb_p(SMB_HOST_DATA));
/* Make sure the SMBus host is ready to start transmitting */
if ((temp = inw_p(SMB_GLOBAL_STATUS)) & (GS_HST_STS | GS_SMB_STS)) {
dev_dbg(&adap->dev, "SMBus busy (%04x). Waiting...\n", temp);
do {
msleep(1);
temp = inw_p(SMB_GLOBAL_STATUS);
} while ((temp & (GS_HST_STS | GS_SMB_STS)) &&
(timeout++ < MAX_TIMEOUT));
/* If the SMBus is still busy, we give up */
if (timeout > MAX_TIMEOUT) {
dev_dbg(&adap->dev, "Busy wait timeout (%04x)\n", temp);
goto abort;
}
timeout = 0;
}
/* start the transaction by setting the start bit */
outw_p(inw(SMB_GLOBAL_ENABLE) | GE_HOST_STC, SMB_GLOBAL_ENABLE);
/* We will always wait for a fraction of a second! */
do {
msleep(1);
temp = inw_p(SMB_GLOBAL_STATUS);
} while ((temp & GS_HST_STS) && (timeout++ < MAX_TIMEOUT));
/* If the SMBus is still busy, we give up */
if (timeout > MAX_TIMEOUT) {
dev_dbg(&adap->dev, "Completion timeout!\n");
goto abort;
}
if (temp & GS_PRERR_STS) {
result = -ENXIO;
dev_dbg(&adap->dev, "SMBus Protocol error (no response)!\n");
}
if (temp & GS_COL_STS) {
result = -EIO;
dev_warn(&adap->dev, "SMBus collision!\n");
}
if (temp & GS_TO_STS) {
result = -ETIMEDOUT;
dev_dbg(&adap->dev, "SMBus protocol timeout!\n");
}
if (temp & GS_HCYC_STS)
dev_dbg(&adap->dev, "SMBus protocol success!\n");
outw_p(GS_CLEAR_STS, SMB_GLOBAL_STATUS);
#ifdef DEBUG
if (((temp = inw_p(SMB_GLOBAL_STATUS)) & GS_CLEAR_STS) != 0x00) {
dev_dbg(&adap->dev,
"Failed reset at end of transaction (%04x)\n", temp);
}
#endif
dev_dbg(&adap->dev,
"Transaction (post): GS=%04x, GE=%04x, ADD=%04x, DAT=%04x\n",
inw_p(SMB_GLOBAL_STATUS), inw_p(SMB_GLOBAL_ENABLE),
inw_p(SMB_HOST_ADDRESS), inb_p(SMB_HOST_DATA));
return result;
abort:
dev_warn(&adap->dev, "Sending abort\n");
outw_p(inw(SMB_GLOBAL_ENABLE) | GE_ABORT, SMB_GLOBAL_ENABLE);
msleep(100);
outw_p(GS_CLEAR_STS, SMB_GLOBAL_STATUS);
return -EIO;
}
/* Return negative errno on error. */
static s32 amd756_access(struct i2c_adapter * adap, u16 addr,
unsigned short flags, char read_write,
u8 command, int size, union i2c_smbus_data * data)
{
int i, len;
int status;
switch (size) {
case I2C_SMBUS_QUICK:
outw_p(((addr & 0x7f) << 1) | (read_write & 0x01),
SMB_HOST_ADDRESS);
size = AMD756_QUICK;
break;
case I2C_SMBUS_BYTE:
outw_p(((addr & 0x7f) << 1) | (read_write & 0x01),
SMB_HOST_ADDRESS);
if (read_write == I2C_SMBUS_WRITE)
outb_p(command, SMB_HOST_DATA);
size = AMD756_BYTE;
break;
case I2C_SMBUS_BYTE_DATA:
outw_p(((addr & 0x7f) << 1) | (read_write & 0x01),
SMB_HOST_ADDRESS);
outb_p(command, SMB_HOST_COMMAND);
if (read_write == I2C_SMBUS_WRITE)
outw_p(data->byte, SMB_HOST_DATA);
size = AMD756_BYTE_DATA;
break;
case I2C_SMBUS_WORD_DATA:
outw_p(((addr & 0x7f) << 1) | (read_write & 0x01),
SMB_HOST_ADDRESS);
outb_p(command, SMB_HOST_COMMAND);
if (read_write == I2C_SMBUS_WRITE)
outw_p(data->word, SMB_HOST_DATA); /* TODO: endian???? */
size = AMD756_WORD_DATA;
break;
case I2C_SMBUS_BLOCK_DATA:
outw_p(((addr & 0x7f) << 1) | (read_write & 0x01),
SMB_HOST_ADDRESS);
outb_p(command, SMB_HOST_COMMAND);
if (read_write == I2C_SMBUS_WRITE) {
len = data->block[0];
if (len < 0)
len = 0;
if (len > 32)
len = 32;
outw_p(len, SMB_HOST_DATA);
/* i = inw_p(SMBHSTCNT); Reset SMBBLKDAT */
for (i = 1; i <= len; i++)
outb_p(data->block[i],
SMB_HOST_BLOCK_DATA);
}
size = AMD756_BLOCK_DATA;
break;
default:
dev_warn(&adap->dev, "Unsupported transaction %d\n", size);
return -EOPNOTSUPP;
}
/* How about enabling interrupts... */
outw_p(size & GE_CYC_TYPE_MASK, SMB_GLOBAL_ENABLE);
status = amd756_transaction(adap);
if (status)
return status;
if ((read_write == I2C_SMBUS_WRITE) || (size == AMD756_QUICK))
return 0;
switch (size) {
case AMD756_BYTE:
data->byte = inw_p(SMB_HOST_DATA);
break;
case AMD756_BYTE_DATA:
data->byte = inw_p(SMB_HOST_DATA);
break;
case AMD756_WORD_DATA:
data->word = inw_p(SMB_HOST_DATA); /* TODO: endian???? */
break;
case AMD756_BLOCK_DATA:
data->block[0] = inw_p(SMB_HOST_DATA) & 0x3f;
if(data->block[0] > 32)
data->block[0] = 32;
/* i = inw_p(SMBHSTCNT); Reset SMBBLKDAT */
for (i = 1; i <= data->block[0]; i++)
data->block[i] = inb_p(SMB_HOST_BLOCK_DATA);
break;
}
return 0;
}
static u32 amd756_func(struct i2c_adapter *adapter)
{
return I2C_FUNC_SMBUS_QUICK | I2C_FUNC_SMBUS_BYTE |
I2C_FUNC_SMBUS_BYTE_DATA | I2C_FUNC_SMBUS_WORD_DATA |
I2C_FUNC_SMBUS_BLOCK_DATA;
}
static const struct i2c_algorithm smbus_algorithm = {
.smbus_xfer = amd756_access,
.functionality = amd756_func,
};
struct i2c_adapter amd756_smbus = {
.owner = THIS_MODULE,
.class = I2C_CLASS_HWMON | I2C_CLASS_SPD,
.algo = &smbus_algorithm,
};
enum chiptype { AMD756, AMD766, AMD768, NFORCE, AMD8111 };
static const char* chipname[] = {
"AMD756", "AMD766", "AMD768",
"nVidia nForce", "AMD8111",
};
static DEFINE_PCI_DEVICE_TABLE(amd756_ids) = {
{ PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_VIPER_740B),
.driver_data = AMD756 },
{ PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_VIPER_7413),
.driver_data = AMD766 },
{ PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_OPUS_7443),
.driver_data = AMD768 },
{ PCI_DEVICE(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8111_SMBUS),
.driver_data = AMD8111 },
{ PCI_DEVICE(PCI_VENDOR_ID_NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE_SMBUS),
.driver_data = NFORCE },
{ 0, }
};
MODULE_DEVICE_TABLE (pci, amd756_ids);
static int amd756_probe(struct pci_dev *pdev, const struct pci_device_id *id)
{
int nforce = (id->driver_data == NFORCE);
int error;
u8 temp;
if (amd756_ioport) {
dev_err(&pdev->dev, "Only one device supported "
"(you have a strange motherboard, btw)\n");
return -ENODEV;
}
if (nforce) {
if (PCI_FUNC(pdev->devfn) != 1)
return -ENODEV;
pci_read_config_word(pdev, SMBBANFORCE, &amd756_ioport);
amd756_ioport &= 0xfffc;
} else { /* amd */
if (PCI_FUNC(pdev->devfn) != 3)
return -ENODEV;
pci_read_config_byte(pdev, SMBGCFG, &temp);
if ((temp & 128) == 0) {
dev_err(&pdev->dev,
"Error: SMBus controller I/O not enabled!\n");
return -ENODEV;
}
/* Determine the address of the SMBus areas */
/* Technically it is a dword but... */
pci_read_config_word(pdev, SMBBA, &amd756_ioport);
amd756_ioport &= 0xff00;
amd756_ioport += SMB_ADDR_OFFSET;
}
error = acpi_check_region(amd756_ioport, SMB_IOSIZE,
amd756_driver.name);
if (error)
return -ENODEV;
if (!request_region(amd756_ioport, SMB_IOSIZE, amd756_driver.name)) {
dev_err(&pdev->dev, "SMB region 0x%x already in use!\n",
amd756_ioport);
return -ENODEV;
}
pci_read_config_byte(pdev, SMBREV, &temp);
dev_dbg(&pdev->dev, "SMBREV = 0x%X\n", temp);
dev_dbg(&pdev->dev, "AMD756_smba = 0x%X\n", amd756_ioport);
/* set up the sysfs linkage to our parent device */
amd756_smbus.dev.parent = &pdev->dev;
snprintf(amd756_smbus.name, sizeof(amd756_smbus.name),
"SMBus %s adapter at %04x", chipname[id->driver_data],
amd756_ioport);
error = i2c_add_adapter(&amd756_smbus);
if (error) {
dev_err(&pdev->dev,
"Adapter registration failed, module not inserted\n");
goto out_err;
}
return 0;
out_err:
release_region(amd756_ioport, SMB_IOSIZE);
return error;
}
static void amd756_remove(struct pci_dev *dev)
{
i2c_del_adapter(&amd756_smbus);
release_region(amd756_ioport, SMB_IOSIZE);
}
static struct pci_driver amd756_driver = {
.name = "amd756_smbus",
.id_table = amd756_ids,
.probe = amd756_probe,
.remove = amd756_remove,
};
module_pci_driver(amd756_driver);
MODULE_AUTHOR("Merlin Hughes <merlin@merlin.org>");
MODULE_DESCRIPTION("AMD756/766/768/8111 and nVidia nForce SMBus driver");
MODULE_LICENSE("GPL");
EXPORT_SYMBOL(amd756_smbus);
| gpl-2.0 |
Hundsbuah/tf300t_10_6_1_8_4 | arch/arm/mach-davinci/board-da830-evm.c | 499 | 17347 | /*
* TI DA830/OMAP L137 EVM board
*
* Author: Mark A. Greer <mgreer@mvista.com>
* Derived from: arch/arm/mach-davinci/board-dm644x-evm.c
*
* 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/kernel.h>
#include <linux/init.h>
#include <linux/console.h>
#include <linux/interrupt.h>
#include <linux/gpio.h>
#include <linux/platform_device.h>
#include <linux/i2c.h>
#include <linux/i2c/pcf857x.h>
#include <linux/i2c/at24.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/spi/spi.h>
#include <linux/spi/flash.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <mach/cp_intc.h>
#include <mach/mux.h>
#include <mach/nand.h>
#include <mach/da8xx.h>
#include <mach/usb.h>
#include <mach/aemif.h>
#include <mach/spi.h>
#define DA830_EVM_PHY_ID ""
/*
* USB1 VBUS is controlled by GPIO1[15], over-current is reported on GPIO2[4].
*/
#define ON_BD_USB_DRV GPIO_TO_PIN(1, 15)
#define ON_BD_USB_OVC GPIO_TO_PIN(2, 4)
static const short da830_evm_usb11_pins[] = {
DA830_GPIO1_15, DA830_GPIO2_4,
-1
};
static da8xx_ocic_handler_t da830_evm_usb_ocic_handler;
static int da830_evm_usb_set_power(unsigned port, int on)
{
gpio_set_value(ON_BD_USB_DRV, on);
return 0;
}
static int da830_evm_usb_get_power(unsigned port)
{
return gpio_get_value(ON_BD_USB_DRV);
}
static int da830_evm_usb_get_oci(unsigned port)
{
return !gpio_get_value(ON_BD_USB_OVC);
}
static irqreturn_t da830_evm_usb_ocic_irq(int, void *);
static int da830_evm_usb_ocic_notify(da8xx_ocic_handler_t handler)
{
int irq = gpio_to_irq(ON_BD_USB_OVC);
int error = 0;
if (handler != NULL) {
da830_evm_usb_ocic_handler = handler;
error = request_irq(irq, da830_evm_usb_ocic_irq, IRQF_DISABLED |
IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,
"OHCI over-current indicator", NULL);
if (error)
printk(KERN_ERR "%s: could not request IRQ to watch "
"over-current indicator changes\n", __func__);
} else
free_irq(irq, NULL);
return error;
}
static struct da8xx_ohci_root_hub da830_evm_usb11_pdata = {
.set_power = da830_evm_usb_set_power,
.get_power = da830_evm_usb_get_power,
.get_oci = da830_evm_usb_get_oci,
.ocic_notify = da830_evm_usb_ocic_notify,
/* TPS2065 switch @ 5V */
.potpgt = (3 + 1) / 2, /* 3 ms max */
};
static irqreturn_t da830_evm_usb_ocic_irq(int irq, void *dev_id)
{
da830_evm_usb_ocic_handler(&da830_evm_usb11_pdata, 1);
return IRQ_HANDLED;
}
static __init void da830_evm_usb_init(void)
{
u32 cfgchip2;
int ret;
/*
* Set up USB clock/mode in the CFGCHIP2 register.
* FYI: CFGCHIP2 is 0x0000ef00 initially.
*/
cfgchip2 = __raw_readl(DA8XX_SYSCFG0_VIRT(DA8XX_CFGCHIP2_REG));
/* USB2.0 PHY reference clock is 24 MHz */
cfgchip2 &= ~CFGCHIP2_REFFREQ;
cfgchip2 |= CFGCHIP2_REFFREQ_24MHZ;
/*
* Select internal reference clock for USB 2.0 PHY
* and use it as a clock source for USB 1.1 PHY
* (this is the default setting anyway).
*/
cfgchip2 &= ~CFGCHIP2_USB1PHYCLKMUX;
cfgchip2 |= CFGCHIP2_USB2PHYCLKMUX;
/*
* We have to override VBUS/ID signals when MUSB is configured into the
* host-only mode -- ID pin will float if no cable is connected, so the
* controller won't be able to drive VBUS thinking that it's a B-device.
* Otherwise, we want to use the OTG mode and enable VBUS comparators.
*/
cfgchip2 &= ~CFGCHIP2_OTGMODE;
#ifdef CONFIG_USB_MUSB_HOST
cfgchip2 |= CFGCHIP2_FORCE_HOST;
#else
cfgchip2 |= CFGCHIP2_SESENDEN | CFGCHIP2_VBDTCTEN;
#endif
__raw_writel(cfgchip2, DA8XX_SYSCFG0_VIRT(DA8XX_CFGCHIP2_REG));
/* USB_REFCLKIN is not used. */
ret = davinci_cfg_reg(DA830_USB0_DRVVBUS);
if (ret)
pr_warning("%s: USB 2.0 PinMux setup failed: %d\n",
__func__, ret);
else {
/*
* TPS2065 switch @ 5V supplies 1 A (sustains 1.5 A),
* with the power on to power good time of 3 ms.
*/
ret = da8xx_register_usb20(1000, 3);
if (ret)
pr_warning("%s: USB 2.0 registration failed: %d\n",
__func__, ret);
}
ret = davinci_cfg_reg_list(da830_evm_usb11_pins);
if (ret) {
pr_warning("%s: USB 1.1 PinMux setup failed: %d\n",
__func__, ret);
return;
}
ret = gpio_request(ON_BD_USB_DRV, "ON_BD_USB_DRV");
if (ret) {
printk(KERN_ERR "%s: failed to request GPIO for USB 1.1 port "
"power control: %d\n", __func__, ret);
return;
}
gpio_direction_output(ON_BD_USB_DRV, 0);
ret = gpio_request(ON_BD_USB_OVC, "ON_BD_USB_OVC");
if (ret) {
printk(KERN_ERR "%s: failed to request GPIO for USB 1.1 port "
"over-current indicator: %d\n", __func__, ret);
return;
}
gpio_direction_input(ON_BD_USB_OVC);
ret = da8xx_register_usb11(&da830_evm_usb11_pdata);
if (ret)
pr_warning("%s: USB 1.1 registration failed: %d\n",
__func__, ret);
}
static struct davinci_uart_config da830_evm_uart_config __initdata = {
.enabled_uarts = 0x7,
};
static const short da830_evm_mcasp1_pins[] = {
DA830_AHCLKX1, DA830_ACLKX1, DA830_AFSX1, DA830_AHCLKR1, DA830_AFSR1,
DA830_AMUTE1, DA830_AXR1_0, DA830_AXR1_1, DA830_AXR1_2, DA830_AXR1_5,
DA830_ACLKR1, DA830_AXR1_6, DA830_AXR1_7, DA830_AXR1_8, DA830_AXR1_10,
DA830_AXR1_11,
-1
};
static u8 da830_iis_serializer_direction[] = {
RX_MODE, INACTIVE_MODE, INACTIVE_MODE, INACTIVE_MODE,
INACTIVE_MODE, TX_MODE, INACTIVE_MODE, INACTIVE_MODE,
INACTIVE_MODE, INACTIVE_MODE, INACTIVE_MODE, INACTIVE_MODE,
};
static struct snd_platform_data da830_evm_snd_data = {
.tx_dma_offset = 0x2000,
.rx_dma_offset = 0x2000,
.op_mode = DAVINCI_MCASP_IIS_MODE,
.num_serializer = ARRAY_SIZE(da830_iis_serializer_direction),
.tdm_slots = 2,
.serial_dir = da830_iis_serializer_direction,
.asp_chan_q = EVENTQ_0,
.version = MCASP_VERSION_2,
.txnumevt = 1,
.rxnumevt = 1,
};
/*
* GPIO2[1] is used as MMC_SD_WP and GPIO2[2] as MMC_SD_INS.
*/
static const short da830_evm_mmc_sd_pins[] = {
DA830_MMCSD_DAT_0, DA830_MMCSD_DAT_1, DA830_MMCSD_DAT_2,
DA830_MMCSD_DAT_3, DA830_MMCSD_DAT_4, DA830_MMCSD_DAT_5,
DA830_MMCSD_DAT_6, DA830_MMCSD_DAT_7, DA830_MMCSD_CLK,
DA830_MMCSD_CMD, DA830_GPIO2_1, DA830_GPIO2_2,
-1
};
#define DA830_MMCSD_WP_PIN GPIO_TO_PIN(2, 1)
#define DA830_MMCSD_CD_PIN GPIO_TO_PIN(2, 2)
static int da830_evm_mmc_get_ro(int index)
{
return gpio_get_value(DA830_MMCSD_WP_PIN);
}
static int da830_evm_mmc_get_cd(int index)
{
return !gpio_get_value(DA830_MMCSD_CD_PIN);
}
static struct davinci_mmc_config da830_evm_mmc_config = {
.get_ro = da830_evm_mmc_get_ro,
.get_cd = da830_evm_mmc_get_cd,
.wires = 8,
.max_freq = 50000000,
.caps = MMC_CAP_MMC_HIGHSPEED | MMC_CAP_SD_HIGHSPEED,
.version = MMC_CTLR_VERSION_2,
};
static inline void da830_evm_init_mmc(void)
{
int ret;
ret = davinci_cfg_reg_list(da830_evm_mmc_sd_pins);
if (ret) {
pr_warning("da830_evm_init: mmc/sd mux setup failed: %d\n",
ret);
return;
}
ret = gpio_request(DA830_MMCSD_WP_PIN, "MMC WP");
if (ret) {
pr_warning("da830_evm_init: can not open GPIO %d\n",
DA830_MMCSD_WP_PIN);
return;
}
gpio_direction_input(DA830_MMCSD_WP_PIN);
ret = gpio_request(DA830_MMCSD_CD_PIN, "MMC CD\n");
if (ret) {
pr_warning("da830_evm_init: can not open GPIO %d\n",
DA830_MMCSD_CD_PIN);
return;
}
gpio_direction_input(DA830_MMCSD_CD_PIN);
ret = da8xx_register_mmcsd0(&da830_evm_mmc_config);
if (ret) {
pr_warning("da830_evm_init: mmc/sd registration failed: %d\n",
ret);
gpio_free(DA830_MMCSD_WP_PIN);
}
}
/*
* UI board NAND/NOR flashes only use 8-bit data bus.
*/
static const short da830_evm_emif25_pins[] = {
DA830_EMA_D_0, DA830_EMA_D_1, DA830_EMA_D_2, DA830_EMA_D_3,
DA830_EMA_D_4, DA830_EMA_D_5, DA830_EMA_D_6, DA830_EMA_D_7,
DA830_EMA_A_0, DA830_EMA_A_1, DA830_EMA_A_2, DA830_EMA_A_3,
DA830_EMA_A_4, DA830_EMA_A_5, DA830_EMA_A_6, DA830_EMA_A_7,
DA830_EMA_A_8, DA830_EMA_A_9, DA830_EMA_A_10, DA830_EMA_A_11,
DA830_EMA_A_12, DA830_EMA_BA_0, DA830_EMA_BA_1, DA830_NEMA_WE,
DA830_NEMA_CS_2, DA830_NEMA_CS_3, DA830_NEMA_OE, DA830_EMA_WAIT_0,
-1
};
#if defined(CONFIG_MMC_DAVINCI) || defined(CONFIG_MMC_DAVINCI_MODULE)
#define HAS_MMC 1
#else
#define HAS_MMC 0
#endif
#ifdef CONFIG_DA830_UI_NAND
static struct mtd_partition da830_evm_nand_partitions[] = {
/* bootloader (U-Boot, etc) in first sector */
[0] = {
.name = "bootloader",
.offset = 0,
.size = SZ_128K,
.mask_flags = MTD_WRITEABLE, /* force read-only */
},
/* bootloader params in the next sector */
[1] = {
.name = "params",
.offset = MTDPART_OFS_APPEND,
.size = SZ_128K,
.mask_flags = MTD_WRITEABLE, /* force read-only */
},
/* kernel */
[2] = {
.name = "kernel",
.offset = MTDPART_OFS_APPEND,
.size = SZ_2M,
.mask_flags = 0,
},
/* file system */
[3] = {
.name = "filesystem",
.offset = MTDPART_OFS_APPEND,
.size = MTDPART_SIZ_FULL,
.mask_flags = 0,
}
};
/* flash bbt decriptors */
static uint8_t da830_evm_nand_bbt_pattern[] = { 'B', 'b', 't', '0' };
static uint8_t da830_evm_nand_mirror_pattern[] = { '1', 't', 'b', 'B' };
static struct nand_bbt_descr da830_evm_nand_bbt_main_descr = {
.options = NAND_BBT_LASTBLOCK | NAND_BBT_CREATE |
NAND_BBT_WRITE | NAND_BBT_2BIT |
NAND_BBT_VERSION | NAND_BBT_PERCHIP,
.offs = 2,
.len = 4,
.veroffs = 16,
.maxblocks = 4,
.pattern = da830_evm_nand_bbt_pattern
};
static struct nand_bbt_descr da830_evm_nand_bbt_mirror_descr = {
.options = NAND_BBT_LASTBLOCK | NAND_BBT_CREATE |
NAND_BBT_WRITE | NAND_BBT_2BIT |
NAND_BBT_VERSION | NAND_BBT_PERCHIP,
.offs = 2,
.len = 4,
.veroffs = 16,
.maxblocks = 4,
.pattern = da830_evm_nand_mirror_pattern
};
static struct davinci_aemif_timing da830_evm_nandflash_timing = {
.wsetup = 24,
.wstrobe = 21,
.whold = 14,
.rsetup = 19,
.rstrobe = 50,
.rhold = 0,
.ta = 20,
};
static struct davinci_nand_pdata da830_evm_nand_pdata = {
.parts = da830_evm_nand_partitions,
.nr_parts = ARRAY_SIZE(da830_evm_nand_partitions),
.ecc_mode = NAND_ECC_HW,
.ecc_bits = 4,
.options = NAND_USE_FLASH_BBT,
.bbt_td = &da830_evm_nand_bbt_main_descr,
.bbt_md = &da830_evm_nand_bbt_mirror_descr,
.timing = &da830_evm_nandflash_timing,
};
static struct resource da830_evm_nand_resources[] = {
[0] = { /* First memory resource is NAND I/O window */
.start = DA8XX_AEMIF_CS3_BASE,
.end = DA8XX_AEMIF_CS3_BASE + PAGE_SIZE - 1,
.flags = IORESOURCE_MEM,
},
[1] = { /* Second memory resource is AEMIF control registers */
.start = DA8XX_AEMIF_CTL_BASE,
.end = DA8XX_AEMIF_CTL_BASE + SZ_32K - 1,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device da830_evm_nand_device = {
.name = "davinci_nand",
.id = 1,
.dev = {
.platform_data = &da830_evm_nand_pdata,
},
.num_resources = ARRAY_SIZE(da830_evm_nand_resources),
.resource = da830_evm_nand_resources,
};
static inline void da830_evm_init_nand(int mux_mode)
{
int ret;
if (HAS_MMC) {
pr_warning("WARNING: both MMC/SD and NAND are "
"enabled, but they share AEMIF pins.\n"
"\tDisable MMC/SD for NAND support.\n");
return;
}
ret = davinci_cfg_reg_list(da830_evm_emif25_pins);
if (ret)
pr_warning("da830_evm_init: emif25 mux setup failed: %d\n",
ret);
ret = platform_device_register(&da830_evm_nand_device);
if (ret)
pr_warning("da830_evm_init: NAND device not registered.\n");
gpio_direction_output(mux_mode, 1);
}
#else
static inline void da830_evm_init_nand(int mux_mode) { }
#endif
#ifdef CONFIG_DA830_UI_LCD
static inline void da830_evm_init_lcdc(int mux_mode)
{
int ret;
ret = davinci_cfg_reg_list(da830_lcdcntl_pins);
if (ret)
pr_warning("da830_evm_init: lcdcntl mux setup failed: %d\n",
ret);
ret = da8xx_register_lcdc(&sharp_lcd035q3dg01_pdata);
if (ret)
pr_warning("da830_evm_init: lcd setup failed: %d\n", ret);
gpio_direction_output(mux_mode, 0);
}
#else
static inline void da830_evm_init_lcdc(int mux_mode) { }
#endif
static struct at24_platform_data da830_evm_i2c_eeprom_info = {
.byte_len = SZ_256K / 8,
.page_size = 64,
.flags = AT24_FLAG_ADDR16,
.setup = davinci_get_mac_addr,
.context = (void *)0x7f00,
};
static int __init da830_evm_ui_expander_setup(struct i2c_client *client,
int gpio, unsigned ngpio, void *context)
{
gpio_request(gpio + 6, "UI MUX_MODE");
/* Drive mux mode low to match the default without UI card */
gpio_direction_output(gpio + 6, 0);
da830_evm_init_lcdc(gpio + 6);
da830_evm_init_nand(gpio + 6);
return 0;
}
static int da830_evm_ui_expander_teardown(struct i2c_client *client, int gpio,
unsigned ngpio, void *context)
{
gpio_free(gpio + 6);
return 0;
}
static struct pcf857x_platform_data __initdata da830_evm_ui_expander_info = {
.gpio_base = DAVINCI_N_GPIO,
.setup = da830_evm_ui_expander_setup,
.teardown = da830_evm_ui_expander_teardown,
};
static struct i2c_board_info __initdata da830_evm_i2c_devices[] = {
{
I2C_BOARD_INFO("24c256", 0x50),
.platform_data = &da830_evm_i2c_eeprom_info,
},
{
I2C_BOARD_INFO("tlv320aic3x", 0x18),
},
{
I2C_BOARD_INFO("pcf8574", 0x3f),
.platform_data = &da830_evm_ui_expander_info,
},
};
static struct davinci_i2c_platform_data da830_evm_i2c_0_pdata = {
.bus_freq = 100, /* kHz */
.bus_delay = 0, /* usec */
};
/*
* The following EDMA channels/slots are not being used by drivers (for
* example: Timer, GPIO, UART events etc) on da830/omap-l137 EVM, hence
* they are being reserved for codecs on the DSP side.
*/
static const s16 da830_dma_rsv_chans[][2] = {
/* (offset, number) */
{ 8, 2},
{12, 2},
{24, 4},
{30, 2},
{-1, -1}
};
static const s16 da830_dma_rsv_slots[][2] = {
/* (offset, number) */
{ 8, 2},
{12, 2},
{24, 4},
{30, 26},
{-1, -1}
};
static struct edma_rsv_info da830_edma_rsv[] = {
{
.rsv_chans = da830_dma_rsv_chans,
.rsv_slots = da830_dma_rsv_slots,
},
};
static struct mtd_partition da830evm_spiflash_part[] = {
[0] = {
.name = "DSP-UBL",
.offset = 0,
.size = SZ_8K,
.mask_flags = MTD_WRITEABLE,
},
[1] = {
.name = "ARM-UBL",
.offset = MTDPART_OFS_APPEND,
.size = SZ_16K + SZ_8K,
.mask_flags = MTD_WRITEABLE,
},
[2] = {
.name = "U-Boot",
.offset = MTDPART_OFS_APPEND,
.size = SZ_256K - SZ_32K,
.mask_flags = MTD_WRITEABLE,
},
[3] = {
.name = "U-Boot-Environment",
.offset = MTDPART_OFS_APPEND,
.size = SZ_16K,
.mask_flags = 0,
},
[4] = {
.name = "Kernel",
.offset = MTDPART_OFS_APPEND,
.size = MTDPART_SIZ_FULL,
.mask_flags = 0,
},
};
static struct flash_platform_data da830evm_spiflash_data = {
.name = "m25p80",
.parts = da830evm_spiflash_part,
.nr_parts = ARRAY_SIZE(da830evm_spiflash_part),
.type = "w25x32",
};
static struct davinci_spi_config da830evm_spiflash_cfg = {
.io_type = SPI_IO_TYPE_DMA,
.c2tdelay = 8,
.t2cdelay = 8,
};
static struct spi_board_info da830evm_spi_info[] = {
{
.modalias = "m25p80",
.platform_data = &da830evm_spiflash_data,
.controller_data = &da830evm_spiflash_cfg,
.mode = SPI_MODE_0,
.max_speed_hz = 30000000,
.bus_num = 0,
.chip_select = 0,
},
};
static __init void da830_evm_init(void)
{
struct davinci_soc_info *soc_info = &davinci_soc_info;
int ret;
ret = da830_register_edma(da830_edma_rsv);
if (ret)
pr_warning("da830_evm_init: edma registration failed: %d\n",
ret);
ret = davinci_cfg_reg_list(da830_i2c0_pins);
if (ret)
pr_warning("da830_evm_init: i2c0 mux setup failed: %d\n",
ret);
ret = da8xx_register_i2c(0, &da830_evm_i2c_0_pdata);
if (ret)
pr_warning("da830_evm_init: i2c0 registration failed: %d\n",
ret);
da830_evm_usb_init();
soc_info->emac_pdata->rmii_en = 1;
soc_info->emac_pdata->phy_id = DA830_EVM_PHY_ID;
ret = davinci_cfg_reg_list(da830_cpgmac_pins);
if (ret)
pr_warning("da830_evm_init: cpgmac mux setup failed: %d\n",
ret);
ret = da8xx_register_emac();
if (ret)
pr_warning("da830_evm_init: emac registration failed: %d\n",
ret);
ret = da8xx_register_watchdog();
if (ret)
pr_warning("da830_evm_init: watchdog registration failed: %d\n",
ret);
davinci_serial_init(&da830_evm_uart_config);
i2c_register_board_info(1, da830_evm_i2c_devices,
ARRAY_SIZE(da830_evm_i2c_devices));
ret = davinci_cfg_reg_list(da830_evm_mcasp1_pins);
if (ret)
pr_warning("da830_evm_init: mcasp1 mux setup failed: %d\n",
ret);
da8xx_register_mcasp(1, &da830_evm_snd_data);
da830_evm_init_mmc();
ret = da8xx_register_rtc();
if (ret)
pr_warning("da830_evm_init: rtc setup failed: %d\n", ret);
ret = da8xx_register_spi(0, da830evm_spi_info,
ARRAY_SIZE(da830evm_spi_info));
if (ret)
pr_warning("da830_evm_init: spi 0 registration failed: %d\n",
ret);
}
#ifdef CONFIG_SERIAL_8250_CONSOLE
static int __init da830_evm_console_init(void)
{
if (!machine_is_davinci_da830_evm())
return 0;
return add_preferred_console("ttyS", 2, "115200");
}
console_initcall(da830_evm_console_init);
#endif
static void __init da830_evm_map_io(void)
{
da830_init();
}
MACHINE_START(DAVINCI_DA830_EVM, "DaVinci DA830/OMAP-L137/AM17x EVM")
.boot_params = (DA8XX_DDR_BASE + 0x100),
.map_io = da830_evm_map_io,
.init_irq = cp_intc_init,
.timer = &davinci_timer,
.init_machine = da830_evm_init,
.dma_zone_size = SZ_128M,
MACHINE_END
| gpl-2.0 |
ProjectOpenCannibal/GingerKernel-LGLS670-old | drivers/ata/sata_sx4.c | 1011 | 40560 | /*
* sata_sx4.c - Promise SATA
*
* Maintained by: Jeff Garzik <jgarzik@pobox.com>
* Please ALWAYS copy linux-ide@vger.kernel.org
* on emails.
*
* Copyright 2003-2004 Red Hat, 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; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*
* libata documentation is available via 'make {ps|pdf}docs',
* as Documentation/DocBook/libata.*
*
* Hardware documentation available under NDA.
*
*/
/*
Theory of operation
-------------------
The SX4 (PDC20621) chip features a single Host DMA (HDMA) copy
engine, DIMM memory, and four ATA engines (one per SATA port).
Data is copied to/from DIMM memory by the HDMA engine, before
handing off to one (or more) of the ATA engines. The ATA
engines operate solely on DIMM memory.
The SX4 behaves like a PATA chip, with no SATA controls or
knowledge whatsoever, leading to the presumption that
PATA<->SATA bridges exist on SX4 boards, external to the
PDC20621 chip itself.
The chip is quite capable, supporting an XOR engine and linked
hardware commands (permits a string to transactions to be
submitted and waited-on as a single unit), and an optional
microprocessor.
The limiting factor is largely software. This Linux driver was
written to multiplex the single HDMA engine to copy disk
transactions into a fixed DIMM memory space, from where an ATA
engine takes over. As a result, each WRITE looks like this:
submit HDMA packet to hardware
hardware copies data from system memory to DIMM
hardware raises interrupt
submit ATA packet to hardware
hardware executes ATA WRITE command, w/ data in DIMM
hardware raises interrupt
and each READ looks like this:
submit ATA packet to hardware
hardware executes ATA READ command, w/ data in DIMM
hardware raises interrupt
submit HDMA packet to hardware
hardware copies data from DIMM to system memory
hardware raises interrupt
This is a very slow, lock-step way of doing things that can
certainly be improved by motivated kernel hackers.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/device.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_cmnd.h>
#include <linux/libata.h>
#include "sata_promise.h"
#define DRV_NAME "sata_sx4"
#define DRV_VERSION "0.12"
enum {
PDC_MMIO_BAR = 3,
PDC_DIMM_BAR = 4,
PDC_PRD_TBL = 0x44, /* Direct command DMA table addr */
PDC_PKT_SUBMIT = 0x40, /* Command packet pointer addr */
PDC_HDMA_PKT_SUBMIT = 0x100, /* Host DMA packet pointer addr */
PDC_INT_SEQMASK = 0x40, /* Mask of asserted SEQ INTs */
PDC_HDMA_CTLSTAT = 0x12C, /* Host DMA control / status */
PDC_CTLSTAT = 0x60, /* IDEn control / status */
PDC_20621_SEQCTL = 0x400,
PDC_20621_SEQMASK = 0x480,
PDC_20621_GENERAL_CTL = 0x484,
PDC_20621_PAGE_SIZE = (32 * 1024),
/* chosen, not constant, values; we design our own DIMM mem map */
PDC_20621_DIMM_WINDOW = 0x0C, /* page# for 32K DIMM window */
PDC_20621_DIMM_BASE = 0x00200000,
PDC_20621_DIMM_DATA = (64 * 1024),
PDC_DIMM_DATA_STEP = (256 * 1024),
PDC_DIMM_WINDOW_STEP = (8 * 1024),
PDC_DIMM_HOST_PRD = (6 * 1024),
PDC_DIMM_HOST_PKT = (128 * 0),
PDC_DIMM_HPKT_PRD = (128 * 1),
PDC_DIMM_ATA_PKT = (128 * 2),
PDC_DIMM_APKT_PRD = (128 * 3),
PDC_DIMM_HEADER_SZ = PDC_DIMM_APKT_PRD + 128,
PDC_PAGE_WINDOW = 0x40,
PDC_PAGE_DATA = PDC_PAGE_WINDOW +
(PDC_20621_DIMM_DATA / PDC_20621_PAGE_SIZE),
PDC_PAGE_SET = PDC_DIMM_DATA_STEP / PDC_20621_PAGE_SIZE,
PDC_CHIP0_OFS = 0xC0000, /* offset of chip #0 */
PDC_20621_ERR_MASK = (1<<19) | (1<<20) | (1<<21) | (1<<22) |
(1<<23),
board_20621 = 0, /* FastTrak S150 SX4 */
PDC_MASK_INT = (1 << 10), /* HDMA/ATA mask int */
PDC_RESET = (1 << 11), /* HDMA/ATA reset */
PDC_DMA_ENABLE = (1 << 7), /* DMA start/stop */
PDC_MAX_HDMA = 32,
PDC_HDMA_Q_MASK = (PDC_MAX_HDMA - 1),
PDC_DIMM0_SPD_DEV_ADDRESS = 0x50,
PDC_DIMM1_SPD_DEV_ADDRESS = 0x51,
PDC_I2C_CONTROL = 0x48,
PDC_I2C_ADDR_DATA = 0x4C,
PDC_DIMM0_CONTROL = 0x80,
PDC_DIMM1_CONTROL = 0x84,
PDC_SDRAM_CONTROL = 0x88,
PDC_I2C_WRITE = 0, /* master -> slave */
PDC_I2C_READ = (1 << 6), /* master <- slave */
PDC_I2C_START = (1 << 7), /* start I2C proto */
PDC_I2C_MASK_INT = (1 << 5), /* mask I2C interrupt */
PDC_I2C_COMPLETE = (1 << 16), /* I2C normal compl. */
PDC_I2C_NO_ACK = (1 << 20), /* slave no-ack addr */
PDC_DIMM_SPD_SUBADDRESS_START = 0x00,
PDC_DIMM_SPD_SUBADDRESS_END = 0x7F,
PDC_DIMM_SPD_ROW_NUM = 3,
PDC_DIMM_SPD_COLUMN_NUM = 4,
PDC_DIMM_SPD_MODULE_ROW = 5,
PDC_DIMM_SPD_TYPE = 11,
PDC_DIMM_SPD_FRESH_RATE = 12,
PDC_DIMM_SPD_BANK_NUM = 17,
PDC_DIMM_SPD_CAS_LATENCY = 18,
PDC_DIMM_SPD_ATTRIBUTE = 21,
PDC_DIMM_SPD_ROW_PRE_CHARGE = 27,
PDC_DIMM_SPD_ROW_ACTIVE_DELAY = 28,
PDC_DIMM_SPD_RAS_CAS_DELAY = 29,
PDC_DIMM_SPD_ACTIVE_PRECHARGE = 30,
PDC_DIMM_SPD_SYSTEM_FREQ = 126,
PDC_CTL_STATUS = 0x08,
PDC_DIMM_WINDOW_CTLR = 0x0C,
PDC_TIME_CONTROL = 0x3C,
PDC_TIME_PERIOD = 0x40,
PDC_TIME_COUNTER = 0x44,
PDC_GENERAL_CTLR = 0x484,
PCI_PLL_INIT = 0x8A531824,
PCI_X_TCOUNT = 0xEE1E5CFF,
/* PDC_TIME_CONTROL bits */
PDC_TIMER_BUZZER = (1 << 10),
PDC_TIMER_MODE_PERIODIC = 0, /* bits 9:8 == 00 */
PDC_TIMER_MODE_ONCE = (1 << 8), /* bits 9:8 == 01 */
PDC_TIMER_ENABLE = (1 << 7),
PDC_TIMER_MASK_INT = (1 << 5),
PDC_TIMER_SEQ_MASK = 0x1f, /* SEQ ID for timer */
PDC_TIMER_DEFAULT = PDC_TIMER_MODE_ONCE |
PDC_TIMER_ENABLE |
PDC_TIMER_MASK_INT,
};
#define ECC_ERASE_BUF_SZ (128 * 1024)
struct pdc_port_priv {
u8 dimm_buf[(ATA_PRD_SZ * ATA_MAX_PRD) + 512];
u8 *pkt;
dma_addr_t pkt_dma;
};
struct pdc_host_priv {
unsigned int doing_hdma;
unsigned int hdma_prod;
unsigned int hdma_cons;
struct {
struct ata_queued_cmd *qc;
unsigned int seq;
unsigned long pkt_ofs;
} hdma[32];
};
static int pdc_sata_init_one(struct pci_dev *pdev, const struct pci_device_id *ent);
static void pdc_error_handler(struct ata_port *ap);
static void pdc_freeze(struct ata_port *ap);
static void pdc_thaw(struct ata_port *ap);
static int pdc_port_start(struct ata_port *ap);
static void pdc20621_qc_prep(struct ata_queued_cmd *qc);
static void pdc_tf_load_mmio(struct ata_port *ap, const struct ata_taskfile *tf);
static void pdc_exec_command_mmio(struct ata_port *ap, const struct ata_taskfile *tf);
static unsigned int pdc20621_dimm_init(struct ata_host *host);
static int pdc20621_detect_dimm(struct ata_host *host);
static unsigned int pdc20621_i2c_read(struct ata_host *host,
u32 device, u32 subaddr, u32 *pdata);
static int pdc20621_prog_dimm0(struct ata_host *host);
static unsigned int pdc20621_prog_dimm_global(struct ata_host *host);
#ifdef ATA_VERBOSE_DEBUG
static void pdc20621_get_from_dimm(struct ata_host *host,
void *psource, u32 offset, u32 size);
#endif
static void pdc20621_put_to_dimm(struct ata_host *host,
void *psource, u32 offset, u32 size);
static void pdc20621_irq_clear(struct ata_port *ap);
static unsigned int pdc20621_qc_issue(struct ata_queued_cmd *qc);
static int pdc_softreset(struct ata_link *link, unsigned int *class,
unsigned long deadline);
static void pdc_post_internal_cmd(struct ata_queued_cmd *qc);
static int pdc_check_atapi_dma(struct ata_queued_cmd *qc);
static struct scsi_host_template pdc_sata_sht = {
ATA_BASE_SHT(DRV_NAME),
.sg_tablesize = LIBATA_MAX_PRD,
.dma_boundary = ATA_DMA_BOUNDARY,
};
/* TODO: inherit from base port_ops after converting to new EH */
static struct ata_port_operations pdc_20621_ops = {
.inherits = &ata_sff_port_ops,
.check_atapi_dma = pdc_check_atapi_dma,
.qc_prep = pdc20621_qc_prep,
.qc_issue = pdc20621_qc_issue,
.freeze = pdc_freeze,
.thaw = pdc_thaw,
.softreset = pdc_softreset,
.error_handler = pdc_error_handler,
.lost_interrupt = ATA_OP_NULL,
.post_internal_cmd = pdc_post_internal_cmd,
.port_start = pdc_port_start,
.sff_tf_load = pdc_tf_load_mmio,
.sff_exec_command = pdc_exec_command_mmio,
.sff_irq_clear = pdc20621_irq_clear,
};
static const struct ata_port_info pdc_port_info[] = {
/* board_20621 */
{
.flags = ATA_FLAG_SATA | ATA_FLAG_NO_LEGACY |
ATA_FLAG_SRST | ATA_FLAG_MMIO |
ATA_FLAG_NO_ATAPI | ATA_FLAG_PIO_POLLING,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA6,
.port_ops = &pdc_20621_ops,
},
};
static const struct pci_device_id pdc_sata_pci_tbl[] = {
{ PCI_VDEVICE(PROMISE, 0x6622), board_20621 },
{ } /* terminate list */
};
static struct pci_driver pdc_sata_pci_driver = {
.name = DRV_NAME,
.id_table = pdc_sata_pci_tbl,
.probe = pdc_sata_init_one,
.remove = ata_pci_remove_one,
};
static int pdc_port_start(struct ata_port *ap)
{
struct device *dev = ap->host->dev;
struct pdc_port_priv *pp;
pp = devm_kzalloc(dev, sizeof(*pp), GFP_KERNEL);
if (!pp)
return -ENOMEM;
pp->pkt = dmam_alloc_coherent(dev, 128, &pp->pkt_dma, GFP_KERNEL);
if (!pp->pkt)
return -ENOMEM;
ap->private_data = pp;
return 0;
}
static inline void pdc20621_ata_sg(struct ata_taskfile *tf, u8 *buf,
unsigned int portno,
unsigned int total_len)
{
u32 addr;
unsigned int dw = PDC_DIMM_APKT_PRD >> 2;
__le32 *buf32 = (__le32 *) buf;
/* output ATA packet S/G table */
addr = PDC_20621_DIMM_BASE + PDC_20621_DIMM_DATA +
(PDC_DIMM_DATA_STEP * portno);
VPRINTK("ATA sg addr 0x%x, %d\n", addr, addr);
buf32[dw] = cpu_to_le32(addr);
buf32[dw + 1] = cpu_to_le32(total_len | ATA_PRD_EOT);
VPRINTK("ATA PSG @ %x == (0x%x, 0x%x)\n",
PDC_20621_DIMM_BASE +
(PDC_DIMM_WINDOW_STEP * portno) +
PDC_DIMM_APKT_PRD,
buf32[dw], buf32[dw + 1]);
}
static inline void pdc20621_host_sg(struct ata_taskfile *tf, u8 *buf,
unsigned int portno,
unsigned int total_len)
{
u32 addr;
unsigned int dw = PDC_DIMM_HPKT_PRD >> 2;
__le32 *buf32 = (__le32 *) buf;
/* output Host DMA packet S/G table */
addr = PDC_20621_DIMM_BASE + PDC_20621_DIMM_DATA +
(PDC_DIMM_DATA_STEP * portno);
buf32[dw] = cpu_to_le32(addr);
buf32[dw + 1] = cpu_to_le32(total_len | ATA_PRD_EOT);
VPRINTK("HOST PSG @ %x == (0x%x, 0x%x)\n",
PDC_20621_DIMM_BASE +
(PDC_DIMM_WINDOW_STEP * portno) +
PDC_DIMM_HPKT_PRD,
buf32[dw], buf32[dw + 1]);
}
static inline unsigned int pdc20621_ata_pkt(struct ata_taskfile *tf,
unsigned int devno, u8 *buf,
unsigned int portno)
{
unsigned int i, dw;
__le32 *buf32 = (__le32 *) buf;
u8 dev_reg;
unsigned int dimm_sg = PDC_20621_DIMM_BASE +
(PDC_DIMM_WINDOW_STEP * portno) +
PDC_DIMM_APKT_PRD;
VPRINTK("ENTER, dimm_sg == 0x%x, %d\n", dimm_sg, dimm_sg);
i = PDC_DIMM_ATA_PKT;
/*
* Set up ATA packet
*/
if ((tf->protocol == ATA_PROT_DMA) && (!(tf->flags & ATA_TFLAG_WRITE)))
buf[i++] = PDC_PKT_READ;
else if (tf->protocol == ATA_PROT_NODATA)
buf[i++] = PDC_PKT_NODATA;
else
buf[i++] = 0;
buf[i++] = 0; /* reserved */
buf[i++] = portno + 1; /* seq. id */
buf[i++] = 0xff; /* delay seq. id */
/* dimm dma S/G, and next-pkt */
dw = i >> 2;
if (tf->protocol == ATA_PROT_NODATA)
buf32[dw] = 0;
else
buf32[dw] = cpu_to_le32(dimm_sg);
buf32[dw + 1] = 0;
i += 8;
if (devno == 0)
dev_reg = ATA_DEVICE_OBS;
else
dev_reg = ATA_DEVICE_OBS | ATA_DEV1;
/* select device */
buf[i++] = (1 << 5) | PDC_PKT_CLEAR_BSY | ATA_REG_DEVICE;
buf[i++] = dev_reg;
/* device control register */
buf[i++] = (1 << 5) | PDC_REG_DEVCTL;
buf[i++] = tf->ctl;
return i;
}
static inline void pdc20621_host_pkt(struct ata_taskfile *tf, u8 *buf,
unsigned int portno)
{
unsigned int dw;
u32 tmp;
__le32 *buf32 = (__le32 *) buf;
unsigned int host_sg = PDC_20621_DIMM_BASE +
(PDC_DIMM_WINDOW_STEP * portno) +
PDC_DIMM_HOST_PRD;
unsigned int dimm_sg = PDC_20621_DIMM_BASE +
(PDC_DIMM_WINDOW_STEP * portno) +
PDC_DIMM_HPKT_PRD;
VPRINTK("ENTER, dimm_sg == 0x%x, %d\n", dimm_sg, dimm_sg);
VPRINTK("host_sg == 0x%x, %d\n", host_sg, host_sg);
dw = PDC_DIMM_HOST_PKT >> 2;
/*
* Set up Host DMA packet
*/
if ((tf->protocol == ATA_PROT_DMA) && (!(tf->flags & ATA_TFLAG_WRITE)))
tmp = PDC_PKT_READ;
else
tmp = 0;
tmp |= ((portno + 1 + 4) << 16); /* seq. id */
tmp |= (0xff << 24); /* delay seq. id */
buf32[dw + 0] = cpu_to_le32(tmp);
buf32[dw + 1] = cpu_to_le32(host_sg);
buf32[dw + 2] = cpu_to_le32(dimm_sg);
buf32[dw + 3] = 0;
VPRINTK("HOST PKT @ %x == (0x%x 0x%x 0x%x 0x%x)\n",
PDC_20621_DIMM_BASE + (PDC_DIMM_WINDOW_STEP * portno) +
PDC_DIMM_HOST_PKT,
buf32[dw + 0],
buf32[dw + 1],
buf32[dw + 2],
buf32[dw + 3]);
}
static void pdc20621_dma_prep(struct ata_queued_cmd *qc)
{
struct scatterlist *sg;
struct ata_port *ap = qc->ap;
struct pdc_port_priv *pp = ap->private_data;
void __iomem *mmio = ap->host->iomap[PDC_MMIO_BAR];
void __iomem *dimm_mmio = ap->host->iomap[PDC_DIMM_BAR];
unsigned int portno = ap->port_no;
unsigned int i, si, idx, total_len = 0, sgt_len;
__le32 *buf = (__le32 *) &pp->dimm_buf[PDC_DIMM_HEADER_SZ];
WARN_ON(!(qc->flags & ATA_QCFLAG_DMAMAP));
VPRINTK("ata%u: ENTER\n", ap->print_id);
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
/*
* Build S/G table
*/
idx = 0;
for_each_sg(qc->sg, sg, qc->n_elem, si) {
buf[idx++] = cpu_to_le32(sg_dma_address(sg));
buf[idx++] = cpu_to_le32(sg_dma_len(sg));
total_len += sg_dma_len(sg);
}
buf[idx - 1] |= cpu_to_le32(ATA_PRD_EOT);
sgt_len = idx * 4;
/*
* Build ATA, host DMA packets
*/
pdc20621_host_sg(&qc->tf, &pp->dimm_buf[0], portno, total_len);
pdc20621_host_pkt(&qc->tf, &pp->dimm_buf[0], portno);
pdc20621_ata_sg(&qc->tf, &pp->dimm_buf[0], portno, total_len);
i = pdc20621_ata_pkt(&qc->tf, qc->dev->devno, &pp->dimm_buf[0], portno);
if (qc->tf.flags & ATA_TFLAG_LBA48)
i = pdc_prep_lba48(&qc->tf, &pp->dimm_buf[0], i);
else
i = pdc_prep_lba28(&qc->tf, &pp->dimm_buf[0], i);
pdc_pkt_footer(&qc->tf, &pp->dimm_buf[0], i);
/* copy three S/G tables and two packets to DIMM MMIO window */
memcpy_toio(dimm_mmio + (portno * PDC_DIMM_WINDOW_STEP),
&pp->dimm_buf, PDC_DIMM_HEADER_SZ);
memcpy_toio(dimm_mmio + (portno * PDC_DIMM_WINDOW_STEP) +
PDC_DIMM_HOST_PRD,
&pp->dimm_buf[PDC_DIMM_HEADER_SZ], sgt_len);
/* force host FIFO dump */
writel(0x00000001, mmio + PDC_20621_GENERAL_CTL);
readl(dimm_mmio); /* MMIO PCI posting flush */
VPRINTK("ata pkt buf ofs %u, prd size %u, mmio copied\n", i, sgt_len);
}
static void pdc20621_nodata_prep(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct pdc_port_priv *pp = ap->private_data;
void __iomem *mmio = ap->host->iomap[PDC_MMIO_BAR];
void __iomem *dimm_mmio = ap->host->iomap[PDC_DIMM_BAR];
unsigned int portno = ap->port_no;
unsigned int i;
VPRINTK("ata%u: ENTER\n", ap->print_id);
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
i = pdc20621_ata_pkt(&qc->tf, qc->dev->devno, &pp->dimm_buf[0], portno);
if (qc->tf.flags & ATA_TFLAG_LBA48)
i = pdc_prep_lba48(&qc->tf, &pp->dimm_buf[0], i);
else
i = pdc_prep_lba28(&qc->tf, &pp->dimm_buf[0], i);
pdc_pkt_footer(&qc->tf, &pp->dimm_buf[0], i);
/* copy three S/G tables and two packets to DIMM MMIO window */
memcpy_toio(dimm_mmio + (portno * PDC_DIMM_WINDOW_STEP),
&pp->dimm_buf, PDC_DIMM_HEADER_SZ);
/* force host FIFO dump */
writel(0x00000001, mmio + PDC_20621_GENERAL_CTL);
readl(dimm_mmio); /* MMIO PCI posting flush */
VPRINTK("ata pkt buf ofs %u, mmio copied\n", i);
}
static void pdc20621_qc_prep(struct ata_queued_cmd *qc)
{
switch (qc->tf.protocol) {
case ATA_PROT_DMA:
pdc20621_dma_prep(qc);
break;
case ATA_PROT_NODATA:
pdc20621_nodata_prep(qc);
break;
default:
break;
}
}
static void __pdc20621_push_hdma(struct ata_queued_cmd *qc,
unsigned int seq,
u32 pkt_ofs)
{
struct ata_port *ap = qc->ap;
struct ata_host *host = ap->host;
void __iomem *mmio = host->iomap[PDC_MMIO_BAR];
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
writel(0x00000001, mmio + PDC_20621_SEQCTL + (seq * 4));
readl(mmio + PDC_20621_SEQCTL + (seq * 4)); /* flush */
writel(pkt_ofs, mmio + PDC_HDMA_PKT_SUBMIT);
readl(mmio + PDC_HDMA_PKT_SUBMIT); /* flush */
}
static void pdc20621_push_hdma(struct ata_queued_cmd *qc,
unsigned int seq,
u32 pkt_ofs)
{
struct ata_port *ap = qc->ap;
struct pdc_host_priv *pp = ap->host->private_data;
unsigned int idx = pp->hdma_prod & PDC_HDMA_Q_MASK;
if (!pp->doing_hdma) {
__pdc20621_push_hdma(qc, seq, pkt_ofs);
pp->doing_hdma = 1;
return;
}
pp->hdma[idx].qc = qc;
pp->hdma[idx].seq = seq;
pp->hdma[idx].pkt_ofs = pkt_ofs;
pp->hdma_prod++;
}
static void pdc20621_pop_hdma(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct pdc_host_priv *pp = ap->host->private_data;
unsigned int idx = pp->hdma_cons & PDC_HDMA_Q_MASK;
/* if nothing on queue, we're done */
if (pp->hdma_prod == pp->hdma_cons) {
pp->doing_hdma = 0;
return;
}
__pdc20621_push_hdma(pp->hdma[idx].qc, pp->hdma[idx].seq,
pp->hdma[idx].pkt_ofs);
pp->hdma_cons++;
}
#ifdef ATA_VERBOSE_DEBUG
static void pdc20621_dump_hdma(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
unsigned int port_no = ap->port_no;
void __iomem *dimm_mmio = ap->host->iomap[PDC_DIMM_BAR];
dimm_mmio += (port_no * PDC_DIMM_WINDOW_STEP);
dimm_mmio += PDC_DIMM_HOST_PKT;
printk(KERN_ERR "HDMA[0] == 0x%08X\n", readl(dimm_mmio));
printk(KERN_ERR "HDMA[1] == 0x%08X\n", readl(dimm_mmio + 4));
printk(KERN_ERR "HDMA[2] == 0x%08X\n", readl(dimm_mmio + 8));
printk(KERN_ERR "HDMA[3] == 0x%08X\n", readl(dimm_mmio + 12));
}
#else
static inline void pdc20621_dump_hdma(struct ata_queued_cmd *qc) { }
#endif /* ATA_VERBOSE_DEBUG */
static void pdc20621_packet_start(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct ata_host *host = ap->host;
unsigned int port_no = ap->port_no;
void __iomem *mmio = host->iomap[PDC_MMIO_BAR];
unsigned int rw = (qc->tf.flags & ATA_TFLAG_WRITE);
u8 seq = (u8) (port_no + 1);
unsigned int port_ofs;
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
VPRINTK("ata%u: ENTER\n", ap->print_id);
wmb(); /* flush PRD, pkt writes */
port_ofs = PDC_20621_DIMM_BASE + (PDC_DIMM_WINDOW_STEP * port_no);
/* if writing, we (1) DMA to DIMM, then (2) do ATA command */
if (rw && qc->tf.protocol == ATA_PROT_DMA) {
seq += 4;
pdc20621_dump_hdma(qc);
pdc20621_push_hdma(qc, seq, port_ofs + PDC_DIMM_HOST_PKT);
VPRINTK("queued ofs 0x%x (%u), seq %u\n",
port_ofs + PDC_DIMM_HOST_PKT,
port_ofs + PDC_DIMM_HOST_PKT,
seq);
} else {
writel(0x00000001, mmio + PDC_20621_SEQCTL + (seq * 4));
readl(mmio + PDC_20621_SEQCTL + (seq * 4)); /* flush */
writel(port_ofs + PDC_DIMM_ATA_PKT,
ap->ioaddr.cmd_addr + PDC_PKT_SUBMIT);
readl(ap->ioaddr.cmd_addr + PDC_PKT_SUBMIT);
VPRINTK("submitted ofs 0x%x (%u), seq %u\n",
port_ofs + PDC_DIMM_ATA_PKT,
port_ofs + PDC_DIMM_ATA_PKT,
seq);
}
}
static unsigned int pdc20621_qc_issue(struct ata_queued_cmd *qc)
{
switch (qc->tf.protocol) {
case ATA_PROT_NODATA:
if (qc->tf.flags & ATA_TFLAG_POLLING)
break;
/*FALLTHROUGH*/
case ATA_PROT_DMA:
pdc20621_packet_start(qc);
return 0;
case ATAPI_PROT_DMA:
BUG();
break;
default:
break;
}
return ata_sff_qc_issue(qc);
}
static inline unsigned int pdc20621_host_intr(struct ata_port *ap,
struct ata_queued_cmd *qc,
unsigned int doing_hdma,
void __iomem *mmio)
{
unsigned int port_no = ap->port_no;
unsigned int port_ofs =
PDC_20621_DIMM_BASE + (PDC_DIMM_WINDOW_STEP * port_no);
u8 status;
unsigned int handled = 0;
VPRINTK("ENTER\n");
if ((qc->tf.protocol == ATA_PROT_DMA) && /* read */
(!(qc->tf.flags & ATA_TFLAG_WRITE))) {
/* step two - DMA from DIMM to host */
if (doing_hdma) {
VPRINTK("ata%u: read hdma, 0x%x 0x%x\n", ap->print_id,
readl(mmio + 0x104), readl(mmio + PDC_HDMA_CTLSTAT));
/* get drive status; clear intr; complete txn */
qc->err_mask |= ac_err_mask(ata_wait_idle(ap));
ata_qc_complete(qc);
pdc20621_pop_hdma(qc);
}
/* step one - exec ATA command */
else {
u8 seq = (u8) (port_no + 1 + 4);
VPRINTK("ata%u: read ata, 0x%x 0x%x\n", ap->print_id,
readl(mmio + 0x104), readl(mmio + PDC_HDMA_CTLSTAT));
/* submit hdma pkt */
pdc20621_dump_hdma(qc);
pdc20621_push_hdma(qc, seq,
port_ofs + PDC_DIMM_HOST_PKT);
}
handled = 1;
} else if (qc->tf.protocol == ATA_PROT_DMA) { /* write */
/* step one - DMA from host to DIMM */
if (doing_hdma) {
u8 seq = (u8) (port_no + 1);
VPRINTK("ata%u: write hdma, 0x%x 0x%x\n", ap->print_id,
readl(mmio + 0x104), readl(mmio + PDC_HDMA_CTLSTAT));
/* submit ata pkt */
writel(0x00000001, mmio + PDC_20621_SEQCTL + (seq * 4));
readl(mmio + PDC_20621_SEQCTL + (seq * 4));
writel(port_ofs + PDC_DIMM_ATA_PKT,
ap->ioaddr.cmd_addr + PDC_PKT_SUBMIT);
readl(ap->ioaddr.cmd_addr + PDC_PKT_SUBMIT);
}
/* step two - execute ATA command */
else {
VPRINTK("ata%u: write ata, 0x%x 0x%x\n", ap->print_id,
readl(mmio + 0x104), readl(mmio + PDC_HDMA_CTLSTAT));
/* get drive status; clear intr; complete txn */
qc->err_mask |= ac_err_mask(ata_wait_idle(ap));
ata_qc_complete(qc);
pdc20621_pop_hdma(qc);
}
handled = 1;
/* command completion, but no data xfer */
} else if (qc->tf.protocol == ATA_PROT_NODATA) {
status = ata_sff_busy_wait(ap, ATA_BUSY | ATA_DRQ, 1000);
DPRINTK("BUS_NODATA (drv_stat 0x%X)\n", status);
qc->err_mask |= ac_err_mask(status);
ata_qc_complete(qc);
handled = 1;
} else {
ap->stats.idle_irq++;
}
return handled;
}
static void pdc20621_irq_clear(struct ata_port *ap)
{
ioread8(ap->ioaddr.status_addr);
}
static irqreturn_t pdc20621_interrupt(int irq, void *dev_instance)
{
struct ata_host *host = dev_instance;
struct ata_port *ap;
u32 mask = 0;
unsigned int i, tmp, port_no;
unsigned int handled = 0;
void __iomem *mmio_base;
VPRINTK("ENTER\n");
if (!host || !host->iomap[PDC_MMIO_BAR]) {
VPRINTK("QUICK EXIT\n");
return IRQ_NONE;
}
mmio_base = host->iomap[PDC_MMIO_BAR];
/* reading should also clear interrupts */
mmio_base += PDC_CHIP0_OFS;
mask = readl(mmio_base + PDC_20621_SEQMASK);
VPRINTK("mask == 0x%x\n", mask);
if (mask == 0xffffffff) {
VPRINTK("QUICK EXIT 2\n");
return IRQ_NONE;
}
mask &= 0xffff; /* only 16 tags possible */
if (!mask) {
VPRINTK("QUICK EXIT 3\n");
return IRQ_NONE;
}
spin_lock(&host->lock);
for (i = 1; i < 9; i++) {
port_no = i - 1;
if (port_no > 3)
port_no -= 4;
if (port_no >= host->n_ports)
ap = NULL;
else
ap = host->ports[port_no];
tmp = mask & (1 << i);
VPRINTK("seq %u, port_no %u, ap %p, tmp %x\n", i, port_no, ap, tmp);
if (tmp && ap) {
struct ata_queued_cmd *qc;
qc = ata_qc_from_tag(ap, ap->link.active_tag);
if (qc && (!(qc->tf.flags & ATA_TFLAG_POLLING)))
handled += pdc20621_host_intr(ap, qc, (i > 4),
mmio_base);
}
}
spin_unlock(&host->lock);
VPRINTK("mask == 0x%x\n", mask);
VPRINTK("EXIT\n");
return IRQ_RETVAL(handled);
}
static void pdc_freeze(struct ata_port *ap)
{
void __iomem *mmio = ap->ioaddr.cmd_addr;
u32 tmp;
/* FIXME: if all 4 ATA engines are stopped, also stop HDMA engine */
tmp = readl(mmio + PDC_CTLSTAT);
tmp |= PDC_MASK_INT;
tmp &= ~PDC_DMA_ENABLE;
writel(tmp, mmio + PDC_CTLSTAT);
readl(mmio + PDC_CTLSTAT); /* flush */
}
static void pdc_thaw(struct ata_port *ap)
{
void __iomem *mmio = ap->ioaddr.cmd_addr;
u32 tmp;
/* FIXME: start HDMA engine, if zero ATA engines running */
/* clear IRQ */
ioread8(ap->ioaddr.status_addr);
/* turn IRQ back on */
tmp = readl(mmio + PDC_CTLSTAT);
tmp &= ~PDC_MASK_INT;
writel(tmp, mmio + PDC_CTLSTAT);
readl(mmio + PDC_CTLSTAT); /* flush */
}
static void pdc_reset_port(struct ata_port *ap)
{
void __iomem *mmio = ap->ioaddr.cmd_addr + PDC_CTLSTAT;
unsigned int i;
u32 tmp;
/* FIXME: handle HDMA copy engine */
for (i = 11; i > 0; i--) {
tmp = readl(mmio);
if (tmp & PDC_RESET)
break;
udelay(100);
tmp |= PDC_RESET;
writel(tmp, mmio);
}
tmp &= ~PDC_RESET;
writel(tmp, mmio);
readl(mmio); /* flush */
}
static int pdc_softreset(struct ata_link *link, unsigned int *class,
unsigned long deadline)
{
pdc_reset_port(link->ap);
return ata_sff_softreset(link, class, deadline);
}
static void pdc_error_handler(struct ata_port *ap)
{
if (!(ap->pflags & ATA_PFLAG_FROZEN))
pdc_reset_port(ap);
ata_sff_error_handler(ap);
}
static void pdc_post_internal_cmd(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
/* make DMA engine forget about the failed command */
if (qc->flags & ATA_QCFLAG_FAILED)
pdc_reset_port(ap);
}
static int pdc_check_atapi_dma(struct ata_queued_cmd *qc)
{
u8 *scsicmd = qc->scsicmd->cmnd;
int pio = 1; /* atapi dma off by default */
/* Whitelist commands that may use DMA. */
switch (scsicmd[0]) {
case WRITE_12:
case WRITE_10:
case WRITE_6:
case READ_12:
case READ_10:
case READ_6:
case 0xad: /* READ_DVD_STRUCTURE */
case 0xbe: /* READ_CD */
pio = 0;
}
/* -45150 (FFFF4FA2) to -1 (FFFFFFFF) shall use PIO mode */
if (scsicmd[0] == WRITE_10) {
unsigned int lba =
(scsicmd[2] << 24) |
(scsicmd[3] << 16) |
(scsicmd[4] << 8) |
scsicmd[5];
if (lba >= 0xFFFF4FA2)
pio = 1;
}
return pio;
}
static void pdc_tf_load_mmio(struct ata_port *ap, const struct ata_taskfile *tf)
{
WARN_ON(tf->protocol == ATA_PROT_DMA ||
tf->protocol == ATAPI_PROT_DMA);
ata_sff_tf_load(ap, tf);
}
static void pdc_exec_command_mmio(struct ata_port *ap, const struct ata_taskfile *tf)
{
WARN_ON(tf->protocol == ATA_PROT_DMA ||
tf->protocol == ATAPI_PROT_DMA);
ata_sff_exec_command(ap, tf);
}
static void pdc_sata_setup_port(struct ata_ioports *port, void __iomem *base)
{
port->cmd_addr = base;
port->data_addr = base;
port->feature_addr =
port->error_addr = base + 0x4;
port->nsect_addr = base + 0x8;
port->lbal_addr = base + 0xc;
port->lbam_addr = base + 0x10;
port->lbah_addr = base + 0x14;
port->device_addr = base + 0x18;
port->command_addr =
port->status_addr = base + 0x1c;
port->altstatus_addr =
port->ctl_addr = base + 0x38;
}
#ifdef ATA_VERBOSE_DEBUG
static void pdc20621_get_from_dimm(struct ata_host *host, void *psource,
u32 offset, u32 size)
{
u32 window_size;
u16 idx;
u8 page_mask;
long dist;
void __iomem *mmio = host->iomap[PDC_MMIO_BAR];
void __iomem *dimm_mmio = host->iomap[PDC_DIMM_BAR];
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
page_mask = 0x00;
window_size = 0x2000 * 4; /* 32K byte uchar size */
idx = (u16) (offset / window_size);
writel(0x01, mmio + PDC_GENERAL_CTLR);
readl(mmio + PDC_GENERAL_CTLR);
writel(((idx) << page_mask), mmio + PDC_DIMM_WINDOW_CTLR);
readl(mmio + PDC_DIMM_WINDOW_CTLR);
offset -= (idx * window_size);
idx++;
dist = ((long) (window_size - (offset + size))) >= 0 ? size :
(long) (window_size - offset);
memcpy_fromio((char *) psource, (char *) (dimm_mmio + offset / 4),
dist);
psource += dist;
size -= dist;
for (; (long) size >= (long) window_size ;) {
writel(0x01, mmio + PDC_GENERAL_CTLR);
readl(mmio + PDC_GENERAL_CTLR);
writel(((idx) << page_mask), mmio + PDC_DIMM_WINDOW_CTLR);
readl(mmio + PDC_DIMM_WINDOW_CTLR);
memcpy_fromio((char *) psource, (char *) (dimm_mmio),
window_size / 4);
psource += window_size;
size -= window_size;
idx++;
}
if (size) {
writel(0x01, mmio + PDC_GENERAL_CTLR);
readl(mmio + PDC_GENERAL_CTLR);
writel(((idx) << page_mask), mmio + PDC_DIMM_WINDOW_CTLR);
readl(mmio + PDC_DIMM_WINDOW_CTLR);
memcpy_fromio((char *) psource, (char *) (dimm_mmio),
size / 4);
}
}
#endif
static void pdc20621_put_to_dimm(struct ata_host *host, void *psource,
u32 offset, u32 size)
{
u32 window_size;
u16 idx;
u8 page_mask;
long dist;
void __iomem *mmio = host->iomap[PDC_MMIO_BAR];
void __iomem *dimm_mmio = host->iomap[PDC_DIMM_BAR];
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
page_mask = 0x00;
window_size = 0x2000 * 4; /* 32K byte uchar size */
idx = (u16) (offset / window_size);
writel(((idx) << page_mask), mmio + PDC_DIMM_WINDOW_CTLR);
readl(mmio + PDC_DIMM_WINDOW_CTLR);
offset -= (idx * window_size);
idx++;
dist = ((long)(s32)(window_size - (offset + size))) >= 0 ? size :
(long) (window_size - offset);
memcpy_toio(dimm_mmio + offset / 4, psource, dist);
writel(0x01, mmio + PDC_GENERAL_CTLR);
readl(mmio + PDC_GENERAL_CTLR);
psource += dist;
size -= dist;
for (; (long) size >= (long) window_size ;) {
writel(((idx) << page_mask), mmio + PDC_DIMM_WINDOW_CTLR);
readl(mmio + PDC_DIMM_WINDOW_CTLR);
memcpy_toio(dimm_mmio, psource, window_size / 4);
writel(0x01, mmio + PDC_GENERAL_CTLR);
readl(mmio + PDC_GENERAL_CTLR);
psource += window_size;
size -= window_size;
idx++;
}
if (size) {
writel(((idx) << page_mask), mmio + PDC_DIMM_WINDOW_CTLR);
readl(mmio + PDC_DIMM_WINDOW_CTLR);
memcpy_toio(dimm_mmio, psource, size / 4);
writel(0x01, mmio + PDC_GENERAL_CTLR);
readl(mmio + PDC_GENERAL_CTLR);
}
}
static unsigned int pdc20621_i2c_read(struct ata_host *host, u32 device,
u32 subaddr, u32 *pdata)
{
void __iomem *mmio = host->iomap[PDC_MMIO_BAR];
u32 i2creg = 0;
u32 status;
u32 count = 0;
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
i2creg |= device << 24;
i2creg |= subaddr << 16;
/* Set the device and subaddress */
writel(i2creg, mmio + PDC_I2C_ADDR_DATA);
readl(mmio + PDC_I2C_ADDR_DATA);
/* Write Control to perform read operation, mask int */
writel(PDC_I2C_READ | PDC_I2C_START | PDC_I2C_MASK_INT,
mmio + PDC_I2C_CONTROL);
for (count = 0; count <= 1000; count ++) {
status = readl(mmio + PDC_I2C_CONTROL);
if (status & PDC_I2C_COMPLETE) {
status = readl(mmio + PDC_I2C_ADDR_DATA);
break;
} else if (count == 1000)
return 0;
}
*pdata = (status >> 8) & 0x000000ff;
return 1;
}
static int pdc20621_detect_dimm(struct ata_host *host)
{
u32 data = 0;
if (pdc20621_i2c_read(host, PDC_DIMM0_SPD_DEV_ADDRESS,
PDC_DIMM_SPD_SYSTEM_FREQ, &data)) {
if (data == 100)
return 100;
} else
return 0;
if (pdc20621_i2c_read(host, PDC_DIMM0_SPD_DEV_ADDRESS, 9, &data)) {
if (data <= 0x75)
return 133;
} else
return 0;
return 0;
}
static int pdc20621_prog_dimm0(struct ata_host *host)
{
u32 spd0[50];
u32 data = 0;
int size, i;
u8 bdimmsize;
void __iomem *mmio = host->iomap[PDC_MMIO_BAR];
static const struct {
unsigned int reg;
unsigned int ofs;
} pdc_i2c_read_data [] = {
{ PDC_DIMM_SPD_TYPE, 11 },
{ PDC_DIMM_SPD_FRESH_RATE, 12 },
{ PDC_DIMM_SPD_COLUMN_NUM, 4 },
{ PDC_DIMM_SPD_ATTRIBUTE, 21 },
{ PDC_DIMM_SPD_ROW_NUM, 3 },
{ PDC_DIMM_SPD_BANK_NUM, 17 },
{ PDC_DIMM_SPD_MODULE_ROW, 5 },
{ PDC_DIMM_SPD_ROW_PRE_CHARGE, 27 },
{ PDC_DIMM_SPD_ROW_ACTIVE_DELAY, 28 },
{ PDC_DIMM_SPD_RAS_CAS_DELAY, 29 },
{ PDC_DIMM_SPD_ACTIVE_PRECHARGE, 30 },
{ PDC_DIMM_SPD_CAS_LATENCY, 18 },
};
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
for (i = 0; i < ARRAY_SIZE(pdc_i2c_read_data); i++)
pdc20621_i2c_read(host, PDC_DIMM0_SPD_DEV_ADDRESS,
pdc_i2c_read_data[i].reg,
&spd0[pdc_i2c_read_data[i].ofs]);
data |= (spd0[4] - 8) | ((spd0[21] != 0) << 3) | ((spd0[3]-11) << 4);
data |= ((spd0[17] / 4) << 6) | ((spd0[5] / 2) << 7) |
((((spd0[27] + 9) / 10) - 1) << 8) ;
data |= (((((spd0[29] > spd0[28])
? spd0[29] : spd0[28]) + 9) / 10) - 1) << 10;
data |= ((spd0[30] - spd0[29] + 9) / 10 - 2) << 12;
if (spd0[18] & 0x08)
data |= ((0x03) << 14);
else if (spd0[18] & 0x04)
data |= ((0x02) << 14);
else if (spd0[18] & 0x01)
data |= ((0x01) << 14);
else
data |= (0 << 14);
/*
Calculate the size of bDIMMSize (power of 2) and
merge the DIMM size by program start/end address.
*/
bdimmsize = spd0[4] + (spd0[5] / 2) + spd0[3] + (spd0[17] / 2) + 3;
size = (1 << bdimmsize) >> 20; /* size = xxx(MB) */
data |= (((size / 16) - 1) << 16);
data |= (0 << 23);
data |= 8;
writel(data, mmio + PDC_DIMM0_CONTROL);
readl(mmio + PDC_DIMM0_CONTROL);
return size;
}
static unsigned int pdc20621_prog_dimm_global(struct ata_host *host)
{
u32 data, spd0;
int error, i;
void __iomem *mmio = host->iomap[PDC_MMIO_BAR];
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
/*
Set To Default : DIMM Module Global Control Register (0x022259F1)
DIMM Arbitration Disable (bit 20)
DIMM Data/Control Output Driving Selection (bit12 - bit15)
Refresh Enable (bit 17)
*/
data = 0x022259F1;
writel(data, mmio + PDC_SDRAM_CONTROL);
readl(mmio + PDC_SDRAM_CONTROL);
/* Turn on for ECC */
pdc20621_i2c_read(host, PDC_DIMM0_SPD_DEV_ADDRESS,
PDC_DIMM_SPD_TYPE, &spd0);
if (spd0 == 0x02) {
data |= (0x01 << 16);
writel(data, mmio + PDC_SDRAM_CONTROL);
readl(mmio + PDC_SDRAM_CONTROL);
printk(KERN_ERR "Local DIMM ECC Enabled\n");
}
/* DIMM Initialization Select/Enable (bit 18/19) */
data &= (~(1<<18));
data |= (1<<19);
writel(data, mmio + PDC_SDRAM_CONTROL);
error = 1;
for (i = 1; i <= 10; i++) { /* polling ~5 secs */
data = readl(mmio + PDC_SDRAM_CONTROL);
if (!(data & (1<<19))) {
error = 0;
break;
}
msleep(i*100);
}
return error;
}
static unsigned int pdc20621_dimm_init(struct ata_host *host)
{
int speed, size, length;
u32 addr, spd0, pci_status;
u32 time_period = 0;
u32 tcount = 0;
u32 ticks = 0;
u32 clock = 0;
u32 fparam = 0;
void __iomem *mmio = host->iomap[PDC_MMIO_BAR];
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
/* Initialize PLL based upon PCI Bus Frequency */
/* Initialize Time Period Register */
writel(0xffffffff, mmio + PDC_TIME_PERIOD);
time_period = readl(mmio + PDC_TIME_PERIOD);
VPRINTK("Time Period Register (0x40): 0x%x\n", time_period);
/* Enable timer */
writel(PDC_TIMER_DEFAULT, mmio + PDC_TIME_CONTROL);
readl(mmio + PDC_TIME_CONTROL);
/* Wait 3 seconds */
msleep(3000);
/*
When timer is enabled, counter is decreased every internal
clock cycle.
*/
tcount = readl(mmio + PDC_TIME_COUNTER);
VPRINTK("Time Counter Register (0x44): 0x%x\n", tcount);
/*
If SX4 is on PCI-X bus, after 3 seconds, the timer counter
register should be >= (0xffffffff - 3x10^8).
*/
if (tcount >= PCI_X_TCOUNT) {
ticks = (time_period - tcount);
VPRINTK("Num counters 0x%x (%d)\n", ticks, ticks);
clock = (ticks / 300000);
VPRINTK("10 * Internal clk = 0x%x (%d)\n", clock, clock);
clock = (clock * 33);
VPRINTK("10 * Internal clk * 33 = 0x%x (%d)\n", clock, clock);
/* PLL F Param (bit 22:16) */
fparam = (1400000 / clock) - 2;
VPRINTK("PLL F Param: 0x%x (%d)\n", fparam, fparam);
/* OD param = 0x2 (bit 31:30), R param = 0x5 (bit 29:25) */
pci_status = (0x8a001824 | (fparam << 16));
} else
pci_status = PCI_PLL_INIT;
/* Initialize PLL. */
VPRINTK("pci_status: 0x%x\n", pci_status);
writel(pci_status, mmio + PDC_CTL_STATUS);
readl(mmio + PDC_CTL_STATUS);
/*
Read SPD of DIMM by I2C interface,
and program the DIMM Module Controller.
*/
if (!(speed = pdc20621_detect_dimm(host))) {
printk(KERN_ERR "Detect Local DIMM Fail\n");
return 1; /* DIMM error */
}
VPRINTK("Local DIMM Speed = %d\n", speed);
/* Programming DIMM0 Module Control Register (index_CID0:80h) */
size = pdc20621_prog_dimm0(host);
VPRINTK("Local DIMM Size = %dMB\n", size);
/* Programming DIMM Module Global Control Register (index_CID0:88h) */
if (pdc20621_prog_dimm_global(host)) {
printk(KERN_ERR "Programming DIMM Module Global Control Register Fail\n");
return 1;
}
#ifdef ATA_VERBOSE_DEBUG
{
u8 test_parttern1[40] =
{0x55,0xAA,'P','r','o','m','i','s','e',' ',
'N','o','t',' ','Y','e','t',' ',
'D','e','f','i','n','e','d',' ',
'1','.','1','0',
'9','8','0','3','1','6','1','2',0,0};
u8 test_parttern2[40] = {0};
pdc20621_put_to_dimm(host, test_parttern2, 0x10040, 40);
pdc20621_put_to_dimm(host, test_parttern2, 0x40, 40);
pdc20621_put_to_dimm(host, test_parttern1, 0x10040, 40);
pdc20621_get_from_dimm(host, test_parttern2, 0x40, 40);
printk(KERN_ERR "%x, %x, %s\n", test_parttern2[0],
test_parttern2[1], &(test_parttern2[2]));
pdc20621_get_from_dimm(host, test_parttern2, 0x10040,
40);
printk(KERN_ERR "%x, %x, %s\n", test_parttern2[0],
test_parttern2[1], &(test_parttern2[2]));
pdc20621_put_to_dimm(host, test_parttern1, 0x40, 40);
pdc20621_get_from_dimm(host, test_parttern2, 0x40, 40);
printk(KERN_ERR "%x, %x, %s\n", test_parttern2[0],
test_parttern2[1], &(test_parttern2[2]));
}
#endif
/* ECC initiliazation. */
pdc20621_i2c_read(host, PDC_DIMM0_SPD_DEV_ADDRESS,
PDC_DIMM_SPD_TYPE, &spd0);
if (spd0 == 0x02) {
void *buf;
VPRINTK("Start ECC initialization\n");
addr = 0;
length = size * 1024 * 1024;
buf = kzalloc(ECC_ERASE_BUF_SZ, GFP_KERNEL);
while (addr < length) {
pdc20621_put_to_dimm(host, buf, addr,
ECC_ERASE_BUF_SZ);
addr += ECC_ERASE_BUF_SZ;
}
kfree(buf);
VPRINTK("Finish ECC initialization\n");
}
return 0;
}
static void pdc_20621_init(struct ata_host *host)
{
u32 tmp;
void __iomem *mmio = host->iomap[PDC_MMIO_BAR];
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
/*
* Select page 0x40 for our 32k DIMM window
*/
tmp = readl(mmio + PDC_20621_DIMM_WINDOW) & 0xffff0000;
tmp |= PDC_PAGE_WINDOW; /* page 40h; arbitrarily selected */
writel(tmp, mmio + PDC_20621_DIMM_WINDOW);
/*
* Reset Host DMA
*/
tmp = readl(mmio + PDC_HDMA_CTLSTAT);
tmp |= PDC_RESET;
writel(tmp, mmio + PDC_HDMA_CTLSTAT);
readl(mmio + PDC_HDMA_CTLSTAT); /* flush */
udelay(10);
tmp = readl(mmio + PDC_HDMA_CTLSTAT);
tmp &= ~PDC_RESET;
writel(tmp, mmio + PDC_HDMA_CTLSTAT);
readl(mmio + PDC_HDMA_CTLSTAT); /* flush */
}
static int pdc_sata_init_one(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
static int printed_version;
const struct ata_port_info *ppi[] =
{ &pdc_port_info[ent->driver_data], NULL };
struct ata_host *host;
struct pdc_host_priv *hpriv;
int i, rc;
if (!printed_version++)
dev_printk(KERN_DEBUG, &pdev->dev, "version " DRV_VERSION "\n");
/* allocate host */
host = ata_host_alloc_pinfo(&pdev->dev, ppi, 4);
hpriv = devm_kzalloc(&pdev->dev, sizeof(*hpriv), GFP_KERNEL);
if (!host || !hpriv)
return -ENOMEM;
host->private_data = hpriv;
/* acquire resources and fill host */
rc = pcim_enable_device(pdev);
if (rc)
return rc;
rc = pcim_iomap_regions(pdev, (1 << PDC_MMIO_BAR) | (1 << PDC_DIMM_BAR),
DRV_NAME);
if (rc == -EBUSY)
pcim_pin_device(pdev);
if (rc)
return rc;
host->iomap = pcim_iomap_table(pdev);
for (i = 0; i < 4; i++) {
struct ata_port *ap = host->ports[i];
void __iomem *base = host->iomap[PDC_MMIO_BAR] + PDC_CHIP0_OFS;
unsigned int offset = 0x200 + i * 0x80;
pdc_sata_setup_port(&ap->ioaddr, base + offset);
ata_port_pbar_desc(ap, PDC_MMIO_BAR, -1, "mmio");
ata_port_pbar_desc(ap, PDC_DIMM_BAR, -1, "dimm");
ata_port_pbar_desc(ap, PDC_MMIO_BAR, offset, "port");
}
/* configure and activate */
rc = pci_set_dma_mask(pdev, ATA_DMA_MASK);
if (rc)
return rc;
rc = pci_set_consistent_dma_mask(pdev, ATA_DMA_MASK);
if (rc)
return rc;
if (pdc20621_dimm_init(host))
return -ENOMEM;
pdc_20621_init(host);
pci_set_master(pdev);
return ata_host_activate(host, pdev->irq, pdc20621_interrupt,
IRQF_SHARED, &pdc_sata_sht);
}
static int __init pdc_sata_init(void)
{
return pci_register_driver(&pdc_sata_pci_driver);
}
static void __exit pdc_sata_exit(void)
{
pci_unregister_driver(&pdc_sata_pci_driver);
}
MODULE_AUTHOR("Jeff Garzik");
MODULE_DESCRIPTION("Promise SATA low-level driver");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, pdc_sata_pci_tbl);
MODULE_VERSION(DRV_VERSION);
module_init(pdc_sata_init);
module_exit(pdc_sata_exit);
| gpl-2.0 |
sktjdgns1189/android_kernel_samsung_SHW-M340S | arch/x86/kernel/signal.c | 1267 | 22479 | /*
* Copyright (C) 1991, 1992 Linus Torvalds
* Copyright (C) 2000, 2001, 2002 Andi Kleen SuSE Labs
*
* 1997-11-28 Modified for POSIX.1b signals by Richard Henderson
* 2000-06-20 Pentium III FXSR, SSE support by Gareth Hughes
* 2000-2002 x86-64 support by Andi Kleen
*/
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/smp.h>
#include <linux/kernel.h>
#include <linux/signal.h>
#include <linux/errno.h>
#include <linux/wait.h>
#include <linux/ptrace.h>
#include <linux/tracehook.h>
#include <linux/unistd.h>
#include <linux/stddef.h>
#include <linux/personality.h>
#include <linux/uaccess.h>
#include <linux/user-return-notifier.h>
#include <asm/processor.h>
#include <asm/ucontext.h>
#include <asm/i387.h>
#include <asm/vdso.h>
#include <asm/mce.h>
#ifdef CONFIG_X86_64
#include <asm/proto.h>
#include <asm/ia32_unistd.h>
#endif /* CONFIG_X86_64 */
#include <asm/syscall.h>
#include <asm/syscalls.h>
#include <asm/sigframe.h>
#define _BLOCKABLE (~(sigmask(SIGKILL) | sigmask(SIGSTOP)))
#define __FIX_EFLAGS (X86_EFLAGS_AC | X86_EFLAGS_OF | \
X86_EFLAGS_DF | X86_EFLAGS_TF | X86_EFLAGS_SF | \
X86_EFLAGS_ZF | X86_EFLAGS_AF | X86_EFLAGS_PF | \
X86_EFLAGS_CF)
#ifdef CONFIG_X86_32
# define FIX_EFLAGS (__FIX_EFLAGS | X86_EFLAGS_RF)
#else
# define FIX_EFLAGS __FIX_EFLAGS
#endif
#define COPY(x) do { \
get_user_ex(regs->x, &sc->x); \
} while (0)
#define GET_SEG(seg) ({ \
unsigned short tmp; \
get_user_ex(tmp, &sc->seg); \
tmp; \
})
#define COPY_SEG(seg) do { \
regs->seg = GET_SEG(seg); \
} while (0)
#define COPY_SEG_CPL3(seg) do { \
regs->seg = GET_SEG(seg) | 3; \
} while (0)
static int
restore_sigcontext(struct pt_regs *regs, struct sigcontext __user *sc,
unsigned long *pax)
{
void __user *buf;
unsigned int tmpflags;
unsigned int err = 0;
/* Always make any pending restarted system calls return -EINTR */
current_thread_info()->restart_block.fn = do_no_restart_syscall;
get_user_try {
#ifdef CONFIG_X86_32
set_user_gs(regs, GET_SEG(gs));
COPY_SEG(fs);
COPY_SEG(es);
COPY_SEG(ds);
#endif /* CONFIG_X86_32 */
COPY(di); COPY(si); COPY(bp); COPY(sp); COPY(bx);
COPY(dx); COPY(cx); COPY(ip);
#ifdef CONFIG_X86_64
COPY(r8);
COPY(r9);
COPY(r10);
COPY(r11);
COPY(r12);
COPY(r13);
COPY(r14);
COPY(r15);
#endif /* CONFIG_X86_64 */
#ifdef CONFIG_X86_32
COPY_SEG_CPL3(cs);
COPY_SEG_CPL3(ss);
#else /* !CONFIG_X86_32 */
/* Kernel saves and restores only the CS segment register on signals,
* which is the bare minimum needed to allow mixed 32/64-bit code.
* App's signal handler can save/restore other segments if needed. */
COPY_SEG_CPL3(cs);
#endif /* CONFIG_X86_32 */
get_user_ex(tmpflags, &sc->flags);
regs->flags = (regs->flags & ~FIX_EFLAGS) | (tmpflags & FIX_EFLAGS);
regs->orig_ax = -1; /* disable syscall checks */
get_user_ex(buf, &sc->fpstate);
err |= restore_i387_xstate(buf);
get_user_ex(*pax, &sc->ax);
} get_user_catch(err);
return err;
}
static int
setup_sigcontext(struct sigcontext __user *sc, void __user *fpstate,
struct pt_regs *regs, unsigned long mask)
{
int err = 0;
put_user_try {
#ifdef CONFIG_X86_32
put_user_ex(get_user_gs(regs), (unsigned int __user *)&sc->gs);
put_user_ex(regs->fs, (unsigned int __user *)&sc->fs);
put_user_ex(regs->es, (unsigned int __user *)&sc->es);
put_user_ex(regs->ds, (unsigned int __user *)&sc->ds);
#endif /* CONFIG_X86_32 */
put_user_ex(regs->di, &sc->di);
put_user_ex(regs->si, &sc->si);
put_user_ex(regs->bp, &sc->bp);
put_user_ex(regs->sp, &sc->sp);
put_user_ex(regs->bx, &sc->bx);
put_user_ex(regs->dx, &sc->dx);
put_user_ex(regs->cx, &sc->cx);
put_user_ex(regs->ax, &sc->ax);
#ifdef CONFIG_X86_64
put_user_ex(regs->r8, &sc->r8);
put_user_ex(regs->r9, &sc->r9);
put_user_ex(regs->r10, &sc->r10);
put_user_ex(regs->r11, &sc->r11);
put_user_ex(regs->r12, &sc->r12);
put_user_ex(regs->r13, &sc->r13);
put_user_ex(regs->r14, &sc->r14);
put_user_ex(regs->r15, &sc->r15);
#endif /* CONFIG_X86_64 */
put_user_ex(current->thread.trap_no, &sc->trapno);
put_user_ex(current->thread.error_code, &sc->err);
put_user_ex(regs->ip, &sc->ip);
#ifdef CONFIG_X86_32
put_user_ex(regs->cs, (unsigned int __user *)&sc->cs);
put_user_ex(regs->flags, &sc->flags);
put_user_ex(regs->sp, &sc->sp_at_signal);
put_user_ex(regs->ss, (unsigned int __user *)&sc->ss);
#else /* !CONFIG_X86_32 */
put_user_ex(regs->flags, &sc->flags);
put_user_ex(regs->cs, &sc->cs);
put_user_ex(0, &sc->gs);
put_user_ex(0, &sc->fs);
#endif /* CONFIG_X86_32 */
put_user_ex(fpstate, &sc->fpstate);
/* non-iBCS2 extensions.. */
put_user_ex(mask, &sc->oldmask);
put_user_ex(current->thread.cr2, &sc->cr2);
} put_user_catch(err);
return err;
}
/*
* Set up a signal frame.
*/
/*
* Determine which stack to use..
*/
static unsigned long align_sigframe(unsigned long sp)
{
#ifdef CONFIG_X86_32
/*
* Align the stack pointer according to the i386 ABI,
* i.e. so that on function entry ((sp + 4) & 15) == 0.
*/
sp = ((sp + 4) & -16ul) - 4;
#else /* !CONFIG_X86_32 */
sp = round_down(sp, 16) - 8;
#endif
return sp;
}
static inline void __user *
get_sigframe(struct k_sigaction *ka, struct pt_regs *regs, size_t frame_size,
void __user **fpstate)
{
/* Default to using normal stack */
unsigned long sp = regs->sp;
int onsigstack = on_sig_stack(sp);
#ifdef CONFIG_X86_64
/* redzone */
sp -= 128;
#endif /* CONFIG_X86_64 */
if (!onsigstack) {
/* This is the X/Open sanctioned signal stack switching. */
if (ka->sa.sa_flags & SA_ONSTACK) {
if (current->sas_ss_size)
sp = current->sas_ss_sp + current->sas_ss_size;
} else {
#ifdef CONFIG_X86_32
/* This is the legacy signal stack switching. */
if ((regs->ss & 0xffff) != __USER_DS &&
!(ka->sa.sa_flags & SA_RESTORER) &&
ka->sa.sa_restorer)
sp = (unsigned long) ka->sa.sa_restorer;
#endif /* CONFIG_X86_32 */
}
}
if (used_math()) {
sp -= sig_xstate_size;
#ifdef CONFIG_X86_64
sp = round_down(sp, 64);
#endif /* CONFIG_X86_64 */
*fpstate = (void __user *)sp;
}
sp = align_sigframe(sp - frame_size);
/*
* If we are on the alternate signal stack and would overflow it, don't.
* Return an always-bogus address instead so we will die with SIGSEGV.
*/
if (onsigstack && !likely(on_sig_stack(sp)))
return (void __user *)-1L;
/* save i387 state */
if (used_math() && save_i387_xstate(*fpstate) < 0)
return (void __user *)-1L;
return (void __user *)sp;
}
#ifdef CONFIG_X86_32
static const struct {
u16 poplmovl;
u32 val;
u16 int80;
} __attribute__((packed)) retcode = {
0xb858, /* popl %eax; movl $..., %eax */
__NR_sigreturn,
0x80cd, /* int $0x80 */
};
static const struct {
u8 movl;
u32 val;
u16 int80;
u8 pad;
} __attribute__((packed)) rt_retcode = {
0xb8, /* movl $..., %eax */
__NR_rt_sigreturn,
0x80cd, /* int $0x80 */
0
};
static int
__setup_frame(int sig, struct k_sigaction *ka, sigset_t *set,
struct pt_regs *regs)
{
struct sigframe __user *frame;
void __user *restorer;
int err = 0;
void __user *fpstate = NULL;
frame = get_sigframe(ka, regs, sizeof(*frame), &fpstate);
if (!access_ok(VERIFY_WRITE, frame, sizeof(*frame)))
return -EFAULT;
if (__put_user(sig, &frame->sig))
return -EFAULT;
if (setup_sigcontext(&frame->sc, fpstate, regs, set->sig[0]))
return -EFAULT;
if (_NSIG_WORDS > 1) {
if (__copy_to_user(&frame->extramask, &set->sig[1],
sizeof(frame->extramask)))
return -EFAULT;
}
if (current->mm->context.vdso)
restorer = VDSO32_SYMBOL(current->mm->context.vdso, sigreturn);
else
restorer = &frame->retcode;
if (ka->sa.sa_flags & SA_RESTORER)
restorer = ka->sa.sa_restorer;
/* Set up to return from userspace. */
err |= __put_user(restorer, &frame->pretcode);
/*
* This is popl %eax ; movl $__NR_sigreturn, %eax ; int $0x80
*
* WE DO NOT USE IT ANY MORE! It's only left here for historical
* reasons and because gdb uses it as a signature to notice
* signal handler stack frames.
*/
err |= __put_user(*((u64 *)&retcode), (u64 *)frame->retcode);
if (err)
return -EFAULT;
/* Set up registers for signal handler */
regs->sp = (unsigned long)frame;
regs->ip = (unsigned long)ka->sa.sa_handler;
regs->ax = (unsigned long)sig;
regs->dx = 0;
regs->cx = 0;
regs->ds = __USER_DS;
regs->es = __USER_DS;
regs->ss = __USER_DS;
regs->cs = __USER_CS;
return 0;
}
static int __setup_rt_frame(int sig, struct k_sigaction *ka, siginfo_t *info,
sigset_t *set, struct pt_regs *regs)
{
struct rt_sigframe __user *frame;
void __user *restorer;
int err = 0;
void __user *fpstate = NULL;
frame = get_sigframe(ka, regs, sizeof(*frame), &fpstate);
if (!access_ok(VERIFY_WRITE, frame, sizeof(*frame)))
return -EFAULT;
put_user_try {
put_user_ex(sig, &frame->sig);
put_user_ex(&frame->info, &frame->pinfo);
put_user_ex(&frame->uc, &frame->puc);
err |= copy_siginfo_to_user(&frame->info, info);
/* Create the ucontext. */
if (cpu_has_xsave)
put_user_ex(UC_FP_XSTATE, &frame->uc.uc_flags);
else
put_user_ex(0, &frame->uc.uc_flags);
put_user_ex(0, &frame->uc.uc_link);
put_user_ex(current->sas_ss_sp, &frame->uc.uc_stack.ss_sp);
put_user_ex(sas_ss_flags(regs->sp),
&frame->uc.uc_stack.ss_flags);
put_user_ex(current->sas_ss_size, &frame->uc.uc_stack.ss_size);
err |= setup_sigcontext(&frame->uc.uc_mcontext, fpstate,
regs, set->sig[0]);
err |= __copy_to_user(&frame->uc.uc_sigmask, set, sizeof(*set));
/* Set up to return from userspace. */
restorer = VDSO32_SYMBOL(current->mm->context.vdso, rt_sigreturn);
if (ka->sa.sa_flags & SA_RESTORER)
restorer = ka->sa.sa_restorer;
put_user_ex(restorer, &frame->pretcode);
/*
* This is movl $__NR_rt_sigreturn, %ax ; int $0x80
*
* WE DO NOT USE IT ANY MORE! It's only left here for historical
* reasons and because gdb uses it as a signature to notice
* signal handler stack frames.
*/
put_user_ex(*((u64 *)&rt_retcode), (u64 *)frame->retcode);
} put_user_catch(err);
if (err)
return -EFAULT;
/* Set up registers for signal handler */
regs->sp = (unsigned long)frame;
regs->ip = (unsigned long)ka->sa.sa_handler;
regs->ax = (unsigned long)sig;
regs->dx = (unsigned long)&frame->info;
regs->cx = (unsigned long)&frame->uc;
regs->ds = __USER_DS;
regs->es = __USER_DS;
regs->ss = __USER_DS;
regs->cs = __USER_CS;
return 0;
}
#else /* !CONFIG_X86_32 */
static int __setup_rt_frame(int sig, struct k_sigaction *ka, siginfo_t *info,
sigset_t *set, struct pt_regs *regs)
{
struct rt_sigframe __user *frame;
void __user *fp = NULL;
int err = 0;
struct task_struct *me = current;
frame = get_sigframe(ka, regs, sizeof(struct rt_sigframe), &fp);
if (!access_ok(VERIFY_WRITE, frame, sizeof(*frame)))
return -EFAULT;
if (ka->sa.sa_flags & SA_SIGINFO) {
if (copy_siginfo_to_user(&frame->info, info))
return -EFAULT;
}
put_user_try {
/* Create the ucontext. */
if (cpu_has_xsave)
put_user_ex(UC_FP_XSTATE, &frame->uc.uc_flags);
else
put_user_ex(0, &frame->uc.uc_flags);
put_user_ex(0, &frame->uc.uc_link);
put_user_ex(me->sas_ss_sp, &frame->uc.uc_stack.ss_sp);
put_user_ex(sas_ss_flags(regs->sp),
&frame->uc.uc_stack.ss_flags);
put_user_ex(me->sas_ss_size, &frame->uc.uc_stack.ss_size);
err |= setup_sigcontext(&frame->uc.uc_mcontext, fp, regs, set->sig[0]);
err |= __copy_to_user(&frame->uc.uc_sigmask, set, sizeof(*set));
/* Set up to return from userspace. If provided, use a stub
already in userspace. */
/* x86-64 should always use SA_RESTORER. */
if (ka->sa.sa_flags & SA_RESTORER) {
put_user_ex(ka->sa.sa_restorer, &frame->pretcode);
} else {
/* could use a vstub here */
err |= -EFAULT;
}
} put_user_catch(err);
if (err)
return -EFAULT;
/* Set up registers for signal handler */
regs->di = sig;
/* In case the signal handler was declared without prototypes */
regs->ax = 0;
/* This also works for non SA_SIGINFO handlers because they expect the
next argument after the signal number on the stack. */
regs->si = (unsigned long)&frame->info;
regs->dx = (unsigned long)&frame->uc;
regs->ip = (unsigned long) ka->sa.sa_handler;
regs->sp = (unsigned long)frame;
/* Set up the CS register to run signal handlers in 64-bit mode,
even if the handler happens to be interrupting 32-bit code. */
regs->cs = __USER_CS;
return 0;
}
#endif /* CONFIG_X86_32 */
#ifdef CONFIG_X86_32
/*
* Atomically swap in the new signal mask, and wait for a signal.
*/
asmlinkage int
sys_sigsuspend(int history0, int history1, old_sigset_t mask)
{
mask &= _BLOCKABLE;
spin_lock_irq(¤t->sighand->siglock);
current->saved_sigmask = current->blocked;
siginitset(¤t->blocked, mask);
recalc_sigpending();
spin_unlock_irq(¤t->sighand->siglock);
current->state = TASK_INTERRUPTIBLE;
schedule();
set_restore_sigmask();
return -ERESTARTNOHAND;
}
asmlinkage int
sys_sigaction(int sig, const struct old_sigaction __user *act,
struct old_sigaction __user *oact)
{
struct k_sigaction new_ka, old_ka;
int ret = 0;
if (act) {
old_sigset_t mask;
if (!access_ok(VERIFY_READ, act, sizeof(*act)))
return -EFAULT;
get_user_try {
get_user_ex(new_ka.sa.sa_handler, &act->sa_handler);
get_user_ex(new_ka.sa.sa_flags, &act->sa_flags);
get_user_ex(mask, &act->sa_mask);
get_user_ex(new_ka.sa.sa_restorer, &act->sa_restorer);
} get_user_catch(ret);
if (ret)
return -EFAULT;
siginitset(&new_ka.sa.sa_mask, mask);
}
ret = do_sigaction(sig, act ? &new_ka : NULL, oact ? &old_ka : NULL);
if (!ret && oact) {
if (!access_ok(VERIFY_WRITE, oact, sizeof(*oact)))
return -EFAULT;
put_user_try {
put_user_ex(old_ka.sa.sa_handler, &oact->sa_handler);
put_user_ex(old_ka.sa.sa_flags, &oact->sa_flags);
put_user_ex(old_ka.sa.sa_mask.sig[0], &oact->sa_mask);
put_user_ex(old_ka.sa.sa_restorer, &oact->sa_restorer);
} put_user_catch(ret);
if (ret)
return -EFAULT;
}
return ret;
}
#endif /* CONFIG_X86_32 */
long
sys_sigaltstack(const stack_t __user *uss, stack_t __user *uoss,
struct pt_regs *regs)
{
return do_sigaltstack(uss, uoss, regs->sp);
}
/*
* Do a signal return; undo the signal stack.
*/
#ifdef CONFIG_X86_32
unsigned long sys_sigreturn(struct pt_regs *regs)
{
struct sigframe __user *frame;
unsigned long ax;
sigset_t set;
frame = (struct sigframe __user *)(regs->sp - 8);
if (!access_ok(VERIFY_READ, frame, sizeof(*frame)))
goto badframe;
if (__get_user(set.sig[0], &frame->sc.oldmask) || (_NSIG_WORDS > 1
&& __copy_from_user(&set.sig[1], &frame->extramask,
sizeof(frame->extramask))))
goto badframe;
sigdelsetmask(&set, ~_BLOCKABLE);
spin_lock_irq(¤t->sighand->siglock);
current->blocked = set;
recalc_sigpending();
spin_unlock_irq(¤t->sighand->siglock);
if (restore_sigcontext(regs, &frame->sc, &ax))
goto badframe;
return ax;
badframe:
signal_fault(regs, frame, "sigreturn");
return 0;
}
#endif /* CONFIG_X86_32 */
long sys_rt_sigreturn(struct pt_regs *regs)
{
struct rt_sigframe __user *frame;
unsigned long ax;
sigset_t set;
frame = (struct rt_sigframe __user *)(regs->sp - sizeof(long));
if (!access_ok(VERIFY_READ, frame, sizeof(*frame)))
goto badframe;
if (__copy_from_user(&set, &frame->uc.uc_sigmask, sizeof(set)))
goto badframe;
sigdelsetmask(&set, ~_BLOCKABLE);
spin_lock_irq(¤t->sighand->siglock);
current->blocked = set;
recalc_sigpending();
spin_unlock_irq(¤t->sighand->siglock);
if (restore_sigcontext(regs, &frame->uc.uc_mcontext, &ax))
goto badframe;
if (do_sigaltstack(&frame->uc.uc_stack, NULL, regs->sp) == -EFAULT)
goto badframe;
return ax;
badframe:
signal_fault(regs, frame, "rt_sigreturn");
return 0;
}
/*
* OK, we're invoking a handler:
*/
static int signr_convert(int sig)
{
#ifdef CONFIG_X86_32
struct thread_info *info = current_thread_info();
if (info->exec_domain && info->exec_domain->signal_invmap && sig < 32)
return info->exec_domain->signal_invmap[sig];
#endif /* CONFIG_X86_32 */
return sig;
}
#ifdef CONFIG_X86_32
#define is_ia32 1
#define ia32_setup_frame __setup_frame
#define ia32_setup_rt_frame __setup_rt_frame
#else /* !CONFIG_X86_32 */
#ifdef CONFIG_IA32_EMULATION
#define is_ia32 test_thread_flag(TIF_IA32)
#else /* !CONFIG_IA32_EMULATION */
#define is_ia32 0
#endif /* CONFIG_IA32_EMULATION */
int ia32_setup_rt_frame(int sig, struct k_sigaction *ka, siginfo_t *info,
sigset_t *set, struct pt_regs *regs);
int ia32_setup_frame(int sig, struct k_sigaction *ka,
sigset_t *set, struct pt_regs *regs);
#endif /* CONFIG_X86_32 */
static int
setup_rt_frame(int sig, struct k_sigaction *ka, siginfo_t *info,
sigset_t *set, struct pt_regs *regs)
{
int usig = signr_convert(sig);
int ret;
/* Set up the stack frame */
if (is_ia32) {
if (ka->sa.sa_flags & SA_SIGINFO)
ret = ia32_setup_rt_frame(usig, ka, info, set, regs);
else
ret = ia32_setup_frame(usig, ka, set, regs);
} else
ret = __setup_rt_frame(sig, ka, info, set, regs);
if (ret) {
force_sigsegv(sig, current);
return -EFAULT;
}
return ret;
}
static int
handle_signal(unsigned long sig, siginfo_t *info, struct k_sigaction *ka,
sigset_t *oldset, struct pt_regs *regs)
{
int ret;
/* Are we from a system call? */
if (syscall_get_nr(current, regs) >= 0) {
/* If so, check system call restarting.. */
switch (syscall_get_error(current, regs)) {
case -ERESTART_RESTARTBLOCK:
case -ERESTARTNOHAND:
regs->ax = -EINTR;
break;
case -ERESTARTSYS:
if (!(ka->sa.sa_flags & SA_RESTART)) {
regs->ax = -EINTR;
break;
}
/* fallthrough */
case -ERESTARTNOINTR:
regs->ax = regs->orig_ax;
regs->ip -= 2;
break;
}
}
/*
* If TF is set due to a debugger (TIF_FORCED_TF), clear the TF
* flag so that register information in the sigcontext is correct.
*/
if (unlikely(regs->flags & X86_EFLAGS_TF) &&
likely(test_and_clear_thread_flag(TIF_FORCED_TF)))
regs->flags &= ~X86_EFLAGS_TF;
ret = setup_rt_frame(sig, ka, info, oldset, regs);
if (ret)
return ret;
#ifdef CONFIG_X86_64
/*
* This has nothing to do with segment registers,
* despite the name. This magic affects uaccess.h
* macros' behavior. Reset it to the normal setting.
*/
set_fs(USER_DS);
#endif
/*
* Clear the direction flag as per the ABI for function entry.
*/
regs->flags &= ~X86_EFLAGS_DF;
/*
* Clear TF when entering the signal handler, but
* notify any tracer that was single-stepping it.
* The tracer may want to single-step inside the
* handler too.
*/
regs->flags &= ~X86_EFLAGS_TF;
spin_lock_irq(¤t->sighand->siglock);
sigorsets(¤t->blocked, ¤t->blocked, &ka->sa.sa_mask);
if (!(ka->sa.sa_flags & SA_NODEFER))
sigaddset(¤t->blocked, sig);
recalc_sigpending();
spin_unlock_irq(¤t->sighand->siglock);
tracehook_signal_handler(sig, info, ka, regs,
test_thread_flag(TIF_SINGLESTEP));
return 0;
}
#ifdef CONFIG_X86_32
#define NR_restart_syscall __NR_restart_syscall
#else /* !CONFIG_X86_32 */
#define NR_restart_syscall \
test_thread_flag(TIF_IA32) ? __NR_ia32_restart_syscall : __NR_restart_syscall
#endif /* CONFIG_X86_32 */
/*
* Note that 'init' is a special process: it doesn't get signals it doesn't
* want to handle. Thus you cannot kill init even with a SIGKILL even by
* mistake.
*/
static void do_signal(struct pt_regs *regs)
{
struct k_sigaction ka;
siginfo_t info;
int signr;
sigset_t *oldset;
/*
* We want the common case to go fast, which is why we may in certain
* cases get here from kernel mode. Just return without doing anything
* if so.
* X86_32: vm86 regs switched out by assembly code before reaching
* here, so testing against kernel CS suffices.
*/
if (!user_mode(regs))
return;
if (current_thread_info()->status & TS_RESTORE_SIGMASK)
oldset = ¤t->saved_sigmask;
else
oldset = ¤t->blocked;
signr = get_signal_to_deliver(&info, &ka, regs, NULL);
if (signr > 0) {
/* Whee! Actually deliver the signal. */
if (handle_signal(signr, &info, &ka, oldset, regs) == 0) {
/*
* A signal was successfully delivered; the saved
* sigmask will have been stored in the signal frame,
* and will be restored by sigreturn, so we can simply
* clear the TS_RESTORE_SIGMASK flag.
*/
current_thread_info()->status &= ~TS_RESTORE_SIGMASK;
}
return;
}
/* Did we come from a system call? */
if (syscall_get_nr(current, regs) >= 0) {
/* Restart the system call - no handlers present */
switch (syscall_get_error(current, regs)) {
case -ERESTARTNOHAND:
case -ERESTARTSYS:
case -ERESTARTNOINTR:
regs->ax = regs->orig_ax;
regs->ip -= 2;
break;
case -ERESTART_RESTARTBLOCK:
regs->ax = NR_restart_syscall;
regs->ip -= 2;
break;
}
}
/*
* If there's no signal to deliver, we just put the saved sigmask
* back.
*/
if (current_thread_info()->status & TS_RESTORE_SIGMASK) {
current_thread_info()->status &= ~TS_RESTORE_SIGMASK;
sigprocmask(SIG_SETMASK, ¤t->saved_sigmask, NULL);
}
}
/*
* notification of userspace execution resumption
* - triggered by the TIF_WORK_MASK flags
*/
void
do_notify_resume(struct pt_regs *regs, void *unused, __u32 thread_info_flags)
{
#ifdef CONFIG_X86_MCE
/* notify userspace of pending MCEs */
if (thread_info_flags & _TIF_MCE_NOTIFY)
mce_notify_process();
#endif /* CONFIG_X86_64 && CONFIG_X86_MCE */
/* deal with pending signal delivery */
if (thread_info_flags & _TIF_SIGPENDING)
do_signal(regs);
if (thread_info_flags & _TIF_NOTIFY_RESUME) {
clear_thread_flag(TIF_NOTIFY_RESUME);
tracehook_notify_resume(regs);
if (current->replacement_session_keyring)
key_replace_session_keyring();
}
if (thread_info_flags & _TIF_USER_RETURN_NOTIFY)
fire_user_return_notifiers();
#ifdef CONFIG_X86_32
clear_thread_flag(TIF_IRET);
#endif /* CONFIG_X86_32 */
}
void signal_fault(struct pt_regs *regs, void __user *frame, char *where)
{
struct task_struct *me = current;
if (show_unhandled_signals && printk_ratelimit()) {
printk("%s"
"%s[%d] bad frame in %s frame:%p ip:%lx sp:%lx orax:%lx",
task_pid_nr(current) > 1 ? KERN_INFO : KERN_EMERG,
me->comm, me->pid, where, frame,
regs->ip, regs->sp, regs->orig_ax);
print_vma_addr(" in ", regs->ip);
printk(KERN_CONT "\n");
}
force_sig(SIGSEGV, me);
}
| gpl-2.0 |
lostpuppy/m180s-kernel-stock | drivers/staging/msm/mddihost_e.c | 3059 | 1595 | /* Copyright (c) 2008-2009, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/mm.h>
#include <linux/fb.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/device.h>
#include <linux/dma-mapping.h>
#include "msm_fb.h"
#include "mddihost.h"
#include "mddihosti.h"
#include <linux/clk.h>
#include <mach/clk.h>
extern struct semaphore mddi_host_mutex;
static boolean mddi_host_ext_powered = FALSE;
void mddi_host_start_ext_display(void)
{
down(&mddi_host_mutex);
if (!mddi_host_ext_powered) {
mddi_host_init(MDDI_HOST_EXT);
mddi_host_ext_powered = TRUE;
}
up(&mddi_host_mutex);
}
void mddi_host_stop_ext_display(void)
{
down(&mddi_host_mutex);
if (mddi_host_ext_powered) {
mddi_host_powerdown(MDDI_HOST_EXT);
mddi_host_ext_powered = FALSE;
}
up(&mddi_host_mutex);
}
| gpl-2.0 |
SlimRoms/kernel_lge_msm7x27a-common | drivers/staging/ft1000/ft1000-pcmcia/ft1000_hw.c | 4851 | 65838 | /*---------------------------------------------------------------------------
FT1000 driver for Flarion Flash OFDM NIC Device
Copyright (C) 2002 Flarion Technologies, All rights reserved.
Copyright (C) 2006 Patrik Ostrihon, All rights reserved.
Copyright (C) 2006 ProWeb Consulting, a.s, All rights reserved.
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your option) any
later version. This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details. You should have received a copy of the GNU General Public
License along with this program; if not, write to the
Free Software Foundation, Inc., 59 Temple Place -
Suite 330, Boston, MA 02111-1307, USA.
-----------------------------------------------------------------------------*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/sched.h>
#include <linux/ptrace.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/timer.h>
#include <linux/interrupt.h>
#include <linux/in.h>
#include <asm/io.h>
#include <asm/bitops.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/if_arp.h>
#include <linux/ioport.h>
#include <linux/wait.h>
#include <linux/vmalloc.h>
#include <linux/firmware.h>
#include <linux/ethtool.h>
#include <pcmcia/cistpl.h>
#include <pcmcia/cisreg.h>
#include <pcmcia/ds.h>
#ifdef FT_DEBUG
#define DEBUG(n, args...) printk(KERN_DEBUG args);
#else
#define DEBUG(n, args...)
#endif
#include <linux/delay.h>
#include "ft1000.h"
static const struct firmware *fw_entry;
static void ft1000_hbchk(u_long data);
static struct timer_list poll_timer = {
.function = ft1000_hbchk
};
static u16 cmdbuffer[1024];
static u8 tempbuffer[1600];
static u8 ft1000_card_present = 0;
static u8 flarion_ft1000_cnt = 0;
static irqreturn_t ft1000_interrupt(int irq, void *dev_id);
static void ft1000_enable_interrupts(struct net_device *dev);
static void ft1000_disable_interrupts(struct net_device *dev);
/* new kernel */
MODULE_AUTHOR("");
MODULE_DESCRIPTION
("Support for Flarion Flash OFDM NIC Device. Support for PCMCIA when used with ft1000_cs.");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("FT1000");
#define MAX_RCV_LOOP 100
//---------------------------------------------------------------------------
//
// Function: ft1000_read_fifo_len
// Description: This function will read the ASIC Uplink FIFO status register
// which will return the number of bytes remaining in the Uplink FIFO.
// Sixteen bytes are subtracted to make sure that the ASIC does not
// reach its threshold.
// Input:
// dev - network device structure
// Output:
// value - number of bytes available in the ASIC Uplink FIFO.
//
//---------------------------------------------------------------------------
static inline u16 ft1000_read_fifo_len(struct net_device *dev)
{
struct ft1000_info *info = netdev_priv(dev);
if (info->AsicID == ELECTRABUZZ_ID) {
return (ft1000_read_reg(dev, FT1000_REG_UFIFO_STAT) - 16);
} else {
return (ft1000_read_reg(dev, FT1000_REG_MAG_UFSR) - 16);
}
}
//---------------------------------------------------------------------------
//
// Function: ft1000_read_dpram
// Description: This function will read the specific area of dpram
// (Electrabuzz ASIC only)
// Input:
// dev - device structure
// offset - index of dpram
// Output:
// value - value of dpram
//
//---------------------------------------------------------------------------
u16 ft1000_read_dpram(struct net_device * dev, int offset)
{
struct ft1000_info *info = netdev_priv(dev);
unsigned long flags;
u16 data;
// Provide mutual exclusive access while reading ASIC registers.
spin_lock_irqsave(&info->dpram_lock, flags);
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR, offset);
data = ft1000_read_reg(dev, FT1000_REG_DPRAM_DATA);
spin_unlock_irqrestore(&info->dpram_lock, flags);
return (data);
}
//---------------------------------------------------------------------------
//
// Function: ft1000_write_dpram
// Description: This function will write to a specific area of dpram
// (Electrabuzz ASIC only)
// Input:
// dev - device structure
// offset - index of dpram
// value - value to write
// Output:
// none.
//
//---------------------------------------------------------------------------
static inline void ft1000_write_dpram(struct net_device *dev,
int offset, u16 value)
{
struct ft1000_info *info = netdev_priv(dev);
unsigned long flags;
// Provide mutual exclusive access while reading ASIC registers.
spin_lock_irqsave(&info->dpram_lock, flags);
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR, offset);
ft1000_write_reg(dev, FT1000_REG_DPRAM_DATA, value);
spin_unlock_irqrestore(&info->dpram_lock, flags);
}
//---------------------------------------------------------------------------
//
// Function: ft1000_read_dpram_mag_16
// Description: This function will read the specific area of dpram
// (Magnemite ASIC only)
// Input:
// dev - device structure
// offset - index of dpram
// Output:
// value - value of dpram
//
//---------------------------------------------------------------------------
u16 ft1000_read_dpram_mag_16(struct net_device *dev, int offset, int Index)
{
struct ft1000_info *info = netdev_priv(dev);
unsigned long flags;
u16 data;
// Provide mutual exclusive access while reading ASIC registers.
spin_lock_irqsave(&info->dpram_lock, flags);
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR, offset);
// check if we want to read upper or lower 32-bit word
if (Index) {
data = ft1000_read_reg(dev, FT1000_REG_MAG_DPDATAL);
} else {
data = ft1000_read_reg(dev, FT1000_REG_MAG_DPDATAH);
}
spin_unlock_irqrestore(&info->dpram_lock, flags);
return (data);
}
//---------------------------------------------------------------------------
//
// Function: ft1000_write_dpram_mag_16
// Description: This function will write to a specific area of dpram
// (Magnemite ASIC only)
// Input:
// dev - device structure
// offset - index of dpram
// value - value to write
// Output:
// none.
//
//---------------------------------------------------------------------------
static inline void ft1000_write_dpram_mag_16(struct net_device *dev,
int offset, u16 value, int Index)
{
struct ft1000_info *info = netdev_priv(dev);
unsigned long flags;
// Provide mutual exclusive access while reading ASIC registers.
spin_lock_irqsave(&info->dpram_lock, flags);
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR, offset);
if (Index) {
ft1000_write_reg(dev, FT1000_REG_MAG_DPDATAL, value);
} else {
ft1000_write_reg(dev, FT1000_REG_MAG_DPDATAH, value);
}
spin_unlock_irqrestore(&info->dpram_lock, flags);
}
//---------------------------------------------------------------------------
//
// Function: ft1000_read_dpram_mag_32
// Description: This function will read the specific area of dpram
// (Magnemite ASIC only)
// Input:
// dev - device structure
// offset - index of dpram
// Output:
// value - value of dpram
//
//---------------------------------------------------------------------------
u32 ft1000_read_dpram_mag_32(struct net_device *dev, int offset)
{
struct ft1000_info *info = netdev_priv(dev);
unsigned long flags;
u32 data;
// Provide mutual exclusive access while reading ASIC registers.
spin_lock_irqsave(&info->dpram_lock, flags);
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR, offset);
data = inl(dev->base_addr + FT1000_REG_MAG_DPDATAL);
spin_unlock_irqrestore(&info->dpram_lock, flags);
return (data);
}
//---------------------------------------------------------------------------
//
// Function: ft1000_write_dpram_mag_32
// Description: This function will write to a specific area of dpram
// (Magnemite ASIC only)
// Input:
// dev - device structure
// offset - index of dpram
// value - value to write
// Output:
// none.
//
//---------------------------------------------------------------------------
void ft1000_write_dpram_mag_32(struct net_device *dev, int offset, u32 value)
{
struct ft1000_info *info = netdev_priv(dev);
unsigned long flags;
// Provide mutual exclusive access while reading ASIC registers.
spin_lock_irqsave(&info->dpram_lock, flags);
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR, offset);
outl(value, dev->base_addr + FT1000_REG_MAG_DPDATAL);
spin_unlock_irqrestore(&info->dpram_lock, flags);
}
//---------------------------------------------------------------------------
//
// Function: ft1000_enable_interrupts
// Description: This function will enable interrupts base on the current interrupt mask.
// Input:
// dev - device structure
// Output:
// None.
//
//---------------------------------------------------------------------------
static void ft1000_enable_interrupts(struct net_device *dev)
{
u16 tempword;
DEBUG(1, "ft1000_hw:ft1000_enable_interrupts()\n");
ft1000_write_reg(dev, FT1000_REG_SUP_IMASK, ISR_DEFAULT_MASK);
tempword = ft1000_read_reg(dev, FT1000_REG_SUP_IMASK);
DEBUG(1,
"ft1000_hw:ft1000_enable_interrupts:current interrupt enable mask = 0x%x\n",
tempword);
}
//---------------------------------------------------------------------------
//
// Function: ft1000_disable_interrupts
// Description: This function will disable all interrupts.
// Input:
// dev - device structure
// Output:
// None.
//
//---------------------------------------------------------------------------
static void ft1000_disable_interrupts(struct net_device *dev)
{
u16 tempword;
DEBUG(1, "ft1000_hw: ft1000_disable_interrupts()\n");
ft1000_write_reg(dev, FT1000_REG_SUP_IMASK, ISR_MASK_ALL);
tempword = ft1000_read_reg(dev, FT1000_REG_SUP_IMASK);
DEBUG(1,
"ft1000_hw:ft1000_disable_interrupts:current interrupt enable mask = 0x%x\n",
tempword);
}
//---------------------------------------------------------------------------
//
// Function: ft1000_reset_asic
// Description: This function will call the Card Service function to reset the
// ASIC.
// Input:
// dev - device structure
// Output:
// none
//
//---------------------------------------------------------------------------
static void ft1000_reset_asic(struct net_device *dev)
{
struct ft1000_info *info = netdev_priv(dev);
u16 tempword;
DEBUG(1, "ft1000_hw:ft1000_reset_asic called\n");
(*info->ft1000_reset) (info->link);
// Let's use the register provided by the Magnemite ASIC to reset the
// ASIC and DSP.
if (info->AsicID == MAGNEMITE_ID) {
ft1000_write_reg(dev, FT1000_REG_RESET,
(DSP_RESET_BIT | ASIC_RESET_BIT));
}
mdelay(1);
if (info->AsicID == ELECTRABUZZ_ID) {
// set watermark to -1 in order to not generate an interrupt
ft1000_write_reg(dev, FT1000_REG_WATERMARK, 0xffff);
} else {
// set watermark to -1 in order to not generate an interrupt
ft1000_write_reg(dev, FT1000_REG_MAG_WATERMARK, 0xffff);
}
// clear interrupts
tempword = ft1000_read_reg(dev, FT1000_REG_SUP_ISR);
DEBUG(1, "ft1000_hw: interrupt status register = 0x%x\n", tempword);
ft1000_write_reg(dev, FT1000_REG_SUP_ISR, tempword);
tempword = ft1000_read_reg(dev, FT1000_REG_SUP_ISR);
DEBUG(1, "ft1000_hw: interrupt status register = 0x%x\n", tempword);
}
//---------------------------------------------------------------------------
//
// Function: ft1000_reset_card
// Description: This function will reset the card
// Input:
// dev - device structure
// Output:
// status - false (card reset fail)
// true (card reset successful)
//
//---------------------------------------------------------------------------
static int ft1000_reset_card(struct net_device *dev)
{
struct ft1000_info *info = netdev_priv(dev);
u16 tempword;
int i;
unsigned long flags;
struct prov_record *ptr;
DEBUG(1, "ft1000_hw:ft1000_reset_card called.....\n");
info->CardReady = 0;
info->ProgConStat = 0;
info->squeseqnum = 0;
ft1000_disable_interrupts(dev);
// del_timer(&poll_timer);
// Make sure we free any memory reserve for provisioning
while (list_empty(&info->prov_list) == 0) {
DEBUG(0,
"ft1000_hw:ft1000_reset_card:deleting provisioning record\n");
ptr = list_entry(info->prov_list.next, struct prov_record, list);
list_del(&ptr->list);
kfree(ptr->pprov_data);
kfree(ptr);
}
if (info->AsicID == ELECTRABUZZ_ID) {
DEBUG(1, "ft1000_hw:ft1000_reset_card:resetting DSP\n");
ft1000_write_reg(dev, FT1000_REG_RESET, DSP_RESET_BIT);
} else {
DEBUG(1,
"ft1000_hw:ft1000_reset_card:resetting ASIC and DSP\n");
ft1000_write_reg(dev, FT1000_REG_RESET,
(DSP_RESET_BIT | ASIC_RESET_BIT));
}
// Copy DSP session record into info block if this is not a coldstart
if (ft1000_card_present == 1) {
spin_lock_irqsave(&info->dpram_lock, flags);
if (info->AsicID == ELECTRABUZZ_ID) {
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR,
FT1000_DPRAM_RX_BASE);
for (i = 0; i < MAX_DSP_SESS_REC; i++) {
info->DSPSess.Rec[i] =
ft1000_read_reg(dev,
FT1000_REG_DPRAM_DATA);
}
} else {
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR,
FT1000_DPRAM_MAG_RX_BASE);
for (i = 0; i < MAX_DSP_SESS_REC / 2; i++) {
info->DSPSess.MagRec[i] =
inl(dev->base_addr + FT1000_REG_MAG_DPDATA);
}
}
spin_unlock_irqrestore(&info->dpram_lock, flags);
}
DEBUG(1, "ft1000_hw:ft1000_reset_card:resetting ASIC\n");
mdelay(10);
//reset ASIC
ft1000_reset_asic(dev);
DEBUG(1, "ft1000_hw:ft1000_reset_card:downloading dsp image\n");
if (info->AsicID == MAGNEMITE_ID) {
// Put dsp in reset and take ASIC out of reset
DEBUG(0,
"ft1000_hw:ft1000_reset_card:Put DSP in reset and take ASIC out of reset\n");
ft1000_write_reg(dev, FT1000_REG_RESET, DSP_RESET_BIT);
// Setting MAGNEMITE ASIC to big endian mode
ft1000_write_reg(dev, FT1000_REG_SUP_CTRL, HOST_INTF_BE);
// Download bootloader
card_bootload(dev);
// Take DSP out of reset
ft1000_write_reg(dev, FT1000_REG_RESET, 0);
// FLARION_DSP_ACTIVE;
mdelay(10);
DEBUG(0, "ft1000_hw:ft1000_reset_card:Take DSP out of reset\n");
// Wait for 0xfefe indicating dsp ready before starting download
for (i = 0; i < 50; i++) {
tempword =
ft1000_read_dpram_mag_16(dev, FT1000_MAG_DPRAM_FEFE,
FT1000_MAG_DPRAM_FEFE_INDX);
if (tempword == 0xfefe) {
break;
}
mdelay(20);
}
if (i == 50) {
DEBUG(0,
"ft1000_hw:ft1000_reset_card:No FEFE detected from DSP\n");
return false;
}
} else {
// Take DSP out of reset
ft1000_write_reg(dev, FT1000_REG_RESET, ~DSP_RESET_BIT);
mdelay(10);
}
if (card_download(dev, fw_entry->data, fw_entry->size)) {
DEBUG(1, "card download unsuccessful\n");
return false;
} else {
DEBUG(1, "card download successful\n");
}
mdelay(10);
if (info->AsicID == ELECTRABUZZ_ID) {
// Need to initialize the FIFO length counter to zero in order to sync up
// with the DSP
info->fifo_cnt = 0;
ft1000_write_dpram(dev, FT1000_FIFO_LEN, info->fifo_cnt);
// Initialize DSP heartbeat area to ho
ft1000_write_dpram(dev, FT1000_HI_HO, ho);
tempword = ft1000_read_dpram(dev, FT1000_HI_HO);
DEBUG(1, "ft1000_hw:ft1000_reset_asic:hi_ho value = 0x%x\n",
tempword);
} else {
// Initialize DSP heartbeat area to ho
ft1000_write_dpram_mag_16(dev, FT1000_MAG_HI_HO, ho_mag,
FT1000_MAG_HI_HO_INDX);
tempword =
ft1000_read_dpram_mag_16(dev, FT1000_MAG_HI_HO,
FT1000_MAG_HI_HO_INDX);
DEBUG(1, "ft1000_hw:ft1000_reset_card:hi_ho value = 0x%x\n",
tempword);
}
info->CardReady = 1;
ft1000_enable_interrupts(dev);
/* Schedule heartbeat process to run every 2 seconds */
// poll_timer.expires = jiffies + (2*HZ);
// poll_timer.data = (u_long)dev;
// add_timer(&poll_timer);
return true;
}
//---------------------------------------------------------------------------
//
// Function: ft1000_chkcard
// Description: This function will check if the device is presently available on
// the system.
// Input:
// dev - device structure
// Output:
// status - false (device is not present)
// true (device is present)
//
//---------------------------------------------------------------------------
static int ft1000_chkcard(struct net_device *dev)
{
u16 tempword;
// Mask register is used to check for device presence since it is never
// set to zero.
tempword = ft1000_read_reg(dev, FT1000_REG_SUP_IMASK);
if (tempword == 0) {
DEBUG(1,
"ft1000_hw:ft1000_chkcard: IMASK = 0 Card not detected\n");
return false;
}
// The system will return the value of 0xffff for the version register
// if the device is not present.
tempword = ft1000_read_reg(dev, FT1000_REG_ASIC_ID);
if (tempword == 0xffff) {
DEBUG(1,
"ft1000_hw:ft1000_chkcard: Version = 0xffff Card not detected\n");
return false;
}
return true;
}
//---------------------------------------------------------------------------
//
// Function: ft1000_hbchk
// Description: This function will perform the heart beat check of the DSP as
// well as the ASIC.
// Input:
// dev - device structure
// Output:
// none
//
//---------------------------------------------------------------------------
static void ft1000_hbchk(u_long data)
{
struct net_device *dev = (struct net_device *)data;
struct ft1000_info *info;
u16 tempword;
info = netdev_priv(dev);
if (info->CardReady == 1) {
// Perform dsp heartbeat check
if (info->AsicID == ELECTRABUZZ_ID) {
tempword = ft1000_read_dpram(dev, FT1000_HI_HO);
} else {
tempword =
ntohs(ft1000_read_dpram_mag_16
(dev, FT1000_MAG_HI_HO,
FT1000_MAG_HI_HO_INDX));
}
DEBUG(1, "ft1000_hw:ft1000_hbchk:hi_ho value = 0x%x\n",
tempword);
// Let's perform another check if ho is not detected
if (tempword != ho) {
if (info->AsicID == ELECTRABUZZ_ID) {
tempword = ft1000_read_dpram(dev, FT1000_HI_HO);
}
else {
tempword = ntohs(ft1000_read_dpram_mag_16(dev, FT1000_MAG_HI_HO, FT1000_MAG_HI_HO_INDX));
}
}
if (tempword != ho) {
printk(KERN_INFO
"ft1000: heartbeat failed - no ho detected\n");
if (info->AsicID == ELECTRABUZZ_ID) {
info->DSP_TIME[0] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER0);
info->DSP_TIME[1] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER1);
info->DSP_TIME[2] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER2);
info->DSP_TIME[3] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER3);
} else {
info->DSP_TIME[0] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER0,
FT1000_MAG_DSP_TIMER0_INDX);
info->DSP_TIME[1] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER1,
FT1000_MAG_DSP_TIMER1_INDX);
info->DSP_TIME[2] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER2,
FT1000_MAG_DSP_TIMER2_INDX);
info->DSP_TIME[3] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER3,
FT1000_MAG_DSP_TIMER3_INDX);
}
info->DrvErrNum = DSP_HB_INFO;
if (ft1000_reset_card(dev) == 0) {
printk(KERN_INFO
"ft1000: Hardware Failure Detected - PC Card disabled\n");
info->ProgConStat = 0xff;
return;
}
/* Schedule this module to run every 2 seconds */
poll_timer.expires = jiffies + (2*HZ);
poll_timer.data = (u_long)dev;
add_timer(&poll_timer);
return;
}
tempword = ft1000_read_reg(dev, FT1000_REG_DOORBELL);
// Let's check doorbell again if fail
if (tempword & FT1000_DB_HB) {
tempword = ft1000_read_reg(dev, FT1000_REG_DOORBELL);
}
if (tempword & FT1000_DB_HB) {
printk(KERN_INFO
"ft1000: heartbeat doorbell not clear by firmware\n");
if (info->AsicID == ELECTRABUZZ_ID) {
info->DSP_TIME[0] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER0);
info->DSP_TIME[1] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER1);
info->DSP_TIME[2] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER2);
info->DSP_TIME[3] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER3);
} else {
info->DSP_TIME[0] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER0,
FT1000_MAG_DSP_TIMER0_INDX);
info->DSP_TIME[1] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER1,
FT1000_MAG_DSP_TIMER1_INDX);
info->DSP_TIME[2] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER2,
FT1000_MAG_DSP_TIMER2_INDX);
info->DSP_TIME[3] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER3,
FT1000_MAG_DSP_TIMER3_INDX);
}
info->DrvErrNum = DSP_HB_INFO;
if (ft1000_reset_card(dev) == 0) {
printk(KERN_INFO
"ft1000: Hardware Failure Detected - PC Card disabled\n");
info->ProgConStat = 0xff;
return;
}
/* Schedule this module to run every 2 seconds */
poll_timer.expires = jiffies + (2*HZ);
poll_timer.data = (u_long)dev;
add_timer(&poll_timer);
return;
}
// Set dedicated area to hi and ring appropriate doorbell according
// to hi/ho heartbeat protocol
if (info->AsicID == ELECTRABUZZ_ID) {
ft1000_write_dpram(dev, FT1000_HI_HO, hi);
} else {
ft1000_write_dpram_mag_16(dev, FT1000_MAG_HI_HO, hi_mag,
FT1000_MAG_HI_HO_INDX);
}
if (info->AsicID == ELECTRABUZZ_ID) {
tempword = ft1000_read_dpram(dev, FT1000_HI_HO);
} else {
tempword =
ntohs(ft1000_read_dpram_mag_16
(dev, FT1000_MAG_HI_HO,
FT1000_MAG_HI_HO_INDX));
}
// Let's write hi again if fail
if (tempword != hi) {
if (info->AsicID == ELECTRABUZZ_ID) {
ft1000_write_dpram(dev, FT1000_HI_HO, hi);
}
else {
ft1000_write_dpram_mag_16(dev, FT1000_MAG_HI_HO, hi_mag, FT1000_MAG_HI_HO_INDX);
}
if (info->AsicID == ELECTRABUZZ_ID) {
tempword = ft1000_read_dpram(dev, FT1000_HI_HO);
}
else {
tempword = ntohs(ft1000_read_dpram_mag_16(dev, FT1000_MAG_HI_HO, FT1000_MAG_HI_HO_INDX));
}
}
if (tempword != hi) {
printk(KERN_INFO
"ft1000: heartbeat failed - cannot write hi into DPRAM\n");
if (info->AsicID == ELECTRABUZZ_ID) {
info->DSP_TIME[0] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER0);
info->DSP_TIME[1] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER1);
info->DSP_TIME[2] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER2);
info->DSP_TIME[3] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER3);
} else {
info->DSP_TIME[0] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER0,
FT1000_MAG_DSP_TIMER0_INDX);
info->DSP_TIME[1] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER1,
FT1000_MAG_DSP_TIMER1_INDX);
info->DSP_TIME[2] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER2,
FT1000_MAG_DSP_TIMER2_INDX);
info->DSP_TIME[3] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER3,
FT1000_MAG_DSP_TIMER3_INDX);
}
info->DrvErrNum = DSP_HB_INFO;
if (ft1000_reset_card(dev) == 0) {
printk(KERN_INFO
"ft1000: Hardware Failure Detected - PC Card disabled\n");
info->ProgConStat = 0xff;
return;
}
/* Schedule this module to run every 2 seconds */
poll_timer.expires = jiffies + (2*HZ);
poll_timer.data = (u_long)dev;
add_timer(&poll_timer);
return;
}
ft1000_write_reg(dev, FT1000_REG_DOORBELL, FT1000_DB_HB);
}
/* Schedule this module to run every 2 seconds */
poll_timer.expires = jiffies + (2 * HZ);
poll_timer.data = (u_long) dev;
add_timer(&poll_timer);
}
//---------------------------------------------------------------------------
//
// Function: ft1000_send_cmd
// Description:
// Input:
// Output:
//
//---------------------------------------------------------------------------
static void ft1000_send_cmd (struct net_device *dev, u16 *ptempbuffer, int size, u16 qtype)
{
struct ft1000_info *info = netdev_priv(dev);
int i;
u16 tempword;
unsigned long flags;
size += sizeof(struct pseudo_hdr);
// check for odd byte and increment to 16-bit word align value
if ((size & 0x0001)) {
size++;
}
DEBUG(1, "FT1000:ft1000_send_cmd:total length = %d\n", size);
DEBUG(1, "FT1000:ft1000_send_cmd:length = %d\n", ntohs(*ptempbuffer));
// put message into slow queue area
// All messages are in the form total_len + pseudo header + message body
spin_lock_irqsave(&info->dpram_lock, flags);
// Make sure SLOWQ doorbell is clear
tempword = ft1000_read_reg(dev, FT1000_REG_DOORBELL);
i=0;
while (tempword & FT1000_DB_DPRAM_TX) {
mdelay(10);
i++;
if (i==10) {
spin_unlock_irqrestore(&info->dpram_lock, flags);
return;
}
tempword = ft1000_read_reg(dev, FT1000_REG_DOORBELL);
}
if (info->AsicID == ELECTRABUZZ_ID) {
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR,
FT1000_DPRAM_TX_BASE);
// Write total length to dpram
ft1000_write_reg(dev, FT1000_REG_DPRAM_DATA, size);
// Write pseudo header and messgae body
for (i = 0; i < (size >> 1); i++) {
DEBUG(1, "FT1000:ft1000_send_cmd:data %d = 0x%x\n", i,
*ptempbuffer);
tempword = htons(*ptempbuffer++);
ft1000_write_reg(dev, FT1000_REG_DPRAM_DATA, tempword);
}
} else {
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR,
FT1000_DPRAM_MAG_TX_BASE);
// Write total length to dpram
ft1000_write_reg(dev, FT1000_REG_MAG_DPDATAH, htons(size));
// Write pseudo header and messgae body
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR,
FT1000_DPRAM_MAG_TX_BASE + 1);
for (i = 0; i < (size >> 2); i++) {
DEBUG(1, "FT1000:ft1000_send_cmd:data = 0x%x\n",
*ptempbuffer);
outw(*ptempbuffer++,
dev->base_addr + FT1000_REG_MAG_DPDATAL);
DEBUG(1, "FT1000:ft1000_send_cmd:data = 0x%x\n",
*ptempbuffer);
outw(*ptempbuffer++,
dev->base_addr + FT1000_REG_MAG_DPDATAH);
}
DEBUG(1, "FT1000:ft1000_send_cmd:data = 0x%x\n", *ptempbuffer);
outw(*ptempbuffer++, dev->base_addr + FT1000_REG_MAG_DPDATAL);
DEBUG(1, "FT1000:ft1000_send_cmd:data = 0x%x\n", *ptempbuffer);
outw(*ptempbuffer++, dev->base_addr + FT1000_REG_MAG_DPDATAH);
}
spin_unlock_irqrestore(&info->dpram_lock, flags);
// ring doorbell to notify DSP that we have a message ready
ft1000_write_reg(dev, FT1000_REG_DOORBELL, FT1000_DB_DPRAM_TX);
}
//---------------------------------------------------------------------------
//
// Function: ft1000_receive_cmd
// Description: This function will read a message from the dpram area.
// Input:
// dev - network device structure
// pbuffer - caller supply address to buffer
// pnxtph - pointer to next pseudo header
// Output:
// Status = 0 (unsuccessful)
// = 1 (successful)
//
//---------------------------------------------------------------------------
static bool ft1000_receive_cmd(struct net_device *dev, u16 *pbuffer,
int maxsz, u16 *pnxtph)
{
struct ft1000_info *info = netdev_priv(dev);
u16 size;
u16 *ppseudohdr;
int i;
u16 tempword;
unsigned long flags;
if (info->AsicID == ELECTRABUZZ_ID) {
size = ( ft1000_read_dpram(dev, *pnxtph) ) + sizeof(struct pseudo_hdr);
} else {
size =
ntohs(ft1000_read_dpram_mag_16
(dev, FT1000_MAG_PH_LEN,
FT1000_MAG_PH_LEN_INDX)) + sizeof(struct pseudo_hdr);
}
if (size > maxsz) {
DEBUG(1,
"FT1000:ft1000_receive_cmd:Invalid command length = %d\n",
size);
return false;
} else {
ppseudohdr = (u16 *) pbuffer;
spin_lock_irqsave(&info->dpram_lock, flags);
if (info->AsicID == ELECTRABUZZ_ID) {
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR,
FT1000_DPRAM_RX_BASE + 2);
for (i = 0; i <= (size >> 1); i++) {
tempword =
ft1000_read_reg(dev, FT1000_REG_DPRAM_DATA);
*pbuffer++ = ntohs(tempword);
}
} else {
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR,
FT1000_DPRAM_MAG_RX_BASE);
*pbuffer = inw(dev->base_addr + FT1000_REG_MAG_DPDATAH);
DEBUG(1, "ft1000_hw:received data = 0x%x\n", *pbuffer);
pbuffer++;
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR,
FT1000_DPRAM_MAG_RX_BASE + 1);
for (i = 0; i <= (size >> 2); i++) {
*pbuffer =
inw(dev->base_addr +
FT1000_REG_MAG_DPDATAL);
pbuffer++;
*pbuffer =
inw(dev->base_addr +
FT1000_REG_MAG_DPDATAH);
pbuffer++;
}
//copy odd aligned word
*pbuffer = inw(dev->base_addr + FT1000_REG_MAG_DPDATAL);
DEBUG(1, "ft1000_hw:received data = 0x%x\n", *pbuffer);
pbuffer++;
*pbuffer = inw(dev->base_addr + FT1000_REG_MAG_DPDATAH);
DEBUG(1, "ft1000_hw:received data = 0x%x\n", *pbuffer);
pbuffer++;
}
if (size & 0x0001) {
//copy odd byte from fifo
tempword = ft1000_read_reg(dev, FT1000_REG_DPRAM_DATA);
*pbuffer = ntohs(tempword);
}
spin_unlock_irqrestore(&info->dpram_lock, flags);
// Check if pseudo header checksum is good
// Calculate pseudo header checksum
tempword = *ppseudohdr++;
for (i = 1; i < 7; i++) {
tempword ^= *ppseudohdr++;
}
if ((tempword != *ppseudohdr)) {
DEBUG(1,
"FT1000:ft1000_receive_cmd:Pseudo header checksum mismatch\n");
// Drop this message
return false;
}
return true;
}
}
//---------------------------------------------------------------------------
//
// Function: ft1000_proc_drvmsg
// Description: This function will process the various driver messages.
// Input:
// dev - device structure
// pnxtph - pointer to next pseudo header
// Output:
// none
//
//---------------------------------------------------------------------------
static void ft1000_proc_drvmsg(struct net_device *dev)
{
struct ft1000_info *info = netdev_priv(dev);
u16 msgtype;
u16 tempword;
struct media_msg *pmediamsg;
struct dsp_init_msg *pdspinitmsg;
struct drv_msg *pdrvmsg;
u16 len;
u16 i;
struct prov_record *ptr;
struct pseudo_hdr *ppseudo_hdr;
u16 *pmsg;
struct timeval tv;
union {
u8 byte[2];
u16 wrd;
} convert;
if (info->AsicID == ELECTRABUZZ_ID) {
tempword = FT1000_DPRAM_RX_BASE+2;
}
else {
tempword = FT1000_DPRAM_MAG_RX_BASE;
}
if ( ft1000_receive_cmd(dev, &cmdbuffer[0], MAX_CMD_SQSIZE, &tempword) ) {
// Get the message type which is total_len + PSEUDO header + msgtype + message body
pdrvmsg = (struct drv_msg *) & cmdbuffer[0];
msgtype = ntohs(pdrvmsg->type);
DEBUG(1, "Command message type = 0x%x\n", msgtype);
switch (msgtype) {
case DSP_PROVISION:
DEBUG(0,
"Got a provisioning request message from DSP\n");
mdelay(25);
while (list_empty(&info->prov_list) == 0) {
DEBUG(0, "Sending a provisioning message\n");
// Make sure SLOWQ doorbell is clear
tempword =
ft1000_read_reg(dev, FT1000_REG_DOORBELL);
i = 0;
while (tempword & FT1000_DB_DPRAM_TX) {
mdelay(5);
i++;
if (i == 10) {
break;
}
}
ptr =
list_entry(info->prov_list.next,
struct prov_record, list);
len = *(u16 *) ptr->pprov_data;
len = htons(len);
pmsg = (u16 *) ptr->pprov_data;
ppseudo_hdr = (struct pseudo_hdr *) pmsg;
// Insert slow queue sequence number
ppseudo_hdr->seq_num = info->squeseqnum++;
ppseudo_hdr->portsrc = 0;
// Calculate new checksum
ppseudo_hdr->checksum = *pmsg++;
DEBUG(1, "checksum = 0x%x\n",
ppseudo_hdr->checksum);
for (i = 1; i < 7; i++) {
ppseudo_hdr->checksum ^= *pmsg++;
DEBUG(1, "checksum = 0x%x\n",
ppseudo_hdr->checksum);
}
ft1000_send_cmd (dev, (u16 *)ptr->pprov_data, len, SLOWQ_TYPE);
list_del(&ptr->list);
kfree(ptr->pprov_data);
kfree(ptr);
}
// Indicate adapter is ready to take application messages after all
// provisioning messages are sent
info->CardReady = 1;
break;
case MEDIA_STATE:
pmediamsg = (struct media_msg *) & cmdbuffer[0];
if (info->ProgConStat != 0xFF) {
if (pmediamsg->state) {
DEBUG(1, "Media is up\n");
if (info->mediastate == 0) {
netif_carrier_on(dev);
netif_wake_queue(dev);
info->mediastate = 1;
do_gettimeofday(&tv);
info->ConTm = tv.tv_sec;
}
} else {
DEBUG(1, "Media is down\n");
if (info->mediastate == 1) {
info->mediastate = 0;
netif_carrier_off(dev);
netif_stop_queue(dev);
info->ConTm = 0;
}
}
}
else {
DEBUG(1,"Media is down\n");
if (info->mediastate == 1) {
info->mediastate = 0;
netif_carrier_off(dev);
netif_stop_queue(dev);
info->ConTm = 0;
}
}
break;
case DSP_INIT_MSG:
pdspinitmsg = (struct dsp_init_msg *) & cmdbuffer[0];
memcpy(info->DspVer, pdspinitmsg->DspVer, DSPVERSZ);
DEBUG(1, "DSPVER = 0x%2x 0x%2x 0x%2x 0x%2x\n",
info->DspVer[0], info->DspVer[1], info->DspVer[2],
info->DspVer[3]);
memcpy(info->HwSerNum, pdspinitmsg->HwSerNum,
HWSERNUMSZ);
memcpy(info->Sku, pdspinitmsg->Sku, SKUSZ);
memcpy(info->eui64, pdspinitmsg->eui64, EUISZ);
dev->dev_addr[0] = info->eui64[0];
dev->dev_addr[1] = info->eui64[1];
dev->dev_addr[2] = info->eui64[2];
dev->dev_addr[3] = info->eui64[5];
dev->dev_addr[4] = info->eui64[6];
dev->dev_addr[5] = info->eui64[7];
if (ntohs(pdspinitmsg->length) ==
(sizeof(struct dsp_init_msg) - 20)) {
memcpy(info->ProductMode,
pdspinitmsg->ProductMode, MODESZ);
memcpy(info->RfCalVer, pdspinitmsg->RfCalVer,
CALVERSZ);
memcpy(info->RfCalDate, pdspinitmsg->RfCalDate,
CALDATESZ);
DEBUG(1, "RFCalVer = 0x%2x 0x%2x\n",
info->RfCalVer[0], info->RfCalVer[1]);
}
break ;
case DSP_STORE_INFO:
DEBUG(1, "FT1000:drivermsg:Got DSP_STORE_INFO\n");
tempword = ntohs(pdrvmsg->length);
info->DSPInfoBlklen = tempword;
if (tempword < (MAX_DSP_SESS_REC - 4)) {
pmsg = (u16 *) & pdrvmsg->data[0];
for (i = 0; i < ((tempword + 1) / 2); i++) {
DEBUG(1,
"FT1000:drivermsg:dsp info data = 0x%x\n",
*pmsg);
info->DSPInfoBlk[i + 10] = *pmsg++;
}
}
break;
case DSP_GET_INFO:
DEBUG(1, "FT1000:drivermsg:Got DSP_GET_INFO\n");
// copy dsp info block to dsp
// allow any outstanding ioctl to finish
mdelay(10);
tempword = ft1000_read_reg(dev, FT1000_REG_DOORBELL);
if (tempword & FT1000_DB_DPRAM_TX) {
mdelay(10);
tempword =
ft1000_read_reg(dev, FT1000_REG_DOORBELL);
if (tempword & FT1000_DB_DPRAM_TX) {
mdelay(10);
}
}
if ((tempword & FT1000_DB_DPRAM_TX) == 0) {
// Put message into Slow Queue
// Form Pseudo header
pmsg = (u16 *) info->DSPInfoBlk;
ppseudo_hdr = (struct pseudo_hdr *) pmsg;
ppseudo_hdr->length =
htons(info->DSPInfoBlklen + 4);
ppseudo_hdr->source = 0x10;
ppseudo_hdr->destination = 0x20;
ppseudo_hdr->portdest = 0;
ppseudo_hdr->portsrc = 0;
ppseudo_hdr->sh_str_id = 0;
ppseudo_hdr->control = 0;
ppseudo_hdr->rsvd1 = 0;
ppseudo_hdr->rsvd2 = 0;
ppseudo_hdr->qos_class = 0;
// Insert slow queue sequence number
ppseudo_hdr->seq_num = info->squeseqnum++;
// Insert application id
ppseudo_hdr->portsrc = 0;
// Calculate new checksum
ppseudo_hdr->checksum = *pmsg++;
for (i = 1; i < 7; i++) {
ppseudo_hdr->checksum ^= *pmsg++;
}
info->DSPInfoBlk[8] = 0x7200;
info->DSPInfoBlk[9] =
htons(info->DSPInfoBlklen);
ft1000_send_cmd (dev, (u16 *)info->DSPInfoBlk, (u16)(info->DSPInfoBlklen+4), 0);
}
break;
case GET_DRV_ERR_RPT_MSG:
DEBUG(1, "FT1000:drivermsg:Got GET_DRV_ERR_RPT_MSG\n");
// copy driver error message to dsp
// allow any outstanding ioctl to finish
mdelay(10);
tempword = ft1000_read_reg(dev, FT1000_REG_DOORBELL);
if (tempword & FT1000_DB_DPRAM_TX) {
mdelay(10);
tempword =
ft1000_read_reg(dev, FT1000_REG_DOORBELL);
if (tempword & FT1000_DB_DPRAM_TX) {
mdelay(10);
}
}
if ((tempword & FT1000_DB_DPRAM_TX) == 0) {
// Put message into Slow Queue
// Form Pseudo header
pmsg = (u16 *) & tempbuffer[0];
ppseudo_hdr = (struct pseudo_hdr *) pmsg;
ppseudo_hdr->length = htons(0x0012);
ppseudo_hdr->source = 0x10;
ppseudo_hdr->destination = 0x20;
ppseudo_hdr->portdest = 0;
ppseudo_hdr->portsrc = 0;
ppseudo_hdr->sh_str_id = 0;
ppseudo_hdr->control = 0;
ppseudo_hdr->rsvd1 = 0;
ppseudo_hdr->rsvd2 = 0;
ppseudo_hdr->qos_class = 0;
// Insert slow queue sequence number
ppseudo_hdr->seq_num = info->squeseqnum++;
// Insert application id
ppseudo_hdr->portsrc = 0;
// Calculate new checksum
ppseudo_hdr->checksum = *pmsg++;
for (i=1; i<7; i++) {
ppseudo_hdr->checksum ^= *pmsg++;
}
pmsg = (u16 *) & tempbuffer[16];
*pmsg++ = htons(RSP_DRV_ERR_RPT_MSG);
*pmsg++ = htons(0x000e);
*pmsg++ = htons(info->DSP_TIME[0]);
*pmsg++ = htons(info->DSP_TIME[1]);
*pmsg++ = htons(info->DSP_TIME[2]);
*pmsg++ = htons(info->DSP_TIME[3]);
convert.byte[0] = info->DspVer[0];
convert.byte[1] = info->DspVer[1];
*pmsg++ = convert.wrd;
convert.byte[0] = info->DspVer[2];
convert.byte[1] = info->DspVer[3];
*pmsg++ = convert.wrd;
*pmsg++ = htons(info->DrvErrNum);
ft1000_send_cmd (dev, (u16 *)&tempbuffer[0], (u16)(0x0012), 0);
info->DrvErrNum = 0;
}
break;
default:
break;
}
}
}
//---------------------------------------------------------------------------
//
// Function: ft1000_parse_dpram_msg
// Description: This function will parse the message received from the DSP
// via the DPRAM interface.
// Input:
// dev - device structure
// Output:
// status - FAILURE
// SUCCESS
//
//---------------------------------------------------------------------------
static int ft1000_parse_dpram_msg(struct net_device *dev)
{
struct ft1000_info *info = netdev_priv(dev);
u16 doorbell;
u16 portid;
u16 nxtph;
u16 total_len;
int i = 0;
int cnt;
unsigned long flags;
doorbell = ft1000_read_reg(dev, FT1000_REG_DOORBELL);
DEBUG(1, "Doorbell = 0x%x\n", doorbell);
if (doorbell & FT1000_ASIC_RESET_REQ) {
// Copy DSP session record from info block
spin_lock_irqsave(&info->dpram_lock, flags);
if (info->AsicID == ELECTRABUZZ_ID) {
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR,
FT1000_DPRAM_RX_BASE);
for (i = 0; i < MAX_DSP_SESS_REC; i++) {
ft1000_write_reg(dev, FT1000_REG_DPRAM_DATA,
info->DSPSess.Rec[i]);
}
} else {
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR,
FT1000_DPRAM_MAG_RX_BASE);
for (i = 0; i < MAX_DSP_SESS_REC / 2; i++) {
outl(info->DSPSess.MagRec[i],
dev->base_addr + FT1000_REG_MAG_DPDATA);
}
}
spin_unlock_irqrestore(&info->dpram_lock, flags);
// clear ASIC RESET request
ft1000_write_reg(dev, FT1000_REG_DOORBELL,
FT1000_ASIC_RESET_REQ);
DEBUG(1, "Got an ASIC RESET Request\n");
ft1000_write_reg(dev, FT1000_REG_DOORBELL,
FT1000_ASIC_RESET_DSP);
if (info->AsicID == MAGNEMITE_ID) {
// Setting MAGNEMITE ASIC to big endian mode
ft1000_write_reg(dev, FT1000_REG_SUP_CTRL,
HOST_INTF_BE);
}
}
if (doorbell & FT1000_DSP_ASIC_RESET) {
DEBUG(0,
"FT1000:ft1000_parse_dpram_msg: Got a dsp ASIC reset message\n");
ft1000_write_reg(dev, FT1000_REG_DOORBELL,
FT1000_DSP_ASIC_RESET);
udelay(200);
return SUCCESS;
}
if (doorbell & FT1000_DB_DPRAM_RX) {
DEBUG(1,
"FT1000:ft1000_parse_dpram_msg: Got a slow queue message\n");
nxtph = FT1000_DPRAM_RX_BASE + 2;
if (info->AsicID == ELECTRABUZZ_ID) {
total_len =
ft1000_read_dpram(dev, FT1000_DPRAM_RX_BASE);
} else {
total_len =
ntohs(ft1000_read_dpram_mag_16
(dev, FT1000_MAG_TOTAL_LEN,
FT1000_MAG_TOTAL_LEN_INDX));
}
DEBUG(1, "FT1000:ft1000_parse_dpram_msg:total length = %d\n",
total_len);
if ((total_len < MAX_CMD_SQSIZE) && (total_len > sizeof(struct pseudo_hdr))) {
total_len += nxtph;
cnt = 0;
// ft1000_read_reg will return a value that needs to be byteswap
// in order to get DSP_QID_OFFSET.
if (info->AsicID == ELECTRABUZZ_ID) {
portid =
(ft1000_read_dpram
(dev,
DSP_QID_OFFSET + FT1000_DPRAM_RX_BASE +
2) >> 8) & 0xff;
} else {
portid =
(ft1000_read_dpram_mag_16
(dev, FT1000_MAG_PORT_ID,
FT1000_MAG_PORT_ID_INDX) & 0xff);
}
DEBUG(1, "DSP_QID = 0x%x\n", portid);
if (portid == DRIVERID) {
// We are assumming one driver message from the DSP at a time.
ft1000_proc_drvmsg(dev);
}
}
ft1000_write_reg(dev, FT1000_REG_DOORBELL, FT1000_DB_DPRAM_RX);
}
if (doorbell & FT1000_DB_COND_RESET) {
// Reset ASIC and DSP
if (info->AsicID == ELECTRABUZZ_ID) {
info->DSP_TIME[0] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER0);
info->DSP_TIME[1] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER1);
info->DSP_TIME[2] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER2);
info->DSP_TIME[3] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER3);
} else {
info->DSP_TIME[0] =
ft1000_read_dpram_mag_16(dev, FT1000_MAG_DSP_TIMER0,
FT1000_MAG_DSP_TIMER0_INDX);
info->DSP_TIME[1] =
ft1000_read_dpram_mag_16(dev, FT1000_MAG_DSP_TIMER1,
FT1000_MAG_DSP_TIMER1_INDX);
info->DSP_TIME[2] =
ft1000_read_dpram_mag_16(dev, FT1000_MAG_DSP_TIMER2,
FT1000_MAG_DSP_TIMER2_INDX);
info->DSP_TIME[3] =
ft1000_read_dpram_mag_16(dev, FT1000_MAG_DSP_TIMER3,
FT1000_MAG_DSP_TIMER3_INDX);
}
info->DrvErrNum = DSP_CONDRESET_INFO;
DEBUG(1, "ft1000_hw:DSP conditional reset requested\n");
ft1000_reset_card(dev);
ft1000_write_reg(dev, FT1000_REG_DOORBELL,
FT1000_DB_COND_RESET);
}
// let's clear any unexpected doorbells from DSP
doorbell =
doorbell & ~(FT1000_DB_DPRAM_RX | FT1000_ASIC_RESET_REQ |
FT1000_DB_COND_RESET | 0xff00);
if (doorbell) {
DEBUG(1, "Clearing unexpected doorbell = 0x%x\n", doorbell);
ft1000_write_reg(dev, FT1000_REG_DOORBELL, doorbell);
}
return SUCCESS;
}
//---------------------------------------------------------------------------
//
// Function: ft1000_flush_fifo
// Description: This function will flush one packet from the downlink
// FIFO.
// Input:
// dev - device structure
// drv_err - driver error causing the flush fifo
// Output:
// None.
//
//---------------------------------------------------------------------------
static void ft1000_flush_fifo(struct net_device *dev, u16 DrvErrNum)
{
struct ft1000_info *info = netdev_priv(dev);
u16 i;
u32 templong;
u16 tempword;
DEBUG(1, "ft1000:ft1000_hw:ft1000_flush_fifo called\n");
if (info->PktIntfErr > MAX_PH_ERR) {
if (info->AsicID == ELECTRABUZZ_ID) {
info->DSP_TIME[0] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER0);
info->DSP_TIME[1] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER1);
info->DSP_TIME[2] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER2);
info->DSP_TIME[3] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER3);
} else {
info->DSP_TIME[0] =
ft1000_read_dpram_mag_16(dev, FT1000_MAG_DSP_TIMER0,
FT1000_MAG_DSP_TIMER0_INDX);
info->DSP_TIME[1] =
ft1000_read_dpram_mag_16(dev, FT1000_MAG_DSP_TIMER1,
FT1000_MAG_DSP_TIMER1_INDX);
info->DSP_TIME[2] =
ft1000_read_dpram_mag_16(dev, FT1000_MAG_DSP_TIMER2,
FT1000_MAG_DSP_TIMER2_INDX);
info->DSP_TIME[3] =
ft1000_read_dpram_mag_16(dev, FT1000_MAG_DSP_TIMER3,
FT1000_MAG_DSP_TIMER3_INDX);
}
info->DrvErrNum = DrvErrNum;
ft1000_reset_card(dev);
return;
} else {
// Flush corrupted pkt from FIFO
i = 0;
do {
if (info->AsicID == ELECTRABUZZ_ID) {
tempword =
ft1000_read_reg(dev, FT1000_REG_DFIFO);
tempword =
ft1000_read_reg(dev, FT1000_REG_DFIFO_STAT);
} else {
templong =
inl(dev->base_addr + FT1000_REG_MAG_DFR);
tempword =
inw(dev->base_addr + FT1000_REG_MAG_DFSR);
}
i++;
// This should never happen unless the ASIC is broken.
// We must reset to recover.
if ((i > 2048) || (tempword == 0)) {
if (info->AsicID == ELECTRABUZZ_ID) {
info->DSP_TIME[0] =
ft1000_read_dpram(dev,
FT1000_DSP_TIMER0);
info->DSP_TIME[1] =
ft1000_read_dpram(dev,
FT1000_DSP_TIMER1);
info->DSP_TIME[2] =
ft1000_read_dpram(dev,
FT1000_DSP_TIMER2);
info->DSP_TIME[3] =
ft1000_read_dpram(dev,
FT1000_DSP_TIMER3);
} else {
info->DSP_TIME[0] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER0,
FT1000_MAG_DSP_TIMER0_INDX);
info->DSP_TIME[1] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER1,
FT1000_MAG_DSP_TIMER1_INDX);
info->DSP_TIME[2] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER2,
FT1000_MAG_DSP_TIMER2_INDX);
info->DSP_TIME[3] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER3,
FT1000_MAG_DSP_TIMER3_INDX);
}
if (tempword == 0) {
// Let's check if ASIC reads are still ok by reading the Mask register
// which is never zero at this point of the code.
tempword =
inw(dev->base_addr +
FT1000_REG_SUP_IMASK);
if (tempword == 0) {
// This indicates that we can not communicate with the ASIC
info->DrvErrNum =
FIFO_FLUSH_BADCNT;
} else {
// Let's assume that we really flush the FIFO
info->PktIntfErr++;
return;
}
} else {
info->DrvErrNum = FIFO_FLUSH_MAXLIMIT;
}
return;
}
tempword = inw(dev->base_addr + FT1000_REG_SUP_STAT);
} while ((tempword & 0x03) != 0x03);
if (info->AsicID == ELECTRABUZZ_ID) {
i++;
DEBUG(0, "Flushing FIFO complete = %x\n", tempword);
// Flush last word in FIFO.
tempword = ft1000_read_reg(dev, FT1000_REG_DFIFO);
// Update FIFO counter for DSP
i = i * 2;
DEBUG(0, "Flush Data byte count to dsp = %d\n", i);
info->fifo_cnt += i;
ft1000_write_dpram(dev, FT1000_FIFO_LEN,
info->fifo_cnt);
} else {
DEBUG(0, "Flushing FIFO complete = %x\n", tempword);
// Flush last word in FIFO
templong = inl(dev->base_addr + FT1000_REG_MAG_DFR);
tempword = inw(dev->base_addr + FT1000_REG_SUP_STAT);
DEBUG(0, "FT1000_REG_SUP_STAT = 0x%x\n", tempword);
tempword = inw(dev->base_addr + FT1000_REG_MAG_DFSR);
DEBUG(0, "FT1000_REG_MAG_DFSR = 0x%x\n", tempword);
}
if (DrvErrNum) {
info->PktIntfErr++;
}
}
}
//---------------------------------------------------------------------------
//
// Function: ft1000_copy_up_pkt
// Description: This function will pull Flarion packets out of the Downlink
// FIFO and convert it to an ethernet packet. The ethernet packet will
// then be deliver to the TCP/IP stack.
// Input:
// dev - device structure
// Output:
// status - FAILURE
// SUCCESS
//
//---------------------------------------------------------------------------
static int ft1000_copy_up_pkt(struct net_device *dev)
{
u16 tempword;
struct ft1000_info *info = netdev_priv(dev);
u16 len;
struct sk_buff *skb;
u16 i;
u8 *pbuffer = NULL;
u8 *ptemp = NULL;
u16 chksum;
u32 *ptemplong;
u32 templong;
DEBUG(1, "ft1000_copy_up_pkt\n");
// Read length
if (info->AsicID == ELECTRABUZZ_ID) {
tempword = ft1000_read_reg(dev, FT1000_REG_DFIFO);
len = tempword;
} else {
tempword = ft1000_read_reg(dev, FT1000_REG_MAG_DFRL);
len = ntohs(tempword);
}
chksum = tempword;
DEBUG(1, "Number of Bytes in FIFO = %d\n", len);
if (len > ENET_MAX_SIZE) {
DEBUG(0, "size of ethernet packet invalid\n");
if (info->AsicID == MAGNEMITE_ID) {
// Read High word to complete 32 bit access
tempword = ft1000_read_reg(dev, FT1000_REG_MAG_DFRH);
}
ft1000_flush_fifo(dev, DSP_PKTLEN_INFO);
info->stats.rx_errors++;
return FAILURE;
}
skb = dev_alloc_skb(len + 12 + 2);
if (skb == NULL) {
DEBUG(0, "No Network buffers available\n");
// Read High word to complete 32 bit access
if (info->AsicID == MAGNEMITE_ID) {
tempword = ft1000_read_reg(dev, FT1000_REG_MAG_DFRH);
}
ft1000_flush_fifo(dev, 0);
info->stats.rx_errors++;
return FAILURE;
}
pbuffer = (u8 *) skb_put(skb, len + 12);
// Pseudo header
if (info->AsicID == ELECTRABUZZ_ID) {
for (i = 1; i < 7; i++) {
tempword = ft1000_read_reg(dev, FT1000_REG_DFIFO);
chksum ^= tempword;
}
// read checksum value
tempword = ft1000_read_reg(dev, FT1000_REG_DFIFO);
} else {
tempword = ft1000_read_reg(dev, FT1000_REG_MAG_DFRH);
DEBUG(1, "Pseudo = 0x%x\n", tempword);
chksum ^= tempword;
tempword = ft1000_read_reg(dev, FT1000_REG_MAG_DFRL);
DEBUG(1, "Pseudo = 0x%x\n", tempword);
chksum ^= tempword;
tempword = ft1000_read_reg(dev, FT1000_REG_MAG_DFRH);
DEBUG(1, "Pseudo = 0x%x\n", tempword);
chksum ^= tempword;
tempword = ft1000_read_reg(dev, FT1000_REG_MAG_DFRL);
DEBUG(1, "Pseudo = 0x%x\n", tempword);
chksum ^= tempword;
tempword = ft1000_read_reg(dev, FT1000_REG_MAG_DFRH);
DEBUG(1, "Pseudo = 0x%x\n", tempword);
chksum ^= tempword;
tempword = ft1000_read_reg(dev, FT1000_REG_MAG_DFRL);
DEBUG(1, "Pseudo = 0x%x\n", tempword);
chksum ^= tempword;
// read checksum value
tempword = ft1000_read_reg(dev, FT1000_REG_MAG_DFRH);
DEBUG(1, "Pseudo = 0x%x\n", tempword);
}
if (chksum != tempword) {
DEBUG(0, "Packet checksum mismatch 0x%x 0x%x\n", chksum,
tempword);
ft1000_flush_fifo(dev, DSP_PKTPHCKSUM_INFO);
info->stats.rx_errors++;
kfree_skb(skb);
return FAILURE;
}
//subtract the number of bytes read already
ptemp = pbuffer;
// fake MAC address
*pbuffer++ = dev->dev_addr[0];
*pbuffer++ = dev->dev_addr[1];
*pbuffer++ = dev->dev_addr[2];
*pbuffer++ = dev->dev_addr[3];
*pbuffer++ = dev->dev_addr[4];
*pbuffer++ = dev->dev_addr[5];
*pbuffer++ = 0x00;
*pbuffer++ = 0x07;
*pbuffer++ = 0x35;
*pbuffer++ = 0xff;
*pbuffer++ = 0xff;
*pbuffer++ = 0xfe;
if (info->AsicID == ELECTRABUZZ_ID) {
for (i = 0; i < len / 2; i++) {
tempword = ft1000_read_reg(dev, FT1000_REG_DFIFO);
*pbuffer++ = (u8) (tempword >> 8);
*pbuffer++ = (u8) tempword;
if (ft1000_chkcard(dev) == false) {
kfree_skb(skb);
return FAILURE;
}
}
// Need to read one more word if odd byte
if (len & 0x0001) {
tempword = ft1000_read_reg(dev, FT1000_REG_DFIFO);
*pbuffer++ = (u8) (tempword >> 8);
}
} else {
ptemplong = (u32 *) pbuffer;
for (i = 0; i < len / 4; i++) {
templong = inl(dev->base_addr + FT1000_REG_MAG_DFR);
DEBUG(1, "Data = 0x%8x\n", templong);
*ptemplong++ = templong;
}
// Need to read one more word if odd align.
if (len & 0x0003) {
templong = inl(dev->base_addr + FT1000_REG_MAG_DFR);
DEBUG(1, "Data = 0x%8x\n", templong);
*ptemplong++ = templong;
}
}
DEBUG(1, "Data passed to Protocol layer:\n");
for (i = 0; i < len + 12; i++) {
DEBUG(1, "Protocol Data: 0x%x\n ", *ptemp++);
}
skb->dev = dev;
skb->protocol = eth_type_trans(skb, dev);
skb->ip_summed = CHECKSUM_UNNECESSARY;
netif_rx(skb);
info->stats.rx_packets++;
// Add on 12 bytes for MAC address which was removed
info->stats.rx_bytes += (len + 12);
if (info->AsicID == ELECTRABUZZ_ID) {
// track how many bytes have been read from FIFO - round up to 16 bit word
tempword = len + 16;
if (tempword & 0x01)
tempword++;
info->fifo_cnt += tempword;
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR, FT1000_FIFO_LEN);
ft1000_write_reg(dev, FT1000_REG_DPRAM_DATA, info->fifo_cnt);
}
return SUCCESS;
}
//---------------------------------------------------------------------------
//
// Function: ft1000_copy_down_pkt
// Description: This function will take an ethernet packet and convert it to
// a Flarion packet prior to sending it to the ASIC Downlink
// FIFO.
// Input:
// dev - device structure
// packet - address of ethernet packet
// len - length of IP packet
// Output:
// status - FAILURE
// SUCCESS
//
//---------------------------------------------------------------------------
static int ft1000_copy_down_pkt(struct net_device *dev, u16 * packet, u16 len)
{
struct ft1000_info *info = netdev_priv(dev);
union {
struct pseudo_hdr blk;
u16 buff[sizeof(struct pseudo_hdr) >> 1];
u8 buffc[sizeof(struct pseudo_hdr)];
} pseudo;
int i;
u32 *plong;
DEBUG(1, "ft1000_hw: copy_down_pkt()\n");
// Check if there is room on the FIFO
if (len > ft1000_read_fifo_len(dev)) {
udelay(10);
if (len > ft1000_read_fifo_len(dev)) {
udelay(20);
}
if (len > ft1000_read_fifo_len(dev)) {
udelay(20);
}
if (len > ft1000_read_fifo_len(dev)) {
udelay(20);
}
if (len > ft1000_read_fifo_len(dev)) {
udelay(20);
}
if (len > ft1000_read_fifo_len(dev)) {
udelay(20);
}
if (len > ft1000_read_fifo_len(dev)) {
DEBUG(1,
"ft1000_hw:ft1000_copy_down_pkt:Transmit FIFO is fulli - pkt drop\n");
info->stats.tx_errors++;
return SUCCESS;
}
}
// Create pseudo header and send pseudo/ip to hardware
if (info->AsicID == ELECTRABUZZ_ID) {
pseudo.blk.length = len;
} else {
pseudo.blk.length = ntohs(len);
}
pseudo.blk.source = DSPID; // Need to swap to get in correct order
pseudo.blk.destination = HOSTID;
pseudo.blk.portdest = NETWORKID; // Need to swap to get in correct order
pseudo.blk.portsrc = DSPAIRID;
pseudo.blk.sh_str_id = 0;
pseudo.blk.control = 0;
pseudo.blk.rsvd1 = 0;
pseudo.blk.seq_num = 0;
pseudo.blk.rsvd2 = info->packetseqnum++;
pseudo.blk.qos_class = 0;
/* Calculate pseudo header checksum */
pseudo.blk.checksum = pseudo.buff[0];
for (i = 1; i < 7; i++) {
pseudo.blk.checksum ^= pseudo.buff[i];
}
// Production Mode
if (info->AsicID == ELECTRABUZZ_ID) {
// copy first word to UFIFO_BEG reg
ft1000_write_reg(dev, FT1000_REG_UFIFO_BEG, pseudo.buff[0]);
DEBUG(1, "ft1000_hw:ft1000_copy_down_pkt:data 0 BEG = 0x%04x\n",
pseudo.buff[0]);
// copy subsequent words to UFIFO_MID reg
ft1000_write_reg(dev, FT1000_REG_UFIFO_MID, pseudo.buff[1]);
DEBUG(1, "ft1000_hw:ft1000_copy_down_pkt:data 1 MID = 0x%04x\n",
pseudo.buff[1]);
ft1000_write_reg(dev, FT1000_REG_UFIFO_MID, pseudo.buff[2]);
DEBUG(1, "ft1000_hw:ft1000_copy_down_pkt:data 2 MID = 0x%04x\n",
pseudo.buff[2]);
ft1000_write_reg(dev, FT1000_REG_UFIFO_MID, pseudo.buff[3]);
DEBUG(1, "ft1000_hw:ft1000_copy_down_pkt:data 3 MID = 0x%04x\n",
pseudo.buff[3]);
ft1000_write_reg(dev, FT1000_REG_UFIFO_MID, pseudo.buff[4]);
DEBUG(1, "ft1000_hw:ft1000_copy_down_pkt:data 4 MID = 0x%04x\n",
pseudo.buff[4]);
ft1000_write_reg(dev, FT1000_REG_UFIFO_MID, pseudo.buff[5]);
DEBUG(1, "ft1000_hw:ft1000_copy_down_pkt:data 5 MID = 0x%04x\n",
pseudo.buff[5]);
ft1000_write_reg(dev, FT1000_REG_UFIFO_MID, pseudo.buff[6]);
DEBUG(1, "ft1000_hw:ft1000_copy_down_pkt:data 6 MID = 0x%04x\n",
pseudo.buff[6]);
ft1000_write_reg(dev, FT1000_REG_UFIFO_MID, pseudo.buff[7]);
DEBUG(1, "ft1000_hw:ft1000_copy_down_pkt:data 7 MID = 0x%04x\n",
pseudo.buff[7]);
// Write PPP type + IP Packet into Downlink FIFO
for (i = 0; i < (len >> 1) - 1; i++) {
ft1000_write_reg(dev, FT1000_REG_UFIFO_MID,
htons(*packet));
DEBUG(1,
"ft1000_hw:ft1000_copy_down_pkt:data %d MID = 0x%04x\n",
i + 8, htons(*packet));
packet++;
}
// Check for odd byte
if (len & 0x0001) {
ft1000_write_reg(dev, FT1000_REG_UFIFO_MID,
htons(*packet));
DEBUG(1,
"ft1000_hw:ft1000_copy_down_pkt:data MID = 0x%04x\n",
htons(*packet));
packet++;
ft1000_write_reg(dev, FT1000_REG_UFIFO_END,
htons(*packet));
DEBUG(1,
"ft1000_hw:ft1000_copy_down_pkt:data %d MID = 0x%04x\n",
i + 8, htons(*packet));
} else {
ft1000_write_reg(dev, FT1000_REG_UFIFO_END,
htons(*packet));
DEBUG(1,
"ft1000_hw:ft1000_copy_down_pkt:data %d MID = 0x%04x\n",
i + 8, htons(*packet));
}
} else {
outl(*(u32 *) & pseudo.buff[0],
dev->base_addr + FT1000_REG_MAG_UFDR);
DEBUG(1, "ft1000_copy_down_pkt: Pseudo = 0x%8x\n",
*(u32 *) & pseudo.buff[0]);
outl(*(u32 *) & pseudo.buff[2],
dev->base_addr + FT1000_REG_MAG_UFDR);
DEBUG(1, "ft1000_copy_down_pkt: Pseudo = 0x%8x\n",
*(u32 *) & pseudo.buff[2]);
outl(*(u32 *) & pseudo.buff[4],
dev->base_addr + FT1000_REG_MAG_UFDR);
DEBUG(1, "ft1000_copy_down_pkt: Pseudo = 0x%8x\n",
*(u32 *) & pseudo.buff[4]);
outl(*(u32 *) & pseudo.buff[6],
dev->base_addr + FT1000_REG_MAG_UFDR);
DEBUG(1, "ft1000_copy_down_pkt: Pseudo = 0x%8x\n",
*(u32 *) & pseudo.buff[6]);
plong = (u32 *) packet;
// Write PPP type + IP Packet into Downlink FIFO
for (i = 0; i < (len >> 2); i++) {
outl(*plong++, dev->base_addr + FT1000_REG_MAG_UFDR);
}
// Check for odd alignment
if (len & 0x0003) {
DEBUG(1,
"ft1000_hw:ft1000_copy_down_pkt:data = 0x%8x\n",
*plong);
outl(*plong++, dev->base_addr + FT1000_REG_MAG_UFDR);
}
outl(1, dev->base_addr + FT1000_REG_MAG_UFER);
}
info->stats.tx_packets++;
// Add 14 bytes for MAC address plus ethernet type
info->stats.tx_bytes += (len + 14);
return SUCCESS;
}
static struct net_device_stats *ft1000_stats(struct net_device *dev)
{
struct ft1000_info *info = netdev_priv(dev);
return (&info->stats);
}
static int ft1000_open(struct net_device *dev)
{
DEBUG(0, "ft1000_hw: ft1000_open is called\n");
ft1000_reset_card(dev);
DEBUG(0, "ft1000_hw: ft1000_open is ended\n");
/* schedule ft1000_hbchk to perform periodic heartbeat checks on DSP and ASIC */
init_timer(&poll_timer);
poll_timer.expires = jiffies + (2 * HZ);
poll_timer.data = (u_long) dev;
add_timer(&poll_timer);
DEBUG(0, "ft1000_hw: ft1000_open is ended2\n");
return 0;
}
static int ft1000_close(struct net_device *dev)
{
struct ft1000_info *info = netdev_priv(dev);
DEBUG(0, "ft1000_hw: ft1000_close()\n");
info->CardReady = 0;
del_timer(&poll_timer);
if (ft1000_card_present == 1) {
DEBUG(0, "Media is down\n");
netif_stop_queue(dev);
ft1000_disable_interrupts(dev);
ft1000_write_reg(dev, FT1000_REG_RESET, DSP_RESET_BIT);
//reset ASIC
ft1000_reset_asic(dev);
}
return 0;
}
static int ft1000_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct ft1000_info *info = netdev_priv(dev);
u8 *pdata;
DEBUG(1, "ft1000_hw: ft1000_start_xmit()\n");
if (skb == NULL) {
DEBUG(1, "ft1000_hw: ft1000_start_xmit:skb == NULL!!!\n");
return 0;
}
DEBUG(1, "ft1000_hw: ft1000_start_xmit:length of packet = %d\n",
skb->len);
pdata = (u8 *) skb->data;
if (info->mediastate == 0) {
/* Drop packet is mediastate is down */
DEBUG(1, "ft1000_hw:ft1000_copy_down_pkt:mediastate is down\n");
return SUCCESS;
}
if ((skb->len < ENET_HEADER_SIZE) || (skb->len > ENET_MAX_SIZE)) {
/* Drop packet which has invalid size */
DEBUG(1,
"ft1000_hw:ft1000_copy_down_pkt:invalid ethernet length\n");
return SUCCESS;
}
ft1000_copy_down_pkt(dev, (u16 *) (pdata + ENET_HEADER_SIZE - 2),
skb->len - ENET_HEADER_SIZE + 2);
dev_kfree_skb(skb);
return 0;
}
static irqreturn_t ft1000_interrupt(int irq, void *dev_id)
{
struct net_device *dev = (struct net_device *)dev_id;
struct ft1000_info *info = netdev_priv(dev);
u16 tempword;
u16 inttype;
int cnt;
DEBUG(1, "ft1000_hw: ft1000_interrupt()\n");
if (info->CardReady == 0) {
ft1000_disable_interrupts(dev);
return IRQ_HANDLED;
}
if (ft1000_chkcard(dev) == false) {
ft1000_disable_interrupts(dev);
return IRQ_HANDLED;
}
ft1000_disable_interrupts(dev);
// Read interrupt type
inttype = ft1000_read_reg(dev, FT1000_REG_SUP_ISR);
// Make sure we process all interrupt before leaving the ISR due to the edge trigger interrupt type
while (inttype) {
if (inttype & ISR_DOORBELL_PEND) {
ft1000_parse_dpram_msg(dev);
}
if (inttype & ISR_RCV) {
DEBUG(1, "Data in FIFO\n");
cnt = 0;
do {
// Check if we have packets in the Downlink FIFO
if (info->AsicID == ELECTRABUZZ_ID) {
tempword =
ft1000_read_reg(dev, FT1000_REG_DFIFO_STAT);
} else {
tempword =
ft1000_read_reg(dev, FT1000_REG_MAG_DFSR);
}
if (tempword & 0x1f) {
ft1000_copy_up_pkt(dev);
} else {
break;
}
cnt++;
} while (cnt < MAX_RCV_LOOP);
}
// clear interrupts
tempword = ft1000_read_reg(dev, FT1000_REG_SUP_ISR);
DEBUG(1, "ft1000_hw: interrupt status register = 0x%x\n", tempword);
ft1000_write_reg(dev, FT1000_REG_SUP_ISR, tempword);
// Read interrupt type
inttype = ft1000_read_reg (dev, FT1000_REG_SUP_ISR);
DEBUG(1,"ft1000_hw: interrupt status register after clear = 0x%x\n",inttype);
}
ft1000_enable_interrupts(dev);
return IRQ_HANDLED;
}
void stop_ft1000_card(struct net_device *dev)
{
struct ft1000_info *info = netdev_priv(dev);
struct prov_record *ptr;
// int cnt;
DEBUG(0, "ft1000_hw: stop_ft1000_card()\n");
info->CardReady = 0;
ft1000_card_present = 0;
netif_stop_queue(dev);
ft1000_disable_interrupts(dev);
// Make sure we free any memory reserve for provisioning
while (list_empty(&info->prov_list) == 0) {
ptr = list_entry(info->prov_list.next, struct prov_record, list);
list_del(&ptr->list);
kfree(ptr->pprov_data);
kfree(ptr);
}
if (info->registered) {
unregister_netdev(dev);
info->registered = 0;
}
free_irq(dev->irq, dev);
release_region(dev->base_addr,256);
release_firmware(fw_entry);
flarion_ft1000_cnt--;
ft1000CleanupProc(dev);
}
static void ft1000_get_drvinfo(struct net_device *dev,
struct ethtool_drvinfo *info)
{
struct ft1000_info *ft_info;
ft_info = netdev_priv(dev);
snprintf(info->driver, 32, "ft1000");
snprintf(info->bus_info, ETHTOOL_BUSINFO_LEN, "PCMCIA 0x%lx",
dev->base_addr);
snprintf(info->fw_version, 32, "%d.%d.%d.%d", ft_info->DspVer[0],
ft_info->DspVer[1], ft_info->DspVer[2], ft_info->DspVer[3]);
}
static u32 ft1000_get_link(struct net_device *dev)
{
struct ft1000_info *info;
info = netdev_priv(dev);
return info->mediastate;
}
static const struct ethtool_ops ops = {
.get_drvinfo = ft1000_get_drvinfo,
.get_link = ft1000_get_link
};
struct net_device *init_ft1000_card(struct pcmcia_device *link,
void *ft1000_reset)
{
struct ft1000_info *info;
struct net_device *dev;
static const struct net_device_ops ft1000ops = // Slavius 21.10.2009 due to kernel changes
{
.ndo_open = &ft1000_open,
.ndo_stop = &ft1000_close,
.ndo_start_xmit = &ft1000_start_xmit,
.ndo_get_stats = &ft1000_stats,
};
DEBUG(1, "ft1000_hw: init_ft1000_card()\n");
DEBUG(1, "ft1000_hw: irq = %d\n", link->irq);
DEBUG(1, "ft1000_hw: port = 0x%04x\n", link->resource[0]->start);
flarion_ft1000_cnt++;
if (flarion_ft1000_cnt > 1) {
flarion_ft1000_cnt--;
printk(KERN_INFO
"ft1000: This driver can not support more than one instance\n");
return NULL;
}
dev = alloc_etherdev(sizeof(struct ft1000_info));
if (!dev) {
printk(KERN_ERR "ft1000: failed to allocate etherdev\n");
return NULL;
}
SET_NETDEV_DEV(dev, &link->dev);
info = netdev_priv(dev);
memset(info, 0, sizeof(struct ft1000_info));
DEBUG(1, "address of dev = 0x%8x\n", (u32) dev);
DEBUG(1, "address of dev info = 0x%8x\n", (u32) info);
DEBUG(0, "device name = %s\n", dev->name);
memset(&info->stats, 0, sizeof(struct net_device_stats));
spin_lock_init(&info->dpram_lock);
info->DrvErrNum = 0;
info->registered = 1;
info->link = link;
info->ft1000_reset = ft1000_reset;
info->mediastate = 0;
info->fifo_cnt = 0;
info->CardReady = 0;
info->DSP_TIME[0] = 0;
info->DSP_TIME[1] = 0;
info->DSP_TIME[2] = 0;
info->DSP_TIME[3] = 0;
flarion_ft1000_cnt = 0;
INIT_LIST_HEAD(&info->prov_list);
info->squeseqnum = 0;
// dev->hard_start_xmit = &ft1000_start_xmit;
// dev->get_stats = &ft1000_stats;
// dev->open = &ft1000_open;
// dev->stop = &ft1000_close;
dev->netdev_ops = &ft1000ops; // Slavius 21.10.2009 due to kernel changes
DEBUG(0, "device name = %s\n", dev->name);
dev->irq = link->irq;
dev->base_addr = link->resource[0]->start;
if (pcmcia_get_mac_from_cis(link, dev)) {
printk(KERN_ERR "ft1000: Could not read mac address\n");
goto err_dev;
}
if (request_irq(dev->irq, ft1000_interrupt, IRQF_SHARED, dev->name, dev)) {
printk(KERN_ERR "ft1000: Could not request_irq\n");
goto err_dev;
}
if (request_region(dev->base_addr, 256, dev->name) == NULL) {
printk(KERN_ERR "ft1000: Could not request_region\n");
goto err_irq;
}
if (register_netdev(dev) != 0) {
DEBUG(0, "ft1000: Could not register netdev");
goto err_reg;
}
info->AsicID = ft1000_read_reg(dev, FT1000_REG_ASIC_ID);
if (info->AsicID == ELECTRABUZZ_ID) {
DEBUG(0, "ft1000_hw: ELECTRABUZZ ASIC\n");
if (request_firmware(&fw_entry, "ft1000.img", &link->dev) != 0) {
printk(KERN_INFO "ft1000: Could not open ft1000.img\n");
goto err_unreg;
}
} else {
DEBUG(0, "ft1000_hw: MAGNEMITE ASIC\n");
if (request_firmware(&fw_entry, "ft2000.img", &link->dev) != 0) {
printk(KERN_INFO "ft1000: Could not open ft2000.img\n");
goto err_unreg;
}
}
ft1000_enable_interrupts(dev);
ft1000InitProc(dev);
ft1000_card_present = 1;
SET_ETHTOOL_OPS(dev, &ops);
printk(KERN_INFO "ft1000: %s: addr 0x%04lx irq %d, MAC addr %pM\n",
dev->name, dev->base_addr, dev->irq, dev->dev_addr);
return dev;
err_unreg:
unregister_netdev(dev);
err_reg:
release_region(dev->base_addr, 256);
err_irq:
free_irq(dev->irq, dev);
err_dev:
free_netdev(dev);
return NULL;
}
| gpl-2.0 |
sssangram14/android_kernel_samsung_arubaslim | drivers/s390/char/sclp_cpi_sys.c | 5107 | 8798 | /*
* drivers/s390/char/sclp_cpi_sys.c
* SCLP control program identification sysfs interface
*
* Copyright IBM Corp. 2001, 2007
* Author(s): Martin Peschke <mpeschke@de.ibm.com>
* Michael Ernst <mernst@de.ibm.com>
*/
#define KMSG_COMPONENT "sclp_cpi"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/stat.h>
#include <linux/device.h>
#include <linux/string.h>
#include <linux/ctype.h>
#include <linux/kmod.h>
#include <linux/timer.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/completion.h>
#include <linux/export.h>
#include <asm/ebcdic.h>
#include <asm/sclp.h>
#include "sclp.h"
#include "sclp_rw.h"
#include "sclp_cpi_sys.h"
#define CPI_LENGTH_NAME 8
#define CPI_LENGTH_LEVEL 16
static DEFINE_MUTEX(sclp_cpi_mutex);
struct cpi_evbuf {
struct evbuf_header header;
u8 id_format;
u8 reserved0;
u8 system_type[CPI_LENGTH_NAME];
u64 reserved1;
u8 system_name[CPI_LENGTH_NAME];
u64 reserved2;
u64 system_level;
u64 reserved3;
u8 sysplex_name[CPI_LENGTH_NAME];
u8 reserved4[16];
} __attribute__((packed));
struct cpi_sccb {
struct sccb_header header;
struct cpi_evbuf cpi_evbuf;
} __attribute__((packed));
static struct sclp_register sclp_cpi_event = {
.send_mask = EVTYP_CTLPROGIDENT_MASK,
};
static char system_name[CPI_LENGTH_NAME + 1];
static char sysplex_name[CPI_LENGTH_NAME + 1];
static char system_type[CPI_LENGTH_NAME + 1];
static u64 system_level;
static void set_data(char *field, char *data)
{
memset(field, ' ', CPI_LENGTH_NAME);
memcpy(field, data, strlen(data));
sclp_ascebc_str(field, CPI_LENGTH_NAME);
}
static void cpi_callback(struct sclp_req *req, void *data)
{
struct completion *completion = data;
complete(completion);
}
static struct sclp_req *cpi_prepare_req(void)
{
struct sclp_req *req;
struct cpi_sccb *sccb;
struct cpi_evbuf *evb;
req = kzalloc(sizeof(struct sclp_req), GFP_KERNEL);
if (!req)
return ERR_PTR(-ENOMEM);
sccb = (struct cpi_sccb *) get_zeroed_page(GFP_KERNEL | GFP_DMA);
if (!sccb) {
kfree(req);
return ERR_PTR(-ENOMEM);
}
/* setup SCCB for Control-Program Identification */
sccb->header.length = sizeof(struct cpi_sccb);
sccb->cpi_evbuf.header.length = sizeof(struct cpi_evbuf);
sccb->cpi_evbuf.header.type = 0x0b;
evb = &sccb->cpi_evbuf;
/* set system type */
set_data(evb->system_type, system_type);
/* set system name */
set_data(evb->system_name, system_name);
/* set system level */
evb->system_level = system_level;
/* set sysplex name */
set_data(evb->sysplex_name, sysplex_name);
/* prepare request data structure presented to SCLP driver */
req->command = SCLP_CMDW_WRITE_EVENT_DATA;
req->sccb = sccb;
req->status = SCLP_REQ_FILLED;
req->callback = cpi_callback;
return req;
}
static void cpi_free_req(struct sclp_req *req)
{
free_page((unsigned long) req->sccb);
kfree(req);
}
static int cpi_req(void)
{
struct completion completion;
struct sclp_req *req;
int rc;
int response;
rc = sclp_register(&sclp_cpi_event);
if (rc)
goto out;
if (!(sclp_cpi_event.sclp_receive_mask & EVTYP_CTLPROGIDENT_MASK)) {
rc = -EOPNOTSUPP;
goto out_unregister;
}
req = cpi_prepare_req();
if (IS_ERR(req)) {
rc = PTR_ERR(req);
goto out_unregister;
}
init_completion(&completion);
req->callback_data = &completion;
/* Add request to sclp queue */
rc = sclp_add_request(req);
if (rc)
goto out_free_req;
wait_for_completion(&completion);
if (req->status != SCLP_REQ_DONE) {
pr_warning("request failed (status=0x%02x)\n",
req->status);
rc = -EIO;
goto out_free_req;
}
response = ((struct cpi_sccb *) req->sccb)->header.response_code;
if (response != 0x0020) {
pr_warning("request failed with response code 0x%x\n",
response);
rc = -EIO;
}
out_free_req:
cpi_free_req(req);
out_unregister:
sclp_unregister(&sclp_cpi_event);
out:
return rc;
}
static int check_string(const char *attr, const char *str)
{
size_t len;
size_t i;
len = strlen(str);
if ((len > 0) && (str[len - 1] == '\n'))
len--;
if (len > CPI_LENGTH_NAME)
return -EINVAL;
for (i = 0; i < len ; i++) {
if (isalpha(str[i]) || isdigit(str[i]) ||
strchr("$@# ", str[i]))
continue;
return -EINVAL;
}
return 0;
}
static void set_string(char *attr, const char *value)
{
size_t len;
size_t i;
len = strlen(value);
if ((len > 0) && (value[len - 1] == '\n'))
len--;
for (i = 0; i < CPI_LENGTH_NAME; i++) {
if (i < len)
attr[i] = toupper(value[i]);
else
attr[i] = ' ';
}
}
static ssize_t system_name_show(struct kobject *kobj,
struct kobj_attribute *attr, char *page)
{
int rc;
mutex_lock(&sclp_cpi_mutex);
rc = snprintf(page, PAGE_SIZE, "%s\n", system_name);
mutex_unlock(&sclp_cpi_mutex);
return rc;
}
static ssize_t system_name_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf,
size_t len)
{
int rc;
rc = check_string("system_name", buf);
if (rc)
return rc;
mutex_lock(&sclp_cpi_mutex);
set_string(system_name, buf);
mutex_unlock(&sclp_cpi_mutex);
return len;
}
static struct kobj_attribute system_name_attr =
__ATTR(system_name, 0644, system_name_show, system_name_store);
static ssize_t sysplex_name_show(struct kobject *kobj,
struct kobj_attribute *attr, char *page)
{
int rc;
mutex_lock(&sclp_cpi_mutex);
rc = snprintf(page, PAGE_SIZE, "%s\n", sysplex_name);
mutex_unlock(&sclp_cpi_mutex);
return rc;
}
static ssize_t sysplex_name_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf,
size_t len)
{
int rc;
rc = check_string("sysplex_name", buf);
if (rc)
return rc;
mutex_lock(&sclp_cpi_mutex);
set_string(sysplex_name, buf);
mutex_unlock(&sclp_cpi_mutex);
return len;
}
static struct kobj_attribute sysplex_name_attr =
__ATTR(sysplex_name, 0644, sysplex_name_show, sysplex_name_store);
static ssize_t system_type_show(struct kobject *kobj,
struct kobj_attribute *attr, char *page)
{
int rc;
mutex_lock(&sclp_cpi_mutex);
rc = snprintf(page, PAGE_SIZE, "%s\n", system_type);
mutex_unlock(&sclp_cpi_mutex);
return rc;
}
static ssize_t system_type_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf,
size_t len)
{
int rc;
rc = check_string("system_type", buf);
if (rc)
return rc;
mutex_lock(&sclp_cpi_mutex);
set_string(system_type, buf);
mutex_unlock(&sclp_cpi_mutex);
return len;
}
static struct kobj_attribute system_type_attr =
__ATTR(system_type, 0644, system_type_show, system_type_store);
static ssize_t system_level_show(struct kobject *kobj,
struct kobj_attribute *attr, char *page)
{
unsigned long long level;
mutex_lock(&sclp_cpi_mutex);
level = system_level;
mutex_unlock(&sclp_cpi_mutex);
return snprintf(page, PAGE_SIZE, "%#018llx\n", level);
}
static ssize_t system_level_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf,
size_t len)
{
unsigned long long level;
char *endp;
level = simple_strtoull(buf, &endp, 16);
if (endp == buf)
return -EINVAL;
if (*endp == '\n')
endp++;
if (*endp)
return -EINVAL;
mutex_lock(&sclp_cpi_mutex);
system_level = level;
mutex_unlock(&sclp_cpi_mutex);
return len;
}
static struct kobj_attribute system_level_attr =
__ATTR(system_level, 0644, system_level_show, system_level_store);
static ssize_t set_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t len)
{
int rc;
mutex_lock(&sclp_cpi_mutex);
rc = cpi_req();
mutex_unlock(&sclp_cpi_mutex);
if (rc)
return rc;
return len;
}
static struct kobj_attribute set_attr = __ATTR(set, 0200, NULL, set_store);
static struct attribute *cpi_attrs[] = {
&system_name_attr.attr,
&sysplex_name_attr.attr,
&system_type_attr.attr,
&system_level_attr.attr,
&set_attr.attr,
NULL,
};
static struct attribute_group cpi_attr_group = {
.attrs = cpi_attrs,
};
static struct kset *cpi_kset;
int sclp_cpi_set_data(const char *system, const char *sysplex, const char *type,
const u64 level)
{
int rc;
rc = check_string("system_name", system);
if (rc)
return rc;
rc = check_string("sysplex_name", sysplex);
if (rc)
return rc;
rc = check_string("system_type", type);
if (rc)
return rc;
mutex_lock(&sclp_cpi_mutex);
set_string(system_name, system);
set_string(sysplex_name, sysplex);
set_string(system_type, type);
system_level = level;
rc = cpi_req();
mutex_unlock(&sclp_cpi_mutex);
return rc;
}
EXPORT_SYMBOL(sclp_cpi_set_data);
static int __init cpi_init(void)
{
int rc;
cpi_kset = kset_create_and_add("cpi", NULL, firmware_kobj);
if (!cpi_kset)
return -ENOMEM;
rc = sysfs_create_group(&cpi_kset->kobj, &cpi_attr_group);
if (rc)
kset_unregister(cpi_kset);
return rc;
}
__initcall(cpi_init);
| gpl-2.0 |
FrozenCow/msm | drivers/input/joystick/analog.c | 5619 | 20374 | /*
* Copyright (c) 1996-2001 Vojtech Pavlik
*/
/*
* Analog joystick and gamepad driver for Linux
*/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Should you need to contact me, the author, you can do so either by
* e-mail - mail your message to <vojtech@ucw.cz>, or by paper mail:
* Vojtech Pavlik, Simunkova 1594, Prague 8, 182 00 Czech Republic
*/
#include <linux/delay.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/bitops.h>
#include <linux/init.h>
#include <linux/input.h>
#include <linux/gameport.h>
#include <linux/jiffies.h>
#include <linux/timex.h>
#define DRIVER_DESC "Analog joystick and gamepad driver"
MODULE_AUTHOR("Vojtech Pavlik <vojtech@ucw.cz>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
/*
* Option parsing.
*/
#define ANALOG_PORTS 16
static char *js[ANALOG_PORTS];
static unsigned int js_nargs;
static int analog_options[ANALOG_PORTS];
module_param_array_named(map, js, charp, &js_nargs, 0);
MODULE_PARM_DESC(map, "Describes analog joysticks type/capabilities");
/*
* Times, feature definitions.
*/
#define ANALOG_RUDDER 0x00004
#define ANALOG_THROTTLE 0x00008
#define ANALOG_AXES_STD 0x0000f
#define ANALOG_BTNS_STD 0x000f0
#define ANALOG_BTNS_CHF 0x00100
#define ANALOG_HAT1_CHF 0x00200
#define ANALOG_HAT2_CHF 0x00400
#define ANALOG_HAT_FCS 0x00800
#define ANALOG_HATS_ALL 0x00e00
#define ANALOG_BTN_TL 0x01000
#define ANALOG_BTN_TR 0x02000
#define ANALOG_BTN_TL2 0x04000
#define ANALOG_BTN_TR2 0x08000
#define ANALOG_BTNS_TLR 0x03000
#define ANALOG_BTNS_TLR2 0x0c000
#define ANALOG_BTNS_GAMEPAD 0x0f000
#define ANALOG_HBTN_CHF 0x10000
#define ANALOG_ANY_CHF 0x10700
#define ANALOG_SAITEK 0x20000
#define ANALOG_EXTENSIONS 0x7ff00
#define ANALOG_GAMEPAD 0x80000
#define ANALOG_MAX_TIME 3 /* 3 ms */
#define ANALOG_LOOP_TIME 2000 /* 2 * loop */
#define ANALOG_SAITEK_DELAY 200 /* 200 us */
#define ANALOG_SAITEK_TIME 2000 /* 2000 us */
#define ANALOG_AXIS_TIME 2 /* 2 * refresh */
#define ANALOG_INIT_RETRIES 8 /* 8 times */
#define ANALOG_FUZZ_BITS 2 /* 2 bit more */
#define ANALOG_FUZZ_MAGIC 36 /* 36 u*ms/loop */
#define ANALOG_MAX_NAME_LENGTH 128
#define ANALOG_MAX_PHYS_LENGTH 32
static short analog_axes[] = { ABS_X, ABS_Y, ABS_RUDDER, ABS_THROTTLE };
static short analog_hats[] = { ABS_HAT0X, ABS_HAT0Y, ABS_HAT1X, ABS_HAT1Y, ABS_HAT2X, ABS_HAT2Y };
static short analog_pads[] = { BTN_Y, BTN_Z, BTN_TL, BTN_TR };
static short analog_exts[] = { ANALOG_HAT1_CHF, ANALOG_HAT2_CHF, ANALOG_HAT_FCS };
static short analog_pad_btn[] = { BTN_A, BTN_B, BTN_C, BTN_X, BTN_TL2, BTN_TR2, BTN_SELECT, BTN_START, BTN_MODE, BTN_BASE };
static short analog_joy_btn[] = { BTN_TRIGGER, BTN_THUMB, BTN_TOP, BTN_TOP2, BTN_BASE, BTN_BASE2,
BTN_BASE3, BTN_BASE4, BTN_BASE5, BTN_BASE6 };
static unsigned char analog_chf[] = { 0xf, 0x0, 0x1, 0x9, 0x2, 0x4, 0xc, 0x8, 0x3, 0x5, 0xb, 0x7, 0xd, 0xe, 0xa, 0x6 };
struct analog {
struct input_dev *dev;
int mask;
short *buttons;
char name[ANALOG_MAX_NAME_LENGTH];
char phys[ANALOG_MAX_PHYS_LENGTH];
};
struct analog_port {
struct gameport *gameport;
struct analog analog[2];
unsigned char mask;
char saitek;
char cooked;
int bads;
int reads;
int speed;
int loop;
int fuzz;
int axes[4];
int buttons;
int initial[4];
int axtime;
};
/*
* Time macros.
*/
#ifdef __i386__
#include <linux/i8253.h>
#define GET_TIME(x) do { if (cpu_has_tsc) rdtscl(x); else x = get_time_pit(); } while (0)
#define DELTA(x,y) (cpu_has_tsc ? ((y) - (x)) : ((x) - (y) + ((x) < (y) ? PIT_TICK_RATE / HZ : 0)))
#define TIME_NAME (cpu_has_tsc?"TSC":"PIT")
static unsigned int get_time_pit(void)
{
unsigned long flags;
unsigned int count;
raw_spin_lock_irqsave(&i8253_lock, flags);
outb_p(0x00, 0x43);
count = inb_p(0x40);
count |= inb_p(0x40) << 8;
raw_spin_unlock_irqrestore(&i8253_lock, flags);
return count;
}
#elif defined(__x86_64__)
#define GET_TIME(x) rdtscl(x)
#define DELTA(x,y) ((y)-(x))
#define TIME_NAME "TSC"
#elif defined(__alpha__)
#define GET_TIME(x) do { x = get_cycles(); } while (0)
#define DELTA(x,y) ((y)-(x))
#define TIME_NAME "PCC"
#elif defined(CONFIG_MN10300)
#define GET_TIME(x) do { x = get_cycles(); } while (0)
#define DELTA(x, y) ((x) - (y))
#define TIME_NAME "TSC"
#else
#define FAKE_TIME
static unsigned long analog_faketime = 0;
#define GET_TIME(x) do { x = analog_faketime++; } while(0)
#define DELTA(x,y) ((y)-(x))
#define TIME_NAME "Unreliable"
#warning Precise timer not defined for this architecture.
#endif
/*
* analog_decode() decodes analog joystick data and reports input events.
*/
static void analog_decode(struct analog *analog, int *axes, int *initial, int buttons)
{
struct input_dev *dev = analog->dev;
int i, j;
if (analog->mask & ANALOG_HAT_FCS)
for (i = 0; i < 4; i++)
if (axes[3] < ((initial[3] * ((i << 1) + 1)) >> 3)) {
buttons |= 1 << (i + 14);
break;
}
for (i = j = 0; i < 6; i++)
if (analog->mask & (0x10 << i))
input_report_key(dev, analog->buttons[j++], (buttons >> i) & 1);
if (analog->mask & ANALOG_HBTN_CHF)
for (i = 0; i < 4; i++)
input_report_key(dev, analog->buttons[j++], (buttons >> (i + 10)) & 1);
if (analog->mask & ANALOG_BTN_TL)
input_report_key(dev, analog_pads[0], axes[2] < (initial[2] >> 1));
if (analog->mask & ANALOG_BTN_TR)
input_report_key(dev, analog_pads[1], axes[3] < (initial[3] >> 1));
if (analog->mask & ANALOG_BTN_TL2)
input_report_key(dev, analog_pads[2], axes[2] > (initial[2] + (initial[2] >> 1)));
if (analog->mask & ANALOG_BTN_TR2)
input_report_key(dev, analog_pads[3], axes[3] > (initial[3] + (initial[3] >> 1)));
for (i = j = 0; i < 4; i++)
if (analog->mask & (1 << i))
input_report_abs(dev, analog_axes[j++], axes[i]);
for (i = j = 0; i < 3; i++)
if (analog->mask & analog_exts[i]) {
input_report_abs(dev, analog_hats[j++],
((buttons >> ((i << 2) + 7)) & 1) - ((buttons >> ((i << 2) + 9)) & 1));
input_report_abs(dev, analog_hats[j++],
((buttons >> ((i << 2) + 8)) & 1) - ((buttons >> ((i << 2) + 6)) & 1));
}
input_sync(dev);
}
/*
* analog_cooked_read() reads analog joystick data.
*/
static int analog_cooked_read(struct analog_port *port)
{
struct gameport *gameport = port->gameport;
unsigned int time[4], start, loop, now, loopout, timeout;
unsigned char data[4], this, last;
unsigned long flags;
int i, j;
loopout = (ANALOG_LOOP_TIME * port->loop) / 1000;
timeout = ANALOG_MAX_TIME * port->speed;
local_irq_save(flags);
gameport_trigger(gameport);
GET_TIME(now);
local_irq_restore(flags);
start = now;
this = port->mask;
i = 0;
do {
loop = now;
last = this;
local_irq_disable();
this = gameport_read(gameport) & port->mask;
GET_TIME(now);
local_irq_restore(flags);
if ((last ^ this) && (DELTA(loop, now) < loopout)) {
data[i] = last ^ this;
time[i] = now;
i++;
}
} while (this && (i < 4) && (DELTA(start, now) < timeout));
this <<= 4;
for (--i; i >= 0; i--) {
this |= data[i];
for (j = 0; j < 4; j++)
if (data[i] & (1 << j))
port->axes[j] = (DELTA(start, time[i]) << ANALOG_FUZZ_BITS) / port->loop;
}
return -(this != port->mask);
}
static int analog_button_read(struct analog_port *port, char saitek, char chf)
{
unsigned char u;
int t = 1, i = 0;
int strobe = gameport_time(port->gameport, ANALOG_SAITEK_TIME);
u = gameport_read(port->gameport);
if (!chf) {
port->buttons = (~u >> 4) & 0xf;
return 0;
}
port->buttons = 0;
while ((~u & 0xf0) && (i < 16) && t) {
port->buttons |= 1 << analog_chf[(~u >> 4) & 0xf];
if (!saitek) return 0;
udelay(ANALOG_SAITEK_DELAY);
t = strobe;
gameport_trigger(port->gameport);
while (((u = gameport_read(port->gameport)) & port->mask) && t) t--;
i++;
}
return -(!t || (i == 16));
}
/*
* analog_poll() repeatedly polls the Analog joysticks.
*/
static void analog_poll(struct gameport *gameport)
{
struct analog_port *port = gameport_get_drvdata(gameport);
int i;
char saitek = !!(port->analog[0].mask & ANALOG_SAITEK);
char chf = !!(port->analog[0].mask & ANALOG_ANY_CHF);
if (port->cooked) {
port->bads -= gameport_cooked_read(port->gameport, port->axes, &port->buttons);
if (chf)
port->buttons = port->buttons ? (1 << analog_chf[port->buttons]) : 0;
port->reads++;
} else {
if (!port->axtime--) {
port->bads -= analog_cooked_read(port);
port->bads -= analog_button_read(port, saitek, chf);
port->reads++;
port->axtime = ANALOG_AXIS_TIME - 1;
} else {
if (!saitek)
analog_button_read(port, saitek, chf);
}
}
for (i = 0; i < 2; i++)
if (port->analog[i].mask)
analog_decode(port->analog + i, port->axes, port->initial, port->buttons);
}
/*
* analog_open() is a callback from the input open routine.
*/
static int analog_open(struct input_dev *dev)
{
struct analog_port *port = input_get_drvdata(dev);
gameport_start_polling(port->gameport);
return 0;
}
/*
* analog_close() is a callback from the input close routine.
*/
static void analog_close(struct input_dev *dev)
{
struct analog_port *port = input_get_drvdata(dev);
gameport_stop_polling(port->gameport);
}
/*
* analog_calibrate_timer() calibrates the timer and computes loop
* and timeout values for a joystick port.
*/
static void analog_calibrate_timer(struct analog_port *port)
{
struct gameport *gameport = port->gameport;
unsigned int i, t, tx, t1, t2, t3;
unsigned long flags;
local_irq_save(flags);
GET_TIME(t1);
#ifdef FAKE_TIME
analog_faketime += 830;
#endif
mdelay(1);
GET_TIME(t2);
GET_TIME(t3);
local_irq_restore(flags);
port->speed = DELTA(t1, t2) - DELTA(t2, t3);
tx = ~0;
for (i = 0; i < 50; i++) {
local_irq_save(flags);
GET_TIME(t1);
for (t = 0; t < 50; t++) { gameport_read(gameport); GET_TIME(t2); }
GET_TIME(t3);
local_irq_restore(flags);
udelay(i);
t = DELTA(t1, t2) - DELTA(t2, t3);
if (t < tx) tx = t;
}
port->loop = tx / 50;
}
/*
* analog_name() constructs a name for an analog joystick.
*/
static void analog_name(struct analog *analog)
{
snprintf(analog->name, sizeof(analog->name), "Analog %d-axis %d-button",
hweight8(analog->mask & ANALOG_AXES_STD),
hweight8(analog->mask & ANALOG_BTNS_STD) + !!(analog->mask & ANALOG_BTNS_CHF) * 2 +
hweight16(analog->mask & ANALOG_BTNS_GAMEPAD) + !!(analog->mask & ANALOG_HBTN_CHF) * 4);
if (analog->mask & ANALOG_HATS_ALL)
snprintf(analog->name, sizeof(analog->name), "%s %d-hat",
analog->name, hweight16(analog->mask & ANALOG_HATS_ALL));
if (analog->mask & ANALOG_HAT_FCS)
strlcat(analog->name, " FCS", sizeof(analog->name));
if (analog->mask & ANALOG_ANY_CHF)
strlcat(analog->name, (analog->mask & ANALOG_SAITEK) ? " Saitek" : " CHF",
sizeof(analog->name));
strlcat(analog->name, (analog->mask & ANALOG_GAMEPAD) ? " gamepad": " joystick",
sizeof(analog->name));
}
/*
* analog_init_device()
*/
static int analog_init_device(struct analog_port *port, struct analog *analog, int index)
{
struct input_dev *input_dev;
int i, j, t, v, w, x, y, z;
int error;
analog_name(analog);
snprintf(analog->phys, sizeof(analog->phys),
"%s/input%d", port->gameport->phys, index);
analog->buttons = (analog->mask & ANALOG_GAMEPAD) ? analog_pad_btn : analog_joy_btn;
analog->dev = input_dev = input_allocate_device();
if (!input_dev)
return -ENOMEM;
input_dev->name = analog->name;
input_dev->phys = analog->phys;
input_dev->id.bustype = BUS_GAMEPORT;
input_dev->id.vendor = GAMEPORT_ID_VENDOR_ANALOG;
input_dev->id.product = analog->mask >> 4;
input_dev->id.version = 0x0100;
input_dev->dev.parent = &port->gameport->dev;
input_set_drvdata(input_dev, port);
input_dev->open = analog_open;
input_dev->close = analog_close;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
for (i = j = 0; i < 4; i++)
if (analog->mask & (1 << i)) {
t = analog_axes[j];
x = port->axes[i];
y = (port->axes[0] + port->axes[1]) >> 1;
z = y - port->axes[i];
z = z > 0 ? z : -z;
v = (x >> 3);
w = (x >> 3);
if ((i == 2 || i == 3) && (j == 2 || j == 3) && (z > (y >> 3)))
x = y;
if (analog->mask & ANALOG_SAITEK) {
if (i == 2) x = port->axes[i];
v = x - (x >> 2);
w = (x >> 4);
}
input_set_abs_params(input_dev, t, v, (x << 1) - v, port->fuzz, w);
j++;
}
for (i = j = 0; i < 3; i++)
if (analog->mask & analog_exts[i])
for (x = 0; x < 2; x++) {
t = analog_hats[j++];
input_set_abs_params(input_dev, t, -1, 1, 0, 0);
}
for (i = j = 0; i < 4; i++)
if (analog->mask & (0x10 << i))
set_bit(analog->buttons[j++], input_dev->keybit);
if (analog->mask & ANALOG_BTNS_CHF)
for (i = 0; i < 2; i++)
set_bit(analog->buttons[j++], input_dev->keybit);
if (analog->mask & ANALOG_HBTN_CHF)
for (i = 0; i < 4; i++)
set_bit(analog->buttons[j++], input_dev->keybit);
for (i = 0; i < 4; i++)
if (analog->mask & (ANALOG_BTN_TL << i))
set_bit(analog_pads[i], input_dev->keybit);
analog_decode(analog, port->axes, port->initial, port->buttons);
error = input_register_device(analog->dev);
if (error) {
input_free_device(analog->dev);
return error;
}
return 0;
}
/*
* analog_init_devices() sets up device-specific values and registers the input devices.
*/
static int analog_init_masks(struct analog_port *port)
{
int i;
struct analog *analog = port->analog;
int max[4];
if (!port->mask)
return -1;
if ((port->mask & 3) != 3 && port->mask != 0xc) {
printk(KERN_WARNING "analog.c: Unknown joystick device found "
"(data=%#x, %s), probably not analog joystick.\n",
port->mask, port->gameport->phys);
return -1;
}
i = analog_options[0]; /* FIXME !!! - need to specify options for different ports */
analog[0].mask = i & 0xfffff;
analog[0].mask &= ~(ANALOG_AXES_STD | ANALOG_HAT_FCS | ANALOG_BTNS_GAMEPAD)
| port->mask | ((port->mask << 8) & ANALOG_HAT_FCS)
| ((port->mask << 10) & ANALOG_BTNS_TLR) | ((port->mask << 12) & ANALOG_BTNS_TLR2);
analog[0].mask &= ~(ANALOG_HAT2_CHF)
| ((analog[0].mask & ANALOG_HBTN_CHF) ? 0 : ANALOG_HAT2_CHF);
analog[0].mask &= ~(ANALOG_THROTTLE | ANALOG_BTN_TR | ANALOG_BTN_TR2)
| ((~analog[0].mask & ANALOG_HAT_FCS) >> 8)
| ((~analog[0].mask & ANALOG_HAT_FCS) << 2)
| ((~analog[0].mask & ANALOG_HAT_FCS) << 4);
analog[0].mask &= ~(ANALOG_THROTTLE | ANALOG_RUDDER)
| (((~analog[0].mask & ANALOG_BTNS_TLR ) >> 10)
& ((~analog[0].mask & ANALOG_BTNS_TLR2) >> 12));
analog[1].mask = ((i >> 20) & 0xff) | ((i >> 12) & 0xf0000);
analog[1].mask &= (analog[0].mask & ANALOG_EXTENSIONS) ? ANALOG_GAMEPAD
: (((ANALOG_BTNS_STD | port->mask) & ~analog[0].mask) | ANALOG_GAMEPAD);
if (port->cooked) {
for (i = 0; i < 4; i++) max[i] = port->axes[i] << 1;
if ((analog[0].mask & 0x7) == 0x7) max[2] = (max[0] + max[1]) >> 1;
if ((analog[0].mask & 0xb) == 0xb) max[3] = (max[0] + max[1]) >> 1;
if ((analog[0].mask & ANALOG_BTN_TL) && !(analog[0].mask & ANALOG_BTN_TL2)) max[2] >>= 1;
if ((analog[0].mask & ANALOG_BTN_TR) && !(analog[0].mask & ANALOG_BTN_TR2)) max[3] >>= 1;
if ((analog[0].mask & ANALOG_HAT_FCS)) max[3] >>= 1;
gameport_calibrate(port->gameport, port->axes, max);
}
for (i = 0; i < 4; i++)
port->initial[i] = port->axes[i];
return -!(analog[0].mask || analog[1].mask);
}
static int analog_init_port(struct gameport *gameport, struct gameport_driver *drv, struct analog_port *port)
{
int i, t, u, v;
port->gameport = gameport;
gameport_set_drvdata(gameport, port);
if (!gameport_open(gameport, drv, GAMEPORT_MODE_RAW)) {
analog_calibrate_timer(port);
gameport_trigger(gameport);
t = gameport_read(gameport);
msleep(ANALOG_MAX_TIME);
port->mask = (gameport_read(gameport) ^ t) & t & 0xf;
port->fuzz = (port->speed * ANALOG_FUZZ_MAGIC) / port->loop / 1000 + ANALOG_FUZZ_BITS;
for (i = 0; i < ANALOG_INIT_RETRIES; i++) {
if (!analog_cooked_read(port))
break;
msleep(ANALOG_MAX_TIME);
}
u = v = 0;
msleep(ANALOG_MAX_TIME);
t = gameport_time(gameport, ANALOG_MAX_TIME * 1000);
gameport_trigger(gameport);
while ((gameport_read(port->gameport) & port->mask) && (u < t))
u++;
udelay(ANALOG_SAITEK_DELAY);
t = gameport_time(gameport, ANALOG_SAITEK_TIME);
gameport_trigger(gameport);
while ((gameport_read(port->gameport) & port->mask) && (v < t))
v++;
if (v < (u >> 1)) { /* FIXME - more than one port */
analog_options[0] |= /* FIXME - more than one port */
ANALOG_SAITEK | ANALOG_BTNS_CHF | ANALOG_HBTN_CHF | ANALOG_HAT1_CHF;
return 0;
}
gameport_close(gameport);
}
if (!gameport_open(gameport, drv, GAMEPORT_MODE_COOKED)) {
for (i = 0; i < ANALOG_INIT_RETRIES; i++)
if (!gameport_cooked_read(gameport, port->axes, &port->buttons))
break;
for (i = 0; i < 4; i++)
if (port->axes[i] != -1)
port->mask |= 1 << i;
port->fuzz = gameport->fuzz;
port->cooked = 1;
return 0;
}
return gameport_open(gameport, drv, GAMEPORT_MODE_RAW);
}
static int analog_connect(struct gameport *gameport, struct gameport_driver *drv)
{
struct analog_port *port;
int i;
int err;
if (!(port = kzalloc(sizeof(struct analog_port), GFP_KERNEL)))
return - ENOMEM;
err = analog_init_port(gameport, drv, port);
if (err)
goto fail1;
err = analog_init_masks(port);
if (err)
goto fail2;
gameport_set_poll_handler(gameport, analog_poll);
gameport_set_poll_interval(gameport, 10);
for (i = 0; i < 2; i++)
if (port->analog[i].mask) {
err = analog_init_device(port, port->analog + i, i);
if (err)
goto fail3;
}
return 0;
fail3: while (--i >= 0)
if (port->analog[i].mask)
input_unregister_device(port->analog[i].dev);
fail2: gameport_close(gameport);
fail1: gameport_set_drvdata(gameport, NULL);
kfree(port);
return err;
}
static void analog_disconnect(struct gameport *gameport)
{
struct analog_port *port = gameport_get_drvdata(gameport);
int i;
for (i = 0; i < 2; i++)
if (port->analog[i].mask)
input_unregister_device(port->analog[i].dev);
gameport_close(gameport);
gameport_set_drvdata(gameport, NULL);
printk(KERN_INFO "analog.c: %d out of %d reads (%d%%) on %s failed\n",
port->bads, port->reads, port->reads ? (port->bads * 100 / port->reads) : 0,
port->gameport->phys);
kfree(port);
}
struct analog_types {
char *name;
int value;
};
static struct analog_types analog_types[] = {
{ "none", 0x00000000 },
{ "auto", 0x000000ff },
{ "2btn", 0x0000003f },
{ "y-joy", 0x0cc00033 },
{ "y-pad", 0x8cc80033 },
{ "fcs", 0x000008f7 },
{ "chf", 0x000002ff },
{ "fullchf", 0x000007ff },
{ "gamepad", 0x000830f3 },
{ "gamepad8", 0x0008f0f3 },
{ NULL, 0 }
};
static void analog_parse_options(void)
{
int i, j;
char *end;
for (i = 0; i < js_nargs; i++) {
for (j = 0; analog_types[j].name; j++)
if (!strcmp(analog_types[j].name, js[i])) {
analog_options[i] = analog_types[j].value;
break;
}
if (analog_types[j].name) continue;
analog_options[i] = simple_strtoul(js[i], &end, 0);
if (end != js[i]) continue;
analog_options[i] = 0xff;
if (!strlen(js[i])) continue;
printk(KERN_WARNING "analog.c: Bad config for port %d - \"%s\"\n", i, js[i]);
}
for (; i < ANALOG_PORTS; i++)
analog_options[i] = 0xff;
}
/*
* The gameport device structure.
*/
static struct gameport_driver analog_drv = {
.driver = {
.name = "analog",
},
.description = DRIVER_DESC,
.connect = analog_connect,
.disconnect = analog_disconnect,
};
static int __init analog_init(void)
{
analog_parse_options();
return gameport_register_driver(&analog_drv);
}
static void __exit analog_exit(void)
{
gameport_unregister_driver(&analog_drv);
}
module_init(analog_init);
module_exit(analog_exit);
| gpl-2.0 |
pengus77/kowalski | arch/microblaze/lib/memset.c | 7667 | 2427 | /*
* Copyright (C) 2008-2009 Michal Simek <monstr@monstr.eu>
* Copyright (C) 2008-2009 PetaLogix
* Copyright (C) 2007 John Williams
*
* Reasonably optimised generic C-code for memset on Microblaze
* This is generic C code to do efficient, alignment-aware memcpy.
*
* It is based on demo code originally Copyright 2001 by Intel Corp, taken from
* http://www.embedded.com/showArticle.jhtml?articleID=19205567
*
* Attempts were made, unsuccessfully, to contact the original
* author of this code (Michael Morrow, Intel). Below is the original
* copyright notice.
*
* This software has been developed by Intel Corporation.
* Intel specifically disclaims all warranties, express or
* implied, and all liability, including consequential and
* other indirect damages, for the use of this program, including
* liability for infringement of any proprietary rights,
* and including the warranties of merchantability and fitness
* for a particular purpose. Intel does not assume any
* responsibility for and errors which may appear in this program
* not any responsibility to update it.
*/
#include <linux/types.h>
#include <linux/stddef.h>
#include <linux/compiler.h>
#include <linux/module.h>
#include <linux/string.h>
#ifdef __HAVE_ARCH_MEMSET
#ifndef CONFIG_OPT_LIB_FUNCTION
void *memset(void *v_src, int c, __kernel_size_t n)
{
char *src = v_src;
/* Truncate c to 8 bits */
c = (c & 0xFF);
/* Simple, byte oriented memset or the rest of count. */
while (n--)
*src++ = c;
return v_src;
}
#else /* CONFIG_OPT_LIB_FUNCTION */
void *memset(void *v_src, int c, __kernel_size_t n)
{
char *src = v_src;
uint32_t *i_src;
uint32_t w32 = 0;
/* Truncate c to 8 bits */
c = (c & 0xFF);
if (unlikely(c)) {
/* Make a repeating word out of it */
w32 = c;
w32 |= w32 << 8;
w32 |= w32 << 16;
}
if (likely(n >= 4)) {
/* Align the destination to a word boundary */
/* This is done in an endian independent manner */
switch ((unsigned) src & 3) {
case 1:
*src++ = c;
--n;
case 2:
*src++ = c;
--n;
case 3:
*src++ = c;
--n;
}
i_src = (void *)src;
/* Do as many full-word copies as we can */
for (; n >= 4; n -= 4)
*i_src++ = w32;
src = (void *)i_src;
}
/* Simple, byte oriented memset or the rest of count. */
while (n--)
*src++ = c;
return v_src;
}
#endif /* CONFIG_OPT_LIB_FUNCTION */
EXPORT_SYMBOL(memset);
#endif /* __HAVE_ARCH_MEMSET */
| gpl-2.0 |
devil1210/EvilKernel | drivers/infiniband/hw/amso1100/c2_rnic.c | 8179 | 16748 | /*
* Copyright (c) 2005 Ammasso, Inc. All rights reserved.
* Copyright (c) 2005 Open Grid Computing, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/pci.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/delay.h>
#include <linux/ethtool.h>
#include <linux/mii.h>
#include <linux/if_vlan.h>
#include <linux/crc32.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/init.h>
#include <linux/dma-mapping.h>
#include <linux/mm.h>
#include <linux/inet.h>
#include <linux/vmalloc.h>
#include <linux/slab.h>
#include <linux/route.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/byteorder.h>
#include <rdma/ib_smi.h>
#include "c2.h"
#include "c2_vq.h"
/* Device capabilities */
#define C2_MIN_PAGESIZE 1024
#define C2_MAX_MRS 32768
#define C2_MAX_QPS 16000
#define C2_MAX_WQE_SZ 256
#define C2_MAX_QP_WR ((128*1024)/C2_MAX_WQE_SZ)
#define C2_MAX_SGES 4
#define C2_MAX_SGE_RD 1
#define C2_MAX_CQS 32768
#define C2_MAX_CQES 4096
#define C2_MAX_PDS 16384
/*
* Send the adapter INIT message to the amso1100
*/
static int c2_adapter_init(struct c2_dev *c2dev)
{
struct c2wr_init_req wr;
int err;
memset(&wr, 0, sizeof(wr));
c2_wr_set_id(&wr, CCWR_INIT);
wr.hdr.context = 0;
wr.hint_count = cpu_to_be64(c2dev->hint_count_dma);
wr.q0_host_shared = cpu_to_be64(c2dev->req_vq.shared_dma);
wr.q1_host_shared = cpu_to_be64(c2dev->rep_vq.shared_dma);
wr.q1_host_msg_pool = cpu_to_be64(c2dev->rep_vq.host_dma);
wr.q2_host_shared = cpu_to_be64(c2dev->aeq.shared_dma);
wr.q2_host_msg_pool = cpu_to_be64(c2dev->aeq.host_dma);
/* Post the init message */
err = vq_send_wr(c2dev, (union c2wr *) & wr);
return err;
}
/*
* Send the adapter TERM message to the amso1100
*/
static void c2_adapter_term(struct c2_dev *c2dev)
{
struct c2wr_init_req wr;
memset(&wr, 0, sizeof(wr));
c2_wr_set_id(&wr, CCWR_TERM);
wr.hdr.context = 0;
/* Post the init message */
vq_send_wr(c2dev, (union c2wr *) & wr);
c2dev->init = 0;
return;
}
/*
* Query the adapter
*/
static int c2_rnic_query(struct c2_dev *c2dev, struct ib_device_attr *props)
{
struct c2_vq_req *vq_req;
struct c2wr_rnic_query_req wr;
struct c2wr_rnic_query_rep *reply;
int err;
vq_req = vq_req_alloc(c2dev);
if (!vq_req)
return -ENOMEM;
c2_wr_set_id(&wr, CCWR_RNIC_QUERY);
wr.hdr.context = (unsigned long) vq_req;
wr.rnic_handle = c2dev->adapter_handle;
vq_req_get(c2dev, vq_req);
err = vq_send_wr(c2dev, (union c2wr *) &wr);
if (err) {
vq_req_put(c2dev, vq_req);
goto bail1;
}
err = vq_wait_for_reply(c2dev, vq_req);
if (err)
goto bail1;
reply =
(struct c2wr_rnic_query_rep *) (unsigned long) (vq_req->reply_msg);
if (!reply)
err = -ENOMEM;
else
err = c2_errno(reply);
if (err)
goto bail2;
props->fw_ver =
((u64)be32_to_cpu(reply->fw_ver_major) << 32) |
((be32_to_cpu(reply->fw_ver_minor) & 0xFFFF) << 16) |
(be32_to_cpu(reply->fw_ver_patch) & 0xFFFF);
memcpy(&props->sys_image_guid, c2dev->netdev->dev_addr, 6);
props->max_mr_size = 0xFFFFFFFF;
props->page_size_cap = ~(C2_MIN_PAGESIZE-1);
props->vendor_id = be32_to_cpu(reply->vendor_id);
props->vendor_part_id = be32_to_cpu(reply->part_number);
props->hw_ver = be32_to_cpu(reply->hw_version);
props->max_qp = be32_to_cpu(reply->max_qps);
props->max_qp_wr = be32_to_cpu(reply->max_qp_depth);
props->device_cap_flags = c2dev->device_cap_flags;
props->max_sge = C2_MAX_SGES;
props->max_sge_rd = C2_MAX_SGE_RD;
props->max_cq = be32_to_cpu(reply->max_cqs);
props->max_cqe = be32_to_cpu(reply->max_cq_depth);
props->max_mr = be32_to_cpu(reply->max_mrs);
props->max_pd = be32_to_cpu(reply->max_pds);
props->max_qp_rd_atom = be32_to_cpu(reply->max_qp_ird);
props->max_ee_rd_atom = 0;
props->max_res_rd_atom = be32_to_cpu(reply->max_global_ird);
props->max_qp_init_rd_atom = be32_to_cpu(reply->max_qp_ord);
props->max_ee_init_rd_atom = 0;
props->atomic_cap = IB_ATOMIC_NONE;
props->max_ee = 0;
props->max_rdd = 0;
props->max_mw = be32_to_cpu(reply->max_mws);
props->max_raw_ipv6_qp = 0;
props->max_raw_ethy_qp = 0;
props->max_mcast_grp = 0;
props->max_mcast_qp_attach = 0;
props->max_total_mcast_qp_attach = 0;
props->max_ah = 0;
props->max_fmr = 0;
props->max_map_per_fmr = 0;
props->max_srq = 0;
props->max_srq_wr = 0;
props->max_srq_sge = 0;
props->max_pkeys = 0;
props->local_ca_ack_delay = 0;
bail2:
vq_repbuf_free(c2dev, reply);
bail1:
vq_req_free(c2dev, vq_req);
return err;
}
/*
* Add an IP address to the RNIC interface
*/
int c2_add_addr(struct c2_dev *c2dev, __be32 inaddr, __be32 inmask)
{
struct c2_vq_req *vq_req;
struct c2wr_rnic_setconfig_req *wr;
struct c2wr_rnic_setconfig_rep *reply;
struct c2_netaddr netaddr;
int err, len;
vq_req = vq_req_alloc(c2dev);
if (!vq_req)
return -ENOMEM;
len = sizeof(struct c2_netaddr);
wr = kmalloc(c2dev->req_vq.msg_size, GFP_KERNEL);
if (!wr) {
err = -ENOMEM;
goto bail0;
}
c2_wr_set_id(wr, CCWR_RNIC_SETCONFIG);
wr->hdr.context = (unsigned long) vq_req;
wr->rnic_handle = c2dev->adapter_handle;
wr->option = cpu_to_be32(C2_CFG_ADD_ADDR);
netaddr.ip_addr = inaddr;
netaddr.netmask = inmask;
netaddr.mtu = 0;
memcpy(wr->data, &netaddr, len);
vq_req_get(c2dev, vq_req);
err = vq_send_wr(c2dev, (union c2wr *) wr);
if (err) {
vq_req_put(c2dev, vq_req);
goto bail1;
}
err = vq_wait_for_reply(c2dev, vq_req);
if (err)
goto bail1;
reply =
(struct c2wr_rnic_setconfig_rep *) (unsigned long) (vq_req->reply_msg);
if (!reply) {
err = -ENOMEM;
goto bail1;
}
err = c2_errno(reply);
vq_repbuf_free(c2dev, reply);
bail1:
kfree(wr);
bail0:
vq_req_free(c2dev, vq_req);
return err;
}
/*
* Delete an IP address from the RNIC interface
*/
int c2_del_addr(struct c2_dev *c2dev, __be32 inaddr, __be32 inmask)
{
struct c2_vq_req *vq_req;
struct c2wr_rnic_setconfig_req *wr;
struct c2wr_rnic_setconfig_rep *reply;
struct c2_netaddr netaddr;
int err, len;
vq_req = vq_req_alloc(c2dev);
if (!vq_req)
return -ENOMEM;
len = sizeof(struct c2_netaddr);
wr = kmalloc(c2dev->req_vq.msg_size, GFP_KERNEL);
if (!wr) {
err = -ENOMEM;
goto bail0;
}
c2_wr_set_id(wr, CCWR_RNIC_SETCONFIG);
wr->hdr.context = (unsigned long) vq_req;
wr->rnic_handle = c2dev->adapter_handle;
wr->option = cpu_to_be32(C2_CFG_DEL_ADDR);
netaddr.ip_addr = inaddr;
netaddr.netmask = inmask;
netaddr.mtu = 0;
memcpy(wr->data, &netaddr, len);
vq_req_get(c2dev, vq_req);
err = vq_send_wr(c2dev, (union c2wr *) wr);
if (err) {
vq_req_put(c2dev, vq_req);
goto bail1;
}
err = vq_wait_for_reply(c2dev, vq_req);
if (err)
goto bail1;
reply =
(struct c2wr_rnic_setconfig_rep *) (unsigned long) (vq_req->reply_msg);
if (!reply) {
err = -ENOMEM;
goto bail1;
}
err = c2_errno(reply);
vq_repbuf_free(c2dev, reply);
bail1:
kfree(wr);
bail0:
vq_req_free(c2dev, vq_req);
return err;
}
/*
* Open a single RNIC instance to use with all
* low level openib calls
*/
static int c2_rnic_open(struct c2_dev *c2dev)
{
struct c2_vq_req *vq_req;
union c2wr wr;
struct c2wr_rnic_open_rep *reply;
int err;
vq_req = vq_req_alloc(c2dev);
if (vq_req == NULL) {
return -ENOMEM;
}
memset(&wr, 0, sizeof(wr));
c2_wr_set_id(&wr, CCWR_RNIC_OPEN);
wr.rnic_open.req.hdr.context = (unsigned long) (vq_req);
wr.rnic_open.req.flags = cpu_to_be16(RNIC_PRIV_MODE);
wr.rnic_open.req.port_num = cpu_to_be16(0);
wr.rnic_open.req.user_context = (unsigned long) c2dev;
vq_req_get(c2dev, vq_req);
err = vq_send_wr(c2dev, &wr);
if (err) {
vq_req_put(c2dev, vq_req);
goto bail0;
}
err = vq_wait_for_reply(c2dev, vq_req);
if (err) {
goto bail0;
}
reply = (struct c2wr_rnic_open_rep *) (unsigned long) (vq_req->reply_msg);
if (!reply) {
err = -ENOMEM;
goto bail0;
}
if ((err = c2_errno(reply)) != 0) {
goto bail1;
}
c2dev->adapter_handle = reply->rnic_handle;
bail1:
vq_repbuf_free(c2dev, reply);
bail0:
vq_req_free(c2dev, vq_req);
return err;
}
/*
* Close the RNIC instance
*/
static int c2_rnic_close(struct c2_dev *c2dev)
{
struct c2_vq_req *vq_req;
union c2wr wr;
struct c2wr_rnic_close_rep *reply;
int err;
vq_req = vq_req_alloc(c2dev);
if (vq_req == NULL) {
return -ENOMEM;
}
memset(&wr, 0, sizeof(wr));
c2_wr_set_id(&wr, CCWR_RNIC_CLOSE);
wr.rnic_close.req.hdr.context = (unsigned long) vq_req;
wr.rnic_close.req.rnic_handle = c2dev->adapter_handle;
vq_req_get(c2dev, vq_req);
err = vq_send_wr(c2dev, &wr);
if (err) {
vq_req_put(c2dev, vq_req);
goto bail0;
}
err = vq_wait_for_reply(c2dev, vq_req);
if (err) {
goto bail0;
}
reply = (struct c2wr_rnic_close_rep *) (unsigned long) (vq_req->reply_msg);
if (!reply) {
err = -ENOMEM;
goto bail0;
}
if ((err = c2_errno(reply)) != 0) {
goto bail1;
}
c2dev->adapter_handle = 0;
bail1:
vq_repbuf_free(c2dev, reply);
bail0:
vq_req_free(c2dev, vq_req);
return err;
}
/*
* Called by c2_probe to initialize the RNIC. This principally
* involves initalizing the various limits and resouce pools that
* comprise the RNIC instance.
*/
int __devinit c2_rnic_init(struct c2_dev *c2dev)
{
int err;
u32 qsize, msgsize;
void *q1_pages;
void *q2_pages;
void __iomem *mmio_regs;
/* Device capabilities */
c2dev->device_cap_flags =
(IB_DEVICE_RESIZE_MAX_WR |
IB_DEVICE_CURR_QP_STATE_MOD |
IB_DEVICE_SYS_IMAGE_GUID |
IB_DEVICE_LOCAL_DMA_LKEY |
IB_DEVICE_MEM_WINDOW);
/* Allocate the qptr_array */
c2dev->qptr_array = vzalloc(C2_MAX_CQS * sizeof(void *));
if (!c2dev->qptr_array) {
return -ENOMEM;
}
/* Initialize the qptr_array */
c2dev->qptr_array[0] = (void *) &c2dev->req_vq;
c2dev->qptr_array[1] = (void *) &c2dev->rep_vq;
c2dev->qptr_array[2] = (void *) &c2dev->aeq;
/* Initialize data structures */
init_waitqueue_head(&c2dev->req_vq_wo);
spin_lock_init(&c2dev->vqlock);
spin_lock_init(&c2dev->lock);
/* Allocate MQ shared pointer pool for kernel clients. User
* mode client pools are hung off the user context
*/
err = c2_init_mqsp_pool(c2dev, GFP_KERNEL, &c2dev->kern_mqsp_pool);
if (err) {
goto bail0;
}
/* Allocate shared pointers for Q0, Q1, and Q2 from
* the shared pointer pool.
*/
c2dev->hint_count = c2_alloc_mqsp(c2dev, c2dev->kern_mqsp_pool,
&c2dev->hint_count_dma,
GFP_KERNEL);
c2dev->req_vq.shared = c2_alloc_mqsp(c2dev, c2dev->kern_mqsp_pool,
&c2dev->req_vq.shared_dma,
GFP_KERNEL);
c2dev->rep_vq.shared = c2_alloc_mqsp(c2dev, c2dev->kern_mqsp_pool,
&c2dev->rep_vq.shared_dma,
GFP_KERNEL);
c2dev->aeq.shared = c2_alloc_mqsp(c2dev, c2dev->kern_mqsp_pool,
&c2dev->aeq.shared_dma, GFP_KERNEL);
if (!c2dev->hint_count || !c2dev->req_vq.shared ||
!c2dev->rep_vq.shared || !c2dev->aeq.shared) {
err = -ENOMEM;
goto bail1;
}
mmio_regs = c2dev->kva;
/* Initialize the Verbs Request Queue */
c2_mq_req_init(&c2dev->req_vq, 0,
be32_to_cpu((__force __be32) readl(mmio_regs + C2_REGS_Q0_QSIZE)),
be32_to_cpu((__force __be32) readl(mmio_regs + C2_REGS_Q0_MSGSIZE)),
mmio_regs +
be32_to_cpu((__force __be32) readl(mmio_regs + C2_REGS_Q0_POOLSTART)),
mmio_regs +
be32_to_cpu((__force __be32) readl(mmio_regs + C2_REGS_Q0_SHARED)),
C2_MQ_ADAPTER_TARGET);
/* Initialize the Verbs Reply Queue */
qsize = be32_to_cpu((__force __be32) readl(mmio_regs + C2_REGS_Q1_QSIZE));
msgsize = be32_to_cpu((__force __be32) readl(mmio_regs + C2_REGS_Q1_MSGSIZE));
q1_pages = dma_alloc_coherent(&c2dev->pcidev->dev, qsize * msgsize,
&c2dev->rep_vq.host_dma, GFP_KERNEL);
if (!q1_pages) {
err = -ENOMEM;
goto bail1;
}
dma_unmap_addr_set(&c2dev->rep_vq, mapping, c2dev->rep_vq.host_dma);
pr_debug("%s rep_vq va %p dma %llx\n", __func__, q1_pages,
(unsigned long long) c2dev->rep_vq.host_dma);
c2_mq_rep_init(&c2dev->rep_vq,
1,
qsize,
msgsize,
q1_pages,
mmio_regs +
be32_to_cpu((__force __be32) readl(mmio_regs + C2_REGS_Q1_SHARED)),
C2_MQ_HOST_TARGET);
/* Initialize the Asynchronus Event Queue */
qsize = be32_to_cpu((__force __be32) readl(mmio_regs + C2_REGS_Q2_QSIZE));
msgsize = be32_to_cpu((__force __be32) readl(mmio_regs + C2_REGS_Q2_MSGSIZE));
q2_pages = dma_alloc_coherent(&c2dev->pcidev->dev, qsize * msgsize,
&c2dev->aeq.host_dma, GFP_KERNEL);
if (!q2_pages) {
err = -ENOMEM;
goto bail2;
}
dma_unmap_addr_set(&c2dev->aeq, mapping, c2dev->aeq.host_dma);
pr_debug("%s aeq va %p dma %llx\n", __func__, q2_pages,
(unsigned long long) c2dev->aeq.host_dma);
c2_mq_rep_init(&c2dev->aeq,
2,
qsize,
msgsize,
q2_pages,
mmio_regs +
be32_to_cpu((__force __be32) readl(mmio_regs + C2_REGS_Q2_SHARED)),
C2_MQ_HOST_TARGET);
/* Initialize the verbs request allocator */
err = vq_init(c2dev);
if (err)
goto bail3;
/* Enable interrupts on the adapter */
writel(0, c2dev->regs + C2_IDIS);
/* create the WR init message */
err = c2_adapter_init(c2dev);
if (err)
goto bail4;
c2dev->init++;
/* open an adapter instance */
err = c2_rnic_open(c2dev);
if (err)
goto bail4;
/* Initialize cached the adapter limits */
if (c2_rnic_query(c2dev, &c2dev->props))
goto bail5;
/* Initialize the PD pool */
err = c2_init_pd_table(c2dev);
if (err)
goto bail5;
/* Initialize the QP pool */
c2_init_qp_table(c2dev);
return 0;
bail5:
c2_rnic_close(c2dev);
bail4:
vq_term(c2dev);
bail3:
dma_free_coherent(&c2dev->pcidev->dev,
c2dev->aeq.q_size * c2dev->aeq.msg_size,
q2_pages, dma_unmap_addr(&c2dev->aeq, mapping));
bail2:
dma_free_coherent(&c2dev->pcidev->dev,
c2dev->rep_vq.q_size * c2dev->rep_vq.msg_size,
q1_pages, dma_unmap_addr(&c2dev->rep_vq, mapping));
bail1:
c2_free_mqsp_pool(c2dev, c2dev->kern_mqsp_pool);
bail0:
vfree(c2dev->qptr_array);
return err;
}
/*
* Called by c2_remove to cleanup the RNIC resources.
*/
void __devexit c2_rnic_term(struct c2_dev *c2dev)
{
/* Close the open adapter instance */
c2_rnic_close(c2dev);
/* Send the TERM message to the adapter */
c2_adapter_term(c2dev);
/* Disable interrupts on the adapter */
writel(1, c2dev->regs + C2_IDIS);
/* Free the QP pool */
c2_cleanup_qp_table(c2dev);
/* Free the PD pool */
c2_cleanup_pd_table(c2dev);
/* Free the verbs request allocator */
vq_term(c2dev);
/* Free the asynchronus event queue */
dma_free_coherent(&c2dev->pcidev->dev,
c2dev->aeq.q_size * c2dev->aeq.msg_size,
c2dev->aeq.msg_pool.host,
dma_unmap_addr(&c2dev->aeq, mapping));
/* Free the verbs reply queue */
dma_free_coherent(&c2dev->pcidev->dev,
c2dev->rep_vq.q_size * c2dev->rep_vq.msg_size,
c2dev->rep_vq.msg_pool.host,
dma_unmap_addr(&c2dev->rep_vq, mapping));
/* Free the MQ shared pointer pool */
c2_free_mqsp_pool(c2dev, c2dev->kern_mqsp_pool);
/* Free the qptr_array */
vfree(c2dev->qptr_array);
return;
}
| gpl-2.0 |
actzendaria/xgt | drivers/gpio/gpio-twl4030.c | 244 | 15393 | /*
* Access to GPIOs on TWL4030/TPS659x0 chips
*
* Copyright (C) 2006-2007 Texas Instruments, Inc.
* Copyright (C) 2006 MontaVista Software, Inc.
*
* Code re-arranged and cleaned up by:
* Syed Mohammed Khasim <x0khasim@ti.com>
*
* Initial Code:
* Andy Lowe / Nishanth Menon
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/kthread.h>
#include <linux/irq.h>
#include <linux/gpio.h>
#include <linux/platform_device.h>
#include <linux/of.h>
#include <linux/irqdomain.h>
#include <linux/i2c/twl.h>
/*
* The GPIO "subchip" supports 18 GPIOs which can be configured as
* inputs or outputs, with pullups or pulldowns on each pin. Each
* GPIO can trigger interrupts on either or both edges.
*
* GPIO interrupts can be fed to either of two IRQ lines; this is
* intended to support multiple hosts.
*
* There are also two LED pins used sometimes as output-only GPIOs.
*/
/* genirq interfaces are not available to modules */
#ifdef MODULE
#define is_module() true
#else
#define is_module() false
#endif
/* GPIO_CTRL Fields */
#define MASK_GPIO_CTRL_GPIO0CD1 BIT(0)
#define MASK_GPIO_CTRL_GPIO1CD2 BIT(1)
#define MASK_GPIO_CTRL_GPIO_ON BIT(2)
/* Mask for GPIO registers when aggregated into a 32-bit integer */
#define GPIO_32_MASK 0x0003ffff
struct gpio_twl4030_priv {
struct gpio_chip gpio_chip;
struct mutex mutex;
int irq_base;
/* Bitfields for state caching */
unsigned int usage_count;
unsigned int direction;
unsigned int out_state;
};
/*----------------------------------------------------------------------*/
static inline struct gpio_twl4030_priv *to_gpio_twl4030(struct gpio_chip *chip)
{
return container_of(chip, struct gpio_twl4030_priv, gpio_chip);
}
/*
* To configure TWL4030 GPIO module registers
*/
static inline int gpio_twl4030_write(u8 address, u8 data)
{
return twl_i2c_write_u8(TWL4030_MODULE_GPIO, data, address);
}
/*----------------------------------------------------------------------*/
/*
* LED register offsets from TWL_MODULE_LED base
* PWMs A and B are dedicated to LEDs A and B, respectively.
*/
#define TWL4030_LED_LEDEN_REG 0x00
#define TWL4030_PWMAON_REG 0x01
#define TWL4030_PWMAOFF_REG 0x02
#define TWL4030_PWMBON_REG 0x03
#define TWL4030_PWMBOFF_REG 0x04
/* LEDEN bits */
#define LEDEN_LEDAON BIT(0)
#define LEDEN_LEDBON BIT(1)
#define LEDEN_LEDAEXT BIT(2)
#define LEDEN_LEDBEXT BIT(3)
#define LEDEN_LEDAPWM BIT(4)
#define LEDEN_LEDBPWM BIT(5)
#define LEDEN_PWM_LENGTHA BIT(6)
#define LEDEN_PWM_LENGTHB BIT(7)
#define PWMxON_LENGTH BIT(7)
/*----------------------------------------------------------------------*/
/*
* To read a TWL4030 GPIO module register
*/
static inline int gpio_twl4030_read(u8 address)
{
u8 data;
int ret = 0;
ret = twl_i2c_read_u8(TWL4030_MODULE_GPIO, &data, address);
return (ret < 0) ? ret : data;
}
/*----------------------------------------------------------------------*/
static u8 cached_leden;
/* The LED lines are open drain outputs ... a FET pulls to GND, so an
* external pullup is needed. We could also expose the integrated PWM
* as a LED brightness control; we initialize it as "always on".
*/
static void twl4030_led_set_value(int led, int value)
{
u8 mask = LEDEN_LEDAON | LEDEN_LEDAPWM;
int status;
if (led)
mask <<= 1;
if (value)
cached_leden &= ~mask;
else
cached_leden |= mask;
status = twl_i2c_write_u8(TWL4030_MODULE_LED, cached_leden,
TWL4030_LED_LEDEN_REG);
}
static int twl4030_set_gpio_direction(int gpio, int is_input)
{
u8 d_bnk = gpio >> 3;
u8 d_msk = BIT(gpio & 0x7);
u8 reg = 0;
u8 base = REG_GPIODATADIR1 + d_bnk;
int ret = 0;
ret = gpio_twl4030_read(base);
if (ret >= 0) {
if (is_input)
reg = ret & ~d_msk;
else
reg = ret | d_msk;
ret = gpio_twl4030_write(base, reg);
}
return ret;
}
static int twl4030_set_gpio_dataout(int gpio, int enable)
{
u8 d_bnk = gpio >> 3;
u8 d_msk = BIT(gpio & 0x7);
u8 base = 0;
if (enable)
base = REG_SETGPIODATAOUT1 + d_bnk;
else
base = REG_CLEARGPIODATAOUT1 + d_bnk;
return gpio_twl4030_write(base, d_msk);
}
static int twl4030_get_gpio_datain(int gpio)
{
u8 d_bnk = gpio >> 3;
u8 d_off = gpio & 0x7;
u8 base = 0;
int ret = 0;
base = REG_GPIODATAIN1 + d_bnk;
ret = gpio_twl4030_read(base);
if (ret > 0)
ret = (ret >> d_off) & 0x1;
return ret;
}
/*----------------------------------------------------------------------*/
static int twl_request(struct gpio_chip *chip, unsigned offset)
{
struct gpio_twl4030_priv *priv = to_gpio_twl4030(chip);
int status = 0;
mutex_lock(&priv->mutex);
/* Support the two LED outputs as output-only GPIOs. */
if (offset >= TWL4030_GPIO_MAX) {
u8 ledclr_mask = LEDEN_LEDAON | LEDEN_LEDAEXT
| LEDEN_LEDAPWM | LEDEN_PWM_LENGTHA;
u8 reg = TWL4030_PWMAON_REG;
offset -= TWL4030_GPIO_MAX;
if (offset) {
ledclr_mask <<= 1;
reg = TWL4030_PWMBON_REG;
}
/* initialize PWM to always-drive */
/* Configure PWM OFF register first */
status = twl_i2c_write_u8(TWL4030_MODULE_LED, 0x7f, reg + 1);
if (status < 0)
goto done;
/* Followed by PWM ON register */
status = twl_i2c_write_u8(TWL4030_MODULE_LED, 0x7f, reg);
if (status < 0)
goto done;
/* init LED to not-driven (high) */
status = twl_i2c_read_u8(TWL4030_MODULE_LED, &cached_leden,
TWL4030_LED_LEDEN_REG);
if (status < 0)
goto done;
cached_leden &= ~ledclr_mask;
status = twl_i2c_write_u8(TWL4030_MODULE_LED, cached_leden,
TWL4030_LED_LEDEN_REG);
if (status < 0)
goto done;
status = 0;
goto done;
}
/* on first use, turn GPIO module "on" */
if (!priv->usage_count) {
struct twl4030_gpio_platform_data *pdata;
u8 value = MASK_GPIO_CTRL_GPIO_ON;
/* optionally have the first two GPIOs switch vMMC1
* and vMMC2 power supplies based on card presence.
*/
pdata = dev_get_platdata(chip->dev);
if (pdata)
value |= pdata->mmc_cd & 0x03;
status = gpio_twl4030_write(REG_GPIO_CTRL, value);
}
done:
if (!status)
priv->usage_count |= BIT(offset);
mutex_unlock(&priv->mutex);
return status;
}
static void twl_free(struct gpio_chip *chip, unsigned offset)
{
struct gpio_twl4030_priv *priv = to_gpio_twl4030(chip);
mutex_lock(&priv->mutex);
if (offset >= TWL4030_GPIO_MAX) {
twl4030_led_set_value(offset - TWL4030_GPIO_MAX, 1);
goto out;
}
priv->usage_count &= ~BIT(offset);
/* on last use, switch off GPIO module */
if (!priv->usage_count)
gpio_twl4030_write(REG_GPIO_CTRL, 0x0);
out:
mutex_unlock(&priv->mutex);
}
static int twl_direction_in(struct gpio_chip *chip, unsigned offset)
{
struct gpio_twl4030_priv *priv = to_gpio_twl4030(chip);
int ret;
mutex_lock(&priv->mutex);
if (offset < TWL4030_GPIO_MAX)
ret = twl4030_set_gpio_direction(offset, 1);
else
ret = -EINVAL; /* LED outputs can't be set as input */
if (!ret)
priv->direction &= ~BIT(offset);
mutex_unlock(&priv->mutex);
return ret;
}
static int twl_get(struct gpio_chip *chip, unsigned offset)
{
struct gpio_twl4030_priv *priv = to_gpio_twl4030(chip);
int ret;
int status = 0;
mutex_lock(&priv->mutex);
if (!(priv->usage_count & BIT(offset))) {
ret = -EPERM;
goto out;
}
if (priv->direction & BIT(offset))
status = priv->out_state & BIT(offset);
else
status = twl4030_get_gpio_datain(offset);
ret = (status <= 0) ? 0 : 1;
out:
mutex_unlock(&priv->mutex);
return ret;
}
static void twl_set(struct gpio_chip *chip, unsigned offset, int value)
{
struct gpio_twl4030_priv *priv = to_gpio_twl4030(chip);
mutex_lock(&priv->mutex);
if (offset < TWL4030_GPIO_MAX)
twl4030_set_gpio_dataout(offset, value);
else
twl4030_led_set_value(offset - TWL4030_GPIO_MAX, value);
if (value)
priv->out_state |= BIT(offset);
else
priv->out_state &= ~BIT(offset);
mutex_unlock(&priv->mutex);
}
static int twl_direction_out(struct gpio_chip *chip, unsigned offset, int value)
{
struct gpio_twl4030_priv *priv = to_gpio_twl4030(chip);
int ret = 0;
mutex_lock(&priv->mutex);
if (offset < TWL4030_GPIO_MAX) {
ret = twl4030_set_gpio_direction(offset, 0);
if (ret) {
mutex_unlock(&priv->mutex);
return ret;
}
}
/*
* LED gpios i.e. offset >= TWL4030_GPIO_MAX are always output
*/
priv->direction |= BIT(offset);
mutex_unlock(&priv->mutex);
twl_set(chip, offset, value);
return ret;
}
static int twl_to_irq(struct gpio_chip *chip, unsigned offset)
{
struct gpio_twl4030_priv *priv = to_gpio_twl4030(chip);
return (priv->irq_base && (offset < TWL4030_GPIO_MAX))
? (priv->irq_base + offset)
: -EINVAL;
}
static struct gpio_chip template_chip = {
.label = "twl4030",
.owner = THIS_MODULE,
.request = twl_request,
.free = twl_free,
.direction_input = twl_direction_in,
.get = twl_get,
.direction_output = twl_direction_out,
.set = twl_set,
.to_irq = twl_to_irq,
.can_sleep = true,
};
/*----------------------------------------------------------------------*/
static int gpio_twl4030_pulls(u32 ups, u32 downs)
{
u8 message[5];
unsigned i, gpio_bit;
/* For most pins, a pulldown was enabled by default.
* We should have data that's specific to this board.
*/
for (gpio_bit = 1, i = 0; i < 5; i++) {
u8 bit_mask;
unsigned j;
for (bit_mask = 0, j = 0; j < 8; j += 2, gpio_bit <<= 1) {
if (ups & gpio_bit)
bit_mask |= 1 << (j + 1);
else if (downs & gpio_bit)
bit_mask |= 1 << (j + 0);
}
message[i] = bit_mask;
}
return twl_i2c_write(TWL4030_MODULE_GPIO, message,
REG_GPIOPUPDCTR1, 5);
}
static int gpio_twl4030_debounce(u32 debounce, u8 mmc_cd)
{
u8 message[3];
/* 30 msec of debouncing is always used for MMC card detect,
* and is optional for everything else.
*/
message[0] = (debounce & 0xff) | (mmc_cd & 0x03);
debounce >>= 8;
message[1] = (debounce & 0xff);
debounce >>= 8;
message[2] = (debounce & 0x03);
return twl_i2c_write(TWL4030_MODULE_GPIO, message,
REG_GPIO_DEBEN1, 3);
}
static int gpio_twl4030_remove(struct platform_device *pdev);
static struct twl4030_gpio_platform_data *of_gpio_twl4030(struct device *dev,
struct twl4030_gpio_platform_data *pdata)
{
struct twl4030_gpio_platform_data *omap_twl_info;
omap_twl_info = devm_kzalloc(dev, sizeof(*omap_twl_info), GFP_KERNEL);
if (!omap_twl_info)
return NULL;
if (pdata)
*omap_twl_info = *pdata;
omap_twl_info->use_leds = of_property_read_bool(dev->of_node,
"ti,use-leds");
of_property_read_u32(dev->of_node, "ti,debounce",
&omap_twl_info->debounce);
of_property_read_u32(dev->of_node, "ti,mmc-cd",
(u32 *)&omap_twl_info->mmc_cd);
of_property_read_u32(dev->of_node, "ti,pullups",
&omap_twl_info->pullups);
of_property_read_u32(dev->of_node, "ti,pulldowns",
&omap_twl_info->pulldowns);
return omap_twl_info;
}
static int gpio_twl4030_probe(struct platform_device *pdev)
{
struct twl4030_gpio_platform_data *pdata = dev_get_platdata(&pdev->dev);
struct device_node *node = pdev->dev.of_node;
struct gpio_twl4030_priv *priv;
int ret, irq_base;
priv = devm_kzalloc(&pdev->dev, sizeof(struct gpio_twl4030_priv),
GFP_KERNEL);
if (!priv)
return -ENOMEM;
/* maybe setup IRQs */
if (is_module()) {
dev_err(&pdev->dev, "can't dispatch IRQs from modules\n");
goto no_irqs;
}
irq_base = irq_alloc_descs(-1, 0, TWL4030_GPIO_MAX, 0);
if (irq_base < 0) {
dev_err(&pdev->dev, "Failed to alloc irq_descs\n");
return irq_base;
}
irq_domain_add_legacy(node, TWL4030_GPIO_MAX, irq_base, 0,
&irq_domain_simple_ops, NULL);
ret = twl4030_sih_setup(&pdev->dev, TWL4030_MODULE_GPIO, irq_base);
if (ret < 0)
return ret;
priv->irq_base = irq_base;
no_irqs:
priv->gpio_chip = template_chip;
priv->gpio_chip.base = -1;
priv->gpio_chip.ngpio = TWL4030_GPIO_MAX;
priv->gpio_chip.dev = &pdev->dev;
mutex_init(&priv->mutex);
if (node)
pdata = of_gpio_twl4030(&pdev->dev, pdata);
if (pdata == NULL) {
dev_err(&pdev->dev, "Platform data is missing\n");
return -ENXIO;
}
/*
* NOTE: boards may waste power if they don't set pullups
* and pulldowns correctly ... default for non-ULPI pins is
* pulldown, and some other pins may have external pullups
* or pulldowns. Careful!
*/
ret = gpio_twl4030_pulls(pdata->pullups, pdata->pulldowns);
if (ret)
dev_dbg(&pdev->dev, "pullups %.05x %.05x --> %d\n",
pdata->pullups, pdata->pulldowns, ret);
ret = gpio_twl4030_debounce(pdata->debounce, pdata->mmc_cd);
if (ret)
dev_dbg(&pdev->dev, "debounce %.03x %.01x --> %d\n",
pdata->debounce, pdata->mmc_cd, ret);
/*
* NOTE: we assume VIBRA_CTL.VIBRA_EN, in MODULE_AUDIO_VOICE,
* is (still) clear if use_leds is set.
*/
if (pdata->use_leds)
priv->gpio_chip.ngpio += 2;
ret = gpiochip_add(&priv->gpio_chip);
if (ret < 0) {
dev_err(&pdev->dev, "could not register gpiochip, %d\n", ret);
priv->gpio_chip.ngpio = 0;
gpio_twl4030_remove(pdev);
goto out;
}
platform_set_drvdata(pdev, priv);
if (pdata && pdata->setup) {
int status;
status = pdata->setup(&pdev->dev, priv->gpio_chip.base,
TWL4030_GPIO_MAX);
if (status)
dev_dbg(&pdev->dev, "setup --> %d\n", status);
}
out:
return ret;
}
/* Cannot use as gpio_twl4030_probe() calls us */
static int gpio_twl4030_remove(struct platform_device *pdev)
{
struct twl4030_gpio_platform_data *pdata = dev_get_platdata(&pdev->dev);
struct gpio_twl4030_priv *priv = platform_get_drvdata(pdev);
int status;
if (pdata && pdata->teardown) {
status = pdata->teardown(&pdev->dev, priv->gpio_chip.base,
TWL4030_GPIO_MAX);
if (status) {
dev_dbg(&pdev->dev, "teardown --> %d\n", status);
return status;
}
}
status = gpiochip_remove(&priv->gpio_chip);
if (status < 0)
return status;
if (is_module())
return 0;
/* REVISIT no support yet for deregistering all the IRQs */
WARN_ON(1);
return -EIO;
}
static const struct of_device_id twl_gpio_match[] = {
{ .compatible = "ti,twl4030-gpio", },
{ },
};
MODULE_DEVICE_TABLE(of, twl_gpio_match);
/* Note: this hardware lives inside an I2C-based multi-function device. */
MODULE_ALIAS("platform:twl4030_gpio");
static struct platform_driver gpio_twl4030_driver = {
.driver = {
.name = "twl4030_gpio",
.owner = THIS_MODULE,
.of_match_table = twl_gpio_match,
},
.probe = gpio_twl4030_probe,
.remove = gpio_twl4030_remove,
};
static int __init gpio_twl4030_init(void)
{
return platform_driver_register(&gpio_twl4030_driver);
}
subsys_initcall(gpio_twl4030_init);
static void __exit gpio_twl4030_exit(void)
{
platform_driver_unregister(&gpio_twl4030_driver);
}
module_exit(gpio_twl4030_exit);
MODULE_AUTHOR("Texas Instruments, Inc.");
MODULE_DESCRIPTION("GPIO interface for TWL4030");
MODULE_LICENSE("GPL");
| gpl-2.0 |
DJSteve/kernel_j5nlte_mm | drivers/staging/prima/CORE/SYS/legacy/src/pal/src/palApiComm.c | 244 | 9820 | /*
* Copyright (c) 2012-2013 The Linux Foundation. All rights reserved.
*
* Previously licensed under the ISC license by Qualcomm Atheros, 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.
*/
/*
* This file was originally distributed by Qualcomm Atheros, Inc.
* under proprietary terms before Copyright ownership was assigned
* to the Linux Foundation.
*/
#include <palApi.h>
#include <sirTypes.h> // needed for tSirRetStatus
#include <vos_api.h>
#include <sirParams.h> // needed for tSirMbMsg
#include "wlan_qct_wda.h"
#ifndef FEATURE_WLAN_PAL_MEM_DISABLE
#ifdef MEMORY_DEBUG
eHalStatus palAllocateMemory_debug( tHddHandle hHdd, void **ppMemory, tANI_U32 numBytes, char* fileName, tANI_U32 lineNum )
{
eHalStatus halStatus = eHAL_STATUS_SUCCESS;
*ppMemory = vos_mem_malloc_debug( numBytes, fileName, lineNum );
if ( NULL == *ppMemory )
{
halStatus = eHAL_STATUS_FAILURE;
}
return( halStatus );
}
#else
eHalStatus palAllocateMemory( tHddHandle hHdd, void **ppMemory, tANI_U32 numBytes )
{
eHalStatus halStatus = eHAL_STATUS_SUCCESS;
*ppMemory = vos_mem_malloc( numBytes );
if ( NULL == *ppMemory )
{
halStatus = eHAL_STATUS_FAILURE;
}
return( halStatus );
}
#endif
eHalStatus palFreeMemory( tHddHandle hHdd, void *pMemory )
{
vos_mem_free( pMemory );
return( eHAL_STATUS_SUCCESS );
}
eHalStatus palFillMemory( tHddHandle hHdd, void *pMemory, tANI_U32 numBytes, tANI_BYTE fillValue )
{
vos_mem_set( pMemory, numBytes, fillValue );
return( eHAL_STATUS_SUCCESS );
}
eHalStatus palCopyMemory( tHddHandle hHdd, void *pDst, const void *pSrc, tANI_U32 numBytes )
{
vos_mem_copy( pDst, pSrc, numBytes );
return( eHAL_STATUS_SUCCESS );
}
tANI_BOOLEAN palEqualMemory( tHddHandle hHdd, void *pMemory1, void *pMemory2, tANI_U32 numBytes )
{
return( vos_mem_compare( pMemory1, pMemory2, numBytes ) );
}
#endif
eHalStatus palPktAlloc(tHddHandle hHdd, eFrameType frmType, tANI_U16 size, void **data, void **ppPacket)
{
eHalStatus halStatus = eHAL_STATUS_FAILURE;
VOS_STATUS vosStatus;
vos_pkt_t *pVosPacket;
do
{
// we are only handling the 802_11_MGMT frame type for PE/LIM. All other frame types should be
// ported to use the VOSS APIs directly and should not be using this palPktAlloc API.
VOS_ASSERT( HAL_TXRX_FRM_802_11_MGMT == frmType );
if ( HAL_TXRX_FRM_802_11_MGMT != frmType ) break;
// allocate one 802_11_MGMT VOS packet, zero the packet and fail the call if nothing is available.
// if we cannot get this vos packet, fail.
vosStatus = vos_pkt_get_packet( &pVosPacket, VOS_PKT_TYPE_TX_802_11_MGMT, size, 1, VOS_TRUE, NULL, NULL );
if ( !VOS_IS_STATUS_SUCCESS( vosStatus ) ) break;
// Reserve the space at the head of the packet for the caller. If we cannot reserve the space
// then we have to fail (return the packet to voss first!)
vosStatus = vos_pkt_reserve_head( pVosPacket, data, size );
if ( !VOS_IS_STATUS_SUCCESS( vosStatus ) )
{
vos_pkt_return_packet( pVosPacket );
break;
}
// Everything went well if we get here. Return the packet pointer to the caller and indicate
// success to the caller.
*ppPacket = (void *)pVosPacket;
halStatus = eHAL_STATUS_SUCCESS;
} while( 0 );
return( halStatus );
}
void palPktFree( tHddHandle hHdd, eFrameType frmType, void* buf, void *pPacket)
{
vos_pkt_t *pVosPacket = (vos_pkt_t *)pPacket;
VOS_STATUS vosStatus;
do
{
VOS_ASSERT( pVosPacket );
if ( !pVosPacket ) break;
// we are only handling the 802_11_MGMT frame type for PE/LIM. All other frame types should be
// ported to use the VOSS APIs directly and should not be using this palPktAlloc API.
VOS_ASSERT( HAL_TXRX_FRM_802_11_MGMT == frmType );
if ( HAL_TXRX_FRM_802_11_MGMT != frmType ) break;
// return the vos packet to Voss. Nothing to do if this fails since the palPktFree does not
// have a return code.
vosStatus = vos_pkt_return_packet( pVosPacket );
VOS_ASSERT( VOS_IS_STATUS_SUCCESS( vosStatus ) );
} while( 0 );
return;
}
tANI_U32 palGetTickCount(tHddHandle hHdd)
{
return( vos_timer_get_system_ticks() );
}
tANI_U32 pal_be32_to_cpu(tANI_U32 x)
{
return( x );
}
tANI_U32 pal_cpu_to_be32(tANI_U32 x)
{
return(( x ) );
}
tANI_U16 pal_be16_to_cpu(tANI_U16 x)
{
return( ( x ) );
}
tANI_U16 pal_cpu_to_be16(tANI_U16 x)
{
return( ( x ) );
}
eHalStatus palSpinLockAlloc( tHddHandle hHdd, tPalSpinLockHandle *pHandle )
{
eHalStatus halStatus = eHAL_STATUS_FAILURE;
VOS_STATUS vosStatus;
vos_lock_t *pLock;
do
{
pLock = vos_mem_malloc( sizeof( vos_lock_t ) );
if ( NULL == pLock ) break;
vos_mem_set(pLock, sizeof( vos_lock_t ), 0);
vosStatus = vos_lock_init( pLock );
if ( !VOS_IS_STATUS_SUCCESS( vosStatus ) )
{
vos_mem_free( pLock );
break;
}
*pHandle = (tPalSpinLockHandle)pLock;
halStatus = eHAL_STATUS_SUCCESS;
} while( 0 );
return( halStatus );
}
eHalStatus palSpinLockFree( tHddHandle hHdd, tPalSpinLockHandle hSpinLock )
{
eHalStatus halStatus = eHAL_STATUS_FAILURE;
vos_lock_t *pLock = (vos_lock_t *)hSpinLock;
VOS_STATUS vosStatus;
vosStatus = vos_lock_destroy( pLock );
if ( VOS_IS_STATUS_SUCCESS( vosStatus ) )
{
// if we successfully destroy the lock, free
// the memory and indicate success to the caller.
vos_mem_free( pLock );
halStatus = eHAL_STATUS_SUCCESS;
}
return( halStatus );
}
eHalStatus palSpinLockTake( tHddHandle hHdd, tPalSpinLockHandle hSpinLock )
{
eHalStatus halStatus = eHAL_STATUS_FAILURE;
vos_lock_t *pLock = (vos_lock_t *)hSpinLock;
VOS_STATUS vosStatus;
vosStatus = vos_lock_acquire( pLock );
if ( VOS_IS_STATUS_SUCCESS( vosStatus ) )
{
// if successfully acquire the lock, indicate success
// to the caller.
halStatus = eHAL_STATUS_SUCCESS;
}
return( halStatus );
}
eHalStatus palSpinLockGive( tHddHandle hHdd, tPalSpinLockHandle hSpinLock )
{
eHalStatus halStatus = eHAL_STATUS_FAILURE;
vos_lock_t *pLock = (vos_lock_t *)hSpinLock;
VOS_STATUS vosStatus;
vosStatus = vos_lock_release( pLock );
if ( VOS_IS_STATUS_SUCCESS( vosStatus ) )
{
// if successfully acquire the lock, indicate success
// to the caller.
halStatus = eHAL_STATUS_SUCCESS;
}
return( halStatus );
}
// Caller of this function MUST dynamically allocate memory for pBuf
// because this funciton will free the memory.
eHalStatus palSendMBMessage(tHddHandle hHdd, void *pBuf)
{
eHalStatus halStatus = eHAL_STATUS_FAILURE;
tSirRetStatus sirStatus;
v_CONTEXT_t vosContext;
v_VOID_t *hHal;
vosContext = vos_get_global_context( VOS_MODULE_ID_HDD, hHdd );
if (NULL == vosContext)
{
VOS_TRACE(VOS_MODULE_ID_SYS, VOS_TRACE_LEVEL_ERROR,
"%s: invalid vosContext", __func__);
}
else
{
hHal = vos_get_context( VOS_MODULE_ID_SME, vosContext );
if (NULL == hHal)
{
VOS_TRACE(VOS_MODULE_ID_SYS, VOS_TRACE_LEVEL_ERROR,
"%s: invalid hHal", __func__);
}
else
{
sirStatus = uMacPostCtrlMsg( hHal, pBuf );
if ( eSIR_SUCCESS == sirStatus )
{
halStatus = eHAL_STATUS_SUCCESS;
}
}
}
vos_mem_free( pBuf );
return( halStatus );
}
//All semophore functions are no-op here
//PAL semaphore functions
//All functions MUST return success. If change needs to be made, please check all callers' logic
eHalStatus palSemaphoreAlloc( tHddHandle hHdd, tPalSemaphoreHandle *pHandle, tANI_S32 count )
{
(void)hHdd;
(void)pHandle;
(void)count;
if(pHandle)
{
*pHandle = NULL;
}
return (eHAL_STATUS_SUCCESS);
}
eHalStatus palSemaphoreFree( tHddHandle hHdd, tPalSemaphoreHandle hSemaphore )
{
(void)hHdd;
(void)hSemaphore;
return (eHAL_STATUS_SUCCESS);
}
eHalStatus palSemaphoreTake( tHddHandle hHdd, tPalSemaphoreHandle hSemaphore )
{
(void)hHdd;
(void)hSemaphore;
return (eHAL_STATUS_SUCCESS);
}
eHalStatus palSemaphoreGive( tHddHandle hHdd, tPalSemaphoreHandle hSemaphore )
{
(void)hHdd;
(void)hSemaphore;
return (eHAL_STATUS_SUCCESS);
}
eHalStatus palMutexAlloc( tHddHandle hHdd, tPalSemaphoreHandle *pHandle)
{
(void)hHdd;
(void)pHandle;
if(pHandle)
{
*pHandle = NULL;
}
return (eHAL_STATUS_SUCCESS);
}
eHalStatus palMutexAllocLocked( tHddHandle hHdd, tPalSemaphoreHandle *pHandle)
{
(void)hHdd;
(void)pHandle;
if(pHandle)
{
*pHandle = NULL;
}
return (eHAL_STATUS_SUCCESS);
}
eAniBoolean pal_in_interrupt(void)
{
return (eANI_BOOLEAN_FALSE);
}
void pal_local_bh_disable(void)
{
}
void pal_local_bh_enable(void)
{
}
| gpl-2.0 |
elopez/linux | drivers/media/usb/cx231xx/cx231xx-audio.c | 500 | 19113 | /*
* Conexant Cx231xx audio extension
*
* Copyright (C) 2008 <srinivasa.deevi at conexant dot com>
* Based on em28xx driver
*
*
* 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/usb.h>
#include <linux/init.h>
#include <linux/sound.h>
#include <linux/spinlock.h>
#include <linux/soundcard.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/proc_fs.h>
#include <linux/module.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/info.h>
#include <sound/initval.h>
#include <sound/control.h>
#include <media/v4l2-common.h>
#include "cx231xx.h"
static int debug;
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "activates debug info");
#define dprintk(fmt, arg...) do { \
if (debug) \
printk(KERN_INFO "cx231xx-audio %s: " fmt, \
__func__, ##arg); \
} while (0)
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;
static int cx231xx_isoc_audio_deinit(struct cx231xx *dev)
{
int i;
dprintk("Stopping isoc\n");
for (i = 0; i < CX231XX_AUDIO_BUFS; i++) {
if (dev->adev.urb[i]) {
if (!irqs_disabled())
usb_kill_urb(dev->adev.urb[i]);
else
usb_unlink_urb(dev->adev.urb[i]);
usb_free_urb(dev->adev.urb[i]);
dev->adev.urb[i] = NULL;
kfree(dev->adev.transfer_buffer[i]);
dev->adev.transfer_buffer[i] = NULL;
}
}
return 0;
}
static int cx231xx_bulk_audio_deinit(struct cx231xx *dev)
{
int i;
dprintk("Stopping bulk\n");
for (i = 0; i < CX231XX_AUDIO_BUFS; i++) {
if (dev->adev.urb[i]) {
if (!irqs_disabled())
usb_kill_urb(dev->adev.urb[i]);
else
usb_unlink_urb(dev->adev.urb[i]);
usb_free_urb(dev->adev.urb[i]);
dev->adev.urb[i] = NULL;
kfree(dev->adev.transfer_buffer[i]);
dev->adev.transfer_buffer[i] = NULL;
}
}
return 0;
}
static void cx231xx_audio_isocirq(struct urb *urb)
{
struct cx231xx *dev = urb->context;
int i;
unsigned int oldptr;
int period_elapsed = 0;
int status;
unsigned char *cp;
unsigned int stride;
struct snd_pcm_substream *substream;
struct snd_pcm_runtime *runtime;
if (dev->state & DEV_DISCONNECTED)
return;
switch (urb->status) {
case 0: /* success */
case -ETIMEDOUT: /* NAK */
break;
case -ECONNRESET: /* kill */
case -ENOENT:
case -ESHUTDOWN:
return;
default: /* error */
dprintk("urb completition error %d.\n", urb->status);
break;
}
if (atomic_read(&dev->stream_started) == 0)
return;
if (dev->adev.capture_pcm_substream) {
substream = dev->adev.capture_pcm_substream;
runtime = substream->runtime;
stride = runtime->frame_bits >> 3;
for (i = 0; i < urb->number_of_packets; i++) {
int length = urb->iso_frame_desc[i].actual_length /
stride;
cp = (unsigned char *)urb->transfer_buffer +
urb->iso_frame_desc[i].offset;
if (!length)
continue;
oldptr = dev->adev.hwptr_done_capture;
if (oldptr + length >= runtime->buffer_size) {
unsigned int cnt;
cnt = runtime->buffer_size - oldptr;
memcpy(runtime->dma_area + oldptr * stride, cp,
cnt * stride);
memcpy(runtime->dma_area, cp + cnt * stride,
length * stride - cnt * stride);
} else {
memcpy(runtime->dma_area + oldptr * stride, cp,
length * stride);
}
snd_pcm_stream_lock(substream);
dev->adev.hwptr_done_capture += length;
if (dev->adev.hwptr_done_capture >=
runtime->buffer_size)
dev->adev.hwptr_done_capture -=
runtime->buffer_size;
dev->adev.capture_transfer_done += length;
if (dev->adev.capture_transfer_done >=
runtime->period_size) {
dev->adev.capture_transfer_done -=
runtime->period_size;
period_elapsed = 1;
}
snd_pcm_stream_unlock(substream);
}
if (period_elapsed)
snd_pcm_period_elapsed(substream);
}
urb->status = 0;
status = usb_submit_urb(urb, GFP_ATOMIC);
if (status < 0) {
cx231xx_errdev("resubmit of audio urb failed (error=%i)\n",
status);
}
return;
}
static void cx231xx_audio_bulkirq(struct urb *urb)
{
struct cx231xx *dev = urb->context;
unsigned int oldptr;
int period_elapsed = 0;
int status;
unsigned char *cp;
unsigned int stride;
struct snd_pcm_substream *substream;
struct snd_pcm_runtime *runtime;
if (dev->state & DEV_DISCONNECTED)
return;
switch (urb->status) {
case 0: /* success */
case -ETIMEDOUT: /* NAK */
break;
case -ECONNRESET: /* kill */
case -ENOENT:
case -ESHUTDOWN:
return;
default: /* error */
dprintk("urb completition error %d.\n", urb->status);
break;
}
if (atomic_read(&dev->stream_started) == 0)
return;
if (dev->adev.capture_pcm_substream) {
substream = dev->adev.capture_pcm_substream;
runtime = substream->runtime;
stride = runtime->frame_bits >> 3;
if (1) {
int length = urb->actual_length /
stride;
cp = (unsigned char *)urb->transfer_buffer;
oldptr = dev->adev.hwptr_done_capture;
if (oldptr + length >= runtime->buffer_size) {
unsigned int cnt;
cnt = runtime->buffer_size - oldptr;
memcpy(runtime->dma_area + oldptr * stride, cp,
cnt * stride);
memcpy(runtime->dma_area, cp + cnt * stride,
length * stride - cnt * stride);
} else {
memcpy(runtime->dma_area + oldptr * stride, cp,
length * stride);
}
snd_pcm_stream_lock(substream);
dev->adev.hwptr_done_capture += length;
if (dev->adev.hwptr_done_capture >=
runtime->buffer_size)
dev->adev.hwptr_done_capture -=
runtime->buffer_size;
dev->adev.capture_transfer_done += length;
if (dev->adev.capture_transfer_done >=
runtime->period_size) {
dev->adev.capture_transfer_done -=
runtime->period_size;
period_elapsed = 1;
}
snd_pcm_stream_unlock(substream);
}
if (period_elapsed)
snd_pcm_period_elapsed(substream);
}
urb->status = 0;
status = usb_submit_urb(urb, GFP_ATOMIC);
if (status < 0) {
cx231xx_errdev("resubmit of audio urb failed (error=%i)\n",
status);
}
return;
}
static int cx231xx_init_audio_isoc(struct cx231xx *dev)
{
int i, errCode;
int sb_size;
cx231xx_info("%s: Starting ISO AUDIO transfers\n", __func__);
if (dev->state & DEV_DISCONNECTED)
return -ENODEV;
sb_size = CX231XX_ISO_NUM_AUDIO_PACKETS * dev->adev.max_pkt_size;
for (i = 0; i < CX231XX_AUDIO_BUFS; i++) {
struct urb *urb;
int j, k;
dev->adev.transfer_buffer[i] = kmalloc(sb_size, GFP_ATOMIC);
if (!dev->adev.transfer_buffer[i])
return -ENOMEM;
memset(dev->adev.transfer_buffer[i], 0x80, sb_size);
urb = usb_alloc_urb(CX231XX_ISO_NUM_AUDIO_PACKETS, GFP_ATOMIC);
if (!urb) {
cx231xx_errdev("usb_alloc_urb failed!\n");
for (j = 0; j < i; j++) {
usb_free_urb(dev->adev.urb[j]);
kfree(dev->adev.transfer_buffer[j]);
}
return -ENOMEM;
}
urb->dev = dev->udev;
urb->context = dev;
urb->pipe = usb_rcvisocpipe(dev->udev,
dev->adev.end_point_addr);
urb->transfer_flags = URB_ISO_ASAP;
urb->transfer_buffer = dev->adev.transfer_buffer[i];
urb->interval = 1;
urb->complete = cx231xx_audio_isocirq;
urb->number_of_packets = CX231XX_ISO_NUM_AUDIO_PACKETS;
urb->transfer_buffer_length = sb_size;
for (j = k = 0; j < CX231XX_ISO_NUM_AUDIO_PACKETS;
j++, k += dev->adev.max_pkt_size) {
urb->iso_frame_desc[j].offset = k;
urb->iso_frame_desc[j].length = dev->adev.max_pkt_size;
}
dev->adev.urb[i] = urb;
}
for (i = 0; i < CX231XX_AUDIO_BUFS; i++) {
errCode = usb_submit_urb(dev->adev.urb[i], GFP_ATOMIC);
if (errCode < 0) {
cx231xx_isoc_audio_deinit(dev);
return errCode;
}
}
return errCode;
}
static int cx231xx_init_audio_bulk(struct cx231xx *dev)
{
int i, errCode;
int sb_size;
cx231xx_info("%s: Starting BULK AUDIO transfers\n", __func__);
if (dev->state & DEV_DISCONNECTED)
return -ENODEV;
sb_size = CX231XX_NUM_AUDIO_PACKETS * dev->adev.max_pkt_size;
for (i = 0; i < CX231XX_AUDIO_BUFS; i++) {
struct urb *urb;
int j;
dev->adev.transfer_buffer[i] = kmalloc(sb_size, GFP_ATOMIC);
if (!dev->adev.transfer_buffer[i])
return -ENOMEM;
memset(dev->adev.transfer_buffer[i], 0x80, sb_size);
urb = usb_alloc_urb(CX231XX_NUM_AUDIO_PACKETS, GFP_ATOMIC);
if (!urb) {
cx231xx_errdev("usb_alloc_urb failed!\n");
for (j = 0; j < i; j++) {
usb_free_urb(dev->adev.urb[j]);
kfree(dev->adev.transfer_buffer[j]);
}
return -ENOMEM;
}
urb->dev = dev->udev;
urb->context = dev;
urb->pipe = usb_rcvbulkpipe(dev->udev,
dev->adev.end_point_addr);
urb->transfer_flags = 0;
urb->transfer_buffer = dev->adev.transfer_buffer[i];
urb->complete = cx231xx_audio_bulkirq;
urb->transfer_buffer_length = sb_size;
dev->adev.urb[i] = urb;
}
for (i = 0; i < CX231XX_AUDIO_BUFS; i++) {
errCode = usb_submit_urb(dev->adev.urb[i], GFP_ATOMIC);
if (errCode < 0) {
cx231xx_bulk_audio_deinit(dev);
return errCode;
}
}
return errCode;
}
static int snd_pcm_alloc_vmalloc_buffer(struct snd_pcm_substream *subs,
size_t size)
{
struct snd_pcm_runtime *runtime = subs->runtime;
dprintk("Allocating vbuffer\n");
if (runtime->dma_area) {
if (runtime->dma_bytes > size)
return 0;
vfree(runtime->dma_area);
}
runtime->dma_area = vmalloc(size);
if (!runtime->dma_area)
return -ENOMEM;
runtime->dma_bytes = size;
return 0;
}
static struct snd_pcm_hardware snd_cx231xx_hw_capture = {
.info = SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_MMAP_VALID,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_KNOT,
.rate_min = 48000,
.rate_max = 48000,
.channels_min = 2,
.channels_max = 2,
.buffer_bytes_max = 62720 * 8, /* just about the value in usbaudio.c */
.period_bytes_min = 64, /* 12544/2, */
.period_bytes_max = 12544,
.periods_min = 2,
.periods_max = 98, /* 12544, */
};
static int snd_cx231xx_capture_open(struct snd_pcm_substream *substream)
{
struct cx231xx *dev = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
int ret = 0;
dprintk("opening device and trying to acquire exclusive lock\n");
if (!dev) {
cx231xx_errdev("BUG: cx231xx can't find device struct."
" Can't proceed with open\n");
return -ENODEV;
}
if (dev->state & DEV_DISCONNECTED) {
cx231xx_errdev("Can't open. the device was removed.\n");
return -ENODEV;
}
/* set alternate setting for audio interface */
/* 1 - 48000 samples per sec */
mutex_lock(&dev->lock);
if (dev->USE_ISO)
ret = cx231xx_set_alt_setting(dev, INDEX_AUDIO, 1);
else
ret = cx231xx_set_alt_setting(dev, INDEX_AUDIO, 0);
mutex_unlock(&dev->lock);
if (ret < 0) {
cx231xx_errdev("failed to set alternate setting !\n");
return ret;
}
runtime->hw = snd_cx231xx_hw_capture;
mutex_lock(&dev->lock);
/* inform hardware to start streaming */
ret = cx231xx_capture_start(dev, 1, Audio);
dev->adev.users++;
mutex_unlock(&dev->lock);
snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS);
dev->adev.capture_pcm_substream = substream;
runtime->private_data = dev;
return 0;
}
static int snd_cx231xx_pcm_close(struct snd_pcm_substream *substream)
{
int ret;
struct cx231xx *dev = snd_pcm_substream_chip(substream);
dprintk("closing device\n");
/* inform hardware to stop streaming */
mutex_lock(&dev->lock);
ret = cx231xx_capture_start(dev, 0, Audio);
/* set alternate setting for audio interface */
/* 1 - 48000 samples per sec */
ret = cx231xx_set_alt_setting(dev, INDEX_AUDIO, 0);
if (ret < 0) {
cx231xx_errdev("failed to set alternate setting !\n");
mutex_unlock(&dev->lock);
return ret;
}
dev->adev.users--;
mutex_unlock(&dev->lock);
if (dev->adev.users == 0 && dev->adev.shutdown == 1) {
dprintk("audio users: %d\n", dev->adev.users);
dprintk("disabling audio stream!\n");
dev->adev.shutdown = 0;
dprintk("released lock\n");
if (atomic_read(&dev->stream_started) > 0) {
atomic_set(&dev->stream_started, 0);
schedule_work(&dev->wq_trigger);
}
}
return 0;
}
static int snd_cx231xx_hw_capture_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
int ret;
dprintk("Setting capture parameters\n");
ret = snd_pcm_alloc_vmalloc_buffer(substream,
params_buffer_bytes(hw_params));
#if 0
/* TODO: set up cx231xx audio chip to deliver the correct audio format,
current default is 48000hz multiplexed => 96000hz mono
which shouldn't matter since analogue TV only supports mono */
unsigned int channels, rate, format;
format = params_format(hw_params);
rate = params_rate(hw_params);
channels = params_channels(hw_params);
#endif
return ret;
}
static int snd_cx231xx_hw_capture_free(struct snd_pcm_substream *substream)
{
struct cx231xx *dev = snd_pcm_substream_chip(substream);
dprintk("Stop capture, if needed\n");
if (atomic_read(&dev->stream_started) > 0) {
atomic_set(&dev->stream_started, 0);
schedule_work(&dev->wq_trigger);
}
return 0;
}
static int snd_cx231xx_prepare(struct snd_pcm_substream *substream)
{
struct cx231xx *dev = snd_pcm_substream_chip(substream);
dev->adev.hwptr_done_capture = 0;
dev->adev.capture_transfer_done = 0;
return 0;
}
static void audio_trigger(struct work_struct *work)
{
struct cx231xx *dev = container_of(work, struct cx231xx, wq_trigger);
if (atomic_read(&dev->stream_started)) {
dprintk("starting capture");
if (is_fw_load(dev) == 0)
cx25840_call(dev, core, load_fw);
if (dev->USE_ISO)
cx231xx_init_audio_isoc(dev);
else
cx231xx_init_audio_bulk(dev);
} else {
dprintk("stopping capture");
cx231xx_isoc_audio_deinit(dev);
}
}
static int snd_cx231xx_capture_trigger(struct snd_pcm_substream *substream,
int cmd)
{
struct cx231xx *dev = snd_pcm_substream_chip(substream);
int retval = 0;
if (dev->state & DEV_DISCONNECTED)
return -ENODEV;
spin_lock(&dev->adev.slock);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
atomic_set(&dev->stream_started, 1);
break;
case SNDRV_PCM_TRIGGER_STOP:
atomic_set(&dev->stream_started, 0);
break;
default:
retval = -EINVAL;
break;
}
spin_unlock(&dev->adev.slock);
schedule_work(&dev->wq_trigger);
return retval;
}
static snd_pcm_uframes_t snd_cx231xx_capture_pointer(struct snd_pcm_substream
*substream)
{
struct cx231xx *dev;
unsigned long flags;
snd_pcm_uframes_t hwptr_done;
dev = snd_pcm_substream_chip(substream);
spin_lock_irqsave(&dev->adev.slock, flags);
hwptr_done = dev->adev.hwptr_done_capture;
spin_unlock_irqrestore(&dev->adev.slock, flags);
return hwptr_done;
}
static struct page *snd_pcm_get_vmalloc_page(struct snd_pcm_substream *subs,
unsigned long offset)
{
void *pageptr = subs->runtime->dma_area + offset;
return vmalloc_to_page(pageptr);
}
static struct snd_pcm_ops snd_cx231xx_pcm_capture = {
.open = snd_cx231xx_capture_open,
.close = snd_cx231xx_pcm_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_cx231xx_hw_capture_params,
.hw_free = snd_cx231xx_hw_capture_free,
.prepare = snd_cx231xx_prepare,
.trigger = snd_cx231xx_capture_trigger,
.pointer = snd_cx231xx_capture_pointer,
.page = snd_pcm_get_vmalloc_page,
};
static int cx231xx_audio_init(struct cx231xx *dev)
{
struct cx231xx_audio *adev = &dev->adev;
struct snd_pcm *pcm;
struct snd_card *card;
static int devnr;
int err;
struct usb_interface *uif;
int i, isoc_pipe = 0;
if (dev->has_alsa_audio != 1) {
/* This device does not support the extension (in this case
the device is expecting the snd-usb-audio module or
doesn't have analog audio support at all) */
return 0;
}
cx231xx_info("cx231xx-audio.c: probing for cx231xx "
"non standard usbaudio\n");
err = snd_card_new(&dev->udev->dev, index[devnr], "Cx231xx Audio",
THIS_MODULE, 0, &card);
if (err < 0)
return err;
spin_lock_init(&adev->slock);
err = snd_pcm_new(card, "Cx231xx Audio", 0, 0, 1, &pcm);
if (err < 0) {
snd_card_free(card);
return err;
}
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE,
&snd_cx231xx_pcm_capture);
pcm->info_flags = 0;
pcm->private_data = dev;
strcpy(pcm->name, "Conexant cx231xx Capture");
strcpy(card->driver, "Cx231xx-Audio");
strcpy(card->shortname, "Cx231xx Audio");
strcpy(card->longname, "Conexant cx231xx Audio");
INIT_WORK(&dev->wq_trigger, audio_trigger);
err = snd_card_register(card);
if (err < 0) {
snd_card_free(card);
return err;
}
adev->sndcard = card;
adev->udev = dev->udev;
/* compute alternate max packet sizes for Audio */
uif =
dev->udev->actconfig->interface[dev->current_pcb_config.
hs_config_info[0].interface_info.
audio_index + 1];
adev->end_point_addr =
uif->altsetting[0].endpoint[isoc_pipe].desc.
bEndpointAddress;
adev->num_alt = uif->num_altsetting;
cx231xx_info("EndPoint Addr 0x%x, Alternate settings: %i\n",
adev->end_point_addr, adev->num_alt);
adev->alt_max_pkt_size = kmalloc(32 * adev->num_alt, GFP_KERNEL);
if (adev->alt_max_pkt_size == NULL) {
cx231xx_errdev("out of memory!\n");
return -ENOMEM;
}
for (i = 0; i < adev->num_alt; i++) {
u16 tmp =
le16_to_cpu(uif->altsetting[i].endpoint[isoc_pipe].desc.
wMaxPacketSize);
adev->alt_max_pkt_size[i] =
(tmp & 0x07ff) * (((tmp & 0x1800) >> 11) + 1);
cx231xx_info("Alternate setting %i, max size= %i\n", i,
adev->alt_max_pkt_size[i]);
}
return 0;
}
static int cx231xx_audio_fini(struct cx231xx *dev)
{
if (dev == NULL)
return 0;
if (dev->has_alsa_audio != 1) {
/* This device does not support the extension (in this case
the device is expecting the snd-usb-audio module or
doesn't have analog audio support at all) */
return 0;
}
if (dev->adev.sndcard) {
snd_card_free(dev->adev.sndcard);
kfree(dev->adev.alt_max_pkt_size);
dev->adev.sndcard = NULL;
}
return 0;
}
static struct cx231xx_ops audio_ops = {
.id = CX231XX_AUDIO,
.name = "Cx231xx Audio Extension",
.init = cx231xx_audio_init,
.fini = cx231xx_audio_fini,
};
static int __init cx231xx_alsa_register(void)
{
return cx231xx_register_extension(&audio_ops);
}
static void __exit cx231xx_alsa_unregister(void)
{
cx231xx_unregister_extension(&audio_ops);
}
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Srinivasa Deevi <srinivasa.deevi@conexant.com>");
MODULE_DESCRIPTION("Cx231xx Audio driver");
module_init(cx231xx_alsa_register);
module_exit(cx231xx_alsa_unregister);
| gpl-2.0 |
Kali-/htc-kernel-ace | drivers/pnp/pnpbios/proc.c | 756 | 7414 | /*
* /proc/bus/pnp interface for Plug and Play devices
*
* Written by David Hinds, dahinds@users.sourceforge.net
* Modified by Thomas Hood
*
* The .../devices and .../<node> and .../boot/<node> files are
* utilized by the lspnp and setpnp utilities, supplied with the
* pcmcia-cs package.
* http://pcmcia-cs.sourceforge.net
*
* The .../escd file is utilized by the lsescd utility written by
* Gunther Mayer.
* http://home.t-online.de/home/gunther.mayer/lsescd
*
* The .../legacy_device_resources file is not used yet.
*
* The other files are human-readable.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/proc_fs.h>
#include <linux/pnp.h>
#include <linux/init.h>
#include <asm/uaccess.h>
#include "pnpbios.h"
static struct proc_dir_entry *proc_pnp = NULL;
static struct proc_dir_entry *proc_pnp_boot = NULL;
static int proc_read_pnpconfig(char *buf, char **start, off_t pos,
int count, int *eof, void *data)
{
struct pnp_isa_config_struc pnps;
if (pnp_bios_isapnp_config(&pnps))
return -EIO;
return snprintf(buf, count,
"structure_revision %d\n"
"number_of_CSNs %d\n"
"ISA_read_data_port 0x%x\n",
pnps.revision, pnps.no_csns, pnps.isa_rd_data_port);
}
static int proc_read_escdinfo(char *buf, char **start, off_t pos,
int count, int *eof, void *data)
{
struct escd_info_struc escd;
if (pnp_bios_escd_info(&escd))
return -EIO;
return snprintf(buf, count,
"min_ESCD_write_size %d\n"
"ESCD_size %d\n"
"NVRAM_base 0x%x\n",
escd.min_escd_write_size,
escd.escd_size, escd.nv_storage_base);
}
#define MAX_SANE_ESCD_SIZE (32*1024)
static int proc_read_escd(char *buf, char **start, off_t pos,
int count, int *eof, void *data)
{
struct escd_info_struc escd;
char *tmpbuf;
int escd_size, escd_left_to_read, n;
if (pnp_bios_escd_info(&escd))
return -EIO;
/* sanity check */
if (escd.escd_size > MAX_SANE_ESCD_SIZE) {
printk(KERN_ERR
"PnPBIOS: proc_read_escd: ESCD size reported by BIOS escd_info call is too great\n");
return -EFBIG;
}
tmpbuf = kzalloc(escd.escd_size, GFP_KERNEL);
if (!tmpbuf)
return -ENOMEM;
if (pnp_bios_read_escd(tmpbuf, escd.nv_storage_base)) {
kfree(tmpbuf);
return -EIO;
}
escd_size =
(unsigned char)(tmpbuf[0]) + (unsigned char)(tmpbuf[1]) * 256;
/* sanity check */
if (escd_size > MAX_SANE_ESCD_SIZE) {
printk(KERN_ERR "PnPBIOS: proc_read_escd: ESCD size reported by"
" BIOS read_escd call is too great\n");
kfree(tmpbuf);
return -EFBIG;
}
escd_left_to_read = escd_size - pos;
if (escd_left_to_read < 0)
escd_left_to_read = 0;
if (escd_left_to_read == 0)
*eof = 1;
n = min(count, escd_left_to_read);
memcpy(buf, tmpbuf + pos, n);
kfree(tmpbuf);
*start = buf;
return n;
}
static int proc_read_legacyres(char *buf, char **start, off_t pos,
int count, int *eof, void *data)
{
/* Assume that the following won't overflow the buffer */
if (pnp_bios_get_stat_res(buf))
return -EIO;
return count; // FIXME: Return actual length
}
static int proc_read_devices(char *buf, char **start, off_t pos,
int count, int *eof, void *data)
{
struct pnp_bios_node *node;
u8 nodenum;
char *p = buf;
if (pos >= 0xff)
return 0;
node = kzalloc(node_info.max_node_size, GFP_KERNEL);
if (!node)
return -ENOMEM;
for (nodenum = pos; nodenum < 0xff;) {
u8 thisnodenum = nodenum;
/* 26 = the number of characters per line sprintf'ed */
if ((p - buf + 26) > count)
break;
if (pnp_bios_get_dev_node(&nodenum, PNPMODE_DYNAMIC, node))
break;
p += sprintf(p, "%02x\t%08x\t%02x:%02x:%02x\t%04x\n",
node->handle, node->eisa_id,
node->type_code[0], node->type_code[1],
node->type_code[2], node->flags);
if (nodenum <= thisnodenum) {
printk(KERN_ERR
"%s Node number 0x%x is out of sequence following node 0x%x. Aborting.\n",
"PnPBIOS: proc_read_devices:",
(unsigned int)nodenum,
(unsigned int)thisnodenum);
*eof = 1;
break;
}
}
kfree(node);
if (nodenum == 0xff)
*eof = 1;
*start = (char *)((off_t) nodenum - pos);
return p - buf;
}
static int proc_read_node(char *buf, char **start, off_t pos,
int count, int *eof, void *data)
{
struct pnp_bios_node *node;
int boot = (long)data >> 8;
u8 nodenum = (long)data;
int len;
node = kzalloc(node_info.max_node_size, GFP_KERNEL);
if (!node)
return -ENOMEM;
if (pnp_bios_get_dev_node(&nodenum, boot, node)) {
kfree(node);
return -EIO;
}
len = node->size - sizeof(struct pnp_bios_node);
memcpy(buf, node->data, len);
kfree(node);
return len;
}
static int proc_write_node(struct file *file, const char __user * buf,
unsigned long count, void *data)
{
struct pnp_bios_node *node;
int boot = (long)data >> 8;
u8 nodenum = (long)data;
int ret = count;
node = kzalloc(node_info.max_node_size, GFP_KERNEL);
if (!node)
return -ENOMEM;
if (pnp_bios_get_dev_node(&nodenum, boot, node)) {
ret = -EIO;
goto out;
}
if (count != node->size - sizeof(struct pnp_bios_node)) {
ret = -EINVAL;
goto out;
}
if (copy_from_user(node->data, buf, count)) {
ret = -EFAULT;
goto out;
}
if (pnp_bios_set_dev_node(node->handle, boot, node) != 0) {
ret = -EINVAL;
goto out;
}
ret = count;
out:
kfree(node);
return ret;
}
int pnpbios_interface_attach_device(struct pnp_bios_node *node)
{
char name[3];
struct proc_dir_entry *ent;
sprintf(name, "%02x", node->handle);
if (!proc_pnp)
return -EIO;
if (!pnpbios_dont_use_current_config) {
ent = create_proc_entry(name, 0, proc_pnp);
if (ent) {
ent->read_proc = proc_read_node;
ent->write_proc = proc_write_node;
ent->data = (void *)(long)(node->handle);
}
}
if (!proc_pnp_boot)
return -EIO;
ent = create_proc_entry(name, 0, proc_pnp_boot);
if (ent) {
ent->read_proc = proc_read_node;
ent->write_proc = proc_write_node;
ent->data = (void *)(long)(node->handle + 0x100);
return 0;
}
return -EIO;
}
/*
* When this is called, pnpbios functions are assumed to
* work and the pnpbios_dont_use_current_config flag
* should already have been set to the appropriate value
*/
int __init pnpbios_proc_init(void)
{
proc_pnp = proc_mkdir("bus/pnp", NULL);
if (!proc_pnp)
return -EIO;
proc_pnp_boot = proc_mkdir("boot", proc_pnp);
if (!proc_pnp_boot)
return -EIO;
create_proc_read_entry("devices", 0, proc_pnp, proc_read_devices, NULL);
create_proc_read_entry("configuration_info", 0, proc_pnp,
proc_read_pnpconfig, NULL);
create_proc_read_entry("escd_info", 0, proc_pnp, proc_read_escdinfo,
NULL);
create_proc_read_entry("escd", S_IRUSR, proc_pnp, proc_read_escd, NULL);
create_proc_read_entry("legacy_device_resources", 0, proc_pnp,
proc_read_legacyres, NULL);
return 0;
}
void __exit pnpbios_proc_exit(void)
{
int i;
char name[3];
if (!proc_pnp)
return;
for (i = 0; i < 0xff; i++) {
sprintf(name, "%02x", i);
if (!pnpbios_dont_use_current_config)
remove_proc_entry(name, proc_pnp);
remove_proc_entry(name, proc_pnp_boot);
}
remove_proc_entry("legacy_device_resources", proc_pnp);
remove_proc_entry("escd", proc_pnp);
remove_proc_entry("escd_info", proc_pnp);
remove_proc_entry("configuration_info", proc_pnp);
remove_proc_entry("devices", proc_pnp);
remove_proc_entry("boot", proc_pnp);
remove_proc_entry("bus/pnp", NULL);
}
| gpl-2.0 |
DZB-Team/kernel_torino_cm11 | fs/adfs/inode.c | 756 | 9480 | /*
* linux/fs/adfs/inode.c
*
* Copyright (C) 1997-1999 Russell King
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/smp_lock.h>
#include <linux/buffer_head.h>
#include <linux/writeback.h>
#include "adfs.h"
/*
* Lookup/Create a block at offset 'block' into 'inode'. We currently do
* not support creation of new blocks, so we return -EIO for this case.
*/
static int
adfs_get_block(struct inode *inode, sector_t block, struct buffer_head *bh,
int create)
{
if (!create) {
if (block >= inode->i_blocks)
goto abort_toobig;
block = __adfs_block_map(inode->i_sb, inode->i_ino, block);
if (block)
map_bh(bh, inode->i_sb, block);
return 0;
}
/* don't support allocation of blocks yet */
return -EIO;
abort_toobig:
return 0;
}
static int adfs_writepage(struct page *page, struct writeback_control *wbc)
{
return block_write_full_page(page, adfs_get_block, wbc);
}
static int adfs_readpage(struct file *file, struct page *page)
{
return block_read_full_page(page, adfs_get_block);
}
static int adfs_write_begin(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, unsigned flags,
struct page **pagep, void **fsdata)
{
*pagep = NULL;
return cont_write_begin(file, mapping, pos, len, flags, pagep, fsdata,
adfs_get_block,
&ADFS_I(mapping->host)->mmu_private);
}
static sector_t _adfs_bmap(struct address_space *mapping, sector_t block)
{
return generic_block_bmap(mapping, block, adfs_get_block);
}
static const struct address_space_operations adfs_aops = {
.readpage = adfs_readpage,
.writepage = adfs_writepage,
.sync_page = block_sync_page,
.write_begin = adfs_write_begin,
.write_end = generic_write_end,
.bmap = _adfs_bmap
};
static inline unsigned int
adfs_filetype(struct inode *inode)
{
unsigned int type;
if (ADFS_I(inode)->stamped)
type = (ADFS_I(inode)->loadaddr >> 8) & 0xfff;
else
type = (unsigned int) -1;
return type;
}
/*
* Convert ADFS attributes and filetype to Linux permission.
*/
static umode_t
adfs_atts2mode(struct super_block *sb, struct inode *inode)
{
unsigned int filetype, attr = ADFS_I(inode)->attr;
umode_t mode, rmask;
struct adfs_sb_info *asb = ADFS_SB(sb);
if (attr & ADFS_NDA_DIRECTORY) {
mode = S_IRUGO & asb->s_owner_mask;
return S_IFDIR | S_IXUGO | mode;
}
filetype = adfs_filetype(inode);
switch (filetype) {
case 0xfc0: /* LinkFS */
return S_IFLNK|S_IRWXUGO;
case 0xfe6: /* UnixExec */
rmask = S_IRUGO | S_IXUGO;
break;
default:
rmask = S_IRUGO;
}
mode = S_IFREG;
if (attr & ADFS_NDA_OWNER_READ)
mode |= rmask & asb->s_owner_mask;
if (attr & ADFS_NDA_OWNER_WRITE)
mode |= S_IWUGO & asb->s_owner_mask;
if (attr & ADFS_NDA_PUBLIC_READ)
mode |= rmask & asb->s_other_mask;
if (attr & ADFS_NDA_PUBLIC_WRITE)
mode |= S_IWUGO & asb->s_other_mask;
return mode;
}
/*
* Convert Linux permission to ADFS attribute. We try to do the reverse
* of atts2mode, but there is not a 1:1 translation.
*/
static int
adfs_mode2atts(struct super_block *sb, struct inode *inode)
{
umode_t mode;
int attr;
struct adfs_sb_info *asb = ADFS_SB(sb);
/* FIXME: should we be able to alter a link? */
if (S_ISLNK(inode->i_mode))
return ADFS_I(inode)->attr;
if (S_ISDIR(inode->i_mode))
attr = ADFS_NDA_DIRECTORY;
else
attr = 0;
mode = inode->i_mode & asb->s_owner_mask;
if (mode & S_IRUGO)
attr |= ADFS_NDA_OWNER_READ;
if (mode & S_IWUGO)
attr |= ADFS_NDA_OWNER_WRITE;
mode = inode->i_mode & asb->s_other_mask;
mode &= ~asb->s_owner_mask;
if (mode & S_IRUGO)
attr |= ADFS_NDA_PUBLIC_READ;
if (mode & S_IWUGO)
attr |= ADFS_NDA_PUBLIC_WRITE;
return attr;
}
/*
* Convert an ADFS time to Unix time. ADFS has a 40-bit centi-second time
* referenced to 1 Jan 1900 (til 2248)
*/
static void
adfs_adfs2unix_time(struct timespec *tv, struct inode *inode)
{
unsigned int high, low;
if (ADFS_I(inode)->stamped == 0)
goto cur_time;
high = ADFS_I(inode)->loadaddr << 24;
low = ADFS_I(inode)->execaddr;
high |= low >> 8;
low &= 255;
/* Files dated pre 01 Jan 1970 00:00:00. */
if (high < 0x336e996a)
goto too_early;
/* Files dated post 18 Jan 2038 03:14:05. */
if (high >= 0x656e9969)
goto too_late;
/* discard 2208988800 (0x336e996a00) seconds of time */
high -= 0x336e996a;
/* convert 40-bit centi-seconds to 32-bit seconds */
tv->tv_sec = (((high % 100) << 8) + low) / 100 + (high / 100 << 8);
tv->tv_nsec = 0;
return;
cur_time:
*tv = CURRENT_TIME_SEC;
return;
too_early:
tv->tv_sec = tv->tv_nsec = 0;
return;
too_late:
tv->tv_sec = 0x7ffffffd;
tv->tv_nsec = 0;
return;
}
/*
* Convert an Unix time to ADFS time. We only do this if the entry has a
* time/date stamp already.
*/
static void
adfs_unix2adfs_time(struct inode *inode, unsigned int secs)
{
unsigned int high, low;
if (ADFS_I(inode)->stamped) {
/* convert 32-bit seconds to 40-bit centi-seconds */
low = (secs & 255) * 100;
high = (secs / 256) * 100 + (low >> 8) + 0x336e996a;
ADFS_I(inode)->loadaddr = (high >> 24) |
(ADFS_I(inode)->loadaddr & ~0xff);
ADFS_I(inode)->execaddr = (low & 255) | (high << 8);
}
}
/*
* Fill in the inode information from the object information.
*
* Note that this is an inode-less filesystem, so we can't use the inode
* number to reference the metadata on the media. Instead, we use the
* inode number to hold the object ID, which in turn will tell us where
* the data is held. We also save the parent object ID, and with these
* two, we can locate the metadata.
*
* This does mean that we rely on an objects parent remaining the same at
* all times - we cannot cope with a cross-directory rename (yet).
*/
struct inode *
adfs_iget(struct super_block *sb, struct object_info *obj)
{
struct inode *inode;
inode = new_inode(sb);
if (!inode)
goto out;
inode->i_uid = ADFS_SB(sb)->s_uid;
inode->i_gid = ADFS_SB(sb)->s_gid;
inode->i_ino = obj->file_id;
inode->i_size = obj->size;
inode->i_nlink = 2;
inode->i_blocks = (inode->i_size + sb->s_blocksize - 1) >>
sb->s_blocksize_bits;
/*
* we need to save the parent directory ID so that
* write_inode can update the directory information
* for this file. This will need special handling
* for cross-directory renames.
*/
ADFS_I(inode)->parent_id = obj->parent_id;
ADFS_I(inode)->loadaddr = obj->loadaddr;
ADFS_I(inode)->execaddr = obj->execaddr;
ADFS_I(inode)->attr = obj->attr;
ADFS_I(inode)->stamped = ((obj->loadaddr & 0xfff00000) == 0xfff00000);
inode->i_mode = adfs_atts2mode(sb, inode);
adfs_adfs2unix_time(&inode->i_mtime, inode);
inode->i_atime = inode->i_mtime;
inode->i_ctime = inode->i_mtime;
if (S_ISDIR(inode->i_mode)) {
inode->i_op = &adfs_dir_inode_operations;
inode->i_fop = &adfs_dir_operations;
} else if (S_ISREG(inode->i_mode)) {
inode->i_op = &adfs_file_inode_operations;
inode->i_fop = &adfs_file_operations;
inode->i_mapping->a_ops = &adfs_aops;
ADFS_I(inode)->mmu_private = inode->i_size;
}
insert_inode_hash(inode);
out:
return inode;
}
/*
* Validate and convert a changed access mode/time to their ADFS equivalents.
* adfs_write_inode will actually write the information back to the directory
* later.
*/
int
adfs_notify_change(struct dentry *dentry, struct iattr *attr)
{
struct inode *inode = dentry->d_inode;
struct super_block *sb = inode->i_sb;
unsigned int ia_valid = attr->ia_valid;
int error;
lock_kernel();
error = inode_change_ok(inode, attr);
/*
* we can't change the UID or GID of any file -
* we have a global UID/GID in the superblock
*/
if ((ia_valid & ATTR_UID && attr->ia_uid != ADFS_SB(sb)->s_uid) ||
(ia_valid & ATTR_GID && attr->ia_gid != ADFS_SB(sb)->s_gid))
error = -EPERM;
if (error)
goto out;
/* XXX: this is missing some actual on-disk truncation.. */
if (ia_valid & ATTR_SIZE)
error = simple_setsize(inode, attr->ia_size);
if (error)
goto out;
if (ia_valid & ATTR_MTIME) {
inode->i_mtime = attr->ia_mtime;
adfs_unix2adfs_time(inode, attr->ia_mtime.tv_sec);
}
/*
* FIXME: should we make these == to i_mtime since we don't
* have the ability to represent them in our filesystem?
*/
if (ia_valid & ATTR_ATIME)
inode->i_atime = attr->ia_atime;
if (ia_valid & ATTR_CTIME)
inode->i_ctime = attr->ia_ctime;
if (ia_valid & ATTR_MODE) {
ADFS_I(inode)->attr = adfs_mode2atts(sb, inode);
inode->i_mode = adfs_atts2mode(sb, inode);
}
/*
* FIXME: should we be marking this inode dirty even if
* we don't have any metadata to write back?
*/
if (ia_valid & (ATTR_SIZE | ATTR_MTIME | ATTR_MODE))
mark_inode_dirty(inode);
out:
unlock_kernel();
return error;
}
/*
* write an existing inode back to the directory, and therefore the disk.
* The adfs-specific inode data has already been updated by
* adfs_notify_change()
*/
int adfs_write_inode(struct inode *inode, struct writeback_control *wbc)
{
struct super_block *sb = inode->i_sb;
struct object_info obj;
int ret;
lock_kernel();
obj.file_id = inode->i_ino;
obj.name_len = 0;
obj.parent_id = ADFS_I(inode)->parent_id;
obj.loadaddr = ADFS_I(inode)->loadaddr;
obj.execaddr = ADFS_I(inode)->execaddr;
obj.attr = ADFS_I(inode)->attr;
obj.size = inode->i_size;
ret = adfs_dir_update(sb, &obj, wbc->sync_mode == WB_SYNC_ALL);
unlock_kernel();
return ret;
}
| gpl-2.0 |
msm8916-zte/android_kernel_zte_msm8916 | drivers/s390/scsi/zfcp_fc.c | 2292 | 27281 | /*
* zfcp device driver
*
* Fibre Channel related functions for the zfcp device driver.
*
* Copyright IBM Corp. 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,
};
static bool no_auto_port_rescan;
module_param_named(no_auto_port_rescan, no_auto_port_rescan, bool, 0600);
MODULE_PARM_DESC(no_auto_port_rescan,
"no automatic port_rescan (default off)");
void zfcp_fc_conditional_port_scan(struct zfcp_adapter *adapter)
{
if (no_auto_port_rescan)
return;
queue_work(adapter->work_queue, &adapter->scan_work);
}
void zfcp_fc_inverse_conditional_port_scan(struct zfcp_adapter *adapter)
{
if (!no_auto_port_rescan)
return;
queue_work(adapter->work_queue, &adapter->scan_work);
}
/**
* 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);
}
zfcp_fc_conditional_port_scan(fsf_req->adapter);
}
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 |
OtherCrashOverride/linux | net/ipv4/netfilter/nf_nat_amanda.c | 2804 | 2333 | /* Amanda extension for TCP NAT alteration.
* (C) 2002 by Brian J. Murrell <netfilter@interlinx.bc.ca>
* based on a copy of HW's ip_nat_irc.c as well as other 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; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/udp.h>
#include <net/netfilter/nf_nat_helper.h>
#include <net/netfilter/nf_nat_rule.h>
#include <net/netfilter/nf_conntrack_helper.h>
#include <net/netfilter/nf_conntrack_expect.h>
#include <linux/netfilter/nf_conntrack_amanda.h>
MODULE_AUTHOR("Brian J. Murrell <netfilter@interlinx.bc.ca>");
MODULE_DESCRIPTION("Amanda NAT helper");
MODULE_LICENSE("GPL");
MODULE_ALIAS("ip_nat_amanda");
static unsigned int help(struct sk_buff *skb,
enum ip_conntrack_info ctinfo,
unsigned int matchoff,
unsigned int matchlen,
struct nf_conntrack_expect *exp)
{
char buffer[sizeof("65535")];
u_int16_t port;
unsigned int ret;
/* Connection comes from client. */
exp->saved_proto.tcp.port = exp->tuple.dst.u.tcp.port;
exp->dir = IP_CT_DIR_ORIGINAL;
/* When you see the packet, we need to NAT it the same as the
* this one (ie. same IP: it will be TCP and master is UDP). */
exp->expectfn = nf_nat_follow_master;
/* Try to get same port: if not, try to change it. */
for (port = ntohs(exp->saved_proto.tcp.port); port != 0; port++) {
int res;
exp->tuple.dst.u.tcp.port = htons(port);
res = nf_ct_expect_related(exp);
if (res == 0)
break;
else if (res != -EBUSY) {
port = 0;
break;
}
}
if (port == 0)
return NF_DROP;
sprintf(buffer, "%u", port);
ret = nf_nat_mangle_udp_packet(skb, exp->master, ctinfo,
matchoff, matchlen,
buffer, strlen(buffer));
if (ret != NF_ACCEPT)
nf_ct_unexpect_related(exp);
return ret;
}
static void __exit nf_nat_amanda_fini(void)
{
rcu_assign_pointer(nf_nat_amanda_hook, NULL);
synchronize_rcu();
}
static int __init nf_nat_amanda_init(void)
{
BUG_ON(nf_nat_amanda_hook != NULL);
rcu_assign_pointer(nf_nat_amanda_hook, help);
return 0;
}
module_init(nf_nat_amanda_init);
module_exit(nf_nat_amanda_fini);
| gpl-2.0 |
NicholasPace/android_kernel_asus_moorefield-stock | fs/fscache/stats.c | 3572 | 10245 | /* FS-Cache statistics
*
* Copyright (C) 2007 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#define FSCACHE_DEBUG_LEVEL THREAD
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include "internal.h"
/*
* operation counters
*/
atomic_t fscache_n_op_pend;
atomic_t fscache_n_op_run;
atomic_t fscache_n_op_enqueue;
atomic_t fscache_n_op_requeue;
atomic_t fscache_n_op_deferred_release;
atomic_t fscache_n_op_release;
atomic_t fscache_n_op_gc;
atomic_t fscache_n_op_cancelled;
atomic_t fscache_n_op_rejected;
atomic_t fscache_n_attr_changed;
atomic_t fscache_n_attr_changed_ok;
atomic_t fscache_n_attr_changed_nobufs;
atomic_t fscache_n_attr_changed_nomem;
atomic_t fscache_n_attr_changed_calls;
atomic_t fscache_n_allocs;
atomic_t fscache_n_allocs_ok;
atomic_t fscache_n_allocs_wait;
atomic_t fscache_n_allocs_nobufs;
atomic_t fscache_n_allocs_intr;
atomic_t fscache_n_allocs_object_dead;
atomic_t fscache_n_alloc_ops;
atomic_t fscache_n_alloc_op_waits;
atomic_t fscache_n_retrievals;
atomic_t fscache_n_retrievals_ok;
atomic_t fscache_n_retrievals_wait;
atomic_t fscache_n_retrievals_nodata;
atomic_t fscache_n_retrievals_nobufs;
atomic_t fscache_n_retrievals_intr;
atomic_t fscache_n_retrievals_nomem;
atomic_t fscache_n_retrievals_object_dead;
atomic_t fscache_n_retrieval_ops;
atomic_t fscache_n_retrieval_op_waits;
atomic_t fscache_n_stores;
atomic_t fscache_n_stores_ok;
atomic_t fscache_n_stores_again;
atomic_t fscache_n_stores_nobufs;
atomic_t fscache_n_stores_oom;
atomic_t fscache_n_store_ops;
atomic_t fscache_n_store_calls;
atomic_t fscache_n_store_pages;
atomic_t fscache_n_store_radix_deletes;
atomic_t fscache_n_store_pages_over_limit;
atomic_t fscache_n_store_vmscan_not_storing;
atomic_t fscache_n_store_vmscan_gone;
atomic_t fscache_n_store_vmscan_busy;
atomic_t fscache_n_store_vmscan_cancelled;
atomic_t fscache_n_store_vmscan_wait;
atomic_t fscache_n_marks;
atomic_t fscache_n_uncaches;
atomic_t fscache_n_acquires;
atomic_t fscache_n_acquires_null;
atomic_t fscache_n_acquires_no_cache;
atomic_t fscache_n_acquires_ok;
atomic_t fscache_n_acquires_nobufs;
atomic_t fscache_n_acquires_oom;
atomic_t fscache_n_invalidates;
atomic_t fscache_n_invalidates_run;
atomic_t fscache_n_updates;
atomic_t fscache_n_updates_null;
atomic_t fscache_n_updates_run;
atomic_t fscache_n_relinquishes;
atomic_t fscache_n_relinquishes_null;
atomic_t fscache_n_relinquishes_waitcrt;
atomic_t fscache_n_relinquishes_retire;
atomic_t fscache_n_cookie_index;
atomic_t fscache_n_cookie_data;
atomic_t fscache_n_cookie_special;
atomic_t fscache_n_object_alloc;
atomic_t fscache_n_object_no_alloc;
atomic_t fscache_n_object_lookups;
atomic_t fscache_n_object_lookups_negative;
atomic_t fscache_n_object_lookups_positive;
atomic_t fscache_n_object_lookups_timed_out;
atomic_t fscache_n_object_created;
atomic_t fscache_n_object_avail;
atomic_t fscache_n_object_dead;
atomic_t fscache_n_checkaux_none;
atomic_t fscache_n_checkaux_okay;
atomic_t fscache_n_checkaux_update;
atomic_t fscache_n_checkaux_obsolete;
atomic_t fscache_n_cop_alloc_object;
atomic_t fscache_n_cop_lookup_object;
atomic_t fscache_n_cop_lookup_complete;
atomic_t fscache_n_cop_grab_object;
atomic_t fscache_n_cop_invalidate_object;
atomic_t fscache_n_cop_update_object;
atomic_t fscache_n_cop_drop_object;
atomic_t fscache_n_cop_put_object;
atomic_t fscache_n_cop_sync_cache;
atomic_t fscache_n_cop_attr_changed;
atomic_t fscache_n_cop_read_or_alloc_page;
atomic_t fscache_n_cop_read_or_alloc_pages;
atomic_t fscache_n_cop_allocate_page;
atomic_t fscache_n_cop_allocate_pages;
atomic_t fscache_n_cop_write_page;
atomic_t fscache_n_cop_uncache_page;
atomic_t fscache_n_cop_dissociate_pages;
/*
* display the general statistics
*/
static int fscache_stats_show(struct seq_file *m, void *v)
{
seq_puts(m, "FS-Cache statistics\n");
seq_printf(m, "Cookies: idx=%u dat=%u spc=%u\n",
atomic_read(&fscache_n_cookie_index),
atomic_read(&fscache_n_cookie_data),
atomic_read(&fscache_n_cookie_special));
seq_printf(m, "Objects: alc=%u nal=%u avl=%u ded=%u\n",
atomic_read(&fscache_n_object_alloc),
atomic_read(&fscache_n_object_no_alloc),
atomic_read(&fscache_n_object_avail),
atomic_read(&fscache_n_object_dead));
seq_printf(m, "ChkAux : non=%u ok=%u upd=%u obs=%u\n",
atomic_read(&fscache_n_checkaux_none),
atomic_read(&fscache_n_checkaux_okay),
atomic_read(&fscache_n_checkaux_update),
atomic_read(&fscache_n_checkaux_obsolete));
seq_printf(m, "Pages : mrk=%u unc=%u\n",
atomic_read(&fscache_n_marks),
atomic_read(&fscache_n_uncaches));
seq_printf(m, "Acquire: n=%u nul=%u noc=%u ok=%u nbf=%u"
" oom=%u\n",
atomic_read(&fscache_n_acquires),
atomic_read(&fscache_n_acquires_null),
atomic_read(&fscache_n_acquires_no_cache),
atomic_read(&fscache_n_acquires_ok),
atomic_read(&fscache_n_acquires_nobufs),
atomic_read(&fscache_n_acquires_oom));
seq_printf(m, "Lookups: n=%u neg=%u pos=%u crt=%u tmo=%u\n",
atomic_read(&fscache_n_object_lookups),
atomic_read(&fscache_n_object_lookups_negative),
atomic_read(&fscache_n_object_lookups_positive),
atomic_read(&fscache_n_object_created),
atomic_read(&fscache_n_object_lookups_timed_out));
seq_printf(m, "Invals : n=%u run=%u\n",
atomic_read(&fscache_n_invalidates),
atomic_read(&fscache_n_invalidates_run));
seq_printf(m, "Updates: n=%u nul=%u run=%u\n",
atomic_read(&fscache_n_updates),
atomic_read(&fscache_n_updates_null),
atomic_read(&fscache_n_updates_run));
seq_printf(m, "Relinqs: n=%u nul=%u wcr=%u rtr=%u\n",
atomic_read(&fscache_n_relinquishes),
atomic_read(&fscache_n_relinquishes_null),
atomic_read(&fscache_n_relinquishes_waitcrt),
atomic_read(&fscache_n_relinquishes_retire));
seq_printf(m, "AttrChg: n=%u ok=%u nbf=%u oom=%u run=%u\n",
atomic_read(&fscache_n_attr_changed),
atomic_read(&fscache_n_attr_changed_ok),
atomic_read(&fscache_n_attr_changed_nobufs),
atomic_read(&fscache_n_attr_changed_nomem),
atomic_read(&fscache_n_attr_changed_calls));
seq_printf(m, "Allocs : n=%u ok=%u wt=%u nbf=%u int=%u\n",
atomic_read(&fscache_n_allocs),
atomic_read(&fscache_n_allocs_ok),
atomic_read(&fscache_n_allocs_wait),
atomic_read(&fscache_n_allocs_nobufs),
atomic_read(&fscache_n_allocs_intr));
seq_printf(m, "Allocs : ops=%u owt=%u abt=%u\n",
atomic_read(&fscache_n_alloc_ops),
atomic_read(&fscache_n_alloc_op_waits),
atomic_read(&fscache_n_allocs_object_dead));
seq_printf(m, "Retrvls: n=%u ok=%u wt=%u nod=%u nbf=%u"
" int=%u oom=%u\n",
atomic_read(&fscache_n_retrievals),
atomic_read(&fscache_n_retrievals_ok),
atomic_read(&fscache_n_retrievals_wait),
atomic_read(&fscache_n_retrievals_nodata),
atomic_read(&fscache_n_retrievals_nobufs),
atomic_read(&fscache_n_retrievals_intr),
atomic_read(&fscache_n_retrievals_nomem));
seq_printf(m, "Retrvls: ops=%u owt=%u abt=%u\n",
atomic_read(&fscache_n_retrieval_ops),
atomic_read(&fscache_n_retrieval_op_waits),
atomic_read(&fscache_n_retrievals_object_dead));
seq_printf(m, "Stores : n=%u ok=%u agn=%u nbf=%u oom=%u\n",
atomic_read(&fscache_n_stores),
atomic_read(&fscache_n_stores_ok),
atomic_read(&fscache_n_stores_again),
atomic_read(&fscache_n_stores_nobufs),
atomic_read(&fscache_n_stores_oom));
seq_printf(m, "Stores : ops=%u run=%u pgs=%u rxd=%u olm=%u\n",
atomic_read(&fscache_n_store_ops),
atomic_read(&fscache_n_store_calls),
atomic_read(&fscache_n_store_pages),
atomic_read(&fscache_n_store_radix_deletes),
atomic_read(&fscache_n_store_pages_over_limit));
seq_printf(m, "VmScan : nos=%u gon=%u bsy=%u can=%u wt=%u\n",
atomic_read(&fscache_n_store_vmscan_not_storing),
atomic_read(&fscache_n_store_vmscan_gone),
atomic_read(&fscache_n_store_vmscan_busy),
atomic_read(&fscache_n_store_vmscan_cancelled),
atomic_read(&fscache_n_store_vmscan_wait));
seq_printf(m, "Ops : pend=%u run=%u enq=%u can=%u rej=%u\n",
atomic_read(&fscache_n_op_pend),
atomic_read(&fscache_n_op_run),
atomic_read(&fscache_n_op_enqueue),
atomic_read(&fscache_n_op_cancelled),
atomic_read(&fscache_n_op_rejected));
seq_printf(m, "Ops : dfr=%u rel=%u gc=%u\n",
atomic_read(&fscache_n_op_deferred_release),
atomic_read(&fscache_n_op_release),
atomic_read(&fscache_n_op_gc));
seq_printf(m, "CacheOp: alo=%d luo=%d luc=%d gro=%d\n",
atomic_read(&fscache_n_cop_alloc_object),
atomic_read(&fscache_n_cop_lookup_object),
atomic_read(&fscache_n_cop_lookup_complete),
atomic_read(&fscache_n_cop_grab_object));
seq_printf(m, "CacheOp: inv=%d upo=%d dro=%d pto=%d atc=%d syn=%d\n",
atomic_read(&fscache_n_cop_invalidate_object),
atomic_read(&fscache_n_cop_update_object),
atomic_read(&fscache_n_cop_drop_object),
atomic_read(&fscache_n_cop_put_object),
atomic_read(&fscache_n_cop_attr_changed),
atomic_read(&fscache_n_cop_sync_cache));
seq_printf(m, "CacheOp: rap=%d ras=%d alp=%d als=%d wrp=%d ucp=%d dsp=%d\n",
atomic_read(&fscache_n_cop_read_or_alloc_page),
atomic_read(&fscache_n_cop_read_or_alloc_pages),
atomic_read(&fscache_n_cop_allocate_page),
atomic_read(&fscache_n_cop_allocate_pages),
atomic_read(&fscache_n_cop_write_page),
atomic_read(&fscache_n_cop_uncache_page),
atomic_read(&fscache_n_cop_dissociate_pages));
return 0;
}
/*
* open "/proc/fs/fscache/stats" allowing provision of a statistical summary
*/
static int fscache_stats_open(struct inode *inode, struct file *file)
{
return single_open(file, fscache_stats_show, NULL);
}
const struct file_operations fscache_stats_fops = {
.owner = THIS_MODULE,
.open = fscache_stats_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
| gpl-2.0 |
CyanogenMod/android_kernel_motorola_msm8226 | drivers/net/ethernet/seeq/seeq8005.c | 4852 | 20596 | /* seeq8005.c: A network driver for linux. */
/*
Based on skeleton.c,
Written 1993-94 by Donald Becker.
See the skeleton.c file for further copyright information.
This software may be used and distributed according to the terms
of the GNU General Public License, incorporated herein by reference.
The author may be reached as hamish@zot.apana.org.au
This file is a network device driver for the SEEQ 8005 chipset and
the Linux operating system.
*/
static const char version[] =
"seeq8005.c:v1.00 8/07/95 Hamish Coleman (hamish@zot.apana.org.au)\n";
/*
Sources:
SEEQ 8005 databook
Version history:
1.00 Public release. cosmetic changes (no warnings now)
0.68 Turning per- packet,interrupt debug messages off - testing for release.
0.67 timing problems/bad buffer reads seem to be fixed now
0.63 *!@$ protocol=eth_type_trans -- now packets flow
0.56 Send working
0.48 Receive working
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/fcntl.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/in.h>
#include <linux/string.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/bitops.h>
#include <linux/jiffies.h>
#include <asm/io.h>
#include <asm/dma.h>
#include "seeq8005.h"
/* First, a few definitions that the brave might change. */
/* A zero-terminated list of I/O addresses to be probed. */
static unsigned int seeq8005_portlist[] __initdata =
{ 0x300, 0x320, 0x340, 0x360, 0};
/* use 0 for production, 1 for verification, >2 for debug */
#ifndef NET_DEBUG
#define NET_DEBUG 1
#endif
static unsigned int net_debug = NET_DEBUG;
/* Information that need to be kept for each board. */
struct net_local {
unsigned short receive_ptr; /* What address in packet memory do we expect a recv_pkt_header? */
long open_time; /* Useless example local info. */
};
/* The station (ethernet) address prefix, used for IDing the board. */
#define SA_ADDR0 0x00
#define SA_ADDR1 0x80
#define SA_ADDR2 0x4b
/* Index to functions, as function prototypes. */
static int seeq8005_probe1(struct net_device *dev, int ioaddr);
static int seeq8005_open(struct net_device *dev);
static void seeq8005_timeout(struct net_device *dev);
static netdev_tx_t seeq8005_send_packet(struct sk_buff *skb,
struct net_device *dev);
static irqreturn_t seeq8005_interrupt(int irq, void *dev_id);
static void seeq8005_rx(struct net_device *dev);
static int seeq8005_close(struct net_device *dev);
static void set_multicast_list(struct net_device *dev);
/* Example routines you must write ;->. */
#define tx_done(dev) (inw(SEEQ_STATUS) & SEEQSTAT_TX_ON)
static void hardware_send_packet(struct net_device *dev, char *buf, int length);
extern void seeq8005_init(struct net_device *dev, int startp);
static inline void wait_for_buffer(struct net_device *dev);
/* Check for a network adaptor of this type, and return '0' iff one exists.
If dev->base_addr == 0, probe all likely locations.
If dev->base_addr == 1, always return failure.
*/
static int io = 0x320;
static int irq = 10;
struct net_device * __init seeq8005_probe(int unit)
{
struct net_device *dev = alloc_etherdev(sizeof(struct net_local));
unsigned *port;
int err = 0;
if (!dev)
return ERR_PTR(-ENODEV);
if (unit >= 0) {
sprintf(dev->name, "eth%d", unit);
netdev_boot_setup_check(dev);
io = dev->base_addr;
irq = dev->irq;
}
if (io > 0x1ff) { /* Check a single specified location. */
err = seeq8005_probe1(dev, io);
} else if (io != 0) { /* Don't probe at all. */
err = -ENXIO;
} else {
for (port = seeq8005_portlist; *port; port++) {
if (seeq8005_probe1(dev, *port) == 0)
break;
}
if (!*port)
err = -ENODEV;
}
if (err)
goto out;
err = register_netdev(dev);
if (err)
goto out1;
return dev;
out1:
release_region(dev->base_addr, SEEQ8005_IO_EXTENT);
out:
free_netdev(dev);
return ERR_PTR(err);
}
static const struct net_device_ops seeq8005_netdev_ops = {
.ndo_open = seeq8005_open,
.ndo_stop = seeq8005_close,
.ndo_start_xmit = seeq8005_send_packet,
.ndo_tx_timeout = seeq8005_timeout,
.ndo_set_rx_mode = set_multicast_list,
.ndo_change_mtu = eth_change_mtu,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
};
/* This is the real probe routine. Linux has a history of friendly device
probes on the ISA bus. A good device probes avoids doing writes, and
verifies that the correct device exists and functions. */
static int __init seeq8005_probe1(struct net_device *dev, int ioaddr)
{
static unsigned version_printed;
int i,j;
unsigned char SA_prom[32];
int old_cfg1;
int old_cfg2;
int old_stat;
int old_dmaar;
int old_rear;
int retval;
if (!request_region(ioaddr, SEEQ8005_IO_EXTENT, "seeq8005"))
return -ENODEV;
if (net_debug>1)
printk("seeq8005: probing at 0x%x\n",ioaddr);
old_stat = inw(SEEQ_STATUS); /* read status register */
if (old_stat == 0xffff) {
retval = -ENODEV;
goto out; /* assume that 0xffff == no device */
}
if ( (old_stat & 0x1800) != 0x1800 ) { /* assume that unused bits are 1, as my manual says */
if (net_debug>1) {
printk("seeq8005: reserved stat bits != 0x1800\n");
printk(" == 0x%04x\n",old_stat);
}
retval = -ENODEV;
goto out;
}
old_rear = inw(SEEQ_REA);
if (old_rear == 0xffff) {
outw(0,SEEQ_REA);
if (inw(SEEQ_REA) == 0xffff) { /* assume that 0xffff == no device */
retval = -ENODEV;
goto out;
}
} else if ((old_rear & 0xff00) != 0xff00) { /* assume that unused bits are 1 */
if (net_debug>1) {
printk("seeq8005: unused rear bits != 0xff00\n");
printk(" == 0x%04x\n",old_rear);
}
retval = -ENODEV;
goto out;
}
old_cfg2 = inw(SEEQ_CFG2); /* read CFG2 register */
old_cfg1 = inw(SEEQ_CFG1);
old_dmaar = inw(SEEQ_DMAAR);
if (net_debug>4) {
printk("seeq8005: stat = 0x%04x\n",old_stat);
printk("seeq8005: cfg1 = 0x%04x\n",old_cfg1);
printk("seeq8005: cfg2 = 0x%04x\n",old_cfg2);
printk("seeq8005: raer = 0x%04x\n",old_rear);
printk("seeq8005: dmaar= 0x%04x\n",old_dmaar);
}
outw( SEEQCMD_FIFO_WRITE | SEEQCMD_SET_ALL_OFF, SEEQ_CMD); /* setup for reading PROM */
outw( 0, SEEQ_DMAAR); /* set starting PROM address */
outw( SEEQCFG1_BUFFER_PROM, SEEQ_CFG1); /* set buffer to look at PROM */
j=0;
for(i=0; i <32; i++) {
j+= SA_prom[i] = inw(SEEQ_BUFFER) & 0xff;
}
#if 0
/* untested because I only have the one card */
if ( (j&0xff) != 0 ) { /* checksum appears to be 8bit = 0 */
if (net_debug>1) { /* check this before deciding that we have a card */
printk("seeq8005: prom sum error\n");
}
outw( old_stat, SEEQ_STATUS);
outw( old_dmaar, SEEQ_DMAAR);
outw( old_cfg1, SEEQ_CFG1);
retval = -ENODEV;
goto out;
}
#endif
outw( SEEQCFG2_RESET, SEEQ_CFG2); /* reset the card */
udelay(5);
outw( SEEQCMD_SET_ALL_OFF, SEEQ_CMD);
if (net_debug) {
printk("seeq8005: prom sum = 0x%08x\n",j);
for(j=0; j<32; j+=16) {
printk("seeq8005: prom %02x: ",j);
for(i=0;i<16;i++) {
printk("%02x ",SA_prom[j|i]);
}
printk(" ");
for(i=0;i<16;i++) {
if ((SA_prom[j|i]>31)&&(SA_prom[j|i]<127)) {
printk("%c", SA_prom[j|i]);
} else {
printk(" ");
}
}
printk("\n");
}
}
#if 0
/*
* testing the packet buffer memory doesn't work yet
* but all other buffer accesses do
* - fixing is not a priority
*/
if (net_debug>1) { /* test packet buffer memory */
printk("seeq8005: testing packet buffer ... ");
outw( SEEQCFG1_BUFFER_BUFFER, SEEQ_CFG1);
outw( SEEQCMD_FIFO_WRITE | SEEQCMD_SET_ALL_OFF, SEEQ_CMD);
outw( 0 , SEEQ_DMAAR);
for(i=0;i<32768;i++) {
outw(0x5a5a, SEEQ_BUFFER);
}
j=jiffies+HZ;
while ( ((inw(SEEQ_STATUS) & SEEQSTAT_FIFO_EMPTY) != SEEQSTAT_FIFO_EMPTY) && time_before(jiffies, j) )
mb();
outw( 0 , SEEQ_DMAAR);
while ( ((inw(SEEQ_STATUS) & SEEQSTAT_WINDOW_INT) != SEEQSTAT_WINDOW_INT) && time_before(jiffies, j+HZ))
mb();
if ( (inw(SEEQ_STATUS) & SEEQSTAT_WINDOW_INT) == SEEQSTAT_WINDOW_INT)
outw( SEEQCMD_WINDOW_INT_ACK | (inw(SEEQ_STATUS)& SEEQCMD_INT_MASK), SEEQ_CMD);
outw( SEEQCMD_FIFO_READ | SEEQCMD_SET_ALL_OFF, SEEQ_CMD);
j=0;
for(i=0;i<32768;i++) {
if (inw(SEEQ_BUFFER) != 0x5a5a)
j++;
}
if (j) {
printk("%i\n",j);
} else {
printk("ok.\n");
}
}
#endif
if (net_debug && version_printed++ == 0)
printk(version);
printk("%s: %s found at %#3x, ", dev->name, "seeq8005", ioaddr);
/* Fill in the 'dev' fields. */
dev->base_addr = ioaddr;
dev->irq = irq;
/* Retrieve and print the ethernet address. */
for (i = 0; i < 6; i++)
dev->dev_addr[i] = SA_prom[i+6];
printk("%pM", dev->dev_addr);
if (dev->irq == 0xff)
; /* Do nothing: a user-level program will set it. */
else if (dev->irq < 2) { /* "Auto-IRQ" */
unsigned long cookie = probe_irq_on();
outw( SEEQCMD_RX_INT_EN | SEEQCMD_SET_RX_ON | SEEQCMD_SET_RX_OFF, SEEQ_CMD );
dev->irq = probe_irq_off(cookie);
if (net_debug >= 2)
printk(" autoirq is %d\n", dev->irq);
} else if (dev->irq == 2)
/* Fixup for users that don't know that IRQ 2 is really IRQ 9,
* or don't know which one to set.
*/
dev->irq = 9;
#if 0
{
int irqval = request_irq(dev->irq, seeq8005_interrupt, 0, "seeq8005", dev);
if (irqval) {
printk ("%s: unable to get IRQ %d (irqval=%d).\n", dev->name,
dev->irq, irqval);
retval = -EAGAIN;
goto out;
}
}
#endif
dev->netdev_ops = &seeq8005_netdev_ops;
dev->watchdog_timeo = HZ/20;
dev->flags &= ~IFF_MULTICAST;
return 0;
out:
release_region(ioaddr, SEEQ8005_IO_EXTENT);
return retval;
}
/* Open/initialize the board. This is called (in the current kernel)
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 seeq8005_open(struct net_device *dev)
{
struct net_local *lp = netdev_priv(dev);
{
int irqval = request_irq(dev->irq, seeq8005_interrupt, 0, "seeq8005", dev);
if (irqval) {
printk ("%s: unable to get IRQ %d (irqval=%d).\n", dev->name,
dev->irq, irqval);
return -EAGAIN;
}
}
/* Reset the hardware here. Don't forget to set the station address. */
seeq8005_init(dev, 1);
lp->open_time = jiffies;
netif_start_queue(dev);
return 0;
}
static void seeq8005_timeout(struct net_device *dev)
{
int ioaddr = dev->base_addr;
printk(KERN_WARNING "%s: transmit timed out, %s?\n", dev->name,
tx_done(dev) ? "IRQ conflict" : "network cable problem");
/* Try to restart the adaptor. */
seeq8005_init(dev, 1);
dev->trans_start = jiffies; /* prevent tx timeout */
netif_wake_queue(dev);
}
static netdev_tx_t seeq8005_send_packet(struct sk_buff *skb,
struct net_device *dev)
{
short length = skb->len;
unsigned char *buf;
if (length < ETH_ZLEN) {
if (skb_padto(skb, ETH_ZLEN))
return NETDEV_TX_OK;
length = ETH_ZLEN;
}
buf = skb->data;
/* Block a timer-based transmit from overlapping */
netif_stop_queue(dev);
hardware_send_packet(dev, buf, length);
dev->stats.tx_bytes += length;
dev_kfree_skb (skb);
/* You might need to clean up and record Tx statistics here. */
return NETDEV_TX_OK;
}
/*
* wait_for_buffer
*
* This routine waits for the SEEQ chip to assert that the FIFO is ready
* by checking for a window interrupt, and then clearing it. This has to
* occur in the interrupt handler!
*/
inline void wait_for_buffer(struct net_device * dev)
{
int ioaddr = dev->base_addr;
unsigned long tmp;
int status;
tmp = jiffies + HZ;
while ( ( ((status=inw(SEEQ_STATUS)) & SEEQSTAT_WINDOW_INT) != SEEQSTAT_WINDOW_INT) && time_before(jiffies, tmp))
cpu_relax();
if ( (status & SEEQSTAT_WINDOW_INT) == SEEQSTAT_WINDOW_INT)
outw( SEEQCMD_WINDOW_INT_ACK | (status & SEEQCMD_INT_MASK), SEEQ_CMD);
}
/* The typical workload of the driver:
Handle the network interface interrupts. */
static irqreturn_t seeq8005_interrupt(int irq, void *dev_id)
{
struct net_device *dev = dev_id;
struct net_local *lp;
int ioaddr, status, boguscount = 0;
int handled = 0;
ioaddr = dev->base_addr;
lp = netdev_priv(dev);
status = inw(SEEQ_STATUS);
do {
if (net_debug >2) {
printk("%s: int, status=0x%04x\n",dev->name,status);
}
if (status & SEEQSTAT_WINDOW_INT) {
handled = 1;
outw( SEEQCMD_WINDOW_INT_ACK | (status & SEEQCMD_INT_MASK), SEEQ_CMD);
if (net_debug) {
printk("%s: window int!\n",dev->name);
}
}
if (status & SEEQSTAT_TX_INT) {
handled = 1;
outw( SEEQCMD_TX_INT_ACK | (status & SEEQCMD_INT_MASK), SEEQ_CMD);
dev->stats.tx_packets++;
netif_wake_queue(dev); /* Inform upper layers. */
}
if (status & SEEQSTAT_RX_INT) {
handled = 1;
/* Got a packet(s). */
seeq8005_rx(dev);
}
status = inw(SEEQ_STATUS);
} while ( (++boguscount < 10) && (status & SEEQSTAT_ANY_INT)) ;
if(net_debug>2) {
printk("%s: eoi\n",dev->name);
}
return IRQ_RETVAL(handled);
}
/* We have a good packet(s), get it/them out of the buffers. */
static void seeq8005_rx(struct net_device *dev)
{
struct net_local *lp = netdev_priv(dev);
int boguscount = 10;
int pkt_hdr;
int ioaddr = dev->base_addr;
do {
int next_packet;
int pkt_len;
int i;
int status;
status = inw(SEEQ_STATUS);
outw( lp->receive_ptr, SEEQ_DMAAR);
outw(SEEQCMD_FIFO_READ | SEEQCMD_RX_INT_ACK | (status & SEEQCMD_INT_MASK), SEEQ_CMD);
wait_for_buffer(dev);
next_packet = ntohs(inw(SEEQ_BUFFER));
pkt_hdr = inw(SEEQ_BUFFER);
if (net_debug>2) {
printk("%s: 0x%04x recv next=0x%04x, hdr=0x%04x\n",dev->name,lp->receive_ptr,next_packet,pkt_hdr);
}
if ((next_packet == 0) || ((pkt_hdr & SEEQPKTH_CHAIN)==0)) { /* Read all the frames? */
return; /* Done for now */
}
if ((pkt_hdr & SEEQPKTS_DONE)==0)
break;
if (next_packet < lp->receive_ptr) {
pkt_len = (next_packet + 0x10000 - ((DEFAULT_TEA+1)<<8)) - lp->receive_ptr - 4;
} else {
pkt_len = next_packet - lp->receive_ptr - 4;
}
if (next_packet < ((DEFAULT_TEA+1)<<8)) { /* is the next_packet address sane? */
printk("%s: recv packet ring corrupt, resetting board\n",dev->name);
seeq8005_init(dev,1);
return;
}
lp->receive_ptr = next_packet;
if (net_debug>2) {
printk("%s: recv len=0x%04x\n",dev->name,pkt_len);
}
if (pkt_hdr & SEEQPKTS_ANY_ERROR) { /* There was an error. */
dev->stats.rx_errors++;
if (pkt_hdr & SEEQPKTS_SHORT) dev->stats.rx_frame_errors++;
if (pkt_hdr & SEEQPKTS_DRIB) dev->stats.rx_frame_errors++;
if (pkt_hdr & SEEQPKTS_OVERSIZE) dev->stats.rx_over_errors++;
if (pkt_hdr & SEEQPKTS_CRC_ERR) dev->stats.rx_crc_errors++;
/* skip over this packet */
outw( SEEQCMD_FIFO_WRITE | SEEQCMD_DMA_INT_ACK | (status & SEEQCMD_INT_MASK), SEEQ_CMD);
outw( (lp->receive_ptr & 0xff00)>>8, SEEQ_REA);
} else {
/* Malloc up new buffer. */
struct sk_buff *skb;
unsigned char *buf;
skb = netdev_alloc_skb(dev, pkt_len);
if (skb == NULL) {
printk("%s: Memory squeeze, dropping packet.\n", dev->name);
dev->stats.rx_dropped++;
break;
}
skb_reserve(skb, 2); /* align data on 16 byte */
buf = skb_put(skb,pkt_len);
insw(SEEQ_BUFFER, buf, (pkt_len + 1) >> 1);
if (net_debug>2) {
char * p = buf;
printk("%s: recv ",dev->name);
for(i=0;i<14;i++) {
printk("%02x ",*(p++)&0xff);
}
printk("\n");
}
skb->protocol=eth_type_trans(skb,dev);
netif_rx(skb);
dev->stats.rx_packets++;
dev->stats.rx_bytes += pkt_len;
}
} while ((--boguscount) && (pkt_hdr & SEEQPKTH_CHAIN));
/* If any worth-while packets have been received, netif_rx()
has done a mark_bh(NET_BH) for us and will work on them
when we get to the bottom-half routine. */
}
/* The inverse routine to net_open(). */
static int seeq8005_close(struct net_device *dev)
{
struct net_local *lp = netdev_priv(dev);
int ioaddr = dev->base_addr;
lp->open_time = 0;
netif_stop_queue(dev);
/* Flush the Tx and disable Rx here. */
outw( SEEQCMD_SET_ALL_OFF, SEEQ_CMD);
free_irq(dev->irq, dev);
/* Update the statistics here. */
return 0;
}
/* Set or clear the multicast filter for this adaptor.
num_addrs == -1 Promiscuous mode, receive all packets
num_addrs == 0 Normal mode, clear multicast list
num_addrs > 0 Multicast mode, receive normal and MC packets, and do
best-effort filtering.
*/
static void set_multicast_list(struct net_device *dev)
{
/*
* I _could_ do up to 6 addresses here, but won't (yet?)
*/
#if 0
int ioaddr = dev->base_addr;
/*
* hmm, not even sure if my matching works _anyway_ - seem to be receiving
* _everything_ . . .
*/
if (num_addrs) { /* Enable promiscuous mode */
outw( (inw(SEEQ_CFG1) & ~SEEQCFG1_MATCH_MASK)| SEEQCFG1_MATCH_ALL, SEEQ_CFG1);
dev->flags|=IFF_PROMISC;
} else { /* Disable promiscuous mode, use normal mode */
outw( (inw(SEEQ_CFG1) & ~SEEQCFG1_MATCH_MASK)| SEEQCFG1_MATCH_BROAD, SEEQ_CFG1);
}
#endif
}
void seeq8005_init(struct net_device *dev, int startp)
{
struct net_local *lp = netdev_priv(dev);
int ioaddr = dev->base_addr;
int i;
outw(SEEQCFG2_RESET, SEEQ_CFG2); /* reset device */
udelay(5);
outw( SEEQCMD_FIFO_WRITE | SEEQCMD_SET_ALL_OFF, SEEQ_CMD);
outw( 0, SEEQ_DMAAR); /* load start address into both low and high byte */
/* wait_for_buffer(dev); */ /* I think that you only need a wait for memory buffer */
outw( SEEQCFG1_BUFFER_MAC0, SEEQ_CFG1);
for(i=0;i<6;i++) { /* set Station address */
outb(dev->dev_addr[i], SEEQ_BUFFER);
udelay(2);
}
outw( SEEQCFG1_BUFFER_TEA, SEEQ_CFG1); /* set xmit end area pointer to 16K */
outb( DEFAULT_TEA, SEEQ_BUFFER); /* this gives us 16K of send buffer and 48K of recv buffer */
lp->receive_ptr = (DEFAULT_TEA+1)<<8; /* so we can find our packet_header */
outw( lp->receive_ptr, SEEQ_RPR); /* Receive Pointer Register is set to recv buffer memory */
outw( 0x00ff, SEEQ_REA); /* Receive Area End */
if (net_debug>4) {
printk("%s: SA0 = ",dev->name);
outw( SEEQCMD_FIFO_READ | SEEQCMD_SET_ALL_OFF, SEEQ_CMD);
outw( 0, SEEQ_DMAAR);
outw( SEEQCFG1_BUFFER_MAC0, SEEQ_CFG1);
for(i=0;i<6;i++) {
printk("%02x ",inb(SEEQ_BUFFER));
}
printk("\n");
}
outw( SEEQCFG1_MAC0_EN | SEEQCFG1_MATCH_BROAD | SEEQCFG1_BUFFER_BUFFER, SEEQ_CFG1);
outw( SEEQCFG2_AUTO_REA | SEEQCFG2_CTRLO, SEEQ_CFG2);
outw( SEEQCMD_SET_RX_ON | SEEQCMD_TX_INT_EN | SEEQCMD_RX_INT_EN, SEEQ_CMD);
if (net_debug>4) {
int old_cfg1;
old_cfg1 = inw(SEEQ_CFG1);
printk("%s: stat = 0x%04x\n",dev->name,inw(SEEQ_STATUS));
printk("%s: cfg1 = 0x%04x\n",dev->name,old_cfg1);
printk("%s: cfg2 = 0x%04x\n",dev->name,inw(SEEQ_CFG2));
printk("%s: raer = 0x%04x\n",dev->name,inw(SEEQ_REA));
printk("%s: dmaar= 0x%04x\n",dev->name,inw(SEEQ_DMAAR));
}
}
static void hardware_send_packet(struct net_device * dev, char *buf, int length)
{
int ioaddr = dev->base_addr;
int status = inw(SEEQ_STATUS);
int transmit_ptr = 0;
unsigned long tmp;
if (net_debug>4) {
printk("%s: send 0x%04x\n",dev->name,length);
}
/* Set FIFO to writemode and set packet-buffer address */
outw( SEEQCMD_FIFO_WRITE | (status & SEEQCMD_INT_MASK), SEEQ_CMD);
outw( transmit_ptr, SEEQ_DMAAR);
/* output SEEQ Packet header barfage */
outw( htons(length + 4), SEEQ_BUFFER);
outw( SEEQPKTH_XMIT | SEEQPKTH_DATA_FOLLOWS | SEEQPKTH_XMIT_INT_EN, SEEQ_BUFFER );
/* blat the buffer */
outsw( SEEQ_BUFFER, buf, (length +1) >> 1);
/* paranoia !! */
outw( 0, SEEQ_BUFFER);
outw( 0, SEEQ_BUFFER);
/* set address of start of transmit chain */
outw( transmit_ptr, SEEQ_TPR);
/* drain FIFO */
tmp = jiffies;
while ( (((status=inw(SEEQ_STATUS)) & SEEQSTAT_FIFO_EMPTY) == 0) && time_before(jiffies, tmp + HZ))
mb();
/* doit ! */
outw( SEEQCMD_WINDOW_INT_ACK | SEEQCMD_SET_TX_ON | (status & SEEQCMD_INT_MASK), SEEQ_CMD);
}
#ifdef MODULE
static struct net_device *dev_seeq;
MODULE_LICENSE("GPL");
module_param(io, int, 0);
module_param(irq, int, 0);
MODULE_PARM_DESC(io, "SEEQ 8005 I/O base address");
MODULE_PARM_DESC(irq, "SEEQ 8005 IRQ number");
int __init init_module(void)
{
dev_seeq = seeq8005_probe(-1);
if (IS_ERR(dev_seeq))
return PTR_ERR(dev_seeq);
return 0;
}
void __exit cleanup_module(void)
{
unregister_netdev(dev_seeq);
release_region(dev_seeq->base_addr, SEEQ8005_IO_EXTENT);
free_netdev(dev_seeq);
}
#endif /* MODULE */
| gpl-2.0 |
hellobbn/android_kernel_htc_msm8974 | drivers/gpu/drm/drm_pci.c | 4852 | 11907 | /* drm_pci.h -- PCI DMA memory management wrappers for DRM -*- linux-c -*- */
/**
* \file drm_pci.c
* \brief Functions and ioctls to manage PCI memory
*
* \warning These interfaces aren't stable yet.
*
* \todo Implement the remaining ioctl's for the PCI pools.
* \todo The wrappers here are so thin that they would be better off inlined..
*
* \author José Fonseca <jrfonseca@tungstengraphics.com>
* \author Leif Delgass <ldelgass@retinalburn.net>
*/
/*
* Copyright 2003 José Fonseca.
* Copyright 2003 Leif Delgass.
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS 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/pci.h>
#include <linux/slab.h>
#include <linux/dma-mapping.h>
#include <linux/export.h>
#include "drmP.h"
/**********************************************************************/
/** \name PCI memory */
/*@{*/
/**
* \brief Allocate a PCI consistent memory block, for DMA.
*/
drm_dma_handle_t *drm_pci_alloc(struct drm_device * dev, size_t size, size_t align)
{
drm_dma_handle_t *dmah;
#if 1
unsigned long addr;
size_t sz;
#endif
/* pci_alloc_consistent only guarantees alignment to the smallest
* PAGE_SIZE order which is greater than or equal to the requested size.
* Return NULL here for now to make sure nobody tries for larger alignment
*/
if (align > size)
return NULL;
dmah = kmalloc(sizeof(drm_dma_handle_t), GFP_KERNEL);
if (!dmah)
return NULL;
dmah->size = size;
dmah->vaddr = dma_alloc_coherent(&dev->pdev->dev, size, &dmah->busaddr, GFP_KERNEL | __GFP_COMP);
if (dmah->vaddr == NULL) {
kfree(dmah);
return NULL;
}
memset(dmah->vaddr, 0, size);
/* XXX - Is virt_to_page() legal for consistent mem? */
/* Reserve */
for (addr = (unsigned long)dmah->vaddr, sz = size;
sz > 0; addr += PAGE_SIZE, sz -= PAGE_SIZE) {
SetPageReserved(virt_to_page(addr));
}
return dmah;
}
EXPORT_SYMBOL(drm_pci_alloc);
/**
* \brief Free a PCI consistent memory block without freeing its descriptor.
*
* This function is for internal use in the Linux-specific DRM core code.
*/
void __drm_pci_free(struct drm_device * dev, drm_dma_handle_t * dmah)
{
#if 1
unsigned long addr;
size_t sz;
#endif
if (dmah->vaddr) {
/* XXX - Is virt_to_page() legal for consistent mem? */
/* Unreserve */
for (addr = (unsigned long)dmah->vaddr, sz = dmah->size;
sz > 0; addr += PAGE_SIZE, sz -= PAGE_SIZE) {
ClearPageReserved(virt_to_page(addr));
}
dma_free_coherent(&dev->pdev->dev, dmah->size, dmah->vaddr,
dmah->busaddr);
}
}
/**
* \brief Free a PCI consistent memory block
*/
void drm_pci_free(struct drm_device * dev, drm_dma_handle_t * dmah)
{
__drm_pci_free(dev, dmah);
kfree(dmah);
}
EXPORT_SYMBOL(drm_pci_free);
#ifdef CONFIG_PCI
static int drm_get_pci_domain(struct drm_device *dev)
{
#ifndef __alpha__
/* For historical reasons, drm_get_pci_domain() is busticated
* on most archs and has to remain so for userspace interface
* < 1.4, except on alpha which was right from the beginning
*/
if (dev->if_version < 0x10004)
return 0;
#endif /* __alpha__ */
return pci_domain_nr(dev->pdev->bus);
}
static int drm_pci_get_irq(struct drm_device *dev)
{
return dev->pdev->irq;
}
static const char *drm_pci_get_name(struct drm_device *dev)
{
struct pci_driver *pdriver = dev->driver->kdriver.pci;
return pdriver->name;
}
int drm_pci_set_busid(struct drm_device *dev, struct drm_master *master)
{
int len, ret;
struct pci_driver *pdriver = dev->driver->kdriver.pci;
master->unique_len = 40;
master->unique_size = master->unique_len;
master->unique = kmalloc(master->unique_size, GFP_KERNEL);
if (master->unique == NULL)
return -ENOMEM;
len = snprintf(master->unique, master->unique_len,
"pci:%04x:%02x:%02x.%d",
drm_get_pci_domain(dev),
dev->pdev->bus->number,
PCI_SLOT(dev->pdev->devfn),
PCI_FUNC(dev->pdev->devfn));
if (len >= master->unique_len) {
DRM_ERROR("buffer overflow");
ret = -EINVAL;
goto err;
} else
master->unique_len = len;
dev->devname =
kmalloc(strlen(pdriver->name) +
master->unique_len + 2, GFP_KERNEL);
if (dev->devname == NULL) {
ret = -ENOMEM;
goto err;
}
sprintf(dev->devname, "%s@%s", pdriver->name,
master->unique);
return 0;
err:
return ret;
}
int drm_pci_set_unique(struct drm_device *dev,
struct drm_master *master,
struct drm_unique *u)
{
int domain, bus, slot, func, ret;
const char *bus_name;
master->unique_len = u->unique_len;
master->unique_size = u->unique_len + 1;
master->unique = kmalloc(master->unique_size, GFP_KERNEL);
if (!master->unique) {
ret = -ENOMEM;
goto err;
}
if (copy_from_user(master->unique, u->unique, master->unique_len)) {
ret = -EFAULT;
goto err;
}
master->unique[master->unique_len] = '\0';
bus_name = dev->driver->bus->get_name(dev);
dev->devname = kmalloc(strlen(bus_name) +
strlen(master->unique) + 2, GFP_KERNEL);
if (!dev->devname) {
ret = -ENOMEM;
goto err;
}
sprintf(dev->devname, "%s@%s", bus_name,
master->unique);
/* Return error if the busid submitted doesn't match the device's actual
* busid.
*/
ret = sscanf(master->unique, "PCI:%d:%d:%d", &bus, &slot, &func);
if (ret != 3) {
ret = -EINVAL;
goto err;
}
domain = bus >> 8;
bus &= 0xff;
if ((domain != drm_get_pci_domain(dev)) ||
(bus != dev->pdev->bus->number) ||
(slot != PCI_SLOT(dev->pdev->devfn)) ||
(func != PCI_FUNC(dev->pdev->devfn))) {
ret = -EINVAL;
goto err;
}
return 0;
err:
return ret;
}
static int drm_pci_irq_by_busid(struct drm_device *dev, struct drm_irq_busid *p)
{
if ((p->busnum >> 8) != drm_get_pci_domain(dev) ||
(p->busnum & 0xff) != dev->pdev->bus->number ||
p->devnum != PCI_SLOT(dev->pdev->devfn) || p->funcnum != PCI_FUNC(dev->pdev->devfn))
return -EINVAL;
p->irq = dev->pdev->irq;
DRM_DEBUG("%d:%d:%d => IRQ %d\n", p->busnum, p->devnum, p->funcnum,
p->irq);
return 0;
}
int drm_pci_agp_init(struct drm_device *dev)
{
if (drm_core_has_AGP(dev)) {
if (drm_pci_device_is_agp(dev))
dev->agp = drm_agp_init(dev);
if (drm_core_check_feature(dev, DRIVER_REQUIRE_AGP)
&& (dev->agp == NULL)) {
DRM_ERROR("Cannot initialize the agpgart module.\n");
return -EINVAL;
}
if (drm_core_has_MTRR(dev)) {
if (dev->agp)
dev->agp->agp_mtrr =
mtrr_add(dev->agp->agp_info.aper_base,
dev->agp->agp_info.aper_size *
1024 * 1024, MTRR_TYPE_WRCOMB, 1);
}
}
return 0;
}
static struct drm_bus drm_pci_bus = {
.bus_type = DRIVER_BUS_PCI,
.get_irq = drm_pci_get_irq,
.get_name = drm_pci_get_name,
.set_busid = drm_pci_set_busid,
.set_unique = drm_pci_set_unique,
.irq_by_busid = drm_pci_irq_by_busid,
.agp_init = drm_pci_agp_init,
};
/**
* Register.
*
* \param pdev - PCI device structure
* \param ent entry from the PCI ID table with device type flags
* \return zero on success or a negative number on failure.
*
* Attempt to gets inter module "drm" information. If we are first
* then register the character device and inter module information.
* Try and register, if we fail to register, backout previous work.
*/
int drm_get_pci_dev(struct pci_dev *pdev, const struct pci_device_id *ent,
struct drm_driver *driver)
{
struct drm_device *dev;
int ret;
DRM_DEBUG("\n");
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev)
return -ENOMEM;
ret = pci_enable_device(pdev);
if (ret)
goto err_g1;
dev->pdev = pdev;
dev->dev = &pdev->dev;
dev->pci_device = pdev->device;
dev->pci_vendor = pdev->vendor;
#ifdef __alpha__
dev->hose = pdev->sysdata;
#endif
mutex_lock(&drm_global_mutex);
if ((ret = drm_fill_in_dev(dev, ent, driver))) {
printk(KERN_ERR "DRM: Fill_in_dev failed.\n");
goto err_g2;
}
if (drm_core_check_feature(dev, DRIVER_MODESET)) {
pci_set_drvdata(pdev, dev);
ret = drm_get_minor(dev, &dev->control, DRM_MINOR_CONTROL);
if (ret)
goto err_g2;
}
if ((ret = drm_get_minor(dev, &dev->primary, DRM_MINOR_LEGACY)))
goto err_g3;
if (dev->driver->load) {
ret = dev->driver->load(dev, ent->driver_data);
if (ret)
goto err_g4;
}
/* setup the grouping for the legacy output */
if (drm_core_check_feature(dev, DRIVER_MODESET)) {
ret = drm_mode_group_init_legacy_group(dev,
&dev->primary->mode_group);
if (ret)
goto err_g4;
}
list_add_tail(&dev->driver_item, &driver->device_list);
DRM_INFO("Initialized %s %d.%d.%d %s for %s on minor %d\n",
driver->name, driver->major, driver->minor, driver->patchlevel,
driver->date, pci_name(pdev), dev->primary->index);
mutex_unlock(&drm_global_mutex);
return 0;
err_g4:
drm_put_minor(&dev->primary);
err_g3:
if (drm_core_check_feature(dev, DRIVER_MODESET))
drm_put_minor(&dev->control);
err_g2:
pci_disable_device(pdev);
err_g1:
kfree(dev);
mutex_unlock(&drm_global_mutex);
return ret;
}
EXPORT_SYMBOL(drm_get_pci_dev);
/**
* PCI device initialization. Called direct from modules at load time.
*
* \return zero on success or a negative number on failure.
*
* Initializes a drm_device structures,registering the
* stubs and initializing the AGP device.
*
* Expands the \c DRIVER_PREINIT and \c DRIVER_POST_INIT macros before and
* after the initialization for driver customization.
*/
int drm_pci_init(struct drm_driver *driver, struct pci_driver *pdriver)
{
struct pci_dev *pdev = NULL;
const struct pci_device_id *pid;
int i;
DRM_DEBUG("\n");
INIT_LIST_HEAD(&driver->device_list);
driver->kdriver.pci = pdriver;
driver->bus = &drm_pci_bus;
if (driver->driver_features & DRIVER_MODESET)
return pci_register_driver(pdriver);
/* If not using KMS, fall back to stealth mode manual scanning. */
for (i = 0; pdriver->id_table[i].vendor != 0; i++) {
pid = &pdriver->id_table[i];
/* Loop around setting up a DRM device for each PCI device
* matching our ID and device class. If we had the internal
* function that pci_get_subsys and pci_get_class used, we'd
* be able to just pass pid in instead of doing a two-stage
* thing.
*/
pdev = NULL;
while ((pdev =
pci_get_subsys(pid->vendor, pid->device, pid->subvendor,
pid->subdevice, pdev)) != NULL) {
if ((pdev->class & pid->class_mask) != pid->class)
continue;
/* stealth mode requires a manual probe */
pci_dev_get(pdev);
drm_get_pci_dev(pdev, pid, driver);
}
}
return 0;
}
#else
int drm_pci_init(struct drm_driver *driver, struct pci_driver *pdriver)
{
return -1;
}
#endif
EXPORT_SYMBOL(drm_pci_init);
/*@}*/
void drm_pci_exit(struct drm_driver *driver, struct pci_driver *pdriver)
{
struct drm_device *dev, *tmp;
DRM_DEBUG("\n");
if (driver->driver_features & DRIVER_MODESET) {
pci_unregister_driver(pdriver);
} else {
list_for_each_entry_safe(dev, tmp, &driver->device_list, driver_item)
drm_put_dev(dev);
}
DRM_INFO("Module unloaded\n");
}
EXPORT_SYMBOL(drm_pci_exit);
| gpl-2.0 |
MrStaticVoid/kernel_m8 | drivers/media/video/omap3isp/ispccdc.c | 4852 | 65255 | /*
* ispccdc.c
*
* TI OMAP3 ISP - CCDC module
*
* Copyright (C) 2009-2010 Nokia Corporation
* Copyright (C) 2009 Texas Instruments, Inc.
*
* Contacts: Laurent Pinchart <laurent.pinchart@ideasonboard.com>
* Sakari Ailus <sakari.ailus@iki.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include <linux/module.h>
#include <linux/uaccess.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/dma-mapping.h>
#include <linux/mm.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <media/v4l2-event.h>
#include "isp.h"
#include "ispreg.h"
#include "ispccdc.h"
static struct v4l2_mbus_framefmt *
__ccdc_get_format(struct isp_ccdc_device *ccdc, struct v4l2_subdev_fh *fh,
unsigned int pad, enum v4l2_subdev_format_whence which);
static const unsigned int ccdc_fmts[] = {
V4L2_MBUS_FMT_Y8_1X8,
V4L2_MBUS_FMT_Y10_1X10,
V4L2_MBUS_FMT_Y12_1X12,
V4L2_MBUS_FMT_SGRBG8_1X8,
V4L2_MBUS_FMT_SRGGB8_1X8,
V4L2_MBUS_FMT_SBGGR8_1X8,
V4L2_MBUS_FMT_SGBRG8_1X8,
V4L2_MBUS_FMT_SGRBG10_1X10,
V4L2_MBUS_FMT_SRGGB10_1X10,
V4L2_MBUS_FMT_SBGGR10_1X10,
V4L2_MBUS_FMT_SGBRG10_1X10,
V4L2_MBUS_FMT_SGRBG12_1X12,
V4L2_MBUS_FMT_SRGGB12_1X12,
V4L2_MBUS_FMT_SBGGR12_1X12,
V4L2_MBUS_FMT_SGBRG12_1X12,
};
/*
* ccdc_print_status - Print current CCDC Module register values.
* @ccdc: Pointer to ISP CCDC device.
*
* Also prints other debug information stored in the CCDC module.
*/
#define CCDC_PRINT_REGISTER(isp, name)\
dev_dbg(isp->dev, "###CCDC " #name "=0x%08x\n", \
isp_reg_readl(isp, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_##name))
static void ccdc_print_status(struct isp_ccdc_device *ccdc)
{
struct isp_device *isp = to_isp_device(ccdc);
dev_dbg(isp->dev, "-------------CCDC Register dump-------------\n");
CCDC_PRINT_REGISTER(isp, PCR);
CCDC_PRINT_REGISTER(isp, SYN_MODE);
CCDC_PRINT_REGISTER(isp, HD_VD_WID);
CCDC_PRINT_REGISTER(isp, PIX_LINES);
CCDC_PRINT_REGISTER(isp, HORZ_INFO);
CCDC_PRINT_REGISTER(isp, VERT_START);
CCDC_PRINT_REGISTER(isp, VERT_LINES);
CCDC_PRINT_REGISTER(isp, CULLING);
CCDC_PRINT_REGISTER(isp, HSIZE_OFF);
CCDC_PRINT_REGISTER(isp, SDOFST);
CCDC_PRINT_REGISTER(isp, SDR_ADDR);
CCDC_PRINT_REGISTER(isp, CLAMP);
CCDC_PRINT_REGISTER(isp, DCSUB);
CCDC_PRINT_REGISTER(isp, COLPTN);
CCDC_PRINT_REGISTER(isp, BLKCMP);
CCDC_PRINT_REGISTER(isp, FPC);
CCDC_PRINT_REGISTER(isp, FPC_ADDR);
CCDC_PRINT_REGISTER(isp, VDINT);
CCDC_PRINT_REGISTER(isp, ALAW);
CCDC_PRINT_REGISTER(isp, REC656IF);
CCDC_PRINT_REGISTER(isp, CFG);
CCDC_PRINT_REGISTER(isp, FMTCFG);
CCDC_PRINT_REGISTER(isp, FMT_HORZ);
CCDC_PRINT_REGISTER(isp, FMT_VERT);
CCDC_PRINT_REGISTER(isp, PRGEVEN0);
CCDC_PRINT_REGISTER(isp, PRGEVEN1);
CCDC_PRINT_REGISTER(isp, PRGODD0);
CCDC_PRINT_REGISTER(isp, PRGODD1);
CCDC_PRINT_REGISTER(isp, VP_OUT);
CCDC_PRINT_REGISTER(isp, LSC_CONFIG);
CCDC_PRINT_REGISTER(isp, LSC_INITIAL);
CCDC_PRINT_REGISTER(isp, LSC_TABLE_BASE);
CCDC_PRINT_REGISTER(isp, LSC_TABLE_OFFSET);
dev_dbg(isp->dev, "--------------------------------------------\n");
}
/*
* omap3isp_ccdc_busy - Get busy state of the CCDC.
* @ccdc: Pointer to ISP CCDC device.
*/
int omap3isp_ccdc_busy(struct isp_ccdc_device *ccdc)
{
struct isp_device *isp = to_isp_device(ccdc);
return isp_reg_readl(isp, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_PCR) &
ISPCCDC_PCR_BUSY;
}
/* -----------------------------------------------------------------------------
* Lens Shading Compensation
*/
/*
* ccdc_lsc_validate_config - Check that LSC configuration is valid.
* @ccdc: Pointer to ISP CCDC device.
* @lsc_cfg: the LSC configuration to check.
*
* Returns 0 if the LSC configuration is valid, or -EINVAL if invalid.
*/
static int ccdc_lsc_validate_config(struct isp_ccdc_device *ccdc,
struct omap3isp_ccdc_lsc_config *lsc_cfg)
{
struct isp_device *isp = to_isp_device(ccdc);
struct v4l2_mbus_framefmt *format;
unsigned int paxel_width, paxel_height;
unsigned int paxel_shift_x, paxel_shift_y;
unsigned int min_width, min_height, min_size;
unsigned int input_width, input_height;
paxel_shift_x = lsc_cfg->gain_mode_m;
paxel_shift_y = lsc_cfg->gain_mode_n;
if ((paxel_shift_x < 2) || (paxel_shift_x > 6) ||
(paxel_shift_y < 2) || (paxel_shift_y > 6)) {
dev_dbg(isp->dev, "CCDC: LSC: Invalid paxel size\n");
return -EINVAL;
}
if (lsc_cfg->offset & 3) {
dev_dbg(isp->dev, "CCDC: LSC: Offset must be a multiple of "
"4\n");
return -EINVAL;
}
if ((lsc_cfg->initial_x & 1) || (lsc_cfg->initial_y & 1)) {
dev_dbg(isp->dev, "CCDC: LSC: initial_x and y must be even\n");
return -EINVAL;
}
format = __ccdc_get_format(ccdc, NULL, CCDC_PAD_SINK,
V4L2_SUBDEV_FORMAT_ACTIVE);
input_width = format->width;
input_height = format->height;
/* Calculate minimum bytesize for validation */
paxel_width = 1 << paxel_shift_x;
min_width = ((input_width + lsc_cfg->initial_x + paxel_width - 1)
>> paxel_shift_x) + 1;
paxel_height = 1 << paxel_shift_y;
min_height = ((input_height + lsc_cfg->initial_y + paxel_height - 1)
>> paxel_shift_y) + 1;
min_size = 4 * min_width * min_height;
if (min_size > lsc_cfg->size) {
dev_dbg(isp->dev, "CCDC: LSC: too small table\n");
return -EINVAL;
}
if (lsc_cfg->offset < (min_width * 4)) {
dev_dbg(isp->dev, "CCDC: LSC: Offset is too small\n");
return -EINVAL;
}
if ((lsc_cfg->size / lsc_cfg->offset) < min_height) {
dev_dbg(isp->dev, "CCDC: LSC: Wrong size/offset combination\n");
return -EINVAL;
}
return 0;
}
/*
* ccdc_lsc_program_table - Program Lens Shading Compensation table address.
* @ccdc: Pointer to ISP CCDC device.
*/
static void ccdc_lsc_program_table(struct isp_ccdc_device *ccdc, u32 addr)
{
isp_reg_writel(to_isp_device(ccdc), addr,
OMAP3_ISP_IOMEM_CCDC, ISPCCDC_LSC_TABLE_BASE);
}
/*
* ccdc_lsc_setup_regs - Configures the lens shading compensation module
* @ccdc: Pointer to ISP CCDC device.
*/
static void ccdc_lsc_setup_regs(struct isp_ccdc_device *ccdc,
struct omap3isp_ccdc_lsc_config *cfg)
{
struct isp_device *isp = to_isp_device(ccdc);
int reg;
isp_reg_writel(isp, cfg->offset, OMAP3_ISP_IOMEM_CCDC,
ISPCCDC_LSC_TABLE_OFFSET);
reg = 0;
reg |= cfg->gain_mode_n << ISPCCDC_LSC_GAIN_MODE_N_SHIFT;
reg |= cfg->gain_mode_m << ISPCCDC_LSC_GAIN_MODE_M_SHIFT;
reg |= cfg->gain_format << ISPCCDC_LSC_GAIN_FORMAT_SHIFT;
isp_reg_writel(isp, reg, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_LSC_CONFIG);
reg = 0;
reg &= ~ISPCCDC_LSC_INITIAL_X_MASK;
reg |= cfg->initial_x << ISPCCDC_LSC_INITIAL_X_SHIFT;
reg &= ~ISPCCDC_LSC_INITIAL_Y_MASK;
reg |= cfg->initial_y << ISPCCDC_LSC_INITIAL_Y_SHIFT;
isp_reg_writel(isp, reg, OMAP3_ISP_IOMEM_CCDC,
ISPCCDC_LSC_INITIAL);
}
static int ccdc_lsc_wait_prefetch(struct isp_ccdc_device *ccdc)
{
struct isp_device *isp = to_isp_device(ccdc);
unsigned int wait;
isp_reg_writel(isp, IRQ0STATUS_CCDC_LSC_PREF_COMP_IRQ,
OMAP3_ISP_IOMEM_MAIN, ISP_IRQ0STATUS);
/* timeout 1 ms */
for (wait = 0; wait < 1000; wait++) {
if (isp_reg_readl(isp, OMAP3_ISP_IOMEM_MAIN, ISP_IRQ0STATUS) &
IRQ0STATUS_CCDC_LSC_PREF_COMP_IRQ) {
isp_reg_writel(isp, IRQ0STATUS_CCDC_LSC_PREF_COMP_IRQ,
OMAP3_ISP_IOMEM_MAIN, ISP_IRQ0STATUS);
return 0;
}
rmb();
udelay(1);
}
return -ETIMEDOUT;
}
/*
* __ccdc_lsc_enable - Enables/Disables the Lens Shading Compensation module.
* @ccdc: Pointer to ISP CCDC device.
* @enable: 0 Disables LSC, 1 Enables LSC.
*/
static int __ccdc_lsc_enable(struct isp_ccdc_device *ccdc, int enable)
{
struct isp_device *isp = to_isp_device(ccdc);
const struct v4l2_mbus_framefmt *format =
__ccdc_get_format(ccdc, NULL, CCDC_PAD_SINK,
V4L2_SUBDEV_FORMAT_ACTIVE);
if ((format->code != V4L2_MBUS_FMT_SGRBG10_1X10) &&
(format->code != V4L2_MBUS_FMT_SRGGB10_1X10) &&
(format->code != V4L2_MBUS_FMT_SBGGR10_1X10) &&
(format->code != V4L2_MBUS_FMT_SGBRG10_1X10))
return -EINVAL;
if (enable)
omap3isp_sbl_enable(isp, OMAP3_ISP_SBL_CCDC_LSC_READ);
isp_reg_clr_set(isp, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_LSC_CONFIG,
ISPCCDC_LSC_ENABLE, enable ? ISPCCDC_LSC_ENABLE : 0);
if (enable) {
if (ccdc_lsc_wait_prefetch(ccdc) < 0) {
isp_reg_clr(isp, OMAP3_ISP_IOMEM_CCDC,
ISPCCDC_LSC_CONFIG, ISPCCDC_LSC_ENABLE);
ccdc->lsc.state = LSC_STATE_STOPPED;
dev_warn(to_device(ccdc), "LSC prefecth timeout\n");
return -ETIMEDOUT;
}
ccdc->lsc.state = LSC_STATE_RUNNING;
} else {
ccdc->lsc.state = LSC_STATE_STOPPING;
}
return 0;
}
static int ccdc_lsc_busy(struct isp_ccdc_device *ccdc)
{
struct isp_device *isp = to_isp_device(ccdc);
return isp_reg_readl(isp, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_LSC_CONFIG) &
ISPCCDC_LSC_BUSY;
}
/* __ccdc_lsc_configure - Apply a new configuration to the LSC engine
* @ccdc: Pointer to ISP CCDC device
* @req: New configuration request
*
* context: in_interrupt()
*/
static int __ccdc_lsc_configure(struct isp_ccdc_device *ccdc,
struct ispccdc_lsc_config_req *req)
{
if (!req->enable)
return -EINVAL;
if (ccdc_lsc_validate_config(ccdc, &req->config) < 0) {
dev_dbg(to_device(ccdc), "Discard LSC configuration\n");
return -EINVAL;
}
if (ccdc_lsc_busy(ccdc))
return -EBUSY;
ccdc_lsc_setup_regs(ccdc, &req->config);
ccdc_lsc_program_table(ccdc, req->table);
return 0;
}
/*
* ccdc_lsc_error_handler - Handle LSC prefetch error scenario.
* @ccdc: Pointer to ISP CCDC device.
*
* Disables LSC, and defers enablement to shadow registers update time.
*/
static void ccdc_lsc_error_handler(struct isp_ccdc_device *ccdc)
{
struct isp_device *isp = to_isp_device(ccdc);
/*
* From OMAP3 TRM: When this event is pending, the module
* goes into transparent mode (output =input). Normal
* operation can be resumed at the start of the next frame
* after:
* 1) Clearing this event
* 2) Disabling the LSC module
* 3) Enabling it
*/
isp_reg_clr(isp, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_LSC_CONFIG,
ISPCCDC_LSC_ENABLE);
ccdc->lsc.state = LSC_STATE_STOPPED;
}
static void ccdc_lsc_free_request(struct isp_ccdc_device *ccdc,
struct ispccdc_lsc_config_req *req)
{
struct isp_device *isp = to_isp_device(ccdc);
if (req == NULL)
return;
if (req->iovm)
dma_unmap_sg(isp->dev, req->iovm->sgt->sgl,
req->iovm->sgt->nents, DMA_TO_DEVICE);
if (req->table)
omap_iommu_vfree(isp->domain, isp->dev, req->table);
kfree(req);
}
static void ccdc_lsc_free_queue(struct isp_ccdc_device *ccdc,
struct list_head *queue)
{
struct ispccdc_lsc_config_req *req, *n;
unsigned long flags;
spin_lock_irqsave(&ccdc->lsc.req_lock, flags);
list_for_each_entry_safe(req, n, queue, list) {
list_del(&req->list);
spin_unlock_irqrestore(&ccdc->lsc.req_lock, flags);
ccdc_lsc_free_request(ccdc, req);
spin_lock_irqsave(&ccdc->lsc.req_lock, flags);
}
spin_unlock_irqrestore(&ccdc->lsc.req_lock, flags);
}
static void ccdc_lsc_free_table_work(struct work_struct *work)
{
struct isp_ccdc_device *ccdc;
struct ispccdc_lsc *lsc;
lsc = container_of(work, struct ispccdc_lsc, table_work);
ccdc = container_of(lsc, struct isp_ccdc_device, lsc);
ccdc_lsc_free_queue(ccdc, &lsc->free_queue);
}
/*
* ccdc_lsc_config - Configure the LSC module from a userspace request
*
* Store the request LSC configuration in the LSC engine request pointer. The
* configuration will be applied to the hardware when the CCDC will be enabled,
* or at the next LSC interrupt if the CCDC is already running.
*/
static int ccdc_lsc_config(struct isp_ccdc_device *ccdc,
struct omap3isp_ccdc_update_config *config)
{
struct isp_device *isp = to_isp_device(ccdc);
struct ispccdc_lsc_config_req *req;
unsigned long flags;
void *table;
u16 update;
int ret;
update = config->update &
(OMAP3ISP_CCDC_CONFIG_LSC | OMAP3ISP_CCDC_TBL_LSC);
if (!update)
return 0;
if (update != (OMAP3ISP_CCDC_CONFIG_LSC | OMAP3ISP_CCDC_TBL_LSC)) {
dev_dbg(to_device(ccdc), "%s: Both LSC configuration and table "
"need to be supplied\n", __func__);
return -EINVAL;
}
req = kzalloc(sizeof(*req), GFP_KERNEL);
if (req == NULL)
return -ENOMEM;
if (config->flag & OMAP3ISP_CCDC_CONFIG_LSC) {
if (copy_from_user(&req->config, config->lsc_cfg,
sizeof(req->config))) {
ret = -EFAULT;
goto done;
}
req->enable = 1;
req->table = omap_iommu_vmalloc(isp->domain, isp->dev, 0,
req->config.size, IOMMU_FLAG);
if (IS_ERR_VALUE(req->table)) {
req->table = 0;
ret = -ENOMEM;
goto done;
}
req->iovm = omap_find_iovm_area(isp->dev, req->table);
if (req->iovm == NULL) {
ret = -ENOMEM;
goto done;
}
if (!dma_map_sg(isp->dev, req->iovm->sgt->sgl,
req->iovm->sgt->nents, DMA_TO_DEVICE)) {
ret = -ENOMEM;
req->iovm = NULL;
goto done;
}
dma_sync_sg_for_cpu(isp->dev, req->iovm->sgt->sgl,
req->iovm->sgt->nents, DMA_TO_DEVICE);
table = omap_da_to_va(isp->dev, req->table);
if (copy_from_user(table, config->lsc, req->config.size)) {
ret = -EFAULT;
goto done;
}
dma_sync_sg_for_device(isp->dev, req->iovm->sgt->sgl,
req->iovm->sgt->nents, DMA_TO_DEVICE);
}
spin_lock_irqsave(&ccdc->lsc.req_lock, flags);
if (ccdc->lsc.request) {
list_add_tail(&ccdc->lsc.request->list, &ccdc->lsc.free_queue);
schedule_work(&ccdc->lsc.table_work);
}
ccdc->lsc.request = req;
spin_unlock_irqrestore(&ccdc->lsc.req_lock, flags);
ret = 0;
done:
if (ret < 0)
ccdc_lsc_free_request(ccdc, req);
return ret;
}
static inline int ccdc_lsc_is_configured(struct isp_ccdc_device *ccdc)
{
unsigned long flags;
spin_lock_irqsave(&ccdc->lsc.req_lock, flags);
if (ccdc->lsc.active) {
spin_unlock_irqrestore(&ccdc->lsc.req_lock, flags);
return 1;
}
spin_unlock_irqrestore(&ccdc->lsc.req_lock, flags);
return 0;
}
static int ccdc_lsc_enable(struct isp_ccdc_device *ccdc)
{
struct ispccdc_lsc *lsc = &ccdc->lsc;
if (lsc->state != LSC_STATE_STOPPED)
return -EINVAL;
if (lsc->active) {
list_add_tail(&lsc->active->list, &lsc->free_queue);
lsc->active = NULL;
}
if (__ccdc_lsc_configure(ccdc, lsc->request) < 0) {
omap3isp_sbl_disable(to_isp_device(ccdc),
OMAP3_ISP_SBL_CCDC_LSC_READ);
list_add_tail(&lsc->request->list, &lsc->free_queue);
lsc->request = NULL;
goto done;
}
lsc->active = lsc->request;
lsc->request = NULL;
__ccdc_lsc_enable(ccdc, 1);
done:
if (!list_empty(&lsc->free_queue))
schedule_work(&lsc->table_work);
return 0;
}
/* -----------------------------------------------------------------------------
* Parameters configuration
*/
/*
* ccdc_configure_clamp - Configure optical-black or digital clamping
* @ccdc: Pointer to ISP CCDC device.
*
* The CCDC performs either optical-black or digital clamp. Configure and enable
* the selected clamp method.
*/
static void ccdc_configure_clamp(struct isp_ccdc_device *ccdc)
{
struct isp_device *isp = to_isp_device(ccdc);
u32 clamp;
if (ccdc->obclamp) {
clamp = ccdc->clamp.obgain << ISPCCDC_CLAMP_OBGAIN_SHIFT;
clamp |= ccdc->clamp.oblen << ISPCCDC_CLAMP_OBSLEN_SHIFT;
clamp |= ccdc->clamp.oblines << ISPCCDC_CLAMP_OBSLN_SHIFT;
clamp |= ccdc->clamp.obstpixel << ISPCCDC_CLAMP_OBST_SHIFT;
isp_reg_writel(isp, clamp, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_CLAMP);
} else {
isp_reg_writel(isp, ccdc->clamp.dcsubval,
OMAP3_ISP_IOMEM_CCDC, ISPCCDC_DCSUB);
}
isp_reg_clr_set(isp, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_CLAMP,
ISPCCDC_CLAMP_CLAMPEN,
ccdc->obclamp ? ISPCCDC_CLAMP_CLAMPEN : 0);
}
/*
* ccdc_configure_fpc - Configure Faulty Pixel Correction
* @ccdc: Pointer to ISP CCDC device.
*/
static void ccdc_configure_fpc(struct isp_ccdc_device *ccdc)
{
struct isp_device *isp = to_isp_device(ccdc);
isp_reg_clr(isp, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_FPC, ISPCCDC_FPC_FPCEN);
if (!ccdc->fpc_en)
return;
isp_reg_writel(isp, ccdc->fpc.fpcaddr, OMAP3_ISP_IOMEM_CCDC,
ISPCCDC_FPC_ADDR);
/* The FPNUM field must be set before enabling FPC. */
isp_reg_writel(isp, (ccdc->fpc.fpnum << ISPCCDC_FPC_FPNUM_SHIFT),
OMAP3_ISP_IOMEM_CCDC, ISPCCDC_FPC);
isp_reg_writel(isp, (ccdc->fpc.fpnum << ISPCCDC_FPC_FPNUM_SHIFT) |
ISPCCDC_FPC_FPCEN, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_FPC);
}
/*
* ccdc_configure_black_comp - Configure Black Level Compensation.
* @ccdc: Pointer to ISP CCDC device.
*/
static void ccdc_configure_black_comp(struct isp_ccdc_device *ccdc)
{
struct isp_device *isp = to_isp_device(ccdc);
u32 blcomp;
blcomp = ccdc->blcomp.b_mg << ISPCCDC_BLKCMP_B_MG_SHIFT;
blcomp |= ccdc->blcomp.gb_g << ISPCCDC_BLKCMP_GB_G_SHIFT;
blcomp |= ccdc->blcomp.gr_cy << ISPCCDC_BLKCMP_GR_CY_SHIFT;
blcomp |= ccdc->blcomp.r_ye << ISPCCDC_BLKCMP_R_YE_SHIFT;
isp_reg_writel(isp, blcomp, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_BLKCMP);
}
/*
* ccdc_configure_lpf - Configure Low-Pass Filter (LPF).
* @ccdc: Pointer to ISP CCDC device.
*/
static void ccdc_configure_lpf(struct isp_ccdc_device *ccdc)
{
struct isp_device *isp = to_isp_device(ccdc);
isp_reg_clr_set(isp, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_SYN_MODE,
ISPCCDC_SYN_MODE_LPF,
ccdc->lpf ? ISPCCDC_SYN_MODE_LPF : 0);
}
/*
* ccdc_configure_alaw - Configure A-law compression.
* @ccdc: Pointer to ISP CCDC device.
*/
static void ccdc_configure_alaw(struct isp_ccdc_device *ccdc)
{
struct isp_device *isp = to_isp_device(ccdc);
u32 alaw = 0;
switch (ccdc->syncif.datsz) {
case 8:
return;
case 10:
alaw = ISPCCDC_ALAW_GWDI_9_0;
break;
case 11:
alaw = ISPCCDC_ALAW_GWDI_10_1;
break;
case 12:
alaw = ISPCCDC_ALAW_GWDI_11_2;
break;
case 13:
alaw = ISPCCDC_ALAW_GWDI_12_3;
break;
}
if (ccdc->alaw)
alaw |= ISPCCDC_ALAW_CCDTBL;
isp_reg_writel(isp, alaw, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_ALAW);
}
/*
* ccdc_config_imgattr - Configure sensor image specific attributes.
* @ccdc: Pointer to ISP CCDC device.
* @colptn: Color pattern of the sensor.
*/
static void ccdc_config_imgattr(struct isp_ccdc_device *ccdc, u32 colptn)
{
struct isp_device *isp = to_isp_device(ccdc);
isp_reg_writel(isp, colptn, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_COLPTN);
}
/*
* ccdc_config - Set CCDC configuration from userspace
* @ccdc: Pointer to ISP CCDC device.
* @userspace_add: Structure containing CCDC configuration sent from userspace.
*
* Returns 0 if successful, -EINVAL if the pointer to the configuration
* structure is null, or the copy_from_user function fails to copy user space
* memory to kernel space memory.
*/
static int ccdc_config(struct isp_ccdc_device *ccdc,
struct omap3isp_ccdc_update_config *ccdc_struct)
{
struct isp_device *isp = to_isp_device(ccdc);
unsigned long flags;
spin_lock_irqsave(&ccdc->lock, flags);
ccdc->shadow_update = 1;
spin_unlock_irqrestore(&ccdc->lock, flags);
if (OMAP3ISP_CCDC_ALAW & ccdc_struct->update) {
ccdc->alaw = !!(OMAP3ISP_CCDC_ALAW & ccdc_struct->flag);
ccdc->update |= OMAP3ISP_CCDC_ALAW;
}
if (OMAP3ISP_CCDC_LPF & ccdc_struct->update) {
ccdc->lpf = !!(OMAP3ISP_CCDC_LPF & ccdc_struct->flag);
ccdc->update |= OMAP3ISP_CCDC_LPF;
}
if (OMAP3ISP_CCDC_BLCLAMP & ccdc_struct->update) {
if (copy_from_user(&ccdc->clamp, ccdc_struct->bclamp,
sizeof(ccdc->clamp))) {
ccdc->shadow_update = 0;
return -EFAULT;
}
ccdc->obclamp = !!(OMAP3ISP_CCDC_BLCLAMP & ccdc_struct->flag);
ccdc->update |= OMAP3ISP_CCDC_BLCLAMP;
}
if (OMAP3ISP_CCDC_BCOMP & ccdc_struct->update) {
if (copy_from_user(&ccdc->blcomp, ccdc_struct->blcomp,
sizeof(ccdc->blcomp))) {
ccdc->shadow_update = 0;
return -EFAULT;
}
ccdc->update |= OMAP3ISP_CCDC_BCOMP;
}
ccdc->shadow_update = 0;
if (OMAP3ISP_CCDC_FPC & ccdc_struct->update) {
u32 table_old = 0;
u32 table_new;
u32 size;
if (ccdc->state != ISP_PIPELINE_STREAM_STOPPED)
return -EBUSY;
ccdc->fpc_en = !!(OMAP3ISP_CCDC_FPC & ccdc_struct->flag);
if (ccdc->fpc_en) {
if (copy_from_user(&ccdc->fpc, ccdc_struct->fpc,
sizeof(ccdc->fpc)))
return -EFAULT;
/*
* table_new must be 64-bytes aligned, but it's
* already done by omap_iommu_vmalloc().
*/
size = ccdc->fpc.fpnum * 4;
table_new = omap_iommu_vmalloc(isp->domain, isp->dev,
0, size, IOMMU_FLAG);
if (IS_ERR_VALUE(table_new))
return -ENOMEM;
if (copy_from_user(omap_da_to_va(isp->dev, table_new),
(__force void __user *)
ccdc->fpc.fpcaddr, size)) {
omap_iommu_vfree(isp->domain, isp->dev,
table_new);
return -EFAULT;
}
table_old = ccdc->fpc.fpcaddr;
ccdc->fpc.fpcaddr = table_new;
}
ccdc_configure_fpc(ccdc);
if (table_old != 0)
omap_iommu_vfree(isp->domain, isp->dev, table_old);
}
return ccdc_lsc_config(ccdc, ccdc_struct);
}
static void ccdc_apply_controls(struct isp_ccdc_device *ccdc)
{
if (ccdc->update & OMAP3ISP_CCDC_ALAW) {
ccdc_configure_alaw(ccdc);
ccdc->update &= ~OMAP3ISP_CCDC_ALAW;
}
if (ccdc->update & OMAP3ISP_CCDC_LPF) {
ccdc_configure_lpf(ccdc);
ccdc->update &= ~OMAP3ISP_CCDC_LPF;
}
if (ccdc->update & OMAP3ISP_CCDC_BLCLAMP) {
ccdc_configure_clamp(ccdc);
ccdc->update &= ~OMAP3ISP_CCDC_BLCLAMP;
}
if (ccdc->update & OMAP3ISP_CCDC_BCOMP) {
ccdc_configure_black_comp(ccdc);
ccdc->update &= ~OMAP3ISP_CCDC_BCOMP;
}
}
/*
* omap3isp_ccdc_restore_context - Restore values of the CCDC module registers
* @dev: Pointer to ISP device
*/
void omap3isp_ccdc_restore_context(struct isp_device *isp)
{
struct isp_ccdc_device *ccdc = &isp->isp_ccdc;
isp_reg_set(isp, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_CFG, ISPCCDC_CFG_VDLC);
ccdc->update = OMAP3ISP_CCDC_ALAW | OMAP3ISP_CCDC_LPF
| OMAP3ISP_CCDC_BLCLAMP | OMAP3ISP_CCDC_BCOMP;
ccdc_apply_controls(ccdc);
ccdc_configure_fpc(ccdc);
}
/* -----------------------------------------------------------------------------
* Format- and pipeline-related configuration helpers
*/
/*
* ccdc_config_vp - Configure the Video Port.
* @ccdc: Pointer to ISP CCDC device.
*/
static void ccdc_config_vp(struct isp_ccdc_device *ccdc)
{
struct isp_pipeline *pipe = to_isp_pipeline(&ccdc->subdev.entity);
struct isp_device *isp = to_isp_device(ccdc);
unsigned long l3_ick = pipe->l3_ick;
unsigned int max_div = isp->revision == ISP_REVISION_15_0 ? 64 : 8;
unsigned int div = 0;
u32 fmtcfg_vp;
fmtcfg_vp = isp_reg_readl(isp, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_FMTCFG)
& ~(ISPCCDC_FMTCFG_VPIN_MASK | ISPCCDC_FMTCFG_VPIF_FRQ_MASK);
switch (ccdc->syncif.datsz) {
case 8:
case 10:
fmtcfg_vp |= ISPCCDC_FMTCFG_VPIN_9_0;
break;
case 11:
fmtcfg_vp |= ISPCCDC_FMTCFG_VPIN_10_1;
break;
case 12:
fmtcfg_vp |= ISPCCDC_FMTCFG_VPIN_11_2;
break;
case 13:
fmtcfg_vp |= ISPCCDC_FMTCFG_VPIN_12_3;
break;
};
if (pipe->input)
div = DIV_ROUND_UP(l3_ick, pipe->max_rate);
else if (ccdc->vpcfg.pixelclk)
div = l3_ick / ccdc->vpcfg.pixelclk;
div = clamp(div, 2U, max_div);
fmtcfg_vp |= (div - 2) << ISPCCDC_FMTCFG_VPIF_FRQ_SHIFT;
isp_reg_writel(isp, fmtcfg_vp, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_FMTCFG);
}
/*
* ccdc_enable_vp - Enable Video Port.
* @ccdc: Pointer to ISP CCDC device.
* @enable: 0 Disables VP, 1 Enables VP
*
* This is needed for outputting image to Preview, H3A and HIST ISP submodules.
*/
static void ccdc_enable_vp(struct isp_ccdc_device *ccdc, u8 enable)
{
struct isp_device *isp = to_isp_device(ccdc);
isp_reg_clr_set(isp, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_FMTCFG,
ISPCCDC_FMTCFG_VPEN, enable ? ISPCCDC_FMTCFG_VPEN : 0);
}
/*
* ccdc_config_outlineoffset - Configure memory saving output line offset
* @ccdc: Pointer to ISP CCDC device.
* @offset: Address offset to start a new line. Must be twice the
* Output width and aligned on 32 byte boundary
* @oddeven: Specifies the odd/even line pattern to be chosen to store the
* output.
* @numlines: Set the value 0-3 for +1-4lines, 4-7 for -1-4lines.
*
* - Configures the output line offset when stored in memory
* - Sets the odd/even line pattern to store the output
* (EVENEVEN (1), ODDEVEN (2), EVENODD (3), ODDODD (4))
* - Configures the number of even and odd line fields in case of rearranging
* the lines.
*/
static void ccdc_config_outlineoffset(struct isp_ccdc_device *ccdc,
u32 offset, u8 oddeven, u8 numlines)
{
struct isp_device *isp = to_isp_device(ccdc);
isp_reg_writel(isp, offset & 0xffff,
OMAP3_ISP_IOMEM_CCDC, ISPCCDC_HSIZE_OFF);
isp_reg_clr(isp, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_SDOFST,
ISPCCDC_SDOFST_FINV);
isp_reg_clr(isp, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_SDOFST,
ISPCCDC_SDOFST_FOFST_4L);
switch (oddeven) {
case EVENEVEN:
isp_reg_set(isp, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_SDOFST,
(numlines & 0x7) << ISPCCDC_SDOFST_LOFST0_SHIFT);
break;
case ODDEVEN:
isp_reg_set(isp, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_SDOFST,
(numlines & 0x7) << ISPCCDC_SDOFST_LOFST1_SHIFT);
break;
case EVENODD:
isp_reg_set(isp, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_SDOFST,
(numlines & 0x7) << ISPCCDC_SDOFST_LOFST2_SHIFT);
break;
case ODDODD:
isp_reg_set(isp, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_SDOFST,
(numlines & 0x7) << ISPCCDC_SDOFST_LOFST3_SHIFT);
break;
default:
break;
}
}
/*
* ccdc_set_outaddr - Set memory address to save output image
* @ccdc: Pointer to ISP CCDC device.
* @addr: ISP MMU Mapped 32-bit memory address aligned on 32 byte boundary.
*
* Sets the memory address where the output will be saved.
*/
static void ccdc_set_outaddr(struct isp_ccdc_device *ccdc, u32 addr)
{
struct isp_device *isp = to_isp_device(ccdc);
isp_reg_writel(isp, addr, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_SDR_ADDR);
}
/*
* omap3isp_ccdc_max_rate - Calculate maximum input data rate based on the input
* @ccdc: Pointer to ISP CCDC device.
* @max_rate: Maximum calculated data rate.
*
* Returns in *max_rate less value between calculated and passed
*/
void omap3isp_ccdc_max_rate(struct isp_ccdc_device *ccdc,
unsigned int *max_rate)
{
struct isp_pipeline *pipe = to_isp_pipeline(&ccdc->subdev.entity);
unsigned int rate;
if (pipe == NULL)
return;
/*
* TRM says that for parallel sensors the maximum data rate
* should be 90% form L3/2 clock, otherwise just L3/2.
*/
if (ccdc->input == CCDC_INPUT_PARALLEL)
rate = pipe->l3_ick / 2 * 9 / 10;
else
rate = pipe->l3_ick / 2;
*max_rate = min(*max_rate, rate);
}
/*
* ccdc_config_sync_if - Set CCDC sync interface configuration
* @ccdc: Pointer to ISP CCDC device.
* @syncif: Structure containing the sync parameters like field state, CCDC in
* master/slave mode, raw/yuv data, polarity of data, field, hs, vs
* signals.
*/
static void ccdc_config_sync_if(struct isp_ccdc_device *ccdc,
struct ispccdc_syncif *syncif)
{
struct isp_device *isp = to_isp_device(ccdc);
u32 syn_mode = isp_reg_readl(isp, OMAP3_ISP_IOMEM_CCDC,
ISPCCDC_SYN_MODE);
syn_mode |= ISPCCDC_SYN_MODE_VDHDEN;
if (syncif->fldstat)
syn_mode |= ISPCCDC_SYN_MODE_FLDSTAT;
else
syn_mode &= ~ISPCCDC_SYN_MODE_FLDSTAT;
syn_mode &= ~ISPCCDC_SYN_MODE_DATSIZ_MASK;
switch (syncif->datsz) {
case 8:
syn_mode |= ISPCCDC_SYN_MODE_DATSIZ_8;
break;
case 10:
syn_mode |= ISPCCDC_SYN_MODE_DATSIZ_10;
break;
case 11:
syn_mode |= ISPCCDC_SYN_MODE_DATSIZ_11;
break;
case 12:
syn_mode |= ISPCCDC_SYN_MODE_DATSIZ_12;
break;
};
if (syncif->fldmode)
syn_mode |= ISPCCDC_SYN_MODE_FLDMODE;
else
syn_mode &= ~ISPCCDC_SYN_MODE_FLDMODE;
if (syncif->datapol)
syn_mode |= ISPCCDC_SYN_MODE_DATAPOL;
else
syn_mode &= ~ISPCCDC_SYN_MODE_DATAPOL;
if (syncif->fldpol)
syn_mode |= ISPCCDC_SYN_MODE_FLDPOL;
else
syn_mode &= ~ISPCCDC_SYN_MODE_FLDPOL;
if (syncif->hdpol)
syn_mode |= ISPCCDC_SYN_MODE_HDPOL;
else
syn_mode &= ~ISPCCDC_SYN_MODE_HDPOL;
if (syncif->vdpol)
syn_mode |= ISPCCDC_SYN_MODE_VDPOL;
else
syn_mode &= ~ISPCCDC_SYN_MODE_VDPOL;
if (syncif->ccdc_mastermode) {
syn_mode |= ISPCCDC_SYN_MODE_FLDOUT | ISPCCDC_SYN_MODE_VDHDOUT;
isp_reg_writel(isp,
syncif->hs_width << ISPCCDC_HD_VD_WID_HDW_SHIFT
| syncif->vs_width << ISPCCDC_HD_VD_WID_VDW_SHIFT,
OMAP3_ISP_IOMEM_CCDC,
ISPCCDC_HD_VD_WID);
isp_reg_writel(isp,
syncif->ppln << ISPCCDC_PIX_LINES_PPLN_SHIFT
| syncif->hlprf << ISPCCDC_PIX_LINES_HLPRF_SHIFT,
OMAP3_ISP_IOMEM_CCDC,
ISPCCDC_PIX_LINES);
} else
syn_mode &= ~(ISPCCDC_SYN_MODE_FLDOUT |
ISPCCDC_SYN_MODE_VDHDOUT);
isp_reg_writel(isp, syn_mode, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_SYN_MODE);
if (!syncif->bt_r656_en)
isp_reg_clr(isp, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_REC656IF,
ISPCCDC_REC656IF_R656ON);
}
/* CCDC formats descriptions */
static const u32 ccdc_sgrbg_pattern =
ISPCCDC_COLPTN_Gr_Cy << ISPCCDC_COLPTN_CP0PLC0_SHIFT |
ISPCCDC_COLPTN_R_Ye << ISPCCDC_COLPTN_CP0PLC1_SHIFT |
ISPCCDC_COLPTN_Gr_Cy << ISPCCDC_COLPTN_CP0PLC2_SHIFT |
ISPCCDC_COLPTN_R_Ye << ISPCCDC_COLPTN_CP0PLC3_SHIFT |
ISPCCDC_COLPTN_B_Mg << ISPCCDC_COLPTN_CP1PLC0_SHIFT |
ISPCCDC_COLPTN_Gb_G << ISPCCDC_COLPTN_CP1PLC1_SHIFT |
ISPCCDC_COLPTN_B_Mg << ISPCCDC_COLPTN_CP1PLC2_SHIFT |
ISPCCDC_COLPTN_Gb_G << ISPCCDC_COLPTN_CP1PLC3_SHIFT |
ISPCCDC_COLPTN_Gr_Cy << ISPCCDC_COLPTN_CP2PLC0_SHIFT |
ISPCCDC_COLPTN_R_Ye << ISPCCDC_COLPTN_CP2PLC1_SHIFT |
ISPCCDC_COLPTN_Gr_Cy << ISPCCDC_COLPTN_CP2PLC2_SHIFT |
ISPCCDC_COLPTN_R_Ye << ISPCCDC_COLPTN_CP2PLC3_SHIFT |
ISPCCDC_COLPTN_B_Mg << ISPCCDC_COLPTN_CP3PLC0_SHIFT |
ISPCCDC_COLPTN_Gb_G << ISPCCDC_COLPTN_CP3PLC1_SHIFT |
ISPCCDC_COLPTN_B_Mg << ISPCCDC_COLPTN_CP3PLC2_SHIFT |
ISPCCDC_COLPTN_Gb_G << ISPCCDC_COLPTN_CP3PLC3_SHIFT;
static const u32 ccdc_srggb_pattern =
ISPCCDC_COLPTN_R_Ye << ISPCCDC_COLPTN_CP0PLC0_SHIFT |
ISPCCDC_COLPTN_Gr_Cy << ISPCCDC_COLPTN_CP0PLC1_SHIFT |
ISPCCDC_COLPTN_R_Ye << ISPCCDC_COLPTN_CP0PLC2_SHIFT |
ISPCCDC_COLPTN_Gr_Cy << ISPCCDC_COLPTN_CP0PLC3_SHIFT |
ISPCCDC_COLPTN_Gb_G << ISPCCDC_COLPTN_CP1PLC0_SHIFT |
ISPCCDC_COLPTN_B_Mg << ISPCCDC_COLPTN_CP1PLC1_SHIFT |
ISPCCDC_COLPTN_Gb_G << ISPCCDC_COLPTN_CP1PLC2_SHIFT |
ISPCCDC_COLPTN_B_Mg << ISPCCDC_COLPTN_CP1PLC3_SHIFT |
ISPCCDC_COLPTN_R_Ye << ISPCCDC_COLPTN_CP2PLC0_SHIFT |
ISPCCDC_COLPTN_Gr_Cy << ISPCCDC_COLPTN_CP2PLC1_SHIFT |
ISPCCDC_COLPTN_R_Ye << ISPCCDC_COLPTN_CP2PLC2_SHIFT |
ISPCCDC_COLPTN_Gr_Cy << ISPCCDC_COLPTN_CP2PLC3_SHIFT |
ISPCCDC_COLPTN_Gb_G << ISPCCDC_COLPTN_CP3PLC0_SHIFT |
ISPCCDC_COLPTN_B_Mg << ISPCCDC_COLPTN_CP3PLC1_SHIFT |
ISPCCDC_COLPTN_Gb_G << ISPCCDC_COLPTN_CP3PLC2_SHIFT |
ISPCCDC_COLPTN_B_Mg << ISPCCDC_COLPTN_CP3PLC3_SHIFT;
static const u32 ccdc_sbggr_pattern =
ISPCCDC_COLPTN_B_Mg << ISPCCDC_COLPTN_CP0PLC0_SHIFT |
ISPCCDC_COLPTN_Gb_G << ISPCCDC_COLPTN_CP0PLC1_SHIFT |
ISPCCDC_COLPTN_B_Mg << ISPCCDC_COLPTN_CP0PLC2_SHIFT |
ISPCCDC_COLPTN_Gb_G << ISPCCDC_COLPTN_CP0PLC3_SHIFT |
ISPCCDC_COLPTN_Gr_Cy << ISPCCDC_COLPTN_CP1PLC0_SHIFT |
ISPCCDC_COLPTN_R_Ye << ISPCCDC_COLPTN_CP1PLC1_SHIFT |
ISPCCDC_COLPTN_Gr_Cy << ISPCCDC_COLPTN_CP1PLC2_SHIFT |
ISPCCDC_COLPTN_R_Ye << ISPCCDC_COLPTN_CP1PLC3_SHIFT |
ISPCCDC_COLPTN_B_Mg << ISPCCDC_COLPTN_CP2PLC0_SHIFT |
ISPCCDC_COLPTN_Gb_G << ISPCCDC_COLPTN_CP2PLC1_SHIFT |
ISPCCDC_COLPTN_B_Mg << ISPCCDC_COLPTN_CP2PLC2_SHIFT |
ISPCCDC_COLPTN_Gb_G << ISPCCDC_COLPTN_CP2PLC3_SHIFT |
ISPCCDC_COLPTN_Gr_Cy << ISPCCDC_COLPTN_CP3PLC0_SHIFT |
ISPCCDC_COLPTN_R_Ye << ISPCCDC_COLPTN_CP3PLC1_SHIFT |
ISPCCDC_COLPTN_Gr_Cy << ISPCCDC_COLPTN_CP3PLC2_SHIFT |
ISPCCDC_COLPTN_R_Ye << ISPCCDC_COLPTN_CP3PLC3_SHIFT;
static const u32 ccdc_sgbrg_pattern =
ISPCCDC_COLPTN_Gb_G << ISPCCDC_COLPTN_CP0PLC0_SHIFT |
ISPCCDC_COLPTN_B_Mg << ISPCCDC_COLPTN_CP0PLC1_SHIFT |
ISPCCDC_COLPTN_Gb_G << ISPCCDC_COLPTN_CP0PLC2_SHIFT |
ISPCCDC_COLPTN_B_Mg << ISPCCDC_COLPTN_CP0PLC3_SHIFT |
ISPCCDC_COLPTN_R_Ye << ISPCCDC_COLPTN_CP1PLC0_SHIFT |
ISPCCDC_COLPTN_Gr_Cy << ISPCCDC_COLPTN_CP1PLC1_SHIFT |
ISPCCDC_COLPTN_R_Ye << ISPCCDC_COLPTN_CP1PLC2_SHIFT |
ISPCCDC_COLPTN_Gr_Cy << ISPCCDC_COLPTN_CP1PLC3_SHIFT |
ISPCCDC_COLPTN_Gb_G << ISPCCDC_COLPTN_CP2PLC0_SHIFT |
ISPCCDC_COLPTN_B_Mg << ISPCCDC_COLPTN_CP2PLC1_SHIFT |
ISPCCDC_COLPTN_Gb_G << ISPCCDC_COLPTN_CP2PLC2_SHIFT |
ISPCCDC_COLPTN_B_Mg << ISPCCDC_COLPTN_CP2PLC3_SHIFT |
ISPCCDC_COLPTN_R_Ye << ISPCCDC_COLPTN_CP3PLC0_SHIFT |
ISPCCDC_COLPTN_Gr_Cy << ISPCCDC_COLPTN_CP3PLC1_SHIFT |
ISPCCDC_COLPTN_R_Ye << ISPCCDC_COLPTN_CP3PLC2_SHIFT |
ISPCCDC_COLPTN_Gr_Cy << ISPCCDC_COLPTN_CP3PLC3_SHIFT;
static void ccdc_configure(struct isp_ccdc_device *ccdc)
{
struct isp_device *isp = to_isp_device(ccdc);
struct isp_parallel_platform_data *pdata = NULL;
struct v4l2_subdev *sensor;
struct v4l2_mbus_framefmt *format;
const struct isp_format_info *fmt_info;
struct v4l2_subdev_format fmt_src;
unsigned int depth_out;
unsigned int depth_in = 0;
struct media_pad *pad;
unsigned long flags;
unsigned int shift;
u32 syn_mode;
u32 ccdc_pattern;
pad = media_entity_remote_source(&ccdc->pads[CCDC_PAD_SINK]);
sensor = media_entity_to_v4l2_subdev(pad->entity);
if (ccdc->input == CCDC_INPUT_PARALLEL)
pdata = &((struct isp_v4l2_subdevs_group *)sensor->host_priv)
->bus.parallel;
/* Compute shift value for lane shifter to configure the bridge. */
fmt_src.pad = pad->index;
fmt_src.which = V4L2_SUBDEV_FORMAT_ACTIVE;
if (!v4l2_subdev_call(sensor, pad, get_fmt, NULL, &fmt_src)) {
fmt_info = omap3isp_video_format_info(fmt_src.format.code);
depth_in = fmt_info->bpp;
}
fmt_info = omap3isp_video_format_info
(isp->isp_ccdc.formats[CCDC_PAD_SINK].code);
depth_out = fmt_info->bpp;
shift = depth_in - depth_out;
omap3isp_configure_bridge(isp, ccdc->input, pdata, shift);
ccdc->syncif.datsz = depth_out;
ccdc->syncif.hdpol = pdata ? pdata->hs_pol : 0;
ccdc->syncif.vdpol = pdata ? pdata->vs_pol : 0;
ccdc_config_sync_if(ccdc, &ccdc->syncif);
/* CCDC_PAD_SINK */
format = &ccdc->formats[CCDC_PAD_SINK];
syn_mode = isp_reg_readl(isp, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_SYN_MODE);
/* Use the raw, unprocessed data when writing to memory. The H3A and
* histogram modules are still fed with lens shading corrected data.
*/
syn_mode &= ~ISPCCDC_SYN_MODE_VP2SDR;
if (ccdc->output & CCDC_OUTPUT_MEMORY)
syn_mode |= ISPCCDC_SYN_MODE_WEN;
else
syn_mode &= ~ISPCCDC_SYN_MODE_WEN;
if (ccdc->output & CCDC_OUTPUT_RESIZER)
syn_mode |= ISPCCDC_SYN_MODE_SDR2RSZ;
else
syn_mode &= ~ISPCCDC_SYN_MODE_SDR2RSZ;
/* Use PACK8 mode for 1byte per pixel formats. */
if (omap3isp_video_format_info(format->code)->bpp <= 8)
syn_mode |= ISPCCDC_SYN_MODE_PACK8;
else
syn_mode &= ~ISPCCDC_SYN_MODE_PACK8;
isp_reg_writel(isp, syn_mode, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_SYN_MODE);
/* Mosaic filter */
switch (format->code) {
case V4L2_MBUS_FMT_SRGGB10_1X10:
case V4L2_MBUS_FMT_SRGGB12_1X12:
ccdc_pattern = ccdc_srggb_pattern;
break;
case V4L2_MBUS_FMT_SBGGR10_1X10:
case V4L2_MBUS_FMT_SBGGR12_1X12:
ccdc_pattern = ccdc_sbggr_pattern;
break;
case V4L2_MBUS_FMT_SGBRG10_1X10:
case V4L2_MBUS_FMT_SGBRG12_1X12:
ccdc_pattern = ccdc_sgbrg_pattern;
break;
default:
/* Use GRBG */
ccdc_pattern = ccdc_sgrbg_pattern;
break;
}
ccdc_config_imgattr(ccdc, ccdc_pattern);
/* Generate VD0 on the last line of the image and VD1 on the
* 2/3 height line.
*/
isp_reg_writel(isp, ((format->height - 2) << ISPCCDC_VDINT_0_SHIFT) |
((format->height * 2 / 3) << ISPCCDC_VDINT_1_SHIFT),
OMAP3_ISP_IOMEM_CCDC, ISPCCDC_VDINT);
/* CCDC_PAD_SOURCE_OF */
format = &ccdc->formats[CCDC_PAD_SOURCE_OF];
isp_reg_writel(isp, (0 << ISPCCDC_HORZ_INFO_SPH_SHIFT) |
((format->width - 1) << ISPCCDC_HORZ_INFO_NPH_SHIFT),
OMAP3_ISP_IOMEM_CCDC, ISPCCDC_HORZ_INFO);
isp_reg_writel(isp, 0 << ISPCCDC_VERT_START_SLV0_SHIFT,
OMAP3_ISP_IOMEM_CCDC, ISPCCDC_VERT_START);
isp_reg_writel(isp, (format->height - 1)
<< ISPCCDC_VERT_LINES_NLV_SHIFT,
OMAP3_ISP_IOMEM_CCDC, ISPCCDC_VERT_LINES);
ccdc_config_outlineoffset(ccdc, ccdc->video_out.bpl_value, 0, 0);
/* CCDC_PAD_SOURCE_VP */
format = &ccdc->formats[CCDC_PAD_SOURCE_VP];
isp_reg_writel(isp, (0 << ISPCCDC_FMT_HORZ_FMTSPH_SHIFT) |
(format->width << ISPCCDC_FMT_HORZ_FMTLNH_SHIFT),
OMAP3_ISP_IOMEM_CCDC, ISPCCDC_FMT_HORZ);
isp_reg_writel(isp, (0 << ISPCCDC_FMT_VERT_FMTSLV_SHIFT) |
((format->height + 1) << ISPCCDC_FMT_VERT_FMTLNV_SHIFT),
OMAP3_ISP_IOMEM_CCDC, ISPCCDC_FMT_VERT);
isp_reg_writel(isp, (format->width << ISPCCDC_VP_OUT_HORZ_NUM_SHIFT) |
(format->height << ISPCCDC_VP_OUT_VERT_NUM_SHIFT),
OMAP3_ISP_IOMEM_CCDC, ISPCCDC_VP_OUT);
spin_lock_irqsave(&ccdc->lsc.req_lock, flags);
if (ccdc->lsc.request == NULL)
goto unlock;
WARN_ON(ccdc->lsc.active);
/* Get last good LSC configuration. If it is not supported for
* the current active resolution discard it.
*/
if (ccdc->lsc.active == NULL &&
__ccdc_lsc_configure(ccdc, ccdc->lsc.request) == 0) {
ccdc->lsc.active = ccdc->lsc.request;
} else {
list_add_tail(&ccdc->lsc.request->list, &ccdc->lsc.free_queue);
schedule_work(&ccdc->lsc.table_work);
}
ccdc->lsc.request = NULL;
unlock:
spin_unlock_irqrestore(&ccdc->lsc.req_lock, flags);
ccdc_apply_controls(ccdc);
}
static void __ccdc_enable(struct isp_ccdc_device *ccdc, int enable)
{
struct isp_device *isp = to_isp_device(ccdc);
isp_reg_clr_set(isp, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_PCR,
ISPCCDC_PCR_EN, enable ? ISPCCDC_PCR_EN : 0);
}
static int ccdc_disable(struct isp_ccdc_device *ccdc)
{
unsigned long flags;
int ret = 0;
spin_lock_irqsave(&ccdc->lock, flags);
if (ccdc->state == ISP_PIPELINE_STREAM_CONTINUOUS)
ccdc->stopping = CCDC_STOP_REQUEST;
spin_unlock_irqrestore(&ccdc->lock, flags);
ret = wait_event_timeout(ccdc->wait,
ccdc->stopping == CCDC_STOP_FINISHED,
msecs_to_jiffies(2000));
if (ret == 0) {
ret = -ETIMEDOUT;
dev_warn(to_device(ccdc), "CCDC stop timeout!\n");
}
omap3isp_sbl_disable(to_isp_device(ccdc), OMAP3_ISP_SBL_CCDC_LSC_READ);
mutex_lock(&ccdc->ioctl_lock);
ccdc_lsc_free_request(ccdc, ccdc->lsc.request);
ccdc->lsc.request = ccdc->lsc.active;
ccdc->lsc.active = NULL;
cancel_work_sync(&ccdc->lsc.table_work);
ccdc_lsc_free_queue(ccdc, &ccdc->lsc.free_queue);
mutex_unlock(&ccdc->ioctl_lock);
ccdc->stopping = CCDC_STOP_NOT_REQUESTED;
return ret > 0 ? 0 : ret;
}
static void ccdc_enable(struct isp_ccdc_device *ccdc)
{
if (ccdc_lsc_is_configured(ccdc))
__ccdc_lsc_enable(ccdc, 1);
__ccdc_enable(ccdc, 1);
}
/* -----------------------------------------------------------------------------
* Interrupt handling
*/
/*
* ccdc_sbl_busy - Poll idle state of CCDC and related SBL memory write bits
* @ccdc: Pointer to ISP CCDC device.
*
* Returns zero if the CCDC is idle and the image has been written to
* memory, too.
*/
static int ccdc_sbl_busy(struct isp_ccdc_device *ccdc)
{
struct isp_device *isp = to_isp_device(ccdc);
return omap3isp_ccdc_busy(ccdc)
| (isp_reg_readl(isp, OMAP3_ISP_IOMEM_SBL, ISPSBL_CCDC_WR_0) &
ISPSBL_CCDC_WR_0_DATA_READY)
| (isp_reg_readl(isp, OMAP3_ISP_IOMEM_SBL, ISPSBL_CCDC_WR_1) &
ISPSBL_CCDC_WR_0_DATA_READY)
| (isp_reg_readl(isp, OMAP3_ISP_IOMEM_SBL, ISPSBL_CCDC_WR_2) &
ISPSBL_CCDC_WR_0_DATA_READY)
| (isp_reg_readl(isp, OMAP3_ISP_IOMEM_SBL, ISPSBL_CCDC_WR_3) &
ISPSBL_CCDC_WR_0_DATA_READY);
}
/*
* ccdc_sbl_wait_idle - Wait until the CCDC and related SBL are idle
* @ccdc: Pointer to ISP CCDC device.
* @max_wait: Max retry count in us for wait for idle/busy transition.
*/
static int ccdc_sbl_wait_idle(struct isp_ccdc_device *ccdc,
unsigned int max_wait)
{
unsigned int wait = 0;
if (max_wait == 0)
max_wait = 10000; /* 10 ms */
for (wait = 0; wait <= max_wait; wait++) {
if (!ccdc_sbl_busy(ccdc))
return 0;
rmb();
udelay(1);
}
return -EBUSY;
}
/* __ccdc_handle_stopping - Handle CCDC and/or LSC stopping sequence
* @ccdc: Pointer to ISP CCDC device.
* @event: Pointing which event trigger handler
*
* Return 1 when the event and stopping request combination is satisfied,
* zero otherwise.
*/
static int __ccdc_handle_stopping(struct isp_ccdc_device *ccdc, u32 event)
{
int rval = 0;
switch ((ccdc->stopping & 3) | event) {
case CCDC_STOP_REQUEST | CCDC_EVENT_VD1:
if (ccdc->lsc.state != LSC_STATE_STOPPED)
__ccdc_lsc_enable(ccdc, 0);
__ccdc_enable(ccdc, 0);
ccdc->stopping = CCDC_STOP_EXECUTED;
return 1;
case CCDC_STOP_EXECUTED | CCDC_EVENT_VD0:
ccdc->stopping |= CCDC_STOP_CCDC_FINISHED;
if (ccdc->lsc.state == LSC_STATE_STOPPED)
ccdc->stopping |= CCDC_STOP_LSC_FINISHED;
rval = 1;
break;
case CCDC_STOP_EXECUTED | CCDC_EVENT_LSC_DONE:
ccdc->stopping |= CCDC_STOP_LSC_FINISHED;
rval = 1;
break;
case CCDC_STOP_EXECUTED | CCDC_EVENT_VD1:
return 1;
}
if (ccdc->stopping == CCDC_STOP_FINISHED) {
wake_up(&ccdc->wait);
rval = 1;
}
return rval;
}
static void ccdc_hs_vs_isr(struct isp_ccdc_device *ccdc)
{
struct isp_pipeline *pipe = to_isp_pipeline(&ccdc->subdev.entity);
struct video_device *vdev = ccdc->subdev.devnode;
struct v4l2_event event;
memset(&event, 0, sizeof(event));
event.type = V4L2_EVENT_FRAME_SYNC;
event.u.frame_sync.frame_sequence = atomic_read(&pipe->frame_number);
v4l2_event_queue(vdev, &event);
}
/*
* ccdc_lsc_isr - Handle LSC events
* @ccdc: Pointer to ISP CCDC device.
* @events: LSC events
*/
static void ccdc_lsc_isr(struct isp_ccdc_device *ccdc, u32 events)
{
unsigned long flags;
if (events & IRQ0STATUS_CCDC_LSC_PREF_ERR_IRQ) {
struct isp_pipeline *pipe =
to_isp_pipeline(&ccdc->subdev.entity);
ccdc_lsc_error_handler(ccdc);
pipe->error = true;
dev_dbg(to_device(ccdc), "lsc prefetch error\n");
}
if (!(events & IRQ0STATUS_CCDC_LSC_DONE_IRQ))
return;
/* LSC_DONE interrupt occur, there are two cases
* 1. stopping for reconfiguration
* 2. stopping because of STREAM OFF command
*/
spin_lock_irqsave(&ccdc->lsc.req_lock, flags);
if (ccdc->lsc.state == LSC_STATE_STOPPING)
ccdc->lsc.state = LSC_STATE_STOPPED;
if (__ccdc_handle_stopping(ccdc, CCDC_EVENT_LSC_DONE))
goto done;
if (ccdc->lsc.state != LSC_STATE_RECONFIG)
goto done;
/* LSC is in STOPPING state, change to the new state */
ccdc->lsc.state = LSC_STATE_STOPPED;
/* This is an exception. Start of frame and LSC_DONE interrupt
* have been received on the same time. Skip this event and wait
* for better times.
*/
if (events & IRQ0STATUS_HS_VS_IRQ)
goto done;
/* The LSC engine is stopped at this point. Enable it if there's a
* pending request.
*/
if (ccdc->lsc.request == NULL)
goto done;
ccdc_lsc_enable(ccdc);
done:
spin_unlock_irqrestore(&ccdc->lsc.req_lock, flags);
}
static int ccdc_isr_buffer(struct isp_ccdc_device *ccdc)
{
struct isp_pipeline *pipe = to_isp_pipeline(&ccdc->subdev.entity);
struct isp_device *isp = to_isp_device(ccdc);
struct isp_buffer *buffer;
int restart = 0;
/* The CCDC generates VD0 interrupts even when disabled (the datasheet
* doesn't explicitly state if that's supposed to happen or not, so it
* can be considered as a hardware bug or as a feature, but we have to
* deal with it anyway). Disabling the CCDC when no buffer is available
* would thus not be enough, we need to handle the situation explicitly.
*/
if (list_empty(&ccdc->video_out.dmaqueue))
goto done;
/* We're in continuous mode, and memory writes were disabled due to a
* buffer underrun. Reenable them now that we have a buffer. The buffer
* address has been set in ccdc_video_queue.
*/
if (ccdc->state == ISP_PIPELINE_STREAM_CONTINUOUS && ccdc->underrun) {
restart = 1;
ccdc->underrun = 0;
goto done;
}
if (ccdc_sbl_wait_idle(ccdc, 1000)) {
dev_info(isp->dev, "CCDC won't become idle!\n");
goto done;
}
buffer = omap3isp_video_buffer_next(&ccdc->video_out);
if (buffer != NULL) {
ccdc_set_outaddr(ccdc, buffer->isp_addr);
restart = 1;
}
pipe->state |= ISP_PIPELINE_IDLE_OUTPUT;
if (ccdc->state == ISP_PIPELINE_STREAM_SINGLESHOT &&
isp_pipeline_ready(pipe))
omap3isp_pipeline_set_stream(pipe,
ISP_PIPELINE_STREAM_SINGLESHOT);
done:
return restart;
}
/*
* ccdc_vd0_isr - Handle VD0 event
* @ccdc: Pointer to ISP CCDC device.
*
* Executes LSC deferred enablement before next frame starts.
*/
static void ccdc_vd0_isr(struct isp_ccdc_device *ccdc)
{
unsigned long flags;
int restart = 0;
if (ccdc->output & CCDC_OUTPUT_MEMORY)
restart = ccdc_isr_buffer(ccdc);
spin_lock_irqsave(&ccdc->lock, flags);
if (__ccdc_handle_stopping(ccdc, CCDC_EVENT_VD0)) {
spin_unlock_irqrestore(&ccdc->lock, flags);
return;
}
if (!ccdc->shadow_update)
ccdc_apply_controls(ccdc);
spin_unlock_irqrestore(&ccdc->lock, flags);
if (restart)
ccdc_enable(ccdc);
}
/*
* ccdc_vd1_isr - Handle VD1 event
* @ccdc: Pointer to ISP CCDC device.
*/
static void ccdc_vd1_isr(struct isp_ccdc_device *ccdc)
{
unsigned long flags;
spin_lock_irqsave(&ccdc->lsc.req_lock, flags);
/*
* Depending on the CCDC pipeline state, CCDC stopping should be
* handled differently. In SINGLESHOT we emulate an internal CCDC
* stopping because the CCDC hw works only in continuous mode.
* When CONTINUOUS pipeline state is used and the CCDC writes it's
* data to memory the CCDC and LSC are stopped immediately but
* without change the CCDC stopping state machine. The CCDC
* stopping state machine should be used only when user request
* for stopping is received (SINGLESHOT is an exeption).
*/
switch (ccdc->state) {
case ISP_PIPELINE_STREAM_SINGLESHOT:
ccdc->stopping = CCDC_STOP_REQUEST;
break;
case ISP_PIPELINE_STREAM_CONTINUOUS:
if (ccdc->output & CCDC_OUTPUT_MEMORY) {
if (ccdc->lsc.state != LSC_STATE_STOPPED)
__ccdc_lsc_enable(ccdc, 0);
__ccdc_enable(ccdc, 0);
}
break;
case ISP_PIPELINE_STREAM_STOPPED:
break;
}
if (__ccdc_handle_stopping(ccdc, CCDC_EVENT_VD1))
goto done;
if (ccdc->lsc.request == NULL)
goto done;
/*
* LSC need to be reconfigured. Stop it here and on next LSC_DONE IRQ
* do the appropriate changes in registers
*/
if (ccdc->lsc.state == LSC_STATE_RUNNING) {
__ccdc_lsc_enable(ccdc, 0);
ccdc->lsc.state = LSC_STATE_RECONFIG;
goto done;
}
/* LSC has been in STOPPED state, enable it */
if (ccdc->lsc.state == LSC_STATE_STOPPED)
ccdc_lsc_enable(ccdc);
done:
spin_unlock_irqrestore(&ccdc->lsc.req_lock, flags);
}
/*
* omap3isp_ccdc_isr - Configure CCDC during interframe time.
* @ccdc: Pointer to ISP CCDC device.
* @events: CCDC events
*/
int omap3isp_ccdc_isr(struct isp_ccdc_device *ccdc, u32 events)
{
if (ccdc->state == ISP_PIPELINE_STREAM_STOPPED)
return 0;
if (events & IRQ0STATUS_CCDC_VD1_IRQ)
ccdc_vd1_isr(ccdc);
ccdc_lsc_isr(ccdc, events);
if (events & IRQ0STATUS_CCDC_VD0_IRQ)
ccdc_vd0_isr(ccdc);
if (events & IRQ0STATUS_HS_VS_IRQ)
ccdc_hs_vs_isr(ccdc);
return 0;
}
/* -----------------------------------------------------------------------------
* ISP video operations
*/
static int ccdc_video_queue(struct isp_video *video, struct isp_buffer *buffer)
{
struct isp_ccdc_device *ccdc = &video->isp->isp_ccdc;
if (!(ccdc->output & CCDC_OUTPUT_MEMORY))
return -ENODEV;
ccdc_set_outaddr(ccdc, buffer->isp_addr);
/* We now have a buffer queued on the output, restart the pipeline
* on the next CCDC interrupt if running in continuous mode (or when
* starting the stream).
*/
ccdc->underrun = 1;
return 0;
}
static const struct isp_video_operations ccdc_video_ops = {
.queue = ccdc_video_queue,
};
/* -----------------------------------------------------------------------------
* V4L2 subdev operations
*/
/*
* ccdc_ioctl - CCDC module private ioctl's
* @sd: ISP CCDC V4L2 subdevice
* @cmd: ioctl command
* @arg: ioctl argument
*
* Return 0 on success or a negative error code otherwise.
*/
static long ccdc_ioctl(struct v4l2_subdev *sd, unsigned int cmd, void *arg)
{
struct isp_ccdc_device *ccdc = v4l2_get_subdevdata(sd);
int ret;
switch (cmd) {
case VIDIOC_OMAP3ISP_CCDC_CFG:
mutex_lock(&ccdc->ioctl_lock);
ret = ccdc_config(ccdc, arg);
mutex_unlock(&ccdc->ioctl_lock);
break;
default:
return -ENOIOCTLCMD;
}
return ret;
}
static int ccdc_subscribe_event(struct v4l2_subdev *sd, struct v4l2_fh *fh,
struct v4l2_event_subscription *sub)
{
if (sub->type != V4L2_EVENT_FRAME_SYNC)
return -EINVAL;
/* line number is zero at frame start */
if (sub->id != 0)
return -EINVAL;
return v4l2_event_subscribe(fh, sub, OMAP3ISP_CCDC_NEVENTS);
}
static int ccdc_unsubscribe_event(struct v4l2_subdev *sd, struct v4l2_fh *fh,
struct v4l2_event_subscription *sub)
{
return v4l2_event_unsubscribe(fh, sub);
}
/*
* ccdc_set_stream - Enable/Disable streaming on the CCDC module
* @sd: ISP CCDC V4L2 subdevice
* @enable: Enable/disable stream
*
* When writing to memory, the CCDC hardware can't be enabled without a memory
* buffer to write to. As the s_stream operation is called in response to a
* STREAMON call without any buffer queued yet, just update the enabled field
* and return immediately. The CCDC will be enabled in ccdc_isr_buffer().
*
* When not writing to memory enable the CCDC immediately.
*/
static int ccdc_set_stream(struct v4l2_subdev *sd, int enable)
{
struct isp_ccdc_device *ccdc = v4l2_get_subdevdata(sd);
struct isp_device *isp = to_isp_device(ccdc);
int ret = 0;
if (ccdc->state == ISP_PIPELINE_STREAM_STOPPED) {
if (enable == ISP_PIPELINE_STREAM_STOPPED)
return 0;
omap3isp_subclk_enable(isp, OMAP3_ISP_SUBCLK_CCDC);
isp_reg_set(isp, OMAP3_ISP_IOMEM_CCDC, ISPCCDC_CFG,
ISPCCDC_CFG_VDLC);
ccdc_configure(ccdc);
/* TODO: Don't configure the video port if all of its output
* links are inactive.
*/
ccdc_config_vp(ccdc);
ccdc_enable_vp(ccdc, 1);
ccdc_print_status(ccdc);
}
switch (enable) {
case ISP_PIPELINE_STREAM_CONTINUOUS:
if (ccdc->output & CCDC_OUTPUT_MEMORY)
omap3isp_sbl_enable(isp, OMAP3_ISP_SBL_CCDC_WRITE);
if (ccdc->underrun || !(ccdc->output & CCDC_OUTPUT_MEMORY))
ccdc_enable(ccdc);
ccdc->underrun = 0;
break;
case ISP_PIPELINE_STREAM_SINGLESHOT:
if (ccdc->output & CCDC_OUTPUT_MEMORY &&
ccdc->state != ISP_PIPELINE_STREAM_SINGLESHOT)
omap3isp_sbl_enable(isp, OMAP3_ISP_SBL_CCDC_WRITE);
ccdc_enable(ccdc);
break;
case ISP_PIPELINE_STREAM_STOPPED:
ret = ccdc_disable(ccdc);
if (ccdc->output & CCDC_OUTPUT_MEMORY)
omap3isp_sbl_disable(isp, OMAP3_ISP_SBL_CCDC_WRITE);
omap3isp_subclk_disable(isp, OMAP3_ISP_SUBCLK_CCDC);
ccdc->underrun = 0;
break;
}
ccdc->state = enable;
return ret;
}
static struct v4l2_mbus_framefmt *
__ccdc_get_format(struct isp_ccdc_device *ccdc, struct v4l2_subdev_fh *fh,
unsigned int pad, enum v4l2_subdev_format_whence which)
{
if (which == V4L2_SUBDEV_FORMAT_TRY)
return v4l2_subdev_get_try_format(fh, pad);
else
return &ccdc->formats[pad];
}
/*
* ccdc_try_format - Try video format on a pad
* @ccdc: ISP CCDC device
* @fh : V4L2 subdev file handle
* @pad: Pad number
* @fmt: Format
*/
static void
ccdc_try_format(struct isp_ccdc_device *ccdc, struct v4l2_subdev_fh *fh,
unsigned int pad, struct v4l2_mbus_framefmt *fmt,
enum v4l2_subdev_format_whence which)
{
struct v4l2_mbus_framefmt *format;
const struct isp_format_info *info;
unsigned int width = fmt->width;
unsigned int height = fmt->height;
unsigned int i;
switch (pad) {
case CCDC_PAD_SINK:
/* TODO: If the CCDC output formatter pad is connected directly
* to the resizer, only YUV formats can be used.
*/
for (i = 0; i < ARRAY_SIZE(ccdc_fmts); i++) {
if (fmt->code == ccdc_fmts[i])
break;
}
/* If not found, use SGRBG10 as default */
if (i >= ARRAY_SIZE(ccdc_fmts))
fmt->code = V4L2_MBUS_FMT_SGRBG10_1X10;
/* Clamp the input size. */
fmt->width = clamp_t(u32, width, 32, 4096);
fmt->height = clamp_t(u32, height, 32, 4096);
break;
case CCDC_PAD_SOURCE_OF:
format = __ccdc_get_format(ccdc, fh, CCDC_PAD_SINK, which);
memcpy(fmt, format, sizeof(*fmt));
/* The data formatter truncates the number of horizontal output
* pixels to a multiple of 16. To avoid clipping data, allow
* callers to request an output size bigger than the input size
* up to the nearest multiple of 16.
*/
fmt->width = clamp_t(u32, width, 32, fmt->width + 15);
fmt->width &= ~15;
fmt->height = clamp_t(u32, height, 32, fmt->height);
break;
case CCDC_PAD_SOURCE_VP:
format = __ccdc_get_format(ccdc, fh, CCDC_PAD_SINK, which);
memcpy(fmt, format, sizeof(*fmt));
/* The video port interface truncates the data to 10 bits. */
info = omap3isp_video_format_info(fmt->code);
fmt->code = info->truncated;
/* The number of lines that can be clocked out from the video
* port output must be at least one line less than the number
* of input lines.
*/
fmt->width = clamp_t(u32, width, 32, fmt->width);
fmt->height = clamp_t(u32, height, 32, fmt->height - 1);
break;
}
/* Data is written to memory unpacked, each 10-bit or 12-bit pixel is
* stored on 2 bytes.
*/
fmt->colorspace = V4L2_COLORSPACE_SRGB;
fmt->field = V4L2_FIELD_NONE;
}
/*
* ccdc_enum_mbus_code - Handle pixel format enumeration
* @sd : pointer to v4l2 subdev structure
* @fh : V4L2 subdev file handle
* @code : pointer to v4l2_subdev_mbus_code_enum structure
* return -EINVAL or zero on success
*/
static int ccdc_enum_mbus_code(struct v4l2_subdev *sd,
struct v4l2_subdev_fh *fh,
struct v4l2_subdev_mbus_code_enum *code)
{
struct isp_ccdc_device *ccdc = v4l2_get_subdevdata(sd);
struct v4l2_mbus_framefmt *format;
switch (code->pad) {
case CCDC_PAD_SINK:
if (code->index >= ARRAY_SIZE(ccdc_fmts))
return -EINVAL;
code->code = ccdc_fmts[code->index];
break;
case CCDC_PAD_SOURCE_OF:
case CCDC_PAD_SOURCE_VP:
/* No format conversion inside CCDC */
if (code->index != 0)
return -EINVAL;
format = __ccdc_get_format(ccdc, fh, CCDC_PAD_SINK,
V4L2_SUBDEV_FORMAT_TRY);
code->code = format->code;
break;
default:
return -EINVAL;
}
return 0;
}
static int ccdc_enum_frame_size(struct v4l2_subdev *sd,
struct v4l2_subdev_fh *fh,
struct v4l2_subdev_frame_size_enum *fse)
{
struct isp_ccdc_device *ccdc = v4l2_get_subdevdata(sd);
struct v4l2_mbus_framefmt format;
if (fse->index != 0)
return -EINVAL;
format.code = fse->code;
format.width = 1;
format.height = 1;
ccdc_try_format(ccdc, fh, fse->pad, &format, V4L2_SUBDEV_FORMAT_TRY);
fse->min_width = format.width;
fse->min_height = format.height;
if (format.code != fse->code)
return -EINVAL;
format.code = fse->code;
format.width = -1;
format.height = -1;
ccdc_try_format(ccdc, fh, fse->pad, &format, V4L2_SUBDEV_FORMAT_TRY);
fse->max_width = format.width;
fse->max_height = format.height;
return 0;
}
/*
* ccdc_get_format - Retrieve the video format on a pad
* @sd : ISP CCDC V4L2 subdevice
* @fh : V4L2 subdev file handle
* @fmt: Format
*
* Return 0 on success or -EINVAL if the pad is invalid or doesn't correspond
* to the format type.
*/
static int ccdc_get_format(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh,
struct v4l2_subdev_format *fmt)
{
struct isp_ccdc_device *ccdc = v4l2_get_subdevdata(sd);
struct v4l2_mbus_framefmt *format;
format = __ccdc_get_format(ccdc, fh, fmt->pad, fmt->which);
if (format == NULL)
return -EINVAL;
fmt->format = *format;
return 0;
}
/*
* ccdc_set_format - Set the video format on a pad
* @sd : ISP CCDC V4L2 subdevice
* @fh : V4L2 subdev file handle
* @fmt: Format
*
* Return 0 on success or -EINVAL if the pad is invalid or doesn't correspond
* to the format type.
*/
static int ccdc_set_format(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh,
struct v4l2_subdev_format *fmt)
{
struct isp_ccdc_device *ccdc = v4l2_get_subdevdata(sd);
struct v4l2_mbus_framefmt *format;
format = __ccdc_get_format(ccdc, fh, fmt->pad, fmt->which);
if (format == NULL)
return -EINVAL;
ccdc_try_format(ccdc, fh, fmt->pad, &fmt->format, fmt->which);
*format = fmt->format;
/* Propagate the format from sink to source */
if (fmt->pad == CCDC_PAD_SINK) {
format = __ccdc_get_format(ccdc, fh, CCDC_PAD_SOURCE_OF,
fmt->which);
*format = fmt->format;
ccdc_try_format(ccdc, fh, CCDC_PAD_SOURCE_OF, format,
fmt->which);
format = __ccdc_get_format(ccdc, fh, CCDC_PAD_SOURCE_VP,
fmt->which);
*format = fmt->format;
ccdc_try_format(ccdc, fh, CCDC_PAD_SOURCE_VP, format,
fmt->which);
}
return 0;
}
/*
* ccdc_init_formats - Initialize formats on all pads
* @sd: ISP CCDC V4L2 subdevice
* @fh: V4L2 subdev file handle
*
* Initialize all pad formats with default values. If fh is not NULL, try
* formats are initialized on the file handle. Otherwise active formats are
* initialized on the device.
*/
static int ccdc_init_formats(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh)
{
struct v4l2_subdev_format format;
memset(&format, 0, sizeof(format));
format.pad = CCDC_PAD_SINK;
format.which = fh ? V4L2_SUBDEV_FORMAT_TRY : V4L2_SUBDEV_FORMAT_ACTIVE;
format.format.code = V4L2_MBUS_FMT_SGRBG10_1X10;
format.format.width = 4096;
format.format.height = 4096;
ccdc_set_format(sd, fh, &format);
return 0;
}
/* V4L2 subdev core operations */
static const struct v4l2_subdev_core_ops ccdc_v4l2_core_ops = {
.ioctl = ccdc_ioctl,
.subscribe_event = ccdc_subscribe_event,
.unsubscribe_event = ccdc_unsubscribe_event,
};
/* V4L2 subdev video operations */
static const struct v4l2_subdev_video_ops ccdc_v4l2_video_ops = {
.s_stream = ccdc_set_stream,
};
/* V4L2 subdev pad operations */
static const struct v4l2_subdev_pad_ops ccdc_v4l2_pad_ops = {
.enum_mbus_code = ccdc_enum_mbus_code,
.enum_frame_size = ccdc_enum_frame_size,
.get_fmt = ccdc_get_format,
.set_fmt = ccdc_set_format,
};
/* V4L2 subdev operations */
static const struct v4l2_subdev_ops ccdc_v4l2_ops = {
.core = &ccdc_v4l2_core_ops,
.video = &ccdc_v4l2_video_ops,
.pad = &ccdc_v4l2_pad_ops,
};
/* V4L2 subdev internal operations */
static const struct v4l2_subdev_internal_ops ccdc_v4l2_internal_ops = {
.open = ccdc_init_formats,
};
/* -----------------------------------------------------------------------------
* Media entity operations
*/
/*
* ccdc_link_setup - Setup CCDC connections
* @entity: CCDC media entity
* @local: Pad at the local end of the link
* @remote: Pad at the remote end of the link
* @flags: Link flags
*
* return -EINVAL or zero on success
*/
static int ccdc_link_setup(struct media_entity *entity,
const struct media_pad *local,
const struct media_pad *remote, u32 flags)
{
struct v4l2_subdev *sd = media_entity_to_v4l2_subdev(entity);
struct isp_ccdc_device *ccdc = v4l2_get_subdevdata(sd);
struct isp_device *isp = to_isp_device(ccdc);
switch (local->index | media_entity_type(remote->entity)) {
case CCDC_PAD_SINK | MEDIA_ENT_T_V4L2_SUBDEV:
/* Read from the sensor (parallel interface), CCP2, CSI2a or
* CSI2c.
*/
if (!(flags & MEDIA_LNK_FL_ENABLED)) {
ccdc->input = CCDC_INPUT_NONE;
break;
}
if (ccdc->input != CCDC_INPUT_NONE)
return -EBUSY;
if (remote->entity == &isp->isp_ccp2.subdev.entity)
ccdc->input = CCDC_INPUT_CCP2B;
else if (remote->entity == &isp->isp_csi2a.subdev.entity)
ccdc->input = CCDC_INPUT_CSI2A;
else if (remote->entity == &isp->isp_csi2c.subdev.entity)
ccdc->input = CCDC_INPUT_CSI2C;
else
ccdc->input = CCDC_INPUT_PARALLEL;
break;
/*
* The ISP core doesn't support pipelines with multiple video outputs.
* Revisit this when it will be implemented, and return -EBUSY for now.
*/
case CCDC_PAD_SOURCE_VP | MEDIA_ENT_T_V4L2_SUBDEV:
/* Write to preview engine, histogram and H3A. When none of
* those links are active, the video port can be disabled.
*/
if (flags & MEDIA_LNK_FL_ENABLED) {
if (ccdc->output & ~CCDC_OUTPUT_PREVIEW)
return -EBUSY;
ccdc->output |= CCDC_OUTPUT_PREVIEW;
} else {
ccdc->output &= ~CCDC_OUTPUT_PREVIEW;
}
break;
case CCDC_PAD_SOURCE_OF | MEDIA_ENT_T_DEVNODE:
/* Write to memory */
if (flags & MEDIA_LNK_FL_ENABLED) {
if (ccdc->output & ~CCDC_OUTPUT_MEMORY)
return -EBUSY;
ccdc->output |= CCDC_OUTPUT_MEMORY;
} else {
ccdc->output &= ~CCDC_OUTPUT_MEMORY;
}
break;
case CCDC_PAD_SOURCE_OF | MEDIA_ENT_T_V4L2_SUBDEV:
/* Write to resizer */
if (flags & MEDIA_LNK_FL_ENABLED) {
if (ccdc->output & ~CCDC_OUTPUT_RESIZER)
return -EBUSY;
ccdc->output |= CCDC_OUTPUT_RESIZER;
} else {
ccdc->output &= ~CCDC_OUTPUT_RESIZER;
}
break;
default:
return -EINVAL;
}
return 0;
}
/* media operations */
static const struct media_entity_operations ccdc_media_ops = {
.link_setup = ccdc_link_setup,
};
void omap3isp_ccdc_unregister_entities(struct isp_ccdc_device *ccdc)
{
v4l2_device_unregister_subdev(&ccdc->subdev);
omap3isp_video_unregister(&ccdc->video_out);
}
int omap3isp_ccdc_register_entities(struct isp_ccdc_device *ccdc,
struct v4l2_device *vdev)
{
int ret;
/* Register the subdev and video node. */
ret = v4l2_device_register_subdev(vdev, &ccdc->subdev);
if (ret < 0)
goto error;
ret = omap3isp_video_register(&ccdc->video_out, vdev);
if (ret < 0)
goto error;
return 0;
error:
omap3isp_ccdc_unregister_entities(ccdc);
return ret;
}
/* -----------------------------------------------------------------------------
* ISP CCDC initialisation and cleanup
*/
/*
* ccdc_init_entities - Initialize V4L2 subdev and media entity
* @ccdc: ISP CCDC module
*
* Return 0 on success and a negative error code on failure.
*/
static int ccdc_init_entities(struct isp_ccdc_device *ccdc)
{
struct v4l2_subdev *sd = &ccdc->subdev;
struct media_pad *pads = ccdc->pads;
struct media_entity *me = &sd->entity;
int ret;
ccdc->input = CCDC_INPUT_NONE;
v4l2_subdev_init(sd, &ccdc_v4l2_ops);
sd->internal_ops = &ccdc_v4l2_internal_ops;
strlcpy(sd->name, "OMAP3 ISP CCDC", sizeof(sd->name));
sd->grp_id = 1 << 16; /* group ID for isp subdevs */
v4l2_set_subdevdata(sd, ccdc);
sd->flags |= V4L2_SUBDEV_FL_HAS_EVENTS | V4L2_SUBDEV_FL_HAS_DEVNODE;
pads[CCDC_PAD_SINK].flags = MEDIA_PAD_FL_SINK;
pads[CCDC_PAD_SOURCE_VP].flags = MEDIA_PAD_FL_SOURCE;
pads[CCDC_PAD_SOURCE_OF].flags = MEDIA_PAD_FL_SOURCE;
me->ops = &ccdc_media_ops;
ret = media_entity_init(me, CCDC_PADS_NUM, pads, 0);
if (ret < 0)
return ret;
ccdc_init_formats(sd, NULL);
ccdc->video_out.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
ccdc->video_out.ops = &ccdc_video_ops;
ccdc->video_out.isp = to_isp_device(ccdc);
ccdc->video_out.capture_mem = PAGE_ALIGN(4096 * 4096) * 3;
ccdc->video_out.bpl_alignment = 32;
ret = omap3isp_video_init(&ccdc->video_out, "CCDC");
if (ret < 0)
goto error_video;
/* Connect the CCDC subdev to the video node. */
ret = media_entity_create_link(&ccdc->subdev.entity, CCDC_PAD_SOURCE_OF,
&ccdc->video_out.video.entity, 0, 0);
if (ret < 0)
goto error_link;
return 0;
error_link:
omap3isp_video_cleanup(&ccdc->video_out);
error_video:
media_entity_cleanup(me);
return ret;
}
/*
* omap3isp_ccdc_init - CCDC module initialization.
* @dev: Device pointer specific to the OMAP3 ISP.
*
* TODO: Get the initialisation values from platform data.
*
* Return 0 on success or a negative error code otherwise.
*/
int omap3isp_ccdc_init(struct isp_device *isp)
{
struct isp_ccdc_device *ccdc = &isp->isp_ccdc;
int ret;
spin_lock_init(&ccdc->lock);
init_waitqueue_head(&ccdc->wait);
mutex_init(&ccdc->ioctl_lock);
ccdc->stopping = CCDC_STOP_NOT_REQUESTED;
INIT_WORK(&ccdc->lsc.table_work, ccdc_lsc_free_table_work);
ccdc->lsc.state = LSC_STATE_STOPPED;
INIT_LIST_HEAD(&ccdc->lsc.free_queue);
spin_lock_init(&ccdc->lsc.req_lock);
ccdc->syncif.ccdc_mastermode = 0;
ccdc->syncif.datapol = 0;
ccdc->syncif.datsz = 0;
ccdc->syncif.fldmode = 0;
ccdc->syncif.fldout = 0;
ccdc->syncif.fldpol = 0;
ccdc->syncif.fldstat = 0;
ccdc->clamp.oblen = 0;
ccdc->clamp.dcsubval = 0;
ccdc->vpcfg.pixelclk = 0;
ccdc->update = OMAP3ISP_CCDC_BLCLAMP;
ccdc_apply_controls(ccdc);
ret = ccdc_init_entities(ccdc);
if (ret < 0) {
mutex_destroy(&ccdc->ioctl_lock);
return ret;
}
return 0;
}
/*
* omap3isp_ccdc_cleanup - CCDC module cleanup.
* @dev: Device pointer specific to the OMAP3 ISP.
*/
void omap3isp_ccdc_cleanup(struct isp_device *isp)
{
struct isp_ccdc_device *ccdc = &isp->isp_ccdc;
omap3isp_video_cleanup(&ccdc->video_out);
media_entity_cleanup(&ccdc->subdev.entity);
/* Free LSC requests. As the CCDC is stopped there's no active request,
* so only the pending request and the free queue need to be handled.
*/
ccdc_lsc_free_request(ccdc, ccdc->lsc.request);
cancel_work_sync(&ccdc->lsc.table_work);
ccdc_lsc_free_queue(ccdc, &ccdc->lsc.free_queue);
if (ccdc->fpc.fpcaddr != 0)
omap_iommu_vfree(isp->domain, isp->dev, ccdc->fpc.fpcaddr);
mutex_destroy(&ccdc->ioctl_lock);
}
| gpl-2.0 |
talnoah/Leaping_Lemur-AOSP | drivers/scsi/aacraid/comminit.c | 4852 | 14963 | /*
* Adaptec AAC series RAID controller driver
* (c) Copyright 2001 Red Hat Inc.
*
* based on the old aacraid driver that is..
* Adaptec aacraid device driver for Linux.
*
* Copyright (c) 2000-2010 Adaptec, Inc.
* 2010 PMC-Sierra, Inc. (aacraid@pmc-sierra.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Module Name:
* comminit.c
*
* Abstract: This supports the initialization of the host adapter commuication interface.
* This is a platform dependent module for the pci cyclone board.
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/spinlock.h>
#include <linux/slab.h>
#include <linux/blkdev.h>
#include <linux/completion.h>
#include <linux/mm.h>
#include <scsi/scsi_host.h>
#include "aacraid.h"
struct aac_common aac_config = {
.irq_mod = 1
};
static int aac_alloc_comm(struct aac_dev *dev, void **commaddr, unsigned long commsize, unsigned long commalign)
{
unsigned char *base;
unsigned long size, align;
const unsigned long fibsize = 4096;
const unsigned long printfbufsiz = 256;
unsigned long host_rrq_size = 0;
struct aac_init *init;
dma_addr_t phys;
unsigned long aac_max_hostphysmempages;
if (dev->comm_interface == AAC_COMM_MESSAGE_TYPE1)
host_rrq_size = (dev->scsi_host_ptr->can_queue
+ AAC_NUM_MGT_FIB) * sizeof(u32);
size = fibsize + sizeof(struct aac_init) + commsize +
commalign + printfbufsiz + host_rrq_size;
base = pci_alloc_consistent(dev->pdev, size, &phys);
if(base == NULL)
{
printk(KERN_ERR "aacraid: unable to create mapping.\n");
return 0;
}
dev->comm_addr = (void *)base;
dev->comm_phys = phys;
dev->comm_size = size;
if (dev->comm_interface == AAC_COMM_MESSAGE_TYPE1) {
dev->host_rrq = (u32 *)(base + fibsize);
dev->host_rrq_pa = phys + fibsize;
memset(dev->host_rrq, 0, host_rrq_size);
}
dev->init = (struct aac_init *)(base + fibsize + host_rrq_size);
dev->init_pa = phys + fibsize + host_rrq_size;
init = dev->init;
init->InitStructRevision = cpu_to_le32(ADAPTER_INIT_STRUCT_REVISION);
if (dev->max_fib_size != sizeof(struct hw_fib))
init->InitStructRevision = cpu_to_le32(ADAPTER_INIT_STRUCT_REVISION_4);
init->MiniPortRevision = cpu_to_le32(Sa_MINIPORT_REVISION);
init->fsrev = cpu_to_le32(dev->fsrev);
/*
* Adapter Fibs are the first thing allocated so that they
* start page aligned
*/
dev->aif_base_va = (struct hw_fib *)base;
init->AdapterFibsVirtualAddress = 0;
init->AdapterFibsPhysicalAddress = cpu_to_le32((u32)phys);
init->AdapterFibsSize = cpu_to_le32(fibsize);
init->AdapterFibAlign = cpu_to_le32(sizeof(struct hw_fib));
/*
* number of 4k pages of host physical memory. The aacraid fw needs
* this number to be less than 4gb worth of pages. New firmware doesn't
* have any issues with the mapping system, but older Firmware did, and
* had *troubles* dealing with the math overloading past 32 bits, thus
* we must limit this field.
*/
aac_max_hostphysmempages = dma_get_required_mask(&dev->pdev->dev) >> 12;
if (aac_max_hostphysmempages < AAC_MAX_HOSTPHYSMEMPAGES)
init->HostPhysMemPages = cpu_to_le32(aac_max_hostphysmempages);
else
init->HostPhysMemPages = cpu_to_le32(AAC_MAX_HOSTPHYSMEMPAGES);
init->InitFlags = 0;
if (dev->comm_interface == AAC_COMM_MESSAGE) {
init->InitFlags |= cpu_to_le32(INITFLAGS_NEW_COMM_SUPPORTED);
dprintk((KERN_WARNING"aacraid: New Comm Interface enabled\n"));
} else if (dev->comm_interface == AAC_COMM_MESSAGE_TYPE1) {
init->InitStructRevision = cpu_to_le32(ADAPTER_INIT_STRUCT_REVISION_6);
init->InitFlags |= cpu_to_le32(INITFLAGS_NEW_COMM_TYPE1_SUPPORTED);
dprintk((KERN_WARNING
"aacraid: New Comm Interface type1 enabled\n"));
}
init->InitFlags |= cpu_to_le32(INITFLAGS_DRIVER_USES_UTC_TIME |
INITFLAGS_DRIVER_SUPPORTS_PM);
init->MaxIoCommands = cpu_to_le32(dev->scsi_host_ptr->can_queue + AAC_NUM_MGT_FIB);
init->MaxIoSize = cpu_to_le32(dev->scsi_host_ptr->max_sectors << 9);
init->MaxFibSize = cpu_to_le32(dev->max_fib_size);
init->MaxNumAif = cpu_to_le32(dev->max_num_aif);
init->HostRRQ_AddrHigh = (u32)((u64)dev->host_rrq_pa >> 32);
init->HostRRQ_AddrLow = (u32)(dev->host_rrq_pa & 0xffffffff);
/*
* Increment the base address by the amount already used
*/
base = base + fibsize + host_rrq_size + sizeof(struct aac_init);
phys = (dma_addr_t)((ulong)phys + fibsize + host_rrq_size +
sizeof(struct aac_init));
/*
* Align the beginning of Headers to commalign
*/
align = (commalign - ((uintptr_t)(base) & (commalign - 1)));
base = base + align;
phys = phys + align;
/*
* Fill in addresses of the Comm Area Headers and Queues
*/
*commaddr = base;
init->CommHeaderAddress = cpu_to_le32((u32)phys);
/*
* Increment the base address by the size of the CommArea
*/
base = base + commsize;
phys = phys + commsize;
/*
* Place the Printf buffer area after the Fast I/O comm area.
*/
dev->printfbuf = (void *)base;
init->printfbuf = cpu_to_le32(phys);
init->printfbufsiz = cpu_to_le32(printfbufsiz);
memset(base, 0, printfbufsiz);
return 1;
}
static void aac_queue_init(struct aac_dev * dev, struct aac_queue * q, u32 *mem, int qsize)
{
q->numpending = 0;
q->dev = dev;
init_waitqueue_head(&q->cmdready);
INIT_LIST_HEAD(&q->cmdq);
init_waitqueue_head(&q->qfull);
spin_lock_init(&q->lockdata);
q->lock = &q->lockdata;
q->headers.producer = (__le32 *)mem;
q->headers.consumer = (__le32 *)(mem+1);
*(q->headers.producer) = cpu_to_le32(qsize);
*(q->headers.consumer) = cpu_to_le32(qsize);
q->entries = qsize;
}
/**
* aac_send_shutdown - shutdown an adapter
* @dev: Adapter to shutdown
*
* This routine will send a VM_CloseAll (shutdown) request to the adapter.
*/
int aac_send_shutdown(struct aac_dev * dev)
{
struct fib * fibctx;
struct aac_close *cmd;
int status;
fibctx = aac_fib_alloc(dev);
if (!fibctx)
return -ENOMEM;
aac_fib_init(fibctx);
cmd = (struct aac_close *) fib_data(fibctx);
cmd->command = cpu_to_le32(VM_CloseAll);
cmd->cid = cpu_to_le32(0xffffffff);
status = aac_fib_send(ContainerCommand,
fibctx,
sizeof(struct aac_close),
FsaNormal,
-2 /* Timeout silently */, 1,
NULL, NULL);
if (status >= 0)
aac_fib_complete(fibctx);
/* FIB should be freed only after getting the response from the F/W */
if (status != -ERESTARTSYS)
aac_fib_free(fibctx);
return status;
}
/**
* aac_comm_init - Initialise FSA data structures
* @dev: Adapter to initialise
*
* Initializes the data structures that are required for the FSA commuication
* interface to operate.
* Returns
* 1 - if we were able to init the commuication interface.
* 0 - If there were errors initing. This is a fatal error.
*/
static int aac_comm_init(struct aac_dev * dev)
{
unsigned long hdrsize = (sizeof(u32) * NUMBER_OF_COMM_QUEUES) * 2;
unsigned long queuesize = sizeof(struct aac_entry) * TOTAL_QUEUE_ENTRIES;
u32 *headers;
struct aac_entry * queues;
unsigned long size;
struct aac_queue_block * comm = dev->queues;
/*
* Now allocate and initialize the zone structures used as our
* pool of FIB context records. The size of the zone is based
* on the system memory size. We also initialize the mutex used
* to protect the zone.
*/
spin_lock_init(&dev->fib_lock);
/*
* Allocate the physically contiguous space for the commuication
* queue headers.
*/
size = hdrsize + queuesize;
if (!aac_alloc_comm(dev, (void * *)&headers, size, QUEUE_ALIGNMENT))
return -ENOMEM;
queues = (struct aac_entry *)(((ulong)headers) + hdrsize);
/* Adapter to Host normal priority Command queue */
comm->queue[HostNormCmdQueue].base = queues;
aac_queue_init(dev, &comm->queue[HostNormCmdQueue], headers, HOST_NORM_CMD_ENTRIES);
queues += HOST_NORM_CMD_ENTRIES;
headers += 2;
/* Adapter to Host high priority command queue */
comm->queue[HostHighCmdQueue].base = queues;
aac_queue_init(dev, &comm->queue[HostHighCmdQueue], headers, HOST_HIGH_CMD_ENTRIES);
queues += HOST_HIGH_CMD_ENTRIES;
headers +=2;
/* Host to adapter normal priority command queue */
comm->queue[AdapNormCmdQueue].base = queues;
aac_queue_init(dev, &comm->queue[AdapNormCmdQueue], headers, ADAP_NORM_CMD_ENTRIES);
queues += ADAP_NORM_CMD_ENTRIES;
headers += 2;
/* host to adapter high priority command queue */
comm->queue[AdapHighCmdQueue].base = queues;
aac_queue_init(dev, &comm->queue[AdapHighCmdQueue], headers, ADAP_HIGH_CMD_ENTRIES);
queues += ADAP_HIGH_CMD_ENTRIES;
headers += 2;
/* adapter to host normal priority response queue */
comm->queue[HostNormRespQueue].base = queues;
aac_queue_init(dev, &comm->queue[HostNormRespQueue], headers, HOST_NORM_RESP_ENTRIES);
queues += HOST_NORM_RESP_ENTRIES;
headers += 2;
/* adapter to host high priority response queue */
comm->queue[HostHighRespQueue].base = queues;
aac_queue_init(dev, &comm->queue[HostHighRespQueue], headers, HOST_HIGH_RESP_ENTRIES);
queues += HOST_HIGH_RESP_ENTRIES;
headers += 2;
/* host to adapter normal priority response queue */
comm->queue[AdapNormRespQueue].base = queues;
aac_queue_init(dev, &comm->queue[AdapNormRespQueue], headers, ADAP_NORM_RESP_ENTRIES);
queues += ADAP_NORM_RESP_ENTRIES;
headers += 2;
/* host to adapter high priority response queue */
comm->queue[AdapHighRespQueue].base = queues;
aac_queue_init(dev, &comm->queue[AdapHighRespQueue], headers, ADAP_HIGH_RESP_ENTRIES);
comm->queue[AdapNormCmdQueue].lock = comm->queue[HostNormRespQueue].lock;
comm->queue[AdapHighCmdQueue].lock = comm->queue[HostHighRespQueue].lock;
comm->queue[AdapNormRespQueue].lock = comm->queue[HostNormCmdQueue].lock;
comm->queue[AdapHighRespQueue].lock = comm->queue[HostHighCmdQueue].lock;
return 0;
}
struct aac_dev *aac_init_adapter(struct aac_dev *dev)
{
u32 status[5];
struct Scsi_Host * host = dev->scsi_host_ptr;
extern int aac_sync_mode;
/*
* Check the preferred comm settings, defaults from template.
*/
dev->management_fib_count = 0;
spin_lock_init(&dev->manage_lock);
spin_lock_init(&dev->sync_lock);
dev->max_fib_size = sizeof(struct hw_fib);
dev->sg_tablesize = host->sg_tablesize = (dev->max_fib_size
- sizeof(struct aac_fibhdr)
- sizeof(struct aac_write) + sizeof(struct sgentry))
/ sizeof(struct sgentry);
dev->comm_interface = AAC_COMM_PRODUCER;
dev->raw_io_interface = dev->raw_io_64 = 0;
if ((!aac_adapter_sync_cmd(dev, GET_ADAPTER_PROPERTIES,
0, 0, 0, 0, 0, 0, status+0, status+1, status+2, NULL, NULL)) &&
(status[0] == 0x00000001)) {
if (status[1] & le32_to_cpu(AAC_OPT_NEW_COMM_64))
dev->raw_io_64 = 1;
dev->sync_mode = aac_sync_mode;
if (dev->a_ops.adapter_comm &&
(status[1] & le32_to_cpu(AAC_OPT_NEW_COMM))) {
dev->comm_interface = AAC_COMM_MESSAGE;
dev->raw_io_interface = 1;
if ((status[1] & le32_to_cpu(AAC_OPT_NEW_COMM_TYPE1))) {
/* driver supports TYPE1 (Tupelo) */
dev->comm_interface = AAC_COMM_MESSAGE_TYPE1;
} else if ((status[1] & le32_to_cpu(AAC_OPT_NEW_COMM_TYPE4)) ||
(status[1] & le32_to_cpu(AAC_OPT_NEW_COMM_TYPE3)) ||
(status[1] & le32_to_cpu(AAC_OPT_NEW_COMM_TYPE2))) {
/* driver doesn't support TYPE2 (Series7), TYPE3 and TYPE4 */
/* switch to sync. mode */
dev->comm_interface = AAC_COMM_MESSAGE_TYPE1;
dev->sync_mode = 1;
}
}
if ((dev->comm_interface == AAC_COMM_MESSAGE) &&
(status[2] > dev->base_size)) {
aac_adapter_ioremap(dev, 0);
dev->base_size = status[2];
if (aac_adapter_ioremap(dev, status[2])) {
/* remap failed, go back ... */
dev->comm_interface = AAC_COMM_PRODUCER;
if (aac_adapter_ioremap(dev, AAC_MIN_FOOTPRINT_SIZE)) {
printk(KERN_WARNING
"aacraid: unable to map adapter.\n");
return NULL;
}
}
}
}
if ((!aac_adapter_sync_cmd(dev, GET_COMM_PREFERRED_SETTINGS,
0, 0, 0, 0, 0, 0,
status+0, status+1, status+2, status+3, status+4))
&& (status[0] == 0x00000001)) {
/*
* status[1] >> 16 maximum command size in KB
* status[1] & 0xFFFF maximum FIB size
* status[2] >> 16 maximum SG elements to driver
* status[2] & 0xFFFF maximum SG elements from driver
* status[3] & 0xFFFF maximum number FIBs outstanding
*/
host->max_sectors = (status[1] >> 16) << 1;
/* Multiple of 32 for PMC */
dev->max_fib_size = status[1] & 0xFFE0;
host->sg_tablesize = status[2] >> 16;
dev->sg_tablesize = status[2] & 0xFFFF;
host->can_queue = (status[3] & 0xFFFF) - AAC_NUM_MGT_FIB;
dev->max_num_aif = status[4] & 0xFFFF;
/*
* NOTE:
* All these overrides are based on a fixed internal
* knowledge and understanding of existing adapters,
* acbsize should be set with caution.
*/
if (acbsize == 512) {
host->max_sectors = AAC_MAX_32BIT_SGBCOUNT;
dev->max_fib_size = 512;
dev->sg_tablesize = host->sg_tablesize
= (512 - sizeof(struct aac_fibhdr)
- sizeof(struct aac_write) + sizeof(struct sgentry))
/ sizeof(struct sgentry);
host->can_queue = AAC_NUM_IO_FIB;
} else if (acbsize == 2048) {
host->max_sectors = 512;
dev->max_fib_size = 2048;
host->sg_tablesize = 65;
dev->sg_tablesize = 81;
host->can_queue = 512 - AAC_NUM_MGT_FIB;
} else if (acbsize == 4096) {
host->max_sectors = 1024;
dev->max_fib_size = 4096;
host->sg_tablesize = 129;
dev->sg_tablesize = 166;
host->can_queue = 256 - AAC_NUM_MGT_FIB;
} else if (acbsize == 8192) {
host->max_sectors = 2048;
dev->max_fib_size = 8192;
host->sg_tablesize = 257;
dev->sg_tablesize = 337;
host->can_queue = 128 - AAC_NUM_MGT_FIB;
} else if (acbsize > 0) {
printk("Illegal acbsize=%d ignored\n", acbsize);
}
}
{
if (numacb > 0) {
if (numacb < host->can_queue)
host->can_queue = numacb;
else
printk("numacb=%d ignored\n", numacb);
}
}
/*
* Ok now init the communication subsystem
*/
dev->queues = kzalloc(sizeof(struct aac_queue_block), GFP_KERNEL);
if (dev->queues == NULL) {
printk(KERN_ERR "Error could not allocate comm region.\n");
return NULL;
}
if (aac_comm_init(dev)<0){
kfree(dev->queues);
return NULL;
}
/*
* Initialize the list of fibs
*/
if (aac_fib_setup(dev) < 0) {
kfree(dev->queues);
return NULL;
}
INIT_LIST_HEAD(&dev->fib_list);
INIT_LIST_HEAD(&dev->sync_fib_list);
return dev;
}
| gpl-2.0 |
D2005-devs/android_kernel_sony_msm8610-old | drivers/acpi/acpica/tbinstal.c | 4852 | 21649 | /******************************************************************************
*
* Module Name: tbinstal - ACPI table installation and removal
*
*****************************************************************************/
/*
* Copyright (C) 2000 - 2012, Intel Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*/
#include <acpi/acpi.h>
#include "accommon.h"
#include "acnamesp.h"
#include "actables.h"
#define _COMPONENT ACPI_TABLES
ACPI_MODULE_NAME("tbinstal")
/******************************************************************************
*
* FUNCTION: acpi_tb_verify_table
*
* PARAMETERS: table_desc - table
*
* RETURN: Status
*
* DESCRIPTION: this function is called to verify and map table
*
*****************************************************************************/
acpi_status acpi_tb_verify_table(struct acpi_table_desc *table_desc)
{
acpi_status status = AE_OK;
ACPI_FUNCTION_TRACE(tb_verify_table);
/* Map the table if necessary */
if (!table_desc->pointer) {
if ((table_desc->flags & ACPI_TABLE_ORIGIN_MASK) ==
ACPI_TABLE_ORIGIN_MAPPED) {
table_desc->pointer =
acpi_os_map_memory(table_desc->address,
table_desc->length);
}
if (!table_desc->pointer) {
return_ACPI_STATUS(AE_NO_MEMORY);
}
}
/* FACS is the odd table, has no standard ACPI header and no checksum */
if (!ACPI_COMPARE_NAME(&table_desc->signature, ACPI_SIG_FACS)) {
/* Always calculate checksum, ignore bad checksum if requested */
status =
acpi_tb_verify_checksum(table_desc->pointer,
table_desc->length);
}
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_tb_add_table
*
* PARAMETERS: table_desc - Table descriptor
* table_index - Where the table index is returned
*
* RETURN: Status
*
* DESCRIPTION: This function is called to add an ACPI table. It is used to
* dynamically load tables via the Load and load_table AML
* operators.
*
******************************************************************************/
acpi_status
acpi_tb_add_table(struct acpi_table_desc *table_desc, u32 *table_index)
{
u32 i;
acpi_status status = AE_OK;
ACPI_FUNCTION_TRACE(tb_add_table);
if (!table_desc->pointer) {
status = acpi_tb_verify_table(table_desc);
if (ACPI_FAILURE(status) || !table_desc->pointer) {
return_ACPI_STATUS(status);
}
}
/*
* Validate the incoming table signature.
*
* 1) Originally, we checked the table signature for "SSDT" or "PSDT".
* 2) We added support for OEMx tables, signature "OEM".
* 3) Valid tables were encountered with a null signature, so we just
* gave up on validating the signature, (05/2008).
* 4) We encountered non-AML tables such as the MADT, which caused
* interpreter errors and kernel faults. So now, we once again allow
* only "SSDT", "OEMx", and now, also a null signature. (05/2011).
*/
if ((table_desc->pointer->signature[0] != 0x00) &&
(!ACPI_COMPARE_NAME(table_desc->pointer->signature, ACPI_SIG_SSDT))
&& (ACPI_STRNCMP(table_desc->pointer->signature, "OEM", 3))) {
ACPI_ERROR((AE_INFO,
"Table has invalid signature [%4.4s] (0x%8.8X), must be SSDT or OEMx",
acpi_ut_valid_acpi_name(*(u32 *)table_desc->
pointer->
signature) ? table_desc->
pointer->signature : "????",
*(u32 *)table_desc->pointer->signature));
return_ACPI_STATUS(AE_BAD_SIGNATURE);
}
(void)acpi_ut_acquire_mutex(ACPI_MTX_TABLES);
/* Check if table is already registered */
for (i = 0; i < acpi_gbl_root_table_list.current_table_count; ++i) {
if (!acpi_gbl_root_table_list.tables[i].pointer) {
status =
acpi_tb_verify_table(&acpi_gbl_root_table_list.
tables[i]);
if (ACPI_FAILURE(status)
|| !acpi_gbl_root_table_list.tables[i].pointer) {
continue;
}
}
/*
* Check for a table match on the entire table length,
* not just the header.
*/
if (table_desc->length !=
acpi_gbl_root_table_list.tables[i].length) {
continue;
}
if (ACPI_MEMCMP(table_desc->pointer,
acpi_gbl_root_table_list.tables[i].pointer,
acpi_gbl_root_table_list.tables[i].length)) {
continue;
}
/*
* Note: the current mechanism does not unregister a table if it is
* dynamically unloaded. The related namespace entries are deleted,
* but the table remains in the root table list.
*
* The assumption here is that the number of different tables that
* will be loaded is actually small, and there is minimal overhead
* in just keeping the table in case it is needed again.
*
* If this assumption changes in the future (perhaps on large
* machines with many table load/unload operations), tables will
* need to be unregistered when they are unloaded, and slots in the
* root table list should be reused when empty.
*/
/*
* Table is already registered.
* We can delete the table that was passed as a parameter.
*/
acpi_tb_delete_table(table_desc);
*table_index = i;
if (acpi_gbl_root_table_list.tables[i].
flags & ACPI_TABLE_IS_LOADED) {
/* Table is still loaded, this is an error */
status = AE_ALREADY_EXISTS;
goto release;
} else {
/* Table was unloaded, allow it to be reloaded */
table_desc->pointer =
acpi_gbl_root_table_list.tables[i].pointer;
table_desc->address =
acpi_gbl_root_table_list.tables[i].address;
status = AE_OK;
goto print_header;
}
}
/*
* ACPI Table Override:
* Allow the host to override dynamically loaded tables.
* NOTE: the table is fully mapped at this point, and the mapping will
* be deleted by tb_table_override if the table is actually overridden.
*/
(void)acpi_tb_table_override(table_desc->pointer, table_desc);
/* Add the table to the global root table list */
status = acpi_tb_store_table(table_desc->address, table_desc->pointer,
table_desc->length, table_desc->flags,
table_index);
if (ACPI_FAILURE(status)) {
goto release;
}
print_header:
acpi_tb_print_table_header(table_desc->address, table_desc->pointer);
release:
(void)acpi_ut_release_mutex(ACPI_MTX_TABLES);
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_tb_table_override
*
* PARAMETERS: table_header - Header for the original table
* table_desc - Table descriptor initialized for the
* original table. May or may not be mapped.
*
* RETURN: Pointer to the entire new table. NULL if table not overridden.
* If overridden, installs the new table within the input table
* descriptor.
*
* DESCRIPTION: Attempt table override by calling the OSL override functions.
* Note: If the table is overridden, then the entire new table
* is mapped and returned by this function.
*
******************************************************************************/
struct acpi_table_header *acpi_tb_table_override(struct acpi_table_header
*table_header,
struct acpi_table_desc
*table_desc)
{
acpi_status status;
struct acpi_table_header *new_table = NULL;
acpi_physical_address new_address = 0;
u32 new_table_length = 0;
u8 new_flags;
char *override_type;
/* (1) Attempt logical override (returns a logical address) */
status = acpi_os_table_override(table_header, &new_table);
if (ACPI_SUCCESS(status) && new_table) {
new_address = ACPI_PTR_TO_PHYSADDR(new_table);
new_table_length = new_table->length;
new_flags = ACPI_TABLE_ORIGIN_OVERRIDE;
override_type = "Logical";
goto finish_override;
}
/* (2) Attempt physical override (returns a physical address) */
status = acpi_os_physical_table_override(table_header,
&new_address,
&new_table_length);
if (ACPI_SUCCESS(status) && new_address && new_table_length) {
/* Map the entire new table */
new_table = acpi_os_map_memory(new_address, new_table_length);
if (!new_table) {
ACPI_EXCEPTION((AE_INFO, AE_NO_MEMORY,
"%4.4s %p Attempted physical table override failed",
table_header->signature,
ACPI_CAST_PTR(void,
table_desc->address)));
return (NULL);
}
override_type = "Physical";
new_flags = ACPI_TABLE_ORIGIN_MAPPED;
goto finish_override;
}
return (NULL); /* There was no override */
finish_override:
ACPI_INFO((AE_INFO,
"%4.4s %p %s table override, new table: %p",
table_header->signature,
ACPI_CAST_PTR(void, table_desc->address),
override_type, new_table));
/* We can now unmap/delete the original table (if fully mapped) */
acpi_tb_delete_table(table_desc);
/* Setup descriptor for the new table */
table_desc->address = new_address;
table_desc->pointer = new_table;
table_desc->length = new_table_length;
table_desc->flags = new_flags;
return (new_table);
}
/*******************************************************************************
*
* FUNCTION: acpi_tb_resize_root_table_list
*
* PARAMETERS: None
*
* RETURN: Status
*
* DESCRIPTION: Expand the size of global table array
*
******************************************************************************/
acpi_status acpi_tb_resize_root_table_list(void)
{
struct acpi_table_desc *tables;
ACPI_FUNCTION_TRACE(tb_resize_root_table_list);
/* allow_resize flag is a parameter to acpi_initialize_tables */
if (!(acpi_gbl_root_table_list.flags & ACPI_ROOT_ALLOW_RESIZE)) {
ACPI_ERROR((AE_INFO,
"Resize of Root Table Array is not allowed"));
return_ACPI_STATUS(AE_SUPPORT);
}
/* Increase the Table Array size */
tables = ACPI_ALLOCATE_ZEROED(((acpi_size) acpi_gbl_root_table_list.
max_table_count +
ACPI_ROOT_TABLE_SIZE_INCREMENT) *
sizeof(struct acpi_table_desc));
if (!tables) {
ACPI_ERROR((AE_INFO,
"Could not allocate new root table array"));
return_ACPI_STATUS(AE_NO_MEMORY);
}
/* Copy and free the previous table array */
if (acpi_gbl_root_table_list.tables) {
ACPI_MEMCPY(tables, acpi_gbl_root_table_list.tables,
(acpi_size) acpi_gbl_root_table_list.
max_table_count * sizeof(struct acpi_table_desc));
if (acpi_gbl_root_table_list.flags & ACPI_ROOT_ORIGIN_ALLOCATED) {
ACPI_FREE(acpi_gbl_root_table_list.tables);
}
}
acpi_gbl_root_table_list.tables = tables;
acpi_gbl_root_table_list.max_table_count +=
ACPI_ROOT_TABLE_SIZE_INCREMENT;
acpi_gbl_root_table_list.flags |= (u8)ACPI_ROOT_ORIGIN_ALLOCATED;
return_ACPI_STATUS(AE_OK);
}
/*******************************************************************************
*
* FUNCTION: acpi_tb_store_table
*
* PARAMETERS: Address - Table address
* Table - Table header
* Length - Table length
* Flags - flags
*
* RETURN: Status and table index.
*
* DESCRIPTION: Add an ACPI table to the global table list
*
******************************************************************************/
acpi_status
acpi_tb_store_table(acpi_physical_address address,
struct acpi_table_header *table,
u32 length, u8 flags, u32 *table_index)
{
acpi_status status;
struct acpi_table_desc *new_table;
/* Ensure that there is room for the table in the Root Table List */
if (acpi_gbl_root_table_list.current_table_count >=
acpi_gbl_root_table_list.max_table_count) {
status = acpi_tb_resize_root_table_list();
if (ACPI_FAILURE(status)) {
return (status);
}
}
new_table =
&acpi_gbl_root_table_list.tables[acpi_gbl_root_table_list.
current_table_count];
/* Initialize added table */
new_table->address = address;
new_table->pointer = table;
new_table->length = length;
new_table->owner_id = 0;
new_table->flags = flags;
ACPI_MOVE_32_TO_32(&new_table->signature, table->signature);
*table_index = acpi_gbl_root_table_list.current_table_count;
acpi_gbl_root_table_list.current_table_count++;
return (AE_OK);
}
/*******************************************************************************
*
* FUNCTION: acpi_tb_delete_table
*
* PARAMETERS: table_index - Table index
*
* RETURN: None
*
* DESCRIPTION: Delete one internal ACPI table
*
******************************************************************************/
void acpi_tb_delete_table(struct acpi_table_desc *table_desc)
{
/* Table must be mapped or allocated */
if (!table_desc->pointer) {
return;
}
switch (table_desc->flags & ACPI_TABLE_ORIGIN_MASK) {
case ACPI_TABLE_ORIGIN_MAPPED:
acpi_os_unmap_memory(table_desc->pointer, table_desc->length);
break;
case ACPI_TABLE_ORIGIN_ALLOCATED:
ACPI_FREE(table_desc->pointer);
break;
/* Not mapped or allocated, there is nothing we can do */
default:
return;
}
table_desc->pointer = NULL;
}
/*******************************************************************************
*
* FUNCTION: acpi_tb_terminate
*
* PARAMETERS: None
*
* RETURN: None
*
* DESCRIPTION: Delete all internal ACPI tables
*
******************************************************************************/
void acpi_tb_terminate(void)
{
u32 i;
ACPI_FUNCTION_TRACE(tb_terminate);
(void)acpi_ut_acquire_mutex(ACPI_MTX_TABLES);
/* Delete the individual tables */
for (i = 0; i < acpi_gbl_root_table_list.current_table_count; i++) {
acpi_tb_delete_table(&acpi_gbl_root_table_list.tables[i]);
}
/*
* Delete the root table array if allocated locally. Array cannot be
* mapped, so we don't need to check for that flag.
*/
if (acpi_gbl_root_table_list.flags & ACPI_ROOT_ORIGIN_ALLOCATED) {
ACPI_FREE(acpi_gbl_root_table_list.tables);
}
acpi_gbl_root_table_list.tables = NULL;
acpi_gbl_root_table_list.flags = 0;
acpi_gbl_root_table_list.current_table_count = 0;
ACPI_DEBUG_PRINT((ACPI_DB_INFO, "ACPI Tables freed\n"));
(void)acpi_ut_release_mutex(ACPI_MTX_TABLES);
}
/*******************************************************************************
*
* FUNCTION: acpi_tb_delete_namespace_by_owner
*
* PARAMETERS: table_index - Table index
*
* RETURN: Status
*
* DESCRIPTION: Delete all namespace objects created when this table was loaded.
*
******************************************************************************/
acpi_status acpi_tb_delete_namespace_by_owner(u32 table_index)
{
acpi_owner_id owner_id;
acpi_status status;
ACPI_FUNCTION_TRACE(tb_delete_namespace_by_owner);
status = acpi_ut_acquire_mutex(ACPI_MTX_TABLES);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
if (table_index >= acpi_gbl_root_table_list.current_table_count) {
/* The table index does not exist */
(void)acpi_ut_release_mutex(ACPI_MTX_TABLES);
return_ACPI_STATUS(AE_NOT_EXIST);
}
/* Get the owner ID for this table, used to delete namespace nodes */
owner_id = acpi_gbl_root_table_list.tables[table_index].owner_id;
(void)acpi_ut_release_mutex(ACPI_MTX_TABLES);
/*
* Need to acquire the namespace writer lock to prevent interference
* with any concurrent namespace walks. The interpreter must be
* released during the deletion since the acquisition of the deletion
* lock may block, and also since the execution of a namespace walk
* must be allowed to use the interpreter.
*/
(void)acpi_ut_release_mutex(ACPI_MTX_INTERPRETER);
status = acpi_ut_acquire_write_lock(&acpi_gbl_namespace_rw_lock);
acpi_ns_delete_namespace_by_owner(owner_id);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
acpi_ut_release_write_lock(&acpi_gbl_namespace_rw_lock);
status = acpi_ut_acquire_mutex(ACPI_MTX_INTERPRETER);
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_tb_allocate_owner_id
*
* PARAMETERS: table_index - Table index
*
* RETURN: Status
*
* DESCRIPTION: Allocates owner_id in table_desc
*
******************************************************************************/
acpi_status acpi_tb_allocate_owner_id(u32 table_index)
{
acpi_status status = AE_BAD_PARAMETER;
ACPI_FUNCTION_TRACE(tb_allocate_owner_id);
(void)acpi_ut_acquire_mutex(ACPI_MTX_TABLES);
if (table_index < acpi_gbl_root_table_list.current_table_count) {
status = acpi_ut_allocate_owner_id
(&(acpi_gbl_root_table_list.tables[table_index].owner_id));
}
(void)acpi_ut_release_mutex(ACPI_MTX_TABLES);
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_tb_release_owner_id
*
* PARAMETERS: table_index - Table index
*
* RETURN: Status
*
* DESCRIPTION: Releases owner_id in table_desc
*
******************************************************************************/
acpi_status acpi_tb_release_owner_id(u32 table_index)
{
acpi_status status = AE_BAD_PARAMETER;
ACPI_FUNCTION_TRACE(tb_release_owner_id);
(void)acpi_ut_acquire_mutex(ACPI_MTX_TABLES);
if (table_index < acpi_gbl_root_table_list.current_table_count) {
acpi_ut_release_owner_id(&
(acpi_gbl_root_table_list.
tables[table_index].owner_id));
status = AE_OK;
}
(void)acpi_ut_release_mutex(ACPI_MTX_TABLES);
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_tb_get_owner_id
*
* PARAMETERS: table_index - Table index
* owner_id - Where the table owner_id is returned
*
* RETURN: Status
*
* DESCRIPTION: returns owner_id for the ACPI table
*
******************************************************************************/
acpi_status acpi_tb_get_owner_id(u32 table_index, acpi_owner_id *owner_id)
{
acpi_status status = AE_BAD_PARAMETER;
ACPI_FUNCTION_TRACE(tb_get_owner_id);
(void)acpi_ut_acquire_mutex(ACPI_MTX_TABLES);
if (table_index < acpi_gbl_root_table_list.current_table_count) {
*owner_id =
acpi_gbl_root_table_list.tables[table_index].owner_id;
status = AE_OK;
}
(void)acpi_ut_release_mutex(ACPI_MTX_TABLES);
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_tb_is_table_loaded
*
* PARAMETERS: table_index - Table index
*
* RETURN: Table Loaded Flag
*
******************************************************************************/
u8 acpi_tb_is_table_loaded(u32 table_index)
{
u8 is_loaded = FALSE;
(void)acpi_ut_acquire_mutex(ACPI_MTX_TABLES);
if (table_index < acpi_gbl_root_table_list.current_table_count) {
is_loaded = (u8)
(acpi_gbl_root_table_list.tables[table_index].flags &
ACPI_TABLE_IS_LOADED);
}
(void)acpi_ut_release_mutex(ACPI_MTX_TABLES);
return (is_loaded);
}
/*******************************************************************************
*
* FUNCTION: acpi_tb_set_table_loaded_flag
*
* PARAMETERS: table_index - Table index
* is_loaded - TRUE if table is loaded, FALSE otherwise
*
* RETURN: None
*
* DESCRIPTION: Sets the table loaded flag to either TRUE or FALSE.
*
******************************************************************************/
void acpi_tb_set_table_loaded_flag(u32 table_index, u8 is_loaded)
{
(void)acpi_ut_acquire_mutex(ACPI_MTX_TABLES);
if (table_index < acpi_gbl_root_table_list.current_table_count) {
if (is_loaded) {
acpi_gbl_root_table_list.tables[table_index].flags |=
ACPI_TABLE_IS_LOADED;
} else {
acpi_gbl_root_table_list.tables[table_index].flags &=
~ACPI_TABLE_IS_LOADED;
}
}
(void)acpi_ut_release_mutex(ACPI_MTX_TABLES);
}
| gpl-2.0 |
schqiushui/kernel_lollipop_sense_m8ace | drivers/acpi/acpica/evevent.c | 4852 | 8774 | /******************************************************************************
*
* Module Name: evevent - Fixed Event handling and dispatch
*
*****************************************************************************/
/*
* Copyright (C) 2000 - 2012, Intel Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*/
#include <acpi/acpi.h>
#include "accommon.h"
#include "acevents.h"
#define _COMPONENT ACPI_EVENTS
ACPI_MODULE_NAME("evevent")
#if (!ACPI_REDUCED_HARDWARE) /* Entire module */
/* Local prototypes */
static acpi_status acpi_ev_fixed_event_initialize(void);
static u32 acpi_ev_fixed_event_dispatch(u32 event);
/*******************************************************************************
*
* FUNCTION: acpi_ev_initialize_events
*
* PARAMETERS: None
*
* RETURN: Status
*
* DESCRIPTION: Initialize global data structures for ACPI events (Fixed, GPE)
*
******************************************************************************/
acpi_status acpi_ev_initialize_events(void)
{
acpi_status status;
ACPI_FUNCTION_TRACE(ev_initialize_events);
/* If Hardware Reduced flag is set, there are no fixed events */
if (acpi_gbl_reduced_hardware) {
return_ACPI_STATUS(AE_OK);
}
/*
* Initialize the Fixed and General Purpose Events. This is done prior to
* enabling SCIs to prevent interrupts from occurring before the handlers
* are installed.
*/
status = acpi_ev_fixed_event_initialize();
if (ACPI_FAILURE(status)) {
ACPI_EXCEPTION((AE_INFO, status,
"Unable to initialize fixed events"));
return_ACPI_STATUS(status);
}
status = acpi_ev_gpe_initialize();
if (ACPI_FAILURE(status)) {
ACPI_EXCEPTION((AE_INFO, status,
"Unable to initialize general purpose events"));
return_ACPI_STATUS(status);
}
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_ev_install_xrupt_handlers
*
* PARAMETERS: None
*
* RETURN: Status
*
* DESCRIPTION: Install interrupt handlers for the SCI and Global Lock
*
******************************************************************************/
acpi_status acpi_ev_install_xrupt_handlers(void)
{
acpi_status status;
ACPI_FUNCTION_TRACE(ev_install_xrupt_handlers);
/* If Hardware Reduced flag is set, there is no ACPI h/w */
if (acpi_gbl_reduced_hardware) {
return_ACPI_STATUS(AE_OK);
}
/* Install the SCI handler */
status = acpi_ev_install_sci_handler();
if (ACPI_FAILURE(status)) {
ACPI_EXCEPTION((AE_INFO, status,
"Unable to install System Control Interrupt handler"));
return_ACPI_STATUS(status);
}
/* Install the handler for the Global Lock */
status = acpi_ev_init_global_lock_handler();
if (ACPI_FAILURE(status)) {
ACPI_EXCEPTION((AE_INFO, status,
"Unable to initialize Global Lock handler"));
return_ACPI_STATUS(status);
}
acpi_gbl_events_initialized = TRUE;
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_ev_fixed_event_initialize
*
* PARAMETERS: None
*
* RETURN: Status
*
* DESCRIPTION: Install the fixed event handlers and disable all fixed events.
*
******************************************************************************/
static acpi_status acpi_ev_fixed_event_initialize(void)
{
u32 i;
acpi_status status;
/*
* Initialize the structure that keeps track of fixed event handlers and
* enable the fixed events.
*/
for (i = 0; i < ACPI_NUM_FIXED_EVENTS; i++) {
acpi_gbl_fixed_event_handlers[i].handler = NULL;
acpi_gbl_fixed_event_handlers[i].context = NULL;
/* Disable the fixed event */
if (acpi_gbl_fixed_event_info[i].enable_register_id != 0xFF) {
status =
acpi_write_bit_register(acpi_gbl_fixed_event_info
[i].enable_register_id,
ACPI_DISABLE_EVENT);
if (ACPI_FAILURE(status)) {
return (status);
}
}
}
return (AE_OK);
}
/*******************************************************************************
*
* FUNCTION: acpi_ev_fixed_event_detect
*
* PARAMETERS: None
*
* RETURN: INTERRUPT_HANDLED or INTERRUPT_NOT_HANDLED
*
* DESCRIPTION: Checks the PM status register for active fixed events
*
******************************************************************************/
u32 acpi_ev_fixed_event_detect(void)
{
u32 int_status = ACPI_INTERRUPT_NOT_HANDLED;
u32 fixed_status;
u32 fixed_enable;
u32 i;
ACPI_FUNCTION_NAME(ev_fixed_event_detect);
/*
* Read the fixed feature status and enable registers, as all the cases
* depend on their values. Ignore errors here.
*/
(void)acpi_hw_register_read(ACPI_REGISTER_PM1_STATUS, &fixed_status);
(void)acpi_hw_register_read(ACPI_REGISTER_PM1_ENABLE, &fixed_enable);
ACPI_DEBUG_PRINT((ACPI_DB_INTERRUPTS,
"Fixed Event Block: Enable %08X Status %08X\n",
fixed_enable, fixed_status));
/*
* Check for all possible Fixed Events and dispatch those that are active
*/
for (i = 0; i < ACPI_NUM_FIXED_EVENTS; i++) {
/* Both the status and enable bits must be on for this event */
if ((fixed_status & acpi_gbl_fixed_event_info[i].
status_bit_mask)
&& (fixed_enable & acpi_gbl_fixed_event_info[i].
enable_bit_mask)) {
/*
* Found an active (signalled) event. Invoke global event
* handler if present.
*/
acpi_fixed_event_count[i]++;
if (acpi_gbl_global_event_handler) {
acpi_gbl_global_event_handler
(ACPI_EVENT_TYPE_FIXED, NULL, i,
acpi_gbl_global_event_handler_context);
}
int_status |= acpi_ev_fixed_event_dispatch(i);
}
}
return (int_status);
}
/*******************************************************************************
*
* FUNCTION: acpi_ev_fixed_event_dispatch
*
* PARAMETERS: Event - Event type
*
* RETURN: INTERRUPT_HANDLED or INTERRUPT_NOT_HANDLED
*
* DESCRIPTION: Clears the status bit for the requested event, calls the
* handler that previously registered for the event.
*
******************************************************************************/
static u32 acpi_ev_fixed_event_dispatch(u32 event)
{
ACPI_FUNCTION_ENTRY();
/* Clear the status bit */
(void)acpi_write_bit_register(acpi_gbl_fixed_event_info[event].
status_register_id, ACPI_CLEAR_STATUS);
/*
* Make sure we've got a handler. If not, report an error. The event is
* disabled to prevent further interrupts.
*/
if (NULL == acpi_gbl_fixed_event_handlers[event].handler) {
(void)acpi_write_bit_register(acpi_gbl_fixed_event_info[event].
enable_register_id,
ACPI_DISABLE_EVENT);
ACPI_ERROR((AE_INFO,
"No installed handler for fixed event [0x%08X]",
event));
return (ACPI_INTERRUPT_NOT_HANDLED);
}
/* Invoke the Fixed Event handler */
return ((acpi_gbl_fixed_event_handlers[event].
handler) (acpi_gbl_fixed_event_handlers[event].context));
}
#endif /* !ACPI_REDUCED_HARDWARE */
| gpl-2.0 |
glewarne/testing | arch/mips/rb532/serial.c | 13044 | 1919 | /*
* BRIEF MODULE DESCRIPTION
* Serial port initialisation.
*
* Copyright 2004 IDT Inc. (rischelp@idt.com)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/init.h>
#include <linux/tty.h>
#include <linux/serial_core.h>
#include <linux/serial_8250.h>
#include <linux/irq.h>
#include <asm/serial.h>
#include <asm/mach-rc32434/rb.h>
extern unsigned int idt_cpu_freq;
static struct uart_port rb532_uart = {
.flags = UPF_BOOT_AUTOCONF,
.line = 0,
.irq = UART0_IRQ,
.iotype = UPIO_MEM,
.membase = (char *)KSEG1ADDR(REGBASE + UART0BASE),
.regshift = 2
};
int __init setup_serial_port(void)
{
rb532_uart.uartclk = idt_cpu_freq;
return early_serial_setup(&rb532_uart);
}
arch_initcall(setup_serial_port);
| gpl-2.0 |
auras76/aur-kernel-XZxx | arch/alpha/kernel/core_wildfire.c | 13812 | 17607 | /*
* linux/arch/alpha/kernel/core_wildfire.c
*
* Wildfire support.
*
* Copyright (C) 2000 Andrea Arcangeli <andrea@suse.de> SuSE
*/
#define __EXTERN_INLINE inline
#include <asm/io.h>
#include <asm/core_wildfire.h>
#undef __EXTERN_INLINE
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <asm/ptrace.h>
#include <asm/smp.h>
#include "proto.h"
#include "pci_impl.h"
#define DEBUG_CONFIG 0
#define DEBUG_DUMP_REGS 0
#define DEBUG_DUMP_CONFIG 1
#if DEBUG_CONFIG
# define DBG_CFG(args) printk args
#else
# define DBG_CFG(args)
#endif
#if DEBUG_DUMP_REGS
static void wildfire_dump_pci_regs(int qbbno, int hoseno);
static void wildfire_dump_pca_regs(int qbbno, int pcano);
static void wildfire_dump_qsa_regs(int qbbno);
static void wildfire_dump_qsd_regs(int qbbno);
static void wildfire_dump_iop_regs(int qbbno);
static void wildfire_dump_gp_regs(int qbbno);
#endif
#if DEBUG_DUMP_CONFIG
static void wildfire_dump_hardware_config(void);
#endif
unsigned char wildfire_hard_qbb_map[WILDFIRE_MAX_QBB];
unsigned char wildfire_soft_qbb_map[WILDFIRE_MAX_QBB];
#define QBB_MAP_EMPTY 0xff
unsigned long wildfire_hard_qbb_mask;
unsigned long wildfire_soft_qbb_mask;
unsigned long wildfire_gp_mask;
unsigned long wildfire_hs_mask;
unsigned long wildfire_iop_mask;
unsigned long wildfire_ior_mask;
unsigned long wildfire_pca_mask;
unsigned long wildfire_cpu_mask;
unsigned long wildfire_mem_mask;
void __init
wildfire_init_hose(int qbbno, int hoseno)
{
struct pci_controller *hose;
wildfire_pci *pci;
hose = alloc_pci_controller();
hose->io_space = alloc_resource();
hose->mem_space = alloc_resource();
/* This is for userland consumption. */
hose->sparse_mem_base = 0;
hose->sparse_io_base = 0;
hose->dense_mem_base = WILDFIRE_MEM(qbbno, hoseno);
hose->dense_io_base = WILDFIRE_IO(qbbno, hoseno);
hose->config_space_base = WILDFIRE_CONF(qbbno, hoseno);
hose->index = (qbbno << 3) + hoseno;
hose->io_space->start = WILDFIRE_IO(qbbno, hoseno) - WILDFIRE_IO_BIAS;
hose->io_space->end = hose->io_space->start + WILDFIRE_IO_SPACE - 1;
hose->io_space->name = pci_io_names[hoseno];
hose->io_space->flags = IORESOURCE_IO;
hose->mem_space->start = WILDFIRE_MEM(qbbno, hoseno)-WILDFIRE_MEM_BIAS;
hose->mem_space->end = hose->mem_space->start + 0xffffffff;
hose->mem_space->name = pci_mem_names[hoseno];
hose->mem_space->flags = IORESOURCE_MEM;
if (request_resource(&ioport_resource, hose->io_space) < 0)
printk(KERN_ERR "Failed to request IO on qbb %d hose %d\n",
qbbno, hoseno);
if (request_resource(&iomem_resource, hose->mem_space) < 0)
printk(KERN_ERR "Failed to request MEM on qbb %d hose %d\n",
qbbno, hoseno);
#if DEBUG_DUMP_REGS
wildfire_dump_pci_regs(qbbno, hoseno);
#endif
/*
* Set up the PCI to main memory translation windows.
*
* Note: Window 3 is scatter-gather only
*
* Window 0 is scatter-gather 8MB at 8MB (for isa)
* Window 1 is direct access 1GB at 1GB
* Window 2 is direct access 1GB at 2GB
* Window 3 is scatter-gather 128MB at 3GB
* ??? We ought to scale window 3 memory.
*
*/
hose->sg_isa = iommu_arena_new(hose, 0x00800000, 0x00800000, 0);
hose->sg_pci = iommu_arena_new(hose, 0xc0000000, 0x08000000, 0);
pci = WILDFIRE_pci(qbbno, hoseno);
pci->pci_window[0].wbase.csr = hose->sg_isa->dma_base | 3;
pci->pci_window[0].wmask.csr = (hose->sg_isa->size - 1) & 0xfff00000;
pci->pci_window[0].tbase.csr = virt_to_phys(hose->sg_isa->ptes);
pci->pci_window[1].wbase.csr = 0x40000000 | 1;
pci->pci_window[1].wmask.csr = (0x40000000 -1) & 0xfff00000;
pci->pci_window[1].tbase.csr = 0;
pci->pci_window[2].wbase.csr = 0x80000000 | 1;
pci->pci_window[2].wmask.csr = (0x40000000 -1) & 0xfff00000;
pci->pci_window[2].tbase.csr = 0x40000000;
pci->pci_window[3].wbase.csr = hose->sg_pci->dma_base | 3;
pci->pci_window[3].wmask.csr = (hose->sg_pci->size - 1) & 0xfff00000;
pci->pci_window[3].tbase.csr = virt_to_phys(hose->sg_pci->ptes);
wildfire_pci_tbi(hose, 0, 0); /* Flush TLB at the end. */
}
void __init
wildfire_init_pca(int qbbno, int pcano)
{
/* Test for PCA existence first. */
if (!WILDFIRE_PCA_EXISTS(qbbno, pcano))
return;
#if DEBUG_DUMP_REGS
wildfire_dump_pca_regs(qbbno, pcano);
#endif
/* Do both hoses of the PCA. */
wildfire_init_hose(qbbno, (pcano << 1) + 0);
wildfire_init_hose(qbbno, (pcano << 1) + 1);
}
void __init
wildfire_init_qbb(int qbbno)
{
int pcano;
/* Test for QBB existence first. */
if (!WILDFIRE_QBB_EXISTS(qbbno))
return;
#if DEBUG_DUMP_REGS
wildfire_dump_qsa_regs(qbbno);
wildfire_dump_qsd_regs(qbbno);
wildfire_dump_iop_regs(qbbno);
wildfire_dump_gp_regs(qbbno);
#endif
/* Init all PCAs here. */
for (pcano = 0; pcano < WILDFIRE_PCA_PER_QBB; pcano++) {
wildfire_init_pca(qbbno, pcano);
}
}
void __init
wildfire_hardware_probe(void)
{
unsigned long temp;
unsigned int hard_qbb, soft_qbb;
wildfire_fast_qsd *fast = WILDFIRE_fast_qsd();
wildfire_qsd *qsd;
wildfire_qsa *qsa;
wildfire_iop *iop;
wildfire_gp *gp;
wildfire_ne *ne;
wildfire_fe *fe;
int i;
temp = fast->qsd_whami.csr;
#if 0
printk(KERN_ERR "fast QSD_WHAMI at base %p is 0x%lx\n", fast, temp);
#endif
hard_qbb = (temp >> 8) & 7;
soft_qbb = (temp >> 4) & 7;
/* Init the HW configuration variables. */
wildfire_hard_qbb_mask = (1 << hard_qbb);
wildfire_soft_qbb_mask = (1 << soft_qbb);
wildfire_gp_mask = 0;
wildfire_hs_mask = 0;
wildfire_iop_mask = 0;
wildfire_ior_mask = 0;
wildfire_pca_mask = 0;
wildfire_cpu_mask = 0;
wildfire_mem_mask = 0;
memset(wildfire_hard_qbb_map, QBB_MAP_EMPTY, WILDFIRE_MAX_QBB);
memset(wildfire_soft_qbb_map, QBB_MAP_EMPTY, WILDFIRE_MAX_QBB);
/* First, determine which QBBs are present. */
qsa = WILDFIRE_qsa(soft_qbb);
temp = qsa->qsa_qbb_id.csr;
#if 0
printk(KERN_ERR "QSA_QBB_ID at base %p is 0x%lx\n", qsa, temp);
#endif
if (temp & 0x40) /* Is there an HS? */
wildfire_hs_mask = 1;
if (temp & 0x20) { /* Is there a GP? */
gp = WILDFIRE_gp(soft_qbb);
temp = 0;
for (i = 0; i < 4; i++) {
temp |= gp->gpa_qbb_map[i].csr << (i * 8);
#if 0
printk(KERN_ERR "GPA_QBB_MAP[%d] at base %p is 0x%lx\n",
i, gp, temp);
#endif
}
for (hard_qbb = 0; hard_qbb < WILDFIRE_MAX_QBB; hard_qbb++) {
if (temp & 8) { /* Is there a QBB? */
soft_qbb = temp & 7;
wildfire_hard_qbb_mask |= (1 << hard_qbb);
wildfire_soft_qbb_mask |= (1 << soft_qbb);
}
temp >>= 4;
}
wildfire_gp_mask = wildfire_soft_qbb_mask;
}
/* Next determine each QBBs resources. */
for (soft_qbb = 0; soft_qbb < WILDFIRE_MAX_QBB; soft_qbb++) {
if (WILDFIRE_QBB_EXISTS(soft_qbb)) {
qsd = WILDFIRE_qsd(soft_qbb);
temp = qsd->qsd_whami.csr;
#if 0
printk(KERN_ERR "QSD_WHAMI at base %p is 0x%lx\n", qsd, temp);
#endif
hard_qbb = (temp >> 8) & 7;
wildfire_hard_qbb_map[hard_qbb] = soft_qbb;
wildfire_soft_qbb_map[soft_qbb] = hard_qbb;
qsa = WILDFIRE_qsa(soft_qbb);
temp = qsa->qsa_qbb_pop[0].csr;
#if 0
printk(KERN_ERR "QSA_QBB_POP_0 at base %p is 0x%lx\n", qsa, temp);
#endif
wildfire_cpu_mask |= ((temp >> 0) & 0xf) << (soft_qbb << 2);
wildfire_mem_mask |= ((temp >> 4) & 0xf) << (soft_qbb << 2);
temp = qsa->qsa_qbb_pop[1].csr;
#if 0
printk(KERN_ERR "QSA_QBB_POP_1 at base %p is 0x%lx\n", qsa, temp);
#endif
wildfire_iop_mask |= (1 << soft_qbb);
wildfire_ior_mask |= ((temp >> 4) & 0xf) << (soft_qbb << 2);
temp = qsa->qsa_qbb_id.csr;
#if 0
printk(KERN_ERR "QSA_QBB_ID at %p is 0x%lx\n", qsa, temp);
#endif
if (temp & 0x20)
wildfire_gp_mask |= (1 << soft_qbb);
/* Probe for PCA existence here. */
for (i = 0; i < WILDFIRE_PCA_PER_QBB; i++) {
iop = WILDFIRE_iop(soft_qbb);
ne = WILDFIRE_ne(soft_qbb, i);
fe = WILDFIRE_fe(soft_qbb, i);
if ((iop->iop_hose[i].init.csr & 1) == 1 &&
((ne->ne_what_am_i.csr & 0xf00000300UL) == 0x100000300UL) &&
((fe->fe_what_am_i.csr & 0xf00000300UL) == 0x100000200UL))
{
wildfire_pca_mask |= 1 << ((soft_qbb << 2) + i);
}
}
}
}
#if DEBUG_DUMP_CONFIG
wildfire_dump_hardware_config();
#endif
}
void __init
wildfire_init_arch(void)
{
int qbbno;
/* With multiple PCI buses, we play with I/O as physical addrs. */
ioport_resource.end = ~0UL;
/* Probe the hardware for info about configuration. */
wildfire_hardware_probe();
/* Now init all the found QBBs. */
for (qbbno = 0; qbbno < WILDFIRE_MAX_QBB; qbbno++) {
wildfire_init_qbb(qbbno);
}
/* Normal direct PCI DMA mapping. */
__direct_map_base = 0x40000000UL;
__direct_map_size = 0x80000000UL;
}
void
wildfire_machine_check(unsigned long vector, unsigned long la_ptr)
{
mb();
mb(); /* magic */
draina();
/* FIXME: clear pci errors */
wrmces(0x7);
mb();
process_mcheck_info(vector, la_ptr, "WILDFIRE",
mcheck_expected(smp_processor_id()));
}
void
wildfire_kill_arch(int mode)
{
}
void
wildfire_pci_tbi(struct pci_controller *hose, dma_addr_t start, dma_addr_t end)
{
int qbbno = hose->index >> 3;
int hoseno = hose->index & 7;
wildfire_pci *pci = WILDFIRE_pci(qbbno, hoseno);
mb();
pci->pci_flush_tlb.csr; /* reading does the trick */
}
static int
mk_conf_addr(struct pci_bus *pbus, unsigned int device_fn, int where,
unsigned long *pci_addr, unsigned char *type1)
{
struct pci_controller *hose = pbus->sysdata;
unsigned long addr;
u8 bus = pbus->number;
DBG_CFG(("mk_conf_addr(bus=%d ,device_fn=0x%x, where=0x%x, "
"pci_addr=0x%p, type1=0x%p)\n",
bus, device_fn, where, pci_addr, type1));
if (!pbus->parent) /* No parent means peer PCI bus. */
bus = 0;
*type1 = (bus != 0);
addr = (bus << 16) | (device_fn << 8) | where;
addr |= hose->config_space_base;
*pci_addr = addr;
DBG_CFG(("mk_conf_addr: returning pci_addr 0x%lx\n", addr));
return 0;
}
static int
wildfire_read_config(struct pci_bus *bus, unsigned int devfn, int where,
int size, u32 *value)
{
unsigned long addr;
unsigned char type1;
if (mk_conf_addr(bus, devfn, where, &addr, &type1))
return PCIBIOS_DEVICE_NOT_FOUND;
switch (size) {
case 1:
*value = __kernel_ldbu(*(vucp)addr);
break;
case 2:
*value = __kernel_ldwu(*(vusp)addr);
break;
case 4:
*value = *(vuip)addr;
break;
}
return PCIBIOS_SUCCESSFUL;
}
static int
wildfire_write_config(struct pci_bus *bus, unsigned int devfn, int where,
int size, u32 value)
{
unsigned long addr;
unsigned char type1;
if (mk_conf_addr(bus, devfn, where, &addr, &type1))
return PCIBIOS_DEVICE_NOT_FOUND;
switch (size) {
case 1:
__kernel_stb(value, *(vucp)addr);
mb();
__kernel_ldbu(*(vucp)addr);
break;
case 2:
__kernel_stw(value, *(vusp)addr);
mb();
__kernel_ldwu(*(vusp)addr);
break;
case 4:
*(vuip)addr = value;
mb();
*(vuip)addr;
break;
}
return PCIBIOS_SUCCESSFUL;
}
struct pci_ops wildfire_pci_ops =
{
.read = wildfire_read_config,
.write = wildfire_write_config,
};
/*
* NUMA Support
*/
int wildfire_pa_to_nid(unsigned long pa)
{
return pa >> 36;
}
int wildfire_cpuid_to_nid(int cpuid)
{
/* assume 4 CPUs per node */
return cpuid >> 2;
}
unsigned long wildfire_node_mem_start(int nid)
{
/* 64GB per node */
return (unsigned long)nid * (64UL * 1024 * 1024 * 1024);
}
unsigned long wildfire_node_mem_size(int nid)
{
/* 64GB per node */
return 64UL * 1024 * 1024 * 1024;
}
#if DEBUG_DUMP_REGS
static void __init
wildfire_dump_pci_regs(int qbbno, int hoseno)
{
wildfire_pci *pci = WILDFIRE_pci(qbbno, hoseno);
int i;
printk(KERN_ERR "PCI registers for QBB %d hose %d (%p)\n",
qbbno, hoseno, pci);
printk(KERN_ERR " PCI_IO_ADDR_EXT: 0x%16lx\n",
pci->pci_io_addr_ext.csr);
printk(KERN_ERR " PCI_CTRL: 0x%16lx\n", pci->pci_ctrl.csr);
printk(KERN_ERR " PCI_ERR_SUM: 0x%16lx\n", pci->pci_err_sum.csr);
printk(KERN_ERR " PCI_ERR_ADDR: 0x%16lx\n", pci->pci_err_addr.csr);
printk(KERN_ERR " PCI_STALL_CNT: 0x%16lx\n", pci->pci_stall_cnt.csr);
printk(KERN_ERR " PCI_PEND_INT: 0x%16lx\n", pci->pci_pend_int.csr);
printk(KERN_ERR " PCI_SENT_INT: 0x%16lx\n", pci->pci_sent_int.csr);
printk(KERN_ERR " DMA window registers for QBB %d hose %d (%p)\n",
qbbno, hoseno, pci);
for (i = 0; i < 4; i++) {
printk(KERN_ERR " window %d: 0x%16lx 0x%16lx 0x%16lx\n", i,
pci->pci_window[i].wbase.csr,
pci->pci_window[i].wmask.csr,
pci->pci_window[i].tbase.csr);
}
printk(KERN_ERR "\n");
}
static void __init
wildfire_dump_pca_regs(int qbbno, int pcano)
{
wildfire_pca *pca = WILDFIRE_pca(qbbno, pcano);
int i;
printk(KERN_ERR "PCA registers for QBB %d PCA %d (%p)\n",
qbbno, pcano, pca);
printk(KERN_ERR " PCA_WHAT_AM_I: 0x%16lx\n", pca->pca_what_am_i.csr);
printk(KERN_ERR " PCA_ERR_SUM: 0x%16lx\n", pca->pca_err_sum.csr);
printk(KERN_ERR " PCA_PEND_INT: 0x%16lx\n", pca->pca_pend_int.csr);
printk(KERN_ERR " PCA_SENT_INT: 0x%16lx\n", pca->pca_sent_int.csr);
printk(KERN_ERR " PCA_STDIO_EL: 0x%16lx\n",
pca->pca_stdio_edge_level.csr);
printk(KERN_ERR " PCA target registers for QBB %d PCA %d (%p)\n",
qbbno, pcano, pca);
for (i = 0; i < 4; i++) {
printk(KERN_ERR " target %d: 0x%16lx 0x%16lx\n", i,
pca->pca_int[i].target.csr,
pca->pca_int[i].enable.csr);
}
printk(KERN_ERR "\n");
}
static void __init
wildfire_dump_qsa_regs(int qbbno)
{
wildfire_qsa *qsa = WILDFIRE_qsa(qbbno);
int i;
printk(KERN_ERR "QSA registers for QBB %d (%p)\n", qbbno, qsa);
printk(KERN_ERR " QSA_QBB_ID: 0x%16lx\n", qsa->qsa_qbb_id.csr);
printk(KERN_ERR " QSA_PORT_ENA: 0x%16lx\n", qsa->qsa_port_ena.csr);
printk(KERN_ERR " QSA_REF_INT: 0x%16lx\n", qsa->qsa_ref_int.csr);
for (i = 0; i < 5; i++)
printk(KERN_ERR " QSA_CONFIG_%d: 0x%16lx\n",
i, qsa->qsa_config[i].csr);
for (i = 0; i < 2; i++)
printk(KERN_ERR " QSA_QBB_POP_%d: 0x%16lx\n",
i, qsa->qsa_qbb_pop[0].csr);
printk(KERN_ERR "\n");
}
static void __init
wildfire_dump_qsd_regs(int qbbno)
{
wildfire_qsd *qsd = WILDFIRE_qsd(qbbno);
printk(KERN_ERR "QSD registers for QBB %d (%p)\n", qbbno, qsd);
printk(KERN_ERR " QSD_WHAMI: 0x%16lx\n", qsd->qsd_whami.csr);
printk(KERN_ERR " QSD_REV: 0x%16lx\n", qsd->qsd_rev.csr);
printk(KERN_ERR " QSD_PORT_PRESENT: 0x%16lx\n",
qsd->qsd_port_present.csr);
printk(KERN_ERR " QSD_PORT_ACTUVE: 0x%16lx\n",
qsd->qsd_port_active.csr);
printk(KERN_ERR " QSD_FAULT_ENA: 0x%16lx\n",
qsd->qsd_fault_ena.csr);
printk(KERN_ERR " QSD_CPU_INT_ENA: 0x%16lx\n",
qsd->qsd_cpu_int_ena.csr);
printk(KERN_ERR " QSD_MEM_CONFIG: 0x%16lx\n",
qsd->qsd_mem_config.csr);
printk(KERN_ERR " QSD_ERR_SUM: 0x%16lx\n",
qsd->qsd_err_sum.csr);
printk(KERN_ERR "\n");
}
static void __init
wildfire_dump_iop_regs(int qbbno)
{
wildfire_iop *iop = WILDFIRE_iop(qbbno);
int i;
printk(KERN_ERR "IOP registers for QBB %d (%p)\n", qbbno, iop);
printk(KERN_ERR " IOA_CONFIG: 0x%16lx\n", iop->ioa_config.csr);
printk(KERN_ERR " IOD_CONFIG: 0x%16lx\n", iop->iod_config.csr);
printk(KERN_ERR " IOP_SWITCH_CREDITS: 0x%16lx\n",
iop->iop_switch_credits.csr);
printk(KERN_ERR " IOP_HOSE_CREDITS: 0x%16lx\n",
iop->iop_hose_credits.csr);
for (i = 0; i < 4; i++)
printk(KERN_ERR " IOP_HOSE_%d_INIT: 0x%16lx\n",
i, iop->iop_hose[i].init.csr);
for (i = 0; i < 4; i++)
printk(KERN_ERR " IOP_DEV_INT_TARGET_%d: 0x%16lx\n",
i, iop->iop_dev_int[i].target.csr);
printk(KERN_ERR "\n");
}
static void __init
wildfire_dump_gp_regs(int qbbno)
{
wildfire_gp *gp = WILDFIRE_gp(qbbno);
int i;
printk(KERN_ERR "GP registers for QBB %d (%p)\n", qbbno, gp);
for (i = 0; i < 4; i++)
printk(KERN_ERR " GPA_QBB_MAP_%d: 0x%16lx\n",
i, gp->gpa_qbb_map[i].csr);
printk(KERN_ERR " GPA_MEM_POP_MAP: 0x%16lx\n",
gp->gpa_mem_pop_map.csr);
printk(KERN_ERR " GPA_SCRATCH: 0x%16lx\n", gp->gpa_scratch.csr);
printk(KERN_ERR " GPA_DIAG: 0x%16lx\n", gp->gpa_diag.csr);
printk(KERN_ERR " GPA_CONFIG_0: 0x%16lx\n", gp->gpa_config_0.csr);
printk(KERN_ERR " GPA_INIT_ID: 0x%16lx\n", gp->gpa_init_id.csr);
printk(KERN_ERR " GPA_CONFIG_2: 0x%16lx\n", gp->gpa_config_2.csr);
printk(KERN_ERR "\n");
}
#endif /* DUMP_REGS */
#if DEBUG_DUMP_CONFIG
static void __init
wildfire_dump_hardware_config(void)
{
int i;
printk(KERN_ERR "Probed Hardware Configuration\n");
printk(KERN_ERR " hard_qbb_mask: 0x%16lx\n", wildfire_hard_qbb_mask);
printk(KERN_ERR " soft_qbb_mask: 0x%16lx\n", wildfire_soft_qbb_mask);
printk(KERN_ERR " gp_mask: 0x%16lx\n", wildfire_gp_mask);
printk(KERN_ERR " hs_mask: 0x%16lx\n", wildfire_hs_mask);
printk(KERN_ERR " iop_mask: 0x%16lx\n", wildfire_iop_mask);
printk(KERN_ERR " ior_mask: 0x%16lx\n", wildfire_ior_mask);
printk(KERN_ERR " pca_mask: 0x%16lx\n", wildfire_pca_mask);
printk(KERN_ERR " cpu_mask: 0x%16lx\n", wildfire_cpu_mask);
printk(KERN_ERR " mem_mask: 0x%16lx\n", wildfire_mem_mask);
printk(" hard_qbb_map: ");
for (i = 0; i < WILDFIRE_MAX_QBB; i++)
if (wildfire_hard_qbb_map[i] == QBB_MAP_EMPTY)
printk("--- ");
else
printk("%3d ", wildfire_hard_qbb_map[i]);
printk("\n");
printk(" soft_qbb_map: ");
for (i = 0; i < WILDFIRE_MAX_QBB; i++)
if (wildfire_soft_qbb_map[i] == QBB_MAP_EMPTY)
printk("--- ");
else
printk("%3d ", wildfire_soft_qbb_map[i]);
printk("\n");
}
#endif /* DUMP_CONFIG */
| gpl-2.0 |
lostemp/samsung-lt-lsk-v3.10.11 | drivers/misc/ibmasm/remote.c | 14836 | 10187 | /*
* IBM ASM Service Processor Device Driver
*
* 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.
*
* Copyright (C) IBM Corporation, 2004
*
* Authors: Max Asböck <amax@us.ibm.com>
* Vernon Mauery <vernux@us.ibm.com>
*
*/
/* Remote mouse and keyboard event handling functions */
#include <linux/pci.h>
#include "ibmasm.h"
#include "remote.h"
#define MOUSE_X_MAX 1600
#define MOUSE_Y_MAX 1200
static const unsigned short xlate_high[XLATE_SIZE] = {
[KEY_SYM_ENTER & 0xff] = KEY_ENTER,
[KEY_SYM_KPSLASH & 0xff] = KEY_KPSLASH,
[KEY_SYM_KPSTAR & 0xff] = KEY_KPASTERISK,
[KEY_SYM_KPMINUS & 0xff] = KEY_KPMINUS,
[KEY_SYM_KPDOT & 0xff] = KEY_KPDOT,
[KEY_SYM_KPPLUS & 0xff] = KEY_KPPLUS,
[KEY_SYM_KP0 & 0xff] = KEY_KP0,
[KEY_SYM_KP1 & 0xff] = KEY_KP1,
[KEY_SYM_KP2 & 0xff] = KEY_KP2, [KEY_SYM_KPDOWN & 0xff] = KEY_KP2,
[KEY_SYM_KP3 & 0xff] = KEY_KP3,
[KEY_SYM_KP4 & 0xff] = KEY_KP4, [KEY_SYM_KPLEFT & 0xff] = KEY_KP4,
[KEY_SYM_KP5 & 0xff] = KEY_KP5,
[KEY_SYM_KP6 & 0xff] = KEY_KP6, [KEY_SYM_KPRIGHT & 0xff] = KEY_KP6,
[KEY_SYM_KP7 & 0xff] = KEY_KP7,
[KEY_SYM_KP8 & 0xff] = KEY_KP8, [KEY_SYM_KPUP & 0xff] = KEY_KP8,
[KEY_SYM_KP9 & 0xff] = KEY_KP9,
[KEY_SYM_BK_SPC & 0xff] = KEY_BACKSPACE,
[KEY_SYM_TAB & 0xff] = KEY_TAB,
[KEY_SYM_CTRL & 0xff] = KEY_LEFTCTRL,
[KEY_SYM_ALT & 0xff] = KEY_LEFTALT,
[KEY_SYM_INSERT & 0xff] = KEY_INSERT,
[KEY_SYM_DELETE & 0xff] = KEY_DELETE,
[KEY_SYM_SHIFT & 0xff] = KEY_LEFTSHIFT,
[KEY_SYM_UARROW & 0xff] = KEY_UP,
[KEY_SYM_DARROW & 0xff] = KEY_DOWN,
[KEY_SYM_LARROW & 0xff] = KEY_LEFT,
[KEY_SYM_RARROW & 0xff] = KEY_RIGHT,
[KEY_SYM_ESCAPE & 0xff] = KEY_ESC,
[KEY_SYM_PAGEUP & 0xff] = KEY_PAGEUP,
[KEY_SYM_PAGEDOWN & 0xff] = KEY_PAGEDOWN,
[KEY_SYM_HOME & 0xff] = KEY_HOME,
[KEY_SYM_END & 0xff] = KEY_END,
[KEY_SYM_F1 & 0xff] = KEY_F1,
[KEY_SYM_F2 & 0xff] = KEY_F2,
[KEY_SYM_F3 & 0xff] = KEY_F3,
[KEY_SYM_F4 & 0xff] = KEY_F4,
[KEY_SYM_F5 & 0xff] = KEY_F5,
[KEY_SYM_F6 & 0xff] = KEY_F6,
[KEY_SYM_F7 & 0xff] = KEY_F7,
[KEY_SYM_F8 & 0xff] = KEY_F8,
[KEY_SYM_F9 & 0xff] = KEY_F9,
[KEY_SYM_F10 & 0xff] = KEY_F10,
[KEY_SYM_F11 & 0xff] = KEY_F11,
[KEY_SYM_F12 & 0xff] = KEY_F12,
[KEY_SYM_CAP_LOCK & 0xff] = KEY_CAPSLOCK,
[KEY_SYM_NUM_LOCK & 0xff] = KEY_NUMLOCK,
[KEY_SYM_SCR_LOCK & 0xff] = KEY_SCROLLLOCK,
};
static const unsigned short xlate[XLATE_SIZE] = {
[NO_KEYCODE] = KEY_RESERVED,
[KEY_SYM_SPACE] = KEY_SPACE,
[KEY_SYM_TILDE] = KEY_GRAVE, [KEY_SYM_BKTIC] = KEY_GRAVE,
[KEY_SYM_ONE] = KEY_1, [KEY_SYM_BANG] = KEY_1,
[KEY_SYM_TWO] = KEY_2, [KEY_SYM_AT] = KEY_2,
[KEY_SYM_THREE] = KEY_3, [KEY_SYM_POUND] = KEY_3,
[KEY_SYM_FOUR] = KEY_4, [KEY_SYM_DOLLAR] = KEY_4,
[KEY_SYM_FIVE] = KEY_5, [KEY_SYM_PERCENT] = KEY_5,
[KEY_SYM_SIX] = KEY_6, [KEY_SYM_CARAT] = KEY_6,
[KEY_SYM_SEVEN] = KEY_7, [KEY_SYM_AMPER] = KEY_7,
[KEY_SYM_EIGHT] = KEY_8, [KEY_SYM_STAR] = KEY_8,
[KEY_SYM_NINE] = KEY_9, [KEY_SYM_LPAREN] = KEY_9,
[KEY_SYM_ZERO] = KEY_0, [KEY_SYM_RPAREN] = KEY_0,
[KEY_SYM_MINUS] = KEY_MINUS, [KEY_SYM_USCORE] = KEY_MINUS,
[KEY_SYM_EQUAL] = KEY_EQUAL, [KEY_SYM_PLUS] = KEY_EQUAL,
[KEY_SYM_LBRKT] = KEY_LEFTBRACE, [KEY_SYM_LCURLY] = KEY_LEFTBRACE,
[KEY_SYM_RBRKT] = KEY_RIGHTBRACE, [KEY_SYM_RCURLY] = KEY_RIGHTBRACE,
[KEY_SYM_SLASH] = KEY_BACKSLASH, [KEY_SYM_PIPE] = KEY_BACKSLASH,
[KEY_SYM_TIC] = KEY_APOSTROPHE, [KEY_SYM_QUOTE] = KEY_APOSTROPHE,
[KEY_SYM_SEMIC] = KEY_SEMICOLON, [KEY_SYM_COLON] = KEY_SEMICOLON,
[KEY_SYM_COMMA] = KEY_COMMA, [KEY_SYM_LT] = KEY_COMMA,
[KEY_SYM_PERIOD] = KEY_DOT, [KEY_SYM_GT] = KEY_DOT,
[KEY_SYM_BSLASH] = KEY_SLASH, [KEY_SYM_QMARK] = KEY_SLASH,
[KEY_SYM_A] = KEY_A, [KEY_SYM_a] = KEY_A,
[KEY_SYM_B] = KEY_B, [KEY_SYM_b] = KEY_B,
[KEY_SYM_C] = KEY_C, [KEY_SYM_c] = KEY_C,
[KEY_SYM_D] = KEY_D, [KEY_SYM_d] = KEY_D,
[KEY_SYM_E] = KEY_E, [KEY_SYM_e] = KEY_E,
[KEY_SYM_F] = KEY_F, [KEY_SYM_f] = KEY_F,
[KEY_SYM_G] = KEY_G, [KEY_SYM_g] = KEY_G,
[KEY_SYM_H] = KEY_H, [KEY_SYM_h] = KEY_H,
[KEY_SYM_I] = KEY_I, [KEY_SYM_i] = KEY_I,
[KEY_SYM_J] = KEY_J, [KEY_SYM_j] = KEY_J,
[KEY_SYM_K] = KEY_K, [KEY_SYM_k] = KEY_K,
[KEY_SYM_L] = KEY_L, [KEY_SYM_l] = KEY_L,
[KEY_SYM_M] = KEY_M, [KEY_SYM_m] = KEY_M,
[KEY_SYM_N] = KEY_N, [KEY_SYM_n] = KEY_N,
[KEY_SYM_O] = KEY_O, [KEY_SYM_o] = KEY_O,
[KEY_SYM_P] = KEY_P, [KEY_SYM_p] = KEY_P,
[KEY_SYM_Q] = KEY_Q, [KEY_SYM_q] = KEY_Q,
[KEY_SYM_R] = KEY_R, [KEY_SYM_r] = KEY_R,
[KEY_SYM_S] = KEY_S, [KEY_SYM_s] = KEY_S,
[KEY_SYM_T] = KEY_T, [KEY_SYM_t] = KEY_T,
[KEY_SYM_U] = KEY_U, [KEY_SYM_u] = KEY_U,
[KEY_SYM_V] = KEY_V, [KEY_SYM_v] = KEY_V,
[KEY_SYM_W] = KEY_W, [KEY_SYM_w] = KEY_W,
[KEY_SYM_X] = KEY_X, [KEY_SYM_x] = KEY_X,
[KEY_SYM_Y] = KEY_Y, [KEY_SYM_y] = KEY_Y,
[KEY_SYM_Z] = KEY_Z, [KEY_SYM_z] = KEY_Z,
};
static void print_input(struct remote_input *input)
{
if (input->type == INPUT_TYPE_MOUSE) {
unsigned char buttons = input->mouse_buttons;
dbg("remote mouse movement: (x,y)=(%d,%d)%s%s%s%s\n",
input->data.mouse.x, input->data.mouse.y,
(buttons) ? " -- buttons:" : "",
(buttons & REMOTE_BUTTON_LEFT) ? "left " : "",
(buttons & REMOTE_BUTTON_MIDDLE) ? "middle " : "",
(buttons & REMOTE_BUTTON_RIGHT) ? "right" : ""
);
} else {
dbg("remote keypress (code, flag, down):"
"%d (0x%x) [0x%x] [0x%x]\n",
input->data.keyboard.key_code,
input->data.keyboard.key_code,
input->data.keyboard.key_flag,
input->data.keyboard.key_down
);
}
}
static void send_mouse_event(struct input_dev *dev, struct remote_input *input)
{
unsigned char buttons = input->mouse_buttons;
input_report_abs(dev, ABS_X, input->data.mouse.x);
input_report_abs(dev, ABS_Y, input->data.mouse.y);
input_report_key(dev, BTN_LEFT, buttons & REMOTE_BUTTON_LEFT);
input_report_key(dev, BTN_MIDDLE, buttons & REMOTE_BUTTON_MIDDLE);
input_report_key(dev, BTN_RIGHT, buttons & REMOTE_BUTTON_RIGHT);
input_sync(dev);
}
static void send_keyboard_event(struct input_dev *dev,
struct remote_input *input)
{
unsigned int key;
unsigned short code = input->data.keyboard.key_code;
if (code & 0xff00)
key = xlate_high[code & 0xff];
else
key = xlate[code];
input_report_key(dev, key, input->data.keyboard.key_down);
input_sync(dev);
}
void ibmasm_handle_mouse_interrupt(struct service_processor *sp)
{
unsigned long reader;
unsigned long writer;
struct remote_input input;
reader = get_queue_reader(sp);
writer = get_queue_writer(sp);
while (reader != writer) {
memcpy_fromio(&input, get_queue_entry(sp, reader),
sizeof(struct remote_input));
print_input(&input);
if (input.type == INPUT_TYPE_MOUSE) {
send_mouse_event(sp->remote.mouse_dev, &input);
} else if (input.type == INPUT_TYPE_KEYBOARD) {
send_keyboard_event(sp->remote.keybd_dev, &input);
} else
break;
reader = advance_queue_reader(sp, reader);
writer = get_queue_writer(sp);
}
}
int ibmasm_init_remote_input_dev(struct service_processor *sp)
{
/* set up the mouse input device */
struct input_dev *mouse_dev, *keybd_dev;
struct pci_dev *pdev = to_pci_dev(sp->dev);
int error = -ENOMEM;
int i;
sp->remote.mouse_dev = mouse_dev = input_allocate_device();
sp->remote.keybd_dev = keybd_dev = input_allocate_device();
if (!mouse_dev || !keybd_dev)
goto err_free_devices;
mouse_dev->id.bustype = BUS_PCI;
mouse_dev->id.vendor = pdev->vendor;
mouse_dev->id.product = pdev->device;
mouse_dev->id.version = 1;
mouse_dev->dev.parent = sp->dev;
mouse_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
mouse_dev->keybit[BIT_WORD(BTN_MOUSE)] = BIT_MASK(BTN_LEFT) |
BIT_MASK(BTN_RIGHT) | BIT_MASK(BTN_MIDDLE);
set_bit(BTN_TOUCH, mouse_dev->keybit);
mouse_dev->name = "ibmasm RSA I remote mouse";
input_set_abs_params(mouse_dev, ABS_X, 0, MOUSE_X_MAX, 0, 0);
input_set_abs_params(mouse_dev, ABS_Y, 0, MOUSE_Y_MAX, 0, 0);
keybd_dev->id.bustype = BUS_PCI;
keybd_dev->id.vendor = pdev->vendor;
keybd_dev->id.product = pdev->device;
keybd_dev->id.version = 2;
keybd_dev->dev.parent = sp->dev;
keybd_dev->evbit[0] = BIT_MASK(EV_KEY);
keybd_dev->name = "ibmasm RSA I remote keyboard";
for (i = 0; i < XLATE_SIZE; i++) {
if (xlate_high[i])
set_bit(xlate_high[i], keybd_dev->keybit);
if (xlate[i])
set_bit(xlate[i], keybd_dev->keybit);
}
error = input_register_device(mouse_dev);
if (error)
goto err_free_devices;
error = input_register_device(keybd_dev);
if (error)
goto err_unregister_mouse_dev;
enable_mouse_interrupts(sp);
printk(KERN_INFO "ibmasm remote responding to events on RSA card %d\n", sp->number);
return 0;
err_unregister_mouse_dev:
input_unregister_device(mouse_dev);
mouse_dev = NULL; /* so we don't try to free it again below */
err_free_devices:
input_free_device(mouse_dev);
input_free_device(keybd_dev);
return error;
}
void ibmasm_free_remote_input_dev(struct service_processor *sp)
{
disable_mouse_interrupts(sp);
input_unregister_device(sp->remote.mouse_dev);
input_unregister_device(sp->remote.keybd_dev);
}
| gpl-2.0 |
iwonasado/kcal | drivers/misc/ibmasm/remote.c | 14836 | 10187 | /*
* IBM ASM Service Processor Device Driver
*
* 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.
*
* Copyright (C) IBM Corporation, 2004
*
* Authors: Max Asböck <amax@us.ibm.com>
* Vernon Mauery <vernux@us.ibm.com>
*
*/
/* Remote mouse and keyboard event handling functions */
#include <linux/pci.h>
#include "ibmasm.h"
#include "remote.h"
#define MOUSE_X_MAX 1600
#define MOUSE_Y_MAX 1200
static const unsigned short xlate_high[XLATE_SIZE] = {
[KEY_SYM_ENTER & 0xff] = KEY_ENTER,
[KEY_SYM_KPSLASH & 0xff] = KEY_KPSLASH,
[KEY_SYM_KPSTAR & 0xff] = KEY_KPASTERISK,
[KEY_SYM_KPMINUS & 0xff] = KEY_KPMINUS,
[KEY_SYM_KPDOT & 0xff] = KEY_KPDOT,
[KEY_SYM_KPPLUS & 0xff] = KEY_KPPLUS,
[KEY_SYM_KP0 & 0xff] = KEY_KP0,
[KEY_SYM_KP1 & 0xff] = KEY_KP1,
[KEY_SYM_KP2 & 0xff] = KEY_KP2, [KEY_SYM_KPDOWN & 0xff] = KEY_KP2,
[KEY_SYM_KP3 & 0xff] = KEY_KP3,
[KEY_SYM_KP4 & 0xff] = KEY_KP4, [KEY_SYM_KPLEFT & 0xff] = KEY_KP4,
[KEY_SYM_KP5 & 0xff] = KEY_KP5,
[KEY_SYM_KP6 & 0xff] = KEY_KP6, [KEY_SYM_KPRIGHT & 0xff] = KEY_KP6,
[KEY_SYM_KP7 & 0xff] = KEY_KP7,
[KEY_SYM_KP8 & 0xff] = KEY_KP8, [KEY_SYM_KPUP & 0xff] = KEY_KP8,
[KEY_SYM_KP9 & 0xff] = KEY_KP9,
[KEY_SYM_BK_SPC & 0xff] = KEY_BACKSPACE,
[KEY_SYM_TAB & 0xff] = KEY_TAB,
[KEY_SYM_CTRL & 0xff] = KEY_LEFTCTRL,
[KEY_SYM_ALT & 0xff] = KEY_LEFTALT,
[KEY_SYM_INSERT & 0xff] = KEY_INSERT,
[KEY_SYM_DELETE & 0xff] = KEY_DELETE,
[KEY_SYM_SHIFT & 0xff] = KEY_LEFTSHIFT,
[KEY_SYM_UARROW & 0xff] = KEY_UP,
[KEY_SYM_DARROW & 0xff] = KEY_DOWN,
[KEY_SYM_LARROW & 0xff] = KEY_LEFT,
[KEY_SYM_RARROW & 0xff] = KEY_RIGHT,
[KEY_SYM_ESCAPE & 0xff] = KEY_ESC,
[KEY_SYM_PAGEUP & 0xff] = KEY_PAGEUP,
[KEY_SYM_PAGEDOWN & 0xff] = KEY_PAGEDOWN,
[KEY_SYM_HOME & 0xff] = KEY_HOME,
[KEY_SYM_END & 0xff] = KEY_END,
[KEY_SYM_F1 & 0xff] = KEY_F1,
[KEY_SYM_F2 & 0xff] = KEY_F2,
[KEY_SYM_F3 & 0xff] = KEY_F3,
[KEY_SYM_F4 & 0xff] = KEY_F4,
[KEY_SYM_F5 & 0xff] = KEY_F5,
[KEY_SYM_F6 & 0xff] = KEY_F6,
[KEY_SYM_F7 & 0xff] = KEY_F7,
[KEY_SYM_F8 & 0xff] = KEY_F8,
[KEY_SYM_F9 & 0xff] = KEY_F9,
[KEY_SYM_F10 & 0xff] = KEY_F10,
[KEY_SYM_F11 & 0xff] = KEY_F11,
[KEY_SYM_F12 & 0xff] = KEY_F12,
[KEY_SYM_CAP_LOCK & 0xff] = KEY_CAPSLOCK,
[KEY_SYM_NUM_LOCK & 0xff] = KEY_NUMLOCK,
[KEY_SYM_SCR_LOCK & 0xff] = KEY_SCROLLLOCK,
};
static const unsigned short xlate[XLATE_SIZE] = {
[NO_KEYCODE] = KEY_RESERVED,
[KEY_SYM_SPACE] = KEY_SPACE,
[KEY_SYM_TILDE] = KEY_GRAVE, [KEY_SYM_BKTIC] = KEY_GRAVE,
[KEY_SYM_ONE] = KEY_1, [KEY_SYM_BANG] = KEY_1,
[KEY_SYM_TWO] = KEY_2, [KEY_SYM_AT] = KEY_2,
[KEY_SYM_THREE] = KEY_3, [KEY_SYM_POUND] = KEY_3,
[KEY_SYM_FOUR] = KEY_4, [KEY_SYM_DOLLAR] = KEY_4,
[KEY_SYM_FIVE] = KEY_5, [KEY_SYM_PERCENT] = KEY_5,
[KEY_SYM_SIX] = KEY_6, [KEY_SYM_CARAT] = KEY_6,
[KEY_SYM_SEVEN] = KEY_7, [KEY_SYM_AMPER] = KEY_7,
[KEY_SYM_EIGHT] = KEY_8, [KEY_SYM_STAR] = KEY_8,
[KEY_SYM_NINE] = KEY_9, [KEY_SYM_LPAREN] = KEY_9,
[KEY_SYM_ZERO] = KEY_0, [KEY_SYM_RPAREN] = KEY_0,
[KEY_SYM_MINUS] = KEY_MINUS, [KEY_SYM_USCORE] = KEY_MINUS,
[KEY_SYM_EQUAL] = KEY_EQUAL, [KEY_SYM_PLUS] = KEY_EQUAL,
[KEY_SYM_LBRKT] = KEY_LEFTBRACE, [KEY_SYM_LCURLY] = KEY_LEFTBRACE,
[KEY_SYM_RBRKT] = KEY_RIGHTBRACE, [KEY_SYM_RCURLY] = KEY_RIGHTBRACE,
[KEY_SYM_SLASH] = KEY_BACKSLASH, [KEY_SYM_PIPE] = KEY_BACKSLASH,
[KEY_SYM_TIC] = KEY_APOSTROPHE, [KEY_SYM_QUOTE] = KEY_APOSTROPHE,
[KEY_SYM_SEMIC] = KEY_SEMICOLON, [KEY_SYM_COLON] = KEY_SEMICOLON,
[KEY_SYM_COMMA] = KEY_COMMA, [KEY_SYM_LT] = KEY_COMMA,
[KEY_SYM_PERIOD] = KEY_DOT, [KEY_SYM_GT] = KEY_DOT,
[KEY_SYM_BSLASH] = KEY_SLASH, [KEY_SYM_QMARK] = KEY_SLASH,
[KEY_SYM_A] = KEY_A, [KEY_SYM_a] = KEY_A,
[KEY_SYM_B] = KEY_B, [KEY_SYM_b] = KEY_B,
[KEY_SYM_C] = KEY_C, [KEY_SYM_c] = KEY_C,
[KEY_SYM_D] = KEY_D, [KEY_SYM_d] = KEY_D,
[KEY_SYM_E] = KEY_E, [KEY_SYM_e] = KEY_E,
[KEY_SYM_F] = KEY_F, [KEY_SYM_f] = KEY_F,
[KEY_SYM_G] = KEY_G, [KEY_SYM_g] = KEY_G,
[KEY_SYM_H] = KEY_H, [KEY_SYM_h] = KEY_H,
[KEY_SYM_I] = KEY_I, [KEY_SYM_i] = KEY_I,
[KEY_SYM_J] = KEY_J, [KEY_SYM_j] = KEY_J,
[KEY_SYM_K] = KEY_K, [KEY_SYM_k] = KEY_K,
[KEY_SYM_L] = KEY_L, [KEY_SYM_l] = KEY_L,
[KEY_SYM_M] = KEY_M, [KEY_SYM_m] = KEY_M,
[KEY_SYM_N] = KEY_N, [KEY_SYM_n] = KEY_N,
[KEY_SYM_O] = KEY_O, [KEY_SYM_o] = KEY_O,
[KEY_SYM_P] = KEY_P, [KEY_SYM_p] = KEY_P,
[KEY_SYM_Q] = KEY_Q, [KEY_SYM_q] = KEY_Q,
[KEY_SYM_R] = KEY_R, [KEY_SYM_r] = KEY_R,
[KEY_SYM_S] = KEY_S, [KEY_SYM_s] = KEY_S,
[KEY_SYM_T] = KEY_T, [KEY_SYM_t] = KEY_T,
[KEY_SYM_U] = KEY_U, [KEY_SYM_u] = KEY_U,
[KEY_SYM_V] = KEY_V, [KEY_SYM_v] = KEY_V,
[KEY_SYM_W] = KEY_W, [KEY_SYM_w] = KEY_W,
[KEY_SYM_X] = KEY_X, [KEY_SYM_x] = KEY_X,
[KEY_SYM_Y] = KEY_Y, [KEY_SYM_y] = KEY_Y,
[KEY_SYM_Z] = KEY_Z, [KEY_SYM_z] = KEY_Z,
};
static void print_input(struct remote_input *input)
{
if (input->type == INPUT_TYPE_MOUSE) {
unsigned char buttons = input->mouse_buttons;
dbg("remote mouse movement: (x,y)=(%d,%d)%s%s%s%s\n",
input->data.mouse.x, input->data.mouse.y,
(buttons) ? " -- buttons:" : "",
(buttons & REMOTE_BUTTON_LEFT) ? "left " : "",
(buttons & REMOTE_BUTTON_MIDDLE) ? "middle " : "",
(buttons & REMOTE_BUTTON_RIGHT) ? "right" : ""
);
} else {
dbg("remote keypress (code, flag, down):"
"%d (0x%x) [0x%x] [0x%x]\n",
input->data.keyboard.key_code,
input->data.keyboard.key_code,
input->data.keyboard.key_flag,
input->data.keyboard.key_down
);
}
}
static void send_mouse_event(struct input_dev *dev, struct remote_input *input)
{
unsigned char buttons = input->mouse_buttons;
input_report_abs(dev, ABS_X, input->data.mouse.x);
input_report_abs(dev, ABS_Y, input->data.mouse.y);
input_report_key(dev, BTN_LEFT, buttons & REMOTE_BUTTON_LEFT);
input_report_key(dev, BTN_MIDDLE, buttons & REMOTE_BUTTON_MIDDLE);
input_report_key(dev, BTN_RIGHT, buttons & REMOTE_BUTTON_RIGHT);
input_sync(dev);
}
static void send_keyboard_event(struct input_dev *dev,
struct remote_input *input)
{
unsigned int key;
unsigned short code = input->data.keyboard.key_code;
if (code & 0xff00)
key = xlate_high[code & 0xff];
else
key = xlate[code];
input_report_key(dev, key, input->data.keyboard.key_down);
input_sync(dev);
}
void ibmasm_handle_mouse_interrupt(struct service_processor *sp)
{
unsigned long reader;
unsigned long writer;
struct remote_input input;
reader = get_queue_reader(sp);
writer = get_queue_writer(sp);
while (reader != writer) {
memcpy_fromio(&input, get_queue_entry(sp, reader),
sizeof(struct remote_input));
print_input(&input);
if (input.type == INPUT_TYPE_MOUSE) {
send_mouse_event(sp->remote.mouse_dev, &input);
} else if (input.type == INPUT_TYPE_KEYBOARD) {
send_keyboard_event(sp->remote.keybd_dev, &input);
} else
break;
reader = advance_queue_reader(sp, reader);
writer = get_queue_writer(sp);
}
}
int ibmasm_init_remote_input_dev(struct service_processor *sp)
{
/* set up the mouse input device */
struct input_dev *mouse_dev, *keybd_dev;
struct pci_dev *pdev = to_pci_dev(sp->dev);
int error = -ENOMEM;
int i;
sp->remote.mouse_dev = mouse_dev = input_allocate_device();
sp->remote.keybd_dev = keybd_dev = input_allocate_device();
if (!mouse_dev || !keybd_dev)
goto err_free_devices;
mouse_dev->id.bustype = BUS_PCI;
mouse_dev->id.vendor = pdev->vendor;
mouse_dev->id.product = pdev->device;
mouse_dev->id.version = 1;
mouse_dev->dev.parent = sp->dev;
mouse_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
mouse_dev->keybit[BIT_WORD(BTN_MOUSE)] = BIT_MASK(BTN_LEFT) |
BIT_MASK(BTN_RIGHT) | BIT_MASK(BTN_MIDDLE);
set_bit(BTN_TOUCH, mouse_dev->keybit);
mouse_dev->name = "ibmasm RSA I remote mouse";
input_set_abs_params(mouse_dev, ABS_X, 0, MOUSE_X_MAX, 0, 0);
input_set_abs_params(mouse_dev, ABS_Y, 0, MOUSE_Y_MAX, 0, 0);
keybd_dev->id.bustype = BUS_PCI;
keybd_dev->id.vendor = pdev->vendor;
keybd_dev->id.product = pdev->device;
keybd_dev->id.version = 2;
keybd_dev->dev.parent = sp->dev;
keybd_dev->evbit[0] = BIT_MASK(EV_KEY);
keybd_dev->name = "ibmasm RSA I remote keyboard";
for (i = 0; i < XLATE_SIZE; i++) {
if (xlate_high[i])
set_bit(xlate_high[i], keybd_dev->keybit);
if (xlate[i])
set_bit(xlate[i], keybd_dev->keybit);
}
error = input_register_device(mouse_dev);
if (error)
goto err_free_devices;
error = input_register_device(keybd_dev);
if (error)
goto err_unregister_mouse_dev;
enable_mouse_interrupts(sp);
printk(KERN_INFO "ibmasm remote responding to events on RSA card %d\n", sp->number);
return 0;
err_unregister_mouse_dev:
input_unregister_device(mouse_dev);
mouse_dev = NULL; /* so we don't try to free it again below */
err_free_devices:
input_free_device(mouse_dev);
input_free_device(keybd_dev);
return error;
}
void ibmasm_free_remote_input_dev(struct service_processor *sp)
{
disable_mouse_interrupts(sp);
input_unregister_device(sp->remote.mouse_dev);
input_unregister_device(sp->remote.keybd_dev);
}
| gpl-2.0 |
notro/linux-staging | lib/iommu-common.c | 245 | 7255 | /*
* IOMMU mmap management and range allocation functions.
* Based almost entirely upon the powerpc iommu allocator.
*/
#include <linux/export.h>
#include <linux/bitmap.h>
#include <linux/bug.h>
#include <linux/iommu-helper.h>
#include <linux/iommu-common.h>
#include <linux/dma-mapping.h>
#include <linux/hash.h>
#ifndef DMA_ERROR_CODE
#define DMA_ERROR_CODE (~(dma_addr_t)0x0)
#endif
static unsigned long iommu_large_alloc = 15;
static DEFINE_PER_CPU(unsigned int, iommu_hash_common);
static inline bool need_flush(struct iommu_map_table *iommu)
{
return (iommu->lazy_flush != NULL &&
(iommu->flags & IOMMU_NEED_FLUSH) != 0);
}
static inline void set_flush(struct iommu_map_table *iommu)
{
iommu->flags |= IOMMU_NEED_FLUSH;
}
static inline void clear_flush(struct iommu_map_table *iommu)
{
iommu->flags &= ~IOMMU_NEED_FLUSH;
}
static void setup_iommu_pool_hash(void)
{
unsigned int i;
static bool do_once;
if (do_once)
return;
do_once = true;
for_each_possible_cpu(i)
per_cpu(iommu_hash_common, i) = hash_32(i, IOMMU_POOL_HASHBITS);
}
/*
* Initialize iommu_pool entries for the iommu_map_table. `num_entries'
* is the number of table entries. If `large_pool' is set to true,
* the top 1/4 of the table will be set aside for pool allocations
* of more than iommu_large_alloc pages.
*/
void iommu_tbl_pool_init(struct iommu_map_table *iommu,
unsigned long num_entries,
u32 table_shift,
void (*lazy_flush)(struct iommu_map_table *),
bool large_pool, u32 npools,
bool skip_span_boundary_check)
{
unsigned int start, i;
struct iommu_pool *p = &(iommu->large_pool);
setup_iommu_pool_hash();
if (npools == 0)
iommu->nr_pools = IOMMU_NR_POOLS;
else
iommu->nr_pools = npools;
BUG_ON(npools > IOMMU_NR_POOLS);
iommu->table_shift = table_shift;
iommu->lazy_flush = lazy_flush;
start = 0;
if (skip_span_boundary_check)
iommu->flags |= IOMMU_NO_SPAN_BOUND;
if (large_pool)
iommu->flags |= IOMMU_HAS_LARGE_POOL;
if (!large_pool)
iommu->poolsize = num_entries/iommu->nr_pools;
else
iommu->poolsize = (num_entries * 3 / 4)/iommu->nr_pools;
for (i = 0; i < iommu->nr_pools; i++) {
spin_lock_init(&(iommu->pools[i].lock));
iommu->pools[i].start = start;
iommu->pools[i].hint = start;
start += iommu->poolsize; /* start for next pool */
iommu->pools[i].end = start - 1;
}
if (!large_pool)
return;
/* initialize large_pool */
spin_lock_init(&(p->lock));
p->start = start;
p->hint = p->start;
p->end = num_entries;
}
EXPORT_SYMBOL(iommu_tbl_pool_init);
unsigned long iommu_tbl_range_alloc(struct device *dev,
struct iommu_map_table *iommu,
unsigned long npages,
unsigned long *handle,
unsigned long mask,
unsigned int align_order)
{
unsigned int pool_hash = __this_cpu_read(iommu_hash_common);
unsigned long n, end, start, limit, boundary_size;
struct iommu_pool *pool;
int pass = 0;
unsigned int pool_nr;
unsigned int npools = iommu->nr_pools;
unsigned long flags;
bool large_pool = ((iommu->flags & IOMMU_HAS_LARGE_POOL) != 0);
bool largealloc = (large_pool && npages > iommu_large_alloc);
unsigned long shift;
unsigned long align_mask = 0;
if (align_order > 0)
align_mask = 0xffffffffffffffffl >> (64 - align_order);
/* Sanity check */
if (unlikely(npages == 0)) {
WARN_ON_ONCE(1);
return DMA_ERROR_CODE;
}
if (largealloc) {
pool = &(iommu->large_pool);
pool_nr = 0; /* to keep compiler happy */
} else {
/* pick out pool_nr */
pool_nr = pool_hash & (npools - 1);
pool = &(iommu->pools[pool_nr]);
}
spin_lock_irqsave(&pool->lock, flags);
again:
if (pass == 0 && handle && *handle &&
(*handle >= pool->start) && (*handle < pool->end))
start = *handle;
else
start = pool->hint;
limit = pool->end;
/* The case below can happen if we have a small segment appended
* to a large, or when the previous alloc was at the very end of
* the available space. If so, go back to the beginning. If a
* flush is needed, it will get done based on the return value
* from iommu_area_alloc() below.
*/
if (start >= limit)
start = pool->start;
shift = iommu->table_map_base >> iommu->table_shift;
if (limit + shift > mask) {
limit = mask - shift + 1;
/* If we're constrained on address range, first try
* at the masked hint to avoid O(n) search complexity,
* but on second pass, start at 0 in pool 0.
*/
if ((start & mask) >= limit || pass > 0) {
spin_unlock(&(pool->lock));
pool = &(iommu->pools[0]);
spin_lock(&(pool->lock));
start = pool->start;
} else {
start &= mask;
}
}
if (dev)
boundary_size = ALIGN(dma_get_seg_boundary(dev) + 1,
1 << iommu->table_shift);
else
boundary_size = ALIGN(1ULL << 32, 1 << iommu->table_shift);
boundary_size = boundary_size >> iommu->table_shift;
/*
* if the skip_span_boundary_check had been set during init, we set
* things up so that iommu_is_span_boundary() merely checks if the
* (index + npages) < num_tsb_entries
*/
if ((iommu->flags & IOMMU_NO_SPAN_BOUND) != 0) {
shift = 0;
boundary_size = iommu->poolsize * iommu->nr_pools;
}
n = iommu_area_alloc(iommu->map, limit, start, npages, shift,
boundary_size, align_mask);
if (n == -1) {
if (likely(pass == 0)) {
/* First failure, rescan from the beginning. */
pool->hint = pool->start;
set_flush(iommu);
pass++;
goto again;
} else if (!largealloc && pass <= iommu->nr_pools) {
spin_unlock(&(pool->lock));
pool_nr = (pool_nr + 1) & (iommu->nr_pools - 1);
pool = &(iommu->pools[pool_nr]);
spin_lock(&(pool->lock));
pool->hint = pool->start;
set_flush(iommu);
pass++;
goto again;
} else {
/* give up */
n = DMA_ERROR_CODE;
goto bail;
}
}
if (n < pool->hint || need_flush(iommu)) {
clear_flush(iommu);
iommu->lazy_flush(iommu);
}
end = n + npages;
pool->hint = end;
/* Update handle for SG allocations */
if (handle)
*handle = end;
bail:
spin_unlock_irqrestore(&(pool->lock), flags);
return n;
}
EXPORT_SYMBOL(iommu_tbl_range_alloc);
static struct iommu_pool *get_pool(struct iommu_map_table *tbl,
unsigned long entry)
{
struct iommu_pool *p;
unsigned long largepool_start = tbl->large_pool.start;
bool large_pool = ((tbl->flags & IOMMU_HAS_LARGE_POOL) != 0);
/* The large pool is the last pool at the top of the table */
if (large_pool && entry >= largepool_start) {
p = &tbl->large_pool;
} else {
unsigned int pool_nr = entry / tbl->poolsize;
BUG_ON(pool_nr >= tbl->nr_pools);
p = &tbl->pools[pool_nr];
}
return p;
}
/* Caller supplies the index of the entry into the iommu map table
* itself when the mapping from dma_addr to the entry is not the
* default addr->entry mapping below.
*/
void iommu_tbl_range_free(struct iommu_map_table *iommu, u64 dma_addr,
unsigned long npages, unsigned long entry)
{
struct iommu_pool *pool;
unsigned long flags;
unsigned long shift = iommu->table_shift;
if (entry == DMA_ERROR_CODE) /* use default addr->entry mapping */
entry = (dma_addr - iommu->table_map_base) >> shift;
pool = get_pool(iommu, entry);
spin_lock_irqsave(&(pool->lock), flags);
bitmap_clear(iommu->map, entry, npages);
spin_unlock_irqrestore(&(pool->lock), flags);
}
EXPORT_SYMBOL(iommu_tbl_range_free);
| gpl-2.0 |
GiterMirror/ti-linux-kernel | drivers/gpu/drm/nouveau/core/subdev/fb/ramnv50.c | 245 | 12971 | /*
* Copyright 2013 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Ben Skeggs
*/
#include <subdev/bios.h>
#include <subdev/bios/bit.h>
#include <subdev/bios/pll.h>
#include <subdev/bios/perf.h>
#include <subdev/bios/timing.h>
#include <subdev/clock/pll.h>
#include <subdev/fb.h>
#include <core/option.h>
#include <core/mm.h>
#include "ramseq.h"
#include "nv50.h"
struct nv50_ramseq {
struct hwsq base;
struct hwsq_reg r_0x002504;
struct hwsq_reg r_0x004008;
struct hwsq_reg r_0x00400c;
struct hwsq_reg r_0x00c040;
struct hwsq_reg r_0x100210;
struct hwsq_reg r_0x1002d0;
struct hwsq_reg r_0x1002d4;
struct hwsq_reg r_0x1002dc;
struct hwsq_reg r_0x100da0[8];
struct hwsq_reg r_0x100e20;
struct hwsq_reg r_0x100e24;
struct hwsq_reg r_0x611200;
struct hwsq_reg r_timing[9];
struct hwsq_reg r_mr[4];
};
struct nv50_ram {
struct nouveau_ram base;
struct nv50_ramseq hwsq;
};
#define QFX5800NVA0 1
static int
nv50_ram_calc(struct nouveau_fb *pfb, u32 freq)
{
struct nouveau_bios *bios = nouveau_bios(pfb);
struct nv50_ram *ram = (void *)pfb->ram;
struct nv50_ramseq *hwsq = &ram->hwsq;
struct nvbios_perfE perfE;
struct nvbios_pll mpll;
struct {
u32 data;
u8 size;
} ramcfg, timing;
u8 ver, hdr, cnt, len, strap;
int N1, M1, N2, M2, P;
int ret, i;
/* lookup closest matching performance table entry for frequency */
i = 0;
do {
ramcfg.data = nvbios_perfEp(bios, i++, &ver, &hdr, &cnt,
&ramcfg.size, &perfE);
if (!ramcfg.data || (ver < 0x25 || ver >= 0x40) ||
(ramcfg.size < 2)) {
nv_error(pfb, "invalid/missing perftab entry\n");
return -EINVAL;
}
} while (perfE.memory < freq);
/* locate specific data set for the attached memory */
strap = nvbios_ramcfg_index(bios);
if (strap >= cnt) {
nv_error(pfb, "invalid ramcfg strap\n");
return -EINVAL;
}
ramcfg.data += hdr + (strap * ramcfg.size);
/* lookup memory timings, if bios says they're present */
strap = nv_ro08(bios, ramcfg.data + 0x01);
if (strap != 0xff) {
timing.data = nvbios_timingEe(bios, strap, &ver, &hdr,
&cnt, &len);
if (!timing.data || ver != 0x10 || hdr < 0x12) {
nv_error(pfb, "invalid/missing timing entry "
"%02x %04x %02x %02x\n",
strap, timing.data, ver, hdr);
return -EINVAL;
}
} else {
timing.data = 0;
}
ret = ram_init(hwsq, nv_subdev(pfb));
if (ret)
return ret;
ram_wait(hwsq, 0x01, 0x00); /* wait for !vblank */
ram_wait(hwsq, 0x01, 0x01); /* wait for vblank */
ram_wr32(hwsq, 0x611200, 0x00003300);
ram_wr32(hwsq, 0x002504, 0x00000001); /* block fifo */
ram_nsec(hwsq, 8000);
ram_setf(hwsq, 0x10, 0x00); /* disable fb */
ram_wait(hwsq, 0x00, 0x01); /* wait for fb disabled */
ram_wr32(hwsq, 0x1002d4, 0x00000001); /* precharge */
ram_wr32(hwsq, 0x1002d0, 0x00000001); /* refresh */
ram_wr32(hwsq, 0x1002d0, 0x00000001); /* refresh */
ram_wr32(hwsq, 0x100210, 0x00000000); /* disable auto-refresh */
ram_wr32(hwsq, 0x1002dc, 0x00000001); /* enable self-refresh */
ret = nvbios_pll_parse(bios, 0x004008, &mpll);
mpll.vco2.max_freq = 0;
if (ret == 0) {
ret = nv04_pll_calc(nv_subdev(pfb), &mpll, freq,
&N1, &M1, &N2, &M2, &P);
if (ret == 0)
ret = -EINVAL;
}
if (ret < 0)
return ret;
ram_mask(hwsq, 0x00c040, 0xc000c000, 0x0000c000);
ram_mask(hwsq, 0x004008, 0x00000200, 0x00000200);
ram_mask(hwsq, 0x00400c, 0x0000ffff, (N1 << 8) | M1);
ram_mask(hwsq, 0x004008, 0x81ff0000, 0x80000000 | (mpll.bias_p << 19) |
(P << 22) | (P << 16));
#if QFX5800NVA0
for (i = 0; i < 8; i++)
ram_mask(hwsq, 0x100da0[i], 0x00000000, 0x00000000); /*XXX*/
#endif
ram_nsec(hwsq, 96000); /*XXX*/
ram_mask(hwsq, 0x004008, 0x00002200, 0x00002000);
ram_wr32(hwsq, 0x1002dc, 0x00000000); /* disable self-refresh */
ram_wr32(hwsq, 0x100210, 0x80000000); /* enable auto-refresh */
ram_nsec(hwsq, 12000);
switch (ram->base.type) {
case NV_MEM_TYPE_DDR2:
ram_nuke(hwsq, mr[0]); /* force update */
ram_mask(hwsq, mr[0], 0x000, 0x000);
break;
case NV_MEM_TYPE_GDDR3:
ram_mask(hwsq, mr[2], 0x000, 0x000);
ram_nuke(hwsq, mr[0]); /* force update */
ram_mask(hwsq, mr[0], 0x000, 0x000);
break;
default:
break;
}
ram_mask(hwsq, timing[3], 0x00000000, 0x00000000); /*XXX*/
ram_mask(hwsq, timing[1], 0x00000000, 0x00000000); /*XXX*/
ram_mask(hwsq, timing[6], 0x00000000, 0x00000000); /*XXX*/
ram_mask(hwsq, timing[7], 0x00000000, 0x00000000); /*XXX*/
ram_mask(hwsq, timing[8], 0x00000000, 0x00000000); /*XXX*/
ram_mask(hwsq, timing[0], 0x00000000, 0x00000000); /*XXX*/
ram_mask(hwsq, timing[2], 0x00000000, 0x00000000); /*XXX*/
ram_mask(hwsq, timing[4], 0x00000000, 0x00000000); /*XXX*/
ram_mask(hwsq, timing[5], 0x00000000, 0x00000000); /*XXX*/
ram_mask(hwsq, timing[0], 0x00000000, 0x00000000); /*XXX*/
#if QFX5800NVA0
ram_nuke(hwsq, 0x100e24);
ram_mask(hwsq, 0x100e24, 0x00000000, 0x00000000);
ram_nuke(hwsq, 0x100e20);
ram_mask(hwsq, 0x100e20, 0x00000000, 0x00000000);
#endif
ram_mask(hwsq, mr[0], 0x100, 0x100);
ram_mask(hwsq, mr[0], 0x100, 0x000);
ram_setf(hwsq, 0x10, 0x01); /* enable fb */
ram_wait(hwsq, 0x00, 0x00); /* wait for fb enabled */
ram_wr32(hwsq, 0x611200, 0x00003330);
ram_wr32(hwsq, 0x002504, 0x00000000); /* un-block fifo */
return 0;
}
static int
nv50_ram_prog(struct nouveau_fb *pfb)
{
struct nouveau_device *device = nv_device(pfb);
struct nv50_ram *ram = (void *)pfb->ram;
struct nv50_ramseq *hwsq = &ram->hwsq;
ram_exec(hwsq, nouveau_boolopt(device->cfgopt, "NvMemExec", false));
return 0;
}
static void
nv50_ram_tidy(struct nouveau_fb *pfb)
{
struct nv50_ram *ram = (void *)pfb->ram;
struct nv50_ramseq *hwsq = &ram->hwsq;
ram_exec(hwsq, false);
}
void
__nv50_ram_put(struct nouveau_fb *pfb, struct nouveau_mem *mem)
{
struct nouveau_mm_node *this;
while (!list_empty(&mem->regions)) {
this = list_first_entry(&mem->regions, typeof(*this), rl_entry);
list_del(&this->rl_entry);
nouveau_mm_free(&pfb->vram, &this);
}
nouveau_mm_free(&pfb->tags, &mem->tag);
}
void
nv50_ram_put(struct nouveau_fb *pfb, struct nouveau_mem **pmem)
{
struct nouveau_mem *mem = *pmem;
*pmem = NULL;
if (unlikely(mem == NULL))
return;
mutex_lock(&pfb->base.mutex);
__nv50_ram_put(pfb, mem);
mutex_unlock(&pfb->base.mutex);
kfree(mem);
}
int
nv50_ram_get(struct nouveau_fb *pfb, u64 size, u32 align, u32 ncmin,
u32 memtype, struct nouveau_mem **pmem)
{
struct nouveau_mm *heap = &pfb->vram;
struct nouveau_mm *tags = &pfb->tags;
struct nouveau_mm_node *r;
struct nouveau_mem *mem;
int comp = (memtype & 0x300) >> 8;
int type = (memtype & 0x07f);
int back = (memtype & 0x800);
int min, max, ret;
max = (size >> 12);
min = ncmin ? (ncmin >> 12) : max;
align >>= 12;
mem = kzalloc(sizeof(*mem), GFP_KERNEL);
if (!mem)
return -ENOMEM;
mutex_lock(&pfb->base.mutex);
if (comp) {
if (align == 16) {
int n = (max >> 4) * comp;
ret = nouveau_mm_head(tags, 1, n, n, 1, &mem->tag);
if (ret)
mem->tag = NULL;
}
if (unlikely(!mem->tag))
comp = 0;
}
INIT_LIST_HEAD(&mem->regions);
mem->memtype = (comp << 7) | type;
mem->size = max;
type = nv50_fb_memtype[type];
do {
if (back)
ret = nouveau_mm_tail(heap, type, max, min, align, &r);
else
ret = nouveau_mm_head(heap, type, max, min, align, &r);
if (ret) {
mutex_unlock(&pfb->base.mutex);
pfb->ram->put(pfb, &mem);
return ret;
}
list_add_tail(&r->rl_entry, &mem->regions);
max -= r->length;
} while (max);
mutex_unlock(&pfb->base.mutex);
r = list_first_entry(&mem->regions, struct nouveau_mm_node, rl_entry);
mem->offset = (u64)r->offset << 12;
*pmem = mem;
return 0;
}
static u32
nv50_fb_vram_rblock(struct nouveau_fb *pfb, struct nouveau_ram *ram)
{
int i, parts, colbits, rowbitsa, rowbitsb, banks;
u64 rowsize, predicted;
u32 r0, r4, rt, ru, rblock_size;
r0 = nv_rd32(pfb, 0x100200);
r4 = nv_rd32(pfb, 0x100204);
rt = nv_rd32(pfb, 0x100250);
ru = nv_rd32(pfb, 0x001540);
nv_debug(pfb, "memcfg 0x%08x 0x%08x 0x%08x 0x%08x\n", r0, r4, rt, ru);
for (i = 0, parts = 0; i < 8; i++) {
if (ru & (0x00010000 << i))
parts++;
}
colbits = (r4 & 0x0000f000) >> 12;
rowbitsa = ((r4 & 0x000f0000) >> 16) + 8;
rowbitsb = ((r4 & 0x00f00000) >> 20) + 8;
banks = 1 << (((r4 & 0x03000000) >> 24) + 2);
rowsize = parts * banks * (1 << colbits) * 8;
predicted = rowsize << rowbitsa;
if (r0 & 0x00000004)
predicted += rowsize << rowbitsb;
if (predicted != ram->size) {
nv_warn(pfb, "memory controller reports %d MiB VRAM\n",
(u32)(ram->size >> 20));
}
rblock_size = rowsize;
if (rt & 1)
rblock_size *= 3;
nv_debug(pfb, "rblock %d bytes\n", rblock_size);
return rblock_size;
}
int
nv50_ram_create_(struct nouveau_object *parent, struct nouveau_object *engine,
struct nouveau_oclass *oclass, int length, void **pobject)
{
const u32 rsvd_head = ( 256 * 1024) >> 12; /* vga memory */
const u32 rsvd_tail = (1024 * 1024) >> 12; /* vbios etc */
struct nouveau_bios *bios = nouveau_bios(parent);
struct nouveau_fb *pfb = nouveau_fb(parent);
struct nouveau_ram *ram;
int ret;
ret = nouveau_ram_create_(parent, engine, oclass, length, pobject);
ram = *pobject;
if (ret)
return ret;
ram->size = nv_rd32(pfb, 0x10020c);
ram->size = (ram->size & 0xffffff00) | ((ram->size & 0x000000ff) << 32);
switch (nv_rd32(pfb, 0x100714) & 0x00000007) {
case 0: ram->type = NV_MEM_TYPE_DDR1; break;
case 1:
if (nouveau_fb_bios_memtype(bios) == NV_MEM_TYPE_DDR3)
ram->type = NV_MEM_TYPE_DDR3;
else
ram->type = NV_MEM_TYPE_DDR2;
break;
case 2: ram->type = NV_MEM_TYPE_GDDR3; break;
case 3: ram->type = NV_MEM_TYPE_GDDR4; break;
case 4: ram->type = NV_MEM_TYPE_GDDR5; break;
default:
break;
}
ret = nouveau_mm_init(&pfb->vram, rsvd_head, (ram->size >> 12) -
(rsvd_head + rsvd_tail),
nv50_fb_vram_rblock(pfb, ram) >> 12);
if (ret)
return ret;
ram->ranks = (nv_rd32(pfb, 0x100200) & 0x4) ? 2 : 1;
ram->tags = nv_rd32(pfb, 0x100320);
ram->get = nv50_ram_get;
ram->put = nv50_ram_put;
return 0;
}
static int
nv50_ram_ctor(struct nouveau_object *parent, struct nouveau_object *engine,
struct nouveau_oclass *oclass, void *data, u32 datasize,
struct nouveau_object **pobject)
{
struct nv50_ram *ram;
int ret, i;
ret = nv50_ram_create(parent, engine, oclass, &ram);
*pobject = nv_object(ram);
if (ret)
return ret;
switch (ram->base.type) {
case NV_MEM_TYPE_DDR2:
case NV_MEM_TYPE_GDDR3:
ram->base.calc = nv50_ram_calc;
ram->base.prog = nv50_ram_prog;
ram->base.tidy = nv50_ram_tidy;
break;
default:
nv_warn(ram, "reclocking of this ram type unsupported\n");
return 0;
}
ram->hwsq.r_0x002504 = hwsq_reg(0x002504);
ram->hwsq.r_0x00c040 = hwsq_reg(0x00c040);
ram->hwsq.r_0x004008 = hwsq_reg(0x004008);
ram->hwsq.r_0x00400c = hwsq_reg(0x00400c);
ram->hwsq.r_0x100210 = hwsq_reg(0x100210);
ram->hwsq.r_0x1002d0 = hwsq_reg(0x1002d0);
ram->hwsq.r_0x1002d4 = hwsq_reg(0x1002d4);
ram->hwsq.r_0x1002dc = hwsq_reg(0x1002dc);
for (i = 0; i < 8; i++)
ram->hwsq.r_0x100da0[i] = hwsq_reg(0x100da0 + (i * 0x04));
ram->hwsq.r_0x100e20 = hwsq_reg(0x100e20);
ram->hwsq.r_0x100e24 = hwsq_reg(0x100e24);
ram->hwsq.r_0x611200 = hwsq_reg(0x611200);
for (i = 0; i < 9; i++)
ram->hwsq.r_timing[i] = hwsq_reg(0x100220 + (i * 0x04));
if (ram->base.ranks > 1) {
ram->hwsq.r_mr[0] = hwsq_reg2(0x1002c0, 0x1002c8);
ram->hwsq.r_mr[1] = hwsq_reg2(0x1002c4, 0x1002cc);
ram->hwsq.r_mr[2] = hwsq_reg2(0x1002e0, 0x1002e8);
ram->hwsq.r_mr[3] = hwsq_reg2(0x1002e4, 0x1002ec);
} else {
ram->hwsq.r_mr[0] = hwsq_reg(0x1002c0);
ram->hwsq.r_mr[1] = hwsq_reg(0x1002c4);
ram->hwsq.r_mr[2] = hwsq_reg(0x1002e0);
ram->hwsq.r_mr[3] = hwsq_reg(0x1002e4);
}
return 0;
}
struct nouveau_oclass
nv50_ram_oclass = {
.ofuncs = &(struct nouveau_ofuncs) {
.ctor = nv50_ram_ctor,
.dtor = _nouveau_ram_dtor,
.init = _nouveau_ram_init,
.fini = _nouveau_ram_fini,
}
};
| gpl-2.0 |
ISTweak/android_kernel_sharp_is03 | drivers/mfd/twl4030-power.c | 501 | 11195 | /*
* linux/drivers/i2c/chips/twl4030-power.c
*
* Handle TWL4030 Power initialization
*
* Copyright (C) 2008 Nokia Corporation
* Copyright (C) 2006 Texas Instruments, Inc
*
* Written by Kalle Jokiniemi
* Peter De Schrijver <peter.de-schrijver@nokia.com>
* Several fixes by Amit Kucheria <amit.kucheria@verdurent.com>
*
* This file is subject to the terms and conditions of the GNU General
* Public License. See the file "COPYING" in the main directory of this
* archive for more details.
*
* 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/pm.h>
#include <linux/i2c/twl4030.h>
#include <linux/platform_device.h>
#include <asm/mach-types.h>
static u8 twl4030_start_script_address = 0x2b;
#define PWR_P1_SW_EVENTS 0x10
#define PWR_DEVOFF (1<<0)
#define PHY_TO_OFF_PM_MASTER(p) (p - 0x36)
#define PHY_TO_OFF_PM_RECEIVER(p) (p - 0x5b)
/* resource - hfclk */
#define R_HFCLKOUT_DEV_GRP PHY_TO_OFF_PM_RECEIVER(0xe6)
/* PM events */
#define R_P1_SW_EVENTS PHY_TO_OFF_PM_MASTER(0x46)
#define R_P2_SW_EVENTS PHY_TO_OFF_PM_MASTER(0x47)
#define R_P3_SW_EVENTS PHY_TO_OFF_PM_MASTER(0x48)
#define R_CFG_P1_TRANSITION PHY_TO_OFF_PM_MASTER(0x36)
#define R_CFG_P2_TRANSITION PHY_TO_OFF_PM_MASTER(0x37)
#define R_CFG_P3_TRANSITION PHY_TO_OFF_PM_MASTER(0x38)
#define LVL_WAKEUP 0x08
#define ENABLE_WARMRESET (1<<4)
#define END_OF_SCRIPT 0x3f
#define R_SEQ_ADD_A2S PHY_TO_OFF_PM_MASTER(0x55)
#define R_SEQ_ADD_S2A12 PHY_TO_OFF_PM_MASTER(0x56)
#define R_SEQ_ADD_S2A3 PHY_TO_OFF_PM_MASTER(0x57)
#define R_SEQ_ADD_WARM PHY_TO_OFF_PM_MASTER(0x58)
#define R_MEMORY_ADDRESS PHY_TO_OFF_PM_MASTER(0x59)
#define R_MEMORY_DATA PHY_TO_OFF_PM_MASTER(0x5a)
#define R_PROTECT_KEY 0x0E
#define R_KEY_1 0xC0
#define R_KEY_2 0x0C
/* resource configuration registers */
#define DEVGROUP_OFFSET 0
#define TYPE_OFFSET 1
/* Bit positions */
#define DEVGROUP_SHIFT 5
#define DEVGROUP_MASK (7 << DEVGROUP_SHIFT)
#define TYPE_SHIFT 0
#define TYPE_MASK (7 << TYPE_SHIFT)
#define TYPE2_SHIFT 3
#define TYPE2_MASK (3 << TYPE2_SHIFT)
static u8 res_config_addrs[] = {
[RES_VAUX1] = 0x17,
[RES_VAUX2] = 0x1b,
[RES_VAUX3] = 0x1f,
[RES_VAUX4] = 0x23,
[RES_VMMC1] = 0x27,
[RES_VMMC2] = 0x2b,
[RES_VPLL1] = 0x2f,
[RES_VPLL2] = 0x33,
[RES_VSIM] = 0x37,
[RES_VDAC] = 0x3b,
[RES_VINTANA1] = 0x3f,
[RES_VINTANA2] = 0x43,
[RES_VINTDIG] = 0x47,
[RES_VIO] = 0x4b,
[RES_VDD1] = 0x55,
[RES_VDD2] = 0x63,
[RES_VUSB_1V5] = 0x71,
[RES_VUSB_1V8] = 0x74,
[RES_VUSB_3V1] = 0x77,
[RES_VUSBCP] = 0x7a,
[RES_REGEN] = 0x7f,
[RES_NRES_PWRON] = 0x82,
[RES_CLKEN] = 0x85,
[RES_SYSEN] = 0x88,
[RES_HFCLKOUT] = 0x8b,
[RES_32KCLKOUT] = 0x8e,
[RES_RESET] = 0x91,
[RES_Main_Ref] = 0x94,
};
static int __init twl4030_write_script_byte(u8 address, u8 byte)
{
int err;
err = twl4030_i2c_write_u8(TWL4030_MODULE_PM_MASTER, address,
R_MEMORY_ADDRESS);
if (err)
goto out;
err = twl4030_i2c_write_u8(TWL4030_MODULE_PM_MASTER, byte,
R_MEMORY_DATA);
out:
return err;
}
static int __init twl4030_write_script_ins(u8 address, u16 pmb_message,
u8 delay, u8 next)
{
int err;
address *= 4;
err = twl4030_write_script_byte(address++, pmb_message >> 8);
if (err)
goto out;
err = twl4030_write_script_byte(address++, pmb_message & 0xff);
if (err)
goto out;
err = twl4030_write_script_byte(address++, delay);
if (err)
goto out;
err = twl4030_write_script_byte(address++, next);
out:
return err;
}
static int __init twl4030_write_script(u8 address, struct twl4030_ins *script,
int len)
{
int err;
for (; len; len--, address++, script++) {
if (len == 1) {
err = twl4030_write_script_ins(address,
script->pmb_message,
script->delay,
END_OF_SCRIPT);
if (err)
break;
} else {
err = twl4030_write_script_ins(address,
script->pmb_message,
script->delay,
address + 1);
if (err)
break;
}
}
return err;
}
static int __init twl4030_config_wakeup3_sequence(u8 address)
{
int err;
u8 data;
/* Set SLEEP to ACTIVE SEQ address for P3 */
err = twl4030_i2c_write_u8(TWL4030_MODULE_PM_MASTER, address,
R_SEQ_ADD_S2A3);
if (err)
goto out;
/* P3 LVL_WAKEUP should be on LEVEL */
err = twl4030_i2c_read_u8(TWL4030_MODULE_PM_MASTER, &data,
R_P3_SW_EVENTS);
if (err)
goto out;
data |= LVL_WAKEUP;
err = twl4030_i2c_write_u8(TWL4030_MODULE_PM_MASTER, data,
R_P3_SW_EVENTS);
out:
if (err)
pr_err("TWL4030 wakeup sequence for P3 config error\n");
return err;
}
static int __init twl4030_config_wakeup12_sequence(u8 address)
{
int err = 0;
u8 data;
/* Set SLEEP to ACTIVE SEQ address for P1 and P2 */
err = twl4030_i2c_write_u8(TWL4030_MODULE_PM_MASTER, address,
R_SEQ_ADD_S2A12);
if (err)
goto out;
/* P1/P2 LVL_WAKEUP should be on LEVEL */
err = twl4030_i2c_read_u8(TWL4030_MODULE_PM_MASTER, &data,
R_P1_SW_EVENTS);
if (err)
goto out;
data |= LVL_WAKEUP;
err = twl4030_i2c_write_u8(TWL4030_MODULE_PM_MASTER, data,
R_P1_SW_EVENTS);
if (err)
goto out;
err = twl4030_i2c_read_u8(TWL4030_MODULE_PM_MASTER, &data,
R_P2_SW_EVENTS);
if (err)
goto out;
data |= LVL_WAKEUP;
err = twl4030_i2c_write_u8(TWL4030_MODULE_PM_MASTER, data,
R_P2_SW_EVENTS);
if (err)
goto out;
if (machine_is_omap_3430sdp() || machine_is_omap_ldp()) {
/* Disabling AC charger effect on sleep-active transitions */
err = twl4030_i2c_read_u8(TWL4030_MODULE_PM_MASTER, &data,
R_CFG_P1_TRANSITION);
if (err)
goto out;
data &= ~(1<<1);
err = twl4030_i2c_write_u8(TWL4030_MODULE_PM_MASTER, data ,
R_CFG_P1_TRANSITION);
if (err)
goto out;
}
out:
if (err)
pr_err("TWL4030 wakeup sequence for P1 and P2" \
"config error\n");
return err;
}
static int __init twl4030_config_sleep_sequence(u8 address)
{
int err;
/* Set ACTIVE to SLEEP SEQ address in T2 memory*/
err = twl4030_i2c_write_u8(TWL4030_MODULE_PM_MASTER, address,
R_SEQ_ADD_A2S);
if (err)
pr_err("TWL4030 sleep sequence config error\n");
return err;
}
static int __init twl4030_config_warmreset_sequence(u8 address)
{
int err;
u8 rd_data;
/* Set WARM RESET SEQ address for P1 */
err = twl4030_i2c_write_u8(TWL4030_MODULE_PM_MASTER, address,
R_SEQ_ADD_WARM);
if (err)
goto out;
/* P1/P2/P3 enable WARMRESET */
err = twl4030_i2c_read_u8(TWL4030_MODULE_PM_MASTER, &rd_data,
R_P1_SW_EVENTS);
if (err)
goto out;
rd_data |= ENABLE_WARMRESET;
err = twl4030_i2c_write_u8(TWL4030_MODULE_PM_MASTER, rd_data,
R_P1_SW_EVENTS);
if (err)
goto out;
err = twl4030_i2c_read_u8(TWL4030_MODULE_PM_MASTER, &rd_data,
R_P2_SW_EVENTS);
if (err)
goto out;
rd_data |= ENABLE_WARMRESET;
err = twl4030_i2c_write_u8(TWL4030_MODULE_PM_MASTER, rd_data,
R_P2_SW_EVENTS);
if (err)
goto out;
err = twl4030_i2c_read_u8(TWL4030_MODULE_PM_MASTER, &rd_data,
R_P3_SW_EVENTS);
if (err)
goto out;
rd_data |= ENABLE_WARMRESET;
err = twl4030_i2c_write_u8(TWL4030_MODULE_PM_MASTER, rd_data,
R_P3_SW_EVENTS);
out:
if (err)
pr_err("TWL4030 warmreset seq config error\n");
return err;
}
static int __init twl4030_configure_resource(struct twl4030_resconfig *rconfig)
{
int rconfig_addr;
int err;
u8 type;
u8 grp;
if (rconfig->resource > TOTAL_RESOURCES) {
pr_err("TWL4030 Resource %d does not exist\n",
rconfig->resource);
return -EINVAL;
}
rconfig_addr = res_config_addrs[rconfig->resource];
/* Set resource group */
err = twl4030_i2c_read_u8(TWL4030_MODULE_PM_RECEIVER, &grp,
rconfig_addr + DEVGROUP_OFFSET);
if (err) {
pr_err("TWL4030 Resource %d group could not be read\n",
rconfig->resource);
return err;
}
if (rconfig->devgroup >= 0) {
grp &= ~DEVGROUP_MASK;
grp |= rconfig->devgroup << DEVGROUP_SHIFT;
err = twl4030_i2c_write_u8(TWL4030_MODULE_PM_RECEIVER,
grp, rconfig_addr + DEVGROUP_OFFSET);
if (err < 0) {
pr_err("TWL4030 failed to program devgroup\n");
return err;
}
}
/* Set resource types */
err = twl4030_i2c_read_u8(TWL4030_MODULE_PM_RECEIVER, &type,
rconfig_addr + TYPE_OFFSET);
if (err < 0) {
pr_err("TWL4030 Resource %d type could not be read\n",
rconfig->resource);
return err;
}
if (rconfig->type >= 0) {
type &= ~TYPE_MASK;
type |= rconfig->type << TYPE_SHIFT;
}
if (rconfig->type2 >= 0) {
type &= ~TYPE2_MASK;
type |= rconfig->type2 << TYPE2_SHIFT;
}
err = twl4030_i2c_write_u8(TWL4030_MODULE_PM_RECEIVER,
type, rconfig_addr + TYPE_OFFSET);
if (err < 0) {
pr_err("TWL4030 failed to program resource type\n");
return err;
}
return 0;
}
static int __init load_twl4030_script(struct twl4030_script *tscript,
u8 address)
{
int err;
static int order;
/* Make sure the script isn't going beyond last valid address (0x3f) */
if ((address + tscript->size) > END_OF_SCRIPT) {
pr_err("TWL4030 scripts too big error\n");
return -EINVAL;
}
err = twl4030_write_script(address, tscript->script, tscript->size);
if (err)
goto out;
if (tscript->flags & TWL4030_WRST_SCRIPT) {
err = twl4030_config_warmreset_sequence(address);
if (err)
goto out;
}
if (tscript->flags & TWL4030_WAKEUP12_SCRIPT) {
err = twl4030_config_wakeup12_sequence(address);
if (err)
goto out;
order = 1;
}
if (tscript->flags & TWL4030_WAKEUP3_SCRIPT) {
err = twl4030_config_wakeup3_sequence(address);
if (err)
goto out;
}
if (tscript->flags & TWL4030_SLEEP_SCRIPT)
if (order)
pr_warning("TWL4030: Bad order of scripts (sleep "\
"script before wakeup) Leads to boot"\
"failure on some boards\n");
err = twl4030_config_sleep_sequence(address);
out:
return err;
}
void __init twl4030_power_init(struct twl4030_power_data *twl4030_scripts)
{
int err = 0;
int i;
struct twl4030_resconfig *resconfig;
u8 address = twl4030_start_script_address;
err = twl4030_i2c_write_u8(TWL4030_MODULE_PM_MASTER, R_KEY_1,
R_PROTECT_KEY);
if (err)
goto unlock;
err = twl4030_i2c_write_u8(TWL4030_MODULE_PM_MASTER, R_KEY_2,
R_PROTECT_KEY);
if (err)
goto unlock;
for (i = 0; i < twl4030_scripts->num; i++) {
err = load_twl4030_script(twl4030_scripts->scripts[i], address);
if (err)
goto load;
address += twl4030_scripts->scripts[i]->size;
}
resconfig = twl4030_scripts->resource_config;
if (resconfig) {
while (resconfig->resource) {
err = twl4030_configure_resource(resconfig);
if (err)
goto resource;
resconfig++;
}
}
err = twl4030_i2c_write_u8(TWL4030_MODULE_PM_MASTER, 0, R_PROTECT_KEY);
if (err)
pr_err("TWL4030 Unable to relock registers\n");
return;
unlock:
if (err)
pr_err("TWL4030 Unable to unlock registers\n");
return;
load:
if (err)
pr_err("TWL4030 failed to load scripts\n");
return;
resource:
if (err)
pr_err("TWL4030 failed to configure resource\n");
return;
}
| gpl-2.0 |
alephzain/archos-gpl-gen8-kernel | drivers/infiniband/hw/amso1100/c2_rnic.c | 757 | 16782 | /*
* Copyright (c) 2005 Ammasso, Inc. All rights reserved.
* Copyright (c) 2005 Open Grid Computing, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/pci.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/delay.h>
#include <linux/ethtool.h>
#include <linux/mii.h>
#include <linux/if_vlan.h>
#include <linux/crc32.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/init.h>
#include <linux/dma-mapping.h>
#include <linux/mm.h>
#include <linux/inet.h>
#include <linux/vmalloc.h>
#include <linux/route.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/byteorder.h>
#include <rdma/ib_smi.h>
#include "c2.h"
#include "c2_vq.h"
/* Device capabilities */
#define C2_MIN_PAGESIZE 1024
#define C2_MAX_MRS 32768
#define C2_MAX_QPS 16000
#define C2_MAX_WQE_SZ 256
#define C2_MAX_QP_WR ((128*1024)/C2_MAX_WQE_SZ)
#define C2_MAX_SGES 4
#define C2_MAX_SGE_RD 1
#define C2_MAX_CQS 32768
#define C2_MAX_CQES 4096
#define C2_MAX_PDS 16384
/*
* Send the adapter INIT message to the amso1100
*/
static int c2_adapter_init(struct c2_dev *c2dev)
{
struct c2wr_init_req wr;
int err;
memset(&wr, 0, sizeof(wr));
c2_wr_set_id(&wr, CCWR_INIT);
wr.hdr.context = 0;
wr.hint_count = cpu_to_be64(c2dev->hint_count_dma);
wr.q0_host_shared = cpu_to_be64(c2dev->req_vq.shared_dma);
wr.q1_host_shared = cpu_to_be64(c2dev->rep_vq.shared_dma);
wr.q1_host_msg_pool = cpu_to_be64(c2dev->rep_vq.host_dma);
wr.q2_host_shared = cpu_to_be64(c2dev->aeq.shared_dma);
wr.q2_host_msg_pool = cpu_to_be64(c2dev->aeq.host_dma);
/* Post the init message */
err = vq_send_wr(c2dev, (union c2wr *) & wr);
return err;
}
/*
* Send the adapter TERM message to the amso1100
*/
static void c2_adapter_term(struct c2_dev *c2dev)
{
struct c2wr_init_req wr;
memset(&wr, 0, sizeof(wr));
c2_wr_set_id(&wr, CCWR_TERM);
wr.hdr.context = 0;
/* Post the init message */
vq_send_wr(c2dev, (union c2wr *) & wr);
c2dev->init = 0;
return;
}
/*
* Query the adapter
*/
static int c2_rnic_query(struct c2_dev *c2dev, struct ib_device_attr *props)
{
struct c2_vq_req *vq_req;
struct c2wr_rnic_query_req wr;
struct c2wr_rnic_query_rep *reply;
int err;
vq_req = vq_req_alloc(c2dev);
if (!vq_req)
return -ENOMEM;
c2_wr_set_id(&wr, CCWR_RNIC_QUERY);
wr.hdr.context = (unsigned long) vq_req;
wr.rnic_handle = c2dev->adapter_handle;
vq_req_get(c2dev, vq_req);
err = vq_send_wr(c2dev, (union c2wr *) &wr);
if (err) {
vq_req_put(c2dev, vq_req);
goto bail1;
}
err = vq_wait_for_reply(c2dev, vq_req);
if (err)
goto bail1;
reply =
(struct c2wr_rnic_query_rep *) (unsigned long) (vq_req->reply_msg);
if (!reply)
err = -ENOMEM;
else
err = c2_errno(reply);
if (err)
goto bail2;
props->fw_ver =
((u64)be32_to_cpu(reply->fw_ver_major) << 32) |
((be32_to_cpu(reply->fw_ver_minor) & 0xFFFF) << 16) |
(be32_to_cpu(reply->fw_ver_patch) & 0xFFFF);
memcpy(&props->sys_image_guid, c2dev->netdev->dev_addr, 6);
props->max_mr_size = 0xFFFFFFFF;
props->page_size_cap = ~(C2_MIN_PAGESIZE-1);
props->vendor_id = be32_to_cpu(reply->vendor_id);
props->vendor_part_id = be32_to_cpu(reply->part_number);
props->hw_ver = be32_to_cpu(reply->hw_version);
props->max_qp = be32_to_cpu(reply->max_qps);
props->max_qp_wr = be32_to_cpu(reply->max_qp_depth);
props->device_cap_flags = c2dev->device_cap_flags;
props->max_sge = C2_MAX_SGES;
props->max_sge_rd = C2_MAX_SGE_RD;
props->max_cq = be32_to_cpu(reply->max_cqs);
props->max_cqe = be32_to_cpu(reply->max_cq_depth);
props->max_mr = be32_to_cpu(reply->max_mrs);
props->max_pd = be32_to_cpu(reply->max_pds);
props->max_qp_rd_atom = be32_to_cpu(reply->max_qp_ird);
props->max_ee_rd_atom = 0;
props->max_res_rd_atom = be32_to_cpu(reply->max_global_ird);
props->max_qp_init_rd_atom = be32_to_cpu(reply->max_qp_ord);
props->max_ee_init_rd_atom = 0;
props->atomic_cap = IB_ATOMIC_NONE;
props->max_ee = 0;
props->max_rdd = 0;
props->max_mw = be32_to_cpu(reply->max_mws);
props->max_raw_ipv6_qp = 0;
props->max_raw_ethy_qp = 0;
props->max_mcast_grp = 0;
props->max_mcast_qp_attach = 0;
props->max_total_mcast_qp_attach = 0;
props->max_ah = 0;
props->max_fmr = 0;
props->max_map_per_fmr = 0;
props->max_srq = 0;
props->max_srq_wr = 0;
props->max_srq_sge = 0;
props->max_pkeys = 0;
props->local_ca_ack_delay = 0;
bail2:
vq_repbuf_free(c2dev, reply);
bail1:
vq_req_free(c2dev, vq_req);
return err;
}
/*
* Add an IP address to the RNIC interface
*/
int c2_add_addr(struct c2_dev *c2dev, __be32 inaddr, __be32 inmask)
{
struct c2_vq_req *vq_req;
struct c2wr_rnic_setconfig_req *wr;
struct c2wr_rnic_setconfig_rep *reply;
struct c2_netaddr netaddr;
int err, len;
vq_req = vq_req_alloc(c2dev);
if (!vq_req)
return -ENOMEM;
len = sizeof(struct c2_netaddr);
wr = kmalloc(c2dev->req_vq.msg_size, GFP_KERNEL);
if (!wr) {
err = -ENOMEM;
goto bail0;
}
c2_wr_set_id(wr, CCWR_RNIC_SETCONFIG);
wr->hdr.context = (unsigned long) vq_req;
wr->rnic_handle = c2dev->adapter_handle;
wr->option = cpu_to_be32(C2_CFG_ADD_ADDR);
netaddr.ip_addr = inaddr;
netaddr.netmask = inmask;
netaddr.mtu = 0;
memcpy(wr->data, &netaddr, len);
vq_req_get(c2dev, vq_req);
err = vq_send_wr(c2dev, (union c2wr *) wr);
if (err) {
vq_req_put(c2dev, vq_req);
goto bail1;
}
err = vq_wait_for_reply(c2dev, vq_req);
if (err)
goto bail1;
reply =
(struct c2wr_rnic_setconfig_rep *) (unsigned long) (vq_req->reply_msg);
if (!reply) {
err = -ENOMEM;
goto bail1;
}
err = c2_errno(reply);
vq_repbuf_free(c2dev, reply);
bail1:
kfree(wr);
bail0:
vq_req_free(c2dev, vq_req);
return err;
}
/*
* Delete an IP address from the RNIC interface
*/
int c2_del_addr(struct c2_dev *c2dev, __be32 inaddr, __be32 inmask)
{
struct c2_vq_req *vq_req;
struct c2wr_rnic_setconfig_req *wr;
struct c2wr_rnic_setconfig_rep *reply;
struct c2_netaddr netaddr;
int err, len;
vq_req = vq_req_alloc(c2dev);
if (!vq_req)
return -ENOMEM;
len = sizeof(struct c2_netaddr);
wr = kmalloc(c2dev->req_vq.msg_size, GFP_KERNEL);
if (!wr) {
err = -ENOMEM;
goto bail0;
}
c2_wr_set_id(wr, CCWR_RNIC_SETCONFIG);
wr->hdr.context = (unsigned long) vq_req;
wr->rnic_handle = c2dev->adapter_handle;
wr->option = cpu_to_be32(C2_CFG_DEL_ADDR);
netaddr.ip_addr = inaddr;
netaddr.netmask = inmask;
netaddr.mtu = 0;
memcpy(wr->data, &netaddr, len);
vq_req_get(c2dev, vq_req);
err = vq_send_wr(c2dev, (union c2wr *) wr);
if (err) {
vq_req_put(c2dev, vq_req);
goto bail1;
}
err = vq_wait_for_reply(c2dev, vq_req);
if (err)
goto bail1;
reply =
(struct c2wr_rnic_setconfig_rep *) (unsigned long) (vq_req->reply_msg);
if (!reply) {
err = -ENOMEM;
goto bail1;
}
err = c2_errno(reply);
vq_repbuf_free(c2dev, reply);
bail1:
kfree(wr);
bail0:
vq_req_free(c2dev, vq_req);
return err;
}
/*
* Open a single RNIC instance to use with all
* low level openib calls
*/
static int c2_rnic_open(struct c2_dev *c2dev)
{
struct c2_vq_req *vq_req;
union c2wr wr;
struct c2wr_rnic_open_rep *reply;
int err;
vq_req = vq_req_alloc(c2dev);
if (vq_req == NULL) {
return -ENOMEM;
}
memset(&wr, 0, sizeof(wr));
c2_wr_set_id(&wr, CCWR_RNIC_OPEN);
wr.rnic_open.req.hdr.context = (unsigned long) (vq_req);
wr.rnic_open.req.flags = cpu_to_be16(RNIC_PRIV_MODE);
wr.rnic_open.req.port_num = cpu_to_be16(0);
wr.rnic_open.req.user_context = (unsigned long) c2dev;
vq_req_get(c2dev, vq_req);
err = vq_send_wr(c2dev, &wr);
if (err) {
vq_req_put(c2dev, vq_req);
goto bail0;
}
err = vq_wait_for_reply(c2dev, vq_req);
if (err) {
goto bail0;
}
reply = (struct c2wr_rnic_open_rep *) (unsigned long) (vq_req->reply_msg);
if (!reply) {
err = -ENOMEM;
goto bail0;
}
if ((err = c2_errno(reply)) != 0) {
goto bail1;
}
c2dev->adapter_handle = reply->rnic_handle;
bail1:
vq_repbuf_free(c2dev, reply);
bail0:
vq_req_free(c2dev, vq_req);
return err;
}
/*
* Close the RNIC instance
*/
static int c2_rnic_close(struct c2_dev *c2dev)
{
struct c2_vq_req *vq_req;
union c2wr wr;
struct c2wr_rnic_close_rep *reply;
int err;
vq_req = vq_req_alloc(c2dev);
if (vq_req == NULL) {
return -ENOMEM;
}
memset(&wr, 0, sizeof(wr));
c2_wr_set_id(&wr, CCWR_RNIC_CLOSE);
wr.rnic_close.req.hdr.context = (unsigned long) vq_req;
wr.rnic_close.req.rnic_handle = c2dev->adapter_handle;
vq_req_get(c2dev, vq_req);
err = vq_send_wr(c2dev, &wr);
if (err) {
vq_req_put(c2dev, vq_req);
goto bail0;
}
err = vq_wait_for_reply(c2dev, vq_req);
if (err) {
goto bail0;
}
reply = (struct c2wr_rnic_close_rep *) (unsigned long) (vq_req->reply_msg);
if (!reply) {
err = -ENOMEM;
goto bail0;
}
if ((err = c2_errno(reply)) != 0) {
goto bail1;
}
c2dev->adapter_handle = 0;
bail1:
vq_repbuf_free(c2dev, reply);
bail0:
vq_req_free(c2dev, vq_req);
return err;
}
/*
* Called by c2_probe to initialize the RNIC. This principally
* involves initalizing the various limits and resouce pools that
* comprise the RNIC instance.
*/
int __devinit c2_rnic_init(struct c2_dev *c2dev)
{
int err;
u32 qsize, msgsize;
void *q1_pages;
void *q2_pages;
void __iomem *mmio_regs;
/* Device capabilities */
c2dev->device_cap_flags =
(IB_DEVICE_RESIZE_MAX_WR |
IB_DEVICE_CURR_QP_STATE_MOD |
IB_DEVICE_SYS_IMAGE_GUID |
IB_DEVICE_LOCAL_DMA_LKEY |
IB_DEVICE_MEM_WINDOW);
/* Allocate the qptr_array */
c2dev->qptr_array = vmalloc(C2_MAX_CQS * sizeof(void *));
if (!c2dev->qptr_array) {
return -ENOMEM;
}
/* Inialize the qptr_array */
memset(c2dev->qptr_array, 0, C2_MAX_CQS * sizeof(void *));
c2dev->qptr_array[0] = (void *) &c2dev->req_vq;
c2dev->qptr_array[1] = (void *) &c2dev->rep_vq;
c2dev->qptr_array[2] = (void *) &c2dev->aeq;
/* Initialize data structures */
init_waitqueue_head(&c2dev->req_vq_wo);
spin_lock_init(&c2dev->vqlock);
spin_lock_init(&c2dev->lock);
/* Allocate MQ shared pointer pool for kernel clients. User
* mode client pools are hung off the user context
*/
err = c2_init_mqsp_pool(c2dev, GFP_KERNEL, &c2dev->kern_mqsp_pool);
if (err) {
goto bail0;
}
/* Allocate shared pointers for Q0, Q1, and Q2 from
* the shared pointer pool.
*/
c2dev->hint_count = c2_alloc_mqsp(c2dev, c2dev->kern_mqsp_pool,
&c2dev->hint_count_dma,
GFP_KERNEL);
c2dev->req_vq.shared = c2_alloc_mqsp(c2dev, c2dev->kern_mqsp_pool,
&c2dev->req_vq.shared_dma,
GFP_KERNEL);
c2dev->rep_vq.shared = c2_alloc_mqsp(c2dev, c2dev->kern_mqsp_pool,
&c2dev->rep_vq.shared_dma,
GFP_KERNEL);
c2dev->aeq.shared = c2_alloc_mqsp(c2dev, c2dev->kern_mqsp_pool,
&c2dev->aeq.shared_dma, GFP_KERNEL);
if (!c2dev->hint_count || !c2dev->req_vq.shared ||
!c2dev->rep_vq.shared || !c2dev->aeq.shared) {
err = -ENOMEM;
goto bail1;
}
mmio_regs = c2dev->kva;
/* Initialize the Verbs Request Queue */
c2_mq_req_init(&c2dev->req_vq, 0,
be32_to_cpu((__force __be32) readl(mmio_regs + C2_REGS_Q0_QSIZE)),
be32_to_cpu((__force __be32) readl(mmio_regs + C2_REGS_Q0_MSGSIZE)),
mmio_regs +
be32_to_cpu((__force __be32) readl(mmio_regs + C2_REGS_Q0_POOLSTART)),
mmio_regs +
be32_to_cpu((__force __be32) readl(mmio_regs + C2_REGS_Q0_SHARED)),
C2_MQ_ADAPTER_TARGET);
/* Initialize the Verbs Reply Queue */
qsize = be32_to_cpu((__force __be32) readl(mmio_regs + C2_REGS_Q1_QSIZE));
msgsize = be32_to_cpu((__force __be32) readl(mmio_regs + C2_REGS_Q1_MSGSIZE));
q1_pages = dma_alloc_coherent(&c2dev->pcidev->dev, qsize * msgsize,
&c2dev->rep_vq.host_dma, GFP_KERNEL);
if (!q1_pages) {
err = -ENOMEM;
goto bail1;
}
pci_unmap_addr_set(&c2dev->rep_vq, mapping, c2dev->rep_vq.host_dma);
pr_debug("%s rep_vq va %p dma %llx\n", __func__, q1_pages,
(unsigned long long) c2dev->rep_vq.host_dma);
c2_mq_rep_init(&c2dev->rep_vq,
1,
qsize,
msgsize,
q1_pages,
mmio_regs +
be32_to_cpu((__force __be32) readl(mmio_regs + C2_REGS_Q1_SHARED)),
C2_MQ_HOST_TARGET);
/* Initialize the Asynchronus Event Queue */
qsize = be32_to_cpu((__force __be32) readl(mmio_regs + C2_REGS_Q2_QSIZE));
msgsize = be32_to_cpu((__force __be32) readl(mmio_regs + C2_REGS_Q2_MSGSIZE));
q2_pages = dma_alloc_coherent(&c2dev->pcidev->dev, qsize * msgsize,
&c2dev->aeq.host_dma, GFP_KERNEL);
if (!q2_pages) {
err = -ENOMEM;
goto bail2;
}
pci_unmap_addr_set(&c2dev->aeq, mapping, c2dev->aeq.host_dma);
pr_debug("%s aeq va %p dma %llx\n", __func__, q2_pages,
(unsigned long long) c2dev->aeq.host_dma);
c2_mq_rep_init(&c2dev->aeq,
2,
qsize,
msgsize,
q2_pages,
mmio_regs +
be32_to_cpu((__force __be32) readl(mmio_regs + C2_REGS_Q2_SHARED)),
C2_MQ_HOST_TARGET);
/* Initialize the verbs request allocator */
err = vq_init(c2dev);
if (err)
goto bail3;
/* Enable interrupts on the adapter */
writel(0, c2dev->regs + C2_IDIS);
/* create the WR init message */
err = c2_adapter_init(c2dev);
if (err)
goto bail4;
c2dev->init++;
/* open an adapter instance */
err = c2_rnic_open(c2dev);
if (err)
goto bail4;
/* Initialize cached the adapter limits */
if (c2_rnic_query(c2dev, &c2dev->props))
goto bail5;
/* Initialize the PD pool */
err = c2_init_pd_table(c2dev);
if (err)
goto bail5;
/* Initialize the QP pool */
c2_init_qp_table(c2dev);
return 0;
bail5:
c2_rnic_close(c2dev);
bail4:
vq_term(c2dev);
bail3:
dma_free_coherent(&c2dev->pcidev->dev,
c2dev->aeq.q_size * c2dev->aeq.msg_size,
q2_pages, pci_unmap_addr(&c2dev->aeq, mapping));
bail2:
dma_free_coherent(&c2dev->pcidev->dev,
c2dev->rep_vq.q_size * c2dev->rep_vq.msg_size,
q1_pages, pci_unmap_addr(&c2dev->rep_vq, mapping));
bail1:
c2_free_mqsp_pool(c2dev, c2dev->kern_mqsp_pool);
bail0:
vfree(c2dev->qptr_array);
return err;
}
/*
* Called by c2_remove to cleanup the RNIC resources.
*/
void __devexit c2_rnic_term(struct c2_dev *c2dev)
{
/* Close the open adapter instance */
c2_rnic_close(c2dev);
/* Send the TERM message to the adapter */
c2_adapter_term(c2dev);
/* Disable interrupts on the adapter */
writel(1, c2dev->regs + C2_IDIS);
/* Free the QP pool */
c2_cleanup_qp_table(c2dev);
/* Free the PD pool */
c2_cleanup_pd_table(c2dev);
/* Free the verbs request allocator */
vq_term(c2dev);
/* Free the asynchronus event queue */
dma_free_coherent(&c2dev->pcidev->dev,
c2dev->aeq.q_size * c2dev->aeq.msg_size,
c2dev->aeq.msg_pool.host,
pci_unmap_addr(&c2dev->aeq, mapping));
/* Free the verbs reply queue */
dma_free_coherent(&c2dev->pcidev->dev,
c2dev->rep_vq.q_size * c2dev->rep_vq.msg_size,
c2dev->rep_vq.msg_pool.host,
pci_unmap_addr(&c2dev->rep_vq, mapping));
/* Free the MQ shared pointer pool */
c2_free_mqsp_pool(c2dev, c2dev->kern_mqsp_pool);
/* Free the qptr_array */
vfree(c2dev->qptr_array);
return;
}
| gpl-2.0 |
atalax/linux | drivers/mfd/ab8500-sysctrl.c | 757 | 4427 | /*
* Copyright (C) ST-Ericsson SA 2010
* Author: Mattias Nilsson <mattias.i.nilsson@stericsson.com> for ST Ericsson.
* License terms: GNU General Public License (GPL) version 2
*/
#include <linux/err.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/pm.h>
#include <linux/reboot.h>
#include <linux/signal.h>
#include <linux/power_supply.h>
#include <linux/mfd/abx500.h>
#include <linux/mfd/abx500/ab8500.h>
#include <linux/mfd/abx500/ab8500-sysctrl.h>
/* RtcCtrl bits */
#define AB8500_ALARM_MIN_LOW 0x08
#define AB8500_ALARM_MIN_MID 0x09
#define RTC_CTRL 0x0B
#define RTC_ALARM_ENABLE 0x4
static struct device *sysctrl_dev;
static void ab8500_power_off(void)
{
sigset_t old;
sigset_t all;
static char *pss[] = {"ab8500_ac", "pm2301", "ab8500_usb"};
int i;
bool charger_present = false;
union power_supply_propval val;
struct power_supply *psy;
int ret;
if (sysctrl_dev == NULL) {
pr_err("%s: sysctrl not initialized\n", __func__);
return;
}
/*
* If we have a charger connected and we're powering off,
* reboot into charge-only mode.
*/
for (i = 0; i < ARRAY_SIZE(pss); i++) {
psy = power_supply_get_by_name(pss[i]);
if (!psy)
continue;
ret = power_supply_get_property(psy, POWER_SUPPLY_PROP_ONLINE,
&val);
power_supply_put(psy);
if (!ret && val.intval) {
charger_present = true;
break;
}
}
if (!charger_present)
goto shutdown;
/* Check if battery is known */
psy = power_supply_get_by_name("ab8500_btemp");
if (psy) {
ret = power_supply_get_property(psy,
POWER_SUPPLY_PROP_TECHNOLOGY, &val);
if (!ret && val.intval != POWER_SUPPLY_TECHNOLOGY_UNKNOWN) {
printk(KERN_INFO
"Charger \"%s\" is connected with known battery."
" Rebooting.\n",
pss[i]);
machine_restart("charging");
}
power_supply_put(psy);
}
shutdown:
sigfillset(&all);
if (!sigprocmask(SIG_BLOCK, &all, &old)) {
(void)ab8500_sysctrl_set(AB8500_STW4500CTRL1,
AB8500_STW4500CTRL1_SWOFF |
AB8500_STW4500CTRL1_SWRESET4500N);
(void)sigprocmask(SIG_SETMASK, &old, NULL);
}
}
static inline bool valid_bank(u8 bank)
{
return ((bank == AB8500_SYS_CTRL1_BLOCK) ||
(bank == AB8500_SYS_CTRL2_BLOCK));
}
int ab8500_sysctrl_read(u16 reg, u8 *value)
{
u8 bank;
if (sysctrl_dev == NULL)
return -EINVAL;
bank = (reg >> 8);
if (!valid_bank(bank))
return -EINVAL;
return abx500_get_register_interruptible(sysctrl_dev, bank,
(u8)(reg & 0xFF), value);
}
EXPORT_SYMBOL(ab8500_sysctrl_read);
int ab8500_sysctrl_write(u16 reg, u8 mask, u8 value)
{
u8 bank;
if (sysctrl_dev == NULL)
return -EINVAL;
bank = (reg >> 8);
if (!valid_bank(bank))
return -EINVAL;
return abx500_mask_and_set_register_interruptible(sysctrl_dev, bank,
(u8)(reg & 0xFF), mask, value);
}
EXPORT_SYMBOL(ab8500_sysctrl_write);
static int ab8500_sysctrl_probe(struct platform_device *pdev)
{
struct ab8500 *ab8500 = dev_get_drvdata(pdev->dev.parent);
struct ab8500_platform_data *plat;
struct ab8500_sysctrl_platform_data *pdata;
plat = dev_get_platdata(pdev->dev.parent);
if (!plat)
return -EINVAL;
sysctrl_dev = &pdev->dev;
if (!pm_power_off)
pm_power_off = ab8500_power_off;
pdata = plat->sysctrl;
if (pdata) {
int last, ret, i, j;
if (is_ab8505(ab8500))
last = AB8500_SYSCLKREQ4RFCLKBUF;
else
last = AB8500_SYSCLKREQ8RFCLKBUF;
for (i = AB8500_SYSCLKREQ1RFCLKBUF; i <= last; i++) {
j = i - AB8500_SYSCLKREQ1RFCLKBUF;
ret = ab8500_sysctrl_write(i, 0xff,
pdata->initial_req_buf_config[j]);
dev_dbg(&pdev->dev,
"Setting SysClkReq%dRfClkBuf 0x%X\n",
j + 1,
pdata->initial_req_buf_config[j]);
if (ret < 0) {
dev_err(&pdev->dev,
"unable to set sysClkReq%dRfClkBuf: "
"%d\n", j + 1, ret);
}
}
}
return 0;
}
static int ab8500_sysctrl_remove(struct platform_device *pdev)
{
sysctrl_dev = NULL;
if (pm_power_off == ab8500_power_off)
pm_power_off = NULL;
return 0;
}
static struct platform_driver ab8500_sysctrl_driver = {
.driver = {
.name = "ab8500-sysctrl",
},
.probe = ab8500_sysctrl_probe,
.remove = ab8500_sysctrl_remove,
};
static int __init ab8500_sysctrl_init(void)
{
return platform_driver_register(&ab8500_sysctrl_driver);
}
arch_initcall(ab8500_sysctrl_init);
MODULE_AUTHOR("Mattias Nilsson <mattias.i.nilsson@stericsson.com");
MODULE_DESCRIPTION("AB8500 system control driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
Megatron007/Megabyte_kernel_victara | net/netfilter/nf_conntrack_expect.c | 1269 | 17019 | /* Expectation handling for nf_conntrack. */
/* (C) 1999-2001 Paul `Rusty' Russell
* (C) 2002-2006 Netfilter Core Team <coreteam@netfilter.org>
* (C) 2003,2004 USAGI/WIDE Project <http://www.linux-ipv6.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/types.h>
#include <linux/netfilter.h>
#include <linux/skbuff.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/stddef.h>
#include <linux/slab.h>
#include <linux/err.h>
#include <linux/percpu.h>
#include <linux/kernel.h>
#include <linux/jhash.h>
#include <linux/moduleparam.h>
#include <linux/export.h>
#include <net/net_namespace.h>
#include <net/netfilter/nf_conntrack.h>
#include <net/netfilter/nf_conntrack_core.h>
#include <net/netfilter/nf_conntrack_expect.h>
#include <net/netfilter/nf_conntrack_helper.h>
#include <net/netfilter/nf_conntrack_tuple.h>
#include <net/netfilter/nf_conntrack_zones.h>
unsigned int nf_ct_expect_hsize __read_mostly;
EXPORT_SYMBOL_GPL(nf_ct_expect_hsize);
unsigned int nf_ct_expect_max __read_mostly;
static struct kmem_cache *nf_ct_expect_cachep __read_mostly;
/* nf_conntrack_expect helper functions */
void nf_ct_unlink_expect_report(struct nf_conntrack_expect *exp,
u32 pid, int report)
{
struct nf_conn_help *master_help = nfct_help(exp->master);
struct net *net = nf_ct_exp_net(exp);
NF_CT_ASSERT(master_help);
NF_CT_ASSERT(!timer_pending(&exp->timeout));
hlist_del_rcu(&exp->hnode);
net->ct.expect_count--;
hlist_del(&exp->lnode);
master_help->expecting[exp->class]--;
nf_ct_expect_event_report(IPEXP_DESTROY, exp, pid, report);
nf_ct_expect_put(exp);
NF_CT_STAT_INC(net, expect_delete);
}
EXPORT_SYMBOL_GPL(nf_ct_unlink_expect_report);
static void nf_ct_expectation_timed_out(unsigned long ul_expect)
{
struct nf_conntrack_expect *exp = (void *)ul_expect;
spin_lock_bh(&nf_conntrack_lock);
nf_ct_unlink_expect(exp);
spin_unlock_bh(&nf_conntrack_lock);
nf_ct_expect_put(exp);
}
static unsigned int nf_ct_expect_dst_hash(const struct nf_conntrack_tuple *tuple)
{
unsigned int hash;
if (unlikely(!nf_conntrack_hash_rnd)) {
init_nf_conntrack_hash_rnd();
}
hash = jhash2(tuple->dst.u3.all, ARRAY_SIZE(tuple->dst.u3.all),
(((tuple->dst.protonum ^ tuple->src.l3num) << 16) |
(__force __u16)tuple->dst.u.all) ^ nf_conntrack_hash_rnd);
return ((u64)hash * nf_ct_expect_hsize) >> 32;
}
struct nf_conntrack_expect *
__nf_ct_expect_find(struct net *net, u16 zone,
const struct nf_conntrack_tuple *tuple)
{
struct nf_conntrack_expect *i;
struct hlist_node *n;
unsigned int h;
if (!net->ct.expect_count)
return NULL;
h = nf_ct_expect_dst_hash(tuple);
hlist_for_each_entry_rcu(i, n, &net->ct.expect_hash[h], hnode) {
if (nf_ct_tuple_mask_cmp(tuple, &i->tuple, &i->mask) &&
nf_ct_zone(i->master) == zone)
return i;
}
return NULL;
}
EXPORT_SYMBOL_GPL(__nf_ct_expect_find);
/* Just find a expectation corresponding to a tuple. */
struct nf_conntrack_expect *
nf_ct_expect_find_get(struct net *net, u16 zone,
const struct nf_conntrack_tuple *tuple)
{
struct nf_conntrack_expect *i;
rcu_read_lock();
i = __nf_ct_expect_find(net, zone, tuple);
if (i && !atomic_inc_not_zero(&i->use))
i = NULL;
rcu_read_unlock();
return i;
}
EXPORT_SYMBOL_GPL(nf_ct_expect_find_get);
/* If an expectation for this connection is found, it gets delete from
* global list then returned. */
struct nf_conntrack_expect *
nf_ct_find_expectation(struct net *net, u16 zone,
const struct nf_conntrack_tuple *tuple)
{
struct nf_conntrack_expect *i, *exp = NULL;
struct hlist_node *n;
unsigned int h;
if (!net->ct.expect_count)
return NULL;
h = nf_ct_expect_dst_hash(tuple);
hlist_for_each_entry(i, n, &net->ct.expect_hash[h], hnode) {
if (!(i->flags & NF_CT_EXPECT_INACTIVE) &&
nf_ct_tuple_mask_cmp(tuple, &i->tuple, &i->mask) &&
nf_ct_zone(i->master) == zone) {
exp = i;
break;
}
}
if (!exp)
return NULL;
/* If master is not in hash table yet (ie. packet hasn't left
this machine yet), how can other end know about expected?
Hence these are not the droids you are looking for (if
master ct never got confirmed, we'd hold a reference to it
and weird things would happen to future packets). */
if (!nf_ct_is_confirmed(exp->master))
return NULL;
if (exp->flags & NF_CT_EXPECT_PERMANENT) {
atomic_inc(&exp->use);
return exp;
} else if (del_timer(&exp->timeout)) {
nf_ct_unlink_expect(exp);
return exp;
}
return NULL;
}
/* delete all expectations for this conntrack */
void nf_ct_remove_expectations(struct nf_conn *ct)
{
struct nf_conn_help *help = nfct_help(ct);
struct nf_conntrack_expect *exp;
struct hlist_node *n, *next;
/* Optimization: most connection never expect any others. */
if (!help)
return;
hlist_for_each_entry_safe(exp, n, next, &help->expectations, lnode) {
if (del_timer(&exp->timeout)) {
nf_ct_unlink_expect(exp);
nf_ct_expect_put(exp);
}
}
}
EXPORT_SYMBOL_GPL(nf_ct_remove_expectations);
/* Would two expected things clash? */
static inline int expect_clash(const struct nf_conntrack_expect *a,
const struct nf_conntrack_expect *b)
{
/* Part covered by intersection of masks must be unequal,
otherwise they clash */
struct nf_conntrack_tuple_mask intersect_mask;
int count;
intersect_mask.src.u.all = a->mask.src.u.all & b->mask.src.u.all;
for (count = 0; count < NF_CT_TUPLE_L3SIZE; count++){
intersect_mask.src.u3.all[count] =
a->mask.src.u3.all[count] & b->mask.src.u3.all[count];
}
return nf_ct_tuple_mask_cmp(&a->tuple, &b->tuple, &intersect_mask);
}
static inline int expect_matches(const struct nf_conntrack_expect *a,
const struct nf_conntrack_expect *b)
{
return a->master == b->master && a->class == b->class &&
nf_ct_tuple_equal(&a->tuple, &b->tuple) &&
nf_ct_tuple_mask_equal(&a->mask, &b->mask) &&
nf_ct_zone(a->master) == nf_ct_zone(b->master);
}
/* Generally a bad idea to call this: could have matched already. */
void nf_ct_unexpect_related(struct nf_conntrack_expect *exp)
{
spin_lock_bh(&nf_conntrack_lock);
if (del_timer(&exp->timeout)) {
nf_ct_unlink_expect(exp);
nf_ct_expect_put(exp);
}
spin_unlock_bh(&nf_conntrack_lock);
}
EXPORT_SYMBOL_GPL(nf_ct_unexpect_related);
/* We don't increase the master conntrack refcount for non-fulfilled
* conntracks. During the conntrack destruction, the expectations are
* always killed before the conntrack itself */
struct nf_conntrack_expect *nf_ct_expect_alloc(struct nf_conn *me)
{
struct nf_conntrack_expect *new;
new = kmem_cache_alloc(nf_ct_expect_cachep, GFP_ATOMIC);
if (!new)
return NULL;
new->master = me;
atomic_set(&new->use, 1);
return new;
}
EXPORT_SYMBOL_GPL(nf_ct_expect_alloc);
void nf_ct_expect_init(struct nf_conntrack_expect *exp, unsigned int class,
u_int8_t family,
const union nf_inet_addr *saddr,
const union nf_inet_addr *daddr,
u_int8_t proto, const __be16 *src, const __be16 *dst)
{
int len;
if (family == AF_INET)
len = 4;
else
len = 16;
exp->flags = 0;
exp->class = class;
exp->expectfn = NULL;
exp->helper = NULL;
exp->tuple.src.l3num = family;
exp->tuple.dst.protonum = proto;
if (saddr) {
memcpy(&exp->tuple.src.u3, saddr, len);
if (sizeof(exp->tuple.src.u3) > len)
/* address needs to be cleared for nf_ct_tuple_equal */
memset((void *)&exp->tuple.src.u3 + len, 0x00,
sizeof(exp->tuple.src.u3) - len);
memset(&exp->mask.src.u3, 0xFF, len);
if (sizeof(exp->mask.src.u3) > len)
memset((void *)&exp->mask.src.u3 + len, 0x00,
sizeof(exp->mask.src.u3) - len);
} else {
memset(&exp->tuple.src.u3, 0x00, sizeof(exp->tuple.src.u3));
memset(&exp->mask.src.u3, 0x00, sizeof(exp->mask.src.u3));
}
if (src) {
exp->tuple.src.u.all = *src;
exp->mask.src.u.all = htons(0xFFFF);
} else {
exp->tuple.src.u.all = 0;
exp->mask.src.u.all = 0;
}
memcpy(&exp->tuple.dst.u3, daddr, len);
if (sizeof(exp->tuple.dst.u3) > len)
/* address needs to be cleared for nf_ct_tuple_equal */
memset((void *)&exp->tuple.dst.u3 + len, 0x00,
sizeof(exp->tuple.dst.u3) - len);
exp->tuple.dst.u.all = *dst;
}
EXPORT_SYMBOL_GPL(nf_ct_expect_init);
static void nf_ct_expect_free_rcu(struct rcu_head *head)
{
struct nf_conntrack_expect *exp;
exp = container_of(head, struct nf_conntrack_expect, rcu);
kmem_cache_free(nf_ct_expect_cachep, exp);
}
void nf_ct_expect_put(struct nf_conntrack_expect *exp)
{
if (atomic_dec_and_test(&exp->use))
call_rcu(&exp->rcu, nf_ct_expect_free_rcu);
}
EXPORT_SYMBOL_GPL(nf_ct_expect_put);
static int nf_ct_expect_insert(struct nf_conntrack_expect *exp)
{
struct nf_conn_help *master_help = nfct_help(exp->master);
struct nf_conntrack_helper *helper;
struct net *net = nf_ct_exp_net(exp);
unsigned int h = nf_ct_expect_dst_hash(&exp->tuple);
/* two references : one for hash insert, one for the timer */
atomic_add(2, &exp->use);
hlist_add_head(&exp->lnode, &master_help->expectations);
master_help->expecting[exp->class]++;
hlist_add_head_rcu(&exp->hnode, &net->ct.expect_hash[h]);
net->ct.expect_count++;
setup_timer(&exp->timeout, nf_ct_expectation_timed_out,
(unsigned long)exp);
helper = rcu_dereference_protected(master_help->helper,
lockdep_is_held(&nf_conntrack_lock));
if (helper) {
exp->timeout.expires = jiffies +
helper->expect_policy[exp->class].timeout * HZ;
}
add_timer(&exp->timeout);
NF_CT_STAT_INC(net, expect_create);
return 0;
}
/* Race with expectations being used means we could have none to find; OK. */
static void evict_oldest_expect(struct nf_conn *master,
struct nf_conntrack_expect *new)
{
struct nf_conn_help *master_help = nfct_help(master);
struct nf_conntrack_expect *exp, *last = NULL;
struct hlist_node *n;
hlist_for_each_entry(exp, n, &master_help->expectations, lnode) {
if (exp->class == new->class)
last = exp;
}
if (last && del_timer(&last->timeout)) {
nf_ct_unlink_expect(last);
nf_ct_expect_put(last);
}
}
static inline int __nf_ct_expect_check(struct nf_conntrack_expect *expect)
{
const struct nf_conntrack_expect_policy *p;
struct nf_conntrack_expect *i;
struct nf_conn *master = expect->master;
struct nf_conn_help *master_help = nfct_help(master);
struct nf_conntrack_helper *helper;
struct net *net = nf_ct_exp_net(expect);
struct hlist_node *n, *next;
unsigned int h;
int ret = 1;
if (!master_help) {
ret = -ESHUTDOWN;
goto out;
}
h = nf_ct_expect_dst_hash(&expect->tuple);
hlist_for_each_entry_safe(i, n, next, &net->ct.expect_hash[h], hnode) {
if (expect_matches(i, expect)) {
if (del_timer(&i->timeout)) {
nf_ct_unlink_expect(i);
nf_ct_expect_put(i);
break;
}
} else if (expect_clash(i, expect)) {
ret = -EBUSY;
goto out;
}
}
/* Will be over limit? */
helper = rcu_dereference_protected(master_help->helper,
lockdep_is_held(&nf_conntrack_lock));
if (helper) {
p = &helper->expect_policy[expect->class];
if (p->max_expected &&
master_help->expecting[expect->class] >= p->max_expected) {
evict_oldest_expect(master, expect);
if (master_help->expecting[expect->class]
>= p->max_expected) {
ret = -EMFILE;
goto out;
}
}
}
if (net->ct.expect_count >= nf_ct_expect_max) {
if (net_ratelimit())
printk(KERN_WARNING
"nf_conntrack: expectation table full\n");
ret = -EMFILE;
}
out:
return ret;
}
int nf_ct_expect_related_report(struct nf_conntrack_expect *expect,
u32 pid, int report)
{
int ret;
spin_lock_bh(&nf_conntrack_lock);
ret = __nf_ct_expect_check(expect);
if (ret <= 0)
goto out;
ret = nf_ct_expect_insert(expect);
if (ret < 0)
goto out;
spin_unlock_bh(&nf_conntrack_lock);
nf_ct_expect_event_report(IPEXP_NEW, expect, pid, report);
return ret;
out:
spin_unlock_bh(&nf_conntrack_lock);
return ret;
}
EXPORT_SYMBOL_GPL(nf_ct_expect_related_report);
#ifdef CONFIG_NF_CONNTRACK_PROCFS
struct ct_expect_iter_state {
struct seq_net_private p;
unsigned int bucket;
};
static struct hlist_node *ct_expect_get_first(struct seq_file *seq)
{
struct net *net = seq_file_net(seq);
struct ct_expect_iter_state *st = seq->private;
struct hlist_node *n;
for (st->bucket = 0; st->bucket < nf_ct_expect_hsize; st->bucket++) {
n = rcu_dereference(hlist_first_rcu(&net->ct.expect_hash[st->bucket]));
if (n)
return n;
}
return NULL;
}
static struct hlist_node *ct_expect_get_next(struct seq_file *seq,
struct hlist_node *head)
{
struct net *net = seq_file_net(seq);
struct ct_expect_iter_state *st = seq->private;
head = rcu_dereference(hlist_next_rcu(head));
while (head == NULL) {
if (++st->bucket >= nf_ct_expect_hsize)
return NULL;
head = rcu_dereference(hlist_first_rcu(&net->ct.expect_hash[st->bucket]));
}
return head;
}
static struct hlist_node *ct_expect_get_idx(struct seq_file *seq, loff_t pos)
{
struct hlist_node *head = ct_expect_get_first(seq);
if (head)
while (pos && (head = ct_expect_get_next(seq, head)))
pos--;
return pos ? NULL : head;
}
static void *exp_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(RCU)
{
rcu_read_lock();
return ct_expect_get_idx(seq, *pos);
}
static void *exp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
(*pos)++;
return ct_expect_get_next(seq, v);
}
static void exp_seq_stop(struct seq_file *seq, void *v)
__releases(RCU)
{
rcu_read_unlock();
}
static int exp_seq_show(struct seq_file *s, void *v)
{
struct nf_conntrack_expect *expect;
struct nf_conntrack_helper *helper;
struct hlist_node *n = v;
char *delim = "";
expect = hlist_entry(n, struct nf_conntrack_expect, hnode);
if (expect->timeout.function)
seq_printf(s, "%ld ", timer_pending(&expect->timeout)
? (long)(expect->timeout.expires - jiffies)/HZ : 0);
else
seq_printf(s, "- ");
seq_printf(s, "l3proto = %u proto=%u ",
expect->tuple.src.l3num,
expect->tuple.dst.protonum);
print_tuple(s, &expect->tuple,
__nf_ct_l3proto_find(expect->tuple.src.l3num),
__nf_ct_l4proto_find(expect->tuple.src.l3num,
expect->tuple.dst.protonum));
if (expect->flags & NF_CT_EXPECT_PERMANENT) {
seq_printf(s, "PERMANENT");
delim = ",";
}
if (expect->flags & NF_CT_EXPECT_INACTIVE) {
seq_printf(s, "%sINACTIVE", delim);
delim = ",";
}
if (expect->flags & NF_CT_EXPECT_USERSPACE)
seq_printf(s, "%sUSERSPACE", delim);
helper = rcu_dereference(nfct_help(expect->master)->helper);
if (helper) {
seq_printf(s, "%s%s", expect->flags ? " " : "", helper->name);
if (helper->expect_policy[expect->class].name)
seq_printf(s, "/%s",
helper->expect_policy[expect->class].name);
}
return seq_putc(s, '\n');
}
static const struct seq_operations exp_seq_ops = {
.start = exp_seq_start,
.next = exp_seq_next,
.stop = exp_seq_stop,
.show = exp_seq_show
};
static int exp_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &exp_seq_ops,
sizeof(struct ct_expect_iter_state));
}
static const struct file_operations exp_file_ops = {
.owner = THIS_MODULE,
.open = exp_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
#endif /* CONFIG_NF_CONNTRACK_PROCFS */
static int exp_proc_init(struct net *net)
{
#ifdef CONFIG_NF_CONNTRACK_PROCFS
struct proc_dir_entry *proc;
proc = proc_net_fops_create(net, "nf_conntrack_expect", 0440, &exp_file_ops);
if (!proc)
return -ENOMEM;
#endif /* CONFIG_NF_CONNTRACK_PROCFS */
return 0;
}
static void exp_proc_remove(struct net *net)
{
#ifdef CONFIG_NF_CONNTRACK_PROCFS
proc_net_remove(net, "nf_conntrack_expect");
#endif /* CONFIG_NF_CONNTRACK_PROCFS */
}
module_param_named(expect_hashsize, nf_ct_expect_hsize, uint, 0400);
int nf_conntrack_expect_init(struct net *net)
{
int err = -ENOMEM;
if (net_eq(net, &init_net)) {
if (!nf_ct_expect_hsize) {
nf_ct_expect_hsize = net->ct.htable_size / 256;
if (!nf_ct_expect_hsize)
nf_ct_expect_hsize = 1;
}
nf_ct_expect_max = nf_ct_expect_hsize * 4;
}
net->ct.expect_count = 0;
net->ct.expect_hash = nf_ct_alloc_hashtable(&nf_ct_expect_hsize, 0);
if (net->ct.expect_hash == NULL)
goto err1;
if (net_eq(net, &init_net)) {
nf_ct_expect_cachep = kmem_cache_create("nf_conntrack_expect",
sizeof(struct nf_conntrack_expect),
0, 0, NULL);
if (!nf_ct_expect_cachep)
goto err2;
}
err = exp_proc_init(net);
if (err < 0)
goto err3;
return 0;
err3:
if (net_eq(net, &init_net))
kmem_cache_destroy(nf_ct_expect_cachep);
err2:
nf_ct_free_hashtable(net->ct.expect_hash, nf_ct_expect_hsize);
err1:
return err;
}
void nf_conntrack_expect_fini(struct net *net)
{
exp_proc_remove(net);
if (net_eq(net, &init_net)) {
rcu_barrier(); /* Wait for call_rcu() before destroy */
kmem_cache_destroy(nf_ct_expect_cachep);
}
nf_ct_free_hashtable(net->ct.expect_hash, nf_ct_expect_hsize);
}
| gpl-2.0 |
todorez/galileo-linux-stable | drivers/hwmon/sis5595.c | 1269 | 25873 | /*
* sis5595.c - Part of lm_sensors, Linux kernel modules
* for hardware monitoring
*
* Copyright (C) 1998 - 2001 Frodo Looijaard <frodol@dds.nl>,
* Kyösti Mälkki <kmalkki@cc.hut.fi>, and
* Mark D. Studebaker <mdsxyz123@yahoo.com>
* Ported to Linux 2.6 by Aurelien Jarno <aurelien@aurel32.net> with
* the help of Jean Delvare <jdelvare@suse.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* SiS southbridge has a LM78-like chip integrated on the same IC.
* This driver is a customized copy of lm78.c
*
* Supports following revisions:
* Version PCI ID PCI Revision
* 1 1039/0008 AF or less
* 2 1039/0008 B0 or greater
*
* Note: these chips contain a 0008 device which is incompatible with the
* 5595. We recognize these by the presence of the listed
* "blacklist" PCI ID and refuse to load.
*
* NOT SUPPORTED PCI ID BLACKLIST PCI ID
* 540 0008 0540
* 550 0008 0550
* 5513 0008 5511
* 5581 0008 5597
* 5582 0008 5597
* 5597 0008 5597
* 5598 0008 5597/5598
* 630 0008 0630
* 645 0008 0645
* 730 0008 0730
* 735 0008 0735
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/ioport.h>
#include <linux/pci.h>
#include <linux/platform_device.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/jiffies.h>
#include <linux/mutex.h>
#include <linux/sysfs.h>
#include <linux/acpi.h>
#include <linux/io.h>
/*
* If force_addr is set to anything different from 0, we forcibly enable
* the device at the given address.
*/
static u16 force_addr;
module_param(force_addr, ushort, 0);
MODULE_PARM_DESC(force_addr,
"Initialize the base address of the sensors");
static struct platform_device *pdev;
/* Many SIS5595 constants specified below */
/* Length of ISA address segment */
#define SIS5595_EXTENT 8
/* PCI Config Registers */
#define SIS5595_BASE_REG 0x68
#define SIS5595_PIN_REG 0x7A
#define SIS5595_ENABLE_REG 0x7B
/* Where are the ISA address/data registers relative to the base address */
#define SIS5595_ADDR_REG_OFFSET 5
#define SIS5595_DATA_REG_OFFSET 6
/* The SIS5595 registers */
#define SIS5595_REG_IN_MAX(nr) (0x2b + (nr) * 2)
#define SIS5595_REG_IN_MIN(nr) (0x2c + (nr) * 2)
#define SIS5595_REG_IN(nr) (0x20 + (nr))
#define SIS5595_REG_FAN_MIN(nr) (0x3b + (nr))
#define SIS5595_REG_FAN(nr) (0x28 + (nr))
/*
* On the first version of the chip, the temp registers are separate.
* On the second version,
* TEMP pin is shared with IN4, configured in PCI register 0x7A.
* The registers are the same as well.
* OVER and HYST are really MAX and MIN.
*/
#define REV2MIN 0xb0
#define SIS5595_REG_TEMP (((data->revision) >= REV2MIN) ? \
SIS5595_REG_IN(4) : 0x27)
#define SIS5595_REG_TEMP_OVER (((data->revision) >= REV2MIN) ? \
SIS5595_REG_IN_MAX(4) : 0x39)
#define SIS5595_REG_TEMP_HYST (((data->revision) >= REV2MIN) ? \
SIS5595_REG_IN_MIN(4) : 0x3a)
#define SIS5595_REG_CONFIG 0x40
#define SIS5595_REG_ALARM1 0x41
#define SIS5595_REG_ALARM2 0x42
#define SIS5595_REG_FANDIV 0x47
/*
* Conversions. Limit checking is only done on the TO_REG
* variants.
*/
/*
* IN: mV, (0V to 4.08V)
* REG: 16mV/bit
*/
static inline u8 IN_TO_REG(unsigned long val)
{
unsigned long nval = clamp_val(val, 0, 4080);
return (nval + 8) / 16;
}
#define IN_FROM_REG(val) ((val) * 16)
static inline u8 FAN_TO_REG(long rpm, int div)
{
if (rpm <= 0)
return 255;
if (rpm > 1350000)
return 1;
return clamp_val((1350000 + rpm * div / 2) / (rpm * div), 1, 254);
}
static inline int FAN_FROM_REG(u8 val, int div)
{
return val == 0 ? -1 : val == 255 ? 0 : 1350000 / (val * div);
}
/*
* TEMP: mC (-54.12C to +157.53C)
* REG: 0.83C/bit + 52.12, two's complement
*/
static inline int TEMP_FROM_REG(s8 val)
{
return val * 830 + 52120;
}
static inline s8 TEMP_TO_REG(long val)
{
int nval = clamp_val(val, -54120, 157530) ;
return nval < 0 ? (nval - 5212 - 415) / 830 : (nval - 5212 + 415) / 830;
}
/*
* FAN DIV: 1, 2, 4, or 8 (defaults to 2)
* REG: 0, 1, 2, or 3 (respectively) (defaults to 1)
*/
static inline u8 DIV_TO_REG(int val)
{
return val == 8 ? 3 : val == 4 ? 2 : val == 1 ? 0 : 1;
}
#define DIV_FROM_REG(val) (1 << (val))
/*
* For each registered chip, we need to keep some data in memory.
* The structure is dynamically allocated.
*/
struct sis5595_data {
unsigned short addr;
const char *name;
struct device *hwmon_dev;
struct mutex lock;
struct mutex update_lock;
char valid; /* !=0 if following fields are valid */
unsigned long last_updated; /* In jiffies */
char maxins; /* == 3 if temp enabled, otherwise == 4 */
u8 revision; /* Reg. value */
u8 in[5]; /* Register value */
u8 in_max[5]; /* Register value */
u8 in_min[5]; /* Register value */
u8 fan[2]; /* Register value */
u8 fan_min[2]; /* Register value */
s8 temp; /* Register value */
s8 temp_over; /* Register value */
s8 temp_hyst; /* Register value */
u8 fan_div[2]; /* Register encoding, shifted right */
u16 alarms; /* Register encoding, combined */
};
static struct pci_dev *s_bridge; /* pointer to the (only) sis5595 */
static int sis5595_probe(struct platform_device *pdev);
static int sis5595_remove(struct platform_device *pdev);
static int sis5595_read_value(struct sis5595_data *data, u8 reg);
static void sis5595_write_value(struct sis5595_data *data, u8 reg, u8 value);
static struct sis5595_data *sis5595_update_device(struct device *dev);
static void sis5595_init_device(struct sis5595_data *data);
static struct platform_driver sis5595_driver = {
.driver = {
.name = "sis5595",
},
.probe = sis5595_probe,
.remove = sis5595_remove,
};
/* 4 Voltages */
static ssize_t show_in(struct device *dev, struct device_attribute *da,
char *buf)
{
struct sis5595_data *data = sis5595_update_device(dev);
struct sensor_device_attribute *attr = to_sensor_dev_attr(da);
int nr = attr->index;
return sprintf(buf, "%d\n", IN_FROM_REG(data->in[nr]));
}
static ssize_t show_in_min(struct device *dev, struct device_attribute *da,
char *buf)
{
struct sis5595_data *data = sis5595_update_device(dev);
struct sensor_device_attribute *attr = to_sensor_dev_attr(da);
int nr = attr->index;
return sprintf(buf, "%d\n", IN_FROM_REG(data->in_min[nr]));
}
static ssize_t show_in_max(struct device *dev, struct device_attribute *da,
char *buf)
{
struct sis5595_data *data = sis5595_update_device(dev);
struct sensor_device_attribute *attr = to_sensor_dev_attr(da);
int nr = attr->index;
return sprintf(buf, "%d\n", IN_FROM_REG(data->in_max[nr]));
}
static ssize_t set_in_min(struct device *dev, struct device_attribute *da,
const char *buf, size_t count)
{
struct sis5595_data *data = dev_get_drvdata(dev);
struct sensor_device_attribute *attr = to_sensor_dev_attr(da);
int nr = attr->index;
unsigned long val;
int err;
err = kstrtoul(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->in_min[nr] = IN_TO_REG(val);
sis5595_write_value(data, SIS5595_REG_IN_MIN(nr), data->in_min[nr]);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t set_in_max(struct device *dev, struct device_attribute *da,
const char *buf, size_t count)
{
struct sis5595_data *data = dev_get_drvdata(dev);
struct sensor_device_attribute *attr = to_sensor_dev_attr(da);
int nr = attr->index;
unsigned long val;
int err;
err = kstrtoul(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->in_max[nr] = IN_TO_REG(val);
sis5595_write_value(data, SIS5595_REG_IN_MAX(nr), data->in_max[nr]);
mutex_unlock(&data->update_lock);
return count;
}
#define show_in_offset(offset) \
static SENSOR_DEVICE_ATTR(in##offset##_input, S_IRUGO, \
show_in, NULL, offset); \
static SENSOR_DEVICE_ATTR(in##offset##_min, S_IRUGO | S_IWUSR, \
show_in_min, set_in_min, offset); \
static SENSOR_DEVICE_ATTR(in##offset##_max, S_IRUGO | S_IWUSR, \
show_in_max, set_in_max, offset);
show_in_offset(0);
show_in_offset(1);
show_in_offset(2);
show_in_offset(3);
show_in_offset(4);
/* Temperature */
static ssize_t show_temp(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct sis5595_data *data = sis5595_update_device(dev);
return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp));
}
static ssize_t show_temp_over(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct sis5595_data *data = sis5595_update_device(dev);
return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp_over));
}
static ssize_t set_temp_over(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct sis5595_data *data = dev_get_drvdata(dev);
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->temp_over = TEMP_TO_REG(val);
sis5595_write_value(data, SIS5595_REG_TEMP_OVER, data->temp_over);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_temp_hyst(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct sis5595_data *data = sis5595_update_device(dev);
return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp_hyst));
}
static ssize_t set_temp_hyst(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct sis5595_data *data = dev_get_drvdata(dev);
long val;
int err;
err = kstrtol(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->temp_hyst = TEMP_TO_REG(val);
sis5595_write_value(data, SIS5595_REG_TEMP_HYST, data->temp_hyst);
mutex_unlock(&data->update_lock);
return count;
}
static DEVICE_ATTR(temp1_input, S_IRUGO, show_temp, NULL);
static DEVICE_ATTR(temp1_max, S_IRUGO | S_IWUSR,
show_temp_over, set_temp_over);
static DEVICE_ATTR(temp1_max_hyst, S_IRUGO | S_IWUSR,
show_temp_hyst, set_temp_hyst);
/* 2 Fans */
static ssize_t show_fan(struct device *dev, struct device_attribute *da,
char *buf)
{
struct sis5595_data *data = sis5595_update_device(dev);
struct sensor_device_attribute *attr = to_sensor_dev_attr(da);
int nr = attr->index;
return sprintf(buf, "%d\n", FAN_FROM_REG(data->fan[nr],
DIV_FROM_REG(data->fan_div[nr])));
}
static ssize_t show_fan_min(struct device *dev, struct device_attribute *da,
char *buf)
{
struct sis5595_data *data = sis5595_update_device(dev);
struct sensor_device_attribute *attr = to_sensor_dev_attr(da);
int nr = attr->index;
return sprintf(buf, "%d\n", FAN_FROM_REG(data->fan_min[nr],
DIV_FROM_REG(data->fan_div[nr])));
}
static ssize_t set_fan_min(struct device *dev, struct device_attribute *da,
const char *buf, size_t count)
{
struct sis5595_data *data = dev_get_drvdata(dev);
struct sensor_device_attribute *attr = to_sensor_dev_attr(da);
int nr = attr->index;
unsigned long val;
int err;
err = kstrtoul(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
data->fan_min[nr] = FAN_TO_REG(val, DIV_FROM_REG(data->fan_div[nr]));
sis5595_write_value(data, SIS5595_REG_FAN_MIN(nr), data->fan_min[nr]);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_fan_div(struct device *dev, struct device_attribute *da,
char *buf)
{
struct sis5595_data *data = sis5595_update_device(dev);
struct sensor_device_attribute *attr = to_sensor_dev_attr(da);
int nr = attr->index;
return sprintf(buf, "%d\n", DIV_FROM_REG(data->fan_div[nr]));
}
/*
* Note: we save and restore the fan minimum here, because its value is
* determined in part by the fan divisor. This follows the principle of
* least surprise; the user doesn't expect the fan minimum to change just
* because the divisor changed.
*/
static ssize_t set_fan_div(struct device *dev, struct device_attribute *da,
const char *buf, size_t count)
{
struct sis5595_data *data = dev_get_drvdata(dev);
struct sensor_device_attribute *attr = to_sensor_dev_attr(da);
int nr = attr->index;
unsigned long min;
int reg;
unsigned long val;
int err;
err = kstrtoul(buf, 10, &val);
if (err)
return err;
mutex_lock(&data->update_lock);
min = FAN_FROM_REG(data->fan_min[nr],
DIV_FROM_REG(data->fan_div[nr]));
reg = sis5595_read_value(data, SIS5595_REG_FANDIV);
switch (val) {
case 1:
data->fan_div[nr] = 0;
break;
case 2:
data->fan_div[nr] = 1;
break;
case 4:
data->fan_div[nr] = 2;
break;
case 8:
data->fan_div[nr] = 3;
break;
default:
dev_err(dev,
"fan_div value %ld not supported. Choose one of 1, 2, 4 or 8!\n",
val);
mutex_unlock(&data->update_lock);
return -EINVAL;
}
switch (nr) {
case 0:
reg = (reg & 0xcf) | (data->fan_div[nr] << 4);
break;
case 1:
reg = (reg & 0x3f) | (data->fan_div[nr] << 6);
break;
}
sis5595_write_value(data, SIS5595_REG_FANDIV, reg);
data->fan_min[nr] =
FAN_TO_REG(min, DIV_FROM_REG(data->fan_div[nr]));
sis5595_write_value(data, SIS5595_REG_FAN_MIN(nr), data->fan_min[nr]);
mutex_unlock(&data->update_lock);
return count;
}
#define show_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);
show_fan_offset(1);
show_fan_offset(2);
/* Alarms */
static ssize_t show_alarms(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct sis5595_data *data = sis5595_update_device(dev);
return sprintf(buf, "%d\n", data->alarms);
}
static DEVICE_ATTR(alarms, S_IRUGO, show_alarms, NULL);
static ssize_t show_alarm(struct device *dev, struct device_attribute *da,
char *buf)
{
struct sis5595_data *data = sis5595_update_device(dev);
int nr = to_sensor_dev_attr(da)->index;
return sprintf(buf, "%u\n", (data->alarms >> nr) & 1);
}
static SENSOR_DEVICE_ATTR(in0_alarm, S_IRUGO, show_alarm, NULL, 0);
static SENSOR_DEVICE_ATTR(in1_alarm, S_IRUGO, show_alarm, NULL, 1);
static SENSOR_DEVICE_ATTR(in2_alarm, S_IRUGO, show_alarm, NULL, 2);
static SENSOR_DEVICE_ATTR(in3_alarm, S_IRUGO, show_alarm, NULL, 3);
static SENSOR_DEVICE_ATTR(in4_alarm, S_IRUGO, show_alarm, NULL, 15);
static SENSOR_DEVICE_ATTR(fan1_alarm, S_IRUGO, show_alarm, NULL, 6);
static SENSOR_DEVICE_ATTR(fan2_alarm, S_IRUGO, show_alarm, NULL, 7);
static SENSOR_DEVICE_ATTR(temp1_alarm, S_IRUGO, show_alarm, NULL, 15);
static ssize_t show_name(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct sis5595_data *data = dev_get_drvdata(dev);
return sprintf(buf, "%s\n", data->name);
}
static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
static struct attribute *sis5595_attributes[] = {
&sensor_dev_attr_in0_input.dev_attr.attr,
&sensor_dev_attr_in0_min.dev_attr.attr,
&sensor_dev_attr_in0_max.dev_attr.attr,
&sensor_dev_attr_in0_alarm.dev_attr.attr,
&sensor_dev_attr_in1_input.dev_attr.attr,
&sensor_dev_attr_in1_min.dev_attr.attr,
&sensor_dev_attr_in1_max.dev_attr.attr,
&sensor_dev_attr_in1_alarm.dev_attr.attr,
&sensor_dev_attr_in2_input.dev_attr.attr,
&sensor_dev_attr_in2_min.dev_attr.attr,
&sensor_dev_attr_in2_max.dev_attr.attr,
&sensor_dev_attr_in2_alarm.dev_attr.attr,
&sensor_dev_attr_in3_input.dev_attr.attr,
&sensor_dev_attr_in3_min.dev_attr.attr,
&sensor_dev_attr_in3_max.dev_attr.attr,
&sensor_dev_attr_in3_alarm.dev_attr.attr,
&sensor_dev_attr_fan1_input.dev_attr.attr,
&sensor_dev_attr_fan1_min.dev_attr.attr,
&sensor_dev_attr_fan1_div.dev_attr.attr,
&sensor_dev_attr_fan1_alarm.dev_attr.attr,
&sensor_dev_attr_fan2_input.dev_attr.attr,
&sensor_dev_attr_fan2_min.dev_attr.attr,
&sensor_dev_attr_fan2_div.dev_attr.attr,
&sensor_dev_attr_fan2_alarm.dev_attr.attr,
&dev_attr_alarms.attr,
&dev_attr_name.attr,
NULL
};
static const struct attribute_group sis5595_group = {
.attrs = sis5595_attributes,
};
static struct attribute *sis5595_attributes_in4[] = {
&sensor_dev_attr_in4_input.dev_attr.attr,
&sensor_dev_attr_in4_min.dev_attr.attr,
&sensor_dev_attr_in4_max.dev_attr.attr,
&sensor_dev_attr_in4_alarm.dev_attr.attr,
NULL
};
static const struct attribute_group sis5595_group_in4 = {
.attrs = sis5595_attributes_in4,
};
static struct attribute *sis5595_attributes_temp1[] = {
&dev_attr_temp1_input.attr,
&dev_attr_temp1_max.attr,
&dev_attr_temp1_max_hyst.attr,
&sensor_dev_attr_temp1_alarm.dev_attr.attr,
NULL
};
static const struct attribute_group sis5595_group_temp1 = {
.attrs = sis5595_attributes_temp1,
};
/* This is called when the module is loaded */
static int sis5595_probe(struct platform_device *pdev)
{
int err = 0;
int i;
struct sis5595_data *data;
struct resource *res;
char val;
/* Reserve the ISA region */
res = platform_get_resource(pdev, IORESOURCE_IO, 0);
if (!devm_request_region(&pdev->dev, res->start, SIS5595_EXTENT,
sis5595_driver.driver.name))
return -EBUSY;
data = devm_kzalloc(&pdev->dev, sizeof(struct sis5595_data),
GFP_KERNEL);
if (!data)
return -ENOMEM;
mutex_init(&data->lock);
mutex_init(&data->update_lock);
data->addr = res->start;
data->name = "sis5595";
platform_set_drvdata(pdev, data);
/*
* Check revision and pin registers to determine whether 4 or 5 voltages
*/
data->revision = s_bridge->revision;
/* 4 voltages, 1 temp */
data->maxins = 3;
if (data->revision >= REV2MIN) {
pci_read_config_byte(s_bridge, SIS5595_PIN_REG, &val);
if (!(val & 0x80))
/* 5 voltages, no temps */
data->maxins = 4;
}
/* Initialize the SIS5595 chip */
sis5595_init_device(data);
/* A few vars need to be filled upon startup */
for (i = 0; i < 2; i++) {
data->fan_min[i] = sis5595_read_value(data,
SIS5595_REG_FAN_MIN(i));
}
/* Register sysfs hooks */
err = sysfs_create_group(&pdev->dev.kobj, &sis5595_group);
if (err)
return err;
if (data->maxins == 4) {
err = sysfs_create_group(&pdev->dev.kobj, &sis5595_group_in4);
if (err)
goto exit_remove_files;
} else {
err = sysfs_create_group(&pdev->dev.kobj, &sis5595_group_temp1);
if (err)
goto exit_remove_files;
}
data->hwmon_dev = hwmon_device_register(&pdev->dev);
if (IS_ERR(data->hwmon_dev)) {
err = PTR_ERR(data->hwmon_dev);
goto exit_remove_files;
}
return 0;
exit_remove_files:
sysfs_remove_group(&pdev->dev.kobj, &sis5595_group);
sysfs_remove_group(&pdev->dev.kobj, &sis5595_group_in4);
sysfs_remove_group(&pdev->dev.kobj, &sis5595_group_temp1);
return err;
}
static int sis5595_remove(struct platform_device *pdev)
{
struct sis5595_data *data = platform_get_drvdata(pdev);
hwmon_device_unregister(data->hwmon_dev);
sysfs_remove_group(&pdev->dev.kobj, &sis5595_group);
sysfs_remove_group(&pdev->dev.kobj, &sis5595_group_in4);
sysfs_remove_group(&pdev->dev.kobj, &sis5595_group_temp1);
return 0;
}
/* ISA access must be locked explicitly. */
static int sis5595_read_value(struct sis5595_data *data, u8 reg)
{
int res;
mutex_lock(&data->lock);
outb_p(reg, data->addr + SIS5595_ADDR_REG_OFFSET);
res = inb_p(data->addr + SIS5595_DATA_REG_OFFSET);
mutex_unlock(&data->lock);
return res;
}
static void sis5595_write_value(struct sis5595_data *data, u8 reg, u8 value)
{
mutex_lock(&data->lock);
outb_p(reg, data->addr + SIS5595_ADDR_REG_OFFSET);
outb_p(value, data->addr + SIS5595_DATA_REG_OFFSET);
mutex_unlock(&data->lock);
}
/* Called when we have found a new SIS5595. */
static void sis5595_init_device(struct sis5595_data *data)
{
u8 config = sis5595_read_value(data, SIS5595_REG_CONFIG);
if (!(config & 0x01))
sis5595_write_value(data, SIS5595_REG_CONFIG,
(config & 0xf7) | 0x01);
}
static struct sis5595_data *sis5595_update_device(struct device *dev)
{
struct sis5595_data *data = dev_get_drvdata(dev);
int i;
mutex_lock(&data->update_lock);
if (time_after(jiffies, data->last_updated + HZ + HZ / 2)
|| !data->valid) {
for (i = 0; i <= data->maxins; i++) {
data->in[i] =
sis5595_read_value(data, SIS5595_REG_IN(i));
data->in_min[i] =
sis5595_read_value(data,
SIS5595_REG_IN_MIN(i));
data->in_max[i] =
sis5595_read_value(data,
SIS5595_REG_IN_MAX(i));
}
for (i = 0; i < 2; i++) {
data->fan[i] =
sis5595_read_value(data, SIS5595_REG_FAN(i));
data->fan_min[i] =
sis5595_read_value(data,
SIS5595_REG_FAN_MIN(i));
}
if (data->maxins == 3) {
data->temp =
sis5595_read_value(data, SIS5595_REG_TEMP);
data->temp_over =
sis5595_read_value(data, SIS5595_REG_TEMP_OVER);
data->temp_hyst =
sis5595_read_value(data, SIS5595_REG_TEMP_HYST);
}
i = sis5595_read_value(data, SIS5595_REG_FANDIV);
data->fan_div[0] = (i >> 4) & 0x03;
data->fan_div[1] = i >> 6;
data->alarms =
sis5595_read_value(data, SIS5595_REG_ALARM1) |
(sis5595_read_value(data, SIS5595_REG_ALARM2) << 8);
data->last_updated = jiffies;
data->valid = 1;
}
mutex_unlock(&data->update_lock);
return data;
}
static const struct pci_device_id sis5595_pci_ids[] = {
{ PCI_DEVICE(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_503) },
{ 0, }
};
MODULE_DEVICE_TABLE(pci, sis5595_pci_ids);
static int blacklist[] = {
PCI_DEVICE_ID_SI_540,
PCI_DEVICE_ID_SI_550,
PCI_DEVICE_ID_SI_630,
PCI_DEVICE_ID_SI_645,
PCI_DEVICE_ID_SI_730,
PCI_DEVICE_ID_SI_735,
PCI_DEVICE_ID_SI_5511, /*
* 5513 chip has the 0008 device but
* that ID shows up in other chips so we
* use the 5511 ID for recognition
*/
PCI_DEVICE_ID_SI_5597,
PCI_DEVICE_ID_SI_5598,
0 };
static int sis5595_device_add(unsigned short address)
{
struct resource res = {
.start = address,
.end = address + SIS5595_EXTENT - 1,
.name = "sis5595",
.flags = IORESOURCE_IO,
};
int err;
err = acpi_check_resource_conflict(&res);
if (err)
goto exit;
pdev = platform_device_alloc("sis5595", address);
if (!pdev) {
err = -ENOMEM;
pr_err("Device allocation failed\n");
goto exit;
}
err = platform_device_add_resources(pdev, &res, 1);
if (err) {
pr_err("Device resource addition failed (%d)\n", err);
goto exit_device_put;
}
err = platform_device_add(pdev);
if (err) {
pr_err("Device addition failed (%d)\n", err);
goto exit_device_put;
}
return 0;
exit_device_put:
platform_device_put(pdev);
exit:
return err;
}
static int sis5595_pci_probe(struct pci_dev *dev,
const struct pci_device_id *id)
{
u16 address;
u8 enable;
int *i;
for (i = blacklist; *i != 0; i++) {
struct pci_dev *d;
d = pci_get_device(PCI_VENDOR_ID_SI, *i, NULL);
if (d) {
dev_err(&d->dev,
"Looked for SIS5595 but found unsupported device %.4x\n",
*i);
pci_dev_put(d);
return -ENODEV;
}
}
force_addr &= ~(SIS5595_EXTENT - 1);
if (force_addr) {
dev_warn(&dev->dev, "Forcing ISA address 0x%x\n", force_addr);
pci_write_config_word(dev, SIS5595_BASE_REG, force_addr);
}
if (PCIBIOS_SUCCESSFUL !=
pci_read_config_word(dev, SIS5595_BASE_REG, &address)) {
dev_err(&dev->dev, "Failed to read ISA address\n");
return -ENODEV;
}
address &= ~(SIS5595_EXTENT - 1);
if (!address) {
dev_err(&dev->dev,
"Base address not set - upgrade BIOS or use force_addr=0xaddr\n");
return -ENODEV;
}
if (force_addr && address != force_addr) {
/* doesn't work for some chips? */
dev_err(&dev->dev, "Failed to force ISA address\n");
return -ENODEV;
}
if (PCIBIOS_SUCCESSFUL !=
pci_read_config_byte(dev, SIS5595_ENABLE_REG, &enable)) {
dev_err(&dev->dev, "Failed to read enable register\n");
return -ENODEV;
}
if (!(enable & 0x80)) {
if ((PCIBIOS_SUCCESSFUL !=
pci_write_config_byte(dev, SIS5595_ENABLE_REG,
enable | 0x80))
|| (PCIBIOS_SUCCESSFUL !=
pci_read_config_byte(dev, SIS5595_ENABLE_REG, &enable))
|| (!(enable & 0x80))) {
/* doesn't work for some chips! */
dev_err(&dev->dev, "Failed to enable HWM device\n");
return -ENODEV;
}
}
if (platform_driver_register(&sis5595_driver)) {
dev_dbg(&dev->dev, "Failed to register sis5595 driver\n");
goto exit;
}
s_bridge = pci_dev_get(dev);
/* Sets global pdev as a side effect */
if (sis5595_device_add(address))
goto exit_unregister;
/*
* Always return failure here. This is to allow other drivers to bind
* to this pci device. We don't really want to have control over the
* pci device, we only wanted to read as few register values from it.
*/
return -ENODEV;
exit_unregister:
pci_dev_put(dev);
platform_driver_unregister(&sis5595_driver);
exit:
return -ENODEV;
}
static struct pci_driver sis5595_pci_driver = {
.name = "sis5595",
.id_table = sis5595_pci_ids,
.probe = sis5595_pci_probe,
};
static int __init sm_sis5595_init(void)
{
return pci_register_driver(&sis5595_pci_driver);
}
static void __exit sm_sis5595_exit(void)
{
pci_unregister_driver(&sis5595_pci_driver);
if (s_bridge != NULL) {
platform_device_unregister(pdev);
platform_driver_unregister(&sis5595_driver);
pci_dev_put(s_bridge);
s_bridge = NULL;
}
}
MODULE_AUTHOR("Aurelien Jarno <aurelien@aurel32.net>");
MODULE_DESCRIPTION("SiS 5595 Sensor device");
MODULE_LICENSE("GPL");
module_init(sm_sis5595_init);
module_exit(sm_sis5595_exit);
| gpl-2.0 |
htc-mirror/ville-ics-crc-3.0.8-ca24d1e | fs/xfs/xfs_rw.c | 2549 | 4655 | /*
* Copyright (c) 2000-2006 Silicon Graphics, Inc.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it would be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "xfs.h"
#include "xfs_fs.h"
#include "xfs_types.h"
#include "xfs_bit.h"
#include "xfs_log.h"
#include "xfs_inum.h"
#include "xfs_trans.h"
#include "xfs_sb.h"
#include "xfs_ag.h"
#include "xfs_mount.h"
#include "xfs_bmap_btree.h"
#include "xfs_dinode.h"
#include "xfs_inode.h"
#include "xfs_error.h"
#include "xfs_rw.h"
/*
* Force a shutdown of the filesystem instantly while keeping
* the filesystem consistent. We don't do an unmount here; just shutdown
* the shop, make sure that absolutely nothing persistent happens to
* this filesystem after this point.
*/
void
xfs_do_force_shutdown(
xfs_mount_t *mp,
int flags,
char *fname,
int lnnum)
{
int logerror;
logerror = flags & SHUTDOWN_LOG_IO_ERROR;
if (!(flags & SHUTDOWN_FORCE_UMOUNT)) {
xfs_notice(mp,
"%s(0x%x) called from line %d of file %s. Return address = 0x%p",
__func__, flags, lnnum, fname, __return_address);
}
/*
* No need to duplicate efforts.
*/
if (XFS_FORCED_SHUTDOWN(mp) && !logerror)
return;
/*
* This flags XFS_MOUNT_FS_SHUTDOWN, makes sure that we don't
* queue up anybody new on the log reservations, and wakes up
* everybody who's sleeping on log reservations to tell them
* the bad news.
*/
if (xfs_log_force_umount(mp, logerror))
return;
if (flags & SHUTDOWN_CORRUPT_INCORE) {
xfs_alert_tag(mp, XFS_PTAG_SHUTDOWN_CORRUPT,
"Corruption of in-memory data detected. Shutting down filesystem");
if (XFS_ERRLEVEL_HIGH <= xfs_error_level)
xfs_stack_trace();
} else if (!(flags & SHUTDOWN_FORCE_UMOUNT)) {
if (logerror) {
xfs_alert_tag(mp, XFS_PTAG_SHUTDOWN_LOGERROR,
"Log I/O Error Detected. Shutting down filesystem");
} else if (flags & SHUTDOWN_DEVICE_REQ) {
xfs_alert_tag(mp, XFS_PTAG_SHUTDOWN_IOERROR,
"All device paths lost. Shutting down filesystem");
} else if (!(flags & SHUTDOWN_REMOTE_REQ)) {
xfs_alert_tag(mp, XFS_PTAG_SHUTDOWN_IOERROR,
"I/O Error Detected. Shutting down filesystem");
}
}
if (!(flags & SHUTDOWN_FORCE_UMOUNT)) {
xfs_alert(mp,
"Please umount the filesystem and rectify the problem(s)");
}
}
/*
* Prints out an ALERT message about I/O error.
*/
void
xfs_ioerror_alert(
char *func,
struct xfs_mount *mp,
xfs_buf_t *bp,
xfs_daddr_t blkno)
{
xfs_alert(mp,
"I/O error occurred: meta-data dev %s block 0x%llx"
" (\"%s\") error %d buf count %zd",
XFS_BUFTARG_NAME(XFS_BUF_TARGET(bp)),
(__uint64_t)blkno, func,
XFS_BUF_GETERROR(bp), XFS_BUF_COUNT(bp));
}
/*
* This isn't an absolute requirement, but it is
* just a good idea to call xfs_read_buf instead of
* directly doing a read_buf call. For one, we shouldn't
* be doing this disk read if we are in SHUTDOWN state anyway,
* so this stops that from happening. Secondly, this does all
* the error checking stuff and the brelse if appropriate for
* the caller, so the code can be a little leaner.
*/
int
xfs_read_buf(
struct xfs_mount *mp,
xfs_buftarg_t *target,
xfs_daddr_t blkno,
int len,
uint flags,
xfs_buf_t **bpp)
{
xfs_buf_t *bp;
int error;
if (!flags)
flags = XBF_LOCK | XBF_MAPPED;
bp = xfs_buf_read(target, blkno, len, flags);
if (!bp)
return XFS_ERROR(EIO);
error = XFS_BUF_GETERROR(bp);
if (bp && !error && !XFS_FORCED_SHUTDOWN(mp)) {
*bpp = bp;
} else {
*bpp = NULL;
if (error) {
xfs_ioerror_alert("xfs_read_buf", mp, bp, XFS_BUF_ADDR(bp));
} else {
error = XFS_ERROR(EIO);
}
if (bp) {
XFS_BUF_UNDONE(bp);
XFS_BUF_UNDELAYWRITE(bp);
XFS_BUF_STALE(bp);
/*
* brelse clears B_ERROR and b_error
*/
xfs_buf_relse(bp);
}
}
return (error);
}
/*
* helper function to extract extent size hint from inode
*/
xfs_extlen_t
xfs_get_extsz_hint(
struct xfs_inode *ip)
{
if ((ip->i_d.di_flags & XFS_DIFLAG_EXTSIZE) && ip->i_d.di_extsize)
return ip->i_d.di_extsize;
if (XFS_IS_REALTIME_INODE(ip))
return ip->i_mount->m_sb.sb_rextsize;
return 0;
}
| gpl-2.0 |
pio-masaki/android_kernel_lge_v510 | crypto/ansi_cprng.c | 3317 | 11358 | /*
* PRNG: Pseudo Random Number Generator
* Based on NIST Recommended PRNG From ANSI X9.31 Appendix A.2.4 using
* AES 128 cipher
*
* (C) Neil Horman <nhorman@tuxdriver.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
* any later version.
*
*
*/
#include <crypto/internal/rng.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/string.h>
#include "internal.h"
#define DEFAULT_PRNG_KEY "0123456789abcdef"
#define DEFAULT_PRNG_KSZ 16
#define DEFAULT_BLK_SZ 16
#define DEFAULT_V_SEED "zaybxcwdveuftgsh"
/*
* Flags for the prng_context flags field
*/
#define PRNG_FIXED_SIZE 0x1
#define PRNG_NEED_RESET 0x2
/*
* Note: DT is our counter value
* I is our intermediate value
* V is our seed vector
* See http://csrc.nist.gov/groups/STM/cavp/documents/rng/931rngext.pdf
* for implementation details
*/
struct prng_context {
spinlock_t prng_lock;
unsigned char rand_data[DEFAULT_BLK_SZ];
unsigned char last_rand_data[DEFAULT_BLK_SZ];
unsigned char DT[DEFAULT_BLK_SZ];
unsigned char I[DEFAULT_BLK_SZ];
unsigned char V[DEFAULT_BLK_SZ];
u32 rand_data_valid;
struct crypto_cipher *tfm;
u32 flags;
};
static int dbg;
static void hexdump(char *note, unsigned char *buf, unsigned int len)
{
if (dbg) {
printk(KERN_CRIT "%s", note);
print_hex_dump(KERN_CONT, "", DUMP_PREFIX_OFFSET,
16, 1,
buf, len, false);
}
}
#define dbgprint(format, args...) do {\
if (dbg)\
printk(format, ##args);\
} while (0)
static void xor_vectors(unsigned char *in1, unsigned char *in2,
unsigned char *out, unsigned int size)
{
int i;
for (i = 0; i < size; i++)
out[i] = in1[i] ^ in2[i];
}
/*
* Returns DEFAULT_BLK_SZ bytes of random data per call
* returns 0 if generation succeeded, <0 if something went wrong
*/
static int _get_more_prng_bytes(struct prng_context *ctx, int cont_test)
{
int i;
unsigned char tmp[DEFAULT_BLK_SZ];
unsigned char *output = NULL;
dbgprint(KERN_CRIT "Calling _get_more_prng_bytes for context %p\n",
ctx);
hexdump("Input DT: ", ctx->DT, DEFAULT_BLK_SZ);
hexdump("Input I: ", ctx->I, DEFAULT_BLK_SZ);
hexdump("Input V: ", ctx->V, DEFAULT_BLK_SZ);
/*
* This algorithm is a 3 stage state machine
*/
for (i = 0; i < 3; i++) {
switch (i) {
case 0:
/*
* Start by encrypting the counter value
* This gives us an intermediate value I
*/
memcpy(tmp, ctx->DT, DEFAULT_BLK_SZ);
output = ctx->I;
hexdump("tmp stage 0: ", tmp, DEFAULT_BLK_SZ);
break;
case 1:
/*
* Next xor I with our secret vector V
* encrypt that result to obtain our
* pseudo random data which we output
*/
xor_vectors(ctx->I, ctx->V, tmp, DEFAULT_BLK_SZ);
hexdump("tmp stage 1: ", tmp, DEFAULT_BLK_SZ);
output = ctx->rand_data;
break;
case 2:
/*
* First check that we didn't produce the same
* random data that we did last time around through this
*/
if (!memcmp(ctx->rand_data, ctx->last_rand_data,
DEFAULT_BLK_SZ)) {
if (cont_test) {
panic("cprng %p Failed repetition check!\n",
ctx);
}
printk(KERN_ERR
"ctx %p Failed repetition check!\n",
ctx);
ctx->flags |= PRNG_NEED_RESET;
return -EINVAL;
}
memcpy(ctx->last_rand_data, ctx->rand_data,
DEFAULT_BLK_SZ);
/*
* Lastly xor the random data with I
* and encrypt that to obtain a new secret vector V
*/
xor_vectors(ctx->rand_data, ctx->I, tmp,
DEFAULT_BLK_SZ);
output = ctx->V;
hexdump("tmp stage 2: ", tmp, DEFAULT_BLK_SZ);
break;
}
/* do the encryption */
crypto_cipher_encrypt_one(ctx->tfm, output, tmp);
}
/*
* Now update our DT value
*/
for (i = DEFAULT_BLK_SZ - 1; i >= 0; i--) {
ctx->DT[i] += 1;
if (ctx->DT[i] != 0)
break;
}
dbgprint("Returning new block for context %p\n", ctx);
ctx->rand_data_valid = 0;
hexdump("Output DT: ", ctx->DT, DEFAULT_BLK_SZ);
hexdump("Output I: ", ctx->I, DEFAULT_BLK_SZ);
hexdump("Output V: ", ctx->V, DEFAULT_BLK_SZ);
hexdump("New Random Data: ", ctx->rand_data, DEFAULT_BLK_SZ);
return 0;
}
/* Our exported functions */
static int get_prng_bytes(char *buf, size_t nbytes, struct prng_context *ctx,
int do_cont_test)
{
unsigned char *ptr = buf;
unsigned int byte_count = (unsigned int)nbytes;
int err;
spin_lock_bh(&ctx->prng_lock);
err = -EINVAL;
if (ctx->flags & PRNG_NEED_RESET)
goto done;
/*
* If the FIXED_SIZE flag is on, only return whole blocks of
* pseudo random data
*/
err = -EINVAL;
if (ctx->flags & PRNG_FIXED_SIZE) {
if (nbytes < DEFAULT_BLK_SZ)
goto done;
byte_count = DEFAULT_BLK_SZ;
}
err = byte_count;
dbgprint(KERN_CRIT "getting %d random bytes for context %p\n",
byte_count, ctx);
remainder:
if (ctx->rand_data_valid == DEFAULT_BLK_SZ) {
if (_get_more_prng_bytes(ctx, do_cont_test) < 0) {
memset(buf, 0, nbytes);
err = -EINVAL;
goto done;
}
}
/*
* Copy any data less than an entire block
*/
if (byte_count < DEFAULT_BLK_SZ) {
empty_rbuf:
for (; ctx->rand_data_valid < DEFAULT_BLK_SZ;
ctx->rand_data_valid++) {
*ptr = ctx->rand_data[ctx->rand_data_valid];
ptr++;
byte_count--;
if (byte_count == 0)
goto done;
}
}
/*
* Now copy whole blocks
*/
for (; byte_count >= DEFAULT_BLK_SZ; byte_count -= DEFAULT_BLK_SZ) {
if (ctx->rand_data_valid == DEFAULT_BLK_SZ) {
if (_get_more_prng_bytes(ctx, do_cont_test) < 0) {
memset(buf, 0, nbytes);
err = -EINVAL;
goto done;
}
}
if (ctx->rand_data_valid > 0)
goto empty_rbuf;
memcpy(ptr, ctx->rand_data, DEFAULT_BLK_SZ);
ctx->rand_data_valid += DEFAULT_BLK_SZ;
ptr += DEFAULT_BLK_SZ;
}
/*
* Now go back and get any remaining partial block
*/
if (byte_count)
goto remainder;
done:
spin_unlock_bh(&ctx->prng_lock);
dbgprint(KERN_CRIT "returning %d from get_prng_bytes in context %p\n",
err, ctx);
return err;
}
static void free_prng_context(struct prng_context *ctx)
{
crypto_free_cipher(ctx->tfm);
}
static int reset_prng_context(struct prng_context *ctx,
unsigned char *key, size_t klen,
unsigned char *V, unsigned char *DT)
{
int ret;
unsigned char *prng_key;
spin_lock_bh(&ctx->prng_lock);
ctx->flags |= PRNG_NEED_RESET;
prng_key = (key != NULL) ? key : (unsigned char *)DEFAULT_PRNG_KEY;
if (!key)
klen = DEFAULT_PRNG_KSZ;
if (V)
memcpy(ctx->V, V, DEFAULT_BLK_SZ);
else
memcpy(ctx->V, DEFAULT_V_SEED, DEFAULT_BLK_SZ);
if (DT)
memcpy(ctx->DT, DT, DEFAULT_BLK_SZ);
else
memset(ctx->DT, 0, DEFAULT_BLK_SZ);
memset(ctx->rand_data, 0, DEFAULT_BLK_SZ);
memset(ctx->last_rand_data, 0, DEFAULT_BLK_SZ);
ctx->rand_data_valid = DEFAULT_BLK_SZ;
ret = crypto_cipher_setkey(ctx->tfm, prng_key, klen);
if (ret) {
dbgprint(KERN_CRIT "PRNG: setkey() failed flags=%x\n",
crypto_cipher_get_flags(ctx->tfm));
goto out;
}
ret = 0;
ctx->flags &= ~PRNG_NEED_RESET;
out:
spin_unlock_bh(&ctx->prng_lock);
return ret;
}
static int cprng_init(struct crypto_tfm *tfm)
{
struct prng_context *ctx = crypto_tfm_ctx(tfm);
spin_lock_init(&ctx->prng_lock);
ctx->tfm = crypto_alloc_cipher("aes", 0, 0);
if (IS_ERR(ctx->tfm)) {
dbgprint(KERN_CRIT "Failed to alloc tfm for context %p\n",
ctx);
return PTR_ERR(ctx->tfm);
}
if (reset_prng_context(ctx, NULL, DEFAULT_PRNG_KSZ, NULL, NULL) < 0)
return -EINVAL;
/*
* after allocation, we should always force the user to reset
* so they don't inadvertently use the insecure default values
* without specifying them intentially
*/
ctx->flags |= PRNG_NEED_RESET;
return 0;
}
static void cprng_exit(struct crypto_tfm *tfm)
{
free_prng_context(crypto_tfm_ctx(tfm));
}
static int cprng_get_random(struct crypto_rng *tfm, u8 *rdata,
unsigned int dlen)
{
struct prng_context *prng = crypto_rng_ctx(tfm);
return get_prng_bytes(rdata, dlen, prng, 0);
}
/*
* This is the cprng_registered reset method the seed value is
* interpreted as the tuple { V KEY DT}
* V and KEY are required during reset, and DT is optional, detected
* as being present by testing the length of the seed
*/
static int cprng_reset(struct crypto_rng *tfm, u8 *seed, unsigned int slen)
{
struct prng_context *prng = crypto_rng_ctx(tfm);
u8 *key = seed + DEFAULT_BLK_SZ;
u8 *dt = NULL;
if (slen < DEFAULT_PRNG_KSZ + DEFAULT_BLK_SZ)
return -EINVAL;
if (slen >= (2 * DEFAULT_BLK_SZ + DEFAULT_PRNG_KSZ))
dt = key + DEFAULT_PRNG_KSZ;
reset_prng_context(prng, key, DEFAULT_PRNG_KSZ, seed, dt);
if (prng->flags & PRNG_NEED_RESET)
return -EINVAL;
return 0;
}
static struct crypto_alg rng_alg = {
.cra_name = "stdrng",
.cra_driver_name = "ansi_cprng",
.cra_priority = 100,
.cra_flags = CRYPTO_ALG_TYPE_RNG,
.cra_ctxsize = sizeof(struct prng_context),
.cra_type = &crypto_rng_type,
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(rng_alg.cra_list),
.cra_init = cprng_init,
.cra_exit = cprng_exit,
.cra_u = {
.rng = {
.rng_make_random = cprng_get_random,
.rng_reset = cprng_reset,
.seedsize = DEFAULT_PRNG_KSZ + 2*DEFAULT_BLK_SZ,
}
}
};
#ifdef CONFIG_CRYPTO_FIPS
static int fips_cprng_get_random(struct crypto_rng *tfm, u8 *rdata,
unsigned int dlen)
{
struct prng_context *prng = crypto_rng_ctx(tfm);
return get_prng_bytes(rdata, dlen, prng, 1);
}
static int fips_cprng_reset(struct crypto_rng *tfm, u8 *seed, unsigned int slen)
{
u8 rdata[DEFAULT_BLK_SZ];
u8 *key = seed + DEFAULT_BLK_SZ;
int rc;
struct prng_context *prng = crypto_rng_ctx(tfm);
if (slen < DEFAULT_PRNG_KSZ + DEFAULT_BLK_SZ)
return -EINVAL;
/* fips strictly requires seed != key */
if (!memcmp(seed, key, DEFAULT_PRNG_KSZ))
return -EINVAL;
rc = cprng_reset(tfm, seed, slen);
if (!rc)
goto out;
/* this primes our continuity test */
rc = get_prng_bytes(rdata, DEFAULT_BLK_SZ, prng, 0);
prng->rand_data_valid = DEFAULT_BLK_SZ;
out:
return rc;
}
static struct crypto_alg fips_rng_alg = {
.cra_name = "fips(ansi_cprng)",
.cra_driver_name = "fips_ansi_cprng",
.cra_priority = 300,
.cra_flags = CRYPTO_ALG_TYPE_RNG,
.cra_ctxsize = sizeof(struct prng_context),
.cra_type = &crypto_rng_type,
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(rng_alg.cra_list),
.cra_init = cprng_init,
.cra_exit = cprng_exit,
.cra_u = {
.rng = {
.rng_make_random = fips_cprng_get_random,
.rng_reset = fips_cprng_reset,
.seedsize = DEFAULT_PRNG_KSZ + 2*DEFAULT_BLK_SZ,
}
}
};
#endif
/* Module initalization */
static int __init prng_mod_init(void)
{
int rc = 0;
rc = crypto_register_alg(&rng_alg);
#ifdef CONFIG_CRYPTO_FIPS
if (rc)
goto out;
rc = crypto_register_alg(&fips_rng_alg);
out:
#endif
return rc;
}
static void __exit prng_mod_fini(void)
{
crypto_unregister_alg(&rng_alg);
#ifdef CONFIG_CRYPTO_FIPS
crypto_unregister_alg(&fips_rng_alg);
#endif
return;
}
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Software Pseudo Random Number Generator");
MODULE_AUTHOR("Neil Horman <nhorman@tuxdriver.com>");
module_param(dbg, int, 0);
MODULE_PARM_DESC(dbg, "Boolean to enable debugging (0/1 == off/on)");
module_init(prng_mod_init);
module_exit(prng_mod_fini);
MODULE_ALIAS("stdrng");
| gpl-2.0 |
helicopter88/android_kernel_lge_hammerhead | drivers/dma/shdma.c | 4853 | 39306 | /*
* Renesas SuperH DMA Engine support
*
* base is drivers/dma/flsdma.c
*
* Copyright (C) 2009 Nobuhiro Iwamatsu <iwamatsu.nobuhiro@renesas.com>
* Copyright (C) 2009 Renesas Solutions, Inc. All rights reserved.
* Copyright (C) 2007 Freescale Semiconductor, Inc. All rights reserved.
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* - DMA of SuperH does not have Hardware DMA chain mode.
* - MAX DMA size is 16MB.
*
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/dmaengine.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/pm_runtime.h>
#include <linux/sh_dma.h>
#include <linux/notifier.h>
#include <linux/kdebug.h>
#include <linux/spinlock.h>
#include <linux/rculist.h>
#include "dmaengine.h"
#include "shdma.h"
/* DMA descriptor control */
enum sh_dmae_desc_status {
DESC_IDLE,
DESC_PREPARED,
DESC_SUBMITTED,
DESC_COMPLETED, /* completed, have to call callback */
DESC_WAITING, /* callback called, waiting for ack / re-submit */
};
#define NR_DESCS_PER_CHANNEL 32
/* Default MEMCPY transfer size = 2^2 = 4 bytes */
#define LOG2_DEFAULT_XFER_SIZE 2
/*
* Used for write-side mutual exclusion for the global device list,
* read-side synchronization by way of RCU, and per-controller data.
*/
static DEFINE_SPINLOCK(sh_dmae_lock);
static LIST_HEAD(sh_dmae_devices);
/* A bitmask with bits enough for enum sh_dmae_slave_chan_id */
static unsigned long sh_dmae_slave_used[BITS_TO_LONGS(SH_DMA_SLAVE_NUMBER)];
static void sh_dmae_chan_ld_cleanup(struct sh_dmae_chan *sh_chan, bool all);
static void sh_chan_xfer_ld_queue(struct sh_dmae_chan *sh_chan);
static void chclr_write(struct sh_dmae_chan *sh_dc, u32 data)
{
struct sh_dmae_device *shdev = to_sh_dev(sh_dc);
__raw_writel(data, shdev->chan_reg +
shdev->pdata->channel[sh_dc->id].chclr_offset);
}
static void sh_dmae_writel(struct sh_dmae_chan *sh_dc, u32 data, u32 reg)
{
__raw_writel(data, sh_dc->base + reg / sizeof(u32));
}
static u32 sh_dmae_readl(struct sh_dmae_chan *sh_dc, u32 reg)
{
return __raw_readl(sh_dc->base + reg / sizeof(u32));
}
static u16 dmaor_read(struct sh_dmae_device *shdev)
{
u32 __iomem *addr = shdev->chan_reg + DMAOR / sizeof(u32);
if (shdev->pdata->dmaor_is_32bit)
return __raw_readl(addr);
else
return __raw_readw(addr);
}
static void dmaor_write(struct sh_dmae_device *shdev, u16 data)
{
u32 __iomem *addr = shdev->chan_reg + DMAOR / sizeof(u32);
if (shdev->pdata->dmaor_is_32bit)
__raw_writel(data, addr);
else
__raw_writew(data, addr);
}
static void chcr_write(struct sh_dmae_chan *sh_dc, u32 data)
{
struct sh_dmae_device *shdev = to_sh_dev(sh_dc);
__raw_writel(data, sh_dc->base + shdev->chcr_offset / sizeof(u32));
}
static u32 chcr_read(struct sh_dmae_chan *sh_dc)
{
struct sh_dmae_device *shdev = to_sh_dev(sh_dc);
return __raw_readl(sh_dc->base + shdev->chcr_offset / sizeof(u32));
}
/*
* Reset DMA controller
*
* SH7780 has two DMAOR register
*/
static void sh_dmae_ctl_stop(struct sh_dmae_device *shdev)
{
unsigned short dmaor;
unsigned long flags;
spin_lock_irqsave(&sh_dmae_lock, flags);
dmaor = dmaor_read(shdev);
dmaor_write(shdev, dmaor & ~(DMAOR_NMIF | DMAOR_AE | DMAOR_DME));
spin_unlock_irqrestore(&sh_dmae_lock, flags);
}
static int sh_dmae_rst(struct sh_dmae_device *shdev)
{
unsigned short dmaor;
unsigned long flags;
spin_lock_irqsave(&sh_dmae_lock, flags);
dmaor = dmaor_read(shdev) & ~(DMAOR_NMIF | DMAOR_AE | DMAOR_DME);
if (shdev->pdata->chclr_present) {
int i;
for (i = 0; i < shdev->pdata->channel_num; i++) {
struct sh_dmae_chan *sh_chan = shdev->chan[i];
if (sh_chan)
chclr_write(sh_chan, 0);
}
}
dmaor_write(shdev, dmaor | shdev->pdata->dmaor_init);
dmaor = dmaor_read(shdev);
spin_unlock_irqrestore(&sh_dmae_lock, flags);
if (dmaor & (DMAOR_AE | DMAOR_NMIF)) {
dev_warn(shdev->common.dev, "Can't initialize DMAOR.\n");
return -EIO;
}
if (shdev->pdata->dmaor_init & ~dmaor)
dev_warn(shdev->common.dev,
"DMAOR=0x%x hasn't latched the initial value 0x%x.\n",
dmaor, shdev->pdata->dmaor_init);
return 0;
}
static bool dmae_is_busy(struct sh_dmae_chan *sh_chan)
{
u32 chcr = chcr_read(sh_chan);
if ((chcr & (CHCR_DE | CHCR_TE)) == CHCR_DE)
return true; /* working */
return false; /* waiting */
}
static unsigned int calc_xmit_shift(struct sh_dmae_chan *sh_chan, u32 chcr)
{
struct sh_dmae_device *shdev = to_sh_dev(sh_chan);
struct sh_dmae_pdata *pdata = shdev->pdata;
int cnt = ((chcr & pdata->ts_low_mask) >> pdata->ts_low_shift) |
((chcr & pdata->ts_high_mask) >> pdata->ts_high_shift);
if (cnt >= pdata->ts_shift_num)
cnt = 0;
return pdata->ts_shift[cnt];
}
static u32 log2size_to_chcr(struct sh_dmae_chan *sh_chan, int l2size)
{
struct sh_dmae_device *shdev = to_sh_dev(sh_chan);
struct sh_dmae_pdata *pdata = shdev->pdata;
int i;
for (i = 0; i < pdata->ts_shift_num; i++)
if (pdata->ts_shift[i] == l2size)
break;
if (i == pdata->ts_shift_num)
i = 0;
return ((i << pdata->ts_low_shift) & pdata->ts_low_mask) |
((i << pdata->ts_high_shift) & pdata->ts_high_mask);
}
static void dmae_set_reg(struct sh_dmae_chan *sh_chan, struct sh_dmae_regs *hw)
{
sh_dmae_writel(sh_chan, hw->sar, SAR);
sh_dmae_writel(sh_chan, hw->dar, DAR);
sh_dmae_writel(sh_chan, hw->tcr >> sh_chan->xmit_shift, TCR);
}
static void dmae_start(struct sh_dmae_chan *sh_chan)
{
struct sh_dmae_device *shdev = to_sh_dev(sh_chan);
u32 chcr = chcr_read(sh_chan);
if (shdev->pdata->needs_tend_set)
sh_dmae_writel(sh_chan, 0xFFFFFFFF, TEND);
chcr |= CHCR_DE | shdev->chcr_ie_bit;
chcr_write(sh_chan, chcr & ~CHCR_TE);
}
static void dmae_halt(struct sh_dmae_chan *sh_chan)
{
struct sh_dmae_device *shdev = to_sh_dev(sh_chan);
u32 chcr = chcr_read(sh_chan);
chcr &= ~(CHCR_DE | CHCR_TE | shdev->chcr_ie_bit);
chcr_write(sh_chan, chcr);
}
static void dmae_init(struct sh_dmae_chan *sh_chan)
{
/*
* Default configuration for dual address memory-memory transfer.
* 0x400 represents auto-request.
*/
u32 chcr = DM_INC | SM_INC | 0x400 | log2size_to_chcr(sh_chan,
LOG2_DEFAULT_XFER_SIZE);
sh_chan->xmit_shift = calc_xmit_shift(sh_chan, chcr);
chcr_write(sh_chan, chcr);
}
static int dmae_set_chcr(struct sh_dmae_chan *sh_chan, u32 val)
{
/* If DMA is active, cannot set CHCR. TODO: remove this superfluous check */
if (dmae_is_busy(sh_chan))
return -EBUSY;
sh_chan->xmit_shift = calc_xmit_shift(sh_chan, val);
chcr_write(sh_chan, val);
return 0;
}
static int dmae_set_dmars(struct sh_dmae_chan *sh_chan, u16 val)
{
struct sh_dmae_device *shdev = to_sh_dev(sh_chan);
struct sh_dmae_pdata *pdata = shdev->pdata;
const struct sh_dmae_channel *chan_pdata = &pdata->channel[sh_chan->id];
u16 __iomem *addr = shdev->dmars;
unsigned int shift = chan_pdata->dmars_bit;
if (dmae_is_busy(sh_chan))
return -EBUSY;
if (pdata->no_dmars)
return 0;
/* in the case of a missing DMARS resource use first memory window */
if (!addr)
addr = (u16 __iomem *)shdev->chan_reg;
addr += chan_pdata->dmars / sizeof(u16);
__raw_writew((__raw_readw(addr) & (0xff00 >> shift)) | (val << shift),
addr);
return 0;
}
static dma_cookie_t sh_dmae_tx_submit(struct dma_async_tx_descriptor *tx)
{
struct sh_desc *desc = tx_to_sh_desc(tx), *chunk, *last = desc, *c;
struct sh_dmae_chan *sh_chan = to_sh_chan(tx->chan);
struct sh_dmae_slave *param = tx->chan->private;
dma_async_tx_callback callback = tx->callback;
dma_cookie_t cookie;
bool power_up;
spin_lock_irq(&sh_chan->desc_lock);
if (list_empty(&sh_chan->ld_queue))
power_up = true;
else
power_up = false;
cookie = dma_cookie_assign(tx);
/* Mark all chunks of this descriptor as submitted, move to the queue */
list_for_each_entry_safe(chunk, c, desc->node.prev, node) {
/*
* All chunks are on the global ld_free, so, we have to find
* the end of the chain ourselves
*/
if (chunk != desc && (chunk->mark == DESC_IDLE ||
chunk->async_tx.cookie > 0 ||
chunk->async_tx.cookie == -EBUSY ||
&chunk->node == &sh_chan->ld_free))
break;
chunk->mark = DESC_SUBMITTED;
/* Callback goes to the last chunk */
chunk->async_tx.callback = NULL;
chunk->cookie = cookie;
list_move_tail(&chunk->node, &sh_chan->ld_queue);
last = chunk;
}
last->async_tx.callback = callback;
last->async_tx.callback_param = tx->callback_param;
dev_dbg(sh_chan->dev, "submit #%d@%p on %d: %x[%d] -> %x\n",
tx->cookie, &last->async_tx, sh_chan->id,
desc->hw.sar, desc->hw.tcr, desc->hw.dar);
if (power_up) {
sh_chan->pm_state = DMAE_PM_BUSY;
pm_runtime_get(sh_chan->dev);
spin_unlock_irq(&sh_chan->desc_lock);
pm_runtime_barrier(sh_chan->dev);
spin_lock_irq(&sh_chan->desc_lock);
/* Have we been reset, while waiting? */
if (sh_chan->pm_state != DMAE_PM_ESTABLISHED) {
dev_dbg(sh_chan->dev, "Bring up channel %d\n",
sh_chan->id);
if (param) {
const struct sh_dmae_slave_config *cfg =
param->config;
dmae_set_dmars(sh_chan, cfg->mid_rid);
dmae_set_chcr(sh_chan, cfg->chcr);
} else {
dmae_init(sh_chan);
}
if (sh_chan->pm_state == DMAE_PM_PENDING)
sh_chan_xfer_ld_queue(sh_chan);
sh_chan->pm_state = DMAE_PM_ESTABLISHED;
}
} else {
sh_chan->pm_state = DMAE_PM_PENDING;
}
spin_unlock_irq(&sh_chan->desc_lock);
return cookie;
}
/* Called with desc_lock held */
static struct sh_desc *sh_dmae_get_desc(struct sh_dmae_chan *sh_chan)
{
struct sh_desc *desc;
list_for_each_entry(desc, &sh_chan->ld_free, node)
if (desc->mark != DESC_PREPARED) {
BUG_ON(desc->mark != DESC_IDLE);
list_del(&desc->node);
return desc;
}
return NULL;
}
static const struct sh_dmae_slave_config *sh_dmae_find_slave(
struct sh_dmae_chan *sh_chan, struct sh_dmae_slave *param)
{
struct sh_dmae_device *shdev = to_sh_dev(sh_chan);
struct sh_dmae_pdata *pdata = shdev->pdata;
int i;
if (param->slave_id >= SH_DMA_SLAVE_NUMBER)
return NULL;
for (i = 0; i < pdata->slave_num; i++)
if (pdata->slave[i].slave_id == param->slave_id)
return pdata->slave + i;
return NULL;
}
static int sh_dmae_alloc_chan_resources(struct dma_chan *chan)
{
struct sh_dmae_chan *sh_chan = to_sh_chan(chan);
struct sh_desc *desc;
struct sh_dmae_slave *param = chan->private;
int ret;
/*
* This relies on the guarantee from dmaengine that alloc_chan_resources
* never runs concurrently with itself or free_chan_resources.
*/
if (param) {
const struct sh_dmae_slave_config *cfg;
cfg = sh_dmae_find_slave(sh_chan, param);
if (!cfg) {
ret = -EINVAL;
goto efindslave;
}
if (test_and_set_bit(param->slave_id, sh_dmae_slave_used)) {
ret = -EBUSY;
goto etestused;
}
param->config = cfg;
}
while (sh_chan->descs_allocated < NR_DESCS_PER_CHANNEL) {
desc = kzalloc(sizeof(struct sh_desc), GFP_KERNEL);
if (!desc)
break;
dma_async_tx_descriptor_init(&desc->async_tx,
&sh_chan->common);
desc->async_tx.tx_submit = sh_dmae_tx_submit;
desc->mark = DESC_IDLE;
list_add(&desc->node, &sh_chan->ld_free);
sh_chan->descs_allocated++;
}
if (!sh_chan->descs_allocated) {
ret = -ENOMEM;
goto edescalloc;
}
return sh_chan->descs_allocated;
edescalloc:
if (param)
clear_bit(param->slave_id, sh_dmae_slave_used);
etestused:
efindslave:
chan->private = NULL;
return ret;
}
/*
* sh_dma_free_chan_resources - Free all resources of the channel.
*/
static void sh_dmae_free_chan_resources(struct dma_chan *chan)
{
struct sh_dmae_chan *sh_chan = to_sh_chan(chan);
struct sh_desc *desc, *_desc;
LIST_HEAD(list);
/* Protect against ISR */
spin_lock_irq(&sh_chan->desc_lock);
dmae_halt(sh_chan);
spin_unlock_irq(&sh_chan->desc_lock);
/* Now no new interrupts will occur */
/* Prepared and not submitted descriptors can still be on the queue */
if (!list_empty(&sh_chan->ld_queue))
sh_dmae_chan_ld_cleanup(sh_chan, true);
if (chan->private) {
/* The caller is holding dma_list_mutex */
struct sh_dmae_slave *param = chan->private;
clear_bit(param->slave_id, sh_dmae_slave_used);
chan->private = NULL;
}
spin_lock_irq(&sh_chan->desc_lock);
list_splice_init(&sh_chan->ld_free, &list);
sh_chan->descs_allocated = 0;
spin_unlock_irq(&sh_chan->desc_lock);
list_for_each_entry_safe(desc, _desc, &list, node)
kfree(desc);
}
/**
* sh_dmae_add_desc - get, set up and return one transfer descriptor
* @sh_chan: DMA channel
* @flags: DMA transfer flags
* @dest: destination DMA address, incremented when direction equals
* DMA_DEV_TO_MEM
* @src: source DMA address, incremented when direction equals
* DMA_MEM_TO_DEV
* @len: DMA transfer length
* @first: if NULL, set to the current descriptor and cookie set to -EBUSY
* @direction: needed for slave DMA to decide which address to keep constant,
* equals DMA_MEM_TO_MEM for MEMCPY
* Returns 0 or an error
* Locks: called with desc_lock held
*/
static struct sh_desc *sh_dmae_add_desc(struct sh_dmae_chan *sh_chan,
unsigned long flags, dma_addr_t *dest, dma_addr_t *src, size_t *len,
struct sh_desc **first, enum dma_transfer_direction direction)
{
struct sh_desc *new;
size_t copy_size;
if (!*len)
return NULL;
/* Allocate the link descriptor from the free list */
new = sh_dmae_get_desc(sh_chan);
if (!new) {
dev_err(sh_chan->dev, "No free link descriptor available\n");
return NULL;
}
copy_size = min(*len, (size_t)SH_DMA_TCR_MAX + 1);
new->hw.sar = *src;
new->hw.dar = *dest;
new->hw.tcr = copy_size;
if (!*first) {
/* First desc */
new->async_tx.cookie = -EBUSY;
*first = new;
} else {
/* Other desc - invisible to the user */
new->async_tx.cookie = -EINVAL;
}
dev_dbg(sh_chan->dev,
"chaining (%u/%u)@%x -> %x with %p, cookie %d, shift %d\n",
copy_size, *len, *src, *dest, &new->async_tx,
new->async_tx.cookie, sh_chan->xmit_shift);
new->mark = DESC_PREPARED;
new->async_tx.flags = flags;
new->direction = direction;
*len -= copy_size;
if (direction == DMA_MEM_TO_MEM || direction == DMA_MEM_TO_DEV)
*src += copy_size;
if (direction == DMA_MEM_TO_MEM || direction == DMA_DEV_TO_MEM)
*dest += copy_size;
return new;
}
/*
* sh_dmae_prep_sg - prepare transfer descriptors from an SG list
*
* Common routine for public (MEMCPY) and slave DMA. The MEMCPY case is also
* converted to scatter-gather to guarantee consistent locking and a correct
* list manipulation. For slave DMA direction carries the usual meaning, and,
* logically, the SG list is RAM and the addr variable contains slave address,
* e.g., the FIFO I/O register. For MEMCPY direction equals DMA_MEM_TO_MEM
* and the SG list contains only one element and points at the source buffer.
*/
static struct dma_async_tx_descriptor *sh_dmae_prep_sg(struct sh_dmae_chan *sh_chan,
struct scatterlist *sgl, unsigned int sg_len, dma_addr_t *addr,
enum dma_transfer_direction direction, unsigned long flags)
{
struct scatterlist *sg;
struct sh_desc *first = NULL, *new = NULL /* compiler... */;
LIST_HEAD(tx_list);
int chunks = 0;
unsigned long irq_flags;
int i;
if (!sg_len)
return NULL;
for_each_sg(sgl, sg, sg_len, i)
chunks += (sg_dma_len(sg) + SH_DMA_TCR_MAX) /
(SH_DMA_TCR_MAX + 1);
/* Have to lock the whole loop to protect against concurrent release */
spin_lock_irqsave(&sh_chan->desc_lock, irq_flags);
/*
* Chaining:
* first descriptor is what user is dealing with in all API calls, its
* cookie is at first set to -EBUSY, at tx-submit to a positive
* number
* if more than one chunk is needed further chunks have cookie = -EINVAL
* the last chunk, if not equal to the first, has cookie = -ENOSPC
* all chunks are linked onto the tx_list head with their .node heads
* only during this function, then they are immediately spliced
* back onto the free list in form of a chain
*/
for_each_sg(sgl, sg, sg_len, i) {
dma_addr_t sg_addr = sg_dma_address(sg);
size_t len = sg_dma_len(sg);
if (!len)
goto err_get_desc;
do {
dev_dbg(sh_chan->dev, "Add SG #%d@%p[%d], dma %llx\n",
i, sg, len, (unsigned long long)sg_addr);
if (direction == DMA_DEV_TO_MEM)
new = sh_dmae_add_desc(sh_chan, flags,
&sg_addr, addr, &len, &first,
direction);
else
new = sh_dmae_add_desc(sh_chan, flags,
addr, &sg_addr, &len, &first,
direction);
if (!new)
goto err_get_desc;
new->chunks = chunks--;
list_add_tail(&new->node, &tx_list);
} while (len);
}
if (new != first)
new->async_tx.cookie = -ENOSPC;
/* Put them back on the free list, so, they don't get lost */
list_splice_tail(&tx_list, &sh_chan->ld_free);
spin_unlock_irqrestore(&sh_chan->desc_lock, irq_flags);
return &first->async_tx;
err_get_desc:
list_for_each_entry(new, &tx_list, node)
new->mark = DESC_IDLE;
list_splice(&tx_list, &sh_chan->ld_free);
spin_unlock_irqrestore(&sh_chan->desc_lock, irq_flags);
return NULL;
}
static struct dma_async_tx_descriptor *sh_dmae_prep_memcpy(
struct dma_chan *chan, dma_addr_t dma_dest, dma_addr_t dma_src,
size_t len, unsigned long flags)
{
struct sh_dmae_chan *sh_chan;
struct scatterlist sg;
if (!chan || !len)
return NULL;
sh_chan = to_sh_chan(chan);
sg_init_table(&sg, 1);
sg_set_page(&sg, pfn_to_page(PFN_DOWN(dma_src)), len,
offset_in_page(dma_src));
sg_dma_address(&sg) = dma_src;
sg_dma_len(&sg) = len;
return sh_dmae_prep_sg(sh_chan, &sg, 1, &dma_dest, DMA_MEM_TO_MEM,
flags);
}
static struct dma_async_tx_descriptor *sh_dmae_prep_slave_sg(
struct dma_chan *chan, struct scatterlist *sgl, unsigned int sg_len,
enum dma_transfer_direction direction, unsigned long flags,
void *context)
{
struct sh_dmae_slave *param;
struct sh_dmae_chan *sh_chan;
dma_addr_t slave_addr;
if (!chan)
return NULL;
sh_chan = to_sh_chan(chan);
param = chan->private;
/* Someone calling slave DMA on a public channel? */
if (!param || !sg_len) {
dev_warn(sh_chan->dev, "%s: bad parameter: %p, %d, %d\n",
__func__, param, sg_len, param ? param->slave_id : -1);
return NULL;
}
slave_addr = param->config->addr;
/*
* if (param != NULL), this is a successfully requested slave channel,
* therefore param->config != NULL too.
*/
return sh_dmae_prep_sg(sh_chan, sgl, sg_len, &slave_addr,
direction, flags);
}
static int sh_dmae_control(struct dma_chan *chan, enum dma_ctrl_cmd cmd,
unsigned long arg)
{
struct sh_dmae_chan *sh_chan = to_sh_chan(chan);
unsigned long flags;
/* Only supports DMA_TERMINATE_ALL */
if (cmd != DMA_TERMINATE_ALL)
return -ENXIO;
if (!chan)
return -EINVAL;
spin_lock_irqsave(&sh_chan->desc_lock, flags);
dmae_halt(sh_chan);
if (!list_empty(&sh_chan->ld_queue)) {
/* Record partial transfer */
struct sh_desc *desc = list_entry(sh_chan->ld_queue.next,
struct sh_desc, node);
desc->partial = (desc->hw.tcr - sh_dmae_readl(sh_chan, TCR)) <<
sh_chan->xmit_shift;
}
spin_unlock_irqrestore(&sh_chan->desc_lock, flags);
sh_dmae_chan_ld_cleanup(sh_chan, true);
return 0;
}
static dma_async_tx_callback __ld_cleanup(struct sh_dmae_chan *sh_chan, bool all)
{
struct sh_desc *desc, *_desc;
/* Is the "exposed" head of a chain acked? */
bool head_acked = false;
dma_cookie_t cookie = 0;
dma_async_tx_callback callback = NULL;
void *param = NULL;
unsigned long flags;
spin_lock_irqsave(&sh_chan->desc_lock, flags);
list_for_each_entry_safe(desc, _desc, &sh_chan->ld_queue, node) {
struct dma_async_tx_descriptor *tx = &desc->async_tx;
BUG_ON(tx->cookie > 0 && tx->cookie != desc->cookie);
BUG_ON(desc->mark != DESC_SUBMITTED &&
desc->mark != DESC_COMPLETED &&
desc->mark != DESC_WAITING);
/*
* queue is ordered, and we use this loop to (1) clean up all
* completed descriptors, and to (2) update descriptor flags of
* any chunks in a (partially) completed chain
*/
if (!all && desc->mark == DESC_SUBMITTED &&
desc->cookie != cookie)
break;
if (tx->cookie > 0)
cookie = tx->cookie;
if (desc->mark == DESC_COMPLETED && desc->chunks == 1) {
if (sh_chan->common.completed_cookie != desc->cookie - 1)
dev_dbg(sh_chan->dev,
"Completing cookie %d, expected %d\n",
desc->cookie,
sh_chan->common.completed_cookie + 1);
sh_chan->common.completed_cookie = desc->cookie;
}
/* Call callback on the last chunk */
if (desc->mark == DESC_COMPLETED && tx->callback) {
desc->mark = DESC_WAITING;
callback = tx->callback;
param = tx->callback_param;
dev_dbg(sh_chan->dev, "descriptor #%d@%p on %d callback\n",
tx->cookie, tx, sh_chan->id);
BUG_ON(desc->chunks != 1);
break;
}
if (tx->cookie > 0 || tx->cookie == -EBUSY) {
if (desc->mark == DESC_COMPLETED) {
BUG_ON(tx->cookie < 0);
desc->mark = DESC_WAITING;
}
head_acked = async_tx_test_ack(tx);
} else {
switch (desc->mark) {
case DESC_COMPLETED:
desc->mark = DESC_WAITING;
/* Fall through */
case DESC_WAITING:
if (head_acked)
async_tx_ack(&desc->async_tx);
}
}
dev_dbg(sh_chan->dev, "descriptor %p #%d completed.\n",
tx, tx->cookie);
if (((desc->mark == DESC_COMPLETED ||
desc->mark == DESC_WAITING) &&
async_tx_test_ack(&desc->async_tx)) || all) {
/* Remove from ld_queue list */
desc->mark = DESC_IDLE;
list_move(&desc->node, &sh_chan->ld_free);
if (list_empty(&sh_chan->ld_queue)) {
dev_dbg(sh_chan->dev, "Bring down channel %d\n", sh_chan->id);
pm_runtime_put(sh_chan->dev);
}
}
}
if (all && !callback)
/*
* Terminating and the loop completed normally: forgive
* uncompleted cookies
*/
sh_chan->common.completed_cookie = sh_chan->common.cookie;
spin_unlock_irqrestore(&sh_chan->desc_lock, flags);
if (callback)
callback(param);
return callback;
}
/*
* sh_chan_ld_cleanup - Clean up link descriptors
*
* This function cleans up the ld_queue of DMA channel.
*/
static void sh_dmae_chan_ld_cleanup(struct sh_dmae_chan *sh_chan, bool all)
{
while (__ld_cleanup(sh_chan, all))
;
}
/* Called under spin_lock_irq(&sh_chan->desc_lock) */
static void sh_chan_xfer_ld_queue(struct sh_dmae_chan *sh_chan)
{
struct sh_desc *desc;
/* DMA work check */
if (dmae_is_busy(sh_chan))
return;
/* Find the first not transferred descriptor */
list_for_each_entry(desc, &sh_chan->ld_queue, node)
if (desc->mark == DESC_SUBMITTED) {
dev_dbg(sh_chan->dev, "Queue #%d to %d: %u@%x -> %x\n",
desc->async_tx.cookie, sh_chan->id,
desc->hw.tcr, desc->hw.sar, desc->hw.dar);
/* Get the ld start address from ld_queue */
dmae_set_reg(sh_chan, &desc->hw);
dmae_start(sh_chan);
break;
}
}
static void sh_dmae_memcpy_issue_pending(struct dma_chan *chan)
{
struct sh_dmae_chan *sh_chan = to_sh_chan(chan);
spin_lock_irq(&sh_chan->desc_lock);
if (sh_chan->pm_state == DMAE_PM_ESTABLISHED)
sh_chan_xfer_ld_queue(sh_chan);
else
sh_chan->pm_state = DMAE_PM_PENDING;
spin_unlock_irq(&sh_chan->desc_lock);
}
static enum dma_status sh_dmae_tx_status(struct dma_chan *chan,
dma_cookie_t cookie,
struct dma_tx_state *txstate)
{
struct sh_dmae_chan *sh_chan = to_sh_chan(chan);
enum dma_status status;
unsigned long flags;
sh_dmae_chan_ld_cleanup(sh_chan, false);
spin_lock_irqsave(&sh_chan->desc_lock, flags);
status = dma_cookie_status(chan, cookie, txstate);
/*
* If we don't find cookie on the queue, it has been aborted and we have
* to report error
*/
if (status != DMA_SUCCESS) {
struct sh_desc *desc;
status = DMA_ERROR;
list_for_each_entry(desc, &sh_chan->ld_queue, node)
if (desc->cookie == cookie) {
status = DMA_IN_PROGRESS;
break;
}
}
spin_unlock_irqrestore(&sh_chan->desc_lock, flags);
return status;
}
static irqreturn_t sh_dmae_interrupt(int irq, void *data)
{
irqreturn_t ret = IRQ_NONE;
struct sh_dmae_chan *sh_chan = data;
u32 chcr;
spin_lock(&sh_chan->desc_lock);
chcr = chcr_read(sh_chan);
if (chcr & CHCR_TE) {
/* DMA stop */
dmae_halt(sh_chan);
ret = IRQ_HANDLED;
tasklet_schedule(&sh_chan->tasklet);
}
spin_unlock(&sh_chan->desc_lock);
return ret;
}
/* Called from error IRQ or NMI */
static bool sh_dmae_reset(struct sh_dmae_device *shdev)
{
unsigned int handled = 0;
int i;
/* halt the dma controller */
sh_dmae_ctl_stop(shdev);
/* We cannot detect, which channel caused the error, have to reset all */
for (i = 0; i < SH_DMAC_MAX_CHANNELS; i++) {
struct sh_dmae_chan *sh_chan = shdev->chan[i];
struct sh_desc *desc;
LIST_HEAD(dl);
if (!sh_chan)
continue;
spin_lock(&sh_chan->desc_lock);
/* Stop the channel */
dmae_halt(sh_chan);
list_splice_init(&sh_chan->ld_queue, &dl);
if (!list_empty(&dl)) {
dev_dbg(sh_chan->dev, "Bring down channel %d\n", sh_chan->id);
pm_runtime_put(sh_chan->dev);
}
sh_chan->pm_state = DMAE_PM_ESTABLISHED;
spin_unlock(&sh_chan->desc_lock);
/* Complete all */
list_for_each_entry(desc, &dl, node) {
struct dma_async_tx_descriptor *tx = &desc->async_tx;
desc->mark = DESC_IDLE;
if (tx->callback)
tx->callback(tx->callback_param);
}
spin_lock(&sh_chan->desc_lock);
list_splice(&dl, &sh_chan->ld_free);
spin_unlock(&sh_chan->desc_lock);
handled++;
}
sh_dmae_rst(shdev);
return !!handled;
}
static irqreturn_t sh_dmae_err(int irq, void *data)
{
struct sh_dmae_device *shdev = data;
if (!(dmaor_read(shdev) & DMAOR_AE))
return IRQ_NONE;
sh_dmae_reset(data);
return IRQ_HANDLED;
}
static void dmae_do_tasklet(unsigned long data)
{
struct sh_dmae_chan *sh_chan = (struct sh_dmae_chan *)data;
struct sh_desc *desc;
u32 sar_buf = sh_dmae_readl(sh_chan, SAR);
u32 dar_buf = sh_dmae_readl(sh_chan, DAR);
spin_lock_irq(&sh_chan->desc_lock);
list_for_each_entry(desc, &sh_chan->ld_queue, node) {
if (desc->mark == DESC_SUBMITTED &&
((desc->direction == DMA_DEV_TO_MEM &&
(desc->hw.dar + desc->hw.tcr) == dar_buf) ||
(desc->hw.sar + desc->hw.tcr) == sar_buf)) {
dev_dbg(sh_chan->dev, "done #%d@%p dst %u\n",
desc->async_tx.cookie, &desc->async_tx,
desc->hw.dar);
desc->mark = DESC_COMPLETED;
break;
}
}
/* Next desc */
sh_chan_xfer_ld_queue(sh_chan);
spin_unlock_irq(&sh_chan->desc_lock);
sh_dmae_chan_ld_cleanup(sh_chan, false);
}
static bool sh_dmae_nmi_notify(struct sh_dmae_device *shdev)
{
/* Fast path out if NMIF is not asserted for this controller */
if ((dmaor_read(shdev) & DMAOR_NMIF) == 0)
return false;
return sh_dmae_reset(shdev);
}
static int sh_dmae_nmi_handler(struct notifier_block *self,
unsigned long cmd, void *data)
{
struct sh_dmae_device *shdev;
int ret = NOTIFY_DONE;
bool triggered;
/*
* Only concern ourselves with NMI events.
*
* Normally we would check the die chain value, but as this needs
* to be architecture independent, check for NMI context instead.
*/
if (!in_nmi())
return NOTIFY_DONE;
rcu_read_lock();
list_for_each_entry_rcu(shdev, &sh_dmae_devices, node) {
/*
* Only stop if one of the controllers has NMIF asserted,
* we do not want to interfere with regular address error
* handling or NMI events that don't concern the DMACs.
*/
triggered = sh_dmae_nmi_notify(shdev);
if (triggered == true)
ret = NOTIFY_OK;
}
rcu_read_unlock();
return ret;
}
static struct notifier_block sh_dmae_nmi_notifier __read_mostly = {
.notifier_call = sh_dmae_nmi_handler,
/* Run before NMI debug handler and KGDB */
.priority = 1,
};
static int __devinit sh_dmae_chan_probe(struct sh_dmae_device *shdev, int id,
int irq, unsigned long flags)
{
int err;
const struct sh_dmae_channel *chan_pdata = &shdev->pdata->channel[id];
struct platform_device *pdev = to_platform_device(shdev->common.dev);
struct sh_dmae_chan *new_sh_chan;
/* alloc channel */
new_sh_chan = kzalloc(sizeof(struct sh_dmae_chan), GFP_KERNEL);
if (!new_sh_chan) {
dev_err(shdev->common.dev,
"No free memory for allocating dma channels!\n");
return -ENOMEM;
}
new_sh_chan->pm_state = DMAE_PM_ESTABLISHED;
/* reference struct dma_device */
new_sh_chan->common.device = &shdev->common;
dma_cookie_init(&new_sh_chan->common);
new_sh_chan->dev = shdev->common.dev;
new_sh_chan->id = id;
new_sh_chan->irq = irq;
new_sh_chan->base = shdev->chan_reg + chan_pdata->offset / sizeof(u32);
/* Init DMA tasklet */
tasklet_init(&new_sh_chan->tasklet, dmae_do_tasklet,
(unsigned long)new_sh_chan);
spin_lock_init(&new_sh_chan->desc_lock);
/* Init descripter manage list */
INIT_LIST_HEAD(&new_sh_chan->ld_queue);
INIT_LIST_HEAD(&new_sh_chan->ld_free);
/* Add the channel to DMA device channel list */
list_add_tail(&new_sh_chan->common.device_node,
&shdev->common.channels);
shdev->common.chancnt++;
if (pdev->id >= 0)
snprintf(new_sh_chan->dev_id, sizeof(new_sh_chan->dev_id),
"sh-dmae%d.%d", pdev->id, new_sh_chan->id);
else
snprintf(new_sh_chan->dev_id, sizeof(new_sh_chan->dev_id),
"sh-dma%d", new_sh_chan->id);
/* set up channel irq */
err = request_irq(irq, &sh_dmae_interrupt, flags,
new_sh_chan->dev_id, new_sh_chan);
if (err) {
dev_err(shdev->common.dev, "DMA channel %d request_irq error "
"with return %d\n", id, err);
goto err_no_irq;
}
shdev->chan[id] = new_sh_chan;
return 0;
err_no_irq:
/* remove from dmaengine device node */
list_del(&new_sh_chan->common.device_node);
kfree(new_sh_chan);
return err;
}
static void sh_dmae_chan_remove(struct sh_dmae_device *shdev)
{
int i;
for (i = shdev->common.chancnt - 1 ; i >= 0 ; i--) {
if (shdev->chan[i]) {
struct sh_dmae_chan *sh_chan = shdev->chan[i];
free_irq(sh_chan->irq, sh_chan);
list_del(&sh_chan->common.device_node);
kfree(sh_chan);
shdev->chan[i] = NULL;
}
}
shdev->common.chancnt = 0;
}
static int __init sh_dmae_probe(struct platform_device *pdev)
{
struct sh_dmae_pdata *pdata = pdev->dev.platform_data;
unsigned long irqflags = IRQF_DISABLED,
chan_flag[SH_DMAC_MAX_CHANNELS] = {};
int errirq, chan_irq[SH_DMAC_MAX_CHANNELS];
int err, i, irq_cnt = 0, irqres = 0, irq_cap = 0;
struct sh_dmae_device *shdev;
struct resource *chan, *dmars, *errirq_res, *chanirq_res;
/* get platform data */
if (!pdata || !pdata->channel_num)
return -ENODEV;
chan = platform_get_resource(pdev, IORESOURCE_MEM, 0);
/* DMARS area is optional */
dmars = platform_get_resource(pdev, IORESOURCE_MEM, 1);
/*
* IRQ resources:
* 1. there always must be at least one IRQ IO-resource. On SH4 it is
* the error IRQ, in which case it is the only IRQ in this resource:
* start == end. If it is the only IRQ resource, all channels also
* use the same IRQ.
* 2. DMA channel IRQ resources can be specified one per resource or in
* ranges (start != end)
* 3. iff all events (channels and, optionally, error) on this
* controller use the same IRQ, only one IRQ resource can be
* specified, otherwise there must be one IRQ per channel, even if
* some of them are equal
* 4. if all IRQs on this controller are equal or if some specific IRQs
* specify IORESOURCE_IRQ_SHAREABLE in their resources, they will be
* requested with the IRQF_SHARED flag
*/
errirq_res = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (!chan || !errirq_res)
return -ENODEV;
if (!request_mem_region(chan->start, resource_size(chan), pdev->name)) {
dev_err(&pdev->dev, "DMAC register region already claimed\n");
return -EBUSY;
}
if (dmars && !request_mem_region(dmars->start, resource_size(dmars), pdev->name)) {
dev_err(&pdev->dev, "DMAC DMARS region already claimed\n");
err = -EBUSY;
goto ermrdmars;
}
err = -ENOMEM;
shdev = kzalloc(sizeof(struct sh_dmae_device), GFP_KERNEL);
if (!shdev) {
dev_err(&pdev->dev, "Not enough memory\n");
goto ealloc;
}
shdev->chan_reg = ioremap(chan->start, resource_size(chan));
if (!shdev->chan_reg)
goto emapchan;
if (dmars) {
shdev->dmars = ioremap(dmars->start, resource_size(dmars));
if (!shdev->dmars)
goto emapdmars;
}
/* platform data */
shdev->pdata = pdata;
if (pdata->chcr_offset)
shdev->chcr_offset = pdata->chcr_offset;
else
shdev->chcr_offset = CHCR;
if (pdata->chcr_ie_bit)
shdev->chcr_ie_bit = pdata->chcr_ie_bit;
else
shdev->chcr_ie_bit = CHCR_IE;
platform_set_drvdata(pdev, shdev);
shdev->common.dev = &pdev->dev;
pm_runtime_enable(&pdev->dev);
pm_runtime_get_sync(&pdev->dev);
spin_lock_irq(&sh_dmae_lock);
list_add_tail_rcu(&shdev->node, &sh_dmae_devices);
spin_unlock_irq(&sh_dmae_lock);
/* reset dma controller - only needed as a test */
err = sh_dmae_rst(shdev);
if (err)
goto rst_err;
INIT_LIST_HEAD(&shdev->common.channels);
if (!pdata->slave_only)
dma_cap_set(DMA_MEMCPY, shdev->common.cap_mask);
if (pdata->slave && pdata->slave_num)
dma_cap_set(DMA_SLAVE, shdev->common.cap_mask);
shdev->common.device_alloc_chan_resources
= sh_dmae_alloc_chan_resources;
shdev->common.device_free_chan_resources = sh_dmae_free_chan_resources;
shdev->common.device_prep_dma_memcpy = sh_dmae_prep_memcpy;
shdev->common.device_tx_status = sh_dmae_tx_status;
shdev->common.device_issue_pending = sh_dmae_memcpy_issue_pending;
/* Compulsory for DMA_SLAVE fields */
shdev->common.device_prep_slave_sg = sh_dmae_prep_slave_sg;
shdev->common.device_control = sh_dmae_control;
/* Default transfer size of 32 bytes requires 32-byte alignment */
shdev->common.copy_align = LOG2_DEFAULT_XFER_SIZE;
#if defined(CONFIG_CPU_SH4) || defined(CONFIG_ARCH_SHMOBILE)
chanirq_res = platform_get_resource(pdev, IORESOURCE_IRQ, 1);
if (!chanirq_res)
chanirq_res = errirq_res;
else
irqres++;
if (chanirq_res == errirq_res ||
(errirq_res->flags & IORESOURCE_BITS) == IORESOURCE_IRQ_SHAREABLE)
irqflags = IRQF_SHARED;
errirq = errirq_res->start;
err = request_irq(errirq, sh_dmae_err, irqflags,
"DMAC Address Error", shdev);
if (err) {
dev_err(&pdev->dev,
"DMA failed requesting irq #%d, error %d\n",
errirq, err);
goto eirq_err;
}
#else
chanirq_res = errirq_res;
#endif /* CONFIG_CPU_SH4 || CONFIG_ARCH_SHMOBILE */
if (chanirq_res->start == chanirq_res->end &&
!platform_get_resource(pdev, IORESOURCE_IRQ, 1)) {
/* Special case - all multiplexed */
for (; irq_cnt < pdata->channel_num; irq_cnt++) {
if (irq_cnt < SH_DMAC_MAX_CHANNELS) {
chan_irq[irq_cnt] = chanirq_res->start;
chan_flag[irq_cnt] = IRQF_SHARED;
} else {
irq_cap = 1;
break;
}
}
} else {
do {
for (i = chanirq_res->start; i <= chanirq_res->end; i++) {
if (irq_cnt >= SH_DMAC_MAX_CHANNELS) {
irq_cap = 1;
break;
}
if ((errirq_res->flags & IORESOURCE_BITS) ==
IORESOURCE_IRQ_SHAREABLE)
chan_flag[irq_cnt] = IRQF_SHARED;
else
chan_flag[irq_cnt] = IRQF_DISABLED;
dev_dbg(&pdev->dev,
"Found IRQ %d for channel %d\n",
i, irq_cnt);
chan_irq[irq_cnt++] = i;
}
if (irq_cnt >= SH_DMAC_MAX_CHANNELS)
break;
chanirq_res = platform_get_resource(pdev,
IORESOURCE_IRQ, ++irqres);
} while (irq_cnt < pdata->channel_num && chanirq_res);
}
/* Create DMA Channel */
for (i = 0; i < irq_cnt; i++) {
err = sh_dmae_chan_probe(shdev, i, chan_irq[i], chan_flag[i]);
if (err)
goto chan_probe_err;
}
if (irq_cap)
dev_notice(&pdev->dev, "Attempting to register %d DMA "
"channels when a maximum of %d are supported.\n",
pdata->channel_num, SH_DMAC_MAX_CHANNELS);
pm_runtime_put(&pdev->dev);
dma_async_device_register(&shdev->common);
return err;
chan_probe_err:
sh_dmae_chan_remove(shdev);
#if defined(CONFIG_CPU_SH4) || defined(CONFIG_ARCH_SHMOBILE)
free_irq(errirq, shdev);
eirq_err:
#endif
rst_err:
spin_lock_irq(&sh_dmae_lock);
list_del_rcu(&shdev->node);
spin_unlock_irq(&sh_dmae_lock);
pm_runtime_put(&pdev->dev);
pm_runtime_disable(&pdev->dev);
if (dmars)
iounmap(shdev->dmars);
platform_set_drvdata(pdev, NULL);
emapdmars:
iounmap(shdev->chan_reg);
synchronize_rcu();
emapchan:
kfree(shdev);
ealloc:
if (dmars)
release_mem_region(dmars->start, resource_size(dmars));
ermrdmars:
release_mem_region(chan->start, resource_size(chan));
return err;
}
static int __exit sh_dmae_remove(struct platform_device *pdev)
{
struct sh_dmae_device *shdev = platform_get_drvdata(pdev);
struct resource *res;
int errirq = platform_get_irq(pdev, 0);
dma_async_device_unregister(&shdev->common);
if (errirq > 0)
free_irq(errirq, shdev);
spin_lock_irq(&sh_dmae_lock);
list_del_rcu(&shdev->node);
spin_unlock_irq(&sh_dmae_lock);
/* channel data remove */
sh_dmae_chan_remove(shdev);
pm_runtime_disable(&pdev->dev);
if (shdev->dmars)
iounmap(shdev->dmars);
iounmap(shdev->chan_reg);
platform_set_drvdata(pdev, NULL);
synchronize_rcu();
kfree(shdev);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (res)
release_mem_region(res->start, resource_size(res));
res = platform_get_resource(pdev, IORESOURCE_MEM, 1);
if (res)
release_mem_region(res->start, resource_size(res));
return 0;
}
static void sh_dmae_shutdown(struct platform_device *pdev)
{
struct sh_dmae_device *shdev = platform_get_drvdata(pdev);
sh_dmae_ctl_stop(shdev);
}
static int sh_dmae_runtime_suspend(struct device *dev)
{
return 0;
}
static int sh_dmae_runtime_resume(struct device *dev)
{
struct sh_dmae_device *shdev = dev_get_drvdata(dev);
return sh_dmae_rst(shdev);
}
#ifdef CONFIG_PM
static int sh_dmae_suspend(struct device *dev)
{
return 0;
}
static int sh_dmae_resume(struct device *dev)
{
struct sh_dmae_device *shdev = dev_get_drvdata(dev);
int i, ret;
ret = sh_dmae_rst(shdev);
if (ret < 0)
dev_err(dev, "Failed to reset!\n");
for (i = 0; i < shdev->pdata->channel_num; i++) {
struct sh_dmae_chan *sh_chan = shdev->chan[i];
struct sh_dmae_slave *param = sh_chan->common.private;
if (!sh_chan->descs_allocated)
continue;
if (param) {
const struct sh_dmae_slave_config *cfg = param->config;
dmae_set_dmars(sh_chan, cfg->mid_rid);
dmae_set_chcr(sh_chan, cfg->chcr);
} else {
dmae_init(sh_chan);
}
}
return 0;
}
#else
#define sh_dmae_suspend NULL
#define sh_dmae_resume NULL
#endif
const struct dev_pm_ops sh_dmae_pm = {
.suspend = sh_dmae_suspend,
.resume = sh_dmae_resume,
.runtime_suspend = sh_dmae_runtime_suspend,
.runtime_resume = sh_dmae_runtime_resume,
};
static struct platform_driver sh_dmae_driver = {
.remove = __exit_p(sh_dmae_remove),
.shutdown = sh_dmae_shutdown,
.driver = {
.owner = THIS_MODULE,
.name = "sh-dma-engine",
.pm = &sh_dmae_pm,
},
};
static int __init sh_dmae_init(void)
{
/* Wire up NMI handling */
int err = register_die_notifier(&sh_dmae_nmi_notifier);
if (err)
return err;
return platform_driver_probe(&sh_dmae_driver, sh_dmae_probe);
}
module_init(sh_dmae_init);
static void __exit sh_dmae_exit(void)
{
platform_driver_unregister(&sh_dmae_driver);
unregister_die_notifier(&sh_dmae_nmi_notifier);
}
module_exit(sh_dmae_exit);
MODULE_AUTHOR("Nobuhiro Iwamatsu <iwamatsu.nobuhiro@renesas.com>");
MODULE_DESCRIPTION("Renesas SH DMA Engine driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:sh-dma-engine");
| gpl-2.0 |
ktoonsez/KT-SGS4 | fs/ext3/fsync.c | 4853 | 3052 | /*
* linux/fs/ext3/fsync.c
*
* Copyright (C) 1993 Stephen Tweedie (sct@redhat.com)
* from
* Copyright (C) 1992 Remy Card (card@masi.ibp.fr)
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
* from
* linux/fs/minix/truncate.c Copyright (C) 1991, 1992 Linus Torvalds
*
* ext3fs fsync primitive
*
* Big-endian to little-endian byte-swapping/bitmaps by
* David S. Miller (davem@caip.rutgers.edu), 1995
*
* Removed unnecessary code duplication for little endian machines
* and excessive __inline__s.
* Andi Kleen, 1997
*
* Major simplications and cleanup - we only need to do the metadata, because
* we can depend on generic_block_fdatasync() to sync the data blocks.
*/
#include <linux/blkdev.h>
#include <linux/writeback.h>
#include "ext3.h"
/*
* akpm: A new design for ext3_sync_file().
*
* This is only called from sys_fsync(), sys_fdatasync() and sys_msync().
* There cannot be a transaction open by this task.
* Another task could have dirtied this inode. Its data can be in any
* state in the journalling system.
*
* What we do is just kick off a commit and wait on it. This will snapshot the
* inode to disk.
*/
int ext3_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
{
struct inode *inode = file->f_mapping->host;
struct ext3_inode_info *ei = EXT3_I(inode);
journal_t *journal = EXT3_SB(inode->i_sb)->s_journal;
int ret, needs_barrier = 0;
tid_t commit_tid;
trace_ext3_sync_file_enter(file, datasync);
if (inode->i_sb->s_flags & MS_RDONLY)
return 0;
ret = filemap_write_and_wait_range(inode->i_mapping, start, end);
if (ret)
goto out;
J_ASSERT(ext3_journal_current_handle() == NULL);
/*
* data=writeback,ordered:
* The caller's filemap_fdatawrite()/wait will sync the data.
* Metadata is in the journal, we wait for a proper transaction
* to commit here.
*
* data=journal:
* filemap_fdatawrite won't do anything (the buffers are clean).
* ext3_force_commit will write the file data into the journal and
* will wait on that.
* filemap_fdatawait() will encounter a ton of newly-dirtied pages
* (they were dirtied by commit). But that's OK - the blocks are
* safe in-journal, which is all fsync() needs to ensure.
*/
if (ext3_should_journal_data(inode)) {
ret = ext3_force_commit(inode->i_sb);
goto out;
}
if (datasync)
commit_tid = atomic_read(&ei->i_datasync_tid);
else
commit_tid = atomic_read(&ei->i_sync_tid);
if (test_opt(inode->i_sb, BARRIER) &&
!journal_trans_will_send_data_barrier(journal, commit_tid))
needs_barrier = 1;
log_start_commit(journal, commit_tid);
ret = log_wait_commit(journal, commit_tid);
/*
* In case we didn't commit a transaction, we have to flush
* disk caches manually so that data really is on persistent
* storage
*/
if (needs_barrier)
blkdev_issue_flush(inode->i_sb->s_bdev, GFP_KERNEL, NULL);
out:
trace_ext3_sync_file_exit(inode, ret);
return ret;
}
| gpl-2.0 |
shichao-an/linux-2.6.34.7 | drivers/staging/go7007/go7007-i2c.c | 4853 | 6374 | /*
* 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/init.h>
#include <linux/delay.h>
#include <linux/sched.h>
#include <linux/list.h>
#include <linux/unistd.h>
#include <linux/time.h>
#include <linux/device.h>
#include <linux/i2c.h>
#include <linux/mutex.h>
#include <linux/uaccess.h>
#include <asm/system.h>
#include "go7007-priv.h"
#include "wis-i2c.h"
/********************* Driver for on-board I2C adapter *********************/
/* #define GO7007_I2C_DEBUG */
#define SPI_I2C_ADDR_BASE 0x1400
#define STATUS_REG_ADDR (SPI_I2C_ADDR_BASE + 0x2)
#define I2C_CTRL_REG_ADDR (SPI_I2C_ADDR_BASE + 0x6)
#define I2C_DEV_UP_ADDR_REG_ADDR (SPI_I2C_ADDR_BASE + 0x7)
#define I2C_LO_ADDR_REG_ADDR (SPI_I2C_ADDR_BASE + 0x8)
#define I2C_DATA_REG_ADDR (SPI_I2C_ADDR_BASE + 0x9)
#define I2C_CLKFREQ_REG_ADDR (SPI_I2C_ADDR_BASE + 0xa)
#define I2C_STATE_MASK 0x0007
#define I2C_READ_READY_MASK 0x0008
/* There is only one I2C port on the TW2804 that feeds all four GO7007 VIPs
* on the Adlink PCI-MPG24, so access is shared between all of them. */
static DEFINE_MUTEX(adlink_mpg24_i2c_lock);
static int go7007_i2c_xfer(struct go7007 *go, u16 addr, int read,
u16 command, int flags, u8 *data)
{
int i, ret = -1;
u16 val;
if (go->status == STATUS_SHUTDOWN)
return -1;
#ifdef GO7007_I2C_DEBUG
if (read)
printk(KERN_DEBUG "go7007-i2c: reading 0x%02x on 0x%02x\n",
command, addr);
else
printk(KERN_DEBUG
"go7007-i2c: writing 0x%02x to 0x%02x on 0x%02x\n",
*data, command, addr);
#endif
mutex_lock(&go->hw_lock);
if (go->board_id == GO7007_BOARDID_ADLINK_MPG24) {
/* Bridge the I2C port on this GO7007 to the shared bus */
mutex_lock(&adlink_mpg24_i2c_lock);
go7007_write_addr(go, 0x3c82, 0x0020);
}
/* Wait for I2C adapter to be ready */
for (i = 0; i < 10; ++i) {
if (go7007_read_addr(go, STATUS_REG_ADDR, &val) < 0)
goto i2c_done;
if (!(val & I2C_STATE_MASK))
break;
msleep(100);
}
if (i == 10) {
printk(KERN_ERR "go7007-i2c: I2C adapter is hung\n");
goto i2c_done;
}
/* Set target register (command) */
go7007_write_addr(go, I2C_CTRL_REG_ADDR, flags);
go7007_write_addr(go, I2C_LO_ADDR_REG_ADDR, command);
/* If we're writing, send the data and target address and we're done */
if (!read) {
go7007_write_addr(go, I2C_DATA_REG_ADDR, *data);
go7007_write_addr(go, I2C_DEV_UP_ADDR_REG_ADDR,
(addr << 9) | (command >> 8));
ret = 0;
goto i2c_done;
}
/* Otherwise, we're reading. First clear i2c_rx_data_rdy. */
if (go7007_read_addr(go, I2C_DATA_REG_ADDR, &val) < 0)
goto i2c_done;
/* Send the target address plus read flag */
go7007_write_addr(go, I2C_DEV_UP_ADDR_REG_ADDR,
(addr << 9) | 0x0100 | (command >> 8));
/* Wait for i2c_rx_data_rdy */
for (i = 0; i < 10; ++i) {
if (go7007_read_addr(go, STATUS_REG_ADDR, &val) < 0)
goto i2c_done;
if (val & I2C_READ_READY_MASK)
break;
msleep(100);
}
if (i == 10) {
printk(KERN_ERR "go7007-i2c: I2C adapter is hung\n");
goto i2c_done;
}
/* Retrieve the read byte */
if (go7007_read_addr(go, I2C_DATA_REG_ADDR, &val) < 0)
goto i2c_done;
*data = val;
ret = 0;
i2c_done:
if (go->board_id == GO7007_BOARDID_ADLINK_MPG24) {
/* Isolate the I2C port on this GO7007 from the shared bus */
go7007_write_addr(go, 0x3c82, 0x0000);
mutex_unlock(&adlink_mpg24_i2c_lock);
}
mutex_unlock(&go->hw_lock);
return ret;
}
static int go7007_smbus_xfer(struct i2c_adapter *adapter, u16 addr,
unsigned short flags, char read_write,
u8 command, int size, union i2c_smbus_data *data)
{
struct go7007 *go = i2c_get_adapdata(adapter);
if (size != I2C_SMBUS_BYTE_DATA)
return -1;
return go7007_i2c_xfer(go, addr, read_write == I2C_SMBUS_READ, command,
flags & I2C_CLIENT_SCCB ? 0x10 : 0x00, &data->byte);
}
/* VERY LIMITED I2C master xfer function -- only needed because the
* SMBus functions only support 8-bit commands and the SAA7135 uses
* 16-bit commands. The I2C interface on the GO7007, as limited as
* it is, does support this mode. */
static int go7007_i2c_master_xfer(struct i2c_adapter *adapter,
struct i2c_msg msgs[], int num)
{
struct go7007 *go = i2c_get_adapdata(adapter);
int i;
for (i = 0; i < num; ++i) {
/* We can only do two things here -- write three bytes, or
* write two bytes and read one byte. */
if (msgs[i].len == 2) {
if (i + 1 == num || msgs[i].addr != msgs[i + 1].addr ||
(msgs[i].flags & I2C_M_RD) ||
!(msgs[i + 1].flags & I2C_M_RD) ||
msgs[i + 1].len != 1)
return -1;
if (go7007_i2c_xfer(go, msgs[i].addr, 1,
(msgs[i].buf[0] << 8) | msgs[i].buf[1],
0x01, &msgs[i + 1].buf[0]) < 0)
return -1;
++i;
} else if (msgs[i].len == 3) {
if (msgs[i].flags & I2C_M_RD)
return -1;
if (msgs[i].len != 3)
return -1;
if (go7007_i2c_xfer(go, msgs[i].addr, 0,
(msgs[i].buf[0] << 8) | msgs[i].buf[1],
0x01, &msgs[i].buf[2]) < 0)
return -1;
} else
return -1;
}
return 0;
}
static u32 go7007_functionality(struct i2c_adapter *adapter)
{
return I2C_FUNC_SMBUS_BYTE_DATA;
}
static struct i2c_algorithm go7007_algo = {
.smbus_xfer = go7007_smbus_xfer,
.master_xfer = go7007_i2c_master_xfer,
.functionality = go7007_functionality,
};
static struct i2c_adapter go7007_adap_templ = {
.owner = THIS_MODULE,
.name = "WIS GO7007SB",
.algo = &go7007_algo,
};
int go7007_i2c_init(struct go7007 *go)
{
memcpy(&go->i2c_adapter, &go7007_adap_templ,
sizeof(go7007_adap_templ));
go->i2c_adapter.dev.parent = go->dev;
i2c_set_adapdata(&go->i2c_adapter, go);
if (i2c_add_adapter(&go->i2c_adapter) < 0) {
printk(KERN_ERR
"go7007-i2c: error: i2c_add_adapter failed\n");
return -1;
}
return 0;
}
| gpl-2.0 |
sssemil/kernel_sniper-ICS | drivers/staging/go7007/go7007-i2c.c | 4853 | 6374 | /*
* 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/init.h>
#include <linux/delay.h>
#include <linux/sched.h>
#include <linux/list.h>
#include <linux/unistd.h>
#include <linux/time.h>
#include <linux/device.h>
#include <linux/i2c.h>
#include <linux/mutex.h>
#include <linux/uaccess.h>
#include <asm/system.h>
#include "go7007-priv.h"
#include "wis-i2c.h"
/********************* Driver for on-board I2C adapter *********************/
/* #define GO7007_I2C_DEBUG */
#define SPI_I2C_ADDR_BASE 0x1400
#define STATUS_REG_ADDR (SPI_I2C_ADDR_BASE + 0x2)
#define I2C_CTRL_REG_ADDR (SPI_I2C_ADDR_BASE + 0x6)
#define I2C_DEV_UP_ADDR_REG_ADDR (SPI_I2C_ADDR_BASE + 0x7)
#define I2C_LO_ADDR_REG_ADDR (SPI_I2C_ADDR_BASE + 0x8)
#define I2C_DATA_REG_ADDR (SPI_I2C_ADDR_BASE + 0x9)
#define I2C_CLKFREQ_REG_ADDR (SPI_I2C_ADDR_BASE + 0xa)
#define I2C_STATE_MASK 0x0007
#define I2C_READ_READY_MASK 0x0008
/* There is only one I2C port on the TW2804 that feeds all four GO7007 VIPs
* on the Adlink PCI-MPG24, so access is shared between all of them. */
static DEFINE_MUTEX(adlink_mpg24_i2c_lock);
static int go7007_i2c_xfer(struct go7007 *go, u16 addr, int read,
u16 command, int flags, u8 *data)
{
int i, ret = -1;
u16 val;
if (go->status == STATUS_SHUTDOWN)
return -1;
#ifdef GO7007_I2C_DEBUG
if (read)
printk(KERN_DEBUG "go7007-i2c: reading 0x%02x on 0x%02x\n",
command, addr);
else
printk(KERN_DEBUG
"go7007-i2c: writing 0x%02x to 0x%02x on 0x%02x\n",
*data, command, addr);
#endif
mutex_lock(&go->hw_lock);
if (go->board_id == GO7007_BOARDID_ADLINK_MPG24) {
/* Bridge the I2C port on this GO7007 to the shared bus */
mutex_lock(&adlink_mpg24_i2c_lock);
go7007_write_addr(go, 0x3c82, 0x0020);
}
/* Wait for I2C adapter to be ready */
for (i = 0; i < 10; ++i) {
if (go7007_read_addr(go, STATUS_REG_ADDR, &val) < 0)
goto i2c_done;
if (!(val & I2C_STATE_MASK))
break;
msleep(100);
}
if (i == 10) {
printk(KERN_ERR "go7007-i2c: I2C adapter is hung\n");
goto i2c_done;
}
/* Set target register (command) */
go7007_write_addr(go, I2C_CTRL_REG_ADDR, flags);
go7007_write_addr(go, I2C_LO_ADDR_REG_ADDR, command);
/* If we're writing, send the data and target address and we're done */
if (!read) {
go7007_write_addr(go, I2C_DATA_REG_ADDR, *data);
go7007_write_addr(go, I2C_DEV_UP_ADDR_REG_ADDR,
(addr << 9) | (command >> 8));
ret = 0;
goto i2c_done;
}
/* Otherwise, we're reading. First clear i2c_rx_data_rdy. */
if (go7007_read_addr(go, I2C_DATA_REG_ADDR, &val) < 0)
goto i2c_done;
/* Send the target address plus read flag */
go7007_write_addr(go, I2C_DEV_UP_ADDR_REG_ADDR,
(addr << 9) | 0x0100 | (command >> 8));
/* Wait for i2c_rx_data_rdy */
for (i = 0; i < 10; ++i) {
if (go7007_read_addr(go, STATUS_REG_ADDR, &val) < 0)
goto i2c_done;
if (val & I2C_READ_READY_MASK)
break;
msleep(100);
}
if (i == 10) {
printk(KERN_ERR "go7007-i2c: I2C adapter is hung\n");
goto i2c_done;
}
/* Retrieve the read byte */
if (go7007_read_addr(go, I2C_DATA_REG_ADDR, &val) < 0)
goto i2c_done;
*data = val;
ret = 0;
i2c_done:
if (go->board_id == GO7007_BOARDID_ADLINK_MPG24) {
/* Isolate the I2C port on this GO7007 from the shared bus */
go7007_write_addr(go, 0x3c82, 0x0000);
mutex_unlock(&adlink_mpg24_i2c_lock);
}
mutex_unlock(&go->hw_lock);
return ret;
}
static int go7007_smbus_xfer(struct i2c_adapter *adapter, u16 addr,
unsigned short flags, char read_write,
u8 command, int size, union i2c_smbus_data *data)
{
struct go7007 *go = i2c_get_adapdata(adapter);
if (size != I2C_SMBUS_BYTE_DATA)
return -1;
return go7007_i2c_xfer(go, addr, read_write == I2C_SMBUS_READ, command,
flags & I2C_CLIENT_SCCB ? 0x10 : 0x00, &data->byte);
}
/* VERY LIMITED I2C master xfer function -- only needed because the
* SMBus functions only support 8-bit commands and the SAA7135 uses
* 16-bit commands. The I2C interface on the GO7007, as limited as
* it is, does support this mode. */
static int go7007_i2c_master_xfer(struct i2c_adapter *adapter,
struct i2c_msg msgs[], int num)
{
struct go7007 *go = i2c_get_adapdata(adapter);
int i;
for (i = 0; i < num; ++i) {
/* We can only do two things here -- write three bytes, or
* write two bytes and read one byte. */
if (msgs[i].len == 2) {
if (i + 1 == num || msgs[i].addr != msgs[i + 1].addr ||
(msgs[i].flags & I2C_M_RD) ||
!(msgs[i + 1].flags & I2C_M_RD) ||
msgs[i + 1].len != 1)
return -1;
if (go7007_i2c_xfer(go, msgs[i].addr, 1,
(msgs[i].buf[0] << 8) | msgs[i].buf[1],
0x01, &msgs[i + 1].buf[0]) < 0)
return -1;
++i;
} else if (msgs[i].len == 3) {
if (msgs[i].flags & I2C_M_RD)
return -1;
if (msgs[i].len != 3)
return -1;
if (go7007_i2c_xfer(go, msgs[i].addr, 0,
(msgs[i].buf[0] << 8) | msgs[i].buf[1],
0x01, &msgs[i].buf[2]) < 0)
return -1;
} else
return -1;
}
return 0;
}
static u32 go7007_functionality(struct i2c_adapter *adapter)
{
return I2C_FUNC_SMBUS_BYTE_DATA;
}
static struct i2c_algorithm go7007_algo = {
.smbus_xfer = go7007_smbus_xfer,
.master_xfer = go7007_i2c_master_xfer,
.functionality = go7007_functionality,
};
static struct i2c_adapter go7007_adap_templ = {
.owner = THIS_MODULE,
.name = "WIS GO7007SB",
.algo = &go7007_algo,
};
int go7007_i2c_init(struct go7007 *go)
{
memcpy(&go->i2c_adapter, &go7007_adap_templ,
sizeof(go7007_adap_templ));
go->i2c_adapter.dev.parent = go->dev;
i2c_set_adapdata(&go->i2c_adapter, go);
if (i2c_add_adapter(&go->i2c_adapter) < 0) {
printk(KERN_ERR
"go7007-i2c: error: i2c_add_adapter failed\n");
return -1;
}
return 0;
}
| gpl-2.0 |
CAF-MSM8610/kernel-msm | sound/soc/sh/migor.c | 5109 | 5400 | /*
* ALSA SoC driver for Migo-R
*
* Copyright (C) 2009-2010 Guennadi Liakhovetski <g.liakhovetski@gmx.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/clkdev.h>
#include <linux/device.h>
#include <linux/firmware.h>
#include <linux/module.h>
#include <asm/clock.h>
#include <cpu/sh7722.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/soc.h>
#include "../codecs/wm8978.h"
#include "siu.h"
/* Default 8000Hz sampling frequency */
static unsigned long codec_freq = 8000 * 512;
static unsigned int use_count;
/* External clock, sourced from the codec at the SIUMCKB pin */
static unsigned long siumckb_recalc(struct clk *clk)
{
return codec_freq;
}
static struct sh_clk_ops siumckb_clk_ops = {
.recalc = siumckb_recalc,
};
static struct clk siumckb_clk = {
.ops = &siumckb_clk_ops,
.rate = 0, /* initialised at run-time */
};
static struct clk_lookup *siumckb_lookup;
static int migor_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *codec_dai = rtd->codec_dai;
int ret;
unsigned int rate = params_rate(params);
ret = snd_soc_dai_set_sysclk(codec_dai, WM8978_PLL, 13000000,
SND_SOC_CLOCK_IN);
if (ret < 0)
return ret;
ret = snd_soc_dai_set_clkdiv(codec_dai, WM8978_OPCLKRATE, rate * 512);
if (ret < 0)
return ret;
ret = snd_soc_dai_set_fmt(codec_dai, SND_SOC_DAIFMT_NB_IF |
SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_CBS_CFS);
if (ret < 0)
return ret;
ret = snd_soc_dai_set_fmt(rtd->cpu_dai, SND_SOC_DAIFMT_NB_IF |
SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_CBS_CFS);
if (ret < 0)
return ret;
codec_freq = rate * 512;
/*
* This propagates the parent frequency change to children and
* recalculates the frequency table
*/
clk_set_rate(&siumckb_clk, codec_freq);
dev_dbg(codec_dai->dev, "%s: configure %luHz\n", __func__, codec_freq);
ret = snd_soc_dai_set_sysclk(rtd->cpu_dai, SIU_CLKB_EXT,
codec_freq / 2, SND_SOC_CLOCK_IN);
if (!ret)
use_count++;
return ret;
}
static int migor_hw_free(struct snd_pcm_substream *substream)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *codec_dai = rtd->codec_dai;
if (use_count) {
use_count--;
if (!use_count)
snd_soc_dai_set_sysclk(codec_dai, WM8978_PLL, 0,
SND_SOC_CLOCK_IN);
} else {
dev_dbg(codec_dai->dev, "Unbalanced hw_free!\n");
}
return 0;
}
static struct snd_soc_ops migor_dai_ops = {
.hw_params = migor_hw_params,
.hw_free = migor_hw_free,
};
static const struct snd_soc_dapm_widget migor_dapm_widgets[] = {
SND_SOC_DAPM_HP("Headphone", NULL),
SND_SOC_DAPM_MIC("Onboard Microphone", NULL),
SND_SOC_DAPM_MIC("External Microphone", NULL),
};
static const struct snd_soc_dapm_route audio_map[] = {
/* Headphone output connected to LHP/RHP, enable OUT4 for VMID */
{ "Headphone", NULL, "OUT4 VMID" },
{ "OUT4 VMID", NULL, "LHP" },
{ "OUT4 VMID", NULL, "RHP" },
/* On-board microphone */
{ "RMICN", NULL, "Mic Bias" },
{ "RMICP", NULL, "Mic Bias" },
{ "Mic Bias", NULL, "Onboard Microphone" },
/* External microphone */
{ "LMICN", NULL, "Mic Bias" },
{ "LMICP", NULL, "Mic Bias" },
{ "Mic Bias", NULL, "External Microphone" },
};
static int migor_dai_init(struct snd_soc_pcm_runtime *rtd)
{
struct snd_soc_codec *codec = rtd->codec;
struct snd_soc_dapm_context *dapm = &codec->dapm;
snd_soc_dapm_new_controls(dapm, migor_dapm_widgets,
ARRAY_SIZE(migor_dapm_widgets));
snd_soc_dapm_add_routes(dapm, audio_map, ARRAY_SIZE(audio_map));
return 0;
}
/* migor digital audio interface glue - connects codec <--> CPU */
static struct snd_soc_dai_link migor_dai = {
.name = "wm8978",
.stream_name = "WM8978",
.cpu_dai_name = "siu-i2s-dai",
.codec_dai_name = "wm8978-hifi",
.platform_name = "siu-pcm-audio",
.codec_name = "wm8978.0-001a",
.ops = &migor_dai_ops,
.init = migor_dai_init,
};
/* migor audio machine driver */
static struct snd_soc_card snd_soc_migor = {
.name = "Migo-R",
.owner = THIS_MODULE,
.dai_link = &migor_dai,
.num_links = 1,
};
static struct platform_device *migor_snd_device;
static int __init migor_init(void)
{
int ret;
ret = clk_register(&siumckb_clk);
if (ret < 0)
return ret;
siumckb_lookup = clkdev_alloc(&siumckb_clk, "siumckb_clk", NULL);
if (!siumckb_lookup) {
ret = -ENOMEM;
goto eclkdevalloc;
}
clkdev_add(siumckb_lookup);
/* Port number used on this machine: port B */
migor_snd_device = platform_device_alloc("soc-audio", 1);
if (!migor_snd_device) {
ret = -ENOMEM;
goto epdevalloc;
}
platform_set_drvdata(migor_snd_device, &snd_soc_migor);
ret = platform_device_add(migor_snd_device);
if (ret)
goto epdevadd;
return 0;
epdevadd:
platform_device_put(migor_snd_device);
epdevalloc:
clkdev_drop(siumckb_lookup);
eclkdevalloc:
clk_unregister(&siumckb_clk);
return ret;
}
static void __exit migor_exit(void)
{
clkdev_drop(siumckb_lookup);
clk_unregister(&siumckb_clk);
platform_device_unregister(migor_snd_device);
}
module_init(migor_init);
module_exit(migor_exit);
MODULE_AUTHOR("Guennadi Liakhovetski <g.liakhovetski@gmx.de>");
MODULE_DESCRIPTION("ALSA SoC Migor");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
CyanogenMod-E1/android_kernel_sony_msm8610 | net/netfilter/nf_conntrack_amanda.c | 8693 | 6065 | /* Amanda extension for IP connection tracking
*
* (C) 2002 by Brian J. Murrell <netfilter@interlinx.bc.ca>
* based on HW's ip_conntrack_irc.c as well as other 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; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/textsearch.h>
#include <linux/skbuff.h>
#include <linux/in.h>
#include <linux/udp.h>
#include <linux/netfilter.h>
#include <linux/gfp.h>
#include <net/netfilter/nf_conntrack.h>
#include <net/netfilter/nf_conntrack_expect.h>
#include <net/netfilter/nf_conntrack_ecache.h>
#include <net/netfilter/nf_conntrack_helper.h>
#include <linux/netfilter/nf_conntrack_amanda.h>
static unsigned int master_timeout __read_mostly = 300;
static char *ts_algo = "kmp";
MODULE_AUTHOR("Brian J. Murrell <netfilter@interlinx.bc.ca>");
MODULE_DESCRIPTION("Amanda connection tracking module");
MODULE_LICENSE("GPL");
MODULE_ALIAS("ip_conntrack_amanda");
MODULE_ALIAS_NFCT_HELPER("amanda");
module_param(master_timeout, uint, 0600);
MODULE_PARM_DESC(master_timeout, "timeout for the master connection");
module_param(ts_algo, charp, 0400);
MODULE_PARM_DESC(ts_algo, "textsearch algorithm to use (default kmp)");
unsigned int (*nf_nat_amanda_hook)(struct sk_buff *skb,
enum ip_conntrack_info ctinfo,
unsigned int matchoff,
unsigned int matchlen,
struct nf_conntrack_expect *exp)
__read_mostly;
EXPORT_SYMBOL_GPL(nf_nat_amanda_hook);
enum amanda_strings {
SEARCH_CONNECT,
SEARCH_NEWLINE,
SEARCH_DATA,
SEARCH_MESG,
SEARCH_INDEX,
};
static struct {
const char *string;
size_t len;
struct ts_config *ts;
} search[] __read_mostly = {
[SEARCH_CONNECT] = {
.string = "CONNECT ",
.len = 8,
},
[SEARCH_NEWLINE] = {
.string = "\n",
.len = 1,
},
[SEARCH_DATA] = {
.string = "DATA ",
.len = 5,
},
[SEARCH_MESG] = {
.string = "MESG ",
.len = 5,
},
[SEARCH_INDEX] = {
.string = "INDEX ",
.len = 6,
},
};
static int amanda_help(struct sk_buff *skb,
unsigned int protoff,
struct nf_conn *ct,
enum ip_conntrack_info ctinfo)
{
struct ts_state ts;
struct nf_conntrack_expect *exp;
struct nf_conntrack_tuple *tuple;
unsigned int dataoff, start, stop, off, i;
char pbuf[sizeof("65535")], *tmp;
u_int16_t len;
__be16 port;
int ret = NF_ACCEPT;
typeof(nf_nat_amanda_hook) nf_nat_amanda;
/* Only look at packets from the Amanda server */
if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL)
return NF_ACCEPT;
/* increase the UDP timeout of the master connection as replies from
* Amanda clients to the server can be quite delayed */
nf_ct_refresh(ct, skb, master_timeout * HZ);
/* No data? */
dataoff = protoff + sizeof(struct udphdr);
if (dataoff >= skb->len) {
if (net_ratelimit())
printk(KERN_ERR "amanda_help: skblen = %u\n", skb->len);
return NF_ACCEPT;
}
memset(&ts, 0, sizeof(ts));
start = skb_find_text(skb, dataoff, skb->len,
search[SEARCH_CONNECT].ts, &ts);
if (start == UINT_MAX)
goto out;
start += dataoff + search[SEARCH_CONNECT].len;
memset(&ts, 0, sizeof(ts));
stop = skb_find_text(skb, start, skb->len,
search[SEARCH_NEWLINE].ts, &ts);
if (stop == UINT_MAX)
goto out;
stop += start;
for (i = SEARCH_DATA; i <= SEARCH_INDEX; i++) {
memset(&ts, 0, sizeof(ts));
off = skb_find_text(skb, start, stop, search[i].ts, &ts);
if (off == UINT_MAX)
continue;
off += start + search[i].len;
len = min_t(unsigned int, sizeof(pbuf) - 1, stop - off);
if (skb_copy_bits(skb, off, pbuf, len))
break;
pbuf[len] = '\0';
port = htons(simple_strtoul(pbuf, &tmp, 10));
len = tmp - pbuf;
if (port == 0 || len > 5)
break;
exp = nf_ct_expect_alloc(ct);
if (exp == NULL) {
ret = NF_DROP;
goto out;
}
tuple = &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple;
nf_ct_expect_init(exp, NF_CT_EXPECT_CLASS_DEFAULT,
nf_ct_l3num(ct),
&tuple->src.u3, &tuple->dst.u3,
IPPROTO_TCP, NULL, &port);
nf_nat_amanda = rcu_dereference(nf_nat_amanda_hook);
if (nf_nat_amanda && ct->status & IPS_NAT_MASK)
ret = nf_nat_amanda(skb, ctinfo, off - dataoff,
len, exp);
else if (nf_ct_expect_related(exp) != 0)
ret = NF_DROP;
nf_ct_expect_put(exp);
}
out:
return ret;
}
static const struct nf_conntrack_expect_policy amanda_exp_policy = {
.max_expected = 3,
.timeout = 180,
};
static struct nf_conntrack_helper amanda_helper[2] __read_mostly = {
{
.name = "amanda",
.me = THIS_MODULE,
.help = amanda_help,
.tuple.src.l3num = AF_INET,
.tuple.src.u.udp.port = cpu_to_be16(10080),
.tuple.dst.protonum = IPPROTO_UDP,
.expect_policy = &amanda_exp_policy,
},
{
.name = "amanda",
.me = THIS_MODULE,
.help = amanda_help,
.tuple.src.l3num = AF_INET6,
.tuple.src.u.udp.port = cpu_to_be16(10080),
.tuple.dst.protonum = IPPROTO_UDP,
.expect_policy = &amanda_exp_policy,
},
};
static void __exit nf_conntrack_amanda_fini(void)
{
int i;
nf_conntrack_helper_unregister(&amanda_helper[0]);
nf_conntrack_helper_unregister(&amanda_helper[1]);
for (i = 0; i < ARRAY_SIZE(search); i++)
textsearch_destroy(search[i].ts);
}
static int __init nf_conntrack_amanda_init(void)
{
int ret, i;
for (i = 0; i < ARRAY_SIZE(search); i++) {
search[i].ts = textsearch_prepare(ts_algo, search[i].string,
search[i].len,
GFP_KERNEL, TS_AUTOLOAD);
if (IS_ERR(search[i].ts)) {
ret = PTR_ERR(search[i].ts);
goto err1;
}
}
ret = nf_conntrack_helper_register(&amanda_helper[0]);
if (ret < 0)
goto err1;
ret = nf_conntrack_helper_register(&amanda_helper[1]);
if (ret < 0)
goto err2;
return 0;
err2:
nf_conntrack_helper_unregister(&amanda_helper[0]);
err1:
while (--i >= 0)
textsearch_destroy(search[i].ts);
return ret;
}
module_init(nf_conntrack_amanda_init);
module_exit(nf_conntrack_amanda_fini);
| gpl-2.0 |
MoKee/android_kernel_oppo_n3 | drivers/i2c/busses/i2c-nforce2-s4985.c | 10229 | 7464 | /*
* i2c-nforce2-s4985.c - i2c-nforce2 extras for the Tyan S4985 motherboard
*
* Copyright (C) 2008 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.
*/
/*
* We select the channels by sending commands to the Philips
* PCA9556 chip at I2C address 0x18. The main adapter is used for
* the non-multiplexed part of the bus, and 4 virtual adapters
* are defined for the multiplexed addresses: 0x50-0x53 (memory
* module EEPROM) located on channels 1-4. We define one virtual
* adapter per CPU, which corresponds to one multiplexed channel:
* CPU0: virtual adapter 1, channel 1
* CPU1: virtual adapter 2, channel 2
* CPU2: virtual adapter 3, channel 3
* CPU3: virtual adapter 4, channel 4
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/i2c.h>
#include <linux/mutex.h>
extern struct i2c_adapter *nforce2_smbus;
static struct i2c_adapter *s4985_adapter;
static struct i2c_algorithm *s4985_algo;
/* Wrapper access functions for multiplexed SMBus */
static DEFINE_MUTEX(nforce2_lock);
static s32 nforce2_access_virt0(struct i2c_adapter *adap, u16 addr,
unsigned short flags, char read_write,
u8 command, int size,
union i2c_smbus_data *data)
{
int error;
/* We exclude the multiplexed addresses */
if ((addr & 0xfc) == 0x50 || (addr & 0xfc) == 0x30
|| addr == 0x18)
return -ENXIO;
mutex_lock(&nforce2_lock);
error = nforce2_smbus->algo->smbus_xfer(adap, addr, flags, read_write,
command, size, data);
mutex_unlock(&nforce2_lock);
return error;
}
/* We remember the last used channels combination so as to only switch
channels when it is really needed. This greatly reduces the SMBus
overhead, but also assumes that nobody will be writing to the PCA9556
in our back. */
static u8 last_channels;
static inline s32 nforce2_access_channel(struct i2c_adapter *adap, u16 addr,
unsigned short flags, char read_write,
u8 command, int size,
union i2c_smbus_data *data,
u8 channels)
{
int error;
/* We exclude the non-multiplexed addresses */
if ((addr & 0xfc) != 0x50 && (addr & 0xfc) != 0x30)
return -ENXIO;
mutex_lock(&nforce2_lock);
if (last_channels != channels) {
union i2c_smbus_data mplxdata;
mplxdata.byte = channels;
error = nforce2_smbus->algo->smbus_xfer(adap, 0x18, 0,
I2C_SMBUS_WRITE, 0x01,
I2C_SMBUS_BYTE_DATA,
&mplxdata);
if (error)
goto UNLOCK;
last_channels = channels;
}
error = nforce2_smbus->algo->smbus_xfer(adap, addr, flags, read_write,
command, size, data);
UNLOCK:
mutex_unlock(&nforce2_lock);
return error;
}
static s32 nforce2_access_virt1(struct i2c_adapter *adap, u16 addr,
unsigned short flags, char read_write,
u8 command, int size,
union i2c_smbus_data *data)
{
/* CPU0: channel 1 enabled */
return nforce2_access_channel(adap, addr, flags, read_write, command,
size, data, 0x02);
}
static s32 nforce2_access_virt2(struct i2c_adapter *adap, u16 addr,
unsigned short flags, char read_write,
u8 command, int size,
union i2c_smbus_data *data)
{
/* CPU1: channel 2 enabled */
return nforce2_access_channel(adap, addr, flags, read_write, command,
size, data, 0x04);
}
static s32 nforce2_access_virt3(struct i2c_adapter *adap, u16 addr,
unsigned short flags, char read_write,
u8 command, int size,
union i2c_smbus_data *data)
{
/* CPU2: channel 3 enabled */
return nforce2_access_channel(adap, addr, flags, read_write, command,
size, data, 0x08);
}
static s32 nforce2_access_virt4(struct i2c_adapter *adap, u16 addr,
unsigned short flags, char read_write,
u8 command, int size,
union i2c_smbus_data *data)
{
/* CPU3: channel 4 enabled */
return nforce2_access_channel(adap, addr, flags, read_write, command,
size, data, 0x10);
}
static int __init nforce2_s4985_init(void)
{
int i, error;
union i2c_smbus_data ioconfig;
if (!nforce2_smbus)
return -ENODEV;
/* Configure the PCA9556 multiplexer */
ioconfig.byte = 0x00; /* All I/O to output mode */
error = i2c_smbus_xfer(nforce2_smbus, 0x18, 0, I2C_SMBUS_WRITE, 0x03,
I2C_SMBUS_BYTE_DATA, &ioconfig);
if (error) {
dev_err(&nforce2_smbus->dev, "PCA9556 configuration failed\n");
error = -EIO;
goto ERROR0;
}
/* Unregister physical bus */
error = i2c_del_adapter(nforce2_smbus);
if (error) {
dev_err(&nforce2_smbus->dev, "Physical bus removal failed\n");
goto ERROR0;
}
printk(KERN_INFO "Enabling SMBus multiplexing for Tyan S4985\n");
/* Define the 5 virtual adapters and algorithms structures */
s4985_adapter = kzalloc(5 * sizeof(struct i2c_adapter), GFP_KERNEL);
if (!s4985_adapter) {
error = -ENOMEM;
goto ERROR1;
}
s4985_algo = kzalloc(5 * sizeof(struct i2c_algorithm), GFP_KERNEL);
if (!s4985_algo) {
error = -ENOMEM;
goto ERROR2;
}
/* Fill in the new structures */
s4985_algo[0] = *(nforce2_smbus->algo);
s4985_algo[0].smbus_xfer = nforce2_access_virt0;
s4985_adapter[0] = *nforce2_smbus;
s4985_adapter[0].algo = s4985_algo;
s4985_adapter[0].dev.parent = nforce2_smbus->dev.parent;
for (i = 1; i < 5; i++) {
s4985_algo[i] = *(nforce2_smbus->algo);
s4985_adapter[i] = *nforce2_smbus;
snprintf(s4985_adapter[i].name, sizeof(s4985_adapter[i].name),
"SMBus nForce2 adapter (CPU%d)", i - 1);
s4985_adapter[i].algo = s4985_algo + i;
s4985_adapter[i].dev.parent = nforce2_smbus->dev.parent;
}
s4985_algo[1].smbus_xfer = nforce2_access_virt1;
s4985_algo[2].smbus_xfer = nforce2_access_virt2;
s4985_algo[3].smbus_xfer = nforce2_access_virt3;
s4985_algo[4].smbus_xfer = nforce2_access_virt4;
/* Register virtual adapters */
for (i = 0; i < 5; i++) {
error = i2c_add_adapter(s4985_adapter + i);
if (error) {
printk(KERN_ERR "i2c-nforce2-s4985: "
"Virtual adapter %d registration "
"failed, module not inserted\n", i);
for (i--; i >= 0; i--)
i2c_del_adapter(s4985_adapter + i);
goto ERROR3;
}
}
return 0;
ERROR3:
kfree(s4985_algo);
s4985_algo = NULL;
ERROR2:
kfree(s4985_adapter);
s4985_adapter = NULL;
ERROR1:
/* Restore physical bus */
i2c_add_adapter(nforce2_smbus);
ERROR0:
return error;
}
static void __exit nforce2_s4985_exit(void)
{
if (s4985_adapter) {
int i;
for (i = 0; i < 5; i++)
i2c_del_adapter(s4985_adapter+i);
kfree(s4985_adapter);
s4985_adapter = NULL;
}
kfree(s4985_algo);
s4985_algo = NULL;
/* Restore physical bus */
if (i2c_add_adapter(nforce2_smbus))
printk(KERN_ERR "i2c-nforce2-s4985: "
"Physical bus restoration failed\n");
}
MODULE_AUTHOR("Jean Delvare <khali@linux-fr.org>");
MODULE_DESCRIPTION("S4985 SMBus multiplexing");
MODULE_LICENSE("GPL");
module_init(nforce2_s4985_init);
module_exit(nforce2_s4985_exit);
| gpl-2.0 |
cphelps76/DEMENTEDElite_kernel_jf | crypto/michael_mic.c | 12277 | 3701 | /*
* Cryptographic API
*
* Michael MIC (IEEE 802.11i/TKIP) keyed digest
*
* Copyright (c) 2004 Jouni Malinen <j@w1.fi>
*
* 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 <crypto/internal/hash.h>
#include <asm/byteorder.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/string.h>
#include <linux/types.h>
struct michael_mic_ctx {
u32 l, r;
};
struct michael_mic_desc_ctx {
u8 pending[4];
size_t pending_len;
u32 l, r;
};
static inline u32 xswap(u32 val)
{
return ((val & 0x00ff00ff) << 8) | ((val & 0xff00ff00) >> 8);
}
#define michael_block(l, r) \
do { \
r ^= rol32(l, 17); \
l += r; \
r ^= xswap(l); \
l += r; \
r ^= rol32(l, 3); \
l += r; \
r ^= ror32(l, 2); \
l += r; \
} while (0)
static int michael_init(struct shash_desc *desc)
{
struct michael_mic_desc_ctx *mctx = shash_desc_ctx(desc);
struct michael_mic_ctx *ctx = crypto_shash_ctx(desc->tfm);
mctx->pending_len = 0;
mctx->l = ctx->l;
mctx->r = ctx->r;
return 0;
}
static int michael_update(struct shash_desc *desc, const u8 *data,
unsigned int len)
{
struct michael_mic_desc_ctx *mctx = shash_desc_ctx(desc);
const __le32 *src;
if (mctx->pending_len) {
int flen = 4 - mctx->pending_len;
if (flen > len)
flen = len;
memcpy(&mctx->pending[mctx->pending_len], data, flen);
mctx->pending_len += flen;
data += flen;
len -= flen;
if (mctx->pending_len < 4)
return 0;
src = (const __le32 *)mctx->pending;
mctx->l ^= le32_to_cpup(src);
michael_block(mctx->l, mctx->r);
mctx->pending_len = 0;
}
src = (const __le32 *)data;
while (len >= 4) {
mctx->l ^= le32_to_cpup(src++);
michael_block(mctx->l, mctx->r);
len -= 4;
}
if (len > 0) {
mctx->pending_len = len;
memcpy(mctx->pending, src, len);
}
return 0;
}
static int michael_final(struct shash_desc *desc, u8 *out)
{
struct michael_mic_desc_ctx *mctx = shash_desc_ctx(desc);
u8 *data = mctx->pending;
__le32 *dst = (__le32 *)out;
/* Last block and padding (0x5a, 4..7 x 0) */
switch (mctx->pending_len) {
case 0:
mctx->l ^= 0x5a;
break;
case 1:
mctx->l ^= data[0] | 0x5a00;
break;
case 2:
mctx->l ^= data[0] | (data[1] << 8) | 0x5a0000;
break;
case 3:
mctx->l ^= data[0] | (data[1] << 8) | (data[2] << 16) |
0x5a000000;
break;
}
michael_block(mctx->l, mctx->r);
/* l ^= 0; */
michael_block(mctx->l, mctx->r);
dst[0] = cpu_to_le32(mctx->l);
dst[1] = cpu_to_le32(mctx->r);
return 0;
}
static int michael_setkey(struct crypto_shash *tfm, const u8 *key,
unsigned int keylen)
{
struct michael_mic_ctx *mctx = crypto_shash_ctx(tfm);
const __le32 *data = (const __le32 *)key;
if (keylen != 8) {
crypto_shash_set_flags(tfm, CRYPTO_TFM_RES_BAD_KEY_LEN);
return -EINVAL;
}
mctx->l = le32_to_cpu(data[0]);
mctx->r = le32_to_cpu(data[1]);
return 0;
}
static struct shash_alg alg = {
.digestsize = 8,
.setkey = michael_setkey,
.init = michael_init,
.update = michael_update,
.final = michael_final,
.descsize = sizeof(struct michael_mic_desc_ctx),
.base = {
.cra_name = "michael_mic",
.cra_blocksize = 8,
.cra_alignmask = 3,
.cra_ctxsize = sizeof(struct michael_mic_ctx),
.cra_module = THIS_MODULE,
}
};
static int __init michael_mic_init(void)
{
return crypto_register_shash(&alg);
}
static void __exit michael_mic_exit(void)
{
crypto_unregister_shash(&alg);
}
module_init(michael_mic_init);
module_exit(michael_mic_exit);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("Michael MIC");
MODULE_AUTHOR("Jouni Malinen <j@w1.fi>");
| gpl-2.0 |
h8rift/android_kernel_htc_msm8960-evita | drivers/macintosh/macio_sysfs.c | 13045 | 1572 | #include <linux/kernel.h>
#include <linux/stat.h>
#include <asm/macio.h>
#define macio_config_of_attr(field, format_string) \
static ssize_t \
field##_show (struct device *dev, struct device_attribute *attr, \
char *buf) \
{ \
struct macio_dev *mdev = to_macio_device (dev); \
return sprintf (buf, format_string, mdev->ofdev.dev.of_node->field); \
}
static ssize_t
compatible_show (struct device *dev, struct device_attribute *attr, char *buf)
{
struct platform_device *of;
const char *compat;
int cplen;
int length = 0;
of = &to_macio_device (dev)->ofdev;
compat = of_get_property(of->dev.of_node, "compatible", &cplen);
if (!compat) {
*buf = '\0';
return 0;
}
while (cplen > 0) {
int l;
length += sprintf (buf, "%s\n", compat);
buf += length;
l = strlen (compat) + 1;
compat += l;
cplen -= l;
}
return length;
}
static ssize_t modalias_show (struct device *dev, struct device_attribute *attr,
char *buf)
{
int len = of_device_get_modalias(dev, buf, PAGE_SIZE - 2);
buf[len] = '\n';
buf[len+1] = 0;
return len+1;
}
static ssize_t devspec_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct platform_device *ofdev;
ofdev = to_platform_device(dev);
return sprintf(buf, "%s\n", ofdev->dev.of_node->full_name);
}
macio_config_of_attr (name, "%s\n");
macio_config_of_attr (type, "%s\n");
struct device_attribute macio_dev_attrs[] = {
__ATTR_RO(name),
__ATTR_RO(type),
__ATTR_RO(compatible),
__ATTR_RO(modalias),
__ATTR_RO(devspec),
__ATTR_NULL
};
| gpl-2.0 |
MoKee/android_kernel_oppo_find5 | arch/m68k/lib/checksum.c | 14069 | 10633 | /*
* INET An implementation of the TCP/IP protocol suite for the LINUX
* operating system. INET is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* IP/TCP/UDP checksumming routines
*
* Authors: Jorge Cwik, <jorge@laser.satlink.net>
* Arnt Gulbrandsen, <agulbra@nvg.unit.no>
* Tom May, <ftom@netcom.com>
* Andreas Schwab, <schwab@issan.informatik.uni-dortmund.de>
* Lots of code moved from tcp.c and ip.c; see those files
* for more names.
*
* 03/02/96 Jes Sorensen, Andreas Schwab, Roman Hodek:
* Fixed some nasty bugs, causing some horrible crashes.
* A: At some points, the sum (%0) was used as
* length-counter instead of the length counter
* (%1). Thanks to Roman Hodek for pointing this out.
* B: GCC seems to mess up if one uses too many
* data-registers to hold input values and one tries to
* specify d0 and d1 as scratch registers. Letting gcc
* choose these registers itself solves the problem.
*
* 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.
*
* 1998/8/31 Andreas Schwab:
* Zero out rest of buffer on exception in
* csum_partial_copy_from_user.
*/
#include <linux/module.h>
#include <net/checksum.h>
/*
* computes a partial checksum, e.g. for TCP/UDP fragments
*/
__wsum csum_partial(const void *buff, int len, __wsum sum)
{
unsigned long tmp1, tmp2;
/*
* Experiments with ethernet and slip connections show that buff
* is aligned on either a 2-byte or 4-byte boundary.
*/
__asm__("movel %2,%3\n\t"
"btst #1,%3\n\t" /* Check alignment */
"jeq 2f\n\t"
"subql #2,%1\n\t" /* buff%4==2: treat first word */
"jgt 1f\n\t"
"addql #2,%1\n\t" /* len was == 2, treat only rest */
"jra 4f\n"
"1:\t"
"addw %2@+,%0\n\t" /* add first word to sum */
"clrl %3\n\t"
"addxl %3,%0\n" /* add X bit */
"2:\t"
/* unrolled loop for the main part: do 8 longs at once */
"movel %1,%3\n\t" /* save len in tmp1 */
"lsrl #5,%1\n\t" /* len/32 */
"jeq 2f\n\t" /* not enough... */
"subql #1,%1\n"
"1:\t"
"movel %2@+,%4\n\t"
"addxl %4,%0\n\t"
"movel %2@+,%4\n\t"
"addxl %4,%0\n\t"
"movel %2@+,%4\n\t"
"addxl %4,%0\n\t"
"movel %2@+,%4\n\t"
"addxl %4,%0\n\t"
"movel %2@+,%4\n\t"
"addxl %4,%0\n\t"
"movel %2@+,%4\n\t"
"addxl %4,%0\n\t"
"movel %2@+,%4\n\t"
"addxl %4,%0\n\t"
"movel %2@+,%4\n\t"
"addxl %4,%0\n\t"
"dbra %1,1b\n\t"
"clrl %4\n\t"
"addxl %4,%0\n\t" /* add X bit */
"clrw %1\n\t"
"subql #1,%1\n\t"
"jcc 1b\n"
"2:\t"
"movel %3,%1\n\t" /* restore len from tmp1 */
"andw #0x1c,%3\n\t" /* number of rest longs */
"jeq 4f\n\t"
"lsrw #2,%3\n\t"
"subqw #1,%3\n"
"3:\t"
/* loop for rest longs */
"movel %2@+,%4\n\t"
"addxl %4,%0\n\t"
"dbra %3,3b\n\t"
"clrl %4\n\t"
"addxl %4,%0\n" /* add X bit */
"4:\t"
/* now check for rest bytes that do not fit into longs */
"andw #3,%1\n\t"
"jeq 7f\n\t"
"clrl %4\n\t" /* clear tmp2 for rest bytes */
"subqw #2,%1\n\t"
"jlt 5f\n\t"
"movew %2@+,%4\n\t" /* have rest >= 2: get word */
"swap %4\n\t" /* into bits 16..31 */
"tstw %1\n\t" /* another byte? */
"jeq 6f\n"
"5:\t"
"moveb %2@,%4\n\t" /* have odd rest: get byte */
"lslw #8,%4\n\t" /* into bits 8..15; 16..31 untouched */
"6:\t"
"addl %4,%0\n\t" /* now add rest long to sum */
"clrl %4\n\t"
"addxl %4,%0\n" /* add X bit */
"7:\t"
: "=d" (sum), "=d" (len), "=a" (buff),
"=&d" (tmp1), "=&d" (tmp2)
: "0" (sum), "1" (len), "2" (buff)
);
return(sum);
}
EXPORT_SYMBOL(csum_partial);
/*
* copy from user space while checksumming, with exception handling.
*/
__wsum
csum_partial_copy_from_user(const void __user *src, void *dst,
int len, __wsum sum, int *csum_err)
{
/*
* GCC doesn't like more than 10 operands for the asm
* statements so we have to use tmp2 for the error
* code.
*/
unsigned long tmp1, tmp2;
__asm__("movel %2,%4\n\t"
"btst #1,%4\n\t" /* Check alignment */
"jeq 2f\n\t"
"subql #2,%1\n\t" /* buff%4==2: treat first word */
"jgt 1f\n\t"
"addql #2,%1\n\t" /* len was == 2, treat only rest */
"jra 4f\n"
"1:\n"
"10:\t"
"movesw %2@+,%4\n\t" /* add first word to sum */
"addw %4,%0\n\t"
"movew %4,%3@+\n\t"
"clrl %4\n\t"
"addxl %4,%0\n" /* add X bit */
"2:\t"
/* unrolled loop for the main part: do 8 longs at once */
"movel %1,%4\n\t" /* save len in tmp1 */
"lsrl #5,%1\n\t" /* len/32 */
"jeq 2f\n\t" /* not enough... */
"subql #1,%1\n"
"1:\n"
"11:\t"
"movesl %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"12:\t"
"movesl %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"13:\t"
"movesl %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"14:\t"
"movesl %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"15:\t"
"movesl %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"16:\t"
"movesl %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"17:\t"
"movesl %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"18:\t"
"movesl %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"dbra %1,1b\n\t"
"clrl %5\n\t"
"addxl %5,%0\n\t" /* add X bit */
"clrw %1\n\t"
"subql #1,%1\n\t"
"jcc 1b\n"
"2:\t"
"movel %4,%1\n\t" /* restore len from tmp1 */
"andw #0x1c,%4\n\t" /* number of rest longs */
"jeq 4f\n\t"
"lsrw #2,%4\n\t"
"subqw #1,%4\n"
"3:\n"
/* loop for rest longs */
"19:\t"
"movesl %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"dbra %4,3b\n\t"
"clrl %5\n\t"
"addxl %5,%0\n" /* add X bit */
"4:\t"
/* now check for rest bytes that do not fit into longs */
"andw #3,%1\n\t"
"jeq 7f\n\t"
"clrl %5\n\t" /* clear tmp2 for rest bytes */
"subqw #2,%1\n\t"
"jlt 5f\n\t"
"20:\t"
"movesw %2@+,%5\n\t" /* have rest >= 2: get word */
"movew %5,%3@+\n\t"
"swap %5\n\t" /* into bits 16..31 */
"tstw %1\n\t" /* another byte? */
"jeq 6f\n"
"5:\n"
"21:\t"
"movesb %2@,%5\n\t" /* have odd rest: get byte */
"moveb %5,%3@+\n\t"
"lslw #8,%5\n\t" /* into bits 8..15; 16..31 untouched */
"6:\t"
"addl %5,%0\n\t" /* now add rest long to sum */
"clrl %5\n\t"
"addxl %5,%0\n\t" /* add X bit */
"7:\t"
"clrl %5\n" /* no error - clear return value */
"8:\n"
".section .fixup,\"ax\"\n"
".even\n"
/* If any exception occurs zero out the rest.
Similarities with the code above are intentional :-) */
"90:\t"
"clrw %3@+\n\t"
"movel %1,%4\n\t"
"lsrl #5,%1\n\t"
"jeq 1f\n\t"
"subql #1,%1\n"
"91:\t"
"clrl %3@+\n"
"92:\t"
"clrl %3@+\n"
"93:\t"
"clrl %3@+\n"
"94:\t"
"clrl %3@+\n"
"95:\t"
"clrl %3@+\n"
"96:\t"
"clrl %3@+\n"
"97:\t"
"clrl %3@+\n"
"98:\t"
"clrl %3@+\n\t"
"dbra %1,91b\n\t"
"clrw %1\n\t"
"subql #1,%1\n\t"
"jcc 91b\n"
"1:\t"
"movel %4,%1\n\t"
"andw #0x1c,%4\n\t"
"jeq 1f\n\t"
"lsrw #2,%4\n\t"
"subqw #1,%4\n"
"99:\t"
"clrl %3@+\n\t"
"dbra %4,99b\n\t"
"1:\t"
"andw #3,%1\n\t"
"jeq 9f\n"
"100:\t"
"clrw %3@+\n\t"
"tstw %1\n\t"
"jeq 9f\n"
"101:\t"
"clrb %3@+\n"
"9:\t"
#define STR(X) STR1(X)
#define STR1(X) #X
"moveq #-" STR(EFAULT) ",%5\n\t"
"jra 8b\n"
".previous\n"
".section __ex_table,\"a\"\n"
".long 10b,90b\n"
".long 11b,91b\n"
".long 12b,92b\n"
".long 13b,93b\n"
".long 14b,94b\n"
".long 15b,95b\n"
".long 16b,96b\n"
".long 17b,97b\n"
".long 18b,98b\n"
".long 19b,99b\n"
".long 20b,100b\n"
".long 21b,101b\n"
".previous"
: "=d" (sum), "=d" (len), "=a" (src), "=a" (dst),
"=&d" (tmp1), "=d" (tmp2)
: "0" (sum), "1" (len), "2" (src), "3" (dst)
);
*csum_err = tmp2;
return(sum);
}
EXPORT_SYMBOL(csum_partial_copy_from_user);
/*
* copy from kernel space while checksumming, otherwise like csum_partial
*/
__wsum
csum_partial_copy_nocheck(const void *src, void *dst, int len, __wsum sum)
{
unsigned long tmp1, tmp2;
__asm__("movel %2,%4\n\t"
"btst #1,%4\n\t" /* Check alignment */
"jeq 2f\n\t"
"subql #2,%1\n\t" /* buff%4==2: treat first word */
"jgt 1f\n\t"
"addql #2,%1\n\t" /* len was == 2, treat only rest */
"jra 4f\n"
"1:\t"
"movew %2@+,%4\n\t" /* add first word to sum */
"addw %4,%0\n\t"
"movew %4,%3@+\n\t"
"clrl %4\n\t"
"addxl %4,%0\n" /* add X bit */
"2:\t"
/* unrolled loop for the main part: do 8 longs at once */
"movel %1,%4\n\t" /* save len in tmp1 */
"lsrl #5,%1\n\t" /* len/32 */
"jeq 2f\n\t" /* not enough... */
"subql #1,%1\n"
"1:\t"
"movel %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"movel %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"movel %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"movel %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"movel %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"movel %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"movel %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"movel %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"dbra %1,1b\n\t"
"clrl %5\n\t"
"addxl %5,%0\n\t" /* add X bit */
"clrw %1\n\t"
"subql #1,%1\n\t"
"jcc 1b\n"
"2:\t"
"movel %4,%1\n\t" /* restore len from tmp1 */
"andw #0x1c,%4\n\t" /* number of rest longs */
"jeq 4f\n\t"
"lsrw #2,%4\n\t"
"subqw #1,%4\n"
"3:\t"
/* loop for rest longs */
"movel %2@+,%5\n\t"
"addxl %5,%0\n\t"
"movel %5,%3@+\n\t"
"dbra %4,3b\n\t"
"clrl %5\n\t"
"addxl %5,%0\n" /* add X bit */
"4:\t"
/* now check for rest bytes that do not fit into longs */
"andw #3,%1\n\t"
"jeq 7f\n\t"
"clrl %5\n\t" /* clear tmp2 for rest bytes */
"subqw #2,%1\n\t"
"jlt 5f\n\t"
"movew %2@+,%5\n\t" /* have rest >= 2: get word */
"movew %5,%3@+\n\t"
"swap %5\n\t" /* into bits 16..31 */
"tstw %1\n\t" /* another byte? */
"jeq 6f\n"
"5:\t"
"moveb %2@,%5\n\t" /* have odd rest: get byte */
"moveb %5,%3@+\n\t"
"lslw #8,%5\n" /* into bits 8..15; 16..31 untouched */
"6:\t"
"addl %5,%0\n\t" /* now add rest long to sum */
"clrl %5\n\t"
"addxl %5,%0\n" /* add X bit */
"7:\t"
: "=d" (sum), "=d" (len), "=a" (src), "=a" (dst),
"=&d" (tmp1), "=&d" (tmp2)
: "0" (sum), "1" (len), "2" (src), "3" (dst)
);
return(sum);
}
EXPORT_SYMBOL(csum_partial_copy_nocheck);
| gpl-2.0 |
shizhai/wprobe | build_dir/target-mips_r2_uClibc-0.9.33.2/linux-ar71xx_generic/u-boot-nbg460n_550n_550nh/u-boot-2010.03/cpu/arm926ejs/davinci/dm646x.c | 246 | 1153 | /*
* SoC-specific code for TMS320DM646x chips
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <asm/arch/hardware.h>
void davinci_enable_uart0(void)
{
lpsc_on(DAVINCI_DM646X_LPSC_UART0);
}
#ifdef CONFIG_DRIVER_TI_EMAC
void davinci_enable_emac(void)
{
lpsc_on(DAVINCI_DM646X_LPSC_EMAC);
}
#endif
#ifdef CONFIG_DRIVER_DAVINCI_I2C
void davinci_enable_i2c(void)
{
lpsc_on(DAVINCI_DM646X_LPSC_I2C);
}
#endif
| gpl-2.0 |
matnyman/xhci | drivers/xen/xen-acpi-memhotplug.c | 246 | 12093 | /*
* Copyright (C) 2012 Intel Corporation
* Author: Liu Jinsong <jinsong.liu@intel.com>
* Author: Jiang Yunhong <yunhong.jiang@intel.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
* NON INFRINGEMENT. See the GNU General Public License for more
* details.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/acpi.h>
#include <xen/acpi.h>
#include <xen/interface/platform.h>
#include <asm/xen/hypercall.h>
#define PREFIX "ACPI:xen_memory_hotplug:"
struct acpi_memory_info {
struct list_head list;
u64 start_addr; /* Memory Range start physical addr */
u64 length; /* Memory Range length */
unsigned short caching; /* memory cache attribute */
unsigned short write_protect; /* memory read/write attribute */
/* copied from buffer getting from _CRS */
unsigned int enabled:1;
};
struct acpi_memory_device {
struct acpi_device *device;
struct list_head res_list;
};
static bool acpi_hotmem_initialized __read_mostly;
static int xen_hotadd_memory(int pxm, struct acpi_memory_info *info)
{
int rc;
struct xen_platform_op op;
op.cmd = XENPF_mem_hotadd;
op.u.mem_add.spfn = info->start_addr >> PAGE_SHIFT;
op.u.mem_add.epfn = (info->start_addr + info->length) >> PAGE_SHIFT;
op.u.mem_add.pxm = pxm;
rc = HYPERVISOR_dom0_op(&op);
if (rc)
pr_err(PREFIX "Xen Hotplug Memory Add failed on "
"0x%lx -> 0x%lx, _PXM: %d, error: %d\n",
(unsigned long)info->start_addr,
(unsigned long)(info->start_addr + info->length),
pxm, rc);
return rc;
}
static int xen_acpi_memory_enable_device(struct acpi_memory_device *mem_device)
{
int pxm, result;
int num_enabled = 0;
struct acpi_memory_info *info;
if (!mem_device)
return -EINVAL;
pxm = xen_acpi_get_pxm(mem_device->device->handle);
if (pxm < 0)
return pxm;
list_for_each_entry(info, &mem_device->res_list, list) {
if (info->enabled) { /* just sanity check...*/
num_enabled++;
continue;
}
if (!info->length)
continue;
result = xen_hotadd_memory(pxm, info);
if (result)
continue;
info->enabled = 1;
num_enabled++;
}
if (!num_enabled)
return -ENODEV;
return 0;
}
static acpi_status
acpi_memory_get_resource(struct acpi_resource *resource, void *context)
{
struct acpi_memory_device *mem_device = context;
struct acpi_resource_address64 address64;
struct acpi_memory_info *info, *new;
acpi_status status;
status = acpi_resource_to_address64(resource, &address64);
if (ACPI_FAILURE(status) ||
(address64.resource_type != ACPI_MEMORY_RANGE))
return AE_OK;
list_for_each_entry(info, &mem_device->res_list, list) {
if ((info->caching == address64.info.mem.caching) &&
(info->write_protect == address64.info.mem.write_protect) &&
(info->start_addr + info->length == address64.minimum)) {
info->length += address64.address_length;
return AE_OK;
}
}
new = kzalloc(sizeof(struct acpi_memory_info), GFP_KERNEL);
if (!new)
return AE_ERROR;
INIT_LIST_HEAD(&new->list);
new->caching = address64.info.mem.caching;
new->write_protect = address64.info.mem.write_protect;
new->start_addr = address64.minimum;
new->length = address64.address_length;
list_add_tail(&new->list, &mem_device->res_list);
return AE_OK;
}
static int
acpi_memory_get_device_resources(struct acpi_memory_device *mem_device)
{
acpi_status status;
struct acpi_memory_info *info, *n;
if (!list_empty(&mem_device->res_list))
return 0;
status = acpi_walk_resources(mem_device->device->handle,
METHOD_NAME__CRS, acpi_memory_get_resource, mem_device);
if (ACPI_FAILURE(status)) {
list_for_each_entry_safe(info, n, &mem_device->res_list, list)
kfree(info);
INIT_LIST_HEAD(&mem_device->res_list);
return -EINVAL;
}
return 0;
}
static int acpi_memory_get_device(acpi_handle handle,
struct acpi_memory_device **mem_device)
{
struct acpi_device *device = NULL;
int result = 0;
acpi_scan_lock_acquire();
acpi_bus_get_device(handle, &device);
if (acpi_device_enumerated(device))
goto end;
/*
* Now add the notified device. This creates the acpi_device
* and invokes .add function
*/
result = acpi_bus_scan(handle);
if (result) {
pr_warn(PREFIX "ACPI namespace scan failed\n");
result = -EINVAL;
goto out;
}
device = NULL;
acpi_bus_get_device(handle, &device);
if (!acpi_device_enumerated(device)) {
pr_warn(PREFIX "Missing device object\n");
result = -EINVAL;
goto out;
}
end:
*mem_device = acpi_driver_data(device);
if (!(*mem_device)) {
pr_err(PREFIX "driver data not found\n");
result = -ENODEV;
goto out;
}
out:
acpi_scan_lock_release();
return result;
}
static int acpi_memory_check_device(struct acpi_memory_device *mem_device)
{
unsigned long long current_status;
/* Get device present/absent information from the _STA */
if (ACPI_FAILURE(acpi_evaluate_integer(mem_device->device->handle,
"_STA", NULL, ¤t_status)))
return -ENODEV;
/*
* Check for device status. Device should be
* present/enabled/functioning.
*/
if (!((current_status & ACPI_STA_DEVICE_PRESENT)
&& (current_status & ACPI_STA_DEVICE_ENABLED)
&& (current_status & ACPI_STA_DEVICE_FUNCTIONING)))
return -ENODEV;
return 0;
}
static int acpi_memory_disable_device(struct acpi_memory_device *mem_device)
{
pr_debug(PREFIX "Xen does not support memory hotremove\n");
return -ENOSYS;
}
static void acpi_memory_device_notify(acpi_handle handle, u32 event, void *data)
{
struct acpi_memory_device *mem_device;
struct acpi_device *device;
u32 ost_code = ACPI_OST_SC_NON_SPECIFIC_FAILURE; /* default */
switch (event) {
case ACPI_NOTIFY_BUS_CHECK:
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"\nReceived BUS CHECK notification for device\n"));
/* Fall Through */
case ACPI_NOTIFY_DEVICE_CHECK:
if (event == ACPI_NOTIFY_DEVICE_CHECK)
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"\nReceived DEVICE CHECK notification for device\n"));
if (acpi_memory_get_device(handle, &mem_device)) {
pr_err(PREFIX "Cannot find driver data\n");
break;
}
ost_code = ACPI_OST_SC_SUCCESS;
break;
case ACPI_NOTIFY_EJECT_REQUEST:
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"\nReceived EJECT REQUEST notification for device\n"));
acpi_scan_lock_acquire();
if (acpi_bus_get_device(handle, &device)) {
acpi_scan_lock_release();
pr_err(PREFIX "Device doesn't exist\n");
break;
}
mem_device = acpi_driver_data(device);
if (!mem_device) {
acpi_scan_lock_release();
pr_err(PREFIX "Driver Data is NULL\n");
break;
}
/*
* TBD: implement acpi_memory_disable_device and invoke
* acpi_bus_remove if Xen support hotremove in the future
*/
acpi_memory_disable_device(mem_device);
acpi_scan_lock_release();
break;
default:
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"Unsupported event [0x%x]\n", event));
/* non-hotplug event; possibly handled by other handler */
return;
}
(void) acpi_evaluate_hotplug_ost(handle, event, ost_code, NULL);
return;
}
static int xen_acpi_memory_device_add(struct acpi_device *device)
{
int result;
struct acpi_memory_device *mem_device = NULL;
if (!device)
return -EINVAL;
mem_device = kzalloc(sizeof(struct acpi_memory_device), GFP_KERNEL);
if (!mem_device)
return -ENOMEM;
INIT_LIST_HEAD(&mem_device->res_list);
mem_device->device = device;
sprintf(acpi_device_name(device), "%s", ACPI_MEMORY_DEVICE_NAME);
sprintf(acpi_device_class(device), "%s", ACPI_MEMORY_DEVICE_CLASS);
device->driver_data = mem_device;
/* Get the range from the _CRS */
result = acpi_memory_get_device_resources(mem_device);
if (result) {
kfree(mem_device);
return result;
}
/*
* For booting existed memory devices, early boot code has recognized
* memory area by EFI/E820. If DSDT shows these memory devices on boot,
* hotplug is not necessary for them.
* For hot-added memory devices during runtime, it need hypercall to
* Xen hypervisor to add memory.
*/
if (!acpi_hotmem_initialized)
return 0;
if (!acpi_memory_check_device(mem_device))
result = xen_acpi_memory_enable_device(mem_device);
return result;
}
static int xen_acpi_memory_device_remove(struct acpi_device *device)
{
struct acpi_memory_device *mem_device = NULL;
if (!device || !acpi_driver_data(device))
return -EINVAL;
mem_device = acpi_driver_data(device);
kfree(mem_device);
return 0;
}
/*
* Helper function to check for memory device
*/
static acpi_status is_memory_device(acpi_handle handle)
{
char *hardware_id;
acpi_status status;
struct acpi_device_info *info;
status = acpi_get_object_info(handle, &info);
if (ACPI_FAILURE(status))
return status;
if (!(info->valid & ACPI_VALID_HID)) {
kfree(info);
return AE_ERROR;
}
hardware_id = info->hardware_id.string;
if ((hardware_id == NULL) ||
(strcmp(hardware_id, ACPI_MEMORY_DEVICE_HID)))
status = AE_ERROR;
kfree(info);
return status;
}
static acpi_status
acpi_memory_register_notify_handler(acpi_handle handle,
u32 level, void *ctxt, void **retv)
{
acpi_status status;
status = is_memory_device(handle);
if (ACPI_FAILURE(status))
return AE_OK; /* continue */
status = acpi_install_notify_handler(handle, ACPI_SYSTEM_NOTIFY,
acpi_memory_device_notify, NULL);
/* continue */
return AE_OK;
}
static acpi_status
acpi_memory_deregister_notify_handler(acpi_handle handle,
u32 level, void *ctxt, void **retv)
{
acpi_status status;
status = is_memory_device(handle);
if (ACPI_FAILURE(status))
return AE_OK; /* continue */
status = acpi_remove_notify_handler(handle,
ACPI_SYSTEM_NOTIFY,
acpi_memory_device_notify);
return AE_OK; /* continue */
}
static const struct acpi_device_id memory_device_ids[] = {
{ACPI_MEMORY_DEVICE_HID, 0},
{"", 0},
};
MODULE_DEVICE_TABLE(acpi, memory_device_ids);
static struct acpi_driver xen_acpi_memory_device_driver = {
.name = "acpi_memhotplug",
.class = ACPI_MEMORY_DEVICE_CLASS,
.ids = memory_device_ids,
.ops = {
.add = xen_acpi_memory_device_add,
.remove = xen_acpi_memory_device_remove,
},
};
static int __init xen_acpi_memory_device_init(void)
{
int result;
acpi_status status;
if (!xen_initial_domain())
return -ENODEV;
/* unregister the stub which only used to reserve driver space */
xen_stub_memory_device_exit();
result = acpi_bus_register_driver(&xen_acpi_memory_device_driver);
if (result < 0) {
xen_stub_memory_device_init();
return -ENODEV;
}
status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
ACPI_UINT32_MAX,
acpi_memory_register_notify_handler,
NULL, NULL, NULL);
if (ACPI_FAILURE(status)) {
pr_warn(PREFIX "walk_namespace failed\n");
acpi_bus_unregister_driver(&xen_acpi_memory_device_driver);
xen_stub_memory_device_init();
return -ENODEV;
}
acpi_hotmem_initialized = true;
return 0;
}
static void __exit xen_acpi_memory_device_exit(void)
{
acpi_status status;
if (!xen_initial_domain())
return;
status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
ACPI_UINT32_MAX,
acpi_memory_deregister_notify_handler,
NULL, NULL, NULL);
if (ACPI_FAILURE(status))
pr_warn(PREFIX "walk_namespace failed\n");
acpi_bus_unregister_driver(&xen_acpi_memory_device_driver);
/*
* stub reserve space again to prevent any chance of native
* driver loading.
*/
xen_stub_memory_device_init();
return;
}
module_init(xen_acpi_memory_device_init);
module_exit(xen_acpi_memory_device_exit);
ACPI_MODULE_NAME("xen-acpi-memhotplug");
MODULE_AUTHOR("Liu Jinsong <jinsong.liu@intel.com>");
MODULE_DESCRIPTION("Xen Hotplug Mem Driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
fanyukui/linux3.12.10 | drivers/gpu/drm/nouveau/core/engine/fifo/nvc0.c | 246 | 20155 | /*
* Copyright 2012 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Ben Skeggs
*/
#include <core/client.h>
#include <core/handle.h>
#include <core/namedb.h>
#include <core/gpuobj.h>
#include <core/engctx.h>
#include <core/event.h>
#include <core/class.h>
#include <core/enum.h>
#include <subdev/timer.h>
#include <subdev/bar.h>
#include <subdev/fb.h>
#include <subdev/vm.h>
#include <engine/dmaobj.h>
#include <engine/fifo.h>
struct nvc0_fifo_priv {
struct nouveau_fifo base;
struct nouveau_gpuobj *playlist[2];
int cur_playlist;
struct {
struct nouveau_gpuobj *mem;
struct nouveau_vma bar;
} user;
int spoon_nr;
};
struct nvc0_fifo_base {
struct nouveau_fifo_base base;
struct nouveau_gpuobj *pgd;
struct nouveau_vm *vm;
};
struct nvc0_fifo_chan {
struct nouveau_fifo_chan base;
};
/*******************************************************************************
* FIFO channel objects
******************************************************************************/
static void
nvc0_fifo_playlist_update(struct nvc0_fifo_priv *priv)
{
struct nouveau_bar *bar = nouveau_bar(priv);
struct nouveau_gpuobj *cur;
int i, p;
mutex_lock(&nv_subdev(priv)->mutex);
cur = priv->playlist[priv->cur_playlist];
priv->cur_playlist = !priv->cur_playlist;
for (i = 0, p = 0; i < 128; i++) {
if (!(nv_rd32(priv, 0x003004 + (i * 8)) & 1))
continue;
nv_wo32(cur, p + 0, i);
nv_wo32(cur, p + 4, 0x00000004);
p += 8;
}
bar->flush(bar);
nv_wr32(priv, 0x002270, cur->addr >> 12);
nv_wr32(priv, 0x002274, 0x01f00000 | (p >> 3));
if (!nv_wait(priv, 0x00227c, 0x00100000, 0x00000000))
nv_error(priv, "playlist update failed\n");
mutex_unlock(&nv_subdev(priv)->mutex);
}
static int
nvc0_fifo_context_attach(struct nouveau_object *parent,
struct nouveau_object *object)
{
struct nouveau_bar *bar = nouveau_bar(parent);
struct nvc0_fifo_base *base = (void *)parent->parent;
struct nouveau_engctx *ectx = (void *)object;
u32 addr;
int ret;
switch (nv_engidx(object->engine)) {
case NVDEV_ENGINE_SW : return 0;
case NVDEV_ENGINE_GR : addr = 0x0210; break;
case NVDEV_ENGINE_COPY0: addr = 0x0230; break;
case NVDEV_ENGINE_COPY1: addr = 0x0240; break;
case NVDEV_ENGINE_BSP : addr = 0x0270; break;
case NVDEV_ENGINE_VP : addr = 0x0250; break;
case NVDEV_ENGINE_PPP : addr = 0x0260; break;
default:
return -EINVAL;
}
if (!ectx->vma.node) {
ret = nouveau_gpuobj_map_vm(nv_gpuobj(ectx), base->vm,
NV_MEM_ACCESS_RW, &ectx->vma);
if (ret)
return ret;
nv_engctx(ectx)->addr = nv_gpuobj(base)->addr >> 12;
}
nv_wo32(base, addr + 0x00, lower_32_bits(ectx->vma.offset) | 4);
nv_wo32(base, addr + 0x04, upper_32_bits(ectx->vma.offset));
bar->flush(bar);
return 0;
}
static int
nvc0_fifo_context_detach(struct nouveau_object *parent, bool suspend,
struct nouveau_object *object)
{
struct nouveau_bar *bar = nouveau_bar(parent);
struct nvc0_fifo_priv *priv = (void *)parent->engine;
struct nvc0_fifo_base *base = (void *)parent->parent;
struct nvc0_fifo_chan *chan = (void *)parent;
u32 addr;
switch (nv_engidx(object->engine)) {
case NVDEV_ENGINE_SW : return 0;
case NVDEV_ENGINE_GR : addr = 0x0210; break;
case NVDEV_ENGINE_COPY0: addr = 0x0230; break;
case NVDEV_ENGINE_COPY1: addr = 0x0240; break;
case NVDEV_ENGINE_BSP : addr = 0x0270; break;
case NVDEV_ENGINE_VP : addr = 0x0250; break;
case NVDEV_ENGINE_PPP : addr = 0x0260; break;
default:
return -EINVAL;
}
nv_wr32(priv, 0x002634, chan->base.chid);
if (!nv_wait(priv, 0x002634, 0xffffffff, chan->base.chid)) {
nv_error(priv, "channel %d [%s] kick timeout\n",
chan->base.chid, nouveau_client_name(chan));
if (suspend)
return -EBUSY;
}
nv_wo32(base, addr + 0x00, 0x00000000);
nv_wo32(base, addr + 0x04, 0x00000000);
bar->flush(bar);
return 0;
}
static int
nvc0_fifo_chan_ctor(struct nouveau_object *parent,
struct nouveau_object *engine,
struct nouveau_oclass *oclass, void *data, u32 size,
struct nouveau_object **pobject)
{
struct nouveau_bar *bar = nouveau_bar(parent);
struct nvc0_fifo_priv *priv = (void *)engine;
struct nvc0_fifo_base *base = (void *)parent;
struct nvc0_fifo_chan *chan;
struct nv50_channel_ind_class *args = data;
u64 usermem, ioffset, ilength;
int ret, i;
if (size < sizeof(*args))
return -EINVAL;
ret = nouveau_fifo_channel_create(parent, engine, oclass, 1,
priv->user.bar.offset, 0x1000,
args->pushbuf,
(1ULL << NVDEV_ENGINE_SW) |
(1ULL << NVDEV_ENGINE_GR) |
(1ULL << NVDEV_ENGINE_COPY0) |
(1ULL << NVDEV_ENGINE_COPY1) |
(1ULL << NVDEV_ENGINE_BSP) |
(1ULL << NVDEV_ENGINE_VP) |
(1ULL << NVDEV_ENGINE_PPP), &chan);
*pobject = nv_object(chan);
if (ret)
return ret;
nv_parent(chan)->context_attach = nvc0_fifo_context_attach;
nv_parent(chan)->context_detach = nvc0_fifo_context_detach;
usermem = chan->base.chid * 0x1000;
ioffset = args->ioffset;
ilength = order_base_2(args->ilength / 8);
for (i = 0; i < 0x1000; i += 4)
nv_wo32(priv->user.mem, usermem + i, 0x00000000);
nv_wo32(base, 0x08, lower_32_bits(priv->user.mem->addr + usermem));
nv_wo32(base, 0x0c, upper_32_bits(priv->user.mem->addr + usermem));
nv_wo32(base, 0x10, 0x0000face);
nv_wo32(base, 0x30, 0xfffff902);
nv_wo32(base, 0x48, lower_32_bits(ioffset));
nv_wo32(base, 0x4c, upper_32_bits(ioffset) | (ilength << 16));
nv_wo32(base, 0x54, 0x00000002);
nv_wo32(base, 0x84, 0x20400000);
nv_wo32(base, 0x94, 0x30000001);
nv_wo32(base, 0x9c, 0x00000100);
nv_wo32(base, 0xa4, 0x1f1f1f1f);
nv_wo32(base, 0xa8, 0x1f1f1f1f);
nv_wo32(base, 0xac, 0x0000001f);
nv_wo32(base, 0xb8, 0xf8000000);
nv_wo32(base, 0xf8, 0x10003080); /* 0x002310 */
nv_wo32(base, 0xfc, 0x10000010); /* 0x002350 */
bar->flush(bar);
return 0;
}
static int
nvc0_fifo_chan_init(struct nouveau_object *object)
{
struct nouveau_gpuobj *base = nv_gpuobj(object->parent);
struct nvc0_fifo_priv *priv = (void *)object->engine;
struct nvc0_fifo_chan *chan = (void *)object;
u32 chid = chan->base.chid;
int ret;
ret = nouveau_fifo_channel_init(&chan->base);
if (ret)
return ret;
nv_wr32(priv, 0x003000 + (chid * 8), 0xc0000000 | base->addr >> 12);
nv_wr32(priv, 0x003004 + (chid * 8), 0x001f0001);
nvc0_fifo_playlist_update(priv);
return 0;
}
static int
nvc0_fifo_chan_fini(struct nouveau_object *object, bool suspend)
{
struct nvc0_fifo_priv *priv = (void *)object->engine;
struct nvc0_fifo_chan *chan = (void *)object;
u32 chid = chan->base.chid;
u32 mask, engine;
nv_mask(priv, 0x003004 + (chid * 8), 0x00000001, 0x00000000);
nvc0_fifo_playlist_update(priv);
mask = nv_rd32(priv, 0x0025a4);
for (engine = 0; mask && engine < 16; engine++) {
if (!(mask & (1 << engine)))
continue;
nv_mask(priv, 0x0025a8 + (engine * 4), 0x00000000, 0x00000000);
mask &= ~(1 << engine);
}
nv_wr32(priv, 0x003000 + (chid * 8), 0x00000000);
return nouveau_fifo_channel_fini(&chan->base, suspend);
}
static struct nouveau_ofuncs
nvc0_fifo_ofuncs = {
.ctor = nvc0_fifo_chan_ctor,
.dtor = _nouveau_fifo_channel_dtor,
.init = nvc0_fifo_chan_init,
.fini = nvc0_fifo_chan_fini,
.rd32 = _nouveau_fifo_channel_rd32,
.wr32 = _nouveau_fifo_channel_wr32,
};
static struct nouveau_oclass
nvc0_fifo_sclass[] = {
{ NVC0_CHANNEL_IND_CLASS, &nvc0_fifo_ofuncs },
{}
};
/*******************************************************************************
* FIFO context - instmem heap and vm setup
******************************************************************************/
static int
nvc0_fifo_context_ctor(struct nouveau_object *parent,
struct nouveau_object *engine,
struct nouveau_oclass *oclass, void *data, u32 size,
struct nouveau_object **pobject)
{
struct nvc0_fifo_base *base;
int ret;
ret = nouveau_fifo_context_create(parent, engine, oclass, NULL, 0x1000,
0x1000, NVOBJ_FLAG_ZERO_ALLOC |
NVOBJ_FLAG_HEAP, &base);
*pobject = nv_object(base);
if (ret)
return ret;
ret = nouveau_gpuobj_new(nv_object(base), NULL, 0x10000, 0x1000, 0,
&base->pgd);
if (ret)
return ret;
nv_wo32(base, 0x0200, lower_32_bits(base->pgd->addr));
nv_wo32(base, 0x0204, upper_32_bits(base->pgd->addr));
nv_wo32(base, 0x0208, 0xffffffff);
nv_wo32(base, 0x020c, 0x000000ff);
ret = nouveau_vm_ref(nouveau_client(parent)->vm, &base->vm, base->pgd);
if (ret)
return ret;
return 0;
}
static void
nvc0_fifo_context_dtor(struct nouveau_object *object)
{
struct nvc0_fifo_base *base = (void *)object;
nouveau_vm_ref(NULL, &base->vm, base->pgd);
nouveau_gpuobj_ref(NULL, &base->pgd);
nouveau_fifo_context_destroy(&base->base);
}
static struct nouveau_oclass
nvc0_fifo_cclass = {
.handle = NV_ENGCTX(FIFO, 0xc0),
.ofuncs = &(struct nouveau_ofuncs) {
.ctor = nvc0_fifo_context_ctor,
.dtor = nvc0_fifo_context_dtor,
.init = _nouveau_fifo_context_init,
.fini = _nouveau_fifo_context_fini,
.rd32 = _nouveau_fifo_context_rd32,
.wr32 = _nouveau_fifo_context_wr32,
},
};
/*******************************************************************************
* PFIFO engine
******************************************************************************/
static const struct nouveau_enum nvc0_fifo_fault_unit[] = {
{ 0x00, "PGRAPH", NULL, NVDEV_ENGINE_GR },
{ 0x03, "PEEPHOLE" },
{ 0x04, "BAR1" },
{ 0x05, "BAR3" },
{ 0x07, "PFIFO", NULL, NVDEV_ENGINE_FIFO },
{ 0x10, "PBSP", NULL, NVDEV_ENGINE_BSP },
{ 0x11, "PPPP", NULL, NVDEV_ENGINE_PPP },
{ 0x13, "PCOUNTER" },
{ 0x14, "PVP", NULL, NVDEV_ENGINE_VP },
{ 0x15, "PCOPY0", NULL, NVDEV_ENGINE_COPY0 },
{ 0x16, "PCOPY1", NULL, NVDEV_ENGINE_COPY1 },
{ 0x17, "PDAEMON" },
{}
};
static const struct nouveau_enum nvc0_fifo_fault_reason[] = {
{ 0x00, "PT_NOT_PRESENT" },
{ 0x01, "PT_TOO_SHORT" },
{ 0x02, "PAGE_NOT_PRESENT" },
{ 0x03, "VM_LIMIT_EXCEEDED" },
{ 0x04, "NO_CHANNEL" },
{ 0x05, "PAGE_SYSTEM_ONLY" },
{ 0x06, "PAGE_READ_ONLY" },
{ 0x0a, "COMPRESSED_SYSRAM" },
{ 0x0c, "INVALID_STORAGE_TYPE" },
{}
};
static const struct nouveau_enum nvc0_fifo_fault_hubclient[] = {
{ 0x01, "PCOPY0" },
{ 0x02, "PCOPY1" },
{ 0x04, "DISPATCH" },
{ 0x05, "CTXCTL" },
{ 0x06, "PFIFO" },
{ 0x07, "BAR_READ" },
{ 0x08, "BAR_WRITE" },
{ 0x0b, "PVP" },
{ 0x0c, "PPPP" },
{ 0x0d, "PBSP" },
{ 0x11, "PCOUNTER" },
{ 0x12, "PDAEMON" },
{ 0x14, "CCACHE" },
{ 0x15, "CCACHE_POST" },
{}
};
static const struct nouveau_enum nvc0_fifo_fault_gpcclient[] = {
{ 0x01, "TEX" },
{ 0x0c, "ESETUP" },
{ 0x0e, "CTXCTL" },
{ 0x0f, "PROP" },
{}
};
static const struct nouveau_bitfield nvc0_fifo_subfifo_intr[] = {
/* { 0x00008000, "" } seen with null ib push */
{ 0x00200000, "ILLEGAL_MTHD" },
{ 0x00800000, "EMPTY_SUBC" },
{}
};
static void
nvc0_fifo_isr_vm_fault(struct nvc0_fifo_priv *priv, int unit)
{
u32 inst = nv_rd32(priv, 0x002800 + (unit * 0x10));
u32 valo = nv_rd32(priv, 0x002804 + (unit * 0x10));
u32 vahi = nv_rd32(priv, 0x002808 + (unit * 0x10));
u32 stat = nv_rd32(priv, 0x00280c + (unit * 0x10));
u32 client = (stat & 0x00001f00) >> 8;
const struct nouveau_enum *en;
struct nouveau_engine *engine;
struct nouveau_object *engctx = NULL;
switch (unit) {
case 3: /* PEEPHOLE */
nv_mask(priv, 0x001718, 0x00000000, 0x00000000);
break;
case 4: /* BAR1 */
nv_mask(priv, 0x001704, 0x00000000, 0x00000000);
break;
case 5: /* BAR3 */
nv_mask(priv, 0x001714, 0x00000000, 0x00000000);
break;
default:
break;
}
nv_error(priv, "%s fault at 0x%010llx [", (stat & 0x00000080) ?
"write" : "read", (u64)vahi << 32 | valo);
nouveau_enum_print(nvc0_fifo_fault_reason, stat & 0x0000000f);
pr_cont("] from ");
en = nouveau_enum_print(nvc0_fifo_fault_unit, unit);
if (stat & 0x00000040) {
pr_cont("/");
nouveau_enum_print(nvc0_fifo_fault_hubclient, client);
} else {
pr_cont("/GPC%d/", (stat & 0x1f000000) >> 24);
nouveau_enum_print(nvc0_fifo_fault_gpcclient, client);
}
if (en && en->data2) {
engine = nouveau_engine(priv, en->data2);
if (engine)
engctx = nouveau_engctx_get(engine, inst);
}
pr_cont(" on channel 0x%010llx [%s]\n", (u64)inst << 12,
nouveau_client_name(engctx));
nouveau_engctx_put(engctx);
}
static int
nvc0_fifo_swmthd(struct nvc0_fifo_priv *priv, u32 chid, u32 mthd, u32 data)
{
struct nvc0_fifo_chan *chan = NULL;
struct nouveau_handle *bind;
unsigned long flags;
int ret = -EINVAL;
spin_lock_irqsave(&priv->base.lock, flags);
if (likely(chid >= priv->base.min && chid <= priv->base.max))
chan = (void *)priv->base.channel[chid];
if (unlikely(!chan))
goto out;
bind = nouveau_namedb_get_class(nv_namedb(chan), 0x906e);
if (likely(bind)) {
if (!mthd || !nv_call(bind->object, mthd, data))
ret = 0;
nouveau_namedb_put(bind);
}
out:
spin_unlock_irqrestore(&priv->base.lock, flags);
return ret;
}
static void
nvc0_fifo_isr_subfifo_intr(struct nvc0_fifo_priv *priv, int unit)
{
u32 stat = nv_rd32(priv, 0x040108 + (unit * 0x2000));
u32 addr = nv_rd32(priv, 0x0400c0 + (unit * 0x2000));
u32 data = nv_rd32(priv, 0x0400c4 + (unit * 0x2000));
u32 chid = nv_rd32(priv, 0x040120 + (unit * 0x2000)) & 0x7f;
u32 subc = (addr & 0x00070000) >> 16;
u32 mthd = (addr & 0x00003ffc);
u32 show = stat;
if (stat & 0x00800000) {
if (!nvc0_fifo_swmthd(priv, chid, mthd, data))
show &= ~0x00800000;
}
if (show) {
nv_error(priv, "SUBFIFO%d:", unit);
nouveau_bitfield_print(nvc0_fifo_subfifo_intr, show);
pr_cont("\n");
nv_error(priv,
"SUBFIFO%d: ch %d [%s] subc %d mthd 0x%04x data 0x%08x\n",
unit, chid,
nouveau_client_name_for_fifo_chid(&priv->base, chid),
subc, mthd, data);
}
nv_wr32(priv, 0x0400c0 + (unit * 0x2000), 0x80600008);
nv_wr32(priv, 0x040108 + (unit * 0x2000), stat);
}
static void
nvc0_fifo_intr(struct nouveau_subdev *subdev)
{
struct nvc0_fifo_priv *priv = (void *)subdev;
u32 mask = nv_rd32(priv, 0x002140);
u32 stat = nv_rd32(priv, 0x002100) & mask;
if (stat & 0x00000001) {
u32 intr = nv_rd32(priv, 0x00252c);
nv_warn(priv, "INTR 0x00000001: 0x%08x\n", intr);
nv_wr32(priv, 0x002100, 0x00000001);
stat &= ~0x00000001;
}
if (stat & 0x00000100) {
u32 intr = nv_rd32(priv, 0x00254c);
nv_warn(priv, "INTR 0x00000100: 0x%08x\n", intr);
nv_wr32(priv, 0x002100, 0x00000100);
stat &= ~0x00000100;
}
if (stat & 0x00010000) {
u32 intr = nv_rd32(priv, 0x00256c);
nv_warn(priv, "INTR 0x00010000: 0x%08x\n", intr);
nv_wr32(priv, 0x002100, 0x00010000);
stat &= ~0x00010000;
}
if (stat & 0x01000000) {
u32 intr = nv_rd32(priv, 0x00258c);
nv_warn(priv, "INTR 0x01000000: 0x%08x\n", intr);
nv_wr32(priv, 0x002100, 0x01000000);
stat &= ~0x01000000;
}
if (stat & 0x10000000) {
u32 units = nv_rd32(priv, 0x00259c);
u32 u = units;
while (u) {
int i = ffs(u) - 1;
nvc0_fifo_isr_vm_fault(priv, i);
u &= ~(1 << i);
}
nv_wr32(priv, 0x00259c, units);
stat &= ~0x10000000;
}
if (stat & 0x20000000) {
u32 units = nv_rd32(priv, 0x0025a0);
u32 u = units;
while (u) {
int i = ffs(u) - 1;
nvc0_fifo_isr_subfifo_intr(priv, i);
u &= ~(1 << i);
}
nv_wr32(priv, 0x0025a0, units);
stat &= ~0x20000000;
}
if (stat & 0x40000000) {
u32 intr0 = nv_rd32(priv, 0x0025a4);
u32 intr1 = nv_mask(priv, 0x002a00, 0x00000000, 0x00000);
nv_debug(priv, "INTR 0x40000000: 0x%08x 0x%08x\n",
intr0, intr1);
stat &= ~0x40000000;
}
if (stat & 0x80000000) {
u32 intr = nv_mask(priv, 0x0025a8, 0x00000000, 0x00000000);
nouveau_event_trigger(priv->base.uevent, 0);
nv_debug(priv, "INTR 0x80000000: 0x%08x\n", intr);
stat &= ~0x80000000;
}
if (stat) {
nv_fatal(priv, "unhandled status 0x%08x\n", stat);
nv_wr32(priv, 0x002100, stat);
nv_wr32(priv, 0x002140, 0);
}
}
static void
nvc0_fifo_uevent_enable(struct nouveau_event *event, int index)
{
struct nvc0_fifo_priv *priv = event->priv;
nv_mask(priv, 0x002140, 0x80000000, 0x80000000);
}
static void
nvc0_fifo_uevent_disable(struct nouveau_event *event, int index)
{
struct nvc0_fifo_priv *priv = event->priv;
nv_mask(priv, 0x002140, 0x80000000, 0x00000000);
}
static int
nvc0_fifo_ctor(struct nouveau_object *parent, struct nouveau_object *engine,
struct nouveau_oclass *oclass, void *data, u32 size,
struct nouveau_object **pobject)
{
struct nvc0_fifo_priv *priv;
int ret;
ret = nouveau_fifo_create(parent, engine, oclass, 0, 127, &priv);
*pobject = nv_object(priv);
if (ret)
return ret;
ret = nouveau_gpuobj_new(nv_object(priv), NULL, 0x1000, 0x1000, 0,
&priv->playlist[0]);
if (ret)
return ret;
ret = nouveau_gpuobj_new(nv_object(priv), NULL, 0x1000, 0x1000, 0,
&priv->playlist[1]);
if (ret)
return ret;
ret = nouveau_gpuobj_new(nv_object(priv), NULL, 128 * 0x1000, 0x1000, 0,
&priv->user.mem);
if (ret)
return ret;
ret = nouveau_gpuobj_map(priv->user.mem, NV_MEM_ACCESS_RW,
&priv->user.bar);
if (ret)
return ret;
priv->base.uevent->enable = nvc0_fifo_uevent_enable;
priv->base.uevent->disable = nvc0_fifo_uevent_disable;
priv->base.uevent->priv = priv;
nv_subdev(priv)->unit = 0x00000100;
nv_subdev(priv)->intr = nvc0_fifo_intr;
nv_engine(priv)->cclass = &nvc0_fifo_cclass;
nv_engine(priv)->sclass = nvc0_fifo_sclass;
return 0;
}
static void
nvc0_fifo_dtor(struct nouveau_object *object)
{
struct nvc0_fifo_priv *priv = (void *)object;
nouveau_gpuobj_unmap(&priv->user.bar);
nouveau_gpuobj_ref(NULL, &priv->user.mem);
nouveau_gpuobj_ref(NULL, &priv->playlist[1]);
nouveau_gpuobj_ref(NULL, &priv->playlist[0]);
nouveau_fifo_destroy(&priv->base);
}
static int
nvc0_fifo_init(struct nouveau_object *object)
{
struct nvc0_fifo_priv *priv = (void *)object;
int ret, i;
ret = nouveau_fifo_init(&priv->base);
if (ret)
return ret;
nv_wr32(priv, 0x000204, 0xffffffff);
nv_wr32(priv, 0x002204, 0xffffffff);
priv->spoon_nr = hweight32(nv_rd32(priv, 0x002204));
nv_debug(priv, "%d subfifo(s)\n", priv->spoon_nr);
/* assign engines to subfifos */
if (priv->spoon_nr >= 3) {
nv_wr32(priv, 0x002208, ~(1 << 0)); /* PGRAPH */
nv_wr32(priv, 0x00220c, ~(1 << 1)); /* PVP */
nv_wr32(priv, 0x002210, ~(1 << 1)); /* PPP */
nv_wr32(priv, 0x002214, ~(1 << 1)); /* PBSP */
nv_wr32(priv, 0x002218, ~(1 << 2)); /* PCE0 */
nv_wr32(priv, 0x00221c, ~(1 << 1)); /* PCE1 */
}
/* PSUBFIFO[n] */
for (i = 0; i < priv->spoon_nr; i++) {
nv_mask(priv, 0x04013c + (i * 0x2000), 0x10000100, 0x00000000);
nv_wr32(priv, 0x040108 + (i * 0x2000), 0xffffffff); /* INTR */
nv_wr32(priv, 0x04010c + (i * 0x2000), 0xfffffeff); /* INTREN */
}
nv_mask(priv, 0x002200, 0x00000001, 0x00000001);
nv_wr32(priv, 0x002254, 0x10000000 | priv->user.bar.offset >> 12);
nv_wr32(priv, 0x002a00, 0xffffffff); /* clears PFIFO.INTR bit 30 */
nv_wr32(priv, 0x002100, 0xffffffff);
nv_wr32(priv, 0x002140, 0x3fffffff);
nv_wr32(priv, 0x002628, 0x00000001); /* makes mthd 0x20 work */
return 0;
}
struct nouveau_oclass *
nvc0_fifo_oclass = &(struct nouveau_oclass) {
.handle = NV_ENGINE(FIFO, 0xc0),
.ofuncs = &(struct nouveau_ofuncs) {
.ctor = nvc0_fifo_ctor,
.dtor = nvc0_fifo_dtor,
.init = nvc0_fifo_init,
.fini = _nouveau_fifo_fini,
},
};
| gpl-2.0 |
ajeet17181/fathom-kernel | drivers/s390/scsi/zfcp_cfdc.c | 758 | 6429 | /*
* zfcp device driver
*
* Userspace interface for accessing the
* Access Control Lists / Control File Data Channel
*
* Copyright IBM Corporation 2008, 2009
*/
#define KMSG_COMPONENT "zfcp"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/miscdevice.h>
#include <asm/compat.h>
#include <asm/ccwdev.h>
#include "zfcp_def.h"
#include "zfcp_ext.h"
#include "zfcp_fsf.h"
#define ZFCP_CFDC_CMND_DOWNLOAD_NORMAL 0x00010001
#define ZFCP_CFDC_CMND_DOWNLOAD_FORCE 0x00010101
#define ZFCP_CFDC_CMND_FULL_ACCESS 0x00000201
#define ZFCP_CFDC_CMND_RESTRICTED_ACCESS 0x00000401
#define ZFCP_CFDC_CMND_UPLOAD 0x00010002
#define ZFCP_CFDC_DOWNLOAD 0x00000001
#define ZFCP_CFDC_UPLOAD 0x00000002
#define ZFCP_CFDC_WITH_CONTROL_FILE 0x00010000
#define ZFCP_CFDC_IOC_MAGIC 0xDD
#define ZFCP_CFDC_IOC \
_IOWR(ZFCP_CFDC_IOC_MAGIC, 0, struct zfcp_cfdc_data)
/**
* struct zfcp_cfdc_data - data for ioctl cfdc interface
* @signature: request signature
* @devno: FCP adapter device number
* @command: command code
* @fsf_status: returns status of FSF command to userspace
* @fsf_status_qual: returned to userspace
* @payloads: access conflicts list
* @control_file: access control table
*/
struct zfcp_cfdc_data {
u32 signature;
u32 devno;
u32 command;
u32 fsf_status;
u8 fsf_status_qual[FSF_STATUS_QUALIFIER_SIZE];
u8 payloads[256];
u8 control_file[0];
};
static int zfcp_cfdc_copy_from_user(struct scatterlist *sg,
void __user *user_buffer)
{
unsigned int length;
unsigned int size = ZFCP_CFDC_MAX_SIZE;
while (size) {
length = min((unsigned int)size, sg->length);
if (copy_from_user(sg_virt(sg++), user_buffer, length))
return -EFAULT;
user_buffer += length;
size -= length;
}
return 0;
}
static int zfcp_cfdc_copy_to_user(void __user *user_buffer,
struct scatterlist *sg)
{
unsigned int length;
unsigned int size = ZFCP_CFDC_MAX_SIZE;
while (size) {
length = min((unsigned int) size, sg->length);
if (copy_to_user(user_buffer, sg_virt(sg++), length))
return -EFAULT;
user_buffer += length;
size -= length;
}
return 0;
}
static struct zfcp_adapter *zfcp_cfdc_get_adapter(u32 devno)
{
char busid[9];
struct ccw_device *cdev;
struct zfcp_adapter *adapter;
snprintf(busid, sizeof(busid), "0.0.%04x", devno);
cdev = get_ccwdev_by_busid(&zfcp_ccw_driver, busid);
if (!cdev)
return NULL;
adapter = zfcp_ccw_adapter_by_cdev(cdev);
put_device(&cdev->dev);
return adapter;
}
static int zfcp_cfdc_set_fsf(struct zfcp_fsf_cfdc *fsf_cfdc, int command)
{
switch (command) {
case ZFCP_CFDC_CMND_DOWNLOAD_NORMAL:
fsf_cfdc->command = FSF_QTCB_DOWNLOAD_CONTROL_FILE;
fsf_cfdc->option = FSF_CFDC_OPTION_NORMAL_MODE;
break;
case ZFCP_CFDC_CMND_DOWNLOAD_FORCE:
fsf_cfdc->command = FSF_QTCB_DOWNLOAD_CONTROL_FILE;
fsf_cfdc->option = FSF_CFDC_OPTION_FORCE;
break;
case ZFCP_CFDC_CMND_FULL_ACCESS:
fsf_cfdc->command = FSF_QTCB_DOWNLOAD_CONTROL_FILE;
fsf_cfdc->option = FSF_CFDC_OPTION_FULL_ACCESS;
break;
case ZFCP_CFDC_CMND_RESTRICTED_ACCESS:
fsf_cfdc->command = FSF_QTCB_DOWNLOAD_CONTROL_FILE;
fsf_cfdc->option = FSF_CFDC_OPTION_RESTRICTED_ACCESS;
break;
case ZFCP_CFDC_CMND_UPLOAD:
fsf_cfdc->command = FSF_QTCB_UPLOAD_CONTROL_FILE;
fsf_cfdc->option = 0;
break;
default:
return -EINVAL;
}
return 0;
}
static int zfcp_cfdc_sg_setup(int command, struct scatterlist *sg,
u8 __user *control_file)
{
int retval;
retval = zfcp_sg_setup_table(sg, ZFCP_CFDC_PAGES);
if (retval)
return retval;
sg[ZFCP_CFDC_PAGES - 1].length = ZFCP_CFDC_MAX_SIZE % PAGE_SIZE;
if (command & ZFCP_CFDC_WITH_CONTROL_FILE &&
command & ZFCP_CFDC_DOWNLOAD) {
retval = zfcp_cfdc_copy_from_user(sg, control_file);
if (retval) {
zfcp_sg_free_table(sg, ZFCP_CFDC_PAGES);
return -EFAULT;
}
}
return 0;
}
static void zfcp_cfdc_req_to_sense(struct zfcp_cfdc_data *data,
struct zfcp_fsf_req *req)
{
data->fsf_status = req->qtcb->header.fsf_status;
memcpy(&data->fsf_status_qual, &req->qtcb->header.fsf_status_qual,
sizeof(union fsf_status_qual));
memcpy(&data->payloads, &req->qtcb->bottom.support.els,
sizeof(req->qtcb->bottom.support.els));
}
static long zfcp_cfdc_dev_ioctl(struct file *file, unsigned int command,
unsigned long arg)
{
struct zfcp_cfdc_data *data;
struct zfcp_cfdc_data __user *data_user;
struct zfcp_adapter *adapter;
struct zfcp_fsf_req *req;
struct zfcp_fsf_cfdc *fsf_cfdc;
int retval;
if (command != ZFCP_CFDC_IOC)
return -ENOTTY;
if (is_compat_task())
data_user = compat_ptr(arg);
else
data_user = (void __user *)arg;
if (!data_user)
return -EINVAL;
fsf_cfdc = kmalloc(sizeof(struct zfcp_fsf_cfdc), GFP_KERNEL);
if (!fsf_cfdc)
return -ENOMEM;
data = kmalloc(sizeof(struct zfcp_cfdc_data), GFP_KERNEL);
if (!data) {
retval = -ENOMEM;
goto no_mem_sense;
}
retval = copy_from_user(data, data_user, sizeof(*data));
if (retval) {
retval = -EFAULT;
goto free_buffer;
}
if (data->signature != 0xCFDCACDF) {
retval = -EINVAL;
goto free_buffer;
}
retval = zfcp_cfdc_set_fsf(fsf_cfdc, data->command);
adapter = zfcp_cfdc_get_adapter(data->devno);
if (!adapter) {
retval = -ENXIO;
goto free_buffer;
}
retval = zfcp_cfdc_sg_setup(data->command, fsf_cfdc->sg,
data_user->control_file);
if (retval)
goto adapter_put;
req = zfcp_fsf_control_file(adapter, fsf_cfdc);
if (IS_ERR(req)) {
retval = PTR_ERR(req);
goto free_sg;
}
if (req->status & ZFCP_STATUS_FSFREQ_ERROR) {
retval = -ENXIO;
goto free_fsf;
}
zfcp_cfdc_req_to_sense(data, req);
retval = copy_to_user(data_user, data, sizeof(*data_user));
if (retval) {
retval = -EFAULT;
goto free_fsf;
}
if (data->command & ZFCP_CFDC_UPLOAD)
retval = zfcp_cfdc_copy_to_user(&data_user->control_file,
fsf_cfdc->sg);
free_fsf:
zfcp_fsf_req_free(req);
free_sg:
zfcp_sg_free_table(fsf_cfdc->sg, ZFCP_CFDC_PAGES);
adapter_put:
zfcp_ccw_adapter_put(adapter);
free_buffer:
kfree(data);
no_mem_sense:
kfree(fsf_cfdc);
return retval;
}
static const struct file_operations zfcp_cfdc_fops = {
.open = nonseekable_open,
.unlocked_ioctl = zfcp_cfdc_dev_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = zfcp_cfdc_dev_ioctl
#endif
};
struct miscdevice zfcp_cfdc_misc = {
.minor = MISC_DYNAMIC_MINOR,
.name = "zfcp_cfdc",
.fops = &zfcp_cfdc_fops,
};
| gpl-2.0 |
klquicksall/EVO3D-CDMA | drivers/net/phy/marvell.c | 758 | 15493 | /*
* drivers/net/phy/marvell.c
*
* Driver for Marvell PHYs
*
* Author: Andy Fleming
*
* Copyright (c) 2004 Freescale Semiconductor, Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
*/
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/unistd.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/spinlock.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/mii.h>
#include <linux/ethtool.h>
#include <linux/phy.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/uaccess.h>
#define MII_M1011_IEVENT 0x13
#define MII_M1011_IEVENT_CLEAR 0x0000
#define MII_M1011_IMASK 0x12
#define MII_M1011_IMASK_INIT 0x6400
#define MII_M1011_IMASK_CLEAR 0x0000
#define MII_M1011_PHY_SCR 0x10
#define MII_M1011_PHY_SCR_AUTO_CROSS 0x0060
#define MII_M1145_PHY_EXT_CR 0x14
#define MII_M1145_RGMII_RX_DELAY 0x0080
#define MII_M1145_RGMII_TX_DELAY 0x0002
#define M1145_DEV_FLAGS_RESISTANCE 0x00000001
#define MII_M1111_PHY_LED_CONTROL 0x18
#define MII_M1111_PHY_LED_DIRECT 0x4100
#define MII_M1111_PHY_LED_COMBINE 0x411c
#define MII_M1111_PHY_EXT_CR 0x14
#define MII_M1111_RX_DELAY 0x80
#define MII_M1111_TX_DELAY 0x2
#define MII_M1111_PHY_EXT_SR 0x1b
#define MII_M1111_HWCFG_MODE_MASK 0xf
#define MII_M1111_HWCFG_MODE_COPPER_RGMII 0xb
#define MII_M1111_HWCFG_MODE_FIBER_RGMII 0x3
#define MII_M1111_HWCFG_MODE_SGMII_NO_CLK 0x4
#define MII_M1111_HWCFG_MODE_COPPER_RTBI 0x9
#define MII_M1111_HWCFG_FIBER_COPPER_AUTO 0x8000
#define MII_M1111_HWCFG_FIBER_COPPER_RES 0x2000
#define MII_M1111_COPPER 0
#define MII_M1111_FIBER 1
#define MII_88E1121_PHY_LED_CTRL 16
#define MII_88E1121_PHY_LED_PAGE 3
#define MII_88E1121_PHY_LED_DEF 0x0030
#define MII_88E1121_PHY_PAGE 22
#define MII_M1011_PHY_STATUS 0x11
#define MII_M1011_PHY_STATUS_1000 0x8000
#define MII_M1011_PHY_STATUS_100 0x4000
#define MII_M1011_PHY_STATUS_SPD_MASK 0xc000
#define MII_M1011_PHY_STATUS_FULLDUPLEX 0x2000
#define MII_M1011_PHY_STATUS_RESOLVED 0x0800
#define MII_M1011_PHY_STATUS_LINK 0x0400
MODULE_DESCRIPTION("Marvell PHY driver");
MODULE_AUTHOR("Andy Fleming");
MODULE_LICENSE("GPL");
static int marvell_ack_interrupt(struct phy_device *phydev)
{
int err;
/* Clear the interrupts by reading the reg */
err = phy_read(phydev, MII_M1011_IEVENT);
if (err < 0)
return err;
return 0;
}
static int marvell_config_intr(struct phy_device *phydev)
{
int err;
if (phydev->interrupts == PHY_INTERRUPT_ENABLED)
err = phy_write(phydev, MII_M1011_IMASK, MII_M1011_IMASK_INIT);
else
err = phy_write(phydev, MII_M1011_IMASK, MII_M1011_IMASK_CLEAR);
return err;
}
static int marvell_config_aneg(struct phy_device *phydev)
{
int err;
/* The Marvell PHY has an errata which requires
* that certain registers get written in order
* to restart autonegotiation */
err = phy_write(phydev, MII_BMCR, BMCR_RESET);
if (err < 0)
return err;
err = phy_write(phydev, 0x1d, 0x1f);
if (err < 0)
return err;
err = phy_write(phydev, 0x1e, 0x200c);
if (err < 0)
return err;
err = phy_write(phydev, 0x1d, 0x5);
if (err < 0)
return err;
err = phy_write(phydev, 0x1e, 0);
if (err < 0)
return err;
err = phy_write(phydev, 0x1e, 0x100);
if (err < 0)
return err;
err = phy_write(phydev, MII_M1011_PHY_SCR,
MII_M1011_PHY_SCR_AUTO_CROSS);
if (err < 0)
return err;
err = phy_write(phydev, MII_M1111_PHY_LED_CONTROL,
MII_M1111_PHY_LED_DIRECT);
if (err < 0)
return err;
err = genphy_config_aneg(phydev);
if (err < 0)
return err;
if (phydev->autoneg != AUTONEG_ENABLE) {
int bmcr;
/*
* A write to speed/duplex bits (that is performed by
* genphy_config_aneg() call above) must be followed by
* a software reset. Otherwise, the write has no effect.
*/
bmcr = phy_read(phydev, MII_BMCR);
if (bmcr < 0)
return bmcr;
err = phy_write(phydev, MII_BMCR, bmcr | BMCR_RESET);
if (err < 0)
return err;
}
return 0;
}
static int m88e1121_config_aneg(struct phy_device *phydev)
{
int err, temp;
err = phy_write(phydev, MII_BMCR, BMCR_RESET);
if (err < 0)
return err;
err = phy_write(phydev, MII_M1011_PHY_SCR,
MII_M1011_PHY_SCR_AUTO_CROSS);
if (err < 0)
return err;
temp = phy_read(phydev, MII_88E1121_PHY_PAGE);
phy_write(phydev, MII_88E1121_PHY_PAGE, MII_88E1121_PHY_LED_PAGE);
phy_write(phydev, MII_88E1121_PHY_LED_CTRL, MII_88E1121_PHY_LED_DEF);
phy_write(phydev, MII_88E1121_PHY_PAGE, temp);
err = genphy_config_aneg(phydev);
return err;
}
static int m88e1111_config_init(struct phy_device *phydev)
{
int err;
int temp;
/* Enable Fiber/Copper auto selection */
temp = phy_read(phydev, MII_M1111_PHY_EXT_SR);
temp &= ~MII_M1111_HWCFG_FIBER_COPPER_AUTO;
phy_write(phydev, MII_M1111_PHY_EXT_SR, temp);
temp = phy_read(phydev, MII_BMCR);
temp |= BMCR_RESET;
phy_write(phydev, MII_BMCR, temp);
if ((phydev->interface == PHY_INTERFACE_MODE_RGMII) ||
(phydev->interface == PHY_INTERFACE_MODE_RGMII_ID) ||
(phydev->interface == PHY_INTERFACE_MODE_RGMII_RXID) ||
(phydev->interface == PHY_INTERFACE_MODE_RGMII_TXID)) {
temp = phy_read(phydev, MII_M1111_PHY_EXT_CR);
if (temp < 0)
return temp;
if (phydev->interface == PHY_INTERFACE_MODE_RGMII_ID) {
temp |= (MII_M1111_RX_DELAY | MII_M1111_TX_DELAY);
} else if (phydev->interface == PHY_INTERFACE_MODE_RGMII_RXID) {
temp &= ~MII_M1111_TX_DELAY;
temp |= MII_M1111_RX_DELAY;
} else if (phydev->interface == PHY_INTERFACE_MODE_RGMII_TXID) {
temp &= ~MII_M1111_RX_DELAY;
temp |= MII_M1111_TX_DELAY;
}
err = phy_write(phydev, MII_M1111_PHY_EXT_CR, temp);
if (err < 0)
return err;
temp = phy_read(phydev, MII_M1111_PHY_EXT_SR);
if (temp < 0)
return temp;
temp &= ~(MII_M1111_HWCFG_MODE_MASK);
if (temp & MII_M1111_HWCFG_FIBER_COPPER_RES)
temp |= MII_M1111_HWCFG_MODE_FIBER_RGMII;
else
temp |= MII_M1111_HWCFG_MODE_COPPER_RGMII;
err = phy_write(phydev, MII_M1111_PHY_EXT_SR, temp);
if (err < 0)
return err;
}
if (phydev->interface == PHY_INTERFACE_MODE_SGMII) {
temp = phy_read(phydev, MII_M1111_PHY_EXT_SR);
if (temp < 0)
return temp;
temp &= ~(MII_M1111_HWCFG_MODE_MASK);
temp |= MII_M1111_HWCFG_MODE_SGMII_NO_CLK;
temp |= MII_M1111_HWCFG_FIBER_COPPER_AUTO;
err = phy_write(phydev, MII_M1111_PHY_EXT_SR, temp);
if (err < 0)
return err;
}
if (phydev->interface == PHY_INTERFACE_MODE_RTBI) {
temp = phy_read(phydev, MII_M1111_PHY_EXT_CR);
if (temp < 0)
return temp;
temp |= (MII_M1111_RX_DELAY | MII_M1111_TX_DELAY);
err = phy_write(phydev, MII_M1111_PHY_EXT_CR, temp);
if (err < 0)
return err;
temp = phy_read(phydev, MII_M1111_PHY_EXT_SR);
if (temp < 0)
return temp;
temp &= ~(MII_M1111_HWCFG_MODE_MASK | MII_M1111_HWCFG_FIBER_COPPER_RES);
temp |= 0x7 | MII_M1111_HWCFG_FIBER_COPPER_AUTO;
err = phy_write(phydev, MII_M1111_PHY_EXT_SR, temp);
if (err < 0)
return err;
/* soft reset */
err = phy_write(phydev, MII_BMCR, BMCR_RESET);
if (err < 0)
return err;
do
temp = phy_read(phydev, MII_BMCR);
while (temp & BMCR_RESET);
temp = phy_read(phydev, MII_M1111_PHY_EXT_SR);
if (temp < 0)
return temp;
temp &= ~(MII_M1111_HWCFG_MODE_MASK | MII_M1111_HWCFG_FIBER_COPPER_RES);
temp |= MII_M1111_HWCFG_MODE_COPPER_RTBI | MII_M1111_HWCFG_FIBER_COPPER_AUTO;
err = phy_write(phydev, MII_M1111_PHY_EXT_SR, temp);
if (err < 0)
return err;
}
err = phy_write(phydev, MII_BMCR, BMCR_RESET);
if (err < 0)
return err;
return 0;
}
static int m88e1118_config_aneg(struct phy_device *phydev)
{
int err;
err = phy_write(phydev, MII_BMCR, BMCR_RESET);
if (err < 0)
return err;
err = phy_write(phydev, MII_M1011_PHY_SCR,
MII_M1011_PHY_SCR_AUTO_CROSS);
if (err < 0)
return err;
err = genphy_config_aneg(phydev);
return 0;
}
static int m88e1118_config_init(struct phy_device *phydev)
{
int err;
/* Change address */
err = phy_write(phydev, 0x16, 0x0002);
if (err < 0)
return err;
/* Enable 1000 Mbit */
err = phy_write(phydev, 0x15, 0x1070);
if (err < 0)
return err;
/* Change address */
err = phy_write(phydev, 0x16, 0x0003);
if (err < 0)
return err;
/* Adjust LED Control */
err = phy_write(phydev, 0x10, 0x021e);
if (err < 0)
return err;
/* Reset address */
err = phy_write(phydev, 0x16, 0x0);
if (err < 0)
return err;
err = phy_write(phydev, MII_BMCR, BMCR_RESET);
if (err < 0)
return err;
return 0;
}
static int m88e1145_config_init(struct phy_device *phydev)
{
int err;
/* Take care of errata E0 & E1 */
err = phy_write(phydev, 0x1d, 0x001b);
if (err < 0)
return err;
err = phy_write(phydev, 0x1e, 0x418f);
if (err < 0)
return err;
err = phy_write(phydev, 0x1d, 0x0016);
if (err < 0)
return err;
err = phy_write(phydev, 0x1e, 0xa2da);
if (err < 0)
return err;
if (phydev->interface == PHY_INTERFACE_MODE_RGMII_ID) {
int temp = phy_read(phydev, MII_M1145_PHY_EXT_CR);
if (temp < 0)
return temp;
temp |= (MII_M1145_RGMII_RX_DELAY | MII_M1145_RGMII_TX_DELAY);
err = phy_write(phydev, MII_M1145_PHY_EXT_CR, temp);
if (err < 0)
return err;
if (phydev->dev_flags & M1145_DEV_FLAGS_RESISTANCE) {
err = phy_write(phydev, 0x1d, 0x0012);
if (err < 0)
return err;
temp = phy_read(phydev, 0x1e);
if (temp < 0)
return temp;
temp &= 0xf03f;
temp |= 2 << 9; /* 36 ohm */
temp |= 2 << 6; /* 39 ohm */
err = phy_write(phydev, 0x1e, temp);
if (err < 0)
return err;
err = phy_write(phydev, 0x1d, 0x3);
if (err < 0)
return err;
err = phy_write(phydev, 0x1e, 0x8000);
if (err < 0)
return err;
}
}
return 0;
}
/* marvell_read_status
*
* Generic status code does not detect Fiber correctly!
* Description:
* Check the link, then figure out the current state
* by comparing what we advertise with what the link partner
* advertises. Start by checking the gigabit possibilities,
* then move on to 10/100.
*/
static int marvell_read_status(struct phy_device *phydev)
{
int adv;
int err;
int lpa;
int status = 0;
/* Update the link, but return if there
* was an error */
err = genphy_update_link(phydev);
if (err)
return err;
if (AUTONEG_ENABLE == phydev->autoneg) {
status = phy_read(phydev, MII_M1011_PHY_STATUS);
if (status < 0)
return status;
lpa = phy_read(phydev, MII_LPA);
if (lpa < 0)
return lpa;
adv = phy_read(phydev, MII_ADVERTISE);
if (adv < 0)
return adv;
lpa &= adv;
if (status & MII_M1011_PHY_STATUS_FULLDUPLEX)
phydev->duplex = DUPLEX_FULL;
else
phydev->duplex = DUPLEX_HALF;
status = status & MII_M1011_PHY_STATUS_SPD_MASK;
phydev->pause = phydev->asym_pause = 0;
switch (status) {
case MII_M1011_PHY_STATUS_1000:
phydev->speed = SPEED_1000;
break;
case MII_M1011_PHY_STATUS_100:
phydev->speed = SPEED_100;
break;
default:
phydev->speed = SPEED_10;
break;
}
if (phydev->duplex == DUPLEX_FULL) {
phydev->pause = lpa & LPA_PAUSE_CAP ? 1 : 0;
phydev->asym_pause = lpa & LPA_PAUSE_ASYM ? 1 : 0;
}
} else {
int bmcr = phy_read(phydev, MII_BMCR);
if (bmcr < 0)
return bmcr;
if (bmcr & BMCR_FULLDPLX)
phydev->duplex = DUPLEX_FULL;
else
phydev->duplex = DUPLEX_HALF;
if (bmcr & BMCR_SPEED1000)
phydev->speed = SPEED_1000;
else if (bmcr & BMCR_SPEED100)
phydev->speed = SPEED_100;
else
phydev->speed = SPEED_10;
phydev->pause = phydev->asym_pause = 0;
}
return 0;
}
static int m88e1121_did_interrupt(struct phy_device *phydev)
{
int imask;
imask = phy_read(phydev, MII_M1011_IEVENT);
if (imask & MII_M1011_IMASK_INIT)
return 1;
return 0;
}
static struct phy_driver marvell_drivers[] = {
{
.phy_id = 0x01410c60,
.phy_id_mask = 0xfffffff0,
.name = "Marvell 88E1101",
.features = PHY_GBIT_FEATURES,
.flags = PHY_HAS_INTERRUPT,
.config_aneg = &marvell_config_aneg,
.read_status = &genphy_read_status,
.ack_interrupt = &marvell_ack_interrupt,
.config_intr = &marvell_config_intr,
.driver = { .owner = THIS_MODULE },
},
{
.phy_id = 0x01410c90,
.phy_id_mask = 0xfffffff0,
.name = "Marvell 88E1112",
.features = PHY_GBIT_FEATURES,
.flags = PHY_HAS_INTERRUPT,
.config_init = &m88e1111_config_init,
.config_aneg = &marvell_config_aneg,
.read_status = &genphy_read_status,
.ack_interrupt = &marvell_ack_interrupt,
.config_intr = &marvell_config_intr,
.driver = { .owner = THIS_MODULE },
},
{
.phy_id = 0x01410cc0,
.phy_id_mask = 0xfffffff0,
.name = "Marvell 88E1111",
.features = PHY_GBIT_FEATURES,
.flags = PHY_HAS_INTERRUPT,
.config_init = &m88e1111_config_init,
.config_aneg = &marvell_config_aneg,
.read_status = &marvell_read_status,
.ack_interrupt = &marvell_ack_interrupt,
.config_intr = &marvell_config_intr,
.driver = { .owner = THIS_MODULE },
},
{
.phy_id = 0x01410e10,
.phy_id_mask = 0xfffffff0,
.name = "Marvell 88E1118",
.features = PHY_GBIT_FEATURES,
.flags = PHY_HAS_INTERRUPT,
.config_init = &m88e1118_config_init,
.config_aneg = &m88e1118_config_aneg,
.read_status = &genphy_read_status,
.ack_interrupt = &marvell_ack_interrupt,
.config_intr = &marvell_config_intr,
.driver = {.owner = THIS_MODULE,},
},
{
.phy_id = 0x01410cb0,
.phy_id_mask = 0xfffffff0,
.name = "Marvell 88E1121R",
.features = PHY_GBIT_FEATURES,
.flags = PHY_HAS_INTERRUPT,
.config_aneg = &m88e1121_config_aneg,
.read_status = &marvell_read_status,
.ack_interrupt = &marvell_ack_interrupt,
.config_intr = &marvell_config_intr,
.did_interrupt = &m88e1121_did_interrupt,
.driver = { .owner = THIS_MODULE },
},
{
.phy_id = 0x01410cd0,
.phy_id_mask = 0xfffffff0,
.name = "Marvell 88E1145",
.features = PHY_GBIT_FEATURES,
.flags = PHY_HAS_INTERRUPT,
.config_init = &m88e1145_config_init,
.config_aneg = &marvell_config_aneg,
.read_status = &genphy_read_status,
.ack_interrupt = &marvell_ack_interrupt,
.config_intr = &marvell_config_intr,
.driver = { .owner = THIS_MODULE },
},
{
.phy_id = 0x01410e30,
.phy_id_mask = 0xfffffff0,
.name = "Marvell 88E1240",
.features = PHY_GBIT_FEATURES,
.flags = PHY_HAS_INTERRUPT,
.config_init = &m88e1111_config_init,
.config_aneg = &marvell_config_aneg,
.read_status = &genphy_read_status,
.ack_interrupt = &marvell_ack_interrupt,
.config_intr = &marvell_config_intr,
.driver = { .owner = THIS_MODULE },
},
};
static int __init marvell_init(void)
{
int ret;
int i;
for (i = 0; i < ARRAY_SIZE(marvell_drivers); i++) {
ret = phy_driver_register(&marvell_drivers[i]);
if (ret) {
while (i-- > 0)
phy_driver_unregister(&marvell_drivers[i]);
return ret;
}
}
return 0;
}
static void __exit marvell_exit(void)
{
int i;
for (i = 0; i < ARRAY_SIZE(marvell_drivers); i++)
phy_driver_unregister(&marvell_drivers[i]);
}
module_init(marvell_init);
module_exit(marvell_exit);
static struct mdio_device_id marvell_tbl[] = {
{ 0x01410c60, 0xfffffff0 },
{ 0x01410c90, 0xfffffff0 },
{ 0x01410cc0, 0xfffffff0 },
{ 0x01410e10, 0xfffffff0 },
{ 0x01410cb0, 0xfffffff0 },
{ 0x01410cd0, 0xfffffff0 },
{ 0x01410e30, 0xfffffff0 },
{ }
};
MODULE_DEVICE_TABLE(mdio, marvell_tbl);
| gpl-2.0 |
t0mm13b/ZTE-Blade-2.6.35.7 | drivers/net/wireless/iwlwifi/iwl-1000.c | 758 | 10077 | /******************************************************************************
*
* Copyright(c) 2008 - 2010 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
* Contact Information:
* Intel Linux Wireless <ilw@linux.intel.com>
* Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*
*****************************************************************************/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/dma-mapping.h>
#include <linux/delay.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/wireless.h>
#include <net/mac80211.h>
#include <linux/etherdevice.h>
#include <asm/unaligned.h>
#include "iwl-eeprom.h"
#include "iwl-dev.h"
#include "iwl-core.h"
#include "iwl-io.h"
#include "iwl-sta.h"
#include "iwl-agn.h"
#include "iwl-helpers.h"
#include "iwl-agn-hw.h"
#include "iwl-agn-led.h"
#include "iwl-agn-debugfs.h"
/* Highest firmware API version supported */
#define IWL1000_UCODE_API_MAX 3
/* Lowest firmware API version supported */
#define IWL1000_UCODE_API_MIN 1
#define IWL1000_FW_PRE "iwlwifi-1000-"
#define _IWL1000_MODULE_FIRMWARE(api) IWL1000_FW_PRE #api ".ucode"
#define IWL1000_MODULE_FIRMWARE(api) _IWL1000_MODULE_FIRMWARE(api)
/*
* For 1000, use advance thermal throttling critical temperature threshold,
* but legacy thermal management implementation for now.
* This is for the reason of 1000 uCode using advance thermal throttling API
* but not implement ct_kill_exit based on ct_kill exit temperature
* so the thermal throttling will still based on legacy thermal throttling
* management.
* The code here need to be modified once 1000 uCode has the advanced thermal
* throttling algorithm in place
*/
static void iwl1000_set_ct_threshold(struct iwl_priv *priv)
{
/* want Celsius */
priv->hw_params.ct_kill_threshold = CT_KILL_THRESHOLD_LEGACY;
priv->hw_params.ct_kill_exit_threshold = CT_KILL_EXIT_THRESHOLD;
}
/* NIC configuration for 1000 series */
static void iwl1000_nic_config(struct iwl_priv *priv)
{
/* set CSR_HW_CONFIG_REG for uCode use */
iwl_set_bit(priv, CSR_HW_IF_CONFIG_REG,
CSR_HW_IF_CONFIG_REG_BIT_RADIO_SI |
CSR_HW_IF_CONFIG_REG_BIT_MAC_SI);
/* Setting digital SVR for 1000 card to 1.32V */
/* locking is acquired in iwl_set_bits_mask_prph() function */
iwl_set_bits_mask_prph(priv, APMG_DIGITAL_SVR_REG,
APMG_SVR_DIGITAL_VOLTAGE_1_32,
~APMG_SVR_VOLTAGE_CONFIG_BIT_MSK);
}
static struct iwl_sensitivity_ranges iwl1000_sensitivity = {
.min_nrg_cck = 95,
.max_nrg_cck = 0, /* not used, set to 0 */
.auto_corr_min_ofdm = 90,
.auto_corr_min_ofdm_mrc = 170,
.auto_corr_min_ofdm_x1 = 120,
.auto_corr_min_ofdm_mrc_x1 = 240,
.auto_corr_max_ofdm = 120,
.auto_corr_max_ofdm_mrc = 210,
.auto_corr_max_ofdm_x1 = 155,
.auto_corr_max_ofdm_mrc_x1 = 290,
.auto_corr_min_cck = 125,
.auto_corr_max_cck = 200,
.auto_corr_min_cck_mrc = 170,
.auto_corr_max_cck_mrc = 400,
.nrg_th_cck = 95,
.nrg_th_ofdm = 95,
.barker_corr_th_min = 190,
.barker_corr_th_min_mrc = 390,
.nrg_th_cca = 62,
};
static int iwl1000_hw_set_hw_params(struct iwl_priv *priv)
{
if (priv->cfg->mod_params->num_of_queues >= IWL_MIN_NUM_QUEUES &&
priv->cfg->mod_params->num_of_queues <= IWLAGN_NUM_QUEUES)
priv->cfg->num_of_queues =
priv->cfg->mod_params->num_of_queues;
priv->hw_params.max_txq_num = priv->cfg->num_of_queues;
priv->hw_params.dma_chnl_num = FH50_TCSR_CHNL_NUM;
priv->hw_params.scd_bc_tbls_size =
priv->cfg->num_of_queues *
sizeof(struct iwlagn_scd_bc_tbl);
priv->hw_params.tfd_size = sizeof(struct iwl_tfd);
priv->hw_params.max_stations = IWL5000_STATION_COUNT;
priv->hw_params.bcast_sta_id = IWL5000_BROADCAST_ID;
priv->hw_params.max_data_size = IWLAGN_RTC_DATA_SIZE;
priv->hw_params.max_inst_size = IWLAGN_RTC_INST_SIZE;
priv->hw_params.max_bsm_size = 0;
priv->hw_params.ht40_channel = BIT(IEEE80211_BAND_2GHZ) |
BIT(IEEE80211_BAND_5GHZ);
priv->hw_params.rx_wrt_ptr_reg = FH_RSCSR_CHNL0_WPTR;
priv->hw_params.tx_chains_num = num_of_ant(priv->cfg->valid_tx_ant);
priv->hw_params.rx_chains_num = num_of_ant(priv->cfg->valid_rx_ant);
priv->hw_params.valid_tx_ant = priv->cfg->valid_tx_ant;
priv->hw_params.valid_rx_ant = priv->cfg->valid_rx_ant;
if (priv->cfg->ops->lib->temp_ops.set_ct_kill)
priv->cfg->ops->lib->temp_ops.set_ct_kill(priv);
/* Set initial sensitivity parameters */
/* Set initial calibration set */
priv->hw_params.sens = &iwl1000_sensitivity;
priv->hw_params.calib_init_cfg =
BIT(IWL_CALIB_XTAL) |
BIT(IWL_CALIB_LO) |
BIT(IWL_CALIB_TX_IQ) |
BIT(IWL_CALIB_TX_IQ_PERD) |
BIT(IWL_CALIB_BASE_BAND);
return 0;
}
static struct iwl_lib_ops iwl1000_lib = {
.set_hw_params = iwl1000_hw_set_hw_params,
.txq_update_byte_cnt_tbl = iwlagn_txq_update_byte_cnt_tbl,
.txq_inval_byte_cnt_tbl = iwlagn_txq_inval_byte_cnt_tbl,
.txq_set_sched = iwlagn_txq_set_sched,
.txq_agg_enable = iwlagn_txq_agg_enable,
.txq_agg_disable = iwlagn_txq_agg_disable,
.txq_attach_buf_to_tfd = iwl_hw_txq_attach_buf_to_tfd,
.txq_free_tfd = iwl_hw_txq_free_tfd,
.txq_init = iwl_hw_tx_queue_init,
.rx_handler_setup = iwlagn_rx_handler_setup,
.setup_deferred_work = iwlagn_setup_deferred_work,
.is_valid_rtc_data_addr = iwlagn_hw_valid_rtc_data_addr,
.load_ucode = iwlagn_load_ucode,
.dump_nic_event_log = iwl_dump_nic_event_log,
.dump_nic_error_log = iwl_dump_nic_error_log,
.dump_csr = iwl_dump_csr,
.dump_fh = iwl_dump_fh,
.init_alive_start = iwlagn_init_alive_start,
.alive_notify = iwlagn_alive_notify,
.send_tx_power = iwlagn_send_tx_power,
.update_chain_flags = iwl_update_chain_flags,
.apm_ops = {
.init = iwl_apm_init,
.stop = iwl_apm_stop,
.config = iwl1000_nic_config,
.set_pwr_src = iwl_set_pwr_src,
},
.eeprom_ops = {
.regulatory_bands = {
EEPROM_REG_BAND_1_CHANNELS,
EEPROM_REG_BAND_2_CHANNELS,
EEPROM_REG_BAND_3_CHANNELS,
EEPROM_REG_BAND_4_CHANNELS,
EEPROM_REG_BAND_5_CHANNELS,
EEPROM_REG_BAND_24_HT40_CHANNELS,
EEPROM_REG_BAND_52_HT40_CHANNELS
},
.verify_signature = iwlcore_eeprom_verify_signature,
.acquire_semaphore = iwlcore_eeprom_acquire_semaphore,
.release_semaphore = iwlcore_eeprom_release_semaphore,
.calib_version = iwlagn_eeprom_calib_version,
.query_addr = iwlagn_eeprom_query_addr,
},
.post_associate = iwl_post_associate,
.isr = iwl_isr_ict,
.config_ap = iwl_config_ap,
.temp_ops = {
.temperature = iwlagn_temperature,
.set_ct_kill = iwl1000_set_ct_threshold,
},
.manage_ibss_station = iwlagn_manage_ibss_station,
.debugfs_ops = {
.rx_stats_read = iwl_ucode_rx_stats_read,
.tx_stats_read = iwl_ucode_tx_stats_read,
.general_stats_read = iwl_ucode_general_stats_read,
},
.recover_from_tx_stall = iwl_bg_monitor_recover,
.check_plcp_health = iwl_good_plcp_health,
.check_ack_health = iwl_good_ack_health,
};
static const struct iwl_ops iwl1000_ops = {
.lib = &iwl1000_lib,
.hcmd = &iwlagn_hcmd,
.utils = &iwlagn_hcmd_utils,
.led = &iwlagn_led_ops,
};
struct iwl_cfg iwl1000_bgn_cfg = {
.name = "Intel(R) Centrino(R) Wireless-N 1000 BGN",
.fw_name_pre = IWL1000_FW_PRE,
.ucode_api_max = IWL1000_UCODE_API_MAX,
.ucode_api_min = IWL1000_UCODE_API_MIN,
.sku = IWL_SKU_G|IWL_SKU_N,
.ops = &iwl1000_ops,
.eeprom_size = OTP_LOW_IMAGE_SIZE,
.eeprom_ver = EEPROM_1000_EEPROM_VERSION,
.eeprom_calib_ver = EEPROM_1000_TX_POWER_VERSION,
.num_of_queues = IWLAGN_NUM_QUEUES,
.num_of_ampdu_queues = IWLAGN_NUM_AMPDU_QUEUES,
.mod_params = &iwlagn_mod_params,
.valid_tx_ant = ANT_A,
.valid_rx_ant = ANT_AB,
.pll_cfg_val = CSR50_ANA_PLL_CFG_VAL,
.set_l0s = true,
.use_bsm = false,
.max_ll_items = OTP_MAX_LL_ITEMS_1000,
.shadow_ram_support = false,
.ht_greenfield_support = true,
.led_compensation = 51,
.use_rts_for_ht = true, /* use rts/cts protection */
.chain_noise_num_beacons = IWL_CAL_NUM_BEACONS,
.support_ct_kill_exit = true,
.plcp_delta_threshold = IWL_MAX_PLCP_ERR_EXT_LONG_THRESHOLD_DEF,
.chain_noise_scale = 1000,
.monitor_recover_period = IWL_MONITORING_PERIOD,
.max_event_log_size = 128,
.ucode_tracing = true,
.sensitivity_calib_by_driver = true,
.chain_noise_calib_by_driver = true,
};
struct iwl_cfg iwl1000_bg_cfg = {
.name = "Intel(R) Centrino(R) Wireless-N 1000 BG",
.fw_name_pre = IWL1000_FW_PRE,
.ucode_api_max = IWL1000_UCODE_API_MAX,
.ucode_api_min = IWL1000_UCODE_API_MIN,
.sku = IWL_SKU_G,
.ops = &iwl1000_ops,
.eeprom_size = OTP_LOW_IMAGE_SIZE,
.eeprom_ver = EEPROM_1000_EEPROM_VERSION,
.eeprom_calib_ver = EEPROM_1000_TX_POWER_VERSION,
.num_of_queues = IWLAGN_NUM_QUEUES,
.num_of_ampdu_queues = IWLAGN_NUM_AMPDU_QUEUES,
.mod_params = &iwlagn_mod_params,
.valid_tx_ant = ANT_A,
.valid_rx_ant = ANT_AB,
.pll_cfg_val = CSR50_ANA_PLL_CFG_VAL,
.set_l0s = true,
.use_bsm = false,
.max_ll_items = OTP_MAX_LL_ITEMS_1000,
.shadow_ram_support = false,
.led_compensation = 51,
.chain_noise_num_beacons = IWL_CAL_NUM_BEACONS,
.support_ct_kill_exit = true,
.plcp_delta_threshold = IWL_MAX_PLCP_ERR_EXT_LONG_THRESHOLD_DEF,
.chain_noise_scale = 1000,
.monitor_recover_period = IWL_MONITORING_PERIOD,
.max_event_log_size = 128,
.ucode_tracing = true,
.sensitivity_calib_by_driver = true,
.chain_noise_calib_by_driver = true,
};
MODULE_FIRMWARE(IWL1000_MODULE_FIRMWARE(IWL1000_UCODE_API_MAX));
| gpl-2.0 |
Stane1983/amlogic-m6_m8 | sound/soc/codecs/adav80x.c | 1782 | 25644 | /*
* ADAV80X Audio Codec driver supporting ADAV801, ADAV803
*
* Copyright 2011 Analog Devices Inc.
* Author: Yi Li <yi.li@analog.com>
* Author: Lars-Peter Clausen <lars@metafoo.de>
*
* Licensed under the GPL-2 or later.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/i2c.h>
#include <linux/spi/spi.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/tlv.h>
#include <sound/soc.h>
#include "adav80x.h"
#define ADAV80X_PLAYBACK_CTRL 0x04
#define ADAV80X_AUX_IN_CTRL 0x05
#define ADAV80X_REC_CTRL 0x06
#define ADAV80X_AUX_OUT_CTRL 0x07
#define ADAV80X_DPATH_CTRL1 0x62
#define ADAV80X_DPATH_CTRL2 0x63
#define ADAV80X_DAC_CTRL1 0x64
#define ADAV80X_DAC_CTRL2 0x65
#define ADAV80X_DAC_CTRL3 0x66
#define ADAV80X_DAC_L_VOL 0x68
#define ADAV80X_DAC_R_VOL 0x69
#define ADAV80X_PGA_L_VOL 0x6c
#define ADAV80X_PGA_R_VOL 0x6d
#define ADAV80X_ADC_CTRL1 0x6e
#define ADAV80X_ADC_CTRL2 0x6f
#define ADAV80X_ADC_L_VOL 0x70
#define ADAV80X_ADC_R_VOL 0x71
#define ADAV80X_PLL_CTRL1 0x74
#define ADAV80X_PLL_CTRL2 0x75
#define ADAV80X_ICLK_CTRL1 0x76
#define ADAV80X_ICLK_CTRL2 0x77
#define ADAV80X_PLL_CLK_SRC 0x78
#define ADAV80X_PLL_OUTE 0x7a
#define ADAV80X_PLL_CLK_SRC_PLL_XIN(pll) 0x00
#define ADAV80X_PLL_CLK_SRC_PLL_MCLKI(pll) (0x40 << (pll))
#define ADAV80X_PLL_CLK_SRC_PLL_MASK(pll) (0x40 << (pll))
#define ADAV80X_ICLK_CTRL1_DAC_SRC(src) ((src) << 5)
#define ADAV80X_ICLK_CTRL1_ADC_SRC(src) ((src) << 2)
#define ADAV80X_ICLK_CTRL1_ICLK2_SRC(src) (src)
#define ADAV80X_ICLK_CTRL2_ICLK1_SRC(src) ((src) << 3)
#define ADAV80X_PLL_CTRL1_PLLDIV 0x10
#define ADAV80X_PLL_CTRL1_PLLPD(pll) (0x04 << (pll))
#define ADAV80X_PLL_CTRL1_XTLPD 0x02
#define ADAV80X_PLL_CTRL2_FIELD(pll, x) ((x) << ((pll) * 4))
#define ADAV80X_PLL_CTRL2_FS_48(pll) ADAV80X_PLL_CTRL2_FIELD((pll), 0x00)
#define ADAV80X_PLL_CTRL2_FS_32(pll) ADAV80X_PLL_CTRL2_FIELD((pll), 0x08)
#define ADAV80X_PLL_CTRL2_FS_44(pll) ADAV80X_PLL_CTRL2_FIELD((pll), 0x0c)
#define ADAV80X_PLL_CTRL2_SEL(pll) ADAV80X_PLL_CTRL2_FIELD((pll), 0x02)
#define ADAV80X_PLL_CTRL2_DOUB(pll) ADAV80X_PLL_CTRL2_FIELD((pll), 0x01)
#define ADAV80X_PLL_CTRL2_PLL_MASK(pll) ADAV80X_PLL_CTRL2_FIELD((pll), 0x0f)
#define ADAV80X_ADC_CTRL1_MODULATOR_MASK 0x80
#define ADAV80X_ADC_CTRL1_MODULATOR_128FS 0x00
#define ADAV80X_ADC_CTRL1_MODULATOR_64FS 0x80
#define ADAV80X_DAC_CTRL1_PD 0x80
#define ADAV80X_DAC_CTRL2_DIV1 0x00
#define ADAV80X_DAC_CTRL2_DIV1_5 0x10
#define ADAV80X_DAC_CTRL2_DIV2 0x20
#define ADAV80X_DAC_CTRL2_DIV3 0x30
#define ADAV80X_DAC_CTRL2_DIV_MASK 0x30
#define ADAV80X_DAC_CTRL2_INTERPOL_256FS 0x00
#define ADAV80X_DAC_CTRL2_INTERPOL_128FS 0x40
#define ADAV80X_DAC_CTRL2_INTERPOL_64FS 0x80
#define ADAV80X_DAC_CTRL2_INTERPOL_MASK 0xc0
#define ADAV80X_DAC_CTRL2_DEEMPH_NONE 0x00
#define ADAV80X_DAC_CTRL2_DEEMPH_44 0x01
#define ADAV80X_DAC_CTRL2_DEEMPH_32 0x02
#define ADAV80X_DAC_CTRL2_DEEMPH_48 0x03
#define ADAV80X_DAC_CTRL2_DEEMPH_MASK 0x01
#define ADAV80X_CAPTURE_MODE_MASTER 0x20
#define ADAV80X_CAPTURE_WORD_LEN24 0x00
#define ADAV80X_CAPTURE_WORD_LEN20 0x04
#define ADAV80X_CAPTRUE_WORD_LEN18 0x08
#define ADAV80X_CAPTURE_WORD_LEN16 0x0c
#define ADAV80X_CAPTURE_WORD_LEN_MASK 0x0c
#define ADAV80X_CAPTURE_MODE_LEFT_J 0x00
#define ADAV80X_CAPTURE_MODE_I2S 0x01
#define ADAV80X_CAPTURE_MODE_RIGHT_J 0x03
#define ADAV80X_CAPTURE_MODE_MASK 0x03
#define ADAV80X_PLAYBACK_MODE_MASTER 0x10
#define ADAV80X_PLAYBACK_MODE_LEFT_J 0x00
#define ADAV80X_PLAYBACK_MODE_I2S 0x01
#define ADAV80X_PLAYBACK_MODE_RIGHT_J_24 0x04
#define ADAV80X_PLAYBACK_MODE_RIGHT_J_20 0x05
#define ADAV80X_PLAYBACK_MODE_RIGHT_J_18 0x06
#define ADAV80X_PLAYBACK_MODE_RIGHT_J_16 0x07
#define ADAV80X_PLAYBACK_MODE_MASK 0x07
#define ADAV80X_PLL_OUTE_SYSCLKPD(x) BIT(2 - (x))
static u8 adav80x_default_regs[] = {
0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x02, 0x01, 0x80, 0x26, 0x00, 0x00,
0x02, 0x40, 0x20, 0x00, 0x09, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd1, 0x92, 0xb1, 0x37,
0x48, 0xd2, 0xfb, 0xca, 0xd2, 0x15, 0xe8, 0x29, 0xb9, 0x6a, 0xda, 0x2b,
0xb7, 0xc0, 0x11, 0x65, 0x5c, 0xf6, 0xff, 0x8d, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa5, 0x00, 0x00,
0x00, 0xe8, 0x46, 0xe1, 0x5b, 0xd3, 0x43, 0x77, 0x93, 0xa7, 0x44, 0xee,
0x32, 0x12, 0xc0, 0x11, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x3f, 0x3f,
0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x1d, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x52, 0x00,
};
struct adav80x {
enum snd_soc_control_type control_type;
enum adav80x_clk_src clk_src;
unsigned int sysclk;
enum adav80x_pll_src pll_src;
unsigned int dai_fmt[2];
unsigned int rate;
bool deemph;
bool sysclk_pd[3];
};
static const char *adav80x_mux_text[] = {
"ADC",
"Playback",
"Aux Playback",
};
static const unsigned int adav80x_mux_values[] = {
0, 2, 3,
};
#define ADAV80X_MUX_ENUM_DECL(name, reg, shift) \
SOC_VALUE_ENUM_DOUBLE_DECL(name, reg, shift, 7, \
ARRAY_SIZE(adav80x_mux_text), adav80x_mux_text, \
adav80x_mux_values)
static ADAV80X_MUX_ENUM_DECL(adav80x_aux_capture_enum, ADAV80X_DPATH_CTRL1, 0);
static ADAV80X_MUX_ENUM_DECL(adav80x_capture_enum, ADAV80X_DPATH_CTRL1, 3);
static ADAV80X_MUX_ENUM_DECL(adav80x_dac_enum, ADAV80X_DPATH_CTRL2, 3);
static const struct snd_kcontrol_new adav80x_aux_capture_mux_ctrl =
SOC_DAPM_VALUE_ENUM("Route", adav80x_aux_capture_enum);
static const struct snd_kcontrol_new adav80x_capture_mux_ctrl =
SOC_DAPM_VALUE_ENUM("Route", adav80x_capture_enum);
static const struct snd_kcontrol_new adav80x_dac_mux_ctrl =
SOC_DAPM_VALUE_ENUM("Route", adav80x_dac_enum);
#define ADAV80X_MUX(name, ctrl) \
SND_SOC_DAPM_VALUE_MUX(name, SND_SOC_NOPM, 0, 0, ctrl)
static const struct snd_soc_dapm_widget adav80x_dapm_widgets[] = {
SND_SOC_DAPM_DAC("DAC", NULL, ADAV80X_DAC_CTRL1, 7, 1),
SND_SOC_DAPM_ADC("ADC", NULL, ADAV80X_ADC_CTRL1, 5, 1),
SND_SOC_DAPM_PGA("Right PGA", ADAV80X_ADC_CTRL1, 0, 1, NULL, 0),
SND_SOC_DAPM_PGA("Left PGA", ADAV80X_ADC_CTRL1, 1, 1, NULL, 0),
SND_SOC_DAPM_AIF_OUT("AIFOUT", "HiFi Capture", 0, SND_SOC_NOPM, 0, 0),
SND_SOC_DAPM_AIF_IN("AIFIN", "HiFi Playback", 0, SND_SOC_NOPM, 0, 0),
SND_SOC_DAPM_AIF_OUT("AIFAUXOUT", "Aux Capture", 0, SND_SOC_NOPM, 0, 0),
SND_SOC_DAPM_AIF_IN("AIFAUXIN", "Aux Playback", 0, SND_SOC_NOPM, 0, 0),
ADAV80X_MUX("Aux Capture Select", &adav80x_aux_capture_mux_ctrl),
ADAV80X_MUX("Capture Select", &adav80x_capture_mux_ctrl),
ADAV80X_MUX("DAC Select", &adav80x_dac_mux_ctrl),
SND_SOC_DAPM_INPUT("VINR"),
SND_SOC_DAPM_INPUT("VINL"),
SND_SOC_DAPM_OUTPUT("VOUTR"),
SND_SOC_DAPM_OUTPUT("VOUTL"),
SND_SOC_DAPM_SUPPLY("SYSCLK", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_SUPPLY("PLL1", ADAV80X_PLL_CTRL1, 2, 1, NULL, 0),
SND_SOC_DAPM_SUPPLY("PLL2", ADAV80X_PLL_CTRL1, 3, 1, NULL, 0),
SND_SOC_DAPM_SUPPLY("OSC", ADAV80X_PLL_CTRL1, 1, 1, NULL, 0),
};
static int adav80x_dapm_sysclk_check(struct snd_soc_dapm_widget *source,
struct snd_soc_dapm_widget *sink)
{
struct snd_soc_codec *codec = source->codec;
struct adav80x *adav80x = snd_soc_codec_get_drvdata(codec);
const char *clk;
switch (adav80x->clk_src) {
case ADAV80X_CLK_PLL1:
clk = "PLL1";
break;
case ADAV80X_CLK_PLL2:
clk = "PLL2";
break;
case ADAV80X_CLK_XTAL:
clk = "OSC";
break;
default:
return 0;
}
return strcmp(source->name, clk) == 0;
}
static int adav80x_dapm_pll_check(struct snd_soc_dapm_widget *source,
struct snd_soc_dapm_widget *sink)
{
struct snd_soc_codec *codec = source->codec;
struct adav80x *adav80x = snd_soc_codec_get_drvdata(codec);
return adav80x->pll_src == ADAV80X_PLL_SRC_XTAL;
}
static const struct snd_soc_dapm_route adav80x_dapm_routes[] = {
{ "DAC Select", "ADC", "ADC" },
{ "DAC Select", "Playback", "AIFIN" },
{ "DAC Select", "Aux Playback", "AIFAUXIN" },
{ "DAC", NULL, "DAC Select" },
{ "Capture Select", "ADC", "ADC" },
{ "Capture Select", "Playback", "AIFIN" },
{ "Capture Select", "Aux Playback", "AIFAUXIN" },
{ "AIFOUT", NULL, "Capture Select" },
{ "Aux Capture Select", "ADC", "ADC" },
{ "Aux Capture Select", "Playback", "AIFIN" },
{ "Aux Capture Select", "Aux Playback", "AIFAUXIN" },
{ "AIFAUXOUT", NULL, "Aux Capture Select" },
{ "VOUTR", NULL, "DAC" },
{ "VOUTL", NULL, "DAC" },
{ "Left PGA", NULL, "VINL" },
{ "Right PGA", NULL, "VINR" },
{ "ADC", NULL, "Left PGA" },
{ "ADC", NULL, "Right PGA" },
{ "SYSCLK", NULL, "PLL1", adav80x_dapm_sysclk_check },
{ "SYSCLK", NULL, "PLL2", adav80x_dapm_sysclk_check },
{ "SYSCLK", NULL, "OSC", adav80x_dapm_sysclk_check },
{ "PLL1", NULL, "OSC", adav80x_dapm_pll_check },
{ "PLL2", NULL, "OSC", adav80x_dapm_pll_check },
{ "ADC", NULL, "SYSCLK" },
{ "DAC", NULL, "SYSCLK" },
{ "AIFOUT", NULL, "SYSCLK" },
{ "AIFAUXOUT", NULL, "SYSCLK" },
{ "AIFIN", NULL, "SYSCLK" },
{ "AIFAUXIN", NULL, "SYSCLK" },
};
static int adav80x_set_deemph(struct snd_soc_codec *codec)
{
struct adav80x *adav80x = snd_soc_codec_get_drvdata(codec);
unsigned int val;
if (adav80x->deemph) {
switch (adav80x->rate) {
case 32000:
val = ADAV80X_DAC_CTRL2_DEEMPH_32;
break;
case 44100:
val = ADAV80X_DAC_CTRL2_DEEMPH_44;
break;
case 48000:
case 64000:
case 88200:
case 96000:
val = ADAV80X_DAC_CTRL2_DEEMPH_48;
break;
default:
val = ADAV80X_DAC_CTRL2_DEEMPH_NONE;
break;
}
} else {
val = ADAV80X_DAC_CTRL2_DEEMPH_NONE;
}
return snd_soc_update_bits(codec, ADAV80X_DAC_CTRL2,
ADAV80X_DAC_CTRL2_DEEMPH_MASK, val);
}
static int adav80x_put_deemph(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct adav80x *adav80x = snd_soc_codec_get_drvdata(codec);
unsigned int deemph = ucontrol->value.enumerated.item[0];
if (deemph > 1)
return -EINVAL;
adav80x->deemph = deemph;
return adav80x_set_deemph(codec);
}
static int adav80x_get_deemph(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct adav80x *adav80x = snd_soc_codec_get_drvdata(codec);
ucontrol->value.enumerated.item[0] = adav80x->deemph;
return 0;
};
static const DECLARE_TLV_DB_SCALE(adav80x_inpga_tlv, 0, 50, 0);
static const DECLARE_TLV_DB_MINMAX(adav80x_digital_tlv, -9563, 0);
static const struct snd_kcontrol_new adav80x_controls[] = {
SOC_DOUBLE_R_TLV("Master Playback Volume", ADAV80X_DAC_L_VOL,
ADAV80X_DAC_R_VOL, 0, 0xff, 0, adav80x_digital_tlv),
SOC_DOUBLE_R_TLV("Master Capture Volume", ADAV80X_ADC_L_VOL,
ADAV80X_ADC_R_VOL, 0, 0xff, 0, adav80x_digital_tlv),
SOC_DOUBLE_R_TLV("PGA Capture Volume", ADAV80X_PGA_L_VOL,
ADAV80X_PGA_R_VOL, 0, 0x30, 0, adav80x_inpga_tlv),
SOC_DOUBLE("Master Playback Switch", ADAV80X_DAC_CTRL1, 0, 1, 1, 0),
SOC_DOUBLE("Master Capture Switch", ADAV80X_ADC_CTRL1, 2, 3, 1, 1),
SOC_SINGLE("ADC High Pass Filter Switch", ADAV80X_ADC_CTRL1, 6, 1, 0),
SOC_SINGLE_BOOL_EXT("Playback De-emphasis Switch", 0,
adav80x_get_deemph, adav80x_put_deemph),
};
static unsigned int adav80x_port_ctrl_regs[2][2] = {
{ ADAV80X_REC_CTRL, ADAV80X_PLAYBACK_CTRL, },
{ ADAV80X_AUX_OUT_CTRL, ADAV80X_AUX_IN_CTRL },
};
static int adav80x_set_dai_fmt(struct snd_soc_dai *dai, unsigned int fmt)
{
struct snd_soc_codec *codec = dai->codec;
struct adav80x *adav80x = snd_soc_codec_get_drvdata(codec);
unsigned int capture = 0x00;
unsigned int playback = 0x00;
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBM_CFM:
capture |= ADAV80X_CAPTURE_MODE_MASTER;
playback |= ADAV80X_PLAYBACK_MODE_MASTER;
case SND_SOC_DAIFMT_CBS_CFS:
break;
default:
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) {
case SND_SOC_DAIFMT_I2S:
capture |= ADAV80X_CAPTURE_MODE_I2S;
playback |= ADAV80X_PLAYBACK_MODE_I2S;
break;
case SND_SOC_DAIFMT_LEFT_J:
capture |= ADAV80X_CAPTURE_MODE_LEFT_J;
playback |= ADAV80X_PLAYBACK_MODE_LEFT_J;
break;
case SND_SOC_DAIFMT_RIGHT_J:
capture |= ADAV80X_CAPTURE_MODE_RIGHT_J;
playback |= ADAV80X_PLAYBACK_MODE_RIGHT_J_24;
break;
default:
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
case SND_SOC_DAIFMT_NB_NF:
break;
default:
return -EINVAL;
}
snd_soc_update_bits(codec, adav80x_port_ctrl_regs[dai->id][0],
ADAV80X_CAPTURE_MODE_MASK | ADAV80X_CAPTURE_MODE_MASTER,
capture);
snd_soc_write(codec, adav80x_port_ctrl_regs[dai->id][1], playback);
adav80x->dai_fmt[dai->id] = fmt & SND_SOC_DAIFMT_FORMAT_MASK;
return 0;
}
static int adav80x_set_adc_clock(struct snd_soc_codec *codec,
unsigned int sample_rate)
{
unsigned int val;
if (sample_rate <= 48000)
val = ADAV80X_ADC_CTRL1_MODULATOR_128FS;
else
val = ADAV80X_ADC_CTRL1_MODULATOR_64FS;
snd_soc_update_bits(codec, ADAV80X_ADC_CTRL1,
ADAV80X_ADC_CTRL1_MODULATOR_MASK, val);
return 0;
}
static int adav80x_set_dac_clock(struct snd_soc_codec *codec,
unsigned int sample_rate)
{
unsigned int val;
if (sample_rate <= 48000)
val = ADAV80X_DAC_CTRL2_DIV1 | ADAV80X_DAC_CTRL2_INTERPOL_256FS;
else
val = ADAV80X_DAC_CTRL2_DIV2 | ADAV80X_DAC_CTRL2_INTERPOL_128FS;
snd_soc_update_bits(codec, ADAV80X_DAC_CTRL2,
ADAV80X_DAC_CTRL2_DIV_MASK | ADAV80X_DAC_CTRL2_INTERPOL_MASK,
val);
return 0;
}
static int adav80x_set_capture_pcm_format(struct snd_soc_codec *codec,
struct snd_soc_dai *dai, snd_pcm_format_t format)
{
unsigned int val;
switch (format) {
case SNDRV_PCM_FORMAT_S16_LE:
val = ADAV80X_CAPTURE_WORD_LEN16;
break;
case SNDRV_PCM_FORMAT_S18_3LE:
val = ADAV80X_CAPTRUE_WORD_LEN18;
break;
case SNDRV_PCM_FORMAT_S20_3LE:
val = ADAV80X_CAPTURE_WORD_LEN20;
break;
case SNDRV_PCM_FORMAT_S24_LE:
val = ADAV80X_CAPTURE_WORD_LEN24;
break;
default:
return -EINVAL;
}
snd_soc_update_bits(codec, adav80x_port_ctrl_regs[dai->id][0],
ADAV80X_CAPTURE_WORD_LEN_MASK, val);
return 0;
}
static int adav80x_set_playback_pcm_format(struct snd_soc_codec *codec,
struct snd_soc_dai *dai, snd_pcm_format_t format)
{
struct adav80x *adav80x = snd_soc_codec_get_drvdata(codec);
unsigned int val;
if (adav80x->dai_fmt[dai->id] != SND_SOC_DAIFMT_RIGHT_J)
return 0;
switch (format) {
case SNDRV_PCM_FORMAT_S16_LE:
val = ADAV80X_PLAYBACK_MODE_RIGHT_J_16;
break;
case SNDRV_PCM_FORMAT_S18_3LE:
val = ADAV80X_PLAYBACK_MODE_RIGHT_J_18;
break;
case SNDRV_PCM_FORMAT_S20_3LE:
val = ADAV80X_PLAYBACK_MODE_RIGHT_J_20;
break;
case SNDRV_PCM_FORMAT_S24_LE:
val = ADAV80X_PLAYBACK_MODE_RIGHT_J_24;
break;
default:
return -EINVAL;
}
snd_soc_update_bits(codec, adav80x_port_ctrl_regs[dai->id][1],
ADAV80X_PLAYBACK_MODE_MASK, val);
return 0;
}
static int adav80x_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params, struct snd_soc_dai *dai)
{
struct snd_soc_codec *codec = dai->codec;
struct adav80x *adav80x = snd_soc_codec_get_drvdata(codec);
unsigned int rate = params_rate(params);
if (rate * 256 != adav80x->sysclk)
return -EINVAL;
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
adav80x_set_playback_pcm_format(codec, dai,
params_format(params));
adav80x_set_dac_clock(codec, rate);
} else {
adav80x_set_capture_pcm_format(codec, dai,
params_format(params));
adav80x_set_adc_clock(codec, rate);
}
adav80x->rate = rate;
adav80x_set_deemph(codec);
return 0;
}
static int adav80x_set_sysclk(struct snd_soc_codec *codec,
int clk_id, int source,
unsigned int freq, int dir)
{
struct adav80x *adav80x = snd_soc_codec_get_drvdata(codec);
if (dir == SND_SOC_CLOCK_IN) {
switch (clk_id) {
case ADAV80X_CLK_XIN:
case ADAV80X_CLK_XTAL:
case ADAV80X_CLK_MCLKI:
case ADAV80X_CLK_PLL1:
case ADAV80X_CLK_PLL2:
break;
default:
return -EINVAL;
}
adav80x->sysclk = freq;
if (adav80x->clk_src != clk_id) {
unsigned int iclk_ctrl1, iclk_ctrl2;
adav80x->clk_src = clk_id;
if (clk_id == ADAV80X_CLK_XTAL)
clk_id = ADAV80X_CLK_XIN;
iclk_ctrl1 = ADAV80X_ICLK_CTRL1_DAC_SRC(clk_id) |
ADAV80X_ICLK_CTRL1_ADC_SRC(clk_id) |
ADAV80X_ICLK_CTRL1_ICLK2_SRC(clk_id);
iclk_ctrl2 = ADAV80X_ICLK_CTRL2_ICLK1_SRC(clk_id);
snd_soc_write(codec, ADAV80X_ICLK_CTRL1, iclk_ctrl1);
snd_soc_write(codec, ADAV80X_ICLK_CTRL2, iclk_ctrl2);
snd_soc_dapm_sync(&codec->dapm);
}
} else {
unsigned int mask;
switch (clk_id) {
case ADAV80X_CLK_SYSCLK1:
case ADAV80X_CLK_SYSCLK2:
case ADAV80X_CLK_SYSCLK3:
break;
default:
return -EINVAL;
}
clk_id -= ADAV80X_CLK_SYSCLK1;
mask = ADAV80X_PLL_OUTE_SYSCLKPD(clk_id);
if (freq == 0) {
snd_soc_update_bits(codec, ADAV80X_PLL_OUTE, mask, mask);
adav80x->sysclk_pd[clk_id] = true;
} else {
snd_soc_update_bits(codec, ADAV80X_PLL_OUTE, mask, 0);
adav80x->sysclk_pd[clk_id] = false;
}
if (adav80x->sysclk_pd[0])
snd_soc_dapm_disable_pin(&codec->dapm, "PLL1");
else
snd_soc_dapm_force_enable_pin(&codec->dapm, "PLL1");
if (adav80x->sysclk_pd[1] || adav80x->sysclk_pd[2])
snd_soc_dapm_disable_pin(&codec->dapm, "PLL2");
else
snd_soc_dapm_force_enable_pin(&codec->dapm, "PLL2");
snd_soc_dapm_sync(&codec->dapm);
}
return 0;
}
static int adav80x_set_pll(struct snd_soc_codec *codec, int pll_id,
int source, unsigned int freq_in, unsigned int freq_out)
{
struct adav80x *adav80x = snd_soc_codec_get_drvdata(codec);
unsigned int pll_ctrl1 = 0;
unsigned int pll_ctrl2 = 0;
unsigned int pll_src;
switch (source) {
case ADAV80X_PLL_SRC_XTAL:
case ADAV80X_PLL_SRC_XIN:
case ADAV80X_PLL_SRC_MCLKI:
break;
default:
return -EINVAL;
}
if (!freq_out)
return 0;
switch (freq_in) {
case 27000000:
break;
case 54000000:
if (source == ADAV80X_PLL_SRC_XIN) {
pll_ctrl1 |= ADAV80X_PLL_CTRL1_PLLDIV;
break;
}
default:
return -EINVAL;
}
if (freq_out > 12288000) {
pll_ctrl2 |= ADAV80X_PLL_CTRL2_DOUB(pll_id);
freq_out /= 2;
}
/* freq_out = sample_rate * 256 */
switch (freq_out) {
case 8192000:
pll_ctrl2 |= ADAV80X_PLL_CTRL2_FS_32(pll_id);
break;
case 11289600:
pll_ctrl2 |= ADAV80X_PLL_CTRL2_FS_44(pll_id);
break;
case 12288000:
pll_ctrl2 |= ADAV80X_PLL_CTRL2_FS_48(pll_id);
break;
default:
return -EINVAL;
}
snd_soc_update_bits(codec, ADAV80X_PLL_CTRL1, ADAV80X_PLL_CTRL1_PLLDIV,
pll_ctrl1);
snd_soc_update_bits(codec, ADAV80X_PLL_CTRL2,
ADAV80X_PLL_CTRL2_PLL_MASK(pll_id), pll_ctrl2);
if (source != adav80x->pll_src) {
if (source == ADAV80X_PLL_SRC_MCLKI)
pll_src = ADAV80X_PLL_CLK_SRC_PLL_MCLKI(pll_id);
else
pll_src = ADAV80X_PLL_CLK_SRC_PLL_XIN(pll_id);
snd_soc_update_bits(codec, ADAV80X_PLL_CLK_SRC,
ADAV80X_PLL_CLK_SRC_PLL_MASK(pll_id), pll_src);
adav80x->pll_src = source;
snd_soc_dapm_sync(&codec->dapm);
}
return 0;
}
static int adav80x_set_bias_level(struct snd_soc_codec *codec,
enum snd_soc_bias_level level)
{
unsigned int mask = ADAV80X_DAC_CTRL1_PD;
switch (level) {
case SND_SOC_BIAS_ON:
break;
case SND_SOC_BIAS_PREPARE:
break;
case SND_SOC_BIAS_STANDBY:
snd_soc_update_bits(codec, ADAV80X_DAC_CTRL1, mask, 0x00);
break;
case SND_SOC_BIAS_OFF:
snd_soc_update_bits(codec, ADAV80X_DAC_CTRL1, mask, mask);
break;
}
codec->dapm.bias_level = level;
return 0;
}
/* Enforce the same sample rate on all audio interfaces */
static int adav80x_dai_startup(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct snd_soc_codec *codec = dai->codec;
struct adav80x *adav80x = snd_soc_codec_get_drvdata(codec);
if (!codec->active || !adav80x->rate)
return 0;
return snd_pcm_hw_constraint_minmax(substream->runtime,
SNDRV_PCM_HW_PARAM_RATE, adav80x->rate, adav80x->rate);
}
static void adav80x_dai_shutdown(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct snd_soc_codec *codec = dai->codec;
struct adav80x *adav80x = snd_soc_codec_get_drvdata(codec);
if (!codec->active)
adav80x->rate = 0;
}
static const struct snd_soc_dai_ops adav80x_dai_ops = {
.set_fmt = adav80x_set_dai_fmt,
.hw_params = adav80x_hw_params,
.startup = adav80x_dai_startup,
.shutdown = adav80x_dai_shutdown,
};
#define ADAV80X_PLAYBACK_RATES (SNDRV_PCM_RATE_32000 | SNDRV_PCM_RATE_44100 | \
SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_64000 | SNDRV_PCM_RATE_88200 | \
SNDRV_PCM_RATE_96000)
#define ADAV80X_CAPTURE_RATES (SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_96000)
#define ADAV80X_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S18_3LE | \
SNDRV_PCM_FMTBIT_S20_3LE | SNDRV_PCM_FMTBIT_S24_LE)
static struct snd_soc_dai_driver adav80x_dais[] = {
{
.name = "adav80x-hifi",
.id = 0,
.playback = {
.stream_name = "HiFi Playback",
.channels_min = 2,
.channels_max = 2,
.rates = ADAV80X_PLAYBACK_RATES,
.formats = ADAV80X_FORMATS,
},
.capture = {
.stream_name = "HiFi Capture",
.channels_min = 2,
.channels_max = 2,
.rates = ADAV80X_CAPTURE_RATES,
.formats = ADAV80X_FORMATS,
},
.ops = &adav80x_dai_ops,
},
{
.name = "adav80x-aux",
.id = 1,
.playback = {
.stream_name = "Aux Playback",
.channels_min = 2,
.channels_max = 2,
.rates = ADAV80X_PLAYBACK_RATES,
.formats = ADAV80X_FORMATS,
},
.capture = {
.stream_name = "Aux Capture",
.channels_min = 2,
.channels_max = 2,
.rates = ADAV80X_CAPTURE_RATES,
.formats = ADAV80X_FORMATS,
},
.ops = &adav80x_dai_ops,
},
};
static int adav80x_probe(struct snd_soc_codec *codec)
{
int ret;
struct adav80x *adav80x = snd_soc_codec_get_drvdata(codec);
ret = snd_soc_codec_set_cache_io(codec, 7, 9, adav80x->control_type);
if (ret) {
dev_err(codec->dev, "failed to set cache I/O: %d\n", ret);
return ret;
}
/* Force PLLs on for SYSCLK output */
snd_soc_dapm_force_enable_pin(&codec->dapm, "PLL1");
snd_soc_dapm_force_enable_pin(&codec->dapm, "PLL2");
/* Power down S/PDIF receiver, since it is currently not supported */
snd_soc_write(codec, ADAV80X_PLL_OUTE, 0x20);
/* Disable DAC zero flag */
snd_soc_write(codec, ADAV80X_DAC_CTRL3, 0x6);
return adav80x_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
}
static int adav80x_suspend(struct snd_soc_codec *codec)
{
return adav80x_set_bias_level(codec, SND_SOC_BIAS_OFF);
}
static int adav80x_resume(struct snd_soc_codec *codec)
{
adav80x_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
codec->cache_sync = 1;
snd_soc_cache_sync(codec);
return 0;
}
static int adav80x_remove(struct snd_soc_codec *codec)
{
return adav80x_set_bias_level(codec, SND_SOC_BIAS_OFF);
}
static struct snd_soc_codec_driver adav80x_codec_driver = {
.probe = adav80x_probe,
.remove = adav80x_remove,
.suspend = adav80x_suspend,
.resume = adav80x_resume,
.set_bias_level = adav80x_set_bias_level,
.set_pll = adav80x_set_pll,
.set_sysclk = adav80x_set_sysclk,
.reg_word_size = sizeof(u8),
.reg_cache_size = ARRAY_SIZE(adav80x_default_regs),
.reg_cache_default = adav80x_default_regs,
.controls = adav80x_controls,
.num_controls = ARRAY_SIZE(adav80x_controls),
.dapm_widgets = adav80x_dapm_widgets,
.num_dapm_widgets = ARRAY_SIZE(adav80x_dapm_widgets),
.dapm_routes = adav80x_dapm_routes,
.num_dapm_routes = ARRAY_SIZE(adav80x_dapm_routes),
};
static int adav80x_bus_probe(struct device *dev,
enum snd_soc_control_type control_type)
{
struct adav80x *adav80x;
int ret;
adav80x = kzalloc(sizeof(*adav80x), GFP_KERNEL);
if (!adav80x)
return -ENOMEM;
dev_set_drvdata(dev, adav80x);
adav80x->control_type = control_type;
ret = snd_soc_register_codec(dev, &adav80x_codec_driver,
adav80x_dais, ARRAY_SIZE(adav80x_dais));
if (ret)
kfree(adav80x);
return ret;
}
static int adav80x_bus_remove(struct device *dev)
{
snd_soc_unregister_codec(dev);
kfree(dev_get_drvdata(dev));
return 0;
}
#if defined(CONFIG_SPI_MASTER)
static int adav80x_spi_probe(struct spi_device *spi)
{
return adav80x_bus_probe(&spi->dev, SND_SOC_SPI);
}
static int adav80x_spi_remove(struct spi_device *spi)
{
return adav80x_bus_remove(&spi->dev);
}
static struct spi_driver adav80x_spi_driver = {
.driver = {
.name = "adav801",
.owner = THIS_MODULE,
},
.probe = adav80x_spi_probe,
.remove = adav80x_spi_remove,
};
#endif
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
static const struct i2c_device_id adav80x_id[] = {
{ "adav803", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, adav80x_id);
static int adav80x_i2c_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
return adav80x_bus_probe(&client->dev, SND_SOC_I2C);
}
static int adav80x_i2c_remove(struct i2c_client *client)
{
return adav80x_bus_remove(&client->dev);
}
static struct i2c_driver adav80x_i2c_driver = {
.driver = {
.name = "adav803",
.owner = THIS_MODULE,
},
.probe = adav80x_i2c_probe,
.remove = adav80x_i2c_remove,
.id_table = adav80x_id,
};
#endif
static int __init adav80x_init(void)
{
int ret = 0;
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
ret = i2c_add_driver(&adav80x_i2c_driver);
if (ret)
return ret;
#endif
#if defined(CONFIG_SPI_MASTER)
ret = spi_register_driver(&adav80x_spi_driver);
#endif
return ret;
}
module_init(adav80x_init);
static void __exit adav80x_exit(void)
{
#if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE)
i2c_del_driver(&adav80x_i2c_driver);
#endif
#if defined(CONFIG_SPI_MASTER)
spi_unregister_driver(&adav80x_spi_driver);
#endif
}
module_exit(adav80x_exit);
MODULE_DESCRIPTION("ASoC ADAV80x driver");
MODULE_AUTHOR("Lars-Peter Clausen <lars@metafoo.de>");
MODULE_AUTHOR("Yi Li <yi.li@analog.com>>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
emceethemouth/kernel_ferrari | drivers/ata/sata_sis.c | 2550 | 8198 | /*
* sata_sis.c - Silicon Integrated Systems SATA
*
* Maintained by: Uwe Koziolek
* Please ALWAYS copy linux-ide@vger.kernel.org
* on emails.
*
* Copyright 2004 Uwe Koziolek
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*
* libata documentation is available via 'make {ps|pdf}docs',
* as Documentation/DocBook/libata.*
*
* Hardware documentation available under NDA.
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/device.h>
#include <scsi/scsi_host.h>
#include <linux/libata.h>
#include "sis.h"
#define DRV_NAME "sata_sis"
#define DRV_VERSION "1.0"
enum {
sis_180 = 0,
SIS_SCR_PCI_BAR = 5,
/* PCI configuration registers */
SIS_GENCTL = 0x54, /* IDE General Control register */
SIS_SCR_BASE = 0xc0, /* sata0 phy SCR registers */
SIS180_SATA1_OFS = 0x10, /* offset from sata0->sata1 phy regs */
SIS182_SATA1_OFS = 0x20, /* offset from sata0->sata1 phy regs */
SIS_PMR = 0x90, /* port mapping register */
SIS_PMR_COMBINED = 0x30,
/* random bits */
SIS_FLAG_CFGSCR = (1 << 30), /* host flag: SCRs via PCI cfg */
GENCTL_IOMAPPED_SCR = (1 << 26), /* if set, SCRs are in IO space */
};
static int sis_init_one(struct pci_dev *pdev, const struct pci_device_id *ent);
static int sis_scr_read(struct ata_link *link, unsigned int sc_reg, u32 *val);
static int sis_scr_write(struct ata_link *link, unsigned int sc_reg, u32 val);
static const struct pci_device_id sis_pci_tbl[] = {
{ PCI_VDEVICE(SI, 0x0180), sis_180 }, /* SiS 964/180 */
{ PCI_VDEVICE(SI, 0x0181), sis_180 }, /* SiS 964/180 */
{ PCI_VDEVICE(SI, 0x0182), sis_180 }, /* SiS 965/965L */
{ PCI_VDEVICE(SI, 0x0183), sis_180 }, /* SiS 965/965L */
{ PCI_VDEVICE(SI, 0x1182), sis_180 }, /* SiS 966/680 */
{ PCI_VDEVICE(SI, 0x1183), sis_180 }, /* SiS 966/966L/968/680 */
{ } /* terminate list */
};
static struct pci_driver sis_pci_driver = {
.name = DRV_NAME,
.id_table = sis_pci_tbl,
.probe = sis_init_one,
.remove = ata_pci_remove_one,
};
static struct scsi_host_template sis_sht = {
ATA_BMDMA_SHT(DRV_NAME),
};
static struct ata_port_operations sis_ops = {
.inherits = &ata_bmdma_port_ops,
.scr_read = sis_scr_read,
.scr_write = sis_scr_write,
};
static const struct ata_port_info sis_port_info = {
.flags = ATA_FLAG_SATA,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA6,
.port_ops = &sis_ops,
};
MODULE_AUTHOR("Uwe Koziolek");
MODULE_DESCRIPTION("low-level driver for Silicon Integrated Systems SATA controller");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, sis_pci_tbl);
MODULE_VERSION(DRV_VERSION);
static unsigned int get_scr_cfg_addr(struct ata_link *link, unsigned int sc_reg)
{
struct ata_port *ap = link->ap;
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
unsigned int addr = SIS_SCR_BASE + (4 * sc_reg);
u8 pmr;
if (ap->port_no) {
switch (pdev->device) {
case 0x0180:
case 0x0181:
pci_read_config_byte(pdev, SIS_PMR, &pmr);
if ((pmr & SIS_PMR_COMBINED) == 0)
addr += SIS180_SATA1_OFS;
break;
case 0x0182:
case 0x0183:
case 0x1182:
addr += SIS182_SATA1_OFS;
break;
}
}
if (link->pmp)
addr += 0x10;
return addr;
}
static u32 sis_scr_cfg_read(struct ata_link *link,
unsigned int sc_reg, u32 *val)
{
struct pci_dev *pdev = to_pci_dev(link->ap->host->dev);
unsigned int cfg_addr = get_scr_cfg_addr(link, sc_reg);
if (sc_reg == SCR_ERROR) /* doesn't exist in PCI cfg space */
return -EINVAL;
pci_read_config_dword(pdev, cfg_addr, val);
return 0;
}
static int sis_scr_cfg_write(struct ata_link *link,
unsigned int sc_reg, u32 val)
{
struct pci_dev *pdev = to_pci_dev(link->ap->host->dev);
unsigned int cfg_addr = get_scr_cfg_addr(link, sc_reg);
pci_write_config_dword(pdev, cfg_addr, val);
return 0;
}
static int sis_scr_read(struct ata_link *link, unsigned int sc_reg, u32 *val)
{
struct ata_port *ap = link->ap;
void __iomem *base = ap->ioaddr.scr_addr + link->pmp * 0x10;
if (sc_reg > SCR_CONTROL)
return -EINVAL;
if (ap->flags & SIS_FLAG_CFGSCR)
return sis_scr_cfg_read(link, sc_reg, val);
*val = ioread32(base + sc_reg * 4);
return 0;
}
static int sis_scr_write(struct ata_link *link, unsigned int sc_reg, u32 val)
{
struct ata_port *ap = link->ap;
void __iomem *base = ap->ioaddr.scr_addr + link->pmp * 0x10;
if (sc_reg > SCR_CONTROL)
return -EINVAL;
if (ap->flags & SIS_FLAG_CFGSCR)
return sis_scr_cfg_write(link, sc_reg, val);
iowrite32(val, base + (sc_reg * 4));
return 0;
}
static int sis_init_one(struct pci_dev *pdev, const struct pci_device_id *ent)
{
struct ata_port_info pi = sis_port_info;
const struct ata_port_info *ppi[] = { &pi, &pi };
struct ata_host *host;
u32 genctl, val;
u8 pmr;
u8 port2_start = 0x20;
int i, rc;
ata_print_version_once(&pdev->dev, DRV_VERSION);
rc = pcim_enable_device(pdev);
if (rc)
return rc;
/* check and see if the SCRs are in IO space or PCI cfg space */
pci_read_config_dword(pdev, SIS_GENCTL, &genctl);
if ((genctl & GENCTL_IOMAPPED_SCR) == 0)
pi.flags |= SIS_FLAG_CFGSCR;
/* if hardware thinks SCRs are in IO space, but there are
* no IO resources assigned, change to PCI cfg space.
*/
if ((!(pi.flags & SIS_FLAG_CFGSCR)) &&
((pci_resource_start(pdev, SIS_SCR_PCI_BAR) == 0) ||
(pci_resource_len(pdev, SIS_SCR_PCI_BAR) < 128))) {
genctl &= ~GENCTL_IOMAPPED_SCR;
pci_write_config_dword(pdev, SIS_GENCTL, genctl);
pi.flags |= SIS_FLAG_CFGSCR;
}
pci_read_config_byte(pdev, SIS_PMR, &pmr);
switch (ent->device) {
case 0x0180:
case 0x0181:
/* The PATA-handling is provided by pata_sis */
switch (pmr & 0x30) {
case 0x10:
ppi[1] = &sis_info133_for_sata;
break;
case 0x30:
ppi[0] = &sis_info133_for_sata;
break;
}
if ((pmr & SIS_PMR_COMBINED) == 0) {
dev_info(&pdev->dev,
"Detected SiS 180/181/964 chipset in SATA mode\n");
port2_start = 64;
} else {
dev_info(&pdev->dev,
"Detected SiS 180/181 chipset in combined mode\n");
port2_start = 0;
pi.flags |= ATA_FLAG_SLAVE_POSS;
}
break;
case 0x0182:
case 0x0183:
pci_read_config_dword(pdev, 0x6C, &val);
if (val & (1L << 31)) {
dev_info(&pdev->dev, "Detected SiS 182/965 chipset\n");
pi.flags |= ATA_FLAG_SLAVE_POSS;
} else {
dev_info(&pdev->dev, "Detected SiS 182/965L chipset\n");
}
break;
case 0x1182:
dev_info(&pdev->dev,
"Detected SiS 1182/966/680 SATA controller\n");
pi.flags |= ATA_FLAG_SLAVE_POSS;
break;
case 0x1183:
dev_info(&pdev->dev,
"Detected SiS 1183/966/966L/968/680 controller in PATA mode\n");
ppi[0] = &sis_info133_for_sata;
ppi[1] = &sis_info133_for_sata;
break;
}
rc = ata_pci_bmdma_prepare_host(pdev, ppi, &host);
if (rc)
return rc;
for (i = 0; i < 2; i++) {
struct ata_port *ap = host->ports[i];
if (ap->flags & ATA_FLAG_SATA &&
ap->flags & ATA_FLAG_SLAVE_POSS) {
rc = ata_slave_link_init(ap);
if (rc)
return rc;
}
}
if (!(pi.flags & SIS_FLAG_CFGSCR)) {
void __iomem *mmio;
rc = pcim_iomap_regions(pdev, 1 << SIS_SCR_PCI_BAR, DRV_NAME);
if (rc)
return rc;
mmio = host->iomap[SIS_SCR_PCI_BAR];
host->ports[0]->ioaddr.scr_addr = mmio;
host->ports[1]->ioaddr.scr_addr = mmio + port2_start;
}
pci_set_master(pdev);
pci_intx(pdev, 1);
return ata_host_activate(host, pdev->irq, ata_bmdma_interrupt,
IRQF_SHARED, &sis_sht);
}
module_pci_driver(sis_pci_driver);
| gpl-2.0 |
erasmux/pyramid_htc_kernel | sound/isa/sb/emu8000_synth.c | 4854 | 3362 | /*
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
* and (c) 1999 Steve Ratcliffe <steve@parabola.demon.co.uk>
* Copyright (C) 1999-2000 Takashi Iwai <tiwai@suse.de>
*
* Emu8000 synth plug-in routine
*
* 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 "emu8000_local.h"
#include <linux/init.h>
#include <sound/initval.h>
MODULE_AUTHOR("Takashi Iwai, Steve Ratcliffe");
MODULE_DESCRIPTION("Emu8000 synth plug-in routine");
MODULE_LICENSE("GPL");
/*----------------------------------------------------------------*/
/*
* create a new hardware dependent device for Emu8000
*/
static int snd_emu8000_new_device(struct snd_seq_device *dev)
{
struct snd_emu8000 *hw;
struct snd_emux *emu;
hw = *(struct snd_emu8000**)SNDRV_SEQ_DEVICE_ARGPTR(dev);
if (hw == NULL)
return -EINVAL;
if (hw->emu)
return -EBUSY; /* already exists..? */
if (snd_emux_new(&emu) < 0)
return -ENOMEM;
hw->emu = emu;
snd_emu8000_ops_setup(hw);
emu->hw = hw;
emu->max_voices = EMU8000_DRAM_VOICES;
emu->num_ports = hw->seq_ports;
if (hw->memhdr) {
snd_printk(KERN_ERR "memhdr is already initialized!?\n");
snd_util_memhdr_free(hw->memhdr);
}
hw->memhdr = snd_util_memhdr_new(hw->mem_size);
if (hw->memhdr == NULL) {
snd_emux_free(emu);
hw->emu = NULL;
return -ENOMEM;
}
emu->memhdr = hw->memhdr;
emu->midi_ports = hw->seq_ports < 2 ? hw->seq_ports : 2; /* number of virmidi ports */
emu->midi_devidx = 1;
emu->linear_panning = 1;
emu->hwdep_idx = 2; /* FIXED */
if (snd_emux_register(emu, dev->card, hw->index, "Emu8000") < 0) {
snd_emux_free(emu);
snd_util_memhdr_free(hw->memhdr);
hw->emu = NULL;
hw->memhdr = NULL;
return -ENOMEM;
}
if (hw->mem_size > 0)
snd_emu8000_pcm_new(dev->card, hw, 1);
dev->driver_data = hw;
return 0;
}
/*
* free all resources
*/
static int snd_emu8000_delete_device(struct snd_seq_device *dev)
{
struct snd_emu8000 *hw;
if (dev->driver_data == NULL)
return 0; /* no synth was allocated actually */
hw = dev->driver_data;
if (hw->pcm)
snd_device_free(dev->card, hw->pcm);
if (hw->emu)
snd_emux_free(hw->emu);
if (hw->memhdr)
snd_util_memhdr_free(hw->memhdr);
hw->emu = NULL;
hw->memhdr = NULL;
return 0;
}
/*
* INIT part
*/
static int __init alsa_emu8000_init(void)
{
static struct snd_seq_dev_ops ops = {
snd_emu8000_new_device,
snd_emu8000_delete_device,
};
return snd_seq_device_register_driver(SNDRV_SEQ_DEV_ID_EMU8000, &ops,
sizeof(struct snd_emu8000*));
}
static void __exit alsa_emu8000_exit(void)
{
snd_seq_device_unregister_driver(SNDRV_SEQ_DEV_ID_EMU8000);
}
module_init(alsa_emu8000_init)
module_exit(alsa_emu8000_exit)
| gpl-2.0 |
lawnn/Dorimanx-LG-G2-D802-Kernel | drivers/watchdog/coh901327_wdt.c | 4854 | 13040 | /*
* coh901327_wdt.c
*
* Copyright (C) 2008-2009 ST-Ericsson AB
* License terms: GNU General Public License (GPL) version 2
* Watchdog driver for the ST-Ericsson AB COH 901 327 IP core
* Author: Linus Walleij <linus.walleij@stericsson.com>
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/watchdog.h>
#include <linux/interrupt.h>
#include <linux/pm.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/bitops.h>
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/err.h>
#define DRV_NAME "WDOG COH 901 327"
/*
* COH 901 327 register definitions
*/
/* WDOG_FEED Register 32bit (-/W) */
#define U300_WDOG_FR 0x00
#define U300_WDOG_FR_FEED_RESTART_TIMER 0xFEEDU
/* WDOG_TIMEOUT Register 32bit (R/W) */
#define U300_WDOG_TR 0x04
#define U300_WDOG_TR_TIMEOUT_MASK 0x7FFFU
/* WDOG_DISABLE1 Register 32bit (-/W) */
#define U300_WDOG_D1R 0x08
#define U300_WDOG_D1R_DISABLE1_DISABLE_TIMER 0x2BADU
/* WDOG_DISABLE2 Register 32bit (R/W) */
#define U300_WDOG_D2R 0x0C
#define U300_WDOG_D2R_DISABLE2_DISABLE_TIMER 0xCAFEU
#define U300_WDOG_D2R_DISABLE_STATUS_DISABLED 0xDABEU
#define U300_WDOG_D2R_DISABLE_STATUS_ENABLED 0x0000U
/* WDOG_STATUS Register 32bit (R/W) */
#define U300_WDOG_SR 0x10
#define U300_WDOG_SR_STATUS_TIMED_OUT 0xCFE8U
#define U300_WDOG_SR_STATUS_NORMAL 0x0000U
#define U300_WDOG_SR_RESET_STATUS_RESET 0xE8B4U
/* WDOG_COUNT Register 32bit (R/-) */
#define U300_WDOG_CR 0x14
#define U300_WDOG_CR_VALID_IND 0x8000U
#define U300_WDOG_CR_VALID_STABLE 0x0000U
#define U300_WDOG_CR_COUNT_VALUE_MASK 0x7FFFU
/* WDOG_JTAGOVR Register 32bit (R/W) */
#define U300_WDOG_JOR 0x18
#define U300_WDOG_JOR_JTAG_MODE_IND 0x0002U
#define U300_WDOG_JOR_JTAG_WATCHDOG_ENABLE 0x0001U
/* WDOG_RESTART Register 32bit (-/W) */
#define U300_WDOG_RR 0x1C
#define U300_WDOG_RR_RESTART_VALUE_RESUME 0xACEDU
/* WDOG_IRQ_EVENT Register 32bit (R/W) */
#define U300_WDOG_IER 0x20
#define U300_WDOG_IER_WILL_BARK_IRQ_EVENT_IND 0x0001U
#define U300_WDOG_IER_WILL_BARK_IRQ_ACK_ENABLE 0x0001U
/* WDOG_IRQ_MASK Register 32bit (R/W) */
#define U300_WDOG_IMR 0x24
#define U300_WDOG_IMR_WILL_BARK_IRQ_ENABLE 0x0001U
/* WDOG_IRQ_FORCE Register 32bit (R/W) */
#define U300_WDOG_IFR 0x28
#define U300_WDOG_IFR_WILL_BARK_IRQ_FORCE_ENABLE 0x0001U
/* Default timeout in seconds = 1 minute */
static unsigned int margin = 60;
static resource_size_t phybase;
static resource_size_t physize;
static int irq;
static void __iomem *virtbase;
static struct device *parent;
/*
* The watchdog block is of course always clocked, the
* clk_enable()/clk_disable() calls are mainly for performing reference
* counting higher up in the clock hierarchy.
*/
static struct clk *clk;
/*
* Enabling and disabling functions.
*/
static void coh901327_enable(u16 timeout)
{
u16 val;
unsigned long freq;
unsigned long delay_ns;
clk_enable(clk);
/* Restart timer if it is disabled */
val = readw(virtbase + U300_WDOG_D2R);
if (val == U300_WDOG_D2R_DISABLE_STATUS_DISABLED)
writew(U300_WDOG_RR_RESTART_VALUE_RESUME,
virtbase + U300_WDOG_RR);
/* Acknowledge any pending interrupt so it doesn't just fire off */
writew(U300_WDOG_IER_WILL_BARK_IRQ_ACK_ENABLE,
virtbase + U300_WDOG_IER);
/*
* The interrupt is cleared in the 32 kHz clock domain.
* Wait 3 32 kHz cycles for it to take effect
*/
freq = clk_get_rate(clk);
delay_ns = DIV_ROUND_UP(1000000000, freq); /* Freq to ns and round up */
delay_ns = 3 * delay_ns; /* Wait 3 cycles */
ndelay(delay_ns);
/* Enable the watchdog interrupt */
writew(U300_WDOG_IMR_WILL_BARK_IRQ_ENABLE, virtbase + U300_WDOG_IMR);
/* Activate the watchdog timer */
writew(timeout, virtbase + U300_WDOG_TR);
/* Start the watchdog timer */
writew(U300_WDOG_FR_FEED_RESTART_TIMER, virtbase + U300_WDOG_FR);
/*
* Extra read so that this change propagate in the watchdog.
*/
(void) readw(virtbase + U300_WDOG_CR);
val = readw(virtbase + U300_WDOG_D2R);
clk_disable(clk);
if (val != U300_WDOG_D2R_DISABLE_STATUS_ENABLED)
dev_err(parent,
"%s(): watchdog not enabled! D2R value %04x\n",
__func__, val);
}
static void coh901327_disable(void)
{
u16 val;
clk_enable(clk);
/* Disable the watchdog interrupt if it is active */
writew(0x0000U, virtbase + U300_WDOG_IMR);
/* If the watchdog is currently enabled, attempt to disable it */
val = readw(virtbase + U300_WDOG_D2R);
if (val != U300_WDOG_D2R_DISABLE_STATUS_DISABLED) {
writew(U300_WDOG_D1R_DISABLE1_DISABLE_TIMER,
virtbase + U300_WDOG_D1R);
writew(U300_WDOG_D2R_DISABLE2_DISABLE_TIMER,
virtbase + U300_WDOG_D2R);
/* Write this twice (else problems occur) */
writew(U300_WDOG_D2R_DISABLE2_DISABLE_TIMER,
virtbase + U300_WDOG_D2R);
}
val = readw(virtbase + U300_WDOG_D2R);
clk_disable(clk);
if (val != U300_WDOG_D2R_DISABLE_STATUS_DISABLED)
dev_err(parent,
"%s(): watchdog not disabled! D2R value %04x\n",
__func__, val);
}
static int coh901327_start(struct watchdog_device *wdt_dev)
{
coh901327_enable(wdt_dev->timeout * 100);
return 0;
}
static int coh901327_stop(struct watchdog_device *wdt_dev)
{
coh901327_disable();
return 0;
}
static int coh901327_ping(struct watchdog_device *wdd)
{
clk_enable(clk);
/* Feed the watchdog */
writew(U300_WDOG_FR_FEED_RESTART_TIMER,
virtbase + U300_WDOG_FR);
clk_disable(clk);
return 0;
}
static int coh901327_settimeout(struct watchdog_device *wdt_dev,
unsigned int time)
{
wdt_dev->timeout = time;
clk_enable(clk);
/* Set new timeout value */
writew(time * 100, virtbase + U300_WDOG_TR);
/* Feed the dog */
writew(U300_WDOG_FR_FEED_RESTART_TIMER,
virtbase + U300_WDOG_FR);
clk_disable(clk);
return 0;
}
static unsigned int coh901327_gettimeleft(struct watchdog_device *wdt_dev)
{
u16 val;
clk_enable(clk);
/* Read repeatedly until the value is stable! */
val = readw(virtbase + U300_WDOG_CR);
while (val & U300_WDOG_CR_VALID_IND)
val = readw(virtbase + U300_WDOG_CR);
val &= U300_WDOG_CR_COUNT_VALUE_MASK;
clk_disable(clk);
if (val != 0)
val /= 100;
return val;
}
/*
* This interrupt occurs 10 ms before the watchdog WILL bark.
*/
static irqreturn_t coh901327_interrupt(int irq, void *data)
{
u16 val;
/*
* Ack IRQ? If this occurs we're FUBAR anyway, so
* just acknowledge, disable the interrupt and await the imminent end.
* If you at some point need a host of callbacks to be called
* when the system is about to watchdog-reset, add them here!
*
* NOTE: on future versions of this IP-block, it will be possible
* to prevent a watchdog reset by feeding the watchdog at this
* point.
*/
clk_enable(clk);
val = readw(virtbase + U300_WDOG_IER);
if (val == U300_WDOG_IER_WILL_BARK_IRQ_EVENT_IND)
writew(U300_WDOG_IER_WILL_BARK_IRQ_ACK_ENABLE,
virtbase + U300_WDOG_IER);
writew(0x0000U, virtbase + U300_WDOG_IMR);
clk_disable(clk);
dev_crit(parent, "watchdog is barking!\n");
return IRQ_HANDLED;
}
static const struct watchdog_info coh901327_ident = {
.options = WDIOF_CARDRESET | WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING,
.identity = DRV_NAME,
};
static struct watchdog_ops coh901327_ops = {
.owner = THIS_MODULE,
.start = coh901327_start,
.stop = coh901327_stop,
.ping = coh901327_ping,
.set_timeout = coh901327_settimeout,
.get_timeleft = coh901327_gettimeleft,
};
static struct watchdog_device coh901327_wdt = {
.info = &coh901327_ident,
.ops = &coh901327_ops,
/*
* Max timeout is 327 since the 10ms
* timeout register is max
* 0x7FFF = 327670ms ~= 327s.
*/
.min_timeout = 0,
.max_timeout = 327,
};
static int __exit coh901327_remove(struct platform_device *pdev)
{
watchdog_unregister_device(&coh901327_wdt);
coh901327_disable();
free_irq(irq, pdev);
clk_put(clk);
iounmap(virtbase);
release_mem_region(phybase, physize);
return 0;
}
static int __init coh901327_probe(struct platform_device *pdev)
{
int ret;
u16 val;
struct resource *res;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res)
return -ENOENT;
parent = &pdev->dev;
physize = resource_size(res);
phybase = res->start;
if (request_mem_region(phybase, physize, DRV_NAME) == NULL) {
ret = -EBUSY;
goto out;
}
virtbase = ioremap(phybase, physize);
if (!virtbase) {
ret = -ENOMEM;
goto out_no_remap;
}
clk = clk_get(&pdev->dev, NULL);
if (IS_ERR(clk)) {
ret = PTR_ERR(clk);
dev_err(&pdev->dev, "could not get clock\n");
goto out_no_clk;
}
ret = clk_enable(clk);
if (ret) {
dev_err(&pdev->dev, "could not enable clock\n");
goto out_no_clk_enable;
}
val = readw(virtbase + U300_WDOG_SR);
switch (val) {
case U300_WDOG_SR_STATUS_TIMED_OUT:
dev_info(&pdev->dev,
"watchdog timed out since last chip reset!\n");
coh901327_wdt.bootstatus |= WDIOF_CARDRESET;
/* Status will be cleared below */
break;
case U300_WDOG_SR_STATUS_NORMAL:
dev_info(&pdev->dev,
"in normal status, no timeouts have occurred.\n");
break;
default:
dev_info(&pdev->dev,
"contains an illegal status code (%08x)\n", val);
break;
}
val = readw(virtbase + U300_WDOG_D2R);
switch (val) {
case U300_WDOG_D2R_DISABLE_STATUS_DISABLED:
dev_info(&pdev->dev, "currently disabled.\n");
break;
case U300_WDOG_D2R_DISABLE_STATUS_ENABLED:
dev_info(&pdev->dev,
"currently enabled! (disabling it now)\n");
coh901327_disable();
break;
default:
dev_err(&pdev->dev,
"contains an illegal enable/disable code (%08x)\n",
val);
break;
}
/* Reset the watchdog */
writew(U300_WDOG_SR_RESET_STATUS_RESET, virtbase + U300_WDOG_SR);
irq = platform_get_irq(pdev, 0);
if (request_irq(irq, coh901327_interrupt, 0,
DRV_NAME " Bark", pdev)) {
ret = -EIO;
goto out_no_irq;
}
clk_disable(clk);
if (margin < 1 || margin > 327)
margin = 60;
coh901327_wdt.timeout = margin;
ret = watchdog_register_device(&coh901327_wdt);
if (ret == 0)
dev_info(&pdev->dev,
"initialized. timer margin=%d sec\n", margin);
else
goto out_no_wdog;
return 0;
out_no_wdog:
free_irq(irq, pdev);
out_no_irq:
clk_disable(clk);
out_no_clk_enable:
clk_put(clk);
out_no_clk:
iounmap(virtbase);
out_no_remap:
release_mem_region(phybase, SZ_4K);
out:
return ret;
}
#ifdef CONFIG_PM
static u16 wdogenablestore;
static u16 irqmaskstore;
static int coh901327_suspend(struct platform_device *pdev, pm_message_t state)
{
irqmaskstore = readw(virtbase + U300_WDOG_IMR) & 0x0001U;
wdogenablestore = readw(virtbase + U300_WDOG_D2R);
/* If watchdog is on, disable it here and now */
if (wdogenablestore == U300_WDOG_D2R_DISABLE_STATUS_ENABLED)
coh901327_disable();
return 0;
}
static int coh901327_resume(struct platform_device *pdev)
{
/* Restore the watchdog interrupt */
writew(irqmaskstore, virtbase + U300_WDOG_IMR);
if (wdogenablestore == U300_WDOG_D2R_DISABLE_STATUS_ENABLED) {
/* Restart the watchdog timer */
writew(U300_WDOG_RR_RESTART_VALUE_RESUME,
virtbase + U300_WDOG_RR);
writew(U300_WDOG_FR_FEED_RESTART_TIMER,
virtbase + U300_WDOG_FR);
}
return 0;
}
#else
#define coh901327_suspend NULL
#define coh901327_resume NULL
#endif
/*
* Mistreating the watchdog is the only way to perform a software reset of the
* system on EMP platforms. So we implement this and export a symbol for it.
*/
void coh901327_watchdog_reset(void)
{
/* Enable even if on JTAG too */
writew(U300_WDOG_JOR_JTAG_WATCHDOG_ENABLE,
virtbase + U300_WDOG_JOR);
/*
* Timeout = 5s, we have to wait for the watchdog reset to
* actually take place: the watchdog will be reloaded with the
* default value immediately, so we HAVE to reboot and get back
* into the kernel in 30s, or the device will reboot again!
* The boot loader will typically deactivate the watchdog, so we
* need time enough for the boot loader to get to the point of
* deactivating the watchdog before it is shut down by it.
*
* NOTE: on future versions of the watchdog, this restriction is
* gone: the watchdog will be reloaded with a default value (1 min)
* instead of last value, and you can conveniently set the watchdog
* timeout to 10ms (value = 1) without any problems.
*/
coh901327_enable(500);
/* Return and await doom */
}
static struct platform_driver coh901327_driver = {
.driver = {
.owner = THIS_MODULE,
.name = "coh901327_wdog",
},
.remove = __exit_p(coh901327_remove),
.suspend = coh901327_suspend,
.resume = coh901327_resume,
};
static int __init coh901327_init(void)
{
return platform_driver_probe(&coh901327_driver, coh901327_probe);
}
module_init(coh901327_init);
static void __exit coh901327_exit(void)
{
platform_driver_unregister(&coh901327_driver);
}
module_exit(coh901327_exit);
MODULE_AUTHOR("Linus Walleij <linus.walleij@stericsson.com>");
MODULE_DESCRIPTION("COH 901 327 Watchdog");
module_param(margin, uint, 0);
MODULE_PARM_DESC(margin, "Watchdog margin in seconds (default 60s)");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:coh901327-watchdog");
| gpl-2.0 |
aopp/android_kernel_lge_hammerhead | drivers/char/ipmi/ipmi_watchdog.c | 4854 | 35627 | /*
* ipmi_watchdog.c
*
* A watchdog timer based upon the 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/moduleparam.h>
#include <linux/ipmi.h>
#include <linux/ipmi_smi.h>
#include <linux/mutex.h>
#include <linux/watchdog.h>
#include <linux/miscdevice.h>
#include <linux/init.h>
#include <linux/completion.h>
#include <linux/kdebug.h>
#include <linux/rwsem.h>
#include <linux/errno.h>
#include <asm/uaccess.h>
#include <linux/notifier.h>
#include <linux/nmi.h>
#include <linux/reboot.h>
#include <linux/wait.h>
#include <linux/poll.h>
#include <linux/string.h>
#include <linux/ctype.h>
#include <linux/delay.h>
#include <linux/atomic.h>
#ifdef CONFIG_X86
/*
* This is ugly, but I've determined that x86 is the only architecture
* that can reasonably support the IPMI NMI watchdog timeout at this
* time. If another architecture adds this capability somehow, it
* will have to be a somewhat different mechanism and I have no idea
* how it will work. So in the unlikely event that another
* architecture supports this, we can figure out a good generic
* mechanism for it at that time.
*/
#include <asm/kdebug.h>
#include <asm/nmi.h>
#define HAVE_DIE_NMI
#endif
#define PFX "IPMI Watchdog: "
/*
* The IPMI command/response information for the watchdog timer.
*/
/* values for byte 1 of the set command, byte 2 of the get response. */
#define WDOG_DONT_LOG (1 << 7)
#define WDOG_DONT_STOP_ON_SET (1 << 6)
#define WDOG_SET_TIMER_USE(byte, use) \
byte = ((byte) & 0xf8) | ((use) & 0x7)
#define WDOG_GET_TIMER_USE(byte) ((byte) & 0x7)
#define WDOG_TIMER_USE_BIOS_FRB2 1
#define WDOG_TIMER_USE_BIOS_POST 2
#define WDOG_TIMER_USE_OS_LOAD 3
#define WDOG_TIMER_USE_SMS_OS 4
#define WDOG_TIMER_USE_OEM 5
/* values for byte 2 of the set command, byte 3 of the get response. */
#define WDOG_SET_PRETIMEOUT_ACT(byte, use) \
byte = ((byte) & 0x8f) | (((use) & 0x7) << 4)
#define WDOG_GET_PRETIMEOUT_ACT(byte) (((byte) >> 4) & 0x7)
#define WDOG_PRETIMEOUT_NONE 0
#define WDOG_PRETIMEOUT_SMI 1
#define WDOG_PRETIMEOUT_NMI 2
#define WDOG_PRETIMEOUT_MSG_INT 3
/* Operations that can be performed on a pretimout. */
#define WDOG_PREOP_NONE 0
#define WDOG_PREOP_PANIC 1
/* Cause data to be available to read. Doesn't work in NMI mode. */
#define WDOG_PREOP_GIVE_DATA 2
/* Actions to perform on a full timeout. */
#define WDOG_SET_TIMEOUT_ACT(byte, use) \
byte = ((byte) & 0xf8) | ((use) & 0x7)
#define WDOG_GET_TIMEOUT_ACT(byte) ((byte) & 0x7)
#define WDOG_TIMEOUT_NONE 0
#define WDOG_TIMEOUT_RESET 1
#define WDOG_TIMEOUT_POWER_DOWN 2
#define WDOG_TIMEOUT_POWER_CYCLE 3
/*
* Byte 3 of the get command, byte 4 of the get response is the
* pre-timeout in seconds.
*/
/* Bits for setting byte 4 of the set command, byte 5 of the get response. */
#define WDOG_EXPIRE_CLEAR_BIOS_FRB2 (1 << 1)
#define WDOG_EXPIRE_CLEAR_BIOS_POST (1 << 2)
#define WDOG_EXPIRE_CLEAR_OS_LOAD (1 << 3)
#define WDOG_EXPIRE_CLEAR_SMS_OS (1 << 4)
#define WDOG_EXPIRE_CLEAR_OEM (1 << 5)
/*
* Setting/getting the watchdog timer value. This is for bytes 5 and
* 6 (the timeout time) of the set command, and bytes 6 and 7 (the
* timeout time) and 8 and 9 (the current countdown value) of the
* response. The timeout value is given in seconds (in the command it
* is 100ms intervals).
*/
#define WDOG_SET_TIMEOUT(byte1, byte2, val) \
(byte1) = (((val) * 10) & 0xff), (byte2) = (((val) * 10) >> 8)
#define WDOG_GET_TIMEOUT(byte1, byte2) \
(((byte1) | ((byte2) << 8)) / 10)
#define IPMI_WDOG_RESET_TIMER 0x22
#define IPMI_WDOG_SET_TIMER 0x24
#define IPMI_WDOG_GET_TIMER 0x25
#define IPMI_WDOG_TIMER_NOT_INIT_RESP 0x80
/* These are here until the real ones get into the watchdog.h interface. */
#ifndef WDIOC_GETTIMEOUT
#define WDIOC_GETTIMEOUT _IOW(WATCHDOG_IOCTL_BASE, 20, int)
#endif
#ifndef WDIOC_SET_PRETIMEOUT
#define WDIOC_SET_PRETIMEOUT _IOW(WATCHDOG_IOCTL_BASE, 21, int)
#endif
#ifndef WDIOC_GET_PRETIMEOUT
#define WDIOC_GET_PRETIMEOUT _IOW(WATCHDOG_IOCTL_BASE, 22, int)
#endif
static DEFINE_MUTEX(ipmi_watchdog_mutex);
static bool nowayout = WATCHDOG_NOWAYOUT;
static ipmi_user_t watchdog_user;
static int watchdog_ifnum;
/* Default the timeout to 10 seconds. */
static int timeout = 10;
/* The pre-timeout is disabled by default. */
static int pretimeout;
/* Default action is to reset the board on a timeout. */
static unsigned char action_val = WDOG_TIMEOUT_RESET;
static char action[16] = "reset";
static unsigned char preaction_val = WDOG_PRETIMEOUT_NONE;
static char preaction[16] = "pre_none";
static unsigned char preop_val = WDOG_PREOP_NONE;
static char preop[16] = "preop_none";
static DEFINE_SPINLOCK(ipmi_read_lock);
static char data_to_read;
static DECLARE_WAIT_QUEUE_HEAD(read_q);
static struct fasync_struct *fasync_q;
static char pretimeout_since_last_heartbeat;
static char expect_close;
static int ifnum_to_use = -1;
/* Parameters to ipmi_set_timeout */
#define IPMI_SET_TIMEOUT_NO_HB 0
#define IPMI_SET_TIMEOUT_HB_IF_NECESSARY 1
#define IPMI_SET_TIMEOUT_FORCE_HB 2
static int ipmi_set_timeout(int do_heartbeat);
static void ipmi_register_watchdog(int ipmi_intf);
static void ipmi_unregister_watchdog(int ipmi_intf);
/*
* If true, the driver will start running as soon as it is configured
* and ready.
*/
static int start_now;
static int set_param_timeout(const char *val, const struct kernel_param *kp)
{
char *endp;
int l;
int rv = 0;
if (!val)
return -EINVAL;
l = simple_strtoul(val, &endp, 0);
if (endp == val)
return -EINVAL;
*((int *)kp->arg) = l;
if (watchdog_user)
rv = ipmi_set_timeout(IPMI_SET_TIMEOUT_HB_IF_NECESSARY);
return rv;
}
static struct kernel_param_ops param_ops_timeout = {
.set = set_param_timeout,
.get = param_get_int,
};
#define param_check_timeout param_check_int
typedef int (*action_fn)(const char *intval, char *outval);
static int action_op(const char *inval, char *outval);
static int preaction_op(const char *inval, char *outval);
static int preop_op(const char *inval, char *outval);
static void check_parms(void);
static int set_param_str(const char *val, const struct kernel_param *kp)
{
action_fn fn = (action_fn) kp->arg;
int rv = 0;
char valcp[16];
char *s;
strncpy(valcp, val, 16);
valcp[15] = '\0';
s = strstrip(valcp);
rv = fn(s, NULL);
if (rv)
goto out;
check_parms();
if (watchdog_user)
rv = ipmi_set_timeout(IPMI_SET_TIMEOUT_HB_IF_NECESSARY);
out:
return rv;
}
static int get_param_str(char *buffer, const struct kernel_param *kp)
{
action_fn fn = (action_fn) kp->arg;
int rv;
rv = fn(NULL, buffer);
if (rv)
return rv;
return strlen(buffer);
}
static int set_param_wdog_ifnum(const char *val, const struct kernel_param *kp)
{
int rv = param_set_int(val, kp);
if (rv)
return rv;
if ((ifnum_to_use < 0) || (ifnum_to_use == watchdog_ifnum))
return 0;
ipmi_unregister_watchdog(watchdog_ifnum);
ipmi_register_watchdog(ifnum_to_use);
return 0;
}
static struct kernel_param_ops param_ops_wdog_ifnum = {
.set = set_param_wdog_ifnum,
.get = param_get_int,
};
#define param_check_wdog_ifnum param_check_int
static struct kernel_param_ops param_ops_str = {
.set = set_param_str,
.get = get_param_str,
};
module_param(ifnum_to_use, wdog_ifnum, 0644);
MODULE_PARM_DESC(ifnum_to_use, "The interface number to use for the watchdog "
"timer. Setting to -1 defaults to the first registered "
"interface");
module_param(timeout, timeout, 0644);
MODULE_PARM_DESC(timeout, "Timeout value in seconds.");
module_param(pretimeout, timeout, 0644);
MODULE_PARM_DESC(pretimeout, "Pretimeout value in seconds.");
module_param_cb(action, ¶m_ops_str, action_op, 0644);
MODULE_PARM_DESC(action, "Timeout action. One of: "
"reset, none, power_cycle, power_off.");
module_param_cb(preaction, ¶m_ops_str, preaction_op, 0644);
MODULE_PARM_DESC(preaction, "Pretimeout action. One of: "
"pre_none, pre_smi, pre_nmi, pre_int.");
module_param_cb(preop, ¶m_ops_str, preop_op, 0644);
MODULE_PARM_DESC(preop, "Pretimeout driver operation. One of: "
"preop_none, preop_panic, preop_give_data.");
module_param(start_now, int, 0444);
MODULE_PARM_DESC(start_now, "Set to 1 to start the watchdog as"
"soon as the driver is loaded.");
module_param(nowayout, bool, 0644);
MODULE_PARM_DESC(nowayout, "Watchdog cannot be stopped once started "
"(default=CONFIG_WATCHDOG_NOWAYOUT)");
/* Default state of the timer. */
static unsigned char ipmi_watchdog_state = WDOG_TIMEOUT_NONE;
/* If shutting down via IPMI, we ignore the heartbeat. */
static int ipmi_ignore_heartbeat;
/* Is someone using the watchdog? Only one user is allowed. */
static unsigned long ipmi_wdog_open;
/*
* If set to 1, the heartbeat command will set the state to reset and
* start the timer. The timer doesn't normally run when the driver is
* first opened until the heartbeat is set the first time, this
* variable is used to accomplish this.
*/
static int ipmi_start_timer_on_heartbeat;
/* IPMI version of the BMC. */
static unsigned char ipmi_version_major;
static unsigned char ipmi_version_minor;
/* If a pretimeout occurs, this is used to allow only one panic to happen. */
static atomic_t preop_panic_excl = ATOMIC_INIT(-1);
#ifdef HAVE_DIE_NMI
static int testing_nmi;
static int nmi_handler_registered;
#endif
static int ipmi_heartbeat(void);
/*
* We use a mutex to make sure that only one thing can send a set
* timeout at one time, because we only have one copy of the data.
* The mutex is claimed when the set_timeout is sent and freed
* when both messages are free.
*/
static atomic_t set_timeout_tofree = ATOMIC_INIT(0);
static DEFINE_MUTEX(set_timeout_lock);
static DECLARE_COMPLETION(set_timeout_wait);
static void set_timeout_free_smi(struct ipmi_smi_msg *msg)
{
if (atomic_dec_and_test(&set_timeout_tofree))
complete(&set_timeout_wait);
}
static void set_timeout_free_recv(struct ipmi_recv_msg *msg)
{
if (atomic_dec_and_test(&set_timeout_tofree))
complete(&set_timeout_wait);
}
static struct ipmi_smi_msg set_timeout_smi_msg = {
.done = set_timeout_free_smi
};
static struct ipmi_recv_msg set_timeout_recv_msg = {
.done = set_timeout_free_recv
};
static int i_ipmi_set_timeout(struct ipmi_smi_msg *smi_msg,
struct ipmi_recv_msg *recv_msg,
int *send_heartbeat_now)
{
struct kernel_ipmi_msg msg;
unsigned char data[6];
int rv;
struct ipmi_system_interface_addr addr;
int hbnow = 0;
/* These can be cleared as we are setting the timeout. */
pretimeout_since_last_heartbeat = 0;
data[0] = 0;
WDOG_SET_TIMER_USE(data[0], WDOG_TIMER_USE_SMS_OS);
if ((ipmi_version_major > 1)
|| ((ipmi_version_major == 1) && (ipmi_version_minor >= 5))) {
/* This is an IPMI 1.5-only feature. */
data[0] |= WDOG_DONT_STOP_ON_SET;
} else if (ipmi_watchdog_state != WDOG_TIMEOUT_NONE) {
/*
* In ipmi 1.0, setting the timer stops the watchdog, we
* need to start it back up again.
*/
hbnow = 1;
}
data[1] = 0;
WDOG_SET_TIMEOUT_ACT(data[1], ipmi_watchdog_state);
if ((pretimeout > 0) && (ipmi_watchdog_state != WDOG_TIMEOUT_NONE)) {
WDOG_SET_PRETIMEOUT_ACT(data[1], preaction_val);
data[2] = pretimeout;
} else {
WDOG_SET_PRETIMEOUT_ACT(data[1], WDOG_PRETIMEOUT_NONE);
data[2] = 0; /* No pretimeout. */
}
data[3] = 0;
WDOG_SET_TIMEOUT(data[4], data[5], timeout);
addr.addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
addr.channel = IPMI_BMC_CHANNEL;
addr.lun = 0;
msg.netfn = 0x06;
msg.cmd = IPMI_WDOG_SET_TIMER;
msg.data = data;
msg.data_len = sizeof(data);
rv = ipmi_request_supply_msgs(watchdog_user,
(struct ipmi_addr *) &addr,
0,
&msg,
NULL,
smi_msg,
recv_msg,
1);
if (rv) {
printk(KERN_WARNING PFX "set timeout error: %d\n",
rv);
}
if (send_heartbeat_now)
*send_heartbeat_now = hbnow;
return rv;
}
static int ipmi_set_timeout(int do_heartbeat)
{
int send_heartbeat_now;
int rv;
/* We can only send one of these at a time. */
mutex_lock(&set_timeout_lock);
atomic_set(&set_timeout_tofree, 2);
rv = i_ipmi_set_timeout(&set_timeout_smi_msg,
&set_timeout_recv_msg,
&send_heartbeat_now);
if (rv) {
mutex_unlock(&set_timeout_lock);
goto out;
}
wait_for_completion(&set_timeout_wait);
mutex_unlock(&set_timeout_lock);
if ((do_heartbeat == IPMI_SET_TIMEOUT_FORCE_HB)
|| ((send_heartbeat_now)
&& (do_heartbeat == IPMI_SET_TIMEOUT_HB_IF_NECESSARY)))
rv = ipmi_heartbeat();
out:
return rv;
}
static atomic_t panic_done_count = ATOMIC_INIT(0);
static void panic_smi_free(struct ipmi_smi_msg *msg)
{
atomic_dec(&panic_done_count);
}
static void panic_recv_free(struct ipmi_recv_msg *msg)
{
atomic_dec(&panic_done_count);
}
static struct ipmi_smi_msg panic_halt_heartbeat_smi_msg = {
.done = panic_smi_free
};
static struct ipmi_recv_msg panic_halt_heartbeat_recv_msg = {
.done = panic_recv_free
};
static void panic_halt_ipmi_heartbeat(void)
{
struct kernel_ipmi_msg msg;
struct ipmi_system_interface_addr addr;
int rv;
/*
* Don't reset the timer if we have the timer turned off, that
* re-enables the watchdog.
*/
if (ipmi_watchdog_state == WDOG_TIMEOUT_NONE)
return;
addr.addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
addr.channel = IPMI_BMC_CHANNEL;
addr.lun = 0;
msg.netfn = 0x06;
msg.cmd = IPMI_WDOG_RESET_TIMER;
msg.data = NULL;
msg.data_len = 0;
atomic_add(2, &panic_done_count);
rv = ipmi_request_supply_msgs(watchdog_user,
(struct ipmi_addr *) &addr,
0,
&msg,
NULL,
&panic_halt_heartbeat_smi_msg,
&panic_halt_heartbeat_recv_msg,
1);
if (rv)
atomic_sub(2, &panic_done_count);
}
static struct ipmi_smi_msg panic_halt_smi_msg = {
.done = panic_smi_free
};
static struct ipmi_recv_msg panic_halt_recv_msg = {
.done = panic_recv_free
};
/*
* Special call, doesn't claim any locks. This is only to be called
* at panic or halt time, in run-to-completion mode, when the caller
* is the only CPU and the only thing that will be going is these IPMI
* calls.
*/
static void panic_halt_ipmi_set_timeout(void)
{
int send_heartbeat_now;
int rv;
/* Wait for the messages to be free. */
while (atomic_read(&panic_done_count) != 0)
ipmi_poll_interface(watchdog_user);
atomic_add(2, &panic_done_count);
rv = i_ipmi_set_timeout(&panic_halt_smi_msg,
&panic_halt_recv_msg,
&send_heartbeat_now);
if (rv) {
atomic_sub(2, &panic_done_count);
printk(KERN_WARNING PFX
"Unable to extend the watchdog timeout.");
} else {
if (send_heartbeat_now)
panic_halt_ipmi_heartbeat();
}
while (atomic_read(&panic_done_count) != 0)
ipmi_poll_interface(watchdog_user);
}
/*
* We use a mutex to make sure that only one thing can send a
* heartbeat at one time, because we only have one copy of the data.
* The semaphore is claimed when the set_timeout is sent and freed
* when both messages are free.
*/
static atomic_t heartbeat_tofree = ATOMIC_INIT(0);
static DEFINE_MUTEX(heartbeat_lock);
static DECLARE_COMPLETION(heartbeat_wait);
static void heartbeat_free_smi(struct ipmi_smi_msg *msg)
{
if (atomic_dec_and_test(&heartbeat_tofree))
complete(&heartbeat_wait);
}
static void heartbeat_free_recv(struct ipmi_recv_msg *msg)
{
if (atomic_dec_and_test(&heartbeat_tofree))
complete(&heartbeat_wait);
}
static struct ipmi_smi_msg heartbeat_smi_msg = {
.done = heartbeat_free_smi
};
static struct ipmi_recv_msg heartbeat_recv_msg = {
.done = heartbeat_free_recv
};
static int ipmi_heartbeat(void)
{
struct kernel_ipmi_msg msg;
int rv;
struct ipmi_system_interface_addr addr;
int timeout_retries = 0;
if (ipmi_ignore_heartbeat)
return 0;
if (ipmi_start_timer_on_heartbeat) {
ipmi_start_timer_on_heartbeat = 0;
ipmi_watchdog_state = action_val;
return ipmi_set_timeout(IPMI_SET_TIMEOUT_FORCE_HB);
} else if (pretimeout_since_last_heartbeat) {
/*
* A pretimeout occurred, make sure we set the timeout.
* We don't want to set the action, though, we want to
* leave that alone (thus it can't be combined with the
* above operation.
*/
return ipmi_set_timeout(IPMI_SET_TIMEOUT_HB_IF_NECESSARY);
}
mutex_lock(&heartbeat_lock);
restart:
atomic_set(&heartbeat_tofree, 2);
/*
* Don't reset the timer if we have the timer turned off, that
* re-enables the watchdog.
*/
if (ipmi_watchdog_state == WDOG_TIMEOUT_NONE) {
mutex_unlock(&heartbeat_lock);
return 0;
}
addr.addr_type = IPMI_SYSTEM_INTERFACE_ADDR_TYPE;
addr.channel = IPMI_BMC_CHANNEL;
addr.lun = 0;
msg.netfn = 0x06;
msg.cmd = IPMI_WDOG_RESET_TIMER;
msg.data = NULL;
msg.data_len = 0;
rv = ipmi_request_supply_msgs(watchdog_user,
(struct ipmi_addr *) &addr,
0,
&msg,
NULL,
&heartbeat_smi_msg,
&heartbeat_recv_msg,
1);
if (rv) {
mutex_unlock(&heartbeat_lock);
printk(KERN_WARNING PFX "heartbeat failure: %d\n",
rv);
return rv;
}
/* Wait for the heartbeat to be sent. */
wait_for_completion(&heartbeat_wait);
if (heartbeat_recv_msg.msg.data[0] == IPMI_WDOG_TIMER_NOT_INIT_RESP) {
timeout_retries++;
if (timeout_retries > 3) {
printk(KERN_ERR PFX ": Unable to restore the IPMI"
" watchdog's settings, giving up.\n");
rv = -EIO;
goto out_unlock;
}
/*
* The timer was not initialized, that means the BMC was
* probably reset and lost the watchdog information. Attempt
* to restore the timer's info. Note that we still hold
* the heartbeat lock, to keep a heartbeat from happening
* in this process, so must say no heartbeat to avoid a
* deadlock on this mutex.
*/
rv = ipmi_set_timeout(IPMI_SET_TIMEOUT_NO_HB);
if (rv) {
printk(KERN_ERR PFX ": Unable to send the command to"
" set the watchdog's settings, giving up.\n");
goto out_unlock;
}
/* We might need a new heartbeat, so do it now */
goto restart;
} else if (heartbeat_recv_msg.msg.data[0] != 0) {
/*
* Got an error in the heartbeat response. It was already
* reported in ipmi_wdog_msg_handler, but we should return
* an error here.
*/
rv = -EINVAL;
}
out_unlock:
mutex_unlock(&heartbeat_lock);
return rv;
}
static struct watchdog_info ident = {
.options = 0, /* WDIOF_SETTIMEOUT, */
.firmware_version = 1,
.identity = "IPMI"
};
static int ipmi_ioctl(struct file *file,
unsigned int cmd, unsigned long arg)
{
void __user *argp = (void __user *)arg;
int i;
int val;
switch (cmd) {
case WDIOC_GETSUPPORT:
i = copy_to_user(argp, &ident, sizeof(ident));
return i ? -EFAULT : 0;
case WDIOC_SETTIMEOUT:
i = copy_from_user(&val, argp, sizeof(int));
if (i)
return -EFAULT;
timeout = val;
return ipmi_set_timeout(IPMI_SET_TIMEOUT_HB_IF_NECESSARY);
case WDIOC_GETTIMEOUT:
i = copy_to_user(argp, &timeout, sizeof(timeout));
if (i)
return -EFAULT;
return 0;
case WDIOC_SET_PRETIMEOUT:
case WDIOC_SETPRETIMEOUT:
i = copy_from_user(&val, argp, sizeof(int));
if (i)
return -EFAULT;
pretimeout = val;
return ipmi_set_timeout(IPMI_SET_TIMEOUT_HB_IF_NECESSARY);
case WDIOC_GET_PRETIMEOUT:
case WDIOC_GETPRETIMEOUT:
i = copy_to_user(argp, &pretimeout, sizeof(pretimeout));
if (i)
return -EFAULT;
return 0;
case WDIOC_KEEPALIVE:
return ipmi_heartbeat();
case WDIOC_SETOPTIONS:
i = copy_from_user(&val, argp, sizeof(int));
if (i)
return -EFAULT;
if (val & WDIOS_DISABLECARD) {
ipmi_watchdog_state = WDOG_TIMEOUT_NONE;
ipmi_set_timeout(IPMI_SET_TIMEOUT_NO_HB);
ipmi_start_timer_on_heartbeat = 0;
}
if (val & WDIOS_ENABLECARD) {
ipmi_watchdog_state = action_val;
ipmi_set_timeout(IPMI_SET_TIMEOUT_FORCE_HB);
}
return 0;
case WDIOC_GETSTATUS:
val = 0;
i = copy_to_user(argp, &val, sizeof(val));
if (i)
return -EFAULT;
return 0;
default:
return -ENOIOCTLCMD;
}
}
static long ipmi_unlocked_ioctl(struct file *file,
unsigned int cmd,
unsigned long arg)
{
int ret;
mutex_lock(&ipmi_watchdog_mutex);
ret = ipmi_ioctl(file, cmd, arg);
mutex_unlock(&ipmi_watchdog_mutex);
return ret;
}
static ssize_t ipmi_write(struct file *file,
const char __user *buf,
size_t len,
loff_t *ppos)
{
int rv;
if (len) {
if (!nowayout) {
size_t i;
/* In case it was set long ago */
expect_close = 0;
for (i = 0; i != len; i++) {
char c;
if (get_user(c, buf + i))
return -EFAULT;
if (c == 'V')
expect_close = 42;
}
}
rv = ipmi_heartbeat();
if (rv)
return rv;
}
return len;
}
static ssize_t ipmi_read(struct file *file,
char __user *buf,
size_t count,
loff_t *ppos)
{
int rv = 0;
wait_queue_t wait;
if (count <= 0)
return 0;
/*
* Reading returns if the pretimeout has gone off, and it only does
* it once per pretimeout.
*/
spin_lock(&ipmi_read_lock);
if (!data_to_read) {
if (file->f_flags & O_NONBLOCK) {
rv = -EAGAIN;
goto out;
}
init_waitqueue_entry(&wait, current);
add_wait_queue(&read_q, &wait);
while (!data_to_read) {
set_current_state(TASK_INTERRUPTIBLE);
spin_unlock(&ipmi_read_lock);
schedule();
spin_lock(&ipmi_read_lock);
}
remove_wait_queue(&read_q, &wait);
if (signal_pending(current)) {
rv = -ERESTARTSYS;
goto out;
}
}
data_to_read = 0;
out:
spin_unlock(&ipmi_read_lock);
if (rv == 0) {
if (copy_to_user(buf, &data_to_read, 1))
rv = -EFAULT;
else
rv = 1;
}
return rv;
}
static int ipmi_open(struct inode *ino, struct file *filep)
{
switch (iminor(ino)) {
case WATCHDOG_MINOR:
if (test_and_set_bit(0, &ipmi_wdog_open))
return -EBUSY;
/*
* Don't start the timer now, let it start on the
* first heartbeat.
*/
ipmi_start_timer_on_heartbeat = 1;
return nonseekable_open(ino, filep);
default:
return (-ENODEV);
}
}
static unsigned int ipmi_poll(struct file *file, poll_table *wait)
{
unsigned int mask = 0;
poll_wait(file, &read_q, wait);
spin_lock(&ipmi_read_lock);
if (data_to_read)
mask |= (POLLIN | POLLRDNORM);
spin_unlock(&ipmi_read_lock);
return mask;
}
static int ipmi_fasync(int fd, struct file *file, int on)
{
int result;
result = fasync_helper(fd, file, on, &fasync_q);
return (result);
}
static int ipmi_close(struct inode *ino, struct file *filep)
{
if (iminor(ino) == WATCHDOG_MINOR) {
if (expect_close == 42) {
ipmi_watchdog_state = WDOG_TIMEOUT_NONE;
ipmi_set_timeout(IPMI_SET_TIMEOUT_NO_HB);
} else {
printk(KERN_CRIT PFX
"Unexpected close, not stopping watchdog!\n");
ipmi_heartbeat();
}
clear_bit(0, &ipmi_wdog_open);
}
expect_close = 0;
return 0;
}
static const struct file_operations ipmi_wdog_fops = {
.owner = THIS_MODULE,
.read = ipmi_read,
.poll = ipmi_poll,
.write = ipmi_write,
.unlocked_ioctl = ipmi_unlocked_ioctl,
.open = ipmi_open,
.release = ipmi_close,
.fasync = ipmi_fasync,
.llseek = no_llseek,
};
static struct miscdevice ipmi_wdog_miscdev = {
.minor = WATCHDOG_MINOR,
.name = "watchdog",
.fops = &ipmi_wdog_fops
};
static void ipmi_wdog_msg_handler(struct ipmi_recv_msg *msg,
void *handler_data)
{
if (msg->msg.cmd == IPMI_WDOG_RESET_TIMER &&
msg->msg.data[0] == IPMI_WDOG_TIMER_NOT_INIT_RESP)
printk(KERN_INFO PFX "response: The IPMI controller appears"
" to have been reset, will attempt to reinitialize"
" the watchdog timer\n");
else if (msg->msg.data[0] != 0)
printk(KERN_ERR PFX "response: Error %x on cmd %x\n",
msg->msg.data[0],
msg->msg.cmd);
ipmi_free_recv_msg(msg);
}
static void ipmi_wdog_pretimeout_handler(void *handler_data)
{
if (preaction_val != WDOG_PRETIMEOUT_NONE) {
if (preop_val == WDOG_PREOP_PANIC) {
if (atomic_inc_and_test(&preop_panic_excl))
panic("Watchdog pre-timeout");
} else if (preop_val == WDOG_PREOP_GIVE_DATA) {
spin_lock(&ipmi_read_lock);
data_to_read = 1;
wake_up_interruptible(&read_q);
kill_fasync(&fasync_q, SIGIO, POLL_IN);
spin_unlock(&ipmi_read_lock);
}
}
/*
* On some machines, the heartbeat will give an error and not
* work unless we re-enable the timer. So do so.
*/
pretimeout_since_last_heartbeat = 1;
}
static struct ipmi_user_hndl ipmi_hndlrs = {
.ipmi_recv_hndl = ipmi_wdog_msg_handler,
.ipmi_watchdog_pretimeout = ipmi_wdog_pretimeout_handler
};
static void ipmi_register_watchdog(int ipmi_intf)
{
int rv = -EBUSY;
if (watchdog_user)
goto out;
if ((ifnum_to_use >= 0) && (ifnum_to_use != ipmi_intf))
goto out;
watchdog_ifnum = ipmi_intf;
rv = ipmi_create_user(ipmi_intf, &ipmi_hndlrs, NULL, &watchdog_user);
if (rv < 0) {
printk(KERN_CRIT PFX "Unable to register with ipmi\n");
goto out;
}
ipmi_get_version(watchdog_user,
&ipmi_version_major,
&ipmi_version_minor);
rv = misc_register(&ipmi_wdog_miscdev);
if (rv < 0) {
ipmi_destroy_user(watchdog_user);
watchdog_user = NULL;
printk(KERN_CRIT PFX "Unable to register misc device\n");
}
#ifdef HAVE_DIE_NMI
if (nmi_handler_registered) {
int old_pretimeout = pretimeout;
int old_timeout = timeout;
int old_preop_val = preop_val;
/*
* Set the pretimeout to go off in a second and give
* ourselves plenty of time to stop the timer.
*/
ipmi_watchdog_state = WDOG_TIMEOUT_RESET;
preop_val = WDOG_PREOP_NONE; /* Make sure nothing happens */
pretimeout = 99;
timeout = 100;
testing_nmi = 1;
rv = ipmi_set_timeout(IPMI_SET_TIMEOUT_FORCE_HB);
if (rv) {
printk(KERN_WARNING PFX "Error starting timer to"
" test NMI: 0x%x. The NMI pretimeout will"
" likely not work\n", rv);
rv = 0;
goto out_restore;
}
msleep(1500);
if (testing_nmi != 2) {
printk(KERN_WARNING PFX "IPMI NMI didn't seem to"
" occur. The NMI pretimeout will"
" likely not work\n");
}
out_restore:
testing_nmi = 0;
preop_val = old_preop_val;
pretimeout = old_pretimeout;
timeout = old_timeout;
}
#endif
out:
if ((start_now) && (rv == 0)) {
/* Run from startup, so start the timer now. */
start_now = 0; /* Disable this function after first startup. */
ipmi_watchdog_state = action_val;
ipmi_set_timeout(IPMI_SET_TIMEOUT_FORCE_HB);
printk(KERN_INFO PFX "Starting now!\n");
} else {
/* Stop the timer now. */
ipmi_watchdog_state = WDOG_TIMEOUT_NONE;
ipmi_set_timeout(IPMI_SET_TIMEOUT_NO_HB);
}
}
static void ipmi_unregister_watchdog(int ipmi_intf)
{
int rv;
if (!watchdog_user)
goto out;
if (watchdog_ifnum != ipmi_intf)
goto out;
/* Make sure no one can call us any more. */
misc_deregister(&ipmi_wdog_miscdev);
/*
* Wait to make sure the message makes it out. The lower layer has
* pointers to our buffers, we want to make sure they are done before
* we release our memory.
*/
while (atomic_read(&set_timeout_tofree))
schedule_timeout_uninterruptible(1);
/* Disconnect from IPMI. */
rv = ipmi_destroy_user(watchdog_user);
if (rv) {
printk(KERN_WARNING PFX "error unlinking from IPMI: %d\n",
rv);
}
watchdog_user = NULL;
out:
return;
}
#ifdef HAVE_DIE_NMI
static int
ipmi_nmi(unsigned int val, struct pt_regs *regs)
{
/*
* If we get here, it's an NMI that's not a memory or I/O
* error. We can't truly tell if it's from IPMI or not
* without sending a message, and sending a message is almost
* impossible because of locking.
*/
if (testing_nmi) {
testing_nmi = 2;
return NMI_HANDLED;
}
/* If we are not expecting a timeout, ignore it. */
if (ipmi_watchdog_state == WDOG_TIMEOUT_NONE)
return NMI_DONE;
if (preaction_val != WDOG_PRETIMEOUT_NMI)
return NMI_DONE;
/*
* If no one else handled the NMI, we assume it was the IPMI
* watchdog.
*/
if (preop_val == WDOG_PREOP_PANIC) {
/* On some machines, the heartbeat will give
an error and not work unless we re-enable
the timer. So do so. */
pretimeout_since_last_heartbeat = 1;
if (atomic_inc_and_test(&preop_panic_excl))
panic(PFX "pre-timeout");
}
return NMI_HANDLED;
}
#endif
static int wdog_reboot_handler(struct notifier_block *this,
unsigned long code,
void *unused)
{
static int reboot_event_handled;
if ((watchdog_user) && (!reboot_event_handled)) {
/* Make sure we only do this once. */
reboot_event_handled = 1;
if (code == SYS_POWER_OFF || code == SYS_HALT) {
/* Disable the WDT if we are shutting down. */
ipmi_watchdog_state = WDOG_TIMEOUT_NONE;
ipmi_set_timeout(IPMI_SET_TIMEOUT_NO_HB);
} else if (ipmi_watchdog_state != WDOG_TIMEOUT_NONE) {
/* Set a long timer to let the reboot happens, but
reboot if it hangs, but only if the watchdog
timer was already running. */
timeout = 120;
pretimeout = 0;
ipmi_watchdog_state = WDOG_TIMEOUT_RESET;
ipmi_set_timeout(IPMI_SET_TIMEOUT_NO_HB);
}
}
return NOTIFY_OK;
}
static struct notifier_block wdog_reboot_notifier = {
.notifier_call = wdog_reboot_handler,
.next = NULL,
.priority = 0
};
static int wdog_panic_handler(struct notifier_block *this,
unsigned long event,
void *unused)
{
static int panic_event_handled;
/* On a panic, if we have a panic timeout, make sure to extend
the watchdog timer to a reasonable value to complete the
panic, if the watchdog timer is running. Plus the
pretimeout is meaningless at panic time. */
if (watchdog_user && !panic_event_handled &&
ipmi_watchdog_state != WDOG_TIMEOUT_NONE) {
/* Make sure we do this only once. */
panic_event_handled = 1;
timeout = 255;
pretimeout = 0;
panic_halt_ipmi_set_timeout();
}
return NOTIFY_OK;
}
static struct notifier_block wdog_panic_notifier = {
.notifier_call = wdog_panic_handler,
.next = NULL,
.priority = 150 /* priority: INT_MAX >= x >= 0 */
};
static void ipmi_new_smi(int if_num, struct device *device)
{
ipmi_register_watchdog(if_num);
}
static void ipmi_smi_gone(int if_num)
{
ipmi_unregister_watchdog(if_num);
}
static struct ipmi_smi_watcher smi_watcher = {
.owner = THIS_MODULE,
.new_smi = ipmi_new_smi,
.smi_gone = ipmi_smi_gone
};
static int action_op(const char *inval, char *outval)
{
if (outval)
strcpy(outval, action);
if (!inval)
return 0;
if (strcmp(inval, "reset") == 0)
action_val = WDOG_TIMEOUT_RESET;
else if (strcmp(inval, "none") == 0)
action_val = WDOG_TIMEOUT_NONE;
else if (strcmp(inval, "power_cycle") == 0)
action_val = WDOG_TIMEOUT_POWER_CYCLE;
else if (strcmp(inval, "power_off") == 0)
action_val = WDOG_TIMEOUT_POWER_DOWN;
else
return -EINVAL;
strcpy(action, inval);
return 0;
}
static int preaction_op(const char *inval, char *outval)
{
if (outval)
strcpy(outval, preaction);
if (!inval)
return 0;
if (strcmp(inval, "pre_none") == 0)
preaction_val = WDOG_PRETIMEOUT_NONE;
else if (strcmp(inval, "pre_smi") == 0)
preaction_val = WDOG_PRETIMEOUT_SMI;
#ifdef HAVE_DIE_NMI
else if (strcmp(inval, "pre_nmi") == 0)
preaction_val = WDOG_PRETIMEOUT_NMI;
#endif
else if (strcmp(inval, "pre_int") == 0)
preaction_val = WDOG_PRETIMEOUT_MSG_INT;
else
return -EINVAL;
strcpy(preaction, inval);
return 0;
}
static int preop_op(const char *inval, char *outval)
{
if (outval)
strcpy(outval, preop);
if (!inval)
return 0;
if (strcmp(inval, "preop_none") == 0)
preop_val = WDOG_PREOP_NONE;
else if (strcmp(inval, "preop_panic") == 0)
preop_val = WDOG_PREOP_PANIC;
else if (strcmp(inval, "preop_give_data") == 0)
preop_val = WDOG_PREOP_GIVE_DATA;
else
return -EINVAL;
strcpy(preop, inval);
return 0;
}
static void check_parms(void)
{
#ifdef HAVE_DIE_NMI
int do_nmi = 0;
int rv;
if (preaction_val == WDOG_PRETIMEOUT_NMI) {
do_nmi = 1;
if (preop_val == WDOG_PREOP_GIVE_DATA) {
printk(KERN_WARNING PFX "Pretimeout op is to give data"
" but NMI pretimeout is enabled, setting"
" pretimeout op to none\n");
preop_op("preop_none", NULL);
do_nmi = 0;
}
}
if (do_nmi && !nmi_handler_registered) {
rv = register_nmi_handler(NMI_UNKNOWN, ipmi_nmi, 0,
"ipmi");
if (rv) {
printk(KERN_WARNING PFX
"Can't register nmi handler\n");
return;
} else
nmi_handler_registered = 1;
} else if (!do_nmi && nmi_handler_registered) {
unregister_nmi_handler(NMI_UNKNOWN, "ipmi");
nmi_handler_registered = 0;
}
#endif
}
static int __init ipmi_wdog_init(void)
{
int rv;
if (action_op(action, NULL)) {
action_op("reset", NULL);
printk(KERN_INFO PFX "Unknown action '%s', defaulting to"
" reset\n", action);
}
if (preaction_op(preaction, NULL)) {
preaction_op("pre_none", NULL);
printk(KERN_INFO PFX "Unknown preaction '%s', defaulting to"
" none\n", preaction);
}
if (preop_op(preop, NULL)) {
preop_op("preop_none", NULL);
printk(KERN_INFO PFX "Unknown preop '%s', defaulting to"
" none\n", preop);
}
check_parms();
register_reboot_notifier(&wdog_reboot_notifier);
atomic_notifier_chain_register(&panic_notifier_list,
&wdog_panic_notifier);
rv = ipmi_smi_watcher_register(&smi_watcher);
if (rv) {
#ifdef HAVE_DIE_NMI
if (nmi_handler_registered)
unregister_nmi_handler(NMI_UNKNOWN, "ipmi");
#endif
atomic_notifier_chain_unregister(&panic_notifier_list,
&wdog_panic_notifier);
unregister_reboot_notifier(&wdog_reboot_notifier);
printk(KERN_WARNING PFX "can't register smi watcher\n");
return rv;
}
printk(KERN_INFO PFX "driver initialized\n");
return 0;
}
static void __exit ipmi_wdog_exit(void)
{
ipmi_smi_watcher_unregister(&smi_watcher);
ipmi_unregister_watchdog(watchdog_ifnum);
#ifdef HAVE_DIE_NMI
if (nmi_handler_registered)
unregister_nmi_handler(NMI_UNKNOWN, "ipmi");
#endif
atomic_notifier_chain_unregister(&panic_notifier_list,
&wdog_panic_notifier);
unregister_reboot_notifier(&wdog_reboot_notifier);
}
module_exit(ipmi_wdog_exit);
module_init(ipmi_wdog_init);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Corey Minyard <minyard@mvista.com>");
MODULE_DESCRIPTION("watchdog timer based upon the IPMI interface.");
| gpl-2.0 |
maxrdlf95/htc_m8_maxkernel | drivers/media/radio/radio-isa.c | 4854 | 9372 | /*
* Framework for ISA radio drivers.
* This takes care of all the V4L2 scaffolding, allowing the ISA drivers
* to concentrate on the actual hardware operation.
*
* Copyright (C) 2012 Hans Verkuil <hans.verkuil@cisco.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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/delay.h>
#include <linux/videodev2.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <media/v4l2-device.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-fh.h>
#include <media/v4l2-ctrls.h>
#include <media/v4l2-event.h>
#include "radio-isa.h"
MODULE_AUTHOR("Hans Verkuil");
MODULE_DESCRIPTION("A framework for ISA radio drivers.");
MODULE_LICENSE("GPL");
#define FREQ_LOW (87U * 16000U)
#define FREQ_HIGH (108U * 16000U)
static int radio_isa_querycap(struct file *file, void *priv,
struct v4l2_capability *v)
{
struct radio_isa_card *isa = video_drvdata(file);
strlcpy(v->driver, isa->drv->driver.driver.name, sizeof(v->driver));
strlcpy(v->card, isa->drv->card, sizeof(v->card));
snprintf(v->bus_info, sizeof(v->bus_info), "ISA:%s", isa->v4l2_dev.name);
v->capabilities = V4L2_CAP_TUNER | V4L2_CAP_RADIO;
v->device_caps = v->capabilities | V4L2_CAP_DEVICE_CAPS;
return 0;
}
static int radio_isa_g_tuner(struct file *file, void *priv,
struct v4l2_tuner *v)
{
struct radio_isa_card *isa = video_drvdata(file);
const struct radio_isa_ops *ops = isa->drv->ops;
if (v->index > 0)
return -EINVAL;
strlcpy(v->name, "FM", sizeof(v->name));
v->type = V4L2_TUNER_RADIO;
v->rangelow = FREQ_LOW;
v->rangehigh = FREQ_HIGH;
v->capability = V4L2_TUNER_CAP_LOW;
if (isa->drv->has_stereo)
v->capability |= V4L2_TUNER_CAP_STEREO;
if (ops->g_rxsubchans)
v->rxsubchans = ops->g_rxsubchans(isa);
else
v->rxsubchans = V4L2_TUNER_SUB_MONO | V4L2_TUNER_SUB_STEREO;
v->audmode = isa->stereo ? V4L2_TUNER_MODE_STEREO : V4L2_TUNER_MODE_MONO;
if (ops->g_signal)
v->signal = ops->g_signal(isa);
else
v->signal = (v->rxsubchans & V4L2_TUNER_SUB_STEREO) ?
0xffff : 0;
return 0;
}
static int radio_isa_s_tuner(struct file *file, void *priv,
struct v4l2_tuner *v)
{
struct radio_isa_card *isa = video_drvdata(file);
const struct radio_isa_ops *ops = isa->drv->ops;
if (v->index)
return -EINVAL;
if (ops->s_stereo) {
isa->stereo = (v->audmode == V4L2_TUNER_MODE_STEREO);
return ops->s_stereo(isa, isa->stereo);
}
return 0;
}
static int radio_isa_s_frequency(struct file *file, void *priv,
struct v4l2_frequency *f)
{
struct radio_isa_card *isa = video_drvdata(file);
int res;
if (f->tuner != 0 || f->type != V4L2_TUNER_RADIO)
return -EINVAL;
f->frequency = clamp(f->frequency, FREQ_LOW, FREQ_HIGH);
res = isa->drv->ops->s_frequency(isa, f->frequency);
if (res == 0)
isa->freq = f->frequency;
return res;
}
static int radio_isa_g_frequency(struct file *file, void *priv,
struct v4l2_frequency *f)
{
struct radio_isa_card *isa = video_drvdata(file);
if (f->tuner != 0)
return -EINVAL;
f->type = V4L2_TUNER_RADIO;
f->frequency = isa->freq;
return 0;
}
static int radio_isa_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct radio_isa_card *isa =
container_of(ctrl->handler, struct radio_isa_card, hdl);
switch (ctrl->id) {
case V4L2_CID_AUDIO_MUTE:
return isa->drv->ops->s_mute_volume(isa, ctrl->val,
isa->volume ? isa->volume->val : 0);
}
return -EINVAL;
}
static int radio_isa_log_status(struct file *file, void *priv)
{
struct radio_isa_card *isa = video_drvdata(file);
v4l2_info(&isa->v4l2_dev, "I/O Port = 0x%03x\n", isa->io);
v4l2_ctrl_handler_log_status(&isa->hdl, isa->v4l2_dev.name);
return 0;
}
static int radio_isa_subscribe_event(struct v4l2_fh *fh,
struct v4l2_event_subscription *sub)
{
if (sub->type == V4L2_EVENT_CTRL)
return v4l2_event_subscribe(fh, sub, 0);
return -EINVAL;
}
static const struct v4l2_ctrl_ops radio_isa_ctrl_ops = {
.s_ctrl = radio_isa_s_ctrl,
};
static const struct v4l2_file_operations radio_isa_fops = {
.owner = THIS_MODULE,
.open = v4l2_fh_open,
.release = v4l2_fh_release,
.poll = v4l2_ctrl_poll,
.unlocked_ioctl = video_ioctl2,
};
static const struct v4l2_ioctl_ops radio_isa_ioctl_ops = {
.vidioc_querycap = radio_isa_querycap,
.vidioc_g_tuner = radio_isa_g_tuner,
.vidioc_s_tuner = radio_isa_s_tuner,
.vidioc_g_frequency = radio_isa_g_frequency,
.vidioc_s_frequency = radio_isa_s_frequency,
.vidioc_log_status = radio_isa_log_status,
.vidioc_subscribe_event = radio_isa_subscribe_event,
.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
};
int radio_isa_match(struct device *pdev, unsigned int dev)
{
struct radio_isa_driver *drv = pdev->platform_data;
return drv->probe || drv->io_params[dev] >= 0;
}
EXPORT_SYMBOL_GPL(radio_isa_match);
static bool radio_isa_valid_io(const struct radio_isa_driver *drv, int io)
{
int i;
for (i = 0; i < drv->num_of_io_ports; i++)
if (drv->io_ports[i] == io)
return true;
return false;
}
int radio_isa_probe(struct device *pdev, unsigned int dev)
{
struct radio_isa_driver *drv = pdev->platform_data;
const struct radio_isa_ops *ops = drv->ops;
struct v4l2_device *v4l2_dev;
struct radio_isa_card *isa;
int res;
isa = drv->ops->alloc();
if (isa == NULL)
return -ENOMEM;
dev_set_drvdata(pdev, isa);
isa->drv = drv;
isa->io = drv->io_params[dev];
v4l2_dev = &isa->v4l2_dev;
strlcpy(v4l2_dev->name, dev_name(pdev), sizeof(v4l2_dev->name));
if (drv->probe && ops->probe) {
int i;
for (i = 0; i < drv->num_of_io_ports; ++i) {
int io = drv->io_ports[i];
if (request_region(io, drv->region_size, v4l2_dev->name)) {
bool found = ops->probe(isa, io);
release_region(io, drv->region_size);
if (found) {
isa->io = io;
break;
}
}
}
}
if (!radio_isa_valid_io(drv, isa->io)) {
int i;
if (isa->io < 0)
return -ENODEV;
v4l2_err(v4l2_dev, "you must set an I/O address with io=0x%03x",
drv->io_ports[0]);
for (i = 1; i < drv->num_of_io_ports; i++)
printk(KERN_CONT "/0x%03x", drv->io_ports[i]);
printk(KERN_CONT ".\n");
kfree(isa);
return -EINVAL;
}
if (!request_region(isa->io, drv->region_size, v4l2_dev->name)) {
v4l2_err(v4l2_dev, "port 0x%x already in use\n", isa->io);
kfree(isa);
return -EBUSY;
}
res = v4l2_device_register(pdev, v4l2_dev);
if (res < 0) {
v4l2_err(v4l2_dev, "Could not register v4l2_device\n");
goto err_dev_reg;
}
v4l2_ctrl_handler_init(&isa->hdl, 1);
isa->mute = v4l2_ctrl_new_std(&isa->hdl, &radio_isa_ctrl_ops,
V4L2_CID_AUDIO_MUTE, 0, 1, 1, 1);
if (drv->max_volume)
isa->volume = v4l2_ctrl_new_std(&isa->hdl, &radio_isa_ctrl_ops,
V4L2_CID_AUDIO_VOLUME, 0, drv->max_volume, 1,
drv->max_volume);
v4l2_dev->ctrl_handler = &isa->hdl;
if (isa->hdl.error) {
res = isa->hdl.error;
v4l2_err(v4l2_dev, "Could not register controls\n");
goto err_hdl;
}
if (drv->max_volume)
v4l2_ctrl_cluster(2, &isa->mute);
v4l2_dev->ctrl_handler = &isa->hdl;
mutex_init(&isa->lock);
isa->vdev.lock = &isa->lock;
strlcpy(isa->vdev.name, v4l2_dev->name, sizeof(isa->vdev.name));
isa->vdev.v4l2_dev = v4l2_dev;
isa->vdev.fops = &radio_isa_fops;
isa->vdev.ioctl_ops = &radio_isa_ioctl_ops;
isa->vdev.release = video_device_release_empty;
set_bit(V4L2_FL_USE_FH_PRIO, &isa->vdev.flags);
video_set_drvdata(&isa->vdev, isa);
isa->freq = FREQ_LOW;
isa->stereo = drv->has_stereo;
if (ops->init)
res = ops->init(isa);
if (!res)
res = v4l2_ctrl_handler_setup(&isa->hdl);
if (!res)
res = ops->s_frequency(isa, isa->freq);
if (!res && ops->s_stereo)
res = ops->s_stereo(isa, isa->stereo);
if (res < 0) {
v4l2_err(v4l2_dev, "Could not setup card\n");
goto err_node_reg;
}
res = video_register_device(&isa->vdev, VFL_TYPE_RADIO,
drv->radio_nr_params[dev]);
if (res < 0) {
v4l2_err(v4l2_dev, "Could not register device node\n");
goto err_node_reg;
}
v4l2_info(v4l2_dev, "Initialized radio card %s on port 0x%03x\n",
drv->card, isa->io);
return 0;
err_node_reg:
v4l2_ctrl_handler_free(&isa->hdl);
err_hdl:
v4l2_device_unregister(&isa->v4l2_dev);
err_dev_reg:
release_region(isa->io, drv->region_size);
kfree(isa);
return res;
}
EXPORT_SYMBOL_GPL(radio_isa_probe);
int radio_isa_remove(struct device *pdev, unsigned int dev)
{
struct radio_isa_card *isa = dev_get_drvdata(pdev);
const struct radio_isa_ops *ops = isa->drv->ops;
ops->s_mute_volume(isa, true, isa->volume ? isa->volume->cur.val : 0);
video_unregister_device(&isa->vdev);
v4l2_ctrl_handler_free(&isa->hdl);
v4l2_device_unregister(&isa->v4l2_dev);
release_region(isa->io, isa->drv->region_size);
v4l2_info(&isa->v4l2_dev, "Removed radio card %s\n", isa->drv->card);
kfree(isa);
return 0;
}
EXPORT_SYMBOL_GPL(radio_isa_remove);
| gpl-2.0 |
slebit/android_kernel_lge_v500 | drivers/s390/cio/qdio_setup.c | 4854 | 14747 | /*
* driver/s390/cio/qdio_setup.c
*
* qdio queue initialization
*
* Copyright (C) IBM Corp. 2008
* Author(s): Jan Glauber <jang@linux.vnet.ibm.com>
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/export.h>
#include <asm/qdio.h>
#include "cio.h"
#include "css.h"
#include "device.h"
#include "ioasm.h"
#include "chsc.h"
#include "qdio.h"
#include "qdio_debug.h"
static struct kmem_cache *qdio_q_cache;
static struct kmem_cache *qdio_aob_cache;
struct qaob *qdio_allocate_aob(void)
{
return kmem_cache_zalloc(qdio_aob_cache, GFP_ATOMIC);
}
EXPORT_SYMBOL_GPL(qdio_allocate_aob);
void qdio_release_aob(struct qaob *aob)
{
kmem_cache_free(qdio_aob_cache, aob);
}
EXPORT_SYMBOL_GPL(qdio_release_aob);
/*
* qebsm is only available under 64bit but the adapter sets the feature
* flag anyway, so we manually override it.
*/
static inline int qebsm_possible(void)
{
#ifdef CONFIG_64BIT
return css_general_characteristics.qebsm;
#endif
return 0;
}
/*
* qib_param_field: pointer to 128 bytes or NULL, if no param field
* nr_input_qs: pointer to nr_queues*128 words of data or NULL
*/
static void set_impl_params(struct qdio_irq *irq_ptr,
unsigned int qib_param_field_format,
unsigned char *qib_param_field,
unsigned long *input_slib_elements,
unsigned long *output_slib_elements)
{
struct qdio_q *q;
int i, j;
if (!irq_ptr)
return;
irq_ptr->qib.pfmt = qib_param_field_format;
if (qib_param_field)
memcpy(irq_ptr->qib.parm, qib_param_field,
QDIO_MAX_BUFFERS_PER_Q);
if (!input_slib_elements)
goto output;
for_each_input_queue(irq_ptr, q, i) {
for (j = 0; j < QDIO_MAX_BUFFERS_PER_Q; j++)
q->slib->slibe[j].parms =
input_slib_elements[i * QDIO_MAX_BUFFERS_PER_Q + j];
}
output:
if (!output_slib_elements)
return;
for_each_output_queue(irq_ptr, q, i) {
for (j = 0; j < QDIO_MAX_BUFFERS_PER_Q; j++)
q->slib->slibe[j].parms =
output_slib_elements[i * QDIO_MAX_BUFFERS_PER_Q + j];
}
}
static int __qdio_allocate_qs(struct qdio_q **irq_ptr_qs, int nr_queues)
{
struct qdio_q *q;
int i;
for (i = 0; i < nr_queues; i++) {
q = kmem_cache_alloc(qdio_q_cache, GFP_KERNEL);
if (!q)
return -ENOMEM;
q->slib = (struct slib *) __get_free_page(GFP_KERNEL);
if (!q->slib) {
kmem_cache_free(qdio_q_cache, q);
return -ENOMEM;
}
irq_ptr_qs[i] = q;
}
return 0;
}
int qdio_allocate_qs(struct qdio_irq *irq_ptr, int nr_input_qs, int nr_output_qs)
{
int rc;
rc = __qdio_allocate_qs(irq_ptr->input_qs, nr_input_qs);
if (rc)
return rc;
rc = __qdio_allocate_qs(irq_ptr->output_qs, nr_output_qs);
return rc;
}
static void setup_queues_misc(struct qdio_q *q, struct qdio_irq *irq_ptr,
qdio_handler_t *handler, int i)
{
struct slib *slib = q->slib;
/* queue must be cleared for qdio_establish */
memset(q, 0, sizeof(*q));
memset(slib, 0, PAGE_SIZE);
q->slib = slib;
q->irq_ptr = irq_ptr;
q->mask = 1 << (31 - i);
q->nr = i;
q->handler = handler;
}
static void setup_storage_lists(struct qdio_q *q, struct qdio_irq *irq_ptr,
void **sbals_array, int i)
{
struct qdio_q *prev;
int j;
DBF_HEX(&q, sizeof(void *));
q->sl = (struct sl *)((char *)q->slib + PAGE_SIZE / 2);
/* fill in sbal */
for (j = 0; j < QDIO_MAX_BUFFERS_PER_Q; j++) {
q->sbal[j] = *sbals_array++;
BUG_ON((unsigned long)q->sbal[j] & 0xff);
}
/* fill in slib */
if (i > 0) {
prev = (q->is_input_q) ? irq_ptr->input_qs[i - 1]
: irq_ptr->output_qs[i - 1];
prev->slib->nsliba = (unsigned long)q->slib;
}
q->slib->sla = (unsigned long)q->sl;
q->slib->slsba = (unsigned long)&q->slsb.val[0];
/* fill in sl */
for (j = 0; j < QDIO_MAX_BUFFERS_PER_Q; j++)
q->sl->element[j].sbal = (unsigned long)q->sbal[j];
}
static void setup_queues(struct qdio_irq *irq_ptr,
struct qdio_initialize *qdio_init)
{
struct qdio_q *q;
void **input_sbal_array = qdio_init->input_sbal_addr_array;
void **output_sbal_array = qdio_init->output_sbal_addr_array;
struct qdio_outbuf_state *output_sbal_state_array =
qdio_init->output_sbal_state_array;
int i;
for_each_input_queue(irq_ptr, q, i) {
DBF_EVENT("inq:%1d", i);
setup_queues_misc(q, irq_ptr, qdio_init->input_handler, i);
q->is_input_q = 1;
q->u.in.queue_start_poll = qdio_init->queue_start_poll_array ?
qdio_init->queue_start_poll_array[i] : NULL;
setup_storage_lists(q, irq_ptr, input_sbal_array, i);
input_sbal_array += QDIO_MAX_BUFFERS_PER_Q;
if (is_thinint_irq(irq_ptr)) {
tasklet_init(&q->tasklet, tiqdio_inbound_processing,
(unsigned long) q);
} else {
tasklet_init(&q->tasklet, qdio_inbound_processing,
(unsigned long) q);
}
}
for_each_output_queue(irq_ptr, q, i) {
DBF_EVENT("outq:%1d", i);
setup_queues_misc(q, irq_ptr, qdio_init->output_handler, i);
q->u.out.sbal_state = output_sbal_state_array;
output_sbal_state_array += QDIO_MAX_BUFFERS_PER_Q;
q->is_input_q = 0;
q->u.out.scan_threshold = qdio_init->scan_threshold;
setup_storage_lists(q, irq_ptr, output_sbal_array, i);
output_sbal_array += QDIO_MAX_BUFFERS_PER_Q;
tasklet_init(&q->tasklet, qdio_outbound_processing,
(unsigned long) q);
setup_timer(&q->u.out.timer, (void(*)(unsigned long))
&qdio_outbound_timer, (unsigned long)q);
}
}
static void process_ac_flags(struct qdio_irq *irq_ptr, unsigned char qdioac)
{
if (qdioac & AC1_SIGA_INPUT_NEEDED)
irq_ptr->siga_flag.input = 1;
if (qdioac & AC1_SIGA_OUTPUT_NEEDED)
irq_ptr->siga_flag.output = 1;
if (qdioac & AC1_SIGA_SYNC_NEEDED)
irq_ptr->siga_flag.sync = 1;
if (!(qdioac & AC1_AUTOMATIC_SYNC_ON_THININT))
irq_ptr->siga_flag.sync_after_ai = 1;
if (!(qdioac & AC1_AUTOMATIC_SYNC_ON_OUT_PCI))
irq_ptr->siga_flag.sync_out_after_pci = 1;
}
static void check_and_setup_qebsm(struct qdio_irq *irq_ptr,
unsigned char qdioac, unsigned long token)
{
if (!(irq_ptr->qib.rflags & QIB_RFLAGS_ENABLE_QEBSM))
goto no_qebsm;
if (!(qdioac & AC1_SC_QEBSM_AVAILABLE) ||
(!(qdioac & AC1_SC_QEBSM_ENABLED)))
goto no_qebsm;
irq_ptr->sch_token = token;
DBF_EVENT("V=V:1");
DBF_EVENT("%8lx", irq_ptr->sch_token);
return;
no_qebsm:
irq_ptr->sch_token = 0;
irq_ptr->qib.rflags &= ~QIB_RFLAGS_ENABLE_QEBSM;
DBF_EVENT("noV=V");
}
/*
* If there is a qdio_irq we use the chsc_page and store the information
* in the qdio_irq, otherwise we copy it to the specified structure.
*/
int qdio_setup_get_ssqd(struct qdio_irq *irq_ptr,
struct subchannel_id *schid,
struct qdio_ssqd_desc *data)
{
struct chsc_ssqd_area *ssqd;
int rc;
DBF_EVENT("getssqd:%4x", schid->sch_no);
if (irq_ptr != NULL)
ssqd = (struct chsc_ssqd_area *)irq_ptr->chsc_page;
else
ssqd = (struct chsc_ssqd_area *)__get_free_page(GFP_KERNEL);
memset(ssqd, 0, PAGE_SIZE);
ssqd->request = (struct chsc_header) {
.length = 0x0010,
.code = 0x0024,
};
ssqd->first_sch = schid->sch_no;
ssqd->last_sch = schid->sch_no;
ssqd->ssid = schid->ssid;
if (chsc(ssqd))
return -EIO;
rc = chsc_error_from_response(ssqd->response.code);
if (rc)
return rc;
if (!(ssqd->qdio_ssqd.flags & CHSC_FLAG_QDIO_CAPABILITY) ||
!(ssqd->qdio_ssqd.flags & CHSC_FLAG_VALIDITY) ||
(ssqd->qdio_ssqd.sch != schid->sch_no))
return -EINVAL;
if (irq_ptr != NULL)
memcpy(&irq_ptr->ssqd_desc, &ssqd->qdio_ssqd,
sizeof(struct qdio_ssqd_desc));
else {
memcpy(data, &ssqd->qdio_ssqd,
sizeof(struct qdio_ssqd_desc));
free_page((unsigned long)ssqd);
}
return 0;
}
void qdio_setup_ssqd_info(struct qdio_irq *irq_ptr)
{
unsigned char qdioac;
int rc;
rc = qdio_setup_get_ssqd(irq_ptr, &irq_ptr->schid, NULL);
if (rc) {
DBF_ERROR("%4x ssqd ERR", irq_ptr->schid.sch_no);
DBF_ERROR("rc:%x", rc);
/* all flags set, worst case */
qdioac = AC1_SIGA_INPUT_NEEDED | AC1_SIGA_OUTPUT_NEEDED |
AC1_SIGA_SYNC_NEEDED;
} else
qdioac = irq_ptr->ssqd_desc.qdioac1;
check_and_setup_qebsm(irq_ptr, qdioac, irq_ptr->ssqd_desc.sch_token);
process_ac_flags(irq_ptr, qdioac);
DBF_EVENT("ac 1:%2x 2:%4x", qdioac, irq_ptr->ssqd_desc.qdioac2);
DBF_EVENT("3:%4x qib:%4x", irq_ptr->ssqd_desc.qdioac3, irq_ptr->qib.ac);
}
void qdio_release_memory(struct qdio_irq *irq_ptr)
{
struct qdio_q *q;
int i;
/*
* Must check queue array manually since irq_ptr->nr_input_queues /
* irq_ptr->nr_input_queues may not yet be set.
*/
for (i = 0; i < QDIO_MAX_QUEUES_PER_IRQ; i++) {
q = irq_ptr->input_qs[i];
if (q) {
free_page((unsigned long) q->slib);
kmem_cache_free(qdio_q_cache, q);
}
}
for (i = 0; i < QDIO_MAX_QUEUES_PER_IRQ; i++) {
q = irq_ptr->output_qs[i];
if (q) {
if (q->u.out.use_cq) {
int n;
for (n = 0; n < QDIO_MAX_BUFFERS_PER_Q; ++n) {
struct qaob *aob = q->u.out.aobs[n];
if (aob) {
qdio_release_aob(aob);
q->u.out.aobs[n] = NULL;
}
}
qdio_disable_async_operation(&q->u.out);
}
free_page((unsigned long) q->slib);
kmem_cache_free(qdio_q_cache, q);
}
}
free_page((unsigned long) irq_ptr->qdr);
free_page(irq_ptr->chsc_page);
free_page((unsigned long) irq_ptr);
}
static void __qdio_allocate_fill_qdr(struct qdio_irq *irq_ptr,
struct qdio_q **irq_ptr_qs,
int i, int nr)
{
irq_ptr->qdr->qdf0[i + nr].sliba =
(unsigned long)irq_ptr_qs[i]->slib;
irq_ptr->qdr->qdf0[i + nr].sla =
(unsigned long)irq_ptr_qs[i]->sl;
irq_ptr->qdr->qdf0[i + nr].slsba =
(unsigned long)&irq_ptr_qs[i]->slsb.val[0];
irq_ptr->qdr->qdf0[i + nr].akey = PAGE_DEFAULT_KEY >> 4;
irq_ptr->qdr->qdf0[i + nr].bkey = PAGE_DEFAULT_KEY >> 4;
irq_ptr->qdr->qdf0[i + nr].ckey = PAGE_DEFAULT_KEY >> 4;
irq_ptr->qdr->qdf0[i + nr].dkey = PAGE_DEFAULT_KEY >> 4;
}
static void setup_qdr(struct qdio_irq *irq_ptr,
struct qdio_initialize *qdio_init)
{
int i;
irq_ptr->qdr->qfmt = qdio_init->q_format;
irq_ptr->qdr->ac = qdio_init->qdr_ac;
irq_ptr->qdr->iqdcnt = qdio_init->no_input_qs;
irq_ptr->qdr->oqdcnt = qdio_init->no_output_qs;
irq_ptr->qdr->iqdsz = sizeof(struct qdesfmt0) / 4; /* size in words */
irq_ptr->qdr->oqdsz = sizeof(struct qdesfmt0) / 4;
irq_ptr->qdr->qiba = (unsigned long)&irq_ptr->qib;
irq_ptr->qdr->qkey = PAGE_DEFAULT_KEY >> 4;
for (i = 0; i < qdio_init->no_input_qs; i++)
__qdio_allocate_fill_qdr(irq_ptr, irq_ptr->input_qs, i, 0);
for (i = 0; i < qdio_init->no_output_qs; i++)
__qdio_allocate_fill_qdr(irq_ptr, irq_ptr->output_qs, i,
qdio_init->no_input_qs);
}
static void setup_qib(struct qdio_irq *irq_ptr,
struct qdio_initialize *init_data)
{
if (qebsm_possible())
irq_ptr->qib.rflags |= QIB_RFLAGS_ENABLE_QEBSM;
irq_ptr->qib.rflags |= init_data->qib_rflags;
irq_ptr->qib.qfmt = init_data->q_format;
if (init_data->no_input_qs)
irq_ptr->qib.isliba =
(unsigned long)(irq_ptr->input_qs[0]->slib);
if (init_data->no_output_qs)
irq_ptr->qib.osliba =
(unsigned long)(irq_ptr->output_qs[0]->slib);
memcpy(irq_ptr->qib.ebcnam, init_data->adapter_name, 8);
}
int qdio_setup_irq(struct qdio_initialize *init_data)
{
struct ciw *ciw;
struct qdio_irq *irq_ptr = init_data->cdev->private->qdio_data;
int rc;
memset(&irq_ptr->qib, 0, sizeof(irq_ptr->qib));
memset(&irq_ptr->siga_flag, 0, sizeof(irq_ptr->siga_flag));
memset(&irq_ptr->ccw, 0, sizeof(irq_ptr->ccw));
memset(&irq_ptr->ssqd_desc, 0, sizeof(irq_ptr->ssqd_desc));
memset(&irq_ptr->perf_stat, 0, sizeof(irq_ptr->perf_stat));
irq_ptr->debugfs_dev = irq_ptr->debugfs_perf = NULL;
irq_ptr->sch_token = irq_ptr->state = irq_ptr->perf_stat_enabled = 0;
/* wipes qib.ac, required by ar7063 */
memset(irq_ptr->qdr, 0, sizeof(struct qdr));
irq_ptr->int_parm = init_data->int_parm;
irq_ptr->nr_input_qs = init_data->no_input_qs;
irq_ptr->nr_output_qs = init_data->no_output_qs;
irq_ptr->schid = ccw_device_get_subchannel_id(init_data->cdev);
irq_ptr->cdev = init_data->cdev;
setup_queues(irq_ptr, init_data);
setup_qib(irq_ptr, init_data);
qdio_setup_thinint(irq_ptr);
set_impl_params(irq_ptr, init_data->qib_param_field_format,
init_data->qib_param_field,
init_data->input_slib_elements,
init_data->output_slib_elements);
/* fill input and output descriptors */
setup_qdr(irq_ptr, init_data);
/* qdr, qib, sls, slsbs, slibs, sbales are filled now */
/* get qdio commands */
ciw = ccw_device_get_ciw(init_data->cdev, CIW_TYPE_EQUEUE);
if (!ciw) {
DBF_ERROR("%4x NO EQ", irq_ptr->schid.sch_no);
rc = -EINVAL;
goto out_err;
}
irq_ptr->equeue = *ciw;
ciw = ccw_device_get_ciw(init_data->cdev, CIW_TYPE_AQUEUE);
if (!ciw) {
DBF_ERROR("%4x NO AQ", irq_ptr->schid.sch_no);
rc = -EINVAL;
goto out_err;
}
irq_ptr->aqueue = *ciw;
/* set new interrupt handler */
irq_ptr->orig_handler = init_data->cdev->handler;
init_data->cdev->handler = qdio_int_handler;
return 0;
out_err:
qdio_release_memory(irq_ptr);
return rc;
}
void qdio_print_subchannel_info(struct qdio_irq *irq_ptr,
struct ccw_device *cdev)
{
char s[80];
snprintf(s, 80, "qdio: %s %s on SC %x using "
"AI:%d QEBSM:%d PCI:%d TDD:%d SIGA:%s%s%s%s%s\n",
dev_name(&cdev->dev),
(irq_ptr->qib.qfmt == QDIO_QETH_QFMT) ? "OSA" :
((irq_ptr->qib.qfmt == QDIO_ZFCP_QFMT) ? "ZFCP" : "HS"),
irq_ptr->schid.sch_no,
is_thinint_irq(irq_ptr),
(irq_ptr->sch_token) ? 1 : 0,
(irq_ptr->qib.ac & QIB_AC_OUTBOUND_PCI_SUPPORTED) ? 1 : 0,
css_general_characteristics.aif_tdd,
(irq_ptr->siga_flag.input) ? "R" : " ",
(irq_ptr->siga_flag.output) ? "W" : " ",
(irq_ptr->siga_flag.sync) ? "S" : " ",
(irq_ptr->siga_flag.sync_after_ai) ? "A" : " ",
(irq_ptr->siga_flag.sync_out_after_pci) ? "P" : " ");
printk(KERN_INFO "%s", s);
}
int qdio_enable_async_operation(struct qdio_output_q *outq)
{
outq->aobs = kzalloc(sizeof(struct qaob *) * QDIO_MAX_BUFFERS_PER_Q,
GFP_ATOMIC);
if (!outq->aobs) {
outq->use_cq = 0;
return -ENOMEM;
}
outq->use_cq = 1;
return 0;
}
void qdio_disable_async_operation(struct qdio_output_q *q)
{
kfree(q->aobs);
q->aobs = NULL;
q->use_cq = 0;
}
int __init qdio_setup_init(void)
{
int rc;
qdio_q_cache = kmem_cache_create("qdio_q", sizeof(struct qdio_q),
256, 0, NULL);
if (!qdio_q_cache)
return -ENOMEM;
qdio_aob_cache = kmem_cache_create("qdio_aob",
sizeof(struct qaob),
sizeof(struct qaob),
0,
NULL);
if (!qdio_aob_cache) {
rc = -ENOMEM;
goto free_qdio_q_cache;
}
/* Check for OSA/FCP thin interrupts (bit 67). */
DBF_EVENT("thinint:%1d",
(css_general_characteristics.aif_osa) ? 1 : 0);
/* Check for QEBSM support in general (bit 58). */
DBF_EVENT("cssQEBSM:%1d", (qebsm_possible()) ? 1 : 0);
rc = 0;
out:
return rc;
free_qdio_q_cache:
kmem_cache_destroy(qdio_q_cache);
goto out;
}
void qdio_setup_exit(void)
{
kmem_cache_destroy(qdio_aob_cache);
kmem_cache_destroy(qdio_q_cache);
}
| gpl-2.0 |
omnirom/android_kernel_oppo_apq8064 | drivers/s390/char/tape_core.c | 5110 | 35668 | /*
* drivers/s390/char/tape_core.c
* basic function of the tape device driver
*
* S390 and zSeries version
* Copyright IBM Corp. 2001, 2009
* Author(s): Carsten Otte <cotte@de.ibm.com>
* Michael Holzheu <holzheu@de.ibm.com>
* Tuan Ngo-Anh <ngoanh@de.ibm.com>
* Martin Schwidefsky <schwidefsky@de.ibm.com>
* Stefan Bader <shbader@de.ibm.com>
*/
#define KMSG_COMPONENT "tape"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/module.h>
#include <linux/init.h> // for kernel parameters
#include <linux/kmod.h> // for requesting modules
#include <linux/spinlock.h> // for locks
#include <linux/vmalloc.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <asm/types.h> // for variable types
#define TAPE_DBF_AREA tape_core_dbf
#include "tape.h"
#include "tape_std.h"
#define LONG_BUSY_TIMEOUT 180 /* seconds */
static void __tape_do_irq (struct ccw_device *, unsigned long, struct irb *);
static void tape_delayed_next_request(struct work_struct *);
static void tape_long_busy_timeout(unsigned long data);
/*
* One list to contain all tape devices of all disciplines, so
* we can assign the devices to minor numbers of the same major
* The list is protected by the rwlock
*/
static LIST_HEAD(tape_device_list);
static DEFINE_RWLOCK(tape_device_lock);
/*
* Pointer to debug area.
*/
debug_info_t *TAPE_DBF_AREA = NULL;
EXPORT_SYMBOL(TAPE_DBF_AREA);
/*
* Printable strings for tape enumerations.
*/
const char *tape_state_verbose[TS_SIZE] =
{
[TS_UNUSED] = "UNUSED",
[TS_IN_USE] = "IN_USE",
[TS_BLKUSE] = "BLKUSE",
[TS_INIT] = "INIT ",
[TS_NOT_OPER] = "NOT_OP"
};
const char *tape_op_verbose[TO_SIZE] =
{
[TO_BLOCK] = "BLK", [TO_BSB] = "BSB",
[TO_BSF] = "BSF", [TO_DSE] = "DSE",
[TO_FSB] = "FSB", [TO_FSF] = "FSF",
[TO_LBL] = "LBL", [TO_NOP] = "NOP",
[TO_RBA] = "RBA", [TO_RBI] = "RBI",
[TO_RFO] = "RFO", [TO_REW] = "REW",
[TO_RUN] = "RUN", [TO_WRI] = "WRI",
[TO_WTM] = "WTM", [TO_MSEN] = "MSN",
[TO_LOAD] = "LOA", [TO_READ_CONFIG] = "RCF",
[TO_READ_ATTMSG] = "RAT",
[TO_DIS] = "DIS", [TO_ASSIGN] = "ASS",
[TO_UNASSIGN] = "UAS", [TO_CRYPT_ON] = "CON",
[TO_CRYPT_OFF] = "COF", [TO_KEKL_SET] = "KLS",
[TO_KEKL_QUERY] = "KLQ",[TO_RDC] = "RDC",
};
static int devid_to_int(struct ccw_dev_id *dev_id)
{
return dev_id->devno + (dev_id->ssid << 16);
}
/*
* Some channel attached tape specific attributes.
*
* FIXME: In the future the first_minor and blocksize attribute should be
* replaced by a link to the cdev tree.
*/
static ssize_t
tape_medium_state_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct tape_device *tdev;
tdev = dev_get_drvdata(dev);
return scnprintf(buf, PAGE_SIZE, "%i\n", tdev->medium_state);
}
static
DEVICE_ATTR(medium_state, 0444, tape_medium_state_show, NULL);
static ssize_t
tape_first_minor_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct tape_device *tdev;
tdev = dev_get_drvdata(dev);
return scnprintf(buf, PAGE_SIZE, "%i\n", tdev->first_minor);
}
static
DEVICE_ATTR(first_minor, 0444, tape_first_minor_show, NULL);
static ssize_t
tape_state_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct tape_device *tdev;
tdev = dev_get_drvdata(dev);
return scnprintf(buf, PAGE_SIZE, "%s\n", (tdev->first_minor < 0) ?
"OFFLINE" : tape_state_verbose[tdev->tape_state]);
}
static
DEVICE_ATTR(state, 0444, tape_state_show, NULL);
static ssize_t
tape_operation_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct tape_device *tdev;
ssize_t rc;
tdev = dev_get_drvdata(dev);
if (tdev->first_minor < 0)
return scnprintf(buf, PAGE_SIZE, "N/A\n");
spin_lock_irq(get_ccwdev_lock(tdev->cdev));
if (list_empty(&tdev->req_queue))
rc = scnprintf(buf, PAGE_SIZE, "---\n");
else {
struct tape_request *req;
req = list_entry(tdev->req_queue.next, struct tape_request,
list);
rc = scnprintf(buf,PAGE_SIZE, "%s\n", tape_op_verbose[req->op]);
}
spin_unlock_irq(get_ccwdev_lock(tdev->cdev));
return rc;
}
static
DEVICE_ATTR(operation, 0444, tape_operation_show, NULL);
static ssize_t
tape_blocksize_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct tape_device *tdev;
tdev = dev_get_drvdata(dev);
return scnprintf(buf, PAGE_SIZE, "%i\n", tdev->char_data.block_size);
}
static
DEVICE_ATTR(blocksize, 0444, tape_blocksize_show, NULL);
static struct attribute *tape_attrs[] = {
&dev_attr_medium_state.attr,
&dev_attr_first_minor.attr,
&dev_attr_state.attr,
&dev_attr_operation.attr,
&dev_attr_blocksize.attr,
NULL
};
static struct attribute_group tape_attr_group = {
.attrs = tape_attrs,
};
/*
* Tape state functions
*/
void
tape_state_set(struct tape_device *device, enum tape_state newstate)
{
const char *str;
if (device->tape_state == TS_NOT_OPER) {
DBF_EVENT(3, "ts_set err: not oper\n");
return;
}
DBF_EVENT(4, "ts. dev: %x\n", device->first_minor);
DBF_EVENT(4, "old ts:\t\n");
if (device->tape_state < TS_SIZE && device->tape_state >=0 )
str = tape_state_verbose[device->tape_state];
else
str = "UNKNOWN TS";
DBF_EVENT(4, "%s\n", str);
DBF_EVENT(4, "new ts:\t\n");
if (newstate < TS_SIZE && newstate >= 0)
str = tape_state_verbose[newstate];
else
str = "UNKNOWN TS";
DBF_EVENT(4, "%s\n", str);
device->tape_state = newstate;
wake_up(&device->state_change_wq);
}
struct tape_med_state_work_data {
struct tape_device *device;
enum tape_medium_state state;
struct work_struct work;
};
static void
tape_med_state_work_handler(struct work_struct *work)
{
static char env_state_loaded[] = "MEDIUM_STATE=LOADED";
static char env_state_unloaded[] = "MEDIUM_STATE=UNLOADED";
struct tape_med_state_work_data *p =
container_of(work, struct tape_med_state_work_data, work);
struct tape_device *device = p->device;
char *envp[] = { NULL, NULL };
switch (p->state) {
case MS_UNLOADED:
pr_info("%s: The tape cartridge has been successfully "
"unloaded\n", dev_name(&device->cdev->dev));
envp[0] = env_state_unloaded;
kobject_uevent_env(&device->cdev->dev.kobj, KOBJ_CHANGE, envp);
break;
case MS_LOADED:
pr_info("%s: A tape cartridge has been mounted\n",
dev_name(&device->cdev->dev));
envp[0] = env_state_loaded;
kobject_uevent_env(&device->cdev->dev.kobj, KOBJ_CHANGE, envp);
break;
default:
break;
}
tape_put_device(device);
kfree(p);
}
static void
tape_med_state_work(struct tape_device *device, enum tape_medium_state state)
{
struct tape_med_state_work_data *p;
p = kzalloc(sizeof(*p), GFP_ATOMIC);
if (p) {
INIT_WORK(&p->work, tape_med_state_work_handler);
p->device = tape_get_device(device);
p->state = state;
schedule_work(&p->work);
}
}
void
tape_med_state_set(struct tape_device *device, enum tape_medium_state newstate)
{
enum tape_medium_state oldstate;
oldstate = device->medium_state;
if (oldstate == newstate)
return;
device->medium_state = newstate;
switch(newstate){
case MS_UNLOADED:
device->tape_generic_status |= GMT_DR_OPEN(~0);
if (oldstate == MS_LOADED)
tape_med_state_work(device, MS_UNLOADED);
break;
case MS_LOADED:
device->tape_generic_status &= ~GMT_DR_OPEN(~0);
if (oldstate == MS_UNLOADED)
tape_med_state_work(device, MS_LOADED);
break;
default:
break;
}
wake_up(&device->state_change_wq);
}
/*
* Stop running ccw. Has to be called with the device lock held.
*/
static int
__tape_cancel_io(struct tape_device *device, struct tape_request *request)
{
int retries;
int rc;
/* Check if interrupt has already been processed */
if (request->callback == NULL)
return 0;
rc = 0;
for (retries = 0; retries < 5; retries++) {
rc = ccw_device_clear(device->cdev, (long) request);
switch (rc) {
case 0:
request->status = TAPE_REQUEST_DONE;
return 0;
case -EBUSY:
request->status = TAPE_REQUEST_CANCEL;
schedule_delayed_work(&device->tape_dnr, 0);
return 0;
case -ENODEV:
DBF_EXCEPTION(2, "device gone, retry\n");
break;
case -EIO:
DBF_EXCEPTION(2, "I/O error, retry\n");
break;
default:
BUG();
}
}
return rc;
}
/*
* Add device into the sorted list, giving it the first
* available minor number.
*/
static int
tape_assign_minor(struct tape_device *device)
{
struct tape_device *tmp;
int minor;
minor = 0;
write_lock(&tape_device_lock);
list_for_each_entry(tmp, &tape_device_list, node) {
if (minor < tmp->first_minor)
break;
minor += TAPE_MINORS_PER_DEV;
}
if (minor >= 256) {
write_unlock(&tape_device_lock);
return -ENODEV;
}
device->first_minor = minor;
list_add_tail(&device->node, &tmp->node);
write_unlock(&tape_device_lock);
return 0;
}
/* remove device from the list */
static void
tape_remove_minor(struct tape_device *device)
{
write_lock(&tape_device_lock);
list_del_init(&device->node);
device->first_minor = -1;
write_unlock(&tape_device_lock);
}
/*
* Set a device online.
*
* This function is called by the common I/O layer to move a device from the
* detected but offline into the online state.
* If we return an error (RC < 0) the device remains in the offline state. This
* can happen if the device is assigned somewhere else, for example.
*/
int
tape_generic_online(struct tape_device *device,
struct tape_discipline *discipline)
{
int rc;
DBF_LH(6, "tape_enable_device(%p, %p)\n", device, discipline);
if (device->tape_state != TS_INIT) {
DBF_LH(3, "Tapestate not INIT (%d)\n", device->tape_state);
return -EINVAL;
}
init_timer(&device->lb_timeout);
device->lb_timeout.function = tape_long_busy_timeout;
/* Let the discipline have a go at the device. */
device->discipline = discipline;
if (!try_module_get(discipline->owner)) {
return -EINVAL;
}
rc = discipline->setup_device(device);
if (rc)
goto out;
rc = tape_assign_minor(device);
if (rc)
goto out_discipline;
rc = tapechar_setup_device(device);
if (rc)
goto out_minor;
rc = tapeblock_setup_device(device);
if (rc)
goto out_char;
tape_state_set(device, TS_UNUSED);
DBF_LH(3, "(%08x): Drive set online\n", device->cdev_id);
return 0;
out_char:
tapechar_cleanup_device(device);
out_minor:
tape_remove_minor(device);
out_discipline:
device->discipline->cleanup_device(device);
device->discipline = NULL;
out:
module_put(discipline->owner);
return rc;
}
static void
tape_cleanup_device(struct tape_device *device)
{
tapeblock_cleanup_device(device);
tapechar_cleanup_device(device);
device->discipline->cleanup_device(device);
module_put(device->discipline->owner);
tape_remove_minor(device);
tape_med_state_set(device, MS_UNKNOWN);
}
/*
* Suspend device.
*
* Called by the common I/O layer if the drive should be suspended on user
* request. We refuse to suspend if the device is loaded or in use for the
* following reason:
* While the Linux guest is suspended, it might be logged off which causes
* devices to be detached. Tape devices are automatically rewound and unloaded
* during DETACH processing (unless the tape device was attached with the
* NOASSIGN or MULTIUSER option). After rewind/unload, there is no way to
* resume the original state of the tape device, since we would need to
* manually re-load the cartridge which was active at suspend time.
*/
int tape_generic_pm_suspend(struct ccw_device *cdev)
{
struct tape_device *device;
device = dev_get_drvdata(&cdev->dev);
if (!device) {
return -ENODEV;
}
DBF_LH(3, "(%08x): tape_generic_pm_suspend(%p)\n",
device->cdev_id, device);
if (device->medium_state != MS_UNLOADED) {
pr_err("A cartridge is loaded in tape device %s, "
"refusing to suspend\n", dev_name(&cdev->dev));
return -EBUSY;
}
spin_lock_irq(get_ccwdev_lock(device->cdev));
switch (device->tape_state) {
case TS_INIT:
case TS_NOT_OPER:
case TS_UNUSED:
spin_unlock_irq(get_ccwdev_lock(device->cdev));
break;
default:
pr_err("Tape device %s is busy, refusing to "
"suspend\n", dev_name(&cdev->dev));
spin_unlock_irq(get_ccwdev_lock(device->cdev));
return -EBUSY;
}
DBF_LH(3, "(%08x): Drive suspended.\n", device->cdev_id);
return 0;
}
/*
* Set device offline.
*
* Called by the common I/O layer if the drive should set offline on user
* request. We may prevent this by returning an error.
* Manual offline is only allowed while the drive is not in use.
*/
int
tape_generic_offline(struct ccw_device *cdev)
{
struct tape_device *device;
device = dev_get_drvdata(&cdev->dev);
if (!device) {
return -ENODEV;
}
DBF_LH(3, "(%08x): tape_generic_offline(%p)\n",
device->cdev_id, device);
spin_lock_irq(get_ccwdev_lock(device->cdev));
switch (device->tape_state) {
case TS_INIT:
case TS_NOT_OPER:
spin_unlock_irq(get_ccwdev_lock(device->cdev));
break;
case TS_UNUSED:
tape_state_set(device, TS_INIT);
spin_unlock_irq(get_ccwdev_lock(device->cdev));
tape_cleanup_device(device);
break;
default:
DBF_EVENT(3, "(%08x): Set offline failed "
"- drive in use.\n",
device->cdev_id);
spin_unlock_irq(get_ccwdev_lock(device->cdev));
return -EBUSY;
}
DBF_LH(3, "(%08x): Drive set offline.\n", device->cdev_id);
return 0;
}
/*
* Allocate memory for a new device structure.
*/
static struct tape_device *
tape_alloc_device(void)
{
struct tape_device *device;
device = kzalloc(sizeof(struct tape_device), GFP_KERNEL);
if (device == NULL) {
DBF_EXCEPTION(2, "ti:no mem\n");
return ERR_PTR(-ENOMEM);
}
device->modeset_byte = kmalloc(1, GFP_KERNEL | GFP_DMA);
if (device->modeset_byte == NULL) {
DBF_EXCEPTION(2, "ti:no mem\n");
kfree(device);
return ERR_PTR(-ENOMEM);
}
mutex_init(&device->mutex);
INIT_LIST_HEAD(&device->req_queue);
INIT_LIST_HEAD(&device->node);
init_waitqueue_head(&device->state_change_wq);
init_waitqueue_head(&device->wait_queue);
device->tape_state = TS_INIT;
device->medium_state = MS_UNKNOWN;
*device->modeset_byte = 0;
device->first_minor = -1;
atomic_set(&device->ref_count, 1);
INIT_DELAYED_WORK(&device->tape_dnr, tape_delayed_next_request);
return device;
}
/*
* Get a reference to an existing device structure. This will automatically
* increment the reference count.
*/
struct tape_device *
tape_get_device(struct tape_device *device)
{
int count;
count = atomic_inc_return(&device->ref_count);
DBF_EVENT(4, "tape_get_device(%p) = %i\n", device, count);
return device;
}
/*
* Decrease the reference counter of a devices structure. If the
* reference counter reaches zero free the device structure.
* The function returns a NULL pointer to be used by the caller
* for clearing reference pointers.
*/
void
tape_put_device(struct tape_device *device)
{
int count;
count = atomic_dec_return(&device->ref_count);
DBF_EVENT(4, "tape_put_device(%p) -> %i\n", device, count);
BUG_ON(count < 0);
if (count == 0) {
kfree(device->modeset_byte);
kfree(device);
}
}
/*
* Find tape device by a device index.
*/
struct tape_device *
tape_find_device(int devindex)
{
struct tape_device *device, *tmp;
device = ERR_PTR(-ENODEV);
read_lock(&tape_device_lock);
list_for_each_entry(tmp, &tape_device_list, node) {
if (tmp->first_minor / TAPE_MINORS_PER_DEV == devindex) {
device = tape_get_device(tmp);
break;
}
}
read_unlock(&tape_device_lock);
return device;
}
/*
* Driverfs tape probe function.
*/
int
tape_generic_probe(struct ccw_device *cdev)
{
struct tape_device *device;
int ret;
struct ccw_dev_id dev_id;
device = tape_alloc_device();
if (IS_ERR(device))
return -ENODEV;
ccw_device_set_options(cdev, CCWDEV_DO_PATHGROUP |
CCWDEV_DO_MULTIPATH);
ret = sysfs_create_group(&cdev->dev.kobj, &tape_attr_group);
if (ret) {
tape_put_device(device);
return ret;
}
dev_set_drvdata(&cdev->dev, device);
cdev->handler = __tape_do_irq;
device->cdev = cdev;
ccw_device_get_id(cdev, &dev_id);
device->cdev_id = devid_to_int(&dev_id);
return ret;
}
static void
__tape_discard_requests(struct tape_device *device)
{
struct tape_request * request;
struct list_head * l, *n;
list_for_each_safe(l, n, &device->req_queue) {
request = list_entry(l, struct tape_request, list);
if (request->status == TAPE_REQUEST_IN_IO)
request->status = TAPE_REQUEST_DONE;
list_del(&request->list);
/* Decrease ref_count for removed request. */
request->device = NULL;
tape_put_device(device);
request->rc = -EIO;
if (request->callback != NULL)
request->callback(request, request->callback_data);
}
}
/*
* Driverfs tape remove function.
*
* This function is called whenever the common I/O layer detects the device
* gone. This can happen at any time and we cannot refuse.
*/
void
tape_generic_remove(struct ccw_device *cdev)
{
struct tape_device * device;
device = dev_get_drvdata(&cdev->dev);
if (!device) {
return;
}
DBF_LH(3, "(%08x): tape_generic_remove(%p)\n", device->cdev_id, cdev);
spin_lock_irq(get_ccwdev_lock(device->cdev));
switch (device->tape_state) {
case TS_INIT:
tape_state_set(device, TS_NOT_OPER);
case TS_NOT_OPER:
/*
* Nothing to do.
*/
spin_unlock_irq(get_ccwdev_lock(device->cdev));
break;
case TS_UNUSED:
/*
* Need only to release the device.
*/
tape_state_set(device, TS_NOT_OPER);
spin_unlock_irq(get_ccwdev_lock(device->cdev));
tape_cleanup_device(device);
break;
default:
/*
* There may be requests on the queue. We will not get
* an interrupt for a request that was running. So we
* just post them all as I/O errors.
*/
DBF_EVENT(3, "(%08x): Drive in use vanished!\n",
device->cdev_id);
pr_warning("%s: A tape unit was detached while in "
"use\n", dev_name(&device->cdev->dev));
tape_state_set(device, TS_NOT_OPER);
__tape_discard_requests(device);
spin_unlock_irq(get_ccwdev_lock(device->cdev));
tape_cleanup_device(device);
}
device = dev_get_drvdata(&cdev->dev);
if (device) {
sysfs_remove_group(&cdev->dev.kobj, &tape_attr_group);
dev_set_drvdata(&cdev->dev, NULL);
tape_put_device(device);
}
}
/*
* Allocate a new tape ccw request
*/
struct tape_request *
tape_alloc_request(int cplength, int datasize)
{
struct tape_request *request;
BUG_ON(datasize > PAGE_SIZE || (cplength*sizeof(struct ccw1)) > PAGE_SIZE);
DBF_LH(6, "tape_alloc_request(%d, %d)\n", cplength, datasize);
request = kzalloc(sizeof(struct tape_request), GFP_KERNEL);
if (request == NULL) {
DBF_EXCEPTION(1, "cqra nomem\n");
return ERR_PTR(-ENOMEM);
}
/* allocate channel program */
if (cplength > 0) {
request->cpaddr = kcalloc(cplength, sizeof(struct ccw1),
GFP_ATOMIC | GFP_DMA);
if (request->cpaddr == NULL) {
DBF_EXCEPTION(1, "cqra nomem\n");
kfree(request);
return ERR_PTR(-ENOMEM);
}
}
/* alloc small kernel buffer */
if (datasize > 0) {
request->cpdata = kzalloc(datasize, GFP_KERNEL | GFP_DMA);
if (request->cpdata == NULL) {
DBF_EXCEPTION(1, "cqra nomem\n");
kfree(request->cpaddr);
kfree(request);
return ERR_PTR(-ENOMEM);
}
}
DBF_LH(6, "New request %p(%p/%p)\n", request, request->cpaddr,
request->cpdata);
return request;
}
/*
* Free tape ccw request
*/
void
tape_free_request (struct tape_request * request)
{
DBF_LH(6, "Free request %p\n", request);
if (request->device)
tape_put_device(request->device);
kfree(request->cpdata);
kfree(request->cpaddr);
kfree(request);
}
static int
__tape_start_io(struct tape_device *device, struct tape_request *request)
{
int rc;
#ifdef CONFIG_S390_TAPE_BLOCK
if (request->op == TO_BLOCK)
device->discipline->check_locate(device, request);
#endif
rc = ccw_device_start(
device->cdev,
request->cpaddr,
(unsigned long) request,
0x00,
request->options
);
if (rc == 0) {
request->status = TAPE_REQUEST_IN_IO;
} else if (rc == -EBUSY) {
/* The common I/O subsystem is currently busy. Retry later. */
request->status = TAPE_REQUEST_QUEUED;
schedule_delayed_work(&device->tape_dnr, 0);
rc = 0;
} else {
/* Start failed. Remove request and indicate failure. */
DBF_EVENT(1, "tape: start request failed with RC = %i\n", rc);
}
return rc;
}
static void
__tape_start_next_request(struct tape_device *device)
{
struct list_head *l, *n;
struct tape_request *request;
int rc;
DBF_LH(6, "__tape_start_next_request(%p)\n", device);
/*
* Try to start each request on request queue until one is
* started successful.
*/
list_for_each_safe(l, n, &device->req_queue) {
request = list_entry(l, struct tape_request, list);
/*
* Avoid race condition if bottom-half was triggered more than
* once.
*/
if (request->status == TAPE_REQUEST_IN_IO)
return;
/*
* Request has already been stopped. We have to wait until
* the request is removed from the queue in the interrupt
* handling.
*/
if (request->status == TAPE_REQUEST_DONE)
return;
/*
* We wanted to cancel the request but the common I/O layer
* was busy at that time. This can only happen if this
* function is called by delayed_next_request.
* Otherwise we start the next request on the queue.
*/
if (request->status == TAPE_REQUEST_CANCEL) {
rc = __tape_cancel_io(device, request);
} else {
rc = __tape_start_io(device, request);
}
if (rc == 0)
return;
/* Set ending status. */
request->rc = rc;
request->status = TAPE_REQUEST_DONE;
/* Remove from request queue. */
list_del(&request->list);
/* Do callback. */
if (request->callback != NULL)
request->callback(request, request->callback_data);
}
}
static void
tape_delayed_next_request(struct work_struct *work)
{
struct tape_device *device =
container_of(work, struct tape_device, tape_dnr.work);
DBF_LH(6, "tape_delayed_next_request(%p)\n", device);
spin_lock_irq(get_ccwdev_lock(device->cdev));
__tape_start_next_request(device);
spin_unlock_irq(get_ccwdev_lock(device->cdev));
}
static void tape_long_busy_timeout(unsigned long data)
{
struct tape_request *request;
struct tape_device *device;
device = (struct tape_device *) data;
spin_lock_irq(get_ccwdev_lock(device->cdev));
request = list_entry(device->req_queue.next, struct tape_request, list);
BUG_ON(request->status != TAPE_REQUEST_LONG_BUSY);
DBF_LH(6, "%08x: Long busy timeout.\n", device->cdev_id);
__tape_start_next_request(device);
device->lb_timeout.data = 0UL;
tape_put_device(device);
spin_unlock_irq(get_ccwdev_lock(device->cdev));
}
static void
__tape_end_request(
struct tape_device * device,
struct tape_request * request,
int rc)
{
DBF_LH(6, "__tape_end_request(%p, %p, %i)\n", device, request, rc);
if (request) {
request->rc = rc;
request->status = TAPE_REQUEST_DONE;
/* Remove from request queue. */
list_del(&request->list);
/* Do callback. */
if (request->callback != NULL)
request->callback(request, request->callback_data);
}
/* Start next request. */
if (!list_empty(&device->req_queue))
__tape_start_next_request(device);
}
/*
* Write sense data to dbf
*/
void
tape_dump_sense_dbf(struct tape_device *device, struct tape_request *request,
struct irb *irb)
{
unsigned int *sptr;
const char* op;
if (request != NULL)
op = tape_op_verbose[request->op];
else
op = "---";
DBF_EVENT(3, "DSTAT : %02x CSTAT: %02x\n",
irb->scsw.cmd.dstat, irb->scsw.cmd.cstat);
DBF_EVENT(3, "DEVICE: %08x OP\t: %s\n", device->cdev_id, op);
sptr = (unsigned int *) irb->ecw;
DBF_EVENT(3, "%08x %08x\n", sptr[0], sptr[1]);
DBF_EVENT(3, "%08x %08x\n", sptr[2], sptr[3]);
DBF_EVENT(3, "%08x %08x\n", sptr[4], sptr[5]);
DBF_EVENT(3, "%08x %08x\n", sptr[6], sptr[7]);
}
/*
* I/O helper function. Adds the request to the request queue
* and starts it if the tape is idle. Has to be called with
* the device lock held.
*/
static int
__tape_start_request(struct tape_device *device, struct tape_request *request)
{
int rc;
switch (request->op) {
case TO_MSEN:
case TO_ASSIGN:
case TO_UNASSIGN:
case TO_READ_ATTMSG:
case TO_RDC:
if (device->tape_state == TS_INIT)
break;
if (device->tape_state == TS_UNUSED)
break;
default:
if (device->tape_state == TS_BLKUSE)
break;
if (device->tape_state != TS_IN_USE)
return -ENODEV;
}
/* Increase use count of device for the added request. */
request->device = tape_get_device(device);
if (list_empty(&device->req_queue)) {
/* No other requests are on the queue. Start this one. */
rc = __tape_start_io(device, request);
if (rc)
return rc;
DBF_LH(5, "Request %p added for execution.\n", request);
list_add(&request->list, &device->req_queue);
} else {
DBF_LH(5, "Request %p add to queue.\n", request);
request->status = TAPE_REQUEST_QUEUED;
list_add_tail(&request->list, &device->req_queue);
}
return 0;
}
/*
* Add the request to the request queue, try to start it if the
* tape is idle. Return without waiting for end of i/o.
*/
int
tape_do_io_async(struct tape_device *device, struct tape_request *request)
{
int rc;
DBF_LH(6, "tape_do_io_async(%p, %p)\n", device, request);
spin_lock_irq(get_ccwdev_lock(device->cdev));
/* Add request to request queue and try to start it. */
rc = __tape_start_request(device, request);
spin_unlock_irq(get_ccwdev_lock(device->cdev));
return rc;
}
/*
* tape_do_io/__tape_wake_up
* Add the request to the request queue, try to start it if the
* tape is idle and wait uninterruptible for its completion.
*/
static void
__tape_wake_up(struct tape_request *request, void *data)
{
request->callback = NULL;
wake_up((wait_queue_head_t *) data);
}
int
tape_do_io(struct tape_device *device, struct tape_request *request)
{
int rc;
spin_lock_irq(get_ccwdev_lock(device->cdev));
/* Setup callback */
request->callback = __tape_wake_up;
request->callback_data = &device->wait_queue;
/* Add request to request queue and try to start it. */
rc = __tape_start_request(device, request);
spin_unlock_irq(get_ccwdev_lock(device->cdev));
if (rc)
return rc;
/* Request added to the queue. Wait for its completion. */
wait_event(device->wait_queue, (request->callback == NULL));
/* Get rc from request */
return request->rc;
}
/*
* tape_do_io_interruptible/__tape_wake_up_interruptible
* Add the request to the request queue, try to start it if the
* tape is idle and wait uninterruptible for its completion.
*/
static void
__tape_wake_up_interruptible(struct tape_request *request, void *data)
{
request->callback = NULL;
wake_up_interruptible((wait_queue_head_t *) data);
}
int
tape_do_io_interruptible(struct tape_device *device,
struct tape_request *request)
{
int rc;
spin_lock_irq(get_ccwdev_lock(device->cdev));
/* Setup callback */
request->callback = __tape_wake_up_interruptible;
request->callback_data = &device->wait_queue;
rc = __tape_start_request(device, request);
spin_unlock_irq(get_ccwdev_lock(device->cdev));
if (rc)
return rc;
/* Request added to the queue. Wait for its completion. */
rc = wait_event_interruptible(device->wait_queue,
(request->callback == NULL));
if (rc != -ERESTARTSYS)
/* Request finished normally. */
return request->rc;
/* Interrupted by a signal. We have to stop the current request. */
spin_lock_irq(get_ccwdev_lock(device->cdev));
rc = __tape_cancel_io(device, request);
spin_unlock_irq(get_ccwdev_lock(device->cdev));
if (rc == 0) {
/* Wait for the interrupt that acknowledges the halt. */
do {
rc = wait_event_interruptible(
device->wait_queue,
(request->callback == NULL)
);
} while (rc == -ERESTARTSYS);
DBF_EVENT(3, "IO stopped on %08x\n", device->cdev_id);
rc = -ERESTARTSYS;
}
return rc;
}
/*
* Stop running ccw.
*/
int
tape_cancel_io(struct tape_device *device, struct tape_request *request)
{
int rc;
spin_lock_irq(get_ccwdev_lock(device->cdev));
rc = __tape_cancel_io(device, request);
spin_unlock_irq(get_ccwdev_lock(device->cdev));
return rc;
}
/*
* Tape interrupt routine, called from the ccw_device layer
*/
static void
__tape_do_irq (struct ccw_device *cdev, unsigned long intparm, struct irb *irb)
{
struct tape_device *device;
struct tape_request *request;
int rc;
device = dev_get_drvdata(&cdev->dev);
if (device == NULL) {
return;
}
request = (struct tape_request *) intparm;
DBF_LH(6, "__tape_do_irq(device=%p, request=%p)\n", device, request);
/* On special conditions irb is an error pointer */
if (IS_ERR(irb)) {
/* FIXME: What to do with the request? */
switch (PTR_ERR(irb)) {
case -ETIMEDOUT:
DBF_LH(1, "(%08x): Request timed out\n",
device->cdev_id);
case -EIO:
__tape_end_request(device, request, -EIO);
break;
default:
DBF_LH(1, "(%08x): Unexpected i/o error %li\n",
device->cdev_id, PTR_ERR(irb));
}
return;
}
/*
* If the condition code is not zero and the start function bit is
* still set, this is an deferred error and the last start I/O did
* not succeed. At this point the condition that caused the deferred
* error might still apply. So we just schedule the request to be
* started later.
*/
if (irb->scsw.cmd.cc != 0 &&
(irb->scsw.cmd.fctl & SCSW_FCTL_START_FUNC) &&
(request->status == TAPE_REQUEST_IN_IO)) {
DBF_EVENT(3,"(%08x): deferred cc=%i, fctl=%i. restarting\n",
device->cdev_id, irb->scsw.cmd.cc, irb->scsw.cmd.fctl);
request->status = TAPE_REQUEST_QUEUED;
schedule_delayed_work(&device->tape_dnr, HZ);
return;
}
/* May be an unsolicited irq */
if(request != NULL)
request->rescnt = irb->scsw.cmd.count;
else if ((irb->scsw.cmd.dstat == 0x85 || irb->scsw.cmd.dstat == 0x80) &&
!list_empty(&device->req_queue)) {
/* Not Ready to Ready after long busy ? */
struct tape_request *req;
req = list_entry(device->req_queue.next,
struct tape_request, list);
if (req->status == TAPE_REQUEST_LONG_BUSY) {
DBF_EVENT(3, "(%08x): del timer\n", device->cdev_id);
if (del_timer(&device->lb_timeout)) {
device->lb_timeout.data = 0UL;
tape_put_device(device);
__tape_start_next_request(device);
}
return;
}
}
if (irb->scsw.cmd.dstat != 0x0c) {
/* Set the 'ONLINE' flag depending on sense byte 1 */
if(*(((__u8 *) irb->ecw) + 1) & SENSE_DRIVE_ONLINE)
device->tape_generic_status |= GMT_ONLINE(~0);
else
device->tape_generic_status &= ~GMT_ONLINE(~0);
/*
* Any request that does not come back with channel end
* and device end is unusual. Log the sense data.
*/
DBF_EVENT(3,"-- Tape Interrupthandler --\n");
tape_dump_sense_dbf(device, request, irb);
} else {
/* Upon normal completion the device _is_ online */
device->tape_generic_status |= GMT_ONLINE(~0);
}
if (device->tape_state == TS_NOT_OPER) {
DBF_EVENT(6, "tape:device is not operational\n");
return;
}
/*
* Request that were canceled still come back with an interrupt.
* To detect these request the state will be set to TAPE_REQUEST_DONE.
*/
if(request != NULL && request->status == TAPE_REQUEST_DONE) {
__tape_end_request(device, request, -EIO);
return;
}
rc = device->discipline->irq(device, request, irb);
/*
* rc < 0 : request finished unsuccessfully.
* rc == TAPE_IO_SUCCESS: request finished successfully.
* rc == TAPE_IO_PENDING: request is still running. Ignore rc.
* rc == TAPE_IO_RETRY: request finished but needs another go.
* rc == TAPE_IO_STOP: request needs to get terminated.
*/
switch (rc) {
case TAPE_IO_SUCCESS:
/* Upon normal completion the device _is_ online */
device->tape_generic_status |= GMT_ONLINE(~0);
__tape_end_request(device, request, rc);
break;
case TAPE_IO_PENDING:
break;
case TAPE_IO_LONG_BUSY:
device->lb_timeout.data =
(unsigned long) tape_get_device(device);
device->lb_timeout.expires = jiffies +
LONG_BUSY_TIMEOUT * HZ;
DBF_EVENT(3, "(%08x): add timer\n", device->cdev_id);
add_timer(&device->lb_timeout);
request->status = TAPE_REQUEST_LONG_BUSY;
break;
case TAPE_IO_RETRY:
rc = __tape_start_io(device, request);
if (rc)
__tape_end_request(device, request, rc);
break;
case TAPE_IO_STOP:
rc = __tape_cancel_io(device, request);
if (rc)
__tape_end_request(device, request, rc);
break;
default:
if (rc > 0) {
DBF_EVENT(6, "xunknownrc\n");
__tape_end_request(device, request, -EIO);
} else {
__tape_end_request(device, request, rc);
}
break;
}
}
/*
* Tape device open function used by tape_char & tape_block frontends.
*/
int
tape_open(struct tape_device *device)
{
int rc;
spin_lock_irq(get_ccwdev_lock(device->cdev));
if (device->tape_state == TS_NOT_OPER) {
DBF_EVENT(6, "TAPE:nodev\n");
rc = -ENODEV;
} else if (device->tape_state == TS_IN_USE) {
DBF_EVENT(6, "TAPE:dbusy\n");
rc = -EBUSY;
} else if (device->tape_state == TS_BLKUSE) {
DBF_EVENT(6, "TAPE:dbusy\n");
rc = -EBUSY;
} else if (device->discipline != NULL &&
!try_module_get(device->discipline->owner)) {
DBF_EVENT(6, "TAPE:nodisc\n");
rc = -ENODEV;
} else {
tape_state_set(device, TS_IN_USE);
rc = 0;
}
spin_unlock_irq(get_ccwdev_lock(device->cdev));
return rc;
}
/*
* Tape device release function used by tape_char & tape_block frontends.
*/
int
tape_release(struct tape_device *device)
{
spin_lock_irq(get_ccwdev_lock(device->cdev));
if (device->tape_state == TS_IN_USE)
tape_state_set(device, TS_UNUSED);
module_put(device->discipline->owner);
spin_unlock_irq(get_ccwdev_lock(device->cdev));
return 0;
}
/*
* Execute a magnetic tape command a number of times.
*/
int
tape_mtop(struct tape_device *device, int mt_op, int mt_count)
{
tape_mtop_fn fn;
int rc;
DBF_EVENT(6, "TAPE:mtio\n");
DBF_EVENT(6, "TAPE:ioop: %x\n", mt_op);
DBF_EVENT(6, "TAPE:arg: %x\n", mt_count);
if (mt_op < 0 || mt_op >= TAPE_NR_MTOPS)
return -EINVAL;
fn = device->discipline->mtop_array[mt_op];
if (fn == NULL)
return -EINVAL;
/* We assume that the backends can handle count up to 500. */
if (mt_op == MTBSR || mt_op == MTFSR || mt_op == MTFSF ||
mt_op == MTBSF || mt_op == MTFSFM || mt_op == MTBSFM) {
rc = 0;
for (; mt_count > 500; mt_count -= 500)
if ((rc = fn(device, 500)) != 0)
break;
if (rc == 0)
rc = fn(device, mt_count);
} else
rc = fn(device, mt_count);
return rc;
}
/*
* Tape init function.
*/
static int
tape_init (void)
{
TAPE_DBF_AREA = debug_register ( "tape", 2, 2, 4*sizeof(long));
debug_register_view(TAPE_DBF_AREA, &debug_sprintf_view);
#ifdef DBF_LIKE_HELL
debug_set_level(TAPE_DBF_AREA, 6);
#endif
DBF_EVENT(3, "tape init\n");
tape_proc_init();
tapechar_init ();
tapeblock_init ();
return 0;
}
/*
* Tape exit function.
*/
static void
tape_exit(void)
{
DBF_EVENT(6, "tape exit\n");
/* Get rid of the frontends */
tapechar_exit();
tapeblock_exit();
tape_proc_cleanup();
debug_unregister (TAPE_DBF_AREA);
}
MODULE_AUTHOR("(C) 2001 IBM Deutschland Entwicklung GmbH by Carsten Otte and "
"Michael Holzheu (cotte@de.ibm.com,holzheu@de.ibm.com)");
MODULE_DESCRIPTION("Linux on zSeries channel attached tape device driver");
MODULE_LICENSE("GPL");
module_init(tape_init);
module_exit(tape_exit);
EXPORT_SYMBOL(tape_generic_remove);
EXPORT_SYMBOL(tape_generic_probe);
EXPORT_SYMBOL(tape_generic_online);
EXPORT_SYMBOL(tape_generic_offline);
EXPORT_SYMBOL(tape_generic_pm_suspend);
EXPORT_SYMBOL(tape_put_device);
EXPORT_SYMBOL(tape_get_device);
EXPORT_SYMBOL(tape_state_verbose);
EXPORT_SYMBOL(tape_op_verbose);
EXPORT_SYMBOL(tape_state_set);
EXPORT_SYMBOL(tape_med_state_set);
EXPORT_SYMBOL(tape_alloc_request);
EXPORT_SYMBOL(tape_free_request);
EXPORT_SYMBOL(tape_dump_sense_dbf);
EXPORT_SYMBOL(tape_do_io);
EXPORT_SYMBOL(tape_do_io_async);
EXPORT_SYMBOL(tape_do_io_interruptible);
EXPORT_SYMBOL(tape_cancel_io);
EXPORT_SYMBOL(tape_mtop);
| gpl-2.0 |
okeer/android_kernel_semc_msm7x30 | drivers/s390/char/tape_core.c | 5110 | 35668 | /*
* drivers/s390/char/tape_core.c
* basic function of the tape device driver
*
* S390 and zSeries version
* Copyright IBM Corp. 2001, 2009
* Author(s): Carsten Otte <cotte@de.ibm.com>
* Michael Holzheu <holzheu@de.ibm.com>
* Tuan Ngo-Anh <ngoanh@de.ibm.com>
* Martin Schwidefsky <schwidefsky@de.ibm.com>
* Stefan Bader <shbader@de.ibm.com>
*/
#define KMSG_COMPONENT "tape"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/module.h>
#include <linux/init.h> // for kernel parameters
#include <linux/kmod.h> // for requesting modules
#include <linux/spinlock.h> // for locks
#include <linux/vmalloc.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <asm/types.h> // for variable types
#define TAPE_DBF_AREA tape_core_dbf
#include "tape.h"
#include "tape_std.h"
#define LONG_BUSY_TIMEOUT 180 /* seconds */
static void __tape_do_irq (struct ccw_device *, unsigned long, struct irb *);
static void tape_delayed_next_request(struct work_struct *);
static void tape_long_busy_timeout(unsigned long data);
/*
* One list to contain all tape devices of all disciplines, so
* we can assign the devices to minor numbers of the same major
* The list is protected by the rwlock
*/
static LIST_HEAD(tape_device_list);
static DEFINE_RWLOCK(tape_device_lock);
/*
* Pointer to debug area.
*/
debug_info_t *TAPE_DBF_AREA = NULL;
EXPORT_SYMBOL(TAPE_DBF_AREA);
/*
* Printable strings for tape enumerations.
*/
const char *tape_state_verbose[TS_SIZE] =
{
[TS_UNUSED] = "UNUSED",
[TS_IN_USE] = "IN_USE",
[TS_BLKUSE] = "BLKUSE",
[TS_INIT] = "INIT ",
[TS_NOT_OPER] = "NOT_OP"
};
const char *tape_op_verbose[TO_SIZE] =
{
[TO_BLOCK] = "BLK", [TO_BSB] = "BSB",
[TO_BSF] = "BSF", [TO_DSE] = "DSE",
[TO_FSB] = "FSB", [TO_FSF] = "FSF",
[TO_LBL] = "LBL", [TO_NOP] = "NOP",
[TO_RBA] = "RBA", [TO_RBI] = "RBI",
[TO_RFO] = "RFO", [TO_REW] = "REW",
[TO_RUN] = "RUN", [TO_WRI] = "WRI",
[TO_WTM] = "WTM", [TO_MSEN] = "MSN",
[TO_LOAD] = "LOA", [TO_READ_CONFIG] = "RCF",
[TO_READ_ATTMSG] = "RAT",
[TO_DIS] = "DIS", [TO_ASSIGN] = "ASS",
[TO_UNASSIGN] = "UAS", [TO_CRYPT_ON] = "CON",
[TO_CRYPT_OFF] = "COF", [TO_KEKL_SET] = "KLS",
[TO_KEKL_QUERY] = "KLQ",[TO_RDC] = "RDC",
};
static int devid_to_int(struct ccw_dev_id *dev_id)
{
return dev_id->devno + (dev_id->ssid << 16);
}
/*
* Some channel attached tape specific attributes.
*
* FIXME: In the future the first_minor and blocksize attribute should be
* replaced by a link to the cdev tree.
*/
static ssize_t
tape_medium_state_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct tape_device *tdev;
tdev = dev_get_drvdata(dev);
return scnprintf(buf, PAGE_SIZE, "%i\n", tdev->medium_state);
}
static
DEVICE_ATTR(medium_state, 0444, tape_medium_state_show, NULL);
static ssize_t
tape_first_minor_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct tape_device *tdev;
tdev = dev_get_drvdata(dev);
return scnprintf(buf, PAGE_SIZE, "%i\n", tdev->first_minor);
}
static
DEVICE_ATTR(first_minor, 0444, tape_first_minor_show, NULL);
static ssize_t
tape_state_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct tape_device *tdev;
tdev = dev_get_drvdata(dev);
return scnprintf(buf, PAGE_SIZE, "%s\n", (tdev->first_minor < 0) ?
"OFFLINE" : tape_state_verbose[tdev->tape_state]);
}
static
DEVICE_ATTR(state, 0444, tape_state_show, NULL);
static ssize_t
tape_operation_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct tape_device *tdev;
ssize_t rc;
tdev = dev_get_drvdata(dev);
if (tdev->first_minor < 0)
return scnprintf(buf, PAGE_SIZE, "N/A\n");
spin_lock_irq(get_ccwdev_lock(tdev->cdev));
if (list_empty(&tdev->req_queue))
rc = scnprintf(buf, PAGE_SIZE, "---\n");
else {
struct tape_request *req;
req = list_entry(tdev->req_queue.next, struct tape_request,
list);
rc = scnprintf(buf,PAGE_SIZE, "%s\n", tape_op_verbose[req->op]);
}
spin_unlock_irq(get_ccwdev_lock(tdev->cdev));
return rc;
}
static
DEVICE_ATTR(operation, 0444, tape_operation_show, NULL);
static ssize_t
tape_blocksize_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct tape_device *tdev;
tdev = dev_get_drvdata(dev);
return scnprintf(buf, PAGE_SIZE, "%i\n", tdev->char_data.block_size);
}
static
DEVICE_ATTR(blocksize, 0444, tape_blocksize_show, NULL);
static struct attribute *tape_attrs[] = {
&dev_attr_medium_state.attr,
&dev_attr_first_minor.attr,
&dev_attr_state.attr,
&dev_attr_operation.attr,
&dev_attr_blocksize.attr,
NULL
};
static struct attribute_group tape_attr_group = {
.attrs = tape_attrs,
};
/*
* Tape state functions
*/
void
tape_state_set(struct tape_device *device, enum tape_state newstate)
{
const char *str;
if (device->tape_state == TS_NOT_OPER) {
DBF_EVENT(3, "ts_set err: not oper\n");
return;
}
DBF_EVENT(4, "ts. dev: %x\n", device->first_minor);
DBF_EVENT(4, "old ts:\t\n");
if (device->tape_state < TS_SIZE && device->tape_state >=0 )
str = tape_state_verbose[device->tape_state];
else
str = "UNKNOWN TS";
DBF_EVENT(4, "%s\n", str);
DBF_EVENT(4, "new ts:\t\n");
if (newstate < TS_SIZE && newstate >= 0)
str = tape_state_verbose[newstate];
else
str = "UNKNOWN TS";
DBF_EVENT(4, "%s\n", str);
device->tape_state = newstate;
wake_up(&device->state_change_wq);
}
struct tape_med_state_work_data {
struct tape_device *device;
enum tape_medium_state state;
struct work_struct work;
};
static void
tape_med_state_work_handler(struct work_struct *work)
{
static char env_state_loaded[] = "MEDIUM_STATE=LOADED";
static char env_state_unloaded[] = "MEDIUM_STATE=UNLOADED";
struct tape_med_state_work_data *p =
container_of(work, struct tape_med_state_work_data, work);
struct tape_device *device = p->device;
char *envp[] = { NULL, NULL };
switch (p->state) {
case MS_UNLOADED:
pr_info("%s: The tape cartridge has been successfully "
"unloaded\n", dev_name(&device->cdev->dev));
envp[0] = env_state_unloaded;
kobject_uevent_env(&device->cdev->dev.kobj, KOBJ_CHANGE, envp);
break;
case MS_LOADED:
pr_info("%s: A tape cartridge has been mounted\n",
dev_name(&device->cdev->dev));
envp[0] = env_state_loaded;
kobject_uevent_env(&device->cdev->dev.kobj, KOBJ_CHANGE, envp);
break;
default:
break;
}
tape_put_device(device);
kfree(p);
}
static void
tape_med_state_work(struct tape_device *device, enum tape_medium_state state)
{
struct tape_med_state_work_data *p;
p = kzalloc(sizeof(*p), GFP_ATOMIC);
if (p) {
INIT_WORK(&p->work, tape_med_state_work_handler);
p->device = tape_get_device(device);
p->state = state;
schedule_work(&p->work);
}
}
void
tape_med_state_set(struct tape_device *device, enum tape_medium_state newstate)
{
enum tape_medium_state oldstate;
oldstate = device->medium_state;
if (oldstate == newstate)
return;
device->medium_state = newstate;
switch(newstate){
case MS_UNLOADED:
device->tape_generic_status |= GMT_DR_OPEN(~0);
if (oldstate == MS_LOADED)
tape_med_state_work(device, MS_UNLOADED);
break;
case MS_LOADED:
device->tape_generic_status &= ~GMT_DR_OPEN(~0);
if (oldstate == MS_UNLOADED)
tape_med_state_work(device, MS_LOADED);
break;
default:
break;
}
wake_up(&device->state_change_wq);
}
/*
* Stop running ccw. Has to be called with the device lock held.
*/
static int
__tape_cancel_io(struct tape_device *device, struct tape_request *request)
{
int retries;
int rc;
/* Check if interrupt has already been processed */
if (request->callback == NULL)
return 0;
rc = 0;
for (retries = 0; retries < 5; retries++) {
rc = ccw_device_clear(device->cdev, (long) request);
switch (rc) {
case 0:
request->status = TAPE_REQUEST_DONE;
return 0;
case -EBUSY:
request->status = TAPE_REQUEST_CANCEL;
schedule_delayed_work(&device->tape_dnr, 0);
return 0;
case -ENODEV:
DBF_EXCEPTION(2, "device gone, retry\n");
break;
case -EIO:
DBF_EXCEPTION(2, "I/O error, retry\n");
break;
default:
BUG();
}
}
return rc;
}
/*
* Add device into the sorted list, giving it the first
* available minor number.
*/
static int
tape_assign_minor(struct tape_device *device)
{
struct tape_device *tmp;
int minor;
minor = 0;
write_lock(&tape_device_lock);
list_for_each_entry(tmp, &tape_device_list, node) {
if (minor < tmp->first_minor)
break;
minor += TAPE_MINORS_PER_DEV;
}
if (minor >= 256) {
write_unlock(&tape_device_lock);
return -ENODEV;
}
device->first_minor = minor;
list_add_tail(&device->node, &tmp->node);
write_unlock(&tape_device_lock);
return 0;
}
/* remove device from the list */
static void
tape_remove_minor(struct tape_device *device)
{
write_lock(&tape_device_lock);
list_del_init(&device->node);
device->first_minor = -1;
write_unlock(&tape_device_lock);
}
/*
* Set a device online.
*
* This function is called by the common I/O layer to move a device from the
* detected but offline into the online state.
* If we return an error (RC < 0) the device remains in the offline state. This
* can happen if the device is assigned somewhere else, for example.
*/
int
tape_generic_online(struct tape_device *device,
struct tape_discipline *discipline)
{
int rc;
DBF_LH(6, "tape_enable_device(%p, %p)\n", device, discipline);
if (device->tape_state != TS_INIT) {
DBF_LH(3, "Tapestate not INIT (%d)\n", device->tape_state);
return -EINVAL;
}
init_timer(&device->lb_timeout);
device->lb_timeout.function = tape_long_busy_timeout;
/* Let the discipline have a go at the device. */
device->discipline = discipline;
if (!try_module_get(discipline->owner)) {
return -EINVAL;
}
rc = discipline->setup_device(device);
if (rc)
goto out;
rc = tape_assign_minor(device);
if (rc)
goto out_discipline;
rc = tapechar_setup_device(device);
if (rc)
goto out_minor;
rc = tapeblock_setup_device(device);
if (rc)
goto out_char;
tape_state_set(device, TS_UNUSED);
DBF_LH(3, "(%08x): Drive set online\n", device->cdev_id);
return 0;
out_char:
tapechar_cleanup_device(device);
out_minor:
tape_remove_minor(device);
out_discipline:
device->discipline->cleanup_device(device);
device->discipline = NULL;
out:
module_put(discipline->owner);
return rc;
}
static void
tape_cleanup_device(struct tape_device *device)
{
tapeblock_cleanup_device(device);
tapechar_cleanup_device(device);
device->discipline->cleanup_device(device);
module_put(device->discipline->owner);
tape_remove_minor(device);
tape_med_state_set(device, MS_UNKNOWN);
}
/*
* Suspend device.
*
* Called by the common I/O layer if the drive should be suspended on user
* request. We refuse to suspend if the device is loaded or in use for the
* following reason:
* While the Linux guest is suspended, it might be logged off which causes
* devices to be detached. Tape devices are automatically rewound and unloaded
* during DETACH processing (unless the tape device was attached with the
* NOASSIGN or MULTIUSER option). After rewind/unload, there is no way to
* resume the original state of the tape device, since we would need to
* manually re-load the cartridge which was active at suspend time.
*/
int tape_generic_pm_suspend(struct ccw_device *cdev)
{
struct tape_device *device;
device = dev_get_drvdata(&cdev->dev);
if (!device) {
return -ENODEV;
}
DBF_LH(3, "(%08x): tape_generic_pm_suspend(%p)\n",
device->cdev_id, device);
if (device->medium_state != MS_UNLOADED) {
pr_err("A cartridge is loaded in tape device %s, "
"refusing to suspend\n", dev_name(&cdev->dev));
return -EBUSY;
}
spin_lock_irq(get_ccwdev_lock(device->cdev));
switch (device->tape_state) {
case TS_INIT:
case TS_NOT_OPER:
case TS_UNUSED:
spin_unlock_irq(get_ccwdev_lock(device->cdev));
break;
default:
pr_err("Tape device %s is busy, refusing to "
"suspend\n", dev_name(&cdev->dev));
spin_unlock_irq(get_ccwdev_lock(device->cdev));
return -EBUSY;
}
DBF_LH(3, "(%08x): Drive suspended.\n", device->cdev_id);
return 0;
}
/*
* Set device offline.
*
* Called by the common I/O layer if the drive should set offline on user
* request. We may prevent this by returning an error.
* Manual offline is only allowed while the drive is not in use.
*/
int
tape_generic_offline(struct ccw_device *cdev)
{
struct tape_device *device;
device = dev_get_drvdata(&cdev->dev);
if (!device) {
return -ENODEV;
}
DBF_LH(3, "(%08x): tape_generic_offline(%p)\n",
device->cdev_id, device);
spin_lock_irq(get_ccwdev_lock(device->cdev));
switch (device->tape_state) {
case TS_INIT:
case TS_NOT_OPER:
spin_unlock_irq(get_ccwdev_lock(device->cdev));
break;
case TS_UNUSED:
tape_state_set(device, TS_INIT);
spin_unlock_irq(get_ccwdev_lock(device->cdev));
tape_cleanup_device(device);
break;
default:
DBF_EVENT(3, "(%08x): Set offline failed "
"- drive in use.\n",
device->cdev_id);
spin_unlock_irq(get_ccwdev_lock(device->cdev));
return -EBUSY;
}
DBF_LH(3, "(%08x): Drive set offline.\n", device->cdev_id);
return 0;
}
/*
* Allocate memory for a new device structure.
*/
static struct tape_device *
tape_alloc_device(void)
{
struct tape_device *device;
device = kzalloc(sizeof(struct tape_device), GFP_KERNEL);
if (device == NULL) {
DBF_EXCEPTION(2, "ti:no mem\n");
return ERR_PTR(-ENOMEM);
}
device->modeset_byte = kmalloc(1, GFP_KERNEL | GFP_DMA);
if (device->modeset_byte == NULL) {
DBF_EXCEPTION(2, "ti:no mem\n");
kfree(device);
return ERR_PTR(-ENOMEM);
}
mutex_init(&device->mutex);
INIT_LIST_HEAD(&device->req_queue);
INIT_LIST_HEAD(&device->node);
init_waitqueue_head(&device->state_change_wq);
init_waitqueue_head(&device->wait_queue);
device->tape_state = TS_INIT;
device->medium_state = MS_UNKNOWN;
*device->modeset_byte = 0;
device->first_minor = -1;
atomic_set(&device->ref_count, 1);
INIT_DELAYED_WORK(&device->tape_dnr, tape_delayed_next_request);
return device;
}
/*
* Get a reference to an existing device structure. This will automatically
* increment the reference count.
*/
struct tape_device *
tape_get_device(struct tape_device *device)
{
int count;
count = atomic_inc_return(&device->ref_count);
DBF_EVENT(4, "tape_get_device(%p) = %i\n", device, count);
return device;
}
/*
* Decrease the reference counter of a devices structure. If the
* reference counter reaches zero free the device structure.
* The function returns a NULL pointer to be used by the caller
* for clearing reference pointers.
*/
void
tape_put_device(struct tape_device *device)
{
int count;
count = atomic_dec_return(&device->ref_count);
DBF_EVENT(4, "tape_put_device(%p) -> %i\n", device, count);
BUG_ON(count < 0);
if (count == 0) {
kfree(device->modeset_byte);
kfree(device);
}
}
/*
* Find tape device by a device index.
*/
struct tape_device *
tape_find_device(int devindex)
{
struct tape_device *device, *tmp;
device = ERR_PTR(-ENODEV);
read_lock(&tape_device_lock);
list_for_each_entry(tmp, &tape_device_list, node) {
if (tmp->first_minor / TAPE_MINORS_PER_DEV == devindex) {
device = tape_get_device(tmp);
break;
}
}
read_unlock(&tape_device_lock);
return device;
}
/*
* Driverfs tape probe function.
*/
int
tape_generic_probe(struct ccw_device *cdev)
{
struct tape_device *device;
int ret;
struct ccw_dev_id dev_id;
device = tape_alloc_device();
if (IS_ERR(device))
return -ENODEV;
ccw_device_set_options(cdev, CCWDEV_DO_PATHGROUP |
CCWDEV_DO_MULTIPATH);
ret = sysfs_create_group(&cdev->dev.kobj, &tape_attr_group);
if (ret) {
tape_put_device(device);
return ret;
}
dev_set_drvdata(&cdev->dev, device);
cdev->handler = __tape_do_irq;
device->cdev = cdev;
ccw_device_get_id(cdev, &dev_id);
device->cdev_id = devid_to_int(&dev_id);
return ret;
}
static void
__tape_discard_requests(struct tape_device *device)
{
struct tape_request * request;
struct list_head * l, *n;
list_for_each_safe(l, n, &device->req_queue) {
request = list_entry(l, struct tape_request, list);
if (request->status == TAPE_REQUEST_IN_IO)
request->status = TAPE_REQUEST_DONE;
list_del(&request->list);
/* Decrease ref_count for removed request. */
request->device = NULL;
tape_put_device(device);
request->rc = -EIO;
if (request->callback != NULL)
request->callback(request, request->callback_data);
}
}
/*
* Driverfs tape remove function.
*
* This function is called whenever the common I/O layer detects the device
* gone. This can happen at any time and we cannot refuse.
*/
void
tape_generic_remove(struct ccw_device *cdev)
{
struct tape_device * device;
device = dev_get_drvdata(&cdev->dev);
if (!device) {
return;
}
DBF_LH(3, "(%08x): tape_generic_remove(%p)\n", device->cdev_id, cdev);
spin_lock_irq(get_ccwdev_lock(device->cdev));
switch (device->tape_state) {
case TS_INIT:
tape_state_set(device, TS_NOT_OPER);
case TS_NOT_OPER:
/*
* Nothing to do.
*/
spin_unlock_irq(get_ccwdev_lock(device->cdev));
break;
case TS_UNUSED:
/*
* Need only to release the device.
*/
tape_state_set(device, TS_NOT_OPER);
spin_unlock_irq(get_ccwdev_lock(device->cdev));
tape_cleanup_device(device);
break;
default:
/*
* There may be requests on the queue. We will not get
* an interrupt for a request that was running. So we
* just post them all as I/O errors.
*/
DBF_EVENT(3, "(%08x): Drive in use vanished!\n",
device->cdev_id);
pr_warning("%s: A tape unit was detached while in "
"use\n", dev_name(&device->cdev->dev));
tape_state_set(device, TS_NOT_OPER);
__tape_discard_requests(device);
spin_unlock_irq(get_ccwdev_lock(device->cdev));
tape_cleanup_device(device);
}
device = dev_get_drvdata(&cdev->dev);
if (device) {
sysfs_remove_group(&cdev->dev.kobj, &tape_attr_group);
dev_set_drvdata(&cdev->dev, NULL);
tape_put_device(device);
}
}
/*
* Allocate a new tape ccw request
*/
struct tape_request *
tape_alloc_request(int cplength, int datasize)
{
struct tape_request *request;
BUG_ON(datasize > PAGE_SIZE || (cplength*sizeof(struct ccw1)) > PAGE_SIZE);
DBF_LH(6, "tape_alloc_request(%d, %d)\n", cplength, datasize);
request = kzalloc(sizeof(struct tape_request), GFP_KERNEL);
if (request == NULL) {
DBF_EXCEPTION(1, "cqra nomem\n");
return ERR_PTR(-ENOMEM);
}
/* allocate channel program */
if (cplength > 0) {
request->cpaddr = kcalloc(cplength, sizeof(struct ccw1),
GFP_ATOMIC | GFP_DMA);
if (request->cpaddr == NULL) {
DBF_EXCEPTION(1, "cqra nomem\n");
kfree(request);
return ERR_PTR(-ENOMEM);
}
}
/* alloc small kernel buffer */
if (datasize > 0) {
request->cpdata = kzalloc(datasize, GFP_KERNEL | GFP_DMA);
if (request->cpdata == NULL) {
DBF_EXCEPTION(1, "cqra nomem\n");
kfree(request->cpaddr);
kfree(request);
return ERR_PTR(-ENOMEM);
}
}
DBF_LH(6, "New request %p(%p/%p)\n", request, request->cpaddr,
request->cpdata);
return request;
}
/*
* Free tape ccw request
*/
void
tape_free_request (struct tape_request * request)
{
DBF_LH(6, "Free request %p\n", request);
if (request->device)
tape_put_device(request->device);
kfree(request->cpdata);
kfree(request->cpaddr);
kfree(request);
}
static int
__tape_start_io(struct tape_device *device, struct tape_request *request)
{
int rc;
#ifdef CONFIG_S390_TAPE_BLOCK
if (request->op == TO_BLOCK)
device->discipline->check_locate(device, request);
#endif
rc = ccw_device_start(
device->cdev,
request->cpaddr,
(unsigned long) request,
0x00,
request->options
);
if (rc == 0) {
request->status = TAPE_REQUEST_IN_IO;
} else if (rc == -EBUSY) {
/* The common I/O subsystem is currently busy. Retry later. */
request->status = TAPE_REQUEST_QUEUED;
schedule_delayed_work(&device->tape_dnr, 0);
rc = 0;
} else {
/* Start failed. Remove request and indicate failure. */
DBF_EVENT(1, "tape: start request failed with RC = %i\n", rc);
}
return rc;
}
static void
__tape_start_next_request(struct tape_device *device)
{
struct list_head *l, *n;
struct tape_request *request;
int rc;
DBF_LH(6, "__tape_start_next_request(%p)\n", device);
/*
* Try to start each request on request queue until one is
* started successful.
*/
list_for_each_safe(l, n, &device->req_queue) {
request = list_entry(l, struct tape_request, list);
/*
* Avoid race condition if bottom-half was triggered more than
* once.
*/
if (request->status == TAPE_REQUEST_IN_IO)
return;
/*
* Request has already been stopped. We have to wait until
* the request is removed from the queue in the interrupt
* handling.
*/
if (request->status == TAPE_REQUEST_DONE)
return;
/*
* We wanted to cancel the request but the common I/O layer
* was busy at that time. This can only happen if this
* function is called by delayed_next_request.
* Otherwise we start the next request on the queue.
*/
if (request->status == TAPE_REQUEST_CANCEL) {
rc = __tape_cancel_io(device, request);
} else {
rc = __tape_start_io(device, request);
}
if (rc == 0)
return;
/* Set ending status. */
request->rc = rc;
request->status = TAPE_REQUEST_DONE;
/* Remove from request queue. */
list_del(&request->list);
/* Do callback. */
if (request->callback != NULL)
request->callback(request, request->callback_data);
}
}
static void
tape_delayed_next_request(struct work_struct *work)
{
struct tape_device *device =
container_of(work, struct tape_device, tape_dnr.work);
DBF_LH(6, "tape_delayed_next_request(%p)\n", device);
spin_lock_irq(get_ccwdev_lock(device->cdev));
__tape_start_next_request(device);
spin_unlock_irq(get_ccwdev_lock(device->cdev));
}
static void tape_long_busy_timeout(unsigned long data)
{
struct tape_request *request;
struct tape_device *device;
device = (struct tape_device *) data;
spin_lock_irq(get_ccwdev_lock(device->cdev));
request = list_entry(device->req_queue.next, struct tape_request, list);
BUG_ON(request->status != TAPE_REQUEST_LONG_BUSY);
DBF_LH(6, "%08x: Long busy timeout.\n", device->cdev_id);
__tape_start_next_request(device);
device->lb_timeout.data = 0UL;
tape_put_device(device);
spin_unlock_irq(get_ccwdev_lock(device->cdev));
}
static void
__tape_end_request(
struct tape_device * device,
struct tape_request * request,
int rc)
{
DBF_LH(6, "__tape_end_request(%p, %p, %i)\n", device, request, rc);
if (request) {
request->rc = rc;
request->status = TAPE_REQUEST_DONE;
/* Remove from request queue. */
list_del(&request->list);
/* Do callback. */
if (request->callback != NULL)
request->callback(request, request->callback_data);
}
/* Start next request. */
if (!list_empty(&device->req_queue))
__tape_start_next_request(device);
}
/*
* Write sense data to dbf
*/
void
tape_dump_sense_dbf(struct tape_device *device, struct tape_request *request,
struct irb *irb)
{
unsigned int *sptr;
const char* op;
if (request != NULL)
op = tape_op_verbose[request->op];
else
op = "---";
DBF_EVENT(3, "DSTAT : %02x CSTAT: %02x\n",
irb->scsw.cmd.dstat, irb->scsw.cmd.cstat);
DBF_EVENT(3, "DEVICE: %08x OP\t: %s\n", device->cdev_id, op);
sptr = (unsigned int *) irb->ecw;
DBF_EVENT(3, "%08x %08x\n", sptr[0], sptr[1]);
DBF_EVENT(3, "%08x %08x\n", sptr[2], sptr[3]);
DBF_EVENT(3, "%08x %08x\n", sptr[4], sptr[5]);
DBF_EVENT(3, "%08x %08x\n", sptr[6], sptr[7]);
}
/*
* I/O helper function. Adds the request to the request queue
* and starts it if the tape is idle. Has to be called with
* the device lock held.
*/
static int
__tape_start_request(struct tape_device *device, struct tape_request *request)
{
int rc;
switch (request->op) {
case TO_MSEN:
case TO_ASSIGN:
case TO_UNASSIGN:
case TO_READ_ATTMSG:
case TO_RDC:
if (device->tape_state == TS_INIT)
break;
if (device->tape_state == TS_UNUSED)
break;
default:
if (device->tape_state == TS_BLKUSE)
break;
if (device->tape_state != TS_IN_USE)
return -ENODEV;
}
/* Increase use count of device for the added request. */
request->device = tape_get_device(device);
if (list_empty(&device->req_queue)) {
/* No other requests are on the queue. Start this one. */
rc = __tape_start_io(device, request);
if (rc)
return rc;
DBF_LH(5, "Request %p added for execution.\n", request);
list_add(&request->list, &device->req_queue);
} else {
DBF_LH(5, "Request %p add to queue.\n", request);
request->status = TAPE_REQUEST_QUEUED;
list_add_tail(&request->list, &device->req_queue);
}
return 0;
}
/*
* Add the request to the request queue, try to start it if the
* tape is idle. Return without waiting for end of i/o.
*/
int
tape_do_io_async(struct tape_device *device, struct tape_request *request)
{
int rc;
DBF_LH(6, "tape_do_io_async(%p, %p)\n", device, request);
spin_lock_irq(get_ccwdev_lock(device->cdev));
/* Add request to request queue and try to start it. */
rc = __tape_start_request(device, request);
spin_unlock_irq(get_ccwdev_lock(device->cdev));
return rc;
}
/*
* tape_do_io/__tape_wake_up
* Add the request to the request queue, try to start it if the
* tape is idle and wait uninterruptible for its completion.
*/
static void
__tape_wake_up(struct tape_request *request, void *data)
{
request->callback = NULL;
wake_up((wait_queue_head_t *) data);
}
int
tape_do_io(struct tape_device *device, struct tape_request *request)
{
int rc;
spin_lock_irq(get_ccwdev_lock(device->cdev));
/* Setup callback */
request->callback = __tape_wake_up;
request->callback_data = &device->wait_queue;
/* Add request to request queue and try to start it. */
rc = __tape_start_request(device, request);
spin_unlock_irq(get_ccwdev_lock(device->cdev));
if (rc)
return rc;
/* Request added to the queue. Wait for its completion. */
wait_event(device->wait_queue, (request->callback == NULL));
/* Get rc from request */
return request->rc;
}
/*
* tape_do_io_interruptible/__tape_wake_up_interruptible
* Add the request to the request queue, try to start it if the
* tape is idle and wait uninterruptible for its completion.
*/
static void
__tape_wake_up_interruptible(struct tape_request *request, void *data)
{
request->callback = NULL;
wake_up_interruptible((wait_queue_head_t *) data);
}
int
tape_do_io_interruptible(struct tape_device *device,
struct tape_request *request)
{
int rc;
spin_lock_irq(get_ccwdev_lock(device->cdev));
/* Setup callback */
request->callback = __tape_wake_up_interruptible;
request->callback_data = &device->wait_queue;
rc = __tape_start_request(device, request);
spin_unlock_irq(get_ccwdev_lock(device->cdev));
if (rc)
return rc;
/* Request added to the queue. Wait for its completion. */
rc = wait_event_interruptible(device->wait_queue,
(request->callback == NULL));
if (rc != -ERESTARTSYS)
/* Request finished normally. */
return request->rc;
/* Interrupted by a signal. We have to stop the current request. */
spin_lock_irq(get_ccwdev_lock(device->cdev));
rc = __tape_cancel_io(device, request);
spin_unlock_irq(get_ccwdev_lock(device->cdev));
if (rc == 0) {
/* Wait for the interrupt that acknowledges the halt. */
do {
rc = wait_event_interruptible(
device->wait_queue,
(request->callback == NULL)
);
} while (rc == -ERESTARTSYS);
DBF_EVENT(3, "IO stopped on %08x\n", device->cdev_id);
rc = -ERESTARTSYS;
}
return rc;
}
/*
* Stop running ccw.
*/
int
tape_cancel_io(struct tape_device *device, struct tape_request *request)
{
int rc;
spin_lock_irq(get_ccwdev_lock(device->cdev));
rc = __tape_cancel_io(device, request);
spin_unlock_irq(get_ccwdev_lock(device->cdev));
return rc;
}
/*
* Tape interrupt routine, called from the ccw_device layer
*/
static void
__tape_do_irq (struct ccw_device *cdev, unsigned long intparm, struct irb *irb)
{
struct tape_device *device;
struct tape_request *request;
int rc;
device = dev_get_drvdata(&cdev->dev);
if (device == NULL) {
return;
}
request = (struct tape_request *) intparm;
DBF_LH(6, "__tape_do_irq(device=%p, request=%p)\n", device, request);
/* On special conditions irb is an error pointer */
if (IS_ERR(irb)) {
/* FIXME: What to do with the request? */
switch (PTR_ERR(irb)) {
case -ETIMEDOUT:
DBF_LH(1, "(%08x): Request timed out\n",
device->cdev_id);
case -EIO:
__tape_end_request(device, request, -EIO);
break;
default:
DBF_LH(1, "(%08x): Unexpected i/o error %li\n",
device->cdev_id, PTR_ERR(irb));
}
return;
}
/*
* If the condition code is not zero and the start function bit is
* still set, this is an deferred error and the last start I/O did
* not succeed. At this point the condition that caused the deferred
* error might still apply. So we just schedule the request to be
* started later.
*/
if (irb->scsw.cmd.cc != 0 &&
(irb->scsw.cmd.fctl & SCSW_FCTL_START_FUNC) &&
(request->status == TAPE_REQUEST_IN_IO)) {
DBF_EVENT(3,"(%08x): deferred cc=%i, fctl=%i. restarting\n",
device->cdev_id, irb->scsw.cmd.cc, irb->scsw.cmd.fctl);
request->status = TAPE_REQUEST_QUEUED;
schedule_delayed_work(&device->tape_dnr, HZ);
return;
}
/* May be an unsolicited irq */
if(request != NULL)
request->rescnt = irb->scsw.cmd.count;
else if ((irb->scsw.cmd.dstat == 0x85 || irb->scsw.cmd.dstat == 0x80) &&
!list_empty(&device->req_queue)) {
/* Not Ready to Ready after long busy ? */
struct tape_request *req;
req = list_entry(device->req_queue.next,
struct tape_request, list);
if (req->status == TAPE_REQUEST_LONG_BUSY) {
DBF_EVENT(3, "(%08x): del timer\n", device->cdev_id);
if (del_timer(&device->lb_timeout)) {
device->lb_timeout.data = 0UL;
tape_put_device(device);
__tape_start_next_request(device);
}
return;
}
}
if (irb->scsw.cmd.dstat != 0x0c) {
/* Set the 'ONLINE' flag depending on sense byte 1 */
if(*(((__u8 *) irb->ecw) + 1) & SENSE_DRIVE_ONLINE)
device->tape_generic_status |= GMT_ONLINE(~0);
else
device->tape_generic_status &= ~GMT_ONLINE(~0);
/*
* Any request that does not come back with channel end
* and device end is unusual. Log the sense data.
*/
DBF_EVENT(3,"-- Tape Interrupthandler --\n");
tape_dump_sense_dbf(device, request, irb);
} else {
/* Upon normal completion the device _is_ online */
device->tape_generic_status |= GMT_ONLINE(~0);
}
if (device->tape_state == TS_NOT_OPER) {
DBF_EVENT(6, "tape:device is not operational\n");
return;
}
/*
* Request that were canceled still come back with an interrupt.
* To detect these request the state will be set to TAPE_REQUEST_DONE.
*/
if(request != NULL && request->status == TAPE_REQUEST_DONE) {
__tape_end_request(device, request, -EIO);
return;
}
rc = device->discipline->irq(device, request, irb);
/*
* rc < 0 : request finished unsuccessfully.
* rc == TAPE_IO_SUCCESS: request finished successfully.
* rc == TAPE_IO_PENDING: request is still running. Ignore rc.
* rc == TAPE_IO_RETRY: request finished but needs another go.
* rc == TAPE_IO_STOP: request needs to get terminated.
*/
switch (rc) {
case TAPE_IO_SUCCESS:
/* Upon normal completion the device _is_ online */
device->tape_generic_status |= GMT_ONLINE(~0);
__tape_end_request(device, request, rc);
break;
case TAPE_IO_PENDING:
break;
case TAPE_IO_LONG_BUSY:
device->lb_timeout.data =
(unsigned long) tape_get_device(device);
device->lb_timeout.expires = jiffies +
LONG_BUSY_TIMEOUT * HZ;
DBF_EVENT(3, "(%08x): add timer\n", device->cdev_id);
add_timer(&device->lb_timeout);
request->status = TAPE_REQUEST_LONG_BUSY;
break;
case TAPE_IO_RETRY:
rc = __tape_start_io(device, request);
if (rc)
__tape_end_request(device, request, rc);
break;
case TAPE_IO_STOP:
rc = __tape_cancel_io(device, request);
if (rc)
__tape_end_request(device, request, rc);
break;
default:
if (rc > 0) {
DBF_EVENT(6, "xunknownrc\n");
__tape_end_request(device, request, -EIO);
} else {
__tape_end_request(device, request, rc);
}
break;
}
}
/*
* Tape device open function used by tape_char & tape_block frontends.
*/
int
tape_open(struct tape_device *device)
{
int rc;
spin_lock_irq(get_ccwdev_lock(device->cdev));
if (device->tape_state == TS_NOT_OPER) {
DBF_EVENT(6, "TAPE:nodev\n");
rc = -ENODEV;
} else if (device->tape_state == TS_IN_USE) {
DBF_EVENT(6, "TAPE:dbusy\n");
rc = -EBUSY;
} else if (device->tape_state == TS_BLKUSE) {
DBF_EVENT(6, "TAPE:dbusy\n");
rc = -EBUSY;
} else if (device->discipline != NULL &&
!try_module_get(device->discipline->owner)) {
DBF_EVENT(6, "TAPE:nodisc\n");
rc = -ENODEV;
} else {
tape_state_set(device, TS_IN_USE);
rc = 0;
}
spin_unlock_irq(get_ccwdev_lock(device->cdev));
return rc;
}
/*
* Tape device release function used by tape_char & tape_block frontends.
*/
int
tape_release(struct tape_device *device)
{
spin_lock_irq(get_ccwdev_lock(device->cdev));
if (device->tape_state == TS_IN_USE)
tape_state_set(device, TS_UNUSED);
module_put(device->discipline->owner);
spin_unlock_irq(get_ccwdev_lock(device->cdev));
return 0;
}
/*
* Execute a magnetic tape command a number of times.
*/
int
tape_mtop(struct tape_device *device, int mt_op, int mt_count)
{
tape_mtop_fn fn;
int rc;
DBF_EVENT(6, "TAPE:mtio\n");
DBF_EVENT(6, "TAPE:ioop: %x\n", mt_op);
DBF_EVENT(6, "TAPE:arg: %x\n", mt_count);
if (mt_op < 0 || mt_op >= TAPE_NR_MTOPS)
return -EINVAL;
fn = device->discipline->mtop_array[mt_op];
if (fn == NULL)
return -EINVAL;
/* We assume that the backends can handle count up to 500. */
if (mt_op == MTBSR || mt_op == MTFSR || mt_op == MTFSF ||
mt_op == MTBSF || mt_op == MTFSFM || mt_op == MTBSFM) {
rc = 0;
for (; mt_count > 500; mt_count -= 500)
if ((rc = fn(device, 500)) != 0)
break;
if (rc == 0)
rc = fn(device, mt_count);
} else
rc = fn(device, mt_count);
return rc;
}
/*
* Tape init function.
*/
static int
tape_init (void)
{
TAPE_DBF_AREA = debug_register ( "tape", 2, 2, 4*sizeof(long));
debug_register_view(TAPE_DBF_AREA, &debug_sprintf_view);
#ifdef DBF_LIKE_HELL
debug_set_level(TAPE_DBF_AREA, 6);
#endif
DBF_EVENT(3, "tape init\n");
tape_proc_init();
tapechar_init ();
tapeblock_init ();
return 0;
}
/*
* Tape exit function.
*/
static void
tape_exit(void)
{
DBF_EVENT(6, "tape exit\n");
/* Get rid of the frontends */
tapechar_exit();
tapeblock_exit();
tape_proc_cleanup();
debug_unregister (TAPE_DBF_AREA);
}
MODULE_AUTHOR("(C) 2001 IBM Deutschland Entwicklung GmbH by Carsten Otte and "
"Michael Holzheu (cotte@de.ibm.com,holzheu@de.ibm.com)");
MODULE_DESCRIPTION("Linux on zSeries channel attached tape device driver");
MODULE_LICENSE("GPL");
module_init(tape_init);
module_exit(tape_exit);
EXPORT_SYMBOL(tape_generic_remove);
EXPORT_SYMBOL(tape_generic_probe);
EXPORT_SYMBOL(tape_generic_online);
EXPORT_SYMBOL(tape_generic_offline);
EXPORT_SYMBOL(tape_generic_pm_suspend);
EXPORT_SYMBOL(tape_put_device);
EXPORT_SYMBOL(tape_get_device);
EXPORT_SYMBOL(tape_state_verbose);
EXPORT_SYMBOL(tape_op_verbose);
EXPORT_SYMBOL(tape_state_set);
EXPORT_SYMBOL(tape_med_state_set);
EXPORT_SYMBOL(tape_alloc_request);
EXPORT_SYMBOL(tape_free_request);
EXPORT_SYMBOL(tape_dump_sense_dbf);
EXPORT_SYMBOL(tape_do_io);
EXPORT_SYMBOL(tape_do_io_async);
EXPORT_SYMBOL(tape_do_io_interruptible);
EXPORT_SYMBOL(tape_cancel_io);
EXPORT_SYMBOL(tape_mtop);
| gpl-2.0 |
HONO/CM10_Kernel | fs/yaffs2/yaffs_verify.c | 7926 | 13283 | /*
* YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
*
* Copyright (C) 2002-2010 Aleph One Ltd.
* for Toby Churchill Ltd and Brightstar Engineering
*
* Created by Charles Manning <charles@aleph1.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 "yaffs_verify.h"
#include "yaffs_trace.h"
#include "yaffs_bitmap.h"
#include "yaffs_getblockinfo.h"
#include "yaffs_nand.h"
int yaffs_skip_verification(struct yaffs_dev *dev)
{
dev = dev;
return !(yaffs_trace_mask &
(YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
}
static int yaffs_skip_full_verification(struct yaffs_dev *dev)
{
dev = dev;
return !(yaffs_trace_mask & (YAFFS_TRACE_VERIFY_FULL));
}
static int yaffs_skip_nand_verification(struct yaffs_dev *dev)
{
dev = dev;
return !(yaffs_trace_mask & (YAFFS_TRACE_VERIFY_NAND));
}
static const char *block_state_name[] = {
"Unknown",
"Needs scanning",
"Scanning",
"Empty",
"Allocating",
"Full",
"Dirty",
"Checkpoint",
"Collecting",
"Dead"
};
void yaffs_verify_blk(struct yaffs_dev *dev, struct yaffs_block_info *bi, int n)
{
int actually_used;
int in_use;
if (yaffs_skip_verification(dev))
return;
/* Report illegal runtime states */
if (bi->block_state >= YAFFS_NUMBER_OF_BLOCK_STATES)
yaffs_trace(YAFFS_TRACE_VERIFY,
"Block %d has undefined state %d",
n, bi->block_state);
switch (bi->block_state) {
case YAFFS_BLOCK_STATE_UNKNOWN:
case YAFFS_BLOCK_STATE_SCANNING:
case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
yaffs_trace(YAFFS_TRACE_VERIFY,
"Block %d has bad run-state %s",
n, block_state_name[bi->block_state]);
}
/* Check pages in use and soft deletions are legal */
actually_used = bi->pages_in_use - bi->soft_del_pages;
if (bi->pages_in_use < 0
|| bi->pages_in_use > dev->param.chunks_per_block
|| bi->soft_del_pages < 0
|| bi->soft_del_pages > dev->param.chunks_per_block
|| actually_used < 0 || actually_used > dev->param.chunks_per_block)
yaffs_trace(YAFFS_TRACE_VERIFY,
"Block %d has illegal values pages_in_used %d soft_del_pages %d",
n, bi->pages_in_use, bi->soft_del_pages);
/* Check chunk bitmap legal */
in_use = yaffs_count_chunk_bits(dev, n);
if (in_use != bi->pages_in_use)
yaffs_trace(YAFFS_TRACE_VERIFY,
"Block %d has inconsistent values pages_in_use %d counted chunk bits %d",
n, bi->pages_in_use, in_use);
}
void yaffs_verify_collected_blk(struct yaffs_dev *dev,
struct yaffs_block_info *bi, int n)
{
yaffs_verify_blk(dev, bi, n);
/* After collection the block should be in the erased state */
if (bi->block_state != YAFFS_BLOCK_STATE_COLLECTING &&
bi->block_state != YAFFS_BLOCK_STATE_EMPTY) {
yaffs_trace(YAFFS_TRACE_ERROR,
"Block %d is in state %d after gc, should be erased",
n, bi->block_state);
}
}
void yaffs_verify_blocks(struct yaffs_dev *dev)
{
int i;
int state_count[YAFFS_NUMBER_OF_BLOCK_STATES];
int illegal_states = 0;
if (yaffs_skip_verification(dev))
return;
memset(state_count, 0, sizeof(state_count));
for (i = dev->internal_start_block; i <= dev->internal_end_block; i++) {
struct yaffs_block_info *bi = yaffs_get_block_info(dev, i);
yaffs_verify_blk(dev, bi, i);
if (bi->block_state < YAFFS_NUMBER_OF_BLOCK_STATES)
state_count[bi->block_state]++;
else
illegal_states++;
}
yaffs_trace(YAFFS_TRACE_VERIFY, "Block summary");
yaffs_trace(YAFFS_TRACE_VERIFY,
"%d blocks have illegal states",
illegal_states);
if (state_count[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
yaffs_trace(YAFFS_TRACE_VERIFY,
"Too many allocating blocks");
for (i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
yaffs_trace(YAFFS_TRACE_VERIFY,
"%s %d blocks",
block_state_name[i], state_count[i]);
if (dev->blocks_in_checkpt != state_count[YAFFS_BLOCK_STATE_CHECKPOINT])
yaffs_trace(YAFFS_TRACE_VERIFY,
"Checkpoint block count wrong dev %d count %d",
dev->blocks_in_checkpt,
state_count[YAFFS_BLOCK_STATE_CHECKPOINT]);
if (dev->n_erased_blocks != state_count[YAFFS_BLOCK_STATE_EMPTY])
yaffs_trace(YAFFS_TRACE_VERIFY,
"Erased block count wrong dev %d count %d",
dev->n_erased_blocks,
state_count[YAFFS_BLOCK_STATE_EMPTY]);
if (state_count[YAFFS_BLOCK_STATE_COLLECTING] > 1)
yaffs_trace(YAFFS_TRACE_VERIFY,
"Too many collecting blocks %d (max is 1)",
state_count[YAFFS_BLOCK_STATE_COLLECTING]);
}
/*
* Verify the object header. oh must be valid, but obj and tags may be NULL in which
* case those tests will not be performed.
*/
void yaffs_verify_oh(struct yaffs_obj *obj, struct yaffs_obj_hdr *oh,
struct yaffs_ext_tags *tags, int parent_check)
{
if (obj && yaffs_skip_verification(obj->my_dev))
return;
if (!(tags && obj && oh)) {
yaffs_trace(YAFFS_TRACE_VERIFY,
"Verifying object header tags %p obj %p oh %p",
tags, obj, oh);
return;
}
if (oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
oh->type > YAFFS_OBJECT_TYPE_MAX)
yaffs_trace(YAFFS_TRACE_VERIFY,
"Obj %d header type is illegal value 0x%x",
tags->obj_id, oh->type);
if (tags->obj_id != obj->obj_id)
yaffs_trace(YAFFS_TRACE_VERIFY,
"Obj %d header mismatch obj_id %d",
tags->obj_id, obj->obj_id);
/*
* Check that the object's parent ids match if parent_check requested.
*
* Tests do not apply to the root object.
*/
if (parent_check && tags->obj_id > 1 && !obj->parent)
yaffs_trace(YAFFS_TRACE_VERIFY,
"Obj %d header mismatch parent_id %d obj->parent is NULL",
tags->obj_id, oh->parent_obj_id);
if (parent_check && obj->parent &&
oh->parent_obj_id != obj->parent->obj_id &&
(oh->parent_obj_id != YAFFS_OBJECTID_UNLINKED ||
obj->parent->obj_id != YAFFS_OBJECTID_DELETED))
yaffs_trace(YAFFS_TRACE_VERIFY,
"Obj %d header mismatch parent_id %d parent_obj_id %d",
tags->obj_id, oh->parent_obj_id,
obj->parent->obj_id);
if (tags->obj_id > 1 && oh->name[0] == 0) /* Null name */
yaffs_trace(YAFFS_TRACE_VERIFY,
"Obj %d header name is NULL",
obj->obj_id);
if (tags->obj_id > 1 && ((u8) (oh->name[0])) == 0xff) /* Trashed name */
yaffs_trace(YAFFS_TRACE_VERIFY,
"Obj %d header name is 0xFF",
obj->obj_id);
}
void yaffs_verify_file(struct yaffs_obj *obj)
{
int required_depth;
int actual_depth;
u32 last_chunk;
u32 x;
u32 i;
struct yaffs_dev *dev;
struct yaffs_ext_tags tags;
struct yaffs_tnode *tn;
u32 obj_id;
if (!obj)
return;
if (yaffs_skip_verification(obj->my_dev))
return;
dev = obj->my_dev;
obj_id = obj->obj_id;
/* Check file size is consistent with tnode depth */
last_chunk =
obj->variant.file_variant.file_size / dev->data_bytes_per_chunk + 1;
x = last_chunk >> YAFFS_TNODES_LEVEL0_BITS;
required_depth = 0;
while (x > 0) {
x >>= YAFFS_TNODES_INTERNAL_BITS;
required_depth++;
}
actual_depth = obj->variant.file_variant.top_level;
/* Check that the chunks in the tnode tree are all correct.
* We do this by scanning through the tnode tree and
* checking the tags for every chunk match.
*/
if (yaffs_skip_nand_verification(dev))
return;
for (i = 1; i <= last_chunk; i++) {
tn = yaffs_find_tnode_0(dev, &obj->variant.file_variant, i);
if (tn) {
u32 the_chunk = yaffs_get_group_base(dev, tn, i);
if (the_chunk > 0) {
yaffs_rd_chunk_tags_nand(dev, the_chunk, NULL,
&tags);
if (tags.obj_id != obj_id || tags.chunk_id != i)
yaffs_trace(YAFFS_TRACE_VERIFY,
"Object %d chunk_id %d NAND mismatch chunk %d tags (%d:%d)",
obj_id, i, the_chunk,
tags.obj_id, tags.chunk_id);
}
}
}
}
void yaffs_verify_link(struct yaffs_obj *obj)
{
if (obj && yaffs_skip_verification(obj->my_dev))
return;
/* Verify sane equivalent object */
}
void yaffs_verify_symlink(struct yaffs_obj *obj)
{
if (obj && yaffs_skip_verification(obj->my_dev))
return;
/* Verify symlink string */
}
void yaffs_verify_special(struct yaffs_obj *obj)
{
if (obj && yaffs_skip_verification(obj->my_dev))
return;
}
void yaffs_verify_obj(struct yaffs_obj *obj)
{
struct yaffs_dev *dev;
u32 chunk_min;
u32 chunk_max;
u32 chunk_id_ok;
u32 chunk_in_range;
u32 chunk_wrongly_deleted;
u32 chunk_valid;
if (!obj)
return;
if (obj->being_created)
return;
dev = obj->my_dev;
if (yaffs_skip_verification(dev))
return;
/* Check sane object header chunk */
chunk_min = dev->internal_start_block * dev->param.chunks_per_block;
chunk_max =
(dev->internal_end_block + 1) * dev->param.chunks_per_block - 1;
chunk_in_range = (((unsigned)(obj->hdr_chunk)) >= chunk_min &&
((unsigned)(obj->hdr_chunk)) <= chunk_max);
chunk_id_ok = chunk_in_range || (obj->hdr_chunk == 0);
chunk_valid = chunk_in_range &&
yaffs_check_chunk_bit(dev,
obj->hdr_chunk / dev->param.chunks_per_block,
obj->hdr_chunk % dev->param.chunks_per_block);
chunk_wrongly_deleted = chunk_in_range && !chunk_valid;
if (!obj->fake && (!chunk_id_ok || chunk_wrongly_deleted))
yaffs_trace(YAFFS_TRACE_VERIFY,
"Obj %d has chunk_id %d %s %s",
obj->obj_id, obj->hdr_chunk,
chunk_id_ok ? "" : ",out of range",
chunk_wrongly_deleted ? ",marked as deleted" : "");
if (chunk_valid && !yaffs_skip_nand_verification(dev)) {
struct yaffs_ext_tags tags;
struct yaffs_obj_hdr *oh;
u8 *buffer = yaffs_get_temp_buffer(dev, __LINE__);
oh = (struct yaffs_obj_hdr *)buffer;
yaffs_rd_chunk_tags_nand(dev, obj->hdr_chunk, buffer, &tags);
yaffs_verify_oh(obj, oh, &tags, 1);
yaffs_release_temp_buffer(dev, buffer, __LINE__);
}
/* Verify it has a parent */
if (obj && !obj->fake && (!obj->parent || obj->parent->my_dev != dev)) {
yaffs_trace(YAFFS_TRACE_VERIFY,
"Obj %d has parent pointer %p which does not look like an object",
obj->obj_id, obj->parent);
}
/* Verify parent is a directory */
if (obj->parent
&& obj->parent->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY) {
yaffs_trace(YAFFS_TRACE_VERIFY,
"Obj %d's parent is not a directory (type %d)",
obj->obj_id, obj->parent->variant_type);
}
switch (obj->variant_type) {
case YAFFS_OBJECT_TYPE_FILE:
yaffs_verify_file(obj);
break;
case YAFFS_OBJECT_TYPE_SYMLINK:
yaffs_verify_symlink(obj);
break;
case YAFFS_OBJECT_TYPE_DIRECTORY:
yaffs_verify_dir(obj);
break;
case YAFFS_OBJECT_TYPE_HARDLINK:
yaffs_verify_link(obj);
break;
case YAFFS_OBJECT_TYPE_SPECIAL:
yaffs_verify_special(obj);
break;
case YAFFS_OBJECT_TYPE_UNKNOWN:
default:
yaffs_trace(YAFFS_TRACE_VERIFY,
"Obj %d has illegaltype %d",
obj->obj_id, obj->variant_type);
break;
}
}
void yaffs_verify_objects(struct yaffs_dev *dev)
{
struct yaffs_obj *obj;
int i;
struct list_head *lh;
if (yaffs_skip_verification(dev))
return;
/* Iterate through the objects in each hash entry */
for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
list_for_each(lh, &dev->obj_bucket[i].list) {
if (lh) {
obj =
list_entry(lh, struct yaffs_obj, hash_link);
yaffs_verify_obj(obj);
}
}
}
}
void yaffs_verify_obj_in_dir(struct yaffs_obj *obj)
{
struct list_head *lh;
struct yaffs_obj *list_obj;
int count = 0;
if (!obj) {
yaffs_trace(YAFFS_TRACE_ALWAYS, "No object to verify");
YBUG();
return;
}
if (yaffs_skip_verification(obj->my_dev))
return;
if (!obj->parent) {
yaffs_trace(YAFFS_TRACE_ALWAYS, "Object does not have parent" );
YBUG();
return;
}
if (obj->parent->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY) {
yaffs_trace(YAFFS_TRACE_ALWAYS, "Parent is not directory");
YBUG();
}
/* Iterate through the objects in each hash entry */
list_for_each(lh, &obj->parent->variant.dir_variant.children) {
if (lh) {
list_obj = list_entry(lh, struct yaffs_obj, siblings);
yaffs_verify_obj(list_obj);
if (obj == list_obj)
count++;
}
}
if (count != 1) {
yaffs_trace(YAFFS_TRACE_ALWAYS,
"Object in directory %d times",
count);
YBUG();
}
}
void yaffs_verify_dir(struct yaffs_obj *directory)
{
struct list_head *lh;
struct yaffs_obj *list_obj;
if (!directory) {
YBUG();
return;
}
if (yaffs_skip_full_verification(directory->my_dev))
return;
if (directory->variant_type != YAFFS_OBJECT_TYPE_DIRECTORY) {
yaffs_trace(YAFFS_TRACE_ALWAYS,
"Directory has wrong type: %d",
directory->variant_type);
YBUG();
}
/* Iterate through the objects in each hash entry */
list_for_each(lh, &directory->variant.dir_variant.children) {
if (lh) {
list_obj = list_entry(lh, struct yaffs_obj, siblings);
if (list_obj->parent != directory) {
yaffs_trace(YAFFS_TRACE_ALWAYS,
"Object in directory list has wrong parent %p",
list_obj->parent);
YBUG();
}
yaffs_verify_obj_in_dir(list_obj);
}
}
}
static int yaffs_free_verification_failures;
void yaffs_verify_free_chunks(struct yaffs_dev *dev)
{
int counted;
int difference;
if (yaffs_skip_verification(dev))
return;
counted = yaffs_count_free_chunks(dev);
difference = dev->n_free_chunks - counted;
if (difference) {
yaffs_trace(YAFFS_TRACE_ALWAYS,
"Freechunks verification failure %d %d %d",
dev->n_free_chunks, counted, difference);
yaffs_free_verification_failures++;
}
}
int yaffs_verify_file_sane(struct yaffs_obj *in)
{
in = in;
return YAFFS_OK;
}
| gpl-2.0 |
yakir-Yang/linux | drivers/net/ethernet/mellanox/mlx5/core/mcg.c | 503 | 2617 | /*
* Copyright (c) 2013-2015, Mellanox Technologies. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mlx5/driver.h>
#include <linux/mlx5/cmd.h>
#include <rdma/ib_verbs.h>
#include "mlx5_core.h"
int mlx5_core_attach_mcg(struct mlx5_core_dev *dev, union ib_gid *mgid, u32 qpn)
{
u32 out[MLX5_ST_SZ_DW(attach_to_mcg_out)] = {0};
u32 in[MLX5_ST_SZ_DW(attach_to_mcg_in)] = {0};
void *gid;
MLX5_SET(attach_to_mcg_in, in, opcode, MLX5_CMD_OP_ATTACH_TO_MCG);
MLX5_SET(attach_to_mcg_in, in, qpn, qpn);
gid = MLX5_ADDR_OF(attach_to_mcg_in, in, multicast_gid);
memcpy(gid, mgid, sizeof(*mgid));
return mlx5_cmd_exec(dev, in, sizeof(in), out, sizeof(out));
}
EXPORT_SYMBOL(mlx5_core_attach_mcg);
int mlx5_core_detach_mcg(struct mlx5_core_dev *dev, union ib_gid *mgid, u32 qpn)
{
u32 out[MLX5_ST_SZ_DW(detach_from_mcg_out)] = {0};
u32 in[MLX5_ST_SZ_DW(detach_from_mcg_in)] = {0};
void *gid;
MLX5_SET(detach_from_mcg_in, in, opcode, MLX5_CMD_OP_DETACH_FROM_MCG);
MLX5_SET(detach_from_mcg_in, in, qpn, qpn);
gid = MLX5_ADDR_OF(detach_from_mcg_in, in, multicast_gid);
memcpy(gid, mgid, sizeof(*mgid));
return mlx5_cmd_exec(dev, in, sizeof(in), out, sizeof(out));
}
EXPORT_SYMBOL(mlx5_core_detach_mcg);
| gpl-2.0 |
zzyjsjcom/linux-3.18.11-zzy | tools/perf/arch/common.c | 759 | 4639 | #include <stdio.h>
#include <sys/utsname.h>
#include "common.h"
#include "../util/debug.h"
const char *const arm_triplets[] = {
"arm-eabi-",
"arm-linux-androideabi-",
"arm-unknown-linux-",
"arm-unknown-linux-gnu-",
"arm-unknown-linux-gnueabi-",
NULL
};
const char *const arm64_triplets[] = {
"aarch64-linux-android-",
NULL
};
const char *const powerpc_triplets[] = {
"powerpc-unknown-linux-gnu-",
"powerpc64-unknown-linux-gnu-",
NULL
};
const char *const s390_triplets[] = {
"s390-ibm-linux-",
NULL
};
const char *const sh_triplets[] = {
"sh-unknown-linux-gnu-",
"sh64-unknown-linux-gnu-",
NULL
};
const char *const sparc_triplets[] = {
"sparc-unknown-linux-gnu-",
"sparc64-unknown-linux-gnu-",
NULL
};
const char *const x86_triplets[] = {
"x86_64-pc-linux-gnu-",
"x86_64-unknown-linux-gnu-",
"i686-pc-linux-gnu-",
"i586-pc-linux-gnu-",
"i486-pc-linux-gnu-",
"i386-pc-linux-gnu-",
"i686-linux-android-",
"i686-android-linux-",
NULL
};
const char *const mips_triplets[] = {
"mips-unknown-linux-gnu-",
"mipsel-linux-android-",
NULL
};
static bool lookup_path(char *name)
{
bool found = false;
char *path, *tmp;
char buf[PATH_MAX];
char *env = getenv("PATH");
if (!env)
return false;
env = strdup(env);
if (!env)
return false;
path = strtok_r(env, ":", &tmp);
while (path) {
scnprintf(buf, sizeof(buf), "%s/%s", path, name);
if (access(buf, F_OK) == 0) {
found = true;
break;
}
path = strtok_r(NULL, ":", &tmp);
}
free(env);
return found;
}
static int lookup_triplets(const char *const *triplets, const char *name)
{
int i;
char buf[PATH_MAX];
for (i = 0; triplets[i] != NULL; i++) {
scnprintf(buf, sizeof(buf), "%s%s", triplets[i], name);
if (lookup_path(buf))
return i;
}
return -1;
}
/*
* Return architecture name in a normalized form.
* The conversion logic comes from the Makefile.
*/
static const char *normalize_arch(char *arch)
{
if (!strcmp(arch, "x86_64"))
return "x86";
if (arch[0] == 'i' && arch[2] == '8' && arch[3] == '6')
return "x86";
if (!strcmp(arch, "sun4u") || !strncmp(arch, "sparc", 5))
return "sparc";
if (!strcmp(arch, "aarch64") || !strcmp(arch, "arm64"))
return "arm64";
if (!strncmp(arch, "arm", 3) || !strcmp(arch, "sa110"))
return "arm";
if (!strncmp(arch, "s390", 4))
return "s390";
if (!strncmp(arch, "parisc", 6))
return "parisc";
if (!strncmp(arch, "powerpc", 7) || !strncmp(arch, "ppc", 3))
return "powerpc";
if (!strncmp(arch, "mips", 4))
return "mips";
if (!strncmp(arch, "sh", 2) && isdigit(arch[2]))
return "sh";
return arch;
}
static int perf_session_env__lookup_binutils_path(struct perf_session_env *env,
const char *name,
const char **path)
{
int idx;
const char *arch, *cross_env;
struct utsname uts;
const char *const *path_list;
char *buf = NULL;
arch = normalize_arch(env->arch);
if (uname(&uts) < 0)
goto out;
/*
* We don't need to try to find objdump path for native system.
* Just use default binutils path (e.g.: "objdump").
*/
if (!strcmp(normalize_arch(uts.machine), arch))
goto out;
cross_env = getenv("CROSS_COMPILE");
if (cross_env) {
if (asprintf(&buf, "%s%s", cross_env, name) < 0)
goto out_error;
if (buf[0] == '/') {
if (access(buf, F_OK) == 0)
goto out;
goto out_error;
}
if (lookup_path(buf))
goto out;
zfree(&buf);
}
if (!strcmp(arch, "arm"))
path_list = arm_triplets;
else if (!strcmp(arch, "arm64"))
path_list = arm64_triplets;
else if (!strcmp(arch, "powerpc"))
path_list = powerpc_triplets;
else if (!strcmp(arch, "sh"))
path_list = sh_triplets;
else if (!strcmp(arch, "s390"))
path_list = s390_triplets;
else if (!strcmp(arch, "sparc"))
path_list = sparc_triplets;
else if (!strcmp(arch, "x86"))
path_list = x86_triplets;
else if (!strcmp(arch, "mips"))
path_list = mips_triplets;
else {
ui__error("binutils for %s not supported.\n", arch);
goto out_error;
}
idx = lookup_triplets(path_list, name);
if (idx < 0) {
ui__error("Please install %s for %s.\n"
"You can add it to PATH, set CROSS_COMPILE or "
"override the default using --%s.\n",
name, arch, name);
goto out_error;
}
if (asprintf(&buf, "%s%s", path_list[idx], name) < 0)
goto out_error;
out:
*path = buf;
return 0;
out_error:
free(buf);
*path = NULL;
return -1;
}
int perf_session_env__lookup_objdump(struct perf_session_env *env)
{
/*
* For live mode, env->arch will be NULL and we can use
* the native objdump tool.
*/
if (env->arch == NULL)
return 0;
return perf_session_env__lookup_binutils_path(env, "objdump",
&objdump_path);
}
| gpl-2.0 |
milokim/linux | drivers/media/i2c/tw2804.c | 1783 | 11171 | /*
* 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/init.h>
#include <linux/i2c.h>
#include <linux/videodev2.h>
#include <linux/ioctl.h>
#include <linux/slab.h>
#include <media/v4l2-subdev.h>
#include <media/v4l2-device.h>
#include <media/v4l2-ctrls.h>
#define TW2804_REG_AUTOGAIN 0x02
#define TW2804_REG_HUE 0x0f
#define TW2804_REG_SATURATION 0x10
#define TW2804_REG_CONTRAST 0x11
#define TW2804_REG_BRIGHTNESS 0x12
#define TW2804_REG_COLOR_KILLER 0x14
#define TW2804_REG_GAIN 0x3c
#define TW2804_REG_CHROMA_GAIN 0x3d
#define TW2804_REG_BLUE_BALANCE 0x3e
#define TW2804_REG_RED_BALANCE 0x3f
struct tw2804 {
struct v4l2_subdev sd;
struct v4l2_ctrl_handler hdl;
u8 channel:2;
u8 input:1;
int norm;
};
static const u8 global_registers[] = {
0x39, 0x00,
0x3a, 0xff,
0x3b, 0x84,
0x3c, 0x80,
0x3d, 0x80,
0x3e, 0x82,
0x3f, 0x82,
0x78, 0x00,
0xff, 0xff, /* Terminator (reg 0xff does not exist) */
};
static const u8 channel_registers[] = {
0x01, 0xc4,
0x02, 0xa5,
0x03, 0x20,
0x04, 0xd0,
0x05, 0x20,
0x06, 0xd0,
0x07, 0x88,
0x08, 0x20,
0x09, 0x07,
0x0a, 0xf0,
0x0b, 0x07,
0x0c, 0xf0,
0x0d, 0x40,
0x0e, 0xd2,
0x0f, 0x80,
0x10, 0x80,
0x11, 0x80,
0x12, 0x80,
0x13, 0x1f,
0x14, 0x00,
0x15, 0x00,
0x16, 0x00,
0x17, 0x00,
0x18, 0xff,
0x19, 0xff,
0x1a, 0xff,
0x1b, 0xff,
0x1c, 0xff,
0x1d, 0xff,
0x1e, 0xff,
0x1f, 0xff,
0x20, 0x07,
0x21, 0x07,
0x22, 0x00,
0x23, 0x91,
0x24, 0x51,
0x25, 0x03,
0x26, 0x00,
0x27, 0x00,
0x28, 0x00,
0x29, 0x00,
0x2a, 0x00,
0x2b, 0x00,
0x2c, 0x00,
0x2d, 0x00,
0x2e, 0x00,
0x2f, 0x00,
0x30, 0x00,
0x31, 0x00,
0x32, 0x00,
0x33, 0x00,
0x34, 0x00,
0x35, 0x00,
0x36, 0x00,
0x37, 0x00,
0xff, 0xff, /* Terminator (reg 0xff does not exist) */
};
static int write_reg(struct i2c_client *client, u8 reg, u8 value, u8 channel)
{
return i2c_smbus_write_byte_data(client, reg | (channel << 6), value);
}
static int write_regs(struct i2c_client *client, const u8 *regs, u8 channel)
{
int ret;
int i;
for (i = 0; regs[i] != 0xff; i += 2) {
ret = i2c_smbus_write_byte_data(client,
regs[i] | (channel << 6), regs[i + 1]);
if (ret < 0)
return ret;
}
return 0;
}
static int read_reg(struct i2c_client *client, u8 reg, u8 channel)
{
return i2c_smbus_read_byte_data(client, (reg) | (channel << 6));
}
static inline struct tw2804 *to_state(struct v4l2_subdev *sd)
{
return container_of(sd, struct tw2804, sd);
}
static inline struct tw2804 *to_state_from_ctrl(struct v4l2_ctrl *ctrl)
{
return container_of(ctrl->handler, struct tw2804, hdl);
}
static int tw2804_log_status(struct v4l2_subdev *sd)
{
struct tw2804 *state = to_state(sd);
v4l2_info(sd, "Standard: %s\n",
state->norm & V4L2_STD_525_60 ? "60 Hz" : "50 Hz");
v4l2_info(sd, "Channel: %d\n", state->channel);
v4l2_info(sd, "Input: %d\n", state->input);
return v4l2_ctrl_subdev_log_status(sd);
}
/*
* These volatile controls are needed because all four channels share
* these controls. So a change made to them through one channel would
* require another channel to be updated.
*
* Normally this would have been done in a different way, but since the one
* board that uses this driver sees this single chip as if it was on four
* different i2c adapters (each adapter belonging to a separate instance of
* the same USB driver) there is no reliable method that I have found to let
* the instances know about each other.
*
* So implementing these global registers as volatile is the best we can do.
*/
static int tw2804_g_volatile_ctrl(struct v4l2_ctrl *ctrl)
{
struct tw2804 *state = to_state_from_ctrl(ctrl);
struct i2c_client *client = v4l2_get_subdevdata(&state->sd);
switch (ctrl->id) {
case V4L2_CID_GAIN:
ctrl->val = read_reg(client, TW2804_REG_GAIN, 0);
return 0;
case V4L2_CID_CHROMA_GAIN:
ctrl->val = read_reg(client, TW2804_REG_CHROMA_GAIN, 0);
return 0;
case V4L2_CID_BLUE_BALANCE:
ctrl->val = read_reg(client, TW2804_REG_BLUE_BALANCE, 0);
return 0;
case V4L2_CID_RED_BALANCE:
ctrl->val = read_reg(client, TW2804_REG_RED_BALANCE, 0);
return 0;
}
return 0;
}
static int tw2804_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct tw2804 *state = to_state_from_ctrl(ctrl);
struct i2c_client *client = v4l2_get_subdevdata(&state->sd);
int addr;
int reg;
switch (ctrl->id) {
case V4L2_CID_AUTOGAIN:
addr = TW2804_REG_AUTOGAIN;
reg = read_reg(client, addr, state->channel);
if (reg < 0)
return reg;
if (ctrl->val == 0)
reg &= ~(1 << 7);
else
reg |= 1 << 7;
return write_reg(client, addr, reg, state->channel);
case V4L2_CID_COLOR_KILLER:
addr = TW2804_REG_COLOR_KILLER;
reg = read_reg(client, addr, state->channel);
if (reg < 0)
return reg;
reg = (reg & ~(0x03)) | (ctrl->val == 0 ? 0x02 : 0x03);
return write_reg(client, addr, reg, state->channel);
case V4L2_CID_GAIN:
return write_reg(client, TW2804_REG_GAIN, ctrl->val, 0);
case V4L2_CID_CHROMA_GAIN:
return write_reg(client, TW2804_REG_CHROMA_GAIN, ctrl->val, 0);
case V4L2_CID_BLUE_BALANCE:
return write_reg(client, TW2804_REG_BLUE_BALANCE, ctrl->val, 0);
case V4L2_CID_RED_BALANCE:
return write_reg(client, TW2804_REG_RED_BALANCE, ctrl->val, 0);
case V4L2_CID_BRIGHTNESS:
return write_reg(client, TW2804_REG_BRIGHTNESS,
ctrl->val, state->channel);
case V4L2_CID_CONTRAST:
return write_reg(client, TW2804_REG_CONTRAST,
ctrl->val, state->channel);
case V4L2_CID_SATURATION:
return write_reg(client, TW2804_REG_SATURATION,
ctrl->val, state->channel);
case V4L2_CID_HUE:
return write_reg(client, TW2804_REG_HUE,
ctrl->val, state->channel);
default:
break;
}
return -EINVAL;
}
static int tw2804_s_std(struct v4l2_subdev *sd, v4l2_std_id norm)
{
struct tw2804 *dec = to_state(sd);
struct i2c_client *client = v4l2_get_subdevdata(sd);
bool is_60hz = norm & V4L2_STD_525_60;
u8 regs[] = {
0x01, is_60hz ? 0xc4 : 0x84,
0x09, is_60hz ? 0x07 : 0x04,
0x0a, is_60hz ? 0xf0 : 0x20,
0x0b, is_60hz ? 0x07 : 0x04,
0x0c, is_60hz ? 0xf0 : 0x20,
0x0d, is_60hz ? 0x40 : 0x4a,
0x16, is_60hz ? 0x00 : 0x40,
0x17, is_60hz ? 0x00 : 0x40,
0x20, is_60hz ? 0x07 : 0x0f,
0x21, is_60hz ? 0x07 : 0x0f,
0xff, 0xff,
};
write_regs(client, regs, dec->channel);
dec->norm = norm;
return 0;
}
static int tw2804_s_video_routing(struct v4l2_subdev *sd, u32 input, u32 output,
u32 config)
{
struct tw2804 *dec = to_state(sd);
struct i2c_client *client = v4l2_get_subdevdata(sd);
int reg;
if (config && config - 1 != dec->channel) {
if (config > 4) {
dev_err(&client->dev,
"channel %d is not between 1 and 4!\n", config);
return -EINVAL;
}
dec->channel = config - 1;
dev_dbg(&client->dev, "initializing TW2804 channel %d\n",
dec->channel);
if (dec->channel == 0 &&
write_regs(client, global_registers, 0) < 0) {
dev_err(&client->dev,
"error initializing TW2804 global registers\n");
return -EIO;
}
if (write_regs(client, channel_registers, dec->channel) < 0) {
dev_err(&client->dev,
"error initializing TW2804 channel %d\n",
dec->channel);
return -EIO;
}
}
if (input > 1)
return -EINVAL;
if (input == dec->input)
return 0;
reg = read_reg(client, 0x22, dec->channel);
if (reg >= 0) {
if (input == 0)
reg &= ~(1 << 2);
else
reg |= 1 << 2;
reg = write_reg(client, 0x22, reg, dec->channel);
}
if (reg >= 0)
dec->input = input;
else
return reg;
return 0;
}
static const struct v4l2_ctrl_ops tw2804_ctrl_ops = {
.g_volatile_ctrl = tw2804_g_volatile_ctrl,
.s_ctrl = tw2804_s_ctrl,
};
static const struct v4l2_subdev_video_ops tw2804_video_ops = {
.s_std = tw2804_s_std,
.s_routing = tw2804_s_video_routing,
};
static const struct v4l2_subdev_core_ops tw2804_core_ops = {
.log_status = tw2804_log_status,
};
static const struct v4l2_subdev_ops tw2804_ops = {
.core = &tw2804_core_ops,
.video = &tw2804_video_ops,
};
static int tw2804_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct i2c_adapter *adapter = client->adapter;
struct tw2804 *state;
struct v4l2_subdev *sd;
struct v4l2_ctrl *ctrl;
int err;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -ENODEV;
state = devm_kzalloc(&client->dev, sizeof(*state), GFP_KERNEL);
if (state == NULL)
return -ENOMEM;
sd = &state->sd;
v4l2_i2c_subdev_init(sd, client, &tw2804_ops);
state->channel = -1;
state->norm = V4L2_STD_NTSC;
v4l2_ctrl_handler_init(&state->hdl, 10);
v4l2_ctrl_new_std(&state->hdl, &tw2804_ctrl_ops,
V4L2_CID_BRIGHTNESS, 0, 255, 1, 128);
v4l2_ctrl_new_std(&state->hdl, &tw2804_ctrl_ops,
V4L2_CID_CONTRAST, 0, 255, 1, 128);
v4l2_ctrl_new_std(&state->hdl, &tw2804_ctrl_ops,
V4L2_CID_SATURATION, 0, 255, 1, 128);
v4l2_ctrl_new_std(&state->hdl, &tw2804_ctrl_ops,
V4L2_CID_HUE, 0, 255, 1, 128);
v4l2_ctrl_new_std(&state->hdl, &tw2804_ctrl_ops,
V4L2_CID_COLOR_KILLER, 0, 1, 1, 0);
v4l2_ctrl_new_std(&state->hdl, &tw2804_ctrl_ops,
V4L2_CID_AUTOGAIN, 0, 1, 1, 0);
ctrl = v4l2_ctrl_new_std(&state->hdl, &tw2804_ctrl_ops,
V4L2_CID_GAIN, 0, 255, 1, 128);
if (ctrl)
ctrl->flags |= V4L2_CTRL_FLAG_VOLATILE;
ctrl = v4l2_ctrl_new_std(&state->hdl, &tw2804_ctrl_ops,
V4L2_CID_CHROMA_GAIN, 0, 255, 1, 128);
if (ctrl)
ctrl->flags |= V4L2_CTRL_FLAG_VOLATILE;
ctrl = v4l2_ctrl_new_std(&state->hdl, &tw2804_ctrl_ops,
V4L2_CID_BLUE_BALANCE, 0, 255, 1, 122);
if (ctrl)
ctrl->flags |= V4L2_CTRL_FLAG_VOLATILE;
ctrl = v4l2_ctrl_new_std(&state->hdl, &tw2804_ctrl_ops,
V4L2_CID_RED_BALANCE, 0, 255, 1, 122);
if (ctrl)
ctrl->flags |= V4L2_CTRL_FLAG_VOLATILE;
sd->ctrl_handler = &state->hdl;
err = state->hdl.error;
if (err) {
v4l2_ctrl_handler_free(&state->hdl);
return err;
}
v4l_info(client, "chip found @ 0x%02x (%s)\n",
client->addr << 1, client->adapter->name);
return 0;
}
static int tw2804_remove(struct i2c_client *client)
{
struct v4l2_subdev *sd = i2c_get_clientdata(client);
struct tw2804 *state = to_state(sd);
v4l2_device_unregister_subdev(sd);
v4l2_ctrl_handler_free(&state->hdl);
return 0;
}
static const struct i2c_device_id tw2804_id[] = {
{ "tw2804", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, tw2804_id);
static struct i2c_driver tw2804_driver = {
.driver = {
.name = "tw2804",
},
.probe = tw2804_probe,
.remove = tw2804_remove,
.id_table = tw2804_id,
};
module_i2c_driver(tw2804_driver);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("TW2804/TW2802 V4L2 i2c driver");
MODULE_AUTHOR("Micronas USA Inc");
| gpl-2.0 |
szezso/android_kernel_motorola_msm8916 | arch/x86/kernel/cpu/intel_cacheinfo.c | 2039 | 33618 | /*
* Routines to indentify caches on Intel CPU.
*
* Changes:
* Venkatesh Pallipadi : Adding cache identification through cpuid(4)
* Ashok Raj <ashok.raj@intel.com>: Work with CPU hotplug infrastructure.
* Andi Kleen / Andreas Herrmann : CPUID4 emulation on AMD.
*/
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/compiler.h>
#include <linux/cpu.h>
#include <linux/sched.h>
#include <linux/pci.h>
#include <asm/processor.h>
#include <linux/smp.h>
#include <asm/amd_nb.h>
#include <asm/smp.h>
#define LVL_1_INST 1
#define LVL_1_DATA 2
#define LVL_2 3
#define LVL_3 4
#define LVL_TRACE 5
struct _cache_table {
unsigned char descriptor;
char cache_type;
short size;
};
#define MB(x) ((x) * 1024)
/* All the cache descriptor types we care about (no TLB or
trace cache entries) */
static const struct _cache_table __cpuinitconst cache_table[] =
{
{ 0x06, LVL_1_INST, 8 }, /* 4-way set assoc, 32 byte line size */
{ 0x08, LVL_1_INST, 16 }, /* 4-way set assoc, 32 byte line size */
{ 0x09, LVL_1_INST, 32 }, /* 4-way set assoc, 64 byte line size */
{ 0x0a, LVL_1_DATA, 8 }, /* 2 way set assoc, 32 byte line size */
{ 0x0c, LVL_1_DATA, 16 }, /* 4-way set assoc, 32 byte line size */
{ 0x0d, LVL_1_DATA, 16 }, /* 4-way set assoc, 64 byte line size */
{ 0x0e, LVL_1_DATA, 24 }, /* 6-way set assoc, 64 byte line size */
{ 0x21, LVL_2, 256 }, /* 8-way set assoc, 64 byte line size */
{ 0x22, LVL_3, 512 }, /* 4-way set assoc, sectored cache, 64 byte line size */
{ 0x23, LVL_3, MB(1) }, /* 8-way set assoc, sectored cache, 64 byte line size */
{ 0x25, LVL_3, MB(2) }, /* 8-way set assoc, sectored cache, 64 byte line size */
{ 0x29, LVL_3, MB(4) }, /* 8-way set assoc, sectored cache, 64 byte line size */
{ 0x2c, LVL_1_DATA, 32 }, /* 8-way set assoc, 64 byte line size */
{ 0x30, LVL_1_INST, 32 }, /* 8-way set assoc, 64 byte line size */
{ 0x39, LVL_2, 128 }, /* 4-way set assoc, sectored cache, 64 byte line size */
{ 0x3a, LVL_2, 192 }, /* 6-way set assoc, sectored cache, 64 byte line size */
{ 0x3b, LVL_2, 128 }, /* 2-way set assoc, sectored cache, 64 byte line size */
{ 0x3c, LVL_2, 256 }, /* 4-way set assoc, sectored cache, 64 byte line size */
{ 0x3d, LVL_2, 384 }, /* 6-way set assoc, sectored cache, 64 byte line size */
{ 0x3e, LVL_2, 512 }, /* 4-way set assoc, sectored cache, 64 byte line size */
{ 0x3f, LVL_2, 256 }, /* 2-way set assoc, 64 byte line size */
{ 0x41, LVL_2, 128 }, /* 4-way set assoc, 32 byte line size */
{ 0x42, LVL_2, 256 }, /* 4-way set assoc, 32 byte line size */
{ 0x43, LVL_2, 512 }, /* 4-way set assoc, 32 byte line size */
{ 0x44, LVL_2, MB(1) }, /* 4-way set assoc, 32 byte line size */
{ 0x45, LVL_2, MB(2) }, /* 4-way set assoc, 32 byte line size */
{ 0x46, LVL_3, MB(4) }, /* 4-way set assoc, 64 byte line size */
{ 0x47, LVL_3, MB(8) }, /* 8-way set assoc, 64 byte line size */
{ 0x48, LVL_2, MB(3) }, /* 12-way set assoc, 64 byte line size */
{ 0x49, LVL_3, MB(4) }, /* 16-way set assoc, 64 byte line size */
{ 0x4a, LVL_3, MB(6) }, /* 12-way set assoc, 64 byte line size */
{ 0x4b, LVL_3, MB(8) }, /* 16-way set assoc, 64 byte line size */
{ 0x4c, LVL_3, MB(12) }, /* 12-way set assoc, 64 byte line size */
{ 0x4d, LVL_3, MB(16) }, /* 16-way set assoc, 64 byte line size */
{ 0x4e, LVL_2, MB(6) }, /* 24-way set assoc, 64 byte line size */
{ 0x60, LVL_1_DATA, 16 }, /* 8-way set assoc, sectored cache, 64 byte line size */
{ 0x66, LVL_1_DATA, 8 }, /* 4-way set assoc, sectored cache, 64 byte line size */
{ 0x67, LVL_1_DATA, 16 }, /* 4-way set assoc, sectored cache, 64 byte line size */
{ 0x68, LVL_1_DATA, 32 }, /* 4-way set assoc, sectored cache, 64 byte line size */
{ 0x70, LVL_TRACE, 12 }, /* 8-way set assoc */
{ 0x71, LVL_TRACE, 16 }, /* 8-way set assoc */
{ 0x72, LVL_TRACE, 32 }, /* 8-way set assoc */
{ 0x73, LVL_TRACE, 64 }, /* 8-way set assoc */
{ 0x78, LVL_2, MB(1) }, /* 4-way set assoc, 64 byte line size */
{ 0x79, LVL_2, 128 }, /* 8-way set assoc, sectored cache, 64 byte line size */
{ 0x7a, LVL_2, 256 }, /* 8-way set assoc, sectored cache, 64 byte line size */
{ 0x7b, LVL_2, 512 }, /* 8-way set assoc, sectored cache, 64 byte line size */
{ 0x7c, LVL_2, MB(1) }, /* 8-way set assoc, sectored cache, 64 byte line size */
{ 0x7d, LVL_2, MB(2) }, /* 8-way set assoc, 64 byte line size */
{ 0x7f, LVL_2, 512 }, /* 2-way set assoc, 64 byte line size */
{ 0x80, LVL_2, 512 }, /* 8-way set assoc, 64 byte line size */
{ 0x82, LVL_2, 256 }, /* 8-way set assoc, 32 byte line size */
{ 0x83, LVL_2, 512 }, /* 8-way set assoc, 32 byte line size */
{ 0x84, LVL_2, MB(1) }, /* 8-way set assoc, 32 byte line size */
{ 0x85, LVL_2, MB(2) }, /* 8-way set assoc, 32 byte line size */
{ 0x86, LVL_2, 512 }, /* 4-way set assoc, 64 byte line size */
{ 0x87, LVL_2, MB(1) }, /* 8-way set assoc, 64 byte line size */
{ 0xd0, LVL_3, 512 }, /* 4-way set assoc, 64 byte line size */
{ 0xd1, LVL_3, MB(1) }, /* 4-way set assoc, 64 byte line size */
{ 0xd2, LVL_3, MB(2) }, /* 4-way set assoc, 64 byte line size */
{ 0xd6, LVL_3, MB(1) }, /* 8-way set assoc, 64 byte line size */
{ 0xd7, LVL_3, MB(2) }, /* 8-way set assoc, 64 byte line size */
{ 0xd8, LVL_3, MB(4) }, /* 12-way set assoc, 64 byte line size */
{ 0xdc, LVL_3, MB(2) }, /* 12-way set assoc, 64 byte line size */
{ 0xdd, LVL_3, MB(4) }, /* 12-way set assoc, 64 byte line size */
{ 0xde, LVL_3, MB(8) }, /* 12-way set assoc, 64 byte line size */
{ 0xe2, LVL_3, MB(2) }, /* 16-way set assoc, 64 byte line size */
{ 0xe3, LVL_3, MB(4) }, /* 16-way set assoc, 64 byte line size */
{ 0xe4, LVL_3, MB(8) }, /* 16-way set assoc, 64 byte line size */
{ 0xea, LVL_3, MB(12) }, /* 24-way set assoc, 64 byte line size */
{ 0xeb, LVL_3, MB(18) }, /* 24-way set assoc, 64 byte line size */
{ 0xec, LVL_3, MB(24) }, /* 24-way set assoc, 64 byte line size */
{ 0x00, 0, 0}
};
enum _cache_type {
CACHE_TYPE_NULL = 0,
CACHE_TYPE_DATA = 1,
CACHE_TYPE_INST = 2,
CACHE_TYPE_UNIFIED = 3
};
union _cpuid4_leaf_eax {
struct {
enum _cache_type type:5;
unsigned int level:3;
unsigned int is_self_initializing:1;
unsigned int is_fully_associative:1;
unsigned int reserved:4;
unsigned int num_threads_sharing:12;
unsigned int num_cores_on_die:6;
} split;
u32 full;
};
union _cpuid4_leaf_ebx {
struct {
unsigned int coherency_line_size:12;
unsigned int physical_line_partition:10;
unsigned int ways_of_associativity:10;
} split;
u32 full;
};
union _cpuid4_leaf_ecx {
struct {
unsigned int number_of_sets:32;
} split;
u32 full;
};
struct _cpuid4_info_regs {
union _cpuid4_leaf_eax eax;
union _cpuid4_leaf_ebx ebx;
union _cpuid4_leaf_ecx ecx;
unsigned long size;
struct amd_northbridge *nb;
};
struct _cpuid4_info {
struct _cpuid4_info_regs base;
DECLARE_BITMAP(shared_cpu_map, NR_CPUS);
};
unsigned short num_cache_leaves;
/* AMD doesn't have CPUID4. Emulate it here to report the same
information to the user. This makes some assumptions about the machine:
L2 not shared, no SMT etc. that is currently true on AMD CPUs.
In theory the TLBs could be reported as fake type (they are in "dummy").
Maybe later */
union l1_cache {
struct {
unsigned line_size:8;
unsigned lines_per_tag:8;
unsigned assoc:8;
unsigned size_in_kb:8;
};
unsigned val;
};
union l2_cache {
struct {
unsigned line_size:8;
unsigned lines_per_tag:4;
unsigned assoc:4;
unsigned size_in_kb:16;
};
unsigned val;
};
union l3_cache {
struct {
unsigned line_size:8;
unsigned lines_per_tag:4;
unsigned assoc:4;
unsigned res:2;
unsigned size_encoded:14;
};
unsigned val;
};
static const unsigned short __cpuinitconst assocs[] = {
[1] = 1,
[2] = 2,
[4] = 4,
[6] = 8,
[8] = 16,
[0xa] = 32,
[0xb] = 48,
[0xc] = 64,
[0xd] = 96,
[0xe] = 128,
[0xf] = 0xffff /* fully associative - no way to show this currently */
};
static const unsigned char __cpuinitconst levels[] = { 1, 1, 2, 3 };
static const unsigned char __cpuinitconst types[] = { 1, 2, 3, 3 };
static void __cpuinit
amd_cpuid4(int leaf, union _cpuid4_leaf_eax *eax,
union _cpuid4_leaf_ebx *ebx,
union _cpuid4_leaf_ecx *ecx)
{
unsigned dummy;
unsigned line_size, lines_per_tag, assoc, size_in_kb;
union l1_cache l1i, l1d;
union l2_cache l2;
union l3_cache l3;
union l1_cache *l1 = &l1d;
eax->full = 0;
ebx->full = 0;
ecx->full = 0;
cpuid(0x80000005, &dummy, &dummy, &l1d.val, &l1i.val);
cpuid(0x80000006, &dummy, &dummy, &l2.val, &l3.val);
switch (leaf) {
case 1:
l1 = &l1i;
case 0:
if (!l1->val)
return;
assoc = assocs[l1->assoc];
line_size = l1->line_size;
lines_per_tag = l1->lines_per_tag;
size_in_kb = l1->size_in_kb;
break;
case 2:
if (!l2.val)
return;
assoc = assocs[l2.assoc];
line_size = l2.line_size;
lines_per_tag = l2.lines_per_tag;
/* cpu_data has errata corrections for K7 applied */
size_in_kb = __this_cpu_read(cpu_info.x86_cache_size);
break;
case 3:
if (!l3.val)
return;
assoc = assocs[l3.assoc];
line_size = l3.line_size;
lines_per_tag = l3.lines_per_tag;
size_in_kb = l3.size_encoded * 512;
if (boot_cpu_has(X86_FEATURE_AMD_DCM)) {
size_in_kb = size_in_kb >> 1;
assoc = assoc >> 1;
}
break;
default:
return;
}
eax->split.is_self_initializing = 1;
eax->split.type = types[leaf];
eax->split.level = levels[leaf];
eax->split.num_threads_sharing = 0;
eax->split.num_cores_on_die = __this_cpu_read(cpu_info.x86_max_cores) - 1;
if (assoc == 0xffff)
eax->split.is_fully_associative = 1;
ebx->split.coherency_line_size = line_size - 1;
ebx->split.ways_of_associativity = assoc - 1;
ebx->split.physical_line_partition = lines_per_tag - 1;
ecx->split.number_of_sets = (size_in_kb * 1024) / line_size /
(ebx->split.ways_of_associativity + 1) - 1;
}
struct _cache_attr {
struct attribute attr;
ssize_t (*show)(struct _cpuid4_info *, char *, unsigned int);
ssize_t (*store)(struct _cpuid4_info *, const char *, size_t count,
unsigned int);
};
#if defined(CONFIG_AMD_NB) && defined(CONFIG_SYSFS)
/*
* L3 cache descriptors
*/
static void __cpuinit amd_calc_l3_indices(struct amd_northbridge *nb)
{
struct amd_l3_cache *l3 = &nb->l3_cache;
unsigned int sc0, sc1, sc2, sc3;
u32 val = 0;
pci_read_config_dword(nb->misc, 0x1C4, &val);
/* calculate subcache sizes */
l3->subcaches[0] = sc0 = !(val & BIT(0));
l3->subcaches[1] = sc1 = !(val & BIT(4));
if (boot_cpu_data.x86 == 0x15) {
l3->subcaches[0] = sc0 += !(val & BIT(1));
l3->subcaches[1] = sc1 += !(val & BIT(5));
}
l3->subcaches[2] = sc2 = !(val & BIT(8)) + !(val & BIT(9));
l3->subcaches[3] = sc3 = !(val & BIT(12)) + !(val & BIT(13));
l3->indices = (max(max3(sc0, sc1, sc2), sc3) << 10) - 1;
}
static void __cpuinit amd_init_l3_cache(struct _cpuid4_info_regs *this_leaf, int index)
{
int node;
/* only for L3, and not in virtualized environments */
if (index < 3)
return;
node = amd_get_nb_id(smp_processor_id());
this_leaf->nb = node_to_amd_nb(node);
if (this_leaf->nb && !this_leaf->nb->l3_cache.indices)
amd_calc_l3_indices(this_leaf->nb);
}
/*
* check whether a slot used for disabling an L3 index is occupied.
* @l3: L3 cache descriptor
* @slot: slot number (0..1)
*
* @returns: the disabled index if used or negative value if slot free.
*/
int amd_get_l3_disable_slot(struct amd_northbridge *nb, unsigned slot)
{
unsigned int reg = 0;
pci_read_config_dword(nb->misc, 0x1BC + slot * 4, ®);
/* check whether this slot is activated already */
if (reg & (3UL << 30))
return reg & 0xfff;
return -1;
}
static ssize_t show_cache_disable(struct _cpuid4_info *this_leaf, char *buf,
unsigned int slot)
{
int index;
if (!this_leaf->base.nb || !amd_nb_has_feature(AMD_NB_L3_INDEX_DISABLE))
return -EINVAL;
index = amd_get_l3_disable_slot(this_leaf->base.nb, slot);
if (index >= 0)
return sprintf(buf, "%d\n", index);
return sprintf(buf, "FREE\n");
}
#define SHOW_CACHE_DISABLE(slot) \
static ssize_t \
show_cache_disable_##slot(struct _cpuid4_info *this_leaf, char *buf, \
unsigned int cpu) \
{ \
return show_cache_disable(this_leaf, buf, slot); \
}
SHOW_CACHE_DISABLE(0)
SHOW_CACHE_DISABLE(1)
static void amd_l3_disable_index(struct amd_northbridge *nb, int cpu,
unsigned slot, unsigned long idx)
{
int i;
idx |= BIT(30);
/*
* disable index in all 4 subcaches
*/
for (i = 0; i < 4; i++) {
u32 reg = idx | (i << 20);
if (!nb->l3_cache.subcaches[i])
continue;
pci_write_config_dword(nb->misc, 0x1BC + slot * 4, reg);
/*
* We need to WBINVD on a core on the node containing the L3
* cache which indices we disable therefore a simple wbinvd()
* is not sufficient.
*/
wbinvd_on_cpu(cpu);
reg |= BIT(31);
pci_write_config_dword(nb->misc, 0x1BC + slot * 4, reg);
}
}
/*
* disable a L3 cache index by using a disable-slot
*
* @l3: L3 cache descriptor
* @cpu: A CPU on the node containing the L3 cache
* @slot: slot number (0..1)
* @index: index to disable
*
* @return: 0 on success, error status on failure
*/
int amd_set_l3_disable_slot(struct amd_northbridge *nb, int cpu, unsigned slot,
unsigned long index)
{
int ret = 0;
/* check if @slot is already used or the index is already disabled */
ret = amd_get_l3_disable_slot(nb, slot);
if (ret >= 0)
return -EEXIST;
if (index > nb->l3_cache.indices)
return -EINVAL;
/* check whether the other slot has disabled the same index already */
if (index == amd_get_l3_disable_slot(nb, !slot))
return -EEXIST;
amd_l3_disable_index(nb, cpu, slot, index);
return 0;
}
static ssize_t store_cache_disable(struct _cpuid4_info *this_leaf,
const char *buf, size_t count,
unsigned int slot)
{
unsigned long val = 0;
int cpu, err = 0;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (!this_leaf->base.nb || !amd_nb_has_feature(AMD_NB_L3_INDEX_DISABLE))
return -EINVAL;
cpu = cpumask_first(to_cpumask(this_leaf->shared_cpu_map));
if (strict_strtoul(buf, 10, &val) < 0)
return -EINVAL;
err = amd_set_l3_disable_slot(this_leaf->base.nb, cpu, slot, val);
if (err) {
if (err == -EEXIST)
pr_warning("L3 slot %d in use/index already disabled!\n",
slot);
return err;
}
return count;
}
#define STORE_CACHE_DISABLE(slot) \
static ssize_t \
store_cache_disable_##slot(struct _cpuid4_info *this_leaf, \
const char *buf, size_t count, \
unsigned int cpu) \
{ \
return store_cache_disable(this_leaf, buf, count, slot); \
}
STORE_CACHE_DISABLE(0)
STORE_CACHE_DISABLE(1)
static struct _cache_attr cache_disable_0 = __ATTR(cache_disable_0, 0644,
show_cache_disable_0, store_cache_disable_0);
static struct _cache_attr cache_disable_1 = __ATTR(cache_disable_1, 0644,
show_cache_disable_1, store_cache_disable_1);
static ssize_t
show_subcaches(struct _cpuid4_info *this_leaf, char *buf, unsigned int cpu)
{
if (!this_leaf->base.nb || !amd_nb_has_feature(AMD_NB_L3_PARTITIONING))
return -EINVAL;
return sprintf(buf, "%x\n", amd_get_subcaches(cpu));
}
static ssize_t
store_subcaches(struct _cpuid4_info *this_leaf, const char *buf, size_t count,
unsigned int cpu)
{
unsigned long val;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (!this_leaf->base.nb || !amd_nb_has_feature(AMD_NB_L3_PARTITIONING))
return -EINVAL;
if (strict_strtoul(buf, 16, &val) < 0)
return -EINVAL;
if (amd_set_subcaches(cpu, val))
return -EINVAL;
return count;
}
static struct _cache_attr subcaches =
__ATTR(subcaches, 0644, show_subcaches, store_subcaches);
#else
#define amd_init_l3_cache(x, y)
#endif /* CONFIG_AMD_NB && CONFIG_SYSFS */
static int
__cpuinit cpuid4_cache_lookup_regs(int index,
struct _cpuid4_info_regs *this_leaf)
{
union _cpuid4_leaf_eax eax;
union _cpuid4_leaf_ebx ebx;
union _cpuid4_leaf_ecx ecx;
unsigned edx;
if (boot_cpu_data.x86_vendor == X86_VENDOR_AMD) {
if (cpu_has_topoext)
cpuid_count(0x8000001d, index, &eax.full,
&ebx.full, &ecx.full, &edx);
else
amd_cpuid4(index, &eax, &ebx, &ecx);
amd_init_l3_cache(this_leaf, index);
} else {
cpuid_count(4, index, &eax.full, &ebx.full, &ecx.full, &edx);
}
if (eax.split.type == CACHE_TYPE_NULL)
return -EIO; /* better error ? */
this_leaf->eax = eax;
this_leaf->ebx = ebx;
this_leaf->ecx = ecx;
this_leaf->size = (ecx.split.number_of_sets + 1) *
(ebx.split.coherency_line_size + 1) *
(ebx.split.physical_line_partition + 1) *
(ebx.split.ways_of_associativity + 1);
return 0;
}
static int __cpuinit find_num_cache_leaves(struct cpuinfo_x86 *c)
{
unsigned int eax, ebx, ecx, edx, op;
union _cpuid4_leaf_eax cache_eax;
int i = -1;
if (c->x86_vendor == X86_VENDOR_AMD)
op = 0x8000001d;
else
op = 4;
do {
++i;
/* Do cpuid(op) loop to find out num_cache_leaves */
cpuid_count(op, i, &eax, &ebx, &ecx, &edx);
cache_eax.full = eax;
} while (cache_eax.split.type != CACHE_TYPE_NULL);
return i;
}
void __cpuinit init_amd_cacheinfo(struct cpuinfo_x86 *c)
{
if (cpu_has_topoext) {
num_cache_leaves = find_num_cache_leaves(c);
} else if (c->extended_cpuid_level >= 0x80000006) {
if (cpuid_edx(0x80000006) & 0xf000)
num_cache_leaves = 4;
else
num_cache_leaves = 3;
}
}
unsigned int __cpuinit init_intel_cacheinfo(struct cpuinfo_x86 *c)
{
/* Cache sizes */
unsigned int trace = 0, l1i = 0, l1d = 0, l2 = 0, l3 = 0;
unsigned int new_l1d = 0, new_l1i = 0; /* Cache sizes from cpuid(4) */
unsigned int new_l2 = 0, new_l3 = 0, i; /* Cache sizes from cpuid(4) */
unsigned int l2_id = 0, l3_id = 0, num_threads_sharing, index_msb;
#ifdef CONFIG_X86_HT
unsigned int cpu = c->cpu_index;
#endif
if (c->cpuid_level > 3) {
static int is_initialized;
if (is_initialized == 0) {
/* Init num_cache_leaves from boot CPU */
num_cache_leaves = find_num_cache_leaves(c);
is_initialized++;
}
/*
* Whenever possible use cpuid(4), deterministic cache
* parameters cpuid leaf to find the cache details
*/
for (i = 0; i < num_cache_leaves; i++) {
struct _cpuid4_info_regs this_leaf;
int retval;
retval = cpuid4_cache_lookup_regs(i, &this_leaf);
if (retval >= 0) {
switch (this_leaf.eax.split.level) {
case 1:
if (this_leaf.eax.split.type ==
CACHE_TYPE_DATA)
new_l1d = this_leaf.size/1024;
else if (this_leaf.eax.split.type ==
CACHE_TYPE_INST)
new_l1i = this_leaf.size/1024;
break;
case 2:
new_l2 = this_leaf.size/1024;
num_threads_sharing = 1 + this_leaf.eax.split.num_threads_sharing;
index_msb = get_count_order(num_threads_sharing);
l2_id = c->apicid & ~((1 << index_msb) - 1);
break;
case 3:
new_l3 = this_leaf.size/1024;
num_threads_sharing = 1 + this_leaf.eax.split.num_threads_sharing;
index_msb = get_count_order(
num_threads_sharing);
l3_id = c->apicid & ~((1 << index_msb) - 1);
break;
default:
break;
}
}
}
}
/*
* Don't use cpuid2 if cpuid4 is supported. For P4, we use cpuid2 for
* trace cache
*/
if ((num_cache_leaves == 0 || c->x86 == 15) && c->cpuid_level > 1) {
/* supports eax=2 call */
int j, n;
unsigned int regs[4];
unsigned char *dp = (unsigned char *)regs;
int only_trace = 0;
if (num_cache_leaves != 0 && c->x86 == 15)
only_trace = 1;
/* Number of times to iterate */
n = cpuid_eax(2) & 0xFF;
for (i = 0 ; i < n ; i++) {
cpuid(2, ®s[0], ®s[1], ®s[2], ®s[3]);
/* If bit 31 is set, this is an unknown format */
for (j = 0 ; j < 3 ; j++)
if (regs[j] & (1 << 31))
regs[j] = 0;
/* Byte 0 is level count, not a descriptor */
for (j = 1 ; j < 16 ; j++) {
unsigned char des = dp[j];
unsigned char k = 0;
/* look up this descriptor in the table */
while (cache_table[k].descriptor != 0) {
if (cache_table[k].descriptor == des) {
if (only_trace && cache_table[k].cache_type != LVL_TRACE)
break;
switch (cache_table[k].cache_type) {
case LVL_1_INST:
l1i += cache_table[k].size;
break;
case LVL_1_DATA:
l1d += cache_table[k].size;
break;
case LVL_2:
l2 += cache_table[k].size;
break;
case LVL_3:
l3 += cache_table[k].size;
break;
case LVL_TRACE:
trace += cache_table[k].size;
break;
}
break;
}
k++;
}
}
}
}
if (new_l1d)
l1d = new_l1d;
if (new_l1i)
l1i = new_l1i;
if (new_l2) {
l2 = new_l2;
#ifdef CONFIG_X86_HT
per_cpu(cpu_llc_id, cpu) = l2_id;
#endif
}
if (new_l3) {
l3 = new_l3;
#ifdef CONFIG_X86_HT
per_cpu(cpu_llc_id, cpu) = l3_id;
#endif
}
c->x86_cache_size = l3 ? l3 : (l2 ? l2 : (l1i+l1d));
return l2;
}
#ifdef CONFIG_SYSFS
/* pointer to _cpuid4_info array (for each cache leaf) */
static DEFINE_PER_CPU(struct _cpuid4_info *, ici_cpuid4_info);
#define CPUID4_INFO_IDX(x, y) (&((per_cpu(ici_cpuid4_info, x))[y]))
#ifdef CONFIG_SMP
static int __cpuinit cache_shared_amd_cpu_map_setup(unsigned int cpu, int index)
{
struct _cpuid4_info *this_leaf;
int i, sibling;
if (cpu_has_topoext) {
unsigned int apicid, nshared, first, last;
if (!per_cpu(ici_cpuid4_info, cpu))
return 0;
this_leaf = CPUID4_INFO_IDX(cpu, index);
nshared = this_leaf->base.eax.split.num_threads_sharing + 1;
apicid = cpu_data(cpu).apicid;
first = apicid - (apicid % nshared);
last = first + nshared - 1;
for_each_online_cpu(i) {
apicid = cpu_data(i).apicid;
if ((apicid < first) || (apicid > last))
continue;
if (!per_cpu(ici_cpuid4_info, i))
continue;
this_leaf = CPUID4_INFO_IDX(i, index);
for_each_online_cpu(sibling) {
apicid = cpu_data(sibling).apicid;
if ((apicid < first) || (apicid > last))
continue;
set_bit(sibling, this_leaf->shared_cpu_map);
}
}
} else if (index == 3) {
for_each_cpu(i, cpu_llc_shared_mask(cpu)) {
if (!per_cpu(ici_cpuid4_info, i))
continue;
this_leaf = CPUID4_INFO_IDX(i, index);
for_each_cpu(sibling, cpu_llc_shared_mask(cpu)) {
if (!cpu_online(sibling))
continue;
set_bit(sibling, this_leaf->shared_cpu_map);
}
}
} else
return 0;
return 1;
}
static void __cpuinit cache_shared_cpu_map_setup(unsigned int cpu, int index)
{
struct _cpuid4_info *this_leaf, *sibling_leaf;
unsigned long num_threads_sharing;
int index_msb, i;
struct cpuinfo_x86 *c = &cpu_data(cpu);
if (c->x86_vendor == X86_VENDOR_AMD) {
if (cache_shared_amd_cpu_map_setup(cpu, index))
return;
}
this_leaf = CPUID4_INFO_IDX(cpu, index);
num_threads_sharing = 1 + this_leaf->base.eax.split.num_threads_sharing;
if (num_threads_sharing == 1)
cpumask_set_cpu(cpu, to_cpumask(this_leaf->shared_cpu_map));
else {
index_msb = get_count_order(num_threads_sharing);
for_each_online_cpu(i) {
if (cpu_data(i).apicid >> index_msb ==
c->apicid >> index_msb) {
cpumask_set_cpu(i,
to_cpumask(this_leaf->shared_cpu_map));
if (i != cpu && per_cpu(ici_cpuid4_info, i)) {
sibling_leaf =
CPUID4_INFO_IDX(i, index);
cpumask_set_cpu(cpu, to_cpumask(
sibling_leaf->shared_cpu_map));
}
}
}
}
}
static void __cpuinit cache_remove_shared_cpu_map(unsigned int cpu, int index)
{
struct _cpuid4_info *this_leaf, *sibling_leaf;
int sibling;
this_leaf = CPUID4_INFO_IDX(cpu, index);
for_each_cpu(sibling, to_cpumask(this_leaf->shared_cpu_map)) {
sibling_leaf = CPUID4_INFO_IDX(sibling, index);
cpumask_clear_cpu(cpu,
to_cpumask(sibling_leaf->shared_cpu_map));
}
}
#else
static void __cpuinit cache_shared_cpu_map_setup(unsigned int cpu, int index)
{
}
static void __cpuinit cache_remove_shared_cpu_map(unsigned int cpu, int index)
{
}
#endif
static void __cpuinit free_cache_attributes(unsigned int cpu)
{
int i;
for (i = 0; i < num_cache_leaves; i++)
cache_remove_shared_cpu_map(cpu, i);
kfree(per_cpu(ici_cpuid4_info, cpu));
per_cpu(ici_cpuid4_info, cpu) = NULL;
}
static void __cpuinit get_cpu_leaves(void *_retval)
{
int j, *retval = _retval, cpu = smp_processor_id();
/* Do cpuid and store the results */
for (j = 0; j < num_cache_leaves; j++) {
struct _cpuid4_info *this_leaf = CPUID4_INFO_IDX(cpu, j);
*retval = cpuid4_cache_lookup_regs(j, &this_leaf->base);
if (unlikely(*retval < 0)) {
int i;
for (i = 0; i < j; i++)
cache_remove_shared_cpu_map(cpu, i);
break;
}
cache_shared_cpu_map_setup(cpu, j);
}
}
static int __cpuinit detect_cache_attributes(unsigned int cpu)
{
int retval;
if (num_cache_leaves == 0)
return -ENOENT;
per_cpu(ici_cpuid4_info, cpu) = kzalloc(
sizeof(struct _cpuid4_info) * num_cache_leaves, GFP_KERNEL);
if (per_cpu(ici_cpuid4_info, cpu) == NULL)
return -ENOMEM;
smp_call_function_single(cpu, get_cpu_leaves, &retval, true);
if (retval) {
kfree(per_cpu(ici_cpuid4_info, cpu));
per_cpu(ici_cpuid4_info, cpu) = NULL;
}
return retval;
}
#include <linux/kobject.h>
#include <linux/sysfs.h>
#include <linux/cpu.h>
/* pointer to kobject for cpuX/cache */
static DEFINE_PER_CPU(struct kobject *, ici_cache_kobject);
struct _index_kobject {
struct kobject kobj;
unsigned int cpu;
unsigned short index;
};
/* pointer to array of kobjects for cpuX/cache/indexY */
static DEFINE_PER_CPU(struct _index_kobject *, ici_index_kobject);
#define INDEX_KOBJECT_PTR(x, y) (&((per_cpu(ici_index_kobject, x))[y]))
#define show_one_plus(file_name, object, val) \
static ssize_t show_##file_name(struct _cpuid4_info *this_leaf, char *buf, \
unsigned int cpu) \
{ \
return sprintf(buf, "%lu\n", (unsigned long)this_leaf->object + val); \
}
show_one_plus(level, base.eax.split.level, 0);
show_one_plus(coherency_line_size, base.ebx.split.coherency_line_size, 1);
show_one_plus(physical_line_partition, base.ebx.split.physical_line_partition, 1);
show_one_plus(ways_of_associativity, base.ebx.split.ways_of_associativity, 1);
show_one_plus(number_of_sets, base.ecx.split.number_of_sets, 1);
static ssize_t show_size(struct _cpuid4_info *this_leaf, char *buf,
unsigned int cpu)
{
return sprintf(buf, "%luK\n", this_leaf->base.size / 1024);
}
static ssize_t show_shared_cpu_map_func(struct _cpuid4_info *this_leaf,
int type, char *buf)
{
ptrdiff_t len = PTR_ALIGN(buf + PAGE_SIZE - 1, PAGE_SIZE) - buf;
int n = 0;
if (len > 1) {
const struct cpumask *mask;
mask = to_cpumask(this_leaf->shared_cpu_map);
n = type ?
cpulist_scnprintf(buf, len-2, mask) :
cpumask_scnprintf(buf, len-2, mask);
buf[n++] = '\n';
buf[n] = '\0';
}
return n;
}
static inline ssize_t show_shared_cpu_map(struct _cpuid4_info *leaf, char *buf,
unsigned int cpu)
{
return show_shared_cpu_map_func(leaf, 0, buf);
}
static inline ssize_t show_shared_cpu_list(struct _cpuid4_info *leaf, char *buf,
unsigned int cpu)
{
return show_shared_cpu_map_func(leaf, 1, buf);
}
static ssize_t show_type(struct _cpuid4_info *this_leaf, char *buf,
unsigned int cpu)
{
switch (this_leaf->base.eax.split.type) {
case CACHE_TYPE_DATA:
return sprintf(buf, "Data\n");
case CACHE_TYPE_INST:
return sprintf(buf, "Instruction\n");
case CACHE_TYPE_UNIFIED:
return sprintf(buf, "Unified\n");
default:
return sprintf(buf, "Unknown\n");
}
}
#define to_object(k) container_of(k, struct _index_kobject, kobj)
#define to_attr(a) container_of(a, struct _cache_attr, attr)
#define define_one_ro(_name) \
static struct _cache_attr _name = \
__ATTR(_name, 0444, show_##_name, NULL)
define_one_ro(level);
define_one_ro(type);
define_one_ro(coherency_line_size);
define_one_ro(physical_line_partition);
define_one_ro(ways_of_associativity);
define_one_ro(number_of_sets);
define_one_ro(size);
define_one_ro(shared_cpu_map);
define_one_ro(shared_cpu_list);
static struct attribute *default_attrs[] = {
&type.attr,
&level.attr,
&coherency_line_size.attr,
&physical_line_partition.attr,
&ways_of_associativity.attr,
&number_of_sets.attr,
&size.attr,
&shared_cpu_map.attr,
&shared_cpu_list.attr,
NULL
};
#ifdef CONFIG_AMD_NB
static struct attribute ** __cpuinit amd_l3_attrs(void)
{
static struct attribute **attrs;
int n;
if (attrs)
return attrs;
n = ARRAY_SIZE(default_attrs);
if (amd_nb_has_feature(AMD_NB_L3_INDEX_DISABLE))
n += 2;
if (amd_nb_has_feature(AMD_NB_L3_PARTITIONING))
n += 1;
attrs = kzalloc(n * sizeof (struct attribute *), GFP_KERNEL);
if (attrs == NULL)
return attrs = default_attrs;
for (n = 0; default_attrs[n]; n++)
attrs[n] = default_attrs[n];
if (amd_nb_has_feature(AMD_NB_L3_INDEX_DISABLE)) {
attrs[n++] = &cache_disable_0.attr;
attrs[n++] = &cache_disable_1.attr;
}
if (amd_nb_has_feature(AMD_NB_L3_PARTITIONING))
attrs[n++] = &subcaches.attr;
return attrs;
}
#endif
static ssize_t show(struct kobject *kobj, struct attribute *attr, char *buf)
{
struct _cache_attr *fattr = to_attr(attr);
struct _index_kobject *this_leaf = to_object(kobj);
ssize_t ret;
ret = fattr->show ?
fattr->show(CPUID4_INFO_IDX(this_leaf->cpu, this_leaf->index),
buf, this_leaf->cpu) :
0;
return ret;
}
static ssize_t store(struct kobject *kobj, struct attribute *attr,
const char *buf, size_t count)
{
struct _cache_attr *fattr = to_attr(attr);
struct _index_kobject *this_leaf = to_object(kobj);
ssize_t ret;
ret = fattr->store ?
fattr->store(CPUID4_INFO_IDX(this_leaf->cpu, this_leaf->index),
buf, count, this_leaf->cpu) :
0;
return ret;
}
static const struct sysfs_ops sysfs_ops = {
.show = show,
.store = store,
};
static struct kobj_type ktype_cache = {
.sysfs_ops = &sysfs_ops,
.default_attrs = default_attrs,
};
static struct kobj_type ktype_percpu_entry = {
.sysfs_ops = &sysfs_ops,
};
static void __cpuinit cpuid4_cache_sysfs_exit(unsigned int cpu)
{
kfree(per_cpu(ici_cache_kobject, cpu));
kfree(per_cpu(ici_index_kobject, cpu));
per_cpu(ici_cache_kobject, cpu) = NULL;
per_cpu(ici_index_kobject, cpu) = NULL;
free_cache_attributes(cpu);
}
static int __cpuinit cpuid4_cache_sysfs_init(unsigned int cpu)
{
int err;
if (num_cache_leaves == 0)
return -ENOENT;
err = detect_cache_attributes(cpu);
if (err)
return err;
/* Allocate all required memory */
per_cpu(ici_cache_kobject, cpu) =
kzalloc(sizeof(struct kobject), GFP_KERNEL);
if (unlikely(per_cpu(ici_cache_kobject, cpu) == NULL))
goto err_out;
per_cpu(ici_index_kobject, cpu) = kzalloc(
sizeof(struct _index_kobject) * num_cache_leaves, GFP_KERNEL);
if (unlikely(per_cpu(ici_index_kobject, cpu) == NULL))
goto err_out;
return 0;
err_out:
cpuid4_cache_sysfs_exit(cpu);
return -ENOMEM;
}
static DECLARE_BITMAP(cache_dev_map, NR_CPUS);
/* Add/Remove cache interface for CPU device */
static int __cpuinit cache_add_dev(struct device *dev)
{
unsigned int cpu = dev->id;
unsigned long i, j;
struct _index_kobject *this_object;
struct _cpuid4_info *this_leaf;
int retval;
retval = cpuid4_cache_sysfs_init(cpu);
if (unlikely(retval < 0))
return retval;
retval = kobject_init_and_add(per_cpu(ici_cache_kobject, cpu),
&ktype_percpu_entry,
&dev->kobj, "%s", "cache");
if (retval < 0) {
cpuid4_cache_sysfs_exit(cpu);
return retval;
}
for (i = 0; i < num_cache_leaves; i++) {
this_object = INDEX_KOBJECT_PTR(cpu, i);
this_object->cpu = cpu;
this_object->index = i;
this_leaf = CPUID4_INFO_IDX(cpu, i);
ktype_cache.default_attrs = default_attrs;
#ifdef CONFIG_AMD_NB
if (this_leaf->base.nb)
ktype_cache.default_attrs = amd_l3_attrs();
#endif
retval = kobject_init_and_add(&(this_object->kobj),
&ktype_cache,
per_cpu(ici_cache_kobject, cpu),
"index%1lu", i);
if (unlikely(retval)) {
for (j = 0; j < i; j++)
kobject_put(&(INDEX_KOBJECT_PTR(cpu, j)->kobj));
kobject_put(per_cpu(ici_cache_kobject, cpu));
cpuid4_cache_sysfs_exit(cpu);
return retval;
}
kobject_uevent(&(this_object->kobj), KOBJ_ADD);
}
cpumask_set_cpu(cpu, to_cpumask(cache_dev_map));
kobject_uevent(per_cpu(ici_cache_kobject, cpu), KOBJ_ADD);
return 0;
}
static void __cpuinit cache_remove_dev(struct device *dev)
{
unsigned int cpu = dev->id;
unsigned long i;
if (per_cpu(ici_cpuid4_info, cpu) == NULL)
return;
if (!cpumask_test_cpu(cpu, to_cpumask(cache_dev_map)))
return;
cpumask_clear_cpu(cpu, to_cpumask(cache_dev_map));
for (i = 0; i < num_cache_leaves; i++)
kobject_put(&(INDEX_KOBJECT_PTR(cpu, i)->kobj));
kobject_put(per_cpu(ici_cache_kobject, cpu));
cpuid4_cache_sysfs_exit(cpu);
}
static int __cpuinit cacheinfo_cpu_callback(struct notifier_block *nfb,
unsigned long action, void *hcpu)
{
unsigned int cpu = (unsigned long)hcpu;
struct device *dev;
dev = get_cpu_device(cpu);
switch (action) {
case CPU_ONLINE:
case CPU_ONLINE_FROZEN:
cache_add_dev(dev);
break;
case CPU_DEAD:
case CPU_DEAD_FROZEN:
cache_remove_dev(dev);
break;
}
return NOTIFY_OK;
}
static struct notifier_block __cpuinitdata cacheinfo_cpu_notifier = {
.notifier_call = cacheinfo_cpu_callback,
};
static int __init cache_sysfs_init(void)
{
int i;
if (num_cache_leaves == 0)
return 0;
for_each_online_cpu(i) {
int err;
struct device *dev = get_cpu_device(i);
err = cache_add_dev(dev);
if (err)
return err;
}
register_hotcpu_notifier(&cacheinfo_cpu_notifier);
return 0;
}
device_initcall(cache_sysfs_init);
#endif
| gpl-2.0 |
engine95/exynos5433-MM-NNKernel | drivers/net/ethernet/intel/ixgbevf/ethtool.c | 2295 | 21183 | /*******************************************************************************
Intel 82599 Virtual Function driver
Copyright(c) 1999 - 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.
This program is distributed in the hope it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Contact Information:
e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
/* ethtool support for ixgbevf */
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/types.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/pci.h>
#include <linux/netdevice.h>
#include <linux/ethtool.h>
#include <linux/vmalloc.h>
#include <linux/if_vlan.h>
#include <linux/uaccess.h>
#include "ixgbevf.h"
#define IXGBE_ALL_RAR_ENTRIES 16
struct ixgbe_stats {
char stat_string[ETH_GSTRING_LEN];
int sizeof_stat;
int stat_offset;
int base_stat_offset;
int saved_reset_offset;
};
#define IXGBEVF_STAT(m, b, r) sizeof(((struct ixgbevf_adapter *)0)->m), \
offsetof(struct ixgbevf_adapter, m), \
offsetof(struct ixgbevf_adapter, b), \
offsetof(struct ixgbevf_adapter, r)
static const struct ixgbe_stats ixgbe_gstrings_stats[] = {
{"rx_packets", IXGBEVF_STAT(stats.vfgprc, stats.base_vfgprc,
stats.saved_reset_vfgprc)},
{"tx_packets", IXGBEVF_STAT(stats.vfgptc, stats.base_vfgptc,
stats.saved_reset_vfgptc)},
{"rx_bytes", IXGBEVF_STAT(stats.vfgorc, stats.base_vfgorc,
stats.saved_reset_vfgorc)},
{"tx_bytes", IXGBEVF_STAT(stats.vfgotc, stats.base_vfgotc,
stats.saved_reset_vfgotc)},
{"tx_busy", IXGBEVF_STAT(tx_busy, zero_base, zero_base)},
{"multicast", IXGBEVF_STAT(stats.vfmprc, stats.base_vfmprc,
stats.saved_reset_vfmprc)},
{"rx_csum_offload_good", IXGBEVF_STAT(hw_csum_rx_good, zero_base,
zero_base)},
{"rx_csum_offload_errors", IXGBEVF_STAT(hw_csum_rx_error, zero_base,
zero_base)},
{"tx_csum_offload_ctxt", IXGBEVF_STAT(hw_csum_tx_good, zero_base,
zero_base)},
};
#define IXGBE_QUEUE_STATS_LEN 0
#define IXGBE_GLOBAL_STATS_LEN ARRAY_SIZE(ixgbe_gstrings_stats)
#define IXGBEVF_STATS_LEN (IXGBE_GLOBAL_STATS_LEN + IXGBE_QUEUE_STATS_LEN)
static const char ixgbe_gstrings_test[][ETH_GSTRING_LEN] = {
"Register test (offline)",
"Link test (on/offline)"
};
#define IXGBE_TEST_LEN (sizeof(ixgbe_gstrings_test) / ETH_GSTRING_LEN)
static int ixgbevf_get_settings(struct net_device *netdev,
struct ethtool_cmd *ecmd)
{
struct ixgbevf_adapter *adapter = netdev_priv(netdev);
struct ixgbe_hw *hw = &adapter->hw;
u32 link_speed = 0;
bool link_up;
ecmd->supported = SUPPORTED_10000baseT_Full;
ecmd->autoneg = AUTONEG_DISABLE;
ecmd->transceiver = XCVR_DUMMY1;
ecmd->port = -1;
hw->mac.get_link_status = 1;
hw->mac.ops.check_link(hw, &link_speed, &link_up, false);
if (link_up) {
__u32 speed = SPEED_10000;
switch (link_speed) {
case IXGBE_LINK_SPEED_10GB_FULL:
speed = SPEED_10000;
break;
case IXGBE_LINK_SPEED_1GB_FULL:
speed = SPEED_1000;
break;
case IXGBE_LINK_SPEED_100_FULL:
speed = SPEED_100;
break;
}
ethtool_cmd_speed_set(ecmd, speed);
ecmd->duplex = DUPLEX_FULL;
} else {
ethtool_cmd_speed_set(ecmd, -1);
ecmd->duplex = -1;
}
return 0;
}
static u32 ixgbevf_get_msglevel(struct net_device *netdev)
{
struct ixgbevf_adapter *adapter = netdev_priv(netdev);
return adapter->msg_enable;
}
static void ixgbevf_set_msglevel(struct net_device *netdev, u32 data)
{
struct ixgbevf_adapter *adapter = netdev_priv(netdev);
adapter->msg_enable = data;
}
#define IXGBE_GET_STAT(_A_, _R_) (_A_->stats._R_)
static char *ixgbevf_reg_names[] = {
"IXGBE_VFCTRL",
"IXGBE_VFSTATUS",
"IXGBE_VFLINKS",
"IXGBE_VFRXMEMWRAP",
"IXGBE_VFFRTIMER",
"IXGBE_VTEICR",
"IXGBE_VTEICS",
"IXGBE_VTEIMS",
"IXGBE_VTEIMC",
"IXGBE_VTEIAC",
"IXGBE_VTEIAM",
"IXGBE_VTEITR",
"IXGBE_VTIVAR",
"IXGBE_VTIVAR_MISC",
"IXGBE_VFRDBAL0",
"IXGBE_VFRDBAL1",
"IXGBE_VFRDBAH0",
"IXGBE_VFRDBAH1",
"IXGBE_VFRDLEN0",
"IXGBE_VFRDLEN1",
"IXGBE_VFRDH0",
"IXGBE_VFRDH1",
"IXGBE_VFRDT0",
"IXGBE_VFRDT1",
"IXGBE_VFRXDCTL0",
"IXGBE_VFRXDCTL1",
"IXGBE_VFSRRCTL0",
"IXGBE_VFSRRCTL1",
"IXGBE_VFPSRTYPE",
"IXGBE_VFTDBAL0",
"IXGBE_VFTDBAL1",
"IXGBE_VFTDBAH0",
"IXGBE_VFTDBAH1",
"IXGBE_VFTDLEN0",
"IXGBE_VFTDLEN1",
"IXGBE_VFTDH0",
"IXGBE_VFTDH1",
"IXGBE_VFTDT0",
"IXGBE_VFTDT1",
"IXGBE_VFTXDCTL0",
"IXGBE_VFTXDCTL1",
"IXGBE_VFTDWBAL0",
"IXGBE_VFTDWBAL1",
"IXGBE_VFTDWBAH0",
"IXGBE_VFTDWBAH1"
};
static int ixgbevf_get_regs_len(struct net_device *netdev)
{
return (ARRAY_SIZE(ixgbevf_reg_names)) * sizeof(u32);
}
static void ixgbevf_get_regs(struct net_device *netdev,
struct ethtool_regs *regs,
void *p)
{
struct ixgbevf_adapter *adapter = netdev_priv(netdev);
struct ixgbe_hw *hw = &adapter->hw;
u32 *regs_buff = p;
u32 regs_len = ixgbevf_get_regs_len(netdev);
u8 i;
memset(p, 0, regs_len);
regs->version = (1 << 24) | hw->revision_id << 16 | hw->device_id;
/* General Registers */
regs_buff[0] = IXGBE_READ_REG(hw, IXGBE_VFCTRL);
regs_buff[1] = IXGBE_READ_REG(hw, IXGBE_VFSTATUS);
regs_buff[2] = IXGBE_READ_REG(hw, IXGBE_VFLINKS);
regs_buff[3] = IXGBE_READ_REG(hw, IXGBE_VFRXMEMWRAP);
regs_buff[4] = IXGBE_READ_REG(hw, IXGBE_VFFRTIMER);
/* Interrupt */
/* don't read EICR because it can clear interrupt causes, instead
* read EICS which is a shadow but doesn't clear EICR */
regs_buff[5] = IXGBE_READ_REG(hw, IXGBE_VTEICS);
regs_buff[6] = IXGBE_READ_REG(hw, IXGBE_VTEICS);
regs_buff[7] = IXGBE_READ_REG(hw, IXGBE_VTEIMS);
regs_buff[8] = IXGBE_READ_REG(hw, IXGBE_VTEIMC);
regs_buff[9] = IXGBE_READ_REG(hw, IXGBE_VTEIAC);
regs_buff[10] = IXGBE_READ_REG(hw, IXGBE_VTEIAM);
regs_buff[11] = IXGBE_READ_REG(hw, IXGBE_VTEITR(0));
regs_buff[12] = IXGBE_READ_REG(hw, IXGBE_VTIVAR(0));
regs_buff[13] = IXGBE_READ_REG(hw, IXGBE_VTIVAR_MISC);
/* Receive DMA */
for (i = 0; i < 2; i++)
regs_buff[14 + i] = IXGBE_READ_REG(hw, IXGBE_VFRDBAL(i));
for (i = 0; i < 2; i++)
regs_buff[16 + i] = IXGBE_READ_REG(hw, IXGBE_VFRDBAH(i));
for (i = 0; i < 2; i++)
regs_buff[18 + i] = IXGBE_READ_REG(hw, IXGBE_VFRDLEN(i));
for (i = 0; i < 2; i++)
regs_buff[20 + i] = IXGBE_READ_REG(hw, IXGBE_VFRDH(i));
for (i = 0; i < 2; i++)
regs_buff[22 + i] = IXGBE_READ_REG(hw, IXGBE_VFRDT(i));
for (i = 0; i < 2; i++)
regs_buff[24 + i] = IXGBE_READ_REG(hw, IXGBE_VFRXDCTL(i));
for (i = 0; i < 2; i++)
regs_buff[26 + i] = IXGBE_READ_REG(hw, IXGBE_VFSRRCTL(i));
/* Receive */
regs_buff[28] = IXGBE_READ_REG(hw, IXGBE_VFPSRTYPE);
/* Transmit */
for (i = 0; i < 2; i++)
regs_buff[29 + i] = IXGBE_READ_REG(hw, IXGBE_VFTDBAL(i));
for (i = 0; i < 2; i++)
regs_buff[31 + i] = IXGBE_READ_REG(hw, IXGBE_VFTDBAH(i));
for (i = 0; i < 2; i++)
regs_buff[33 + i] = IXGBE_READ_REG(hw, IXGBE_VFTDLEN(i));
for (i = 0; i < 2; i++)
regs_buff[35 + i] = IXGBE_READ_REG(hw, IXGBE_VFTDH(i));
for (i = 0; i < 2; i++)
regs_buff[37 + i] = IXGBE_READ_REG(hw, IXGBE_VFTDT(i));
for (i = 0; i < 2; i++)
regs_buff[39 + i] = IXGBE_READ_REG(hw, IXGBE_VFTXDCTL(i));
for (i = 0; i < 2; i++)
regs_buff[41 + i] = IXGBE_READ_REG(hw, IXGBE_VFTDWBAL(i));
for (i = 0; i < 2; i++)
regs_buff[43 + i] = IXGBE_READ_REG(hw, IXGBE_VFTDWBAH(i));
for (i = 0; i < ARRAY_SIZE(ixgbevf_reg_names); i++)
hw_dbg(hw, "%s\t%8.8x\n", ixgbevf_reg_names[i], regs_buff[i]);
}
static void ixgbevf_get_drvinfo(struct net_device *netdev,
struct ethtool_drvinfo *drvinfo)
{
struct ixgbevf_adapter *adapter = netdev_priv(netdev);
strlcpy(drvinfo->driver, ixgbevf_driver_name, sizeof(drvinfo->driver));
strlcpy(drvinfo->version, ixgbevf_driver_version,
sizeof(drvinfo->version));
strlcpy(drvinfo->bus_info, pci_name(adapter->pdev),
sizeof(drvinfo->bus_info));
}
static void ixgbevf_get_ringparam(struct net_device *netdev,
struct ethtool_ringparam *ring)
{
struct ixgbevf_adapter *adapter = netdev_priv(netdev);
ring->rx_max_pending = IXGBEVF_MAX_RXD;
ring->tx_max_pending = IXGBEVF_MAX_TXD;
ring->rx_pending = adapter->rx_ring_count;
ring->tx_pending = adapter->tx_ring_count;
}
static int ixgbevf_set_ringparam(struct net_device *netdev,
struct ethtool_ringparam *ring)
{
struct ixgbevf_adapter *adapter = netdev_priv(netdev);
struct ixgbevf_ring *tx_ring = NULL, *rx_ring = NULL;
u32 new_rx_count, new_tx_count;
int i, err = 0;
if ((ring->rx_mini_pending) || (ring->rx_jumbo_pending))
return -EINVAL;
new_tx_count = max_t(u32, ring->tx_pending, IXGBEVF_MIN_TXD);
new_tx_count = min_t(u32, new_tx_count, IXGBEVF_MAX_TXD);
new_tx_count = ALIGN(new_tx_count, IXGBE_REQ_TX_DESCRIPTOR_MULTIPLE);
new_rx_count = max_t(u32, ring->rx_pending, IXGBEVF_MIN_RXD);
new_rx_count = min_t(u32, new_rx_count, IXGBEVF_MAX_RXD);
new_rx_count = ALIGN(new_rx_count, IXGBE_REQ_RX_DESCRIPTOR_MULTIPLE);
/* if nothing to do return success */
if ((new_tx_count == adapter->tx_ring_count) &&
(new_rx_count == adapter->rx_ring_count))
return 0;
while (test_and_set_bit(__IXGBEVF_RESETTING, &adapter->state))
usleep_range(1000, 2000);
if (!netif_running(adapter->netdev)) {
for (i = 0; i < adapter->num_tx_queues; i++)
adapter->tx_ring[i].count = new_tx_count;
for (i = 0; i < adapter->num_rx_queues; i++)
adapter->rx_ring[i].count = new_rx_count;
adapter->tx_ring_count = new_tx_count;
adapter->rx_ring_count = new_rx_count;
goto clear_reset;
}
if (new_tx_count != adapter->tx_ring_count) {
tx_ring = vmalloc(adapter->num_tx_queues * sizeof(*tx_ring));
if (!tx_ring) {
err = -ENOMEM;
goto clear_reset;
}
for (i = 0; i < adapter->num_tx_queues; i++) {
/* clone ring and setup updated count */
tx_ring[i] = adapter->tx_ring[i];
tx_ring[i].count = new_tx_count;
err = ixgbevf_setup_tx_resources(adapter, &tx_ring[i]);
if (!err)
continue;
while (i) {
i--;
ixgbevf_free_tx_resources(adapter, &tx_ring[i]);
}
vfree(tx_ring);
tx_ring = NULL;
goto clear_reset;
}
}
if (new_rx_count != adapter->rx_ring_count) {
rx_ring = vmalloc(adapter->num_rx_queues * sizeof(*rx_ring));
if (!rx_ring) {
err = -ENOMEM;
goto clear_reset;
}
for (i = 0; i < adapter->num_rx_queues; i++) {
/* clone ring and setup updated count */
rx_ring[i] = adapter->rx_ring[i];
rx_ring[i].count = new_rx_count;
err = ixgbevf_setup_rx_resources(adapter, &rx_ring[i]);
if (!err)
continue;
while (i) {
i--;
ixgbevf_free_rx_resources(adapter, &rx_ring[i]);
}
vfree(rx_ring);
rx_ring = NULL;
goto clear_reset;
}
}
/* bring interface down to prepare for update */
ixgbevf_down(adapter);
/* Tx */
if (tx_ring) {
for (i = 0; i < adapter->num_tx_queues; i++) {
ixgbevf_free_tx_resources(adapter,
&adapter->tx_ring[i]);
adapter->tx_ring[i] = tx_ring[i];
}
adapter->tx_ring_count = new_tx_count;
vfree(tx_ring);
tx_ring = NULL;
}
/* Rx */
if (rx_ring) {
for (i = 0; i < adapter->num_rx_queues; i++) {
ixgbevf_free_rx_resources(adapter,
&adapter->rx_ring[i]);
adapter->rx_ring[i] = rx_ring[i];
}
adapter->rx_ring_count = new_rx_count;
vfree(rx_ring);
rx_ring = NULL;
}
/* restore interface using new values */
ixgbevf_up(adapter);
clear_reset:
/* free Tx resources if Rx error is encountered */
if (tx_ring) {
for (i = 0; i < adapter->num_tx_queues; i++)
ixgbevf_free_tx_resources(adapter, &tx_ring[i]);
vfree(tx_ring);
}
clear_bit(__IXGBEVF_RESETTING, &adapter->state);
return err;
}
static int ixgbevf_get_sset_count(struct net_device *dev, int stringset)
{
switch (stringset) {
case ETH_SS_TEST:
return IXGBE_TEST_LEN;
case ETH_SS_STATS:
return IXGBE_GLOBAL_STATS_LEN;
default:
return -EINVAL;
}
}
static void ixgbevf_get_ethtool_stats(struct net_device *netdev,
struct ethtool_stats *stats, u64 *data)
{
struct ixgbevf_adapter *adapter = netdev_priv(netdev);
int i;
ixgbevf_update_stats(adapter);
for (i = 0; i < IXGBE_GLOBAL_STATS_LEN; i++) {
char *p = (char *)adapter +
ixgbe_gstrings_stats[i].stat_offset;
char *b = (char *)adapter +
ixgbe_gstrings_stats[i].base_stat_offset;
char *r = (char *)adapter +
ixgbe_gstrings_stats[i].saved_reset_offset;
data[i] = ((ixgbe_gstrings_stats[i].sizeof_stat ==
sizeof(u64)) ? *(u64 *)p : *(u32 *)p) -
((ixgbe_gstrings_stats[i].sizeof_stat ==
sizeof(u64)) ? *(u64 *)b : *(u32 *)b) +
((ixgbe_gstrings_stats[i].sizeof_stat ==
sizeof(u64)) ? *(u64 *)r : *(u32 *)r);
}
}
static void ixgbevf_get_strings(struct net_device *netdev, u32 stringset,
u8 *data)
{
char *p = (char *)data;
int i;
switch (stringset) {
case ETH_SS_TEST:
memcpy(data, *ixgbe_gstrings_test,
IXGBE_TEST_LEN * ETH_GSTRING_LEN);
break;
case ETH_SS_STATS:
for (i = 0; i < IXGBE_GLOBAL_STATS_LEN; i++) {
memcpy(p, ixgbe_gstrings_stats[i].stat_string,
ETH_GSTRING_LEN);
p += ETH_GSTRING_LEN;
}
break;
}
}
static int ixgbevf_link_test(struct ixgbevf_adapter *adapter, u64 *data)
{
struct ixgbe_hw *hw = &adapter->hw;
bool link_up;
u32 link_speed = 0;
*data = 0;
hw->mac.ops.check_link(hw, &link_speed, &link_up, true);
if (!link_up)
*data = 1;
return *data;
}
/* ethtool register test data */
struct ixgbevf_reg_test {
u16 reg;
u8 array_len;
u8 test_type;
u32 mask;
u32 write;
};
/* In the hardware, registers are laid out either singly, in arrays
* spaced 0x40 bytes apart, or in contiguous tables. We assume
* most tests take place on arrays or single registers (handled
* as a single-element array) and special-case the tables.
* Table tests are always pattern tests.
*
* We also make provision for some required setup steps by specifying
* registers to be written without any read-back testing.
*/
#define PATTERN_TEST 1
#define SET_READ_TEST 2
#define WRITE_NO_TEST 3
#define TABLE32_TEST 4
#define TABLE64_TEST_LO 5
#define TABLE64_TEST_HI 6
/* default VF register test */
static const struct ixgbevf_reg_test reg_test_vf[] = {
{ IXGBE_VFRDBAL(0), 2, PATTERN_TEST, 0xFFFFFF80, 0xFFFFFF80 },
{ IXGBE_VFRDBAH(0), 2, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF },
{ IXGBE_VFRDLEN(0), 2, PATTERN_TEST, 0x000FFF80, 0x000FFFFF },
{ IXGBE_VFRXDCTL(0), 2, WRITE_NO_TEST, 0, IXGBE_RXDCTL_ENABLE },
{ IXGBE_VFRDT(0), 2, PATTERN_TEST, 0x0000FFFF, 0x0000FFFF },
{ IXGBE_VFRXDCTL(0), 2, WRITE_NO_TEST, 0, 0 },
{ IXGBE_VFTDBAL(0), 2, PATTERN_TEST, 0xFFFFFF80, 0xFFFFFFFF },
{ IXGBE_VFTDBAH(0), 2, PATTERN_TEST, 0xFFFFFFFF, 0xFFFFFFFF },
{ IXGBE_VFTDLEN(0), 2, PATTERN_TEST, 0x000FFF80, 0x000FFF80 },
{ 0, 0, 0, 0 }
};
static const u32 register_test_patterns[] = {
0x5A5A5A5A, 0xA5A5A5A5, 0x00000000, 0xFFFFFFFF
};
#define REG_PATTERN_TEST(R, M, W) \
{ \
u32 pat, val, before; \
for (pat = 0; pat < ARRAY_SIZE(register_test_patterns); pat++) { \
before = readl(adapter->hw.hw_addr + R); \
writel((register_test_patterns[pat] & W), \
(adapter->hw.hw_addr + R)); \
val = readl(adapter->hw.hw_addr + R); \
if (val != (register_test_patterns[pat] & W & M)) { \
hw_dbg(&adapter->hw, \
"pattern test reg %04X failed: got " \
"0x%08X expected 0x%08X\n", \
R, val, (register_test_patterns[pat] & W & M)); \
*data = R; \
writel(before, adapter->hw.hw_addr + R); \
return 1; \
} \
writel(before, adapter->hw.hw_addr + R); \
} \
}
#define REG_SET_AND_CHECK(R, M, W) \
{ \
u32 val, before; \
before = readl(adapter->hw.hw_addr + R); \
writel((W & M), (adapter->hw.hw_addr + R)); \
val = readl(adapter->hw.hw_addr + R); \
if ((W & M) != (val & M)) { \
pr_err("set/check reg %04X test failed: got 0x%08X expected " \
"0x%08X\n", R, (val & M), (W & M)); \
*data = R; \
writel(before, (adapter->hw.hw_addr + R)); \
return 1; \
} \
writel(before, (adapter->hw.hw_addr + R)); \
}
static int ixgbevf_reg_test(struct ixgbevf_adapter *adapter, u64 *data)
{
const struct ixgbevf_reg_test *test;
u32 i;
test = reg_test_vf;
/*
* Perform the register test, looping through the test table
* until we either fail or reach the null entry.
*/
while (test->reg) {
for (i = 0; i < test->array_len; i++) {
switch (test->test_type) {
case PATTERN_TEST:
REG_PATTERN_TEST(test->reg + (i * 0x40),
test->mask,
test->write);
break;
case SET_READ_TEST:
REG_SET_AND_CHECK(test->reg + (i * 0x40),
test->mask,
test->write);
break;
case WRITE_NO_TEST:
writel(test->write,
(adapter->hw.hw_addr + test->reg)
+ (i * 0x40));
break;
case TABLE32_TEST:
REG_PATTERN_TEST(test->reg + (i * 4),
test->mask,
test->write);
break;
case TABLE64_TEST_LO:
REG_PATTERN_TEST(test->reg + (i * 8),
test->mask,
test->write);
break;
case TABLE64_TEST_HI:
REG_PATTERN_TEST((test->reg + 4) + (i * 8),
test->mask,
test->write);
break;
}
}
test++;
}
*data = 0;
return *data;
}
static void ixgbevf_diag_test(struct net_device *netdev,
struct ethtool_test *eth_test, u64 *data)
{
struct ixgbevf_adapter *adapter = netdev_priv(netdev);
bool if_running = netif_running(netdev);
set_bit(__IXGBEVF_TESTING, &adapter->state);
if (eth_test->flags == ETH_TEST_FL_OFFLINE) {
/* Offline tests */
hw_dbg(&adapter->hw, "offline testing starting\n");
/* Link test performed before hardware reset so autoneg doesn't
* interfere with test result */
if (ixgbevf_link_test(adapter, &data[1]))
eth_test->flags |= ETH_TEST_FL_FAILED;
if (if_running)
/* indicate we're in test mode */
dev_close(netdev);
else
ixgbevf_reset(adapter);
hw_dbg(&adapter->hw, "register testing starting\n");
if (ixgbevf_reg_test(adapter, &data[0]))
eth_test->flags |= ETH_TEST_FL_FAILED;
ixgbevf_reset(adapter);
clear_bit(__IXGBEVF_TESTING, &adapter->state);
if (if_running)
dev_open(netdev);
} else {
hw_dbg(&adapter->hw, "online testing starting\n");
/* Online tests */
if (ixgbevf_link_test(adapter, &data[1]))
eth_test->flags |= ETH_TEST_FL_FAILED;
/* Online tests aren't run; pass by default */
data[0] = 0;
clear_bit(__IXGBEVF_TESTING, &adapter->state);
}
msleep_interruptible(4 * 1000);
}
static int ixgbevf_nway_reset(struct net_device *netdev)
{
struct ixgbevf_adapter *adapter = netdev_priv(netdev);
if (netif_running(netdev))
ixgbevf_reinit_locked(adapter);
return 0;
}
static const struct ethtool_ops ixgbevf_ethtool_ops = {
.get_settings = ixgbevf_get_settings,
.get_drvinfo = ixgbevf_get_drvinfo,
.get_regs_len = ixgbevf_get_regs_len,
.get_regs = ixgbevf_get_regs,
.nway_reset = ixgbevf_nway_reset,
.get_link = ethtool_op_get_link,
.get_ringparam = ixgbevf_get_ringparam,
.set_ringparam = ixgbevf_set_ringparam,
.get_msglevel = ixgbevf_get_msglevel,
.set_msglevel = ixgbevf_set_msglevel,
.self_test = ixgbevf_diag_test,
.get_sset_count = ixgbevf_get_sset_count,
.get_strings = ixgbevf_get_strings,
.get_ethtool_stats = ixgbevf_get_ethtool_stats,
};
void ixgbevf_set_ethtool_ops(struct net_device *netdev)
{
SET_ETHTOOL_OPS(netdev, &ixgbevf_ethtool_ops);
}
| gpl-2.0 |
Lucius1972/Vex | drivers/gpu/drm/mgag200/mgag200_drv.c | 2295 | 3516 | /*
* Copyright 2012 Red Hat
*
* This file is subject to the terms and conditions of the GNU General
* Public License version 2. See the file COPYING in the main
* directory of this archive for more details.
*
* Authors: Matthew Garrett
* Dave Airlie
*/
#include <linux/module.h>
#include <linux/console.h>
#include <drm/drmP.h>
#include "mgag200_drv.h"
#include <drm/drm_pciids.h>
/*
* This is the generic driver code. This binds the driver to the drm core,
* which then performs further device association and calls our graphics init
* functions
*/
int mgag200_modeset = -1;
MODULE_PARM_DESC(modeset, "Disable/Enable modesetting");
module_param_named(modeset, mgag200_modeset, int, 0400);
static struct drm_driver driver;
static DEFINE_PCI_DEVICE_TABLE(pciidlist) = {
{ PCI_VENDOR_ID_MATROX, 0x522, PCI_ANY_ID, PCI_ANY_ID, 0, 0, G200_SE_A },
{ PCI_VENDOR_ID_MATROX, 0x524, PCI_ANY_ID, PCI_ANY_ID, 0, 0, G200_SE_B },
{ PCI_VENDOR_ID_MATROX, 0x530, PCI_ANY_ID, PCI_ANY_ID, 0, 0, G200_EV },
{ PCI_VENDOR_ID_MATROX, 0x532, PCI_ANY_ID, PCI_ANY_ID, 0, 0, G200_WB },
{ PCI_VENDOR_ID_MATROX, 0x533, PCI_ANY_ID, PCI_ANY_ID, 0, 0, G200_EH },
{ PCI_VENDOR_ID_MATROX, 0x534, PCI_ANY_ID, PCI_ANY_ID, 0, 0, G200_ER },
{0,}
};
MODULE_DEVICE_TABLE(pci, pciidlist);
static void mgag200_kick_out_firmware_fb(struct pci_dev *pdev)
{
struct apertures_struct *ap;
bool primary = false;
ap = alloc_apertures(1);
if (!ap)
return;
ap->ranges[0].base = pci_resource_start(pdev, 0);
ap->ranges[0].size = pci_resource_len(pdev, 0);
#ifdef CONFIG_X86
primary = pdev->resource[PCI_ROM_RESOURCE].flags & IORESOURCE_ROM_SHADOW;
#endif
remove_conflicting_framebuffers(ap, "mgag200drmfb", primary);
kfree(ap);
}
static int mga_pci_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
{
mgag200_kick_out_firmware_fb(pdev);
return drm_get_pci_dev(pdev, ent, &driver);
}
static void mga_pci_remove(struct pci_dev *pdev)
{
struct drm_device *dev = pci_get_drvdata(pdev);
drm_put_dev(dev);
}
static const struct file_operations mgag200_driver_fops = {
.owner = THIS_MODULE,
.open = drm_open,
.release = drm_release,
.unlocked_ioctl = drm_ioctl,
.mmap = mgag200_mmap,
.poll = drm_poll,
.fasync = drm_fasync,
#ifdef CONFIG_COMPAT
.compat_ioctl = drm_compat_ioctl,
#endif
.read = drm_read,
};
static struct drm_driver driver = {
.driver_features = DRIVER_GEM | DRIVER_MODESET | DRIVER_USE_MTRR,
.load = mgag200_driver_load,
.unload = mgag200_driver_unload,
.fops = &mgag200_driver_fops,
.name = DRIVER_NAME,
.desc = DRIVER_DESC,
.date = DRIVER_DATE,
.major = DRIVER_MAJOR,
.minor = DRIVER_MINOR,
.patchlevel = DRIVER_PATCHLEVEL,
.gem_init_object = mgag200_gem_init_object,
.gem_free_object = mgag200_gem_free_object,
.dumb_create = mgag200_dumb_create,
.dumb_map_offset = mgag200_dumb_mmap_offset,
.dumb_destroy = mgag200_dumb_destroy,
};
static struct pci_driver mgag200_pci_driver = {
.name = DRIVER_NAME,
.id_table = pciidlist,
.probe = mga_pci_probe,
.remove = mga_pci_remove,
};
static int __init mgag200_init(void)
{
#ifdef CONFIG_VGA_CONSOLE
if (vgacon_text_force() && mgag200_modeset == -1)
return -EINVAL;
#endif
if (mgag200_modeset == 0)
return -EINVAL;
return drm_pci_init(&driver, &mgag200_pci_driver);
}
static void __exit mgag200_exit(void)
{
drm_pci_exit(&driver, &mgag200_pci_driver);
}
module_init(mgag200_init);
module_exit(mgag200_exit);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
| gpl-2.0 |
rudij7/android_kernel_motorola_msm8939 | drivers/staging/ft1000/ft1000-usb/ft1000_hw.c | 2295 | 54458 | //=====================================================
// CopyRight (C) 2007 Qualcomm Inc. All Rights Reserved.
//
//
// This file is part of Express Card USB Driver
//
// $Id:
//====================================================
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/usb.h>
#include "ft1000_usb.h"
#include <linux/types.h>
#define HARLEY_READ_REGISTER 0x0
#define HARLEY_WRITE_REGISTER 0x01
#define HARLEY_READ_DPRAM_32 0x02
#define HARLEY_READ_DPRAM_LOW 0x03
#define HARLEY_READ_DPRAM_HIGH 0x04
#define HARLEY_WRITE_DPRAM_32 0x05
#define HARLEY_WRITE_DPRAM_LOW 0x06
#define HARLEY_WRITE_DPRAM_HIGH 0x07
#define HARLEY_READ_OPERATION 0xc1
#define HARLEY_WRITE_OPERATION 0x41
//#define JDEBUG
static int ft1000_reset(void *ft1000dev);
static int ft1000_submit_rx_urb(struct ft1000_info *info);
static int ft1000_start_xmit(struct sk_buff *skb, struct net_device *dev);
static int ft1000_open (struct net_device *dev);
static struct net_device_stats *ft1000_netdev_stats(struct net_device *dev);
static int ft1000_chkcard (struct ft1000_usb *dev);
static u8 tempbuffer[1600];
#define MAX_RCV_LOOP 100
//---------------------------------------------------------------------------
// Function: ft1000_control
//
// Parameters: ft1000_usb - device structure
// pipe - usb control message pipe
// request - control request
// requesttype - control message request type
// value - value to be written or 0
// index - register index
// data - data buffer to hold the read/write values
// size - data size
// timeout - control message time out value
//
// Returns: STATUS_SUCCESS - success
// STATUS_FAILURE - failure
//
// Description: This function sends a control message via USB interface synchronously
//
// Notes:
//
//---------------------------------------------------------------------------
static int ft1000_control(struct ft1000_usb *ft1000dev, unsigned int pipe,
u8 request, u8 requesttype, u16 value, u16 index,
void *data, u16 size, int timeout)
{
u16 ret;
if ((ft1000dev == NULL) || (ft1000dev->dev == NULL)) {
DEBUG("ft1000dev or ft1000dev->dev == NULL, failure\n");
return -ENODEV;
}
ret = usb_control_msg(ft1000dev->dev, pipe, request, requesttype,
value, index, data, size, timeout);
if (ret > 0)
ret = 0;
return ret;
}
//---------------------------------------------------------------------------
// Function: ft1000_read_register
//
// Parameters: ft1000_usb - device structure
// Data - data buffer to hold the value read
// nRegIndex - register index
//
// Returns: STATUS_SUCCESS - success
// STATUS_FAILURE - failure
//
// Description: This function returns the value in a register
//
// Notes:
//
//---------------------------------------------------------------------------
int ft1000_read_register(struct ft1000_usb *ft1000dev, u16* Data,
u16 nRegIndx)
{
int ret = STATUS_SUCCESS;
ret = ft1000_control(ft1000dev,
usb_rcvctrlpipe(ft1000dev->dev, 0),
HARLEY_READ_REGISTER,
HARLEY_READ_OPERATION,
0,
nRegIndx,
Data,
2,
USB_CTRL_GET_TIMEOUT);
return ret;
}
//---------------------------------------------------------------------------
// Function: ft1000_write_register
//
// Parameters: ft1000_usb - device structure
// value - value to write into a register
// nRegIndex - register index
//
// Returns: STATUS_SUCCESS - success
// STATUS_FAILURE - failure
//
// Description: This function writes the value in a register
//
// Notes:
//
//---------------------------------------------------------------------------
int ft1000_write_register(struct ft1000_usb *ft1000dev, u16 value,
u16 nRegIndx)
{
int ret = STATUS_SUCCESS;
ret = ft1000_control(ft1000dev,
usb_sndctrlpipe(ft1000dev->dev, 0),
HARLEY_WRITE_REGISTER,
HARLEY_WRITE_OPERATION,
value,
nRegIndx,
NULL,
0,
USB_CTRL_SET_TIMEOUT);
return ret;
}
//---------------------------------------------------------------------------
// Function: ft1000_read_dpram32
//
// Parameters: ft1000_usb - device structure
// indx - starting address to read
// buffer - data buffer to hold the data read
// cnt - number of byte read from DPRAM
//
// Returns: STATUS_SUCCESS - success
// STATUS_FAILURE - failure
//
// Description: This function read a number of bytes from DPRAM
//
// Notes:
//
//---------------------------------------------------------------------------
int ft1000_read_dpram32(struct ft1000_usb *ft1000dev, u16 indx, u8 *buffer,
u16 cnt)
{
int ret = STATUS_SUCCESS;
ret = ft1000_control(ft1000dev,
usb_rcvctrlpipe(ft1000dev->dev, 0),
HARLEY_READ_DPRAM_32,
HARLEY_READ_OPERATION,
0,
indx,
buffer,
cnt,
USB_CTRL_GET_TIMEOUT);
return ret;
}
//---------------------------------------------------------------------------
// Function: ft1000_write_dpram32
//
// Parameters: ft1000_usb - device structure
// indx - starting address to write the data
// buffer - data buffer to write into DPRAM
// cnt - number of bytes to write
//
// Returns: STATUS_SUCCESS - success
// STATUS_FAILURE - failure
//
// Description: This function writes into DPRAM a number of bytes
//
// Notes:
//
//---------------------------------------------------------------------------
int ft1000_write_dpram32(struct ft1000_usb *ft1000dev, u16 indx, u8 *buffer,
u16 cnt)
{
int ret = STATUS_SUCCESS;
if (cnt % 4)
cnt += cnt - (cnt % 4);
ret = ft1000_control(ft1000dev,
usb_sndctrlpipe(ft1000dev->dev, 0),
HARLEY_WRITE_DPRAM_32,
HARLEY_WRITE_OPERATION,
0,
indx,
buffer,
cnt,
USB_CTRL_SET_TIMEOUT);
return ret;
}
//---------------------------------------------------------------------------
// Function: ft1000_read_dpram16
//
// Parameters: ft1000_usb - device structure
// indx - starting address to read
// buffer - data buffer to hold the data read
// hightlow - high or low 16 bit word
//
// Returns: STATUS_SUCCESS - success
// STATUS_FAILURE - failure
//
// Description: This function read 16 bits from DPRAM
//
// Notes:
//
//---------------------------------------------------------------------------
int ft1000_read_dpram16(struct ft1000_usb *ft1000dev, u16 indx, u8 *buffer,
u8 highlow)
{
int ret = STATUS_SUCCESS;
u8 request;
if (highlow == 0)
request = HARLEY_READ_DPRAM_LOW;
else
request = HARLEY_READ_DPRAM_HIGH;
ret = ft1000_control(ft1000dev,
usb_rcvctrlpipe(ft1000dev->dev, 0),
request,
HARLEY_READ_OPERATION,
0,
indx,
buffer,
2,
USB_CTRL_GET_TIMEOUT);
return ret;
}
//---------------------------------------------------------------------------
// Function: ft1000_write_dpram16
//
// Parameters: ft1000_usb - device structure
// indx - starting address to write the data
// value - 16bits value to write
// hightlow - high or low 16 bit word
//
// Returns: STATUS_SUCCESS - success
// STATUS_FAILURE - failure
//
// Description: This function writes into DPRAM a number of bytes
//
// Notes:
//
//---------------------------------------------------------------------------
int ft1000_write_dpram16(struct ft1000_usb *ft1000dev, u16 indx, u16 value, u8 highlow)
{
int ret = STATUS_SUCCESS;
u8 request;
if (highlow == 0)
request = HARLEY_WRITE_DPRAM_LOW;
else
request = HARLEY_WRITE_DPRAM_HIGH;
ret = ft1000_control(ft1000dev,
usb_sndctrlpipe(ft1000dev->dev, 0),
request,
HARLEY_WRITE_OPERATION,
value,
indx,
NULL,
0,
USB_CTRL_SET_TIMEOUT);
return ret;
}
//---------------------------------------------------------------------------
// Function: fix_ft1000_read_dpram32
//
// Parameters: ft1000_usb - device structure
// indx - starting address to read
// buffer - data buffer to hold the data read
//
//
// Returns: STATUS_SUCCESS - success
// STATUS_FAILURE - failure
//
// Description: This function read DPRAM 4 words at a time
//
// Notes:
//
//---------------------------------------------------------------------------
int fix_ft1000_read_dpram32(struct ft1000_usb *ft1000dev, u16 indx,
u8 *buffer)
{
u8 buf[16];
u16 pos;
int ret = STATUS_SUCCESS;
pos = (indx / 4) * 4;
ret = ft1000_read_dpram32(ft1000dev, pos, buf, 16);
if (ret == STATUS_SUCCESS) {
pos = (indx % 4) * 4;
*buffer++ = buf[pos++];
*buffer++ = buf[pos++];
*buffer++ = buf[pos++];
*buffer++ = buf[pos++];
} else {
DEBUG("fix_ft1000_read_dpram32: DPRAM32 Read failed\n");
*buffer++ = 0;
*buffer++ = 0;
*buffer++ = 0;
*buffer++ = 0;
}
return ret;
}
//---------------------------------------------------------------------------
// Function: fix_ft1000_write_dpram32
//
// Parameters: ft1000_usb - device structure
// indx - starting address to write
// buffer - data buffer to write
//
//
// Returns: STATUS_SUCCESS - success
// STATUS_FAILURE - failure
//
// Description: This function write to DPRAM 4 words at a time
//
// Notes:
//
//---------------------------------------------------------------------------
int fix_ft1000_write_dpram32(struct ft1000_usb *ft1000dev, u16 indx, u8 *buffer)
{
u16 pos1;
u16 pos2;
u16 i;
u8 buf[32];
u8 resultbuffer[32];
u8 *pdata;
int ret = STATUS_SUCCESS;
pos1 = (indx / 4) * 4;
pdata = buffer;
ret = ft1000_read_dpram32(ft1000dev, pos1, buf, 16);
if (ret == STATUS_SUCCESS) {
pos2 = (indx % 4)*4;
buf[pos2++] = *buffer++;
buf[pos2++] = *buffer++;
buf[pos2++] = *buffer++;
buf[pos2++] = *buffer++;
ret = ft1000_write_dpram32(ft1000dev, pos1, buf, 16);
} else {
DEBUG("fix_ft1000_write_dpram32: DPRAM32 Read failed\n");
return ret;
}
ret = ft1000_read_dpram32(ft1000dev, pos1, (u8 *)&resultbuffer[0], 16);
if (ret == STATUS_SUCCESS) {
buffer = pdata;
for (i = 0; i < 16; i++) {
if (buf[i] != resultbuffer[i])
ret = STATUS_FAILURE;
}
}
if (ret == STATUS_FAILURE) {
ret = ft1000_write_dpram32(ft1000dev, pos1,
(u8 *)&tempbuffer[0], 16);
ret = ft1000_read_dpram32(ft1000dev, pos1,
(u8 *)&resultbuffer[0], 16);
if (ret == STATUS_SUCCESS) {
buffer = pdata;
for (i = 0; i < 16; i++) {
if (tempbuffer[i] != resultbuffer[i]) {
ret = STATUS_FAILURE;
DEBUG("%s Failed to write\n",
__func__);
}
}
}
}
return ret;
}
//------------------------------------------------------------------------
//
// Function: card_reset_dsp
//
// Synopsis: This function is called to reset or activate the DSP
//
// Arguments: value - reset or activate
//
// Returns: None
//-----------------------------------------------------------------------
static void card_reset_dsp(struct ft1000_usb *ft1000dev, bool value)
{
u16 status = STATUS_SUCCESS;
u16 tempword;
status = ft1000_write_register(ft1000dev, HOST_INTF_BE,
FT1000_REG_SUP_CTRL);
status = ft1000_read_register(ft1000dev, &tempword,
FT1000_REG_SUP_CTRL);
if (value) {
DEBUG("Reset DSP\n");
status = ft1000_read_register(ft1000dev, &tempword,
FT1000_REG_RESET);
tempword |= DSP_RESET_BIT;
status = ft1000_write_register(ft1000dev, tempword,
FT1000_REG_RESET);
} else {
DEBUG("Activate DSP\n");
status = ft1000_read_register(ft1000dev, &tempword,
FT1000_REG_RESET);
tempword |= DSP_ENCRYPTED;
tempword &= ~DSP_UNENCRYPTED;
status = ft1000_write_register(ft1000dev, tempword,
FT1000_REG_RESET);
status = ft1000_read_register(ft1000dev, &tempword,
FT1000_REG_RESET);
tempword &= ~EFUSE_MEM_DISABLE;
tempword &= ~DSP_RESET_BIT;
status = ft1000_write_register(ft1000dev, tempword,
FT1000_REG_RESET);
status = ft1000_read_register(ft1000dev, &tempword,
FT1000_REG_RESET);
}
}
//---------------------------------------------------------------------------
// Function: card_send_command
//
// Parameters: ft1000_usb - device structure
// ptempbuffer - command buffer
// size - command buffer size
//
// Returns: STATUS_SUCCESS - success
// STATUS_FAILURE - failure
//
// Description: This function sends a command to ASIC
//
// Notes:
//
//---------------------------------------------------------------------------
void card_send_command(struct ft1000_usb *ft1000dev, void *ptempbuffer,
int size)
{
unsigned short temp;
unsigned char *commandbuf;
DEBUG("card_send_command: enter card_send_command... size=%d\n", size);
commandbuf = kmalloc(size + 2, GFP_KERNEL);
memcpy((void *)commandbuf + 2, (void *)ptempbuffer, size);
ft1000_read_register(ft1000dev, &temp, FT1000_REG_DOORBELL);
if (temp & 0x0100)
msleep(10);
/* check for odd word */
size = size + 2;
/* Must force to be 32 bit aligned */
if (size % 4)
size += 4 - (size % 4);
ft1000_write_dpram32(ft1000dev, 0, commandbuf, size);
msleep(1);
ft1000_write_register(ft1000dev, FT1000_DB_DPRAM_TX,
FT1000_REG_DOORBELL);
msleep(1);
ft1000_read_register(ft1000dev, &temp, FT1000_REG_DOORBELL);
if ((temp & 0x0100) == 0) {
//DEBUG("card_send_command: Message sent\n");
}
}
//--------------------------------------------------------------------------
//
// Function: dsp_reload
//
// Synopsis: This function is called to load or reload the DSP
//
// Arguments: ft1000dev - device structure
//
// Returns: None
//-----------------------------------------------------------------------
int dsp_reload(struct ft1000_usb *ft1000dev)
{
u16 status;
u16 tempword;
u32 templong;
struct ft1000_info *pft1000info;
pft1000info = netdev_priv(ft1000dev->net);
pft1000info->CardReady = 0;
/* Program Interrupt Mask register */
status = ft1000_write_register(ft1000dev, 0xffff, FT1000_REG_SUP_IMASK);
status = ft1000_read_register(ft1000dev, &tempword, FT1000_REG_RESET);
tempword |= ASIC_RESET_BIT;
status = ft1000_write_register(ft1000dev, tempword, FT1000_REG_RESET);
msleep(1000);
status = ft1000_read_register(ft1000dev, &tempword, FT1000_REG_RESET);
DEBUG("Reset Register = 0x%x\n", tempword);
/* Toggle DSP reset */
card_reset_dsp(ft1000dev, 1);
msleep(1000);
card_reset_dsp(ft1000dev, 0);
msleep(1000);
status =
ft1000_write_register(ft1000dev, HOST_INTF_BE, FT1000_REG_SUP_CTRL);
/* Let's check for FEFE */
status =
ft1000_read_dpram32(ft1000dev, FT1000_MAG_DPRAM_FEFE_INDX,
(u8 *) &templong, 4);
DEBUG("templong (fefe) = 0x%8x\n", templong);
/* call codeloader */
status = scram_dnldr(ft1000dev, pFileStart, FileLength);
if (status != STATUS_SUCCESS)
return -EIO;
msleep(1000);
DEBUG("dsp_reload returned\n");
return 0;
}
//---------------------------------------------------------------------------
//
// Function: ft1000_reset_asic
// Description: This function will call the Card Service function to reset the
// ASIC.
// Input:
// dev - device structure
// Output:
// none
//
//---------------------------------------------------------------------------
static void ft1000_reset_asic(struct net_device *dev)
{
struct ft1000_info *info = netdev_priv(dev);
struct ft1000_usb *ft1000dev = info->priv;
u16 tempword;
DEBUG("ft1000_hw:ft1000_reset_asic called\n");
/* Let's use the register provided by the Magnemite ASIC to reset the
* ASIC and DSP.
*/
ft1000_write_register(ft1000dev, (DSP_RESET_BIT | ASIC_RESET_BIT),
FT1000_REG_RESET);
mdelay(1);
/* set watermark to -1 in order to not generate an interrupt */
ft1000_write_register(ft1000dev, 0xffff, FT1000_REG_MAG_WATERMARK);
/* clear interrupts */
ft1000_read_register(ft1000dev, &tempword, FT1000_REG_SUP_ISR);
DEBUG("ft1000_hw: interrupt status register = 0x%x\n", tempword);
ft1000_write_register(ft1000dev, tempword, FT1000_REG_SUP_ISR);
ft1000_read_register(ft1000dev, &tempword, FT1000_REG_SUP_ISR);
DEBUG("ft1000_hw: interrupt status register = 0x%x\n", tempword);
}
//---------------------------------------------------------------------------
//
// Function: ft1000_reset_card
// Description: This function will reset the card
// Input:
// dev - device structure
// Output:
// status - FALSE (card reset fail)
// TRUE (card reset successful)
//
//---------------------------------------------------------------------------
static int ft1000_reset_card(struct net_device *dev)
{
struct ft1000_info *info = netdev_priv(dev);
struct ft1000_usb *ft1000dev = info->priv;
u16 tempword;
struct prov_record *ptr;
DEBUG("ft1000_hw:ft1000_reset_card called.....\n");
ft1000dev->fCondResetPend = 1;
info->CardReady = 0;
ft1000dev->fProvComplete = 0;
/* Make sure we free any memory reserve for provisioning */
while (list_empty(&info->prov_list) == 0) {
DEBUG("ft1000_reset_card:deleting provisioning record\n");
ptr =
list_entry(info->prov_list.next, struct prov_record, list);
list_del(&ptr->list);
kfree(ptr->pprov_data);
kfree(ptr);
}
DEBUG("ft1000_hw:ft1000_reset_card: reset asic\n");
ft1000_reset_asic(dev);
DEBUG("ft1000_hw:ft1000_reset_card: call dsp_reload\n");
dsp_reload(ft1000dev);
DEBUG("dsp reload successful\n");
mdelay(10);
/* Initialize DSP heartbeat area */
ft1000_write_dpram16(ft1000dev, FT1000_MAG_HI_HO, ho_mag,
FT1000_MAG_HI_HO_INDX);
ft1000_read_dpram16(ft1000dev, FT1000_MAG_HI_HO, (u8 *) &tempword,
FT1000_MAG_HI_HO_INDX);
DEBUG("ft1000_hw:ft1000_reset_card:hi_ho value = 0x%x\n", tempword);
info->CardReady = 1;
ft1000dev->fCondResetPend = 0;
return TRUE;
}
static const struct net_device_ops ftnet_ops =
{
.ndo_open = &ft1000_open,
.ndo_stop = &ft1000_close,
.ndo_start_xmit = &ft1000_start_xmit,
.ndo_get_stats = &ft1000_netdev_stats,
};
//---------------------------------------------------------------------------
// Function: init_ft1000_netdev
//
// Parameters: ft1000dev - device structure
//
//
// Returns: STATUS_SUCCESS - success
// STATUS_FAILURE - failure
//
// Description: This function initialize the network device
//
// Notes:
//
//---------------------------------------------------------------------------
int init_ft1000_netdev(struct ft1000_usb *ft1000dev)
{
struct net_device *netdev;
struct ft1000_info *pInfo = NULL;
struct dpram_blk *pdpram_blk;
int i, ret_val;
struct list_head *cur, *tmp;
char card_nr[2];
u8 gCardIndex = 0;
DEBUG("Enter init_ft1000_netdev...\n");
netdev = alloc_etherdev(sizeof(struct ft1000_info));
if (!netdev) {
DEBUG("init_ft1000_netdev: can not allocate network device\n");
return -ENOMEM;
}
pInfo = netdev_priv(netdev);
memset(pInfo, 0, sizeof(struct ft1000_info));
dev_alloc_name(netdev, netdev->name);
DEBUG("init_ft1000_netdev: network device name is %s\n", netdev->name);
if (strncmp(netdev->name, "eth", 3) == 0) {
card_nr[0] = netdev->name[3];
card_nr[1] = '\0';
ret_val = kstrtou8(card_nr, 10, &gCardIndex);
if (ret_val) {
printk(KERN_ERR "Can't parse netdev\n");
goto err_net;
}
ft1000dev->CardNumber = gCardIndex;
DEBUG("card number = %d\n", ft1000dev->CardNumber);
} else {
printk(KERN_ERR "ft1000: Invalid device name\n");
ret_val = -ENXIO;
goto err_net;
}
memset(&pInfo->stats, 0, sizeof(struct net_device_stats));
spin_lock_init(&pInfo->dpram_lock);
pInfo->priv = ft1000dev;
pInfo->DrvErrNum = 0;
pInfo->registered = 1;
pInfo->ft1000_reset = ft1000_reset;
pInfo->mediastate = 0;
pInfo->fifo_cnt = 0;
ft1000dev->DeviceCreated = FALSE;
pInfo->CardReady = 0;
pInfo->DSP_TIME[0] = 0;
pInfo->DSP_TIME[1] = 0;
pInfo->DSP_TIME[2] = 0;
pInfo->DSP_TIME[3] = 0;
ft1000dev->fAppMsgPend = 0;
ft1000dev->fCondResetPend = 0;
ft1000dev->usbboot = 0;
ft1000dev->dspalive = 0;
memset(&ft1000dev->tempbuf[0], 0, sizeof(ft1000dev->tempbuf));
INIT_LIST_HEAD(&pInfo->prov_list);
INIT_LIST_HEAD(&ft1000dev->nodes.list);
netdev->netdev_ops = &ftnet_ops;
ft1000dev->net = netdev;
DEBUG("Initialize free_buff_lock and freercvpool\n");
spin_lock_init(&free_buff_lock);
/* initialize a list of buffers to be use for queuing
* up receive command data
*/
INIT_LIST_HEAD(&freercvpool);
/* create list of free buffers */
for (i = 0; i < NUM_OF_FREE_BUFFERS; i++) {
/* Get memory for DPRAM_DATA link list */
pdpram_blk = kmalloc(sizeof(struct dpram_blk), GFP_KERNEL);
if (pdpram_blk == NULL) {
ret_val = -ENOMEM;
goto err_free;
}
/* Get a block of memory to store command data */
pdpram_blk->pbuffer = kmalloc(MAX_CMD_SQSIZE, GFP_KERNEL);
if (pdpram_blk->pbuffer == NULL) {
ret_val = -ENOMEM;
kfree(pdpram_blk);
goto err_free;
}
/* link provisioning data */
list_add_tail(&pdpram_blk->list, &freercvpool);
}
numofmsgbuf = NUM_OF_FREE_BUFFERS;
return 0;
err_free:
list_for_each_safe(cur, tmp, &freercvpool) {
pdpram_blk = list_entry(cur, struct dpram_blk, list);
list_del(&pdpram_blk->list);
kfree(pdpram_blk->pbuffer);
kfree(pdpram_blk);
}
err_net:
free_netdev(netdev);
return ret_val;
}
//---------------------------------------------------------------------------
// Function: reg_ft1000_netdev
//
// Parameters: ft1000dev - device structure
//
//
// Returns: STATUS_SUCCESS - success
// STATUS_FAILURE - failure
//
// Description: This function register the network driver
//
// Notes:
//
//---------------------------------------------------------------------------
int reg_ft1000_netdev(struct ft1000_usb *ft1000dev,
struct usb_interface *intf)
{
struct net_device *netdev;
struct ft1000_info *pInfo;
int rc;
netdev = ft1000dev->net;
pInfo = netdev_priv(ft1000dev->net);
DEBUG("Enter reg_ft1000_netdev...\n");
ft1000_read_register(ft1000dev, &pInfo->AsicID, FT1000_REG_ASIC_ID);
usb_set_intfdata(intf, pInfo);
SET_NETDEV_DEV(netdev, &intf->dev);
rc = register_netdev(netdev);
if (rc) {
DEBUG("reg_ft1000_netdev: could not register network device\n");
free_netdev(netdev);
return rc;
}
ft1000_create_dev(ft1000dev);
DEBUG("reg_ft1000_netdev returned\n");
pInfo->CardReady = 1;
return 0;
}
int ft1000_reset(void *dev)
{
ft1000_reset_card(dev);
return 0;
}
//---------------------------------------------------------------------------
// Function: ft1000_usb_transmit_complete
//
// Parameters: urb - transmitted usb urb
//
//
// Returns: none
//
// Description: This is the callback function when a urb is transmitted
//
// Notes:
//
//---------------------------------------------------------------------------
static void ft1000_usb_transmit_complete(struct urb *urb)
{
struct ft1000_usb *ft1000dev = urb->context;
if (urb->status)
pr_err("%s: TX status %d\n", ft1000dev->net->name, urb->status);
netif_wake_queue(ft1000dev->net);
}
//---------------------------------------------------------------------------
//
// Function: ft1000_copy_down_pkt
// Description: This function will take an ethernet packet and convert it to
// a Flarion packet prior to sending it to the ASIC Downlink
// FIFO.
// Input:
// dev - device structure
// packet - address of ethernet packet
// len - length of IP packet
// Output:
// status - FAILURE
// SUCCESS
//
//---------------------------------------------------------------------------
static int ft1000_copy_down_pkt(struct net_device *netdev, u8 * packet, u16 len)
{
struct ft1000_info *pInfo = netdev_priv(netdev);
struct ft1000_usb *pFt1000Dev = pInfo->priv;
int count, ret;
u8 *t;
struct pseudo_hdr hdr;
if (!pInfo->CardReady) {
DEBUG("ft1000_copy_down_pkt::Card Not Ready\n");
return -ENODEV;
}
count = sizeof(struct pseudo_hdr) + len;
if (count > MAX_BUF_SIZE) {
DEBUG("Error:ft1000_copy_down_pkt:Message Size Overflow!\n");
DEBUG("size = %d\n", count);
return -EINVAL;
}
if (count % 4)
count = count + (4 - (count % 4));
memset(&hdr, 0, sizeof(struct pseudo_hdr));
hdr.length = ntohs(count);
hdr.source = 0x10;
hdr.destination = 0x20;
hdr.portdest = 0x20;
hdr.portsrc = 0x10;
hdr.sh_str_id = 0x91;
hdr.control = 0x00;
hdr.checksum = hdr.length ^ hdr.source ^ hdr.destination ^
hdr.portdest ^ hdr.portsrc ^ hdr.sh_str_id ^ hdr.control;
memcpy(&pFt1000Dev->tx_buf[0], &hdr, sizeof(hdr));
memcpy(&(pFt1000Dev->tx_buf[sizeof(struct pseudo_hdr)]), packet, len);
netif_stop_queue(netdev);
usb_fill_bulk_urb(pFt1000Dev->tx_urb,
pFt1000Dev->dev,
usb_sndbulkpipe(pFt1000Dev->dev,
pFt1000Dev->bulk_out_endpointAddr),
pFt1000Dev->tx_buf, count,
ft1000_usb_transmit_complete, (void *)pFt1000Dev);
t = (u8 *) pFt1000Dev->tx_urb->transfer_buffer;
ret = usb_submit_urb(pFt1000Dev->tx_urb, GFP_ATOMIC);
if (ret) {
DEBUG("ft1000 failed tx_urb %d\n", ret);
return ret;
} else {
pInfo->stats.tx_packets++;
pInfo->stats.tx_bytes += (len + 14);
}
return 0;
}
//---------------------------------------------------------------------------
// Function: ft1000_start_xmit
//
// Parameters: skb - socket buffer to be sent
// dev - network device
//
//
// Returns: none
//
// Description: transmit a ethernet packet
//
// Notes:
//
//---------------------------------------------------------------------------
static int ft1000_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct ft1000_info *pInfo = netdev_priv(dev);
struct ft1000_usb *pFt1000Dev = pInfo->priv;
u8 *pdata;
int maxlen, pipe;
if (skb == NULL) {
DEBUG("ft1000_hw: ft1000_start_xmit:skb == NULL!!!\n");
return NETDEV_TX_OK;
}
if (pFt1000Dev->status & FT1000_STATUS_CLOSING) {
DEBUG("network driver is closed, return\n");
goto err;
}
pipe =
usb_sndbulkpipe(pFt1000Dev->dev, pFt1000Dev->bulk_out_endpointAddr);
maxlen = usb_maxpacket(pFt1000Dev->dev, pipe, usb_pipeout(pipe));
pdata = (u8 *) skb->data;
if (pInfo->mediastate == 0) {
/* Drop packet is mediastate is down */
DEBUG("ft1000_hw:ft1000_start_xmit:mediastate is down\n");
goto err;
}
if ((skb->len < ENET_HEADER_SIZE) || (skb->len > ENET_MAX_SIZE)) {
/* Drop packet which has invalid size */
DEBUG("ft1000_hw:ft1000_start_xmit:invalid ethernet length\n");
goto err;
}
ft1000_copy_down_pkt(dev, (pdata + ENET_HEADER_SIZE - 2),
skb->len - ENET_HEADER_SIZE + 2);
err:
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
//---------------------------------------------------------------------------
//
// Function: ft1000_copy_up_pkt
// Description: This function will take a packet from the FIFO up link and
// convert it into an ethernet packet and deliver it to the IP stack
// Input:
// urb - the receiving usb urb
//
// Output:
// status - FAILURE
// SUCCESS
//
//---------------------------------------------------------------------------
static int ft1000_copy_up_pkt(struct urb *urb)
{
struct ft1000_info *info = urb->context;
struct ft1000_usb *ft1000dev = info->priv;
struct net_device *net = ft1000dev->net;
u16 tempword;
u16 len;
u16 lena;
struct sk_buff *skb;
u16 i;
u8 *pbuffer = NULL;
u8 *ptemp = NULL;
u16 *chksum;
if (ft1000dev->status & FT1000_STATUS_CLOSING) {
DEBUG("network driver is closed, return\n");
return STATUS_SUCCESS;
}
// Read length
len = urb->transfer_buffer_length;
lena = urb->actual_length;
chksum = (u16 *) ft1000dev->rx_buf;
tempword = *chksum++;
for (i = 1; i < 7; i++)
tempword ^= *chksum++;
if (tempword != *chksum) {
info->stats.rx_errors++;
ft1000_submit_rx_urb(info);
return STATUS_FAILURE;
}
skb = dev_alloc_skb(len + 12 + 2);
if (skb == NULL) {
DEBUG("ft1000_copy_up_pkt: No Network buffers available\n");
info->stats.rx_errors++;
ft1000_submit_rx_urb(info);
return STATUS_FAILURE;
}
pbuffer = (u8 *) skb_put(skb, len + 12);
/* subtract the number of bytes read already */
ptemp = pbuffer;
/* fake MAC address */
*pbuffer++ = net->dev_addr[0];
*pbuffer++ = net->dev_addr[1];
*pbuffer++ = net->dev_addr[2];
*pbuffer++ = net->dev_addr[3];
*pbuffer++ = net->dev_addr[4];
*pbuffer++ = net->dev_addr[5];
*pbuffer++ = 0x00;
*pbuffer++ = 0x07;
*pbuffer++ = 0x35;
*pbuffer++ = 0xff;
*pbuffer++ = 0xff;
*pbuffer++ = 0xfe;
memcpy(pbuffer, ft1000dev->rx_buf + sizeof(struct pseudo_hdr),
len - sizeof(struct pseudo_hdr));
skb->dev = net;
skb->protocol = eth_type_trans(skb, net);
skb->ip_summed = CHECKSUM_UNNECESSARY;
netif_rx(skb);
info->stats.rx_packets++;
/* Add on 12 bytes for MAC address which was removed */
info->stats.rx_bytes += (lena + 12);
ft1000_submit_rx_urb(info);
return SUCCESS;
}
//---------------------------------------------------------------------------
//
// Function: ft1000_submit_rx_urb
// Description: the receiving function of the network driver
//
// Input:
// info - a private structure contains the device information
//
// Output:
// status - FAILURE
// SUCCESS
//
//---------------------------------------------------------------------------
static int ft1000_submit_rx_urb(struct ft1000_info *info)
{
int result;
struct ft1000_usb *pFt1000Dev = info->priv;
if (pFt1000Dev->status & FT1000_STATUS_CLOSING) {
DEBUG("network driver is closed, return\n");
return -ENODEV;
}
usb_fill_bulk_urb(pFt1000Dev->rx_urb,
pFt1000Dev->dev,
usb_rcvbulkpipe(pFt1000Dev->dev,
pFt1000Dev->bulk_in_endpointAddr),
pFt1000Dev->rx_buf, MAX_BUF_SIZE,
(usb_complete_t) ft1000_copy_up_pkt, info);
result = usb_submit_urb(pFt1000Dev->rx_urb, GFP_ATOMIC);
if (result) {
pr_err("ft1000_submit_rx_urb: submitting rx_urb %d failed\n",
result);
return result;
}
return 0;
}
//---------------------------------------------------------------------------
// Function: ft1000_open
//
// Parameters:
// dev - network device
//
//
// Returns: none
//
// Description: open the network driver
//
// Notes:
//
//---------------------------------------------------------------------------
static int ft1000_open(struct net_device *dev)
{
struct ft1000_info *pInfo = netdev_priv(dev);
struct ft1000_usb *pFt1000Dev = pInfo->priv;
struct timeval tv;
DEBUG("ft1000_open is called for card %d\n", pFt1000Dev->CardNumber);
pInfo->stats.rx_bytes = 0;
pInfo->stats.tx_bytes = 0;
pInfo->stats.rx_packets = 0;
pInfo->stats.tx_packets = 0;
do_gettimeofday(&tv);
pInfo->ConTm = tv.tv_sec;
pInfo->ProgConStat = 0;
netif_start_queue(dev);
netif_carrier_on(dev);
return ft1000_submit_rx_urb(pInfo);
}
//---------------------------------------------------------------------------
// Function: ft1000_close
//
// Parameters:
// net - network device
//
//
// Returns: none
//
// Description: close the network driver
//
// Notes:
//
//---------------------------------------------------------------------------
int ft1000_close(struct net_device *net)
{
struct ft1000_info *pInfo = netdev_priv(net);
struct ft1000_usb *ft1000dev = pInfo->priv;
ft1000dev->status |= FT1000_STATUS_CLOSING;
DEBUG("ft1000_close: pInfo=%p, ft1000dev=%p\n", pInfo, ft1000dev);
netif_carrier_off(net);
netif_stop_queue(net);
ft1000dev->status &= ~FT1000_STATUS_CLOSING;
pInfo->ProgConStat = 0xff;
return 0;
}
static struct net_device_stats *ft1000_netdev_stats(struct net_device *dev)
{
struct ft1000_info *info = netdev_priv(dev);
return &(info->stats);
}
//---------------------------------------------------------------------------
//
// Function: ft1000_chkcard
// Description: This function will check if the device is presently available on
// the system.
// Input:
// dev - device structure
// Output:
// status - FALSE (device is not present)
// TRUE (device is present)
//
//---------------------------------------------------------------------------
static int ft1000_chkcard(struct ft1000_usb *dev)
{
u16 tempword;
u16 status;
if (dev->fCondResetPend) {
DEBUG
("ft1000_hw:ft1000_chkcard:Card is being reset, return FALSE\n");
return TRUE;
}
/* Mask register is used to check for device presence since it is never
* set to zero.
*/
status = ft1000_read_register(dev, &tempword, FT1000_REG_SUP_IMASK);
if (tempword == 0) {
DEBUG
("ft1000_hw:ft1000_chkcard: IMASK = 0 Card not detected\n");
return FALSE;
}
/* The system will return the value of 0xffff for the version register
* if the device is not present.
*/
status = ft1000_read_register(dev, &tempword, FT1000_REG_ASIC_ID);
if (tempword != 0x1b01) {
dev->status |= FT1000_STATUS_CLOSING;
DEBUG
("ft1000_hw:ft1000_chkcard: Version = 0xffff Card not detected\n");
return FALSE;
}
return TRUE;
}
//---------------------------------------------------------------------------
//
// Function: ft1000_receive_cmd
// Description: This function will read a message from the dpram area.
// Input:
// dev - network device structure
// pbuffer - caller supply address to buffer
// pnxtph - pointer to next pseudo header
// Output:
// Status = 0 (unsuccessful)
// = 1 (successful)
//
//---------------------------------------------------------------------------
static bool ft1000_receive_cmd(struct ft1000_usb *dev, u16 *pbuffer,
int maxsz, u16 *pnxtph)
{
u16 size, ret;
u16 *ppseudohdr;
int i;
u16 tempword;
ret =
ft1000_read_dpram16(dev, FT1000_MAG_PH_LEN, (u8 *) &size,
FT1000_MAG_PH_LEN_INDX);
size = ntohs(size) + PSEUDOSZ;
if (size > maxsz) {
DEBUG("FT1000:ft1000_receive_cmd:Invalid command length = %d\n",
size);
return FALSE;
} else {
ppseudohdr = (u16 *) pbuffer;
ft1000_write_register(dev, FT1000_DPRAM_MAG_RX_BASE,
FT1000_REG_DPRAM_ADDR);
ret =
ft1000_read_register(dev, pbuffer, FT1000_REG_MAG_DPDATAH);
pbuffer++;
ft1000_write_register(dev, FT1000_DPRAM_MAG_RX_BASE + 1,
FT1000_REG_DPRAM_ADDR);
for (i = 0; i <= (size >> 2); i++) {
ret =
ft1000_read_register(dev, pbuffer,
FT1000_REG_MAG_DPDATAL);
pbuffer++;
ret =
ft1000_read_register(dev, pbuffer,
FT1000_REG_MAG_DPDATAH);
pbuffer++;
}
/* copy odd aligned word */
ret =
ft1000_read_register(dev, pbuffer, FT1000_REG_MAG_DPDATAL);
pbuffer++;
ret =
ft1000_read_register(dev, pbuffer, FT1000_REG_MAG_DPDATAH);
pbuffer++;
if (size & 0x0001) {
/* copy odd byte from fifo */
ret =
ft1000_read_register(dev, &tempword,
FT1000_REG_DPRAM_DATA);
*pbuffer = ntohs(tempword);
}
/* Check if pseudo header checksum is good
* Calculate pseudo header checksum
*/
tempword = *ppseudohdr++;
for (i = 1; i < 7; i++)
tempword ^= *ppseudohdr++;
if ((tempword != *ppseudohdr))
return FALSE;
return TRUE;
}
}
static int ft1000_dsp_prov(void *arg)
{
struct ft1000_usb *dev = (struct ft1000_usb *)arg;
struct ft1000_info *info = netdev_priv(dev->net);
u16 tempword;
u16 len;
u16 i = 0;
struct prov_record *ptr;
struct pseudo_hdr *ppseudo_hdr;
u16 *pmsg;
u16 status;
u16 TempShortBuf[256];
DEBUG("*** DspProv Entered\n");
while (list_empty(&info->prov_list) == 0) {
DEBUG("DSP Provisioning List Entry\n");
/* Check if doorbell is available */
DEBUG("check if doorbell is cleared\n");
status =
ft1000_read_register(dev, &tempword, FT1000_REG_DOORBELL);
if (status) {
DEBUG("ft1000_dsp_prov::ft1000_read_register error\n");
break;
}
while (tempword & FT1000_DB_DPRAM_TX) {
mdelay(10);
i++;
if (i == 10) {
DEBUG("FT1000:ft1000_dsp_prov:message drop\n");
return STATUS_FAILURE;
}
ft1000_read_register(dev, &tempword,
FT1000_REG_DOORBELL);
}
if (!(tempword & FT1000_DB_DPRAM_TX)) {
DEBUG("*** Provision Data Sent to DSP\n");
/* Send provisioning data */
ptr =
list_entry(info->prov_list.next, struct prov_record,
list);
len = *(u16 *) ptr->pprov_data;
len = htons(len);
len += PSEUDOSZ;
pmsg = (u16 *) ptr->pprov_data;
ppseudo_hdr = (struct pseudo_hdr *)pmsg;
/* Insert slow queue sequence number */
ppseudo_hdr->seq_num = info->squeseqnum++;
ppseudo_hdr->portsrc = 0;
/* Calculate new checksum */
ppseudo_hdr->checksum = *pmsg++;
for (i = 1; i < 7; i++) {
ppseudo_hdr->checksum ^= *pmsg++;
}
TempShortBuf[0] = 0;
TempShortBuf[1] = htons(len);
memcpy(&TempShortBuf[2], ppseudo_hdr, len);
status =
ft1000_write_dpram32(dev, 0,
(u8 *) &TempShortBuf[0],
(unsigned short)(len + 2));
status =
ft1000_write_register(dev, FT1000_DB_DPRAM_TX,
FT1000_REG_DOORBELL);
list_del(&ptr->list);
kfree(ptr->pprov_data);
kfree(ptr);
}
msleep(10);
}
DEBUG("DSP Provisioning List Entry finished\n");
msleep(100);
dev->fProvComplete = 1;
info->CardReady = 1;
return STATUS_SUCCESS;
}
static int ft1000_proc_drvmsg(struct ft1000_usb *dev, u16 size)
{
struct ft1000_info *info = netdev_priv(dev->net);
u16 msgtype;
u16 tempword;
struct media_msg *pmediamsg;
struct dsp_init_msg *pdspinitmsg;
struct drv_msg *pdrvmsg;
u16 i;
struct pseudo_hdr *ppseudo_hdr;
u16 *pmsg;
u16 status;
union {
u8 byte[2];
u16 wrd;
} convert;
char *cmdbuffer = kmalloc(1600, GFP_KERNEL);
if (!cmdbuffer)
return STATUS_FAILURE;
status = ft1000_read_dpram32(dev, 0x200, cmdbuffer, size);
#ifdef JDEBUG
DEBUG("ft1000_proc_drvmsg:cmdbuffer\n");
for (i = 0; i < size; i += 5) {
if ((i + 5) < size)
DEBUG("0x%x, 0x%x, 0x%x, 0x%x, 0x%x\n", cmdbuffer[i],
cmdbuffer[i + 1], cmdbuffer[i + 2],
cmdbuffer[i + 3], cmdbuffer[i + 4]);
else {
for (j = i; j < size; j++)
DEBUG("0x%x ", cmdbuffer[j]);
DEBUG("\n");
break;
}
}
#endif
pdrvmsg = (struct drv_msg *)&cmdbuffer[2];
msgtype = ntohs(pdrvmsg->type);
DEBUG("ft1000_proc_drvmsg:Command message type = 0x%x\n", msgtype);
switch (msgtype) {
case MEDIA_STATE:{
DEBUG
("ft1000_proc_drvmsg:Command message type = MEDIA_STATE");
pmediamsg = (struct media_msg *)&cmdbuffer[0];
if (info->ProgConStat != 0xFF) {
if (pmediamsg->state) {
DEBUG("Media is up\n");
if (info->mediastate == 0) {
if (dev->NetDevRegDone) {
netif_wake_queue(dev->
net);
}
info->mediastate = 1;
}
} else {
DEBUG("Media is down\n");
if (info->mediastate == 1) {
info->mediastate = 0;
if (dev->NetDevRegDone) {
}
info->ConTm = 0;
}
}
} else {
DEBUG("Media is down\n");
if (info->mediastate == 1) {
info->mediastate = 0;
info->ConTm = 0;
}
}
break;
}
case DSP_INIT_MSG:{
DEBUG
("ft1000_proc_drvmsg:Command message type = DSP_INIT_MSG");
pdspinitmsg = (struct dsp_init_msg *)&cmdbuffer[2];
memcpy(info->DspVer, pdspinitmsg->DspVer, DSPVERSZ);
DEBUG("DSPVER = 0x%2x 0x%2x 0x%2x 0x%2x\n",
info->DspVer[0], info->DspVer[1], info->DspVer[2],
info->DspVer[3]);
memcpy(info->HwSerNum, pdspinitmsg->HwSerNum,
HWSERNUMSZ);
memcpy(info->Sku, pdspinitmsg->Sku, SKUSZ);
memcpy(info->eui64, pdspinitmsg->eui64, EUISZ);
DEBUG("EUI64=%2x.%2x.%2x.%2x.%2x.%2x.%2x.%2x\n",
info->eui64[0], info->eui64[1], info->eui64[2],
info->eui64[3], info->eui64[4], info->eui64[5],
info->eui64[6], info->eui64[7]);
dev->net->dev_addr[0] = info->eui64[0];
dev->net->dev_addr[1] = info->eui64[1];
dev->net->dev_addr[2] = info->eui64[2];
dev->net->dev_addr[3] = info->eui64[5];
dev->net->dev_addr[4] = info->eui64[6];
dev->net->dev_addr[5] = info->eui64[7];
if (ntohs(pdspinitmsg->length) ==
(sizeof(struct dsp_init_msg) - 20)) {
memcpy(info->ProductMode,
pdspinitmsg->ProductMode, MODESZ);
memcpy(info->RfCalVer, pdspinitmsg->RfCalVer,
CALVERSZ);
memcpy(info->RfCalDate, pdspinitmsg->RfCalDate,
CALDATESZ);
DEBUG("RFCalVer = 0x%2x 0x%2x\n",
info->RfCalVer[0], info->RfCalVer[1]);
}
break;
}
case DSP_PROVISION:{
DEBUG
("ft1000_proc_drvmsg:Command message type = DSP_PROVISION\n");
/* kick off dspprov routine to start provisioning
* Send provisioning data to DSP
*/
if (list_empty(&info->prov_list) == 0) {
dev->fProvComplete = 0;
status = ft1000_dsp_prov(dev);
if (status != STATUS_SUCCESS)
goto out;
} else {
dev->fProvComplete = 1;
status =
ft1000_write_register(dev, FT1000_DB_HB,
FT1000_REG_DOORBELL);
DEBUG
("FT1000:drivermsg:No more DSP provisioning data in dsp image\n");
}
DEBUG("ft1000_proc_drvmsg:DSP PROVISION is done\n");
break;
}
case DSP_STORE_INFO:{
DEBUG
("ft1000_proc_drvmsg:Command message type = DSP_STORE_INFO");
DEBUG("FT1000:drivermsg:Got DSP_STORE_INFO\n");
tempword = ntohs(pdrvmsg->length);
info->DSPInfoBlklen = tempword;
if (tempword < (MAX_DSP_SESS_REC - 4)) {
pmsg = (u16 *) &pdrvmsg->data[0];
for (i = 0; i < ((tempword + 1) / 2); i++) {
DEBUG
("FT1000:drivermsg:dsp info data = 0x%x\n",
*pmsg);
info->DSPInfoBlk[i + 10] = *pmsg++;
}
} else {
info->DSPInfoBlklen = 0;
}
break;
}
case DSP_GET_INFO:{
DEBUG("FT1000:drivermsg:Got DSP_GET_INFO\n");
/* copy dsp info block to dsp */
dev->DrvMsgPend = 1;
/* allow any outstanding ioctl to finish */
mdelay(10);
status =
ft1000_read_register(dev, &tempword,
FT1000_REG_DOORBELL);
if (tempword & FT1000_DB_DPRAM_TX) {
mdelay(10);
status =
ft1000_read_register(dev, &tempword,
FT1000_REG_DOORBELL);
if (tempword & FT1000_DB_DPRAM_TX) {
mdelay(10);
status =
ft1000_read_register(dev, &tempword,
FT1000_REG_DOORBELL);
if (tempword & FT1000_DB_DPRAM_TX)
break;
}
}
/* Put message into Slow Queue
* Form Pseudo header
*/
pmsg = (u16 *) info->DSPInfoBlk;
*pmsg++ = 0;
*pmsg++ =
htons(info->DSPInfoBlklen + 20 +
info->DSPInfoBlklen);
ppseudo_hdr =
(struct pseudo_hdr *)(u16 *) &info->DSPInfoBlk[2];
ppseudo_hdr->length =
htons(info->DSPInfoBlklen + 4 +
info->DSPInfoBlklen);
ppseudo_hdr->source = 0x10;
ppseudo_hdr->destination = 0x20;
ppseudo_hdr->portdest = 0;
ppseudo_hdr->portsrc = 0;
ppseudo_hdr->sh_str_id = 0;
ppseudo_hdr->control = 0;
ppseudo_hdr->rsvd1 = 0;
ppseudo_hdr->rsvd2 = 0;
ppseudo_hdr->qos_class = 0;
/* Insert slow queue sequence number */
ppseudo_hdr->seq_num = info->squeseqnum++;
/* Insert application id */
ppseudo_hdr->portsrc = 0;
/* Calculate new checksum */
ppseudo_hdr->checksum = *pmsg++;
for (i = 1; i < 7; i++)
ppseudo_hdr->checksum ^= *pmsg++;
info->DSPInfoBlk[10] = 0x7200;
info->DSPInfoBlk[11] = htons(info->DSPInfoBlklen);
status =
ft1000_write_dpram32(dev, 0,
(u8 *) &info->DSPInfoBlk[0],
(unsigned short)(info->
DSPInfoBlklen
+ 22));
status =
ft1000_write_register(dev, FT1000_DB_DPRAM_TX,
FT1000_REG_DOORBELL);
dev->DrvMsgPend = 0;
break;
}
case GET_DRV_ERR_RPT_MSG:{
DEBUG("FT1000:drivermsg:Got GET_DRV_ERR_RPT_MSG\n");
/* copy driver error message to dsp */
dev->DrvMsgPend = 1;
/* allow any outstanding ioctl to finish */
mdelay(10);
status =
ft1000_read_register(dev, &tempword,
FT1000_REG_DOORBELL);
if (tempword & FT1000_DB_DPRAM_TX) {
mdelay(10);
status =
ft1000_read_register(dev, &tempword,
FT1000_REG_DOORBELL);
if (tempword & FT1000_DB_DPRAM_TX)
mdelay(10);
}
if ((tempword & FT1000_DB_DPRAM_TX) == 0) {
/* Put message into Slow Queue
* Form Pseudo header
*/
pmsg = (u16 *) &tempbuffer[0];
ppseudo_hdr = (struct pseudo_hdr *)pmsg;
ppseudo_hdr->length = htons(0x0012);
ppseudo_hdr->source = 0x10;
ppseudo_hdr->destination = 0x20;
ppseudo_hdr->portdest = 0;
ppseudo_hdr->portsrc = 0;
ppseudo_hdr->sh_str_id = 0;
ppseudo_hdr->control = 0;
ppseudo_hdr->rsvd1 = 0;
ppseudo_hdr->rsvd2 = 0;
ppseudo_hdr->qos_class = 0;
/* Insert slow queue sequence number */
ppseudo_hdr->seq_num = info->squeseqnum++;
/* Insert application id */
ppseudo_hdr->portsrc = 0;
/* Calculate new checksum */
ppseudo_hdr->checksum = *pmsg++;
for (i = 1; i < 7; i++)
ppseudo_hdr->checksum ^= *pmsg++;
pmsg = (u16 *) &tempbuffer[16];
*pmsg++ = htons(RSP_DRV_ERR_RPT_MSG);
*pmsg++ = htons(0x000e);
*pmsg++ = htons(info->DSP_TIME[0]);
*pmsg++ = htons(info->DSP_TIME[1]);
*pmsg++ = htons(info->DSP_TIME[2]);
*pmsg++ = htons(info->DSP_TIME[3]);
convert.byte[0] = info->DspVer[0];
convert.byte[1] = info->DspVer[1];
*pmsg++ = convert.wrd;
convert.byte[0] = info->DspVer[2];
convert.byte[1] = info->DspVer[3];
*pmsg++ = convert.wrd;
*pmsg++ = htons(info->DrvErrNum);
card_send_command(dev,
(unsigned char *)&tempbuffer[0],
(u16) (0x0012 + PSEUDOSZ));
info->DrvErrNum = 0;
}
dev->DrvMsgPend = 0;
break;
}
default:
break;
}
status = STATUS_SUCCESS;
out:
kfree(cmdbuffer);
DEBUG("return from ft1000_proc_drvmsg\n");
return status;
}
int ft1000_poll(void* dev_id)
{
struct ft1000_usb *dev = (struct ft1000_usb *)dev_id;
struct ft1000_info *info = netdev_priv(dev->net);
u16 tempword;
u16 status;
u16 size;
int i;
u16 data;
u16 modulo;
u16 portid;
u16 nxtph;
struct dpram_blk *pdpram_blk;
struct pseudo_hdr *ppseudo_hdr;
unsigned long flags;
if (ft1000_chkcard(dev) == FALSE) {
DEBUG("ft1000_poll::ft1000_chkcard: failed\n");
return STATUS_FAILURE;
}
status = ft1000_read_register (dev, &tempword, FT1000_REG_DOORBELL);
if ( !status )
{
if (tempword & FT1000_DB_DPRAM_RX) {
status = ft1000_read_dpram16(dev, 0x200, (u8 *)&data, 0);
size = ntohs(data) + 16 + 2;
if (size % 4) {
modulo = 4 - (size % 4);
size = size + modulo;
}
status = ft1000_read_dpram16(dev, 0x201, (u8 *)&portid, 1);
portid &= 0xff;
if (size < MAX_CMD_SQSIZE) {
switch (portid)
{
case DRIVERID:
DEBUG("ft1000_poll: FT1000_REG_DOORBELL message type: FT1000_DB_DPRAM_RX : portid DRIVERID\n");
status = ft1000_proc_drvmsg (dev, size);
if (status != STATUS_SUCCESS )
return status;
break;
case DSPBCMSGID:
// This is a dsp broadcast message
// Check which application has registered for dsp broadcast messages
for (i=0; i<MAX_NUM_APP; i++) {
if ( (dev->app_info[i].DspBCMsgFlag) && (dev->app_info[i].fileobject) &&
(dev->app_info[i].NumOfMsg < MAX_MSG_LIMIT) )
{
nxtph = FT1000_DPRAM_RX_BASE + 2;
pdpram_blk = ft1000_get_buffer (&freercvpool);
if (pdpram_blk != NULL) {
if ( ft1000_receive_cmd(dev, pdpram_blk->pbuffer, MAX_CMD_SQSIZE, &nxtph) ) {
ppseudo_hdr = (struct pseudo_hdr *)pdpram_blk->pbuffer;
// Put message into the appropriate application block
dev->app_info[i].nRxMsg++;
spin_lock_irqsave(&free_buff_lock, flags);
list_add_tail(&pdpram_blk->list, &dev->app_info[i].app_sqlist);
dev->app_info[i].NumOfMsg++;
spin_unlock_irqrestore(&free_buff_lock, flags);
wake_up_interruptible(&dev->app_info[i].wait_dpram_msg);
}
else {
dev->app_info[i].nRxMsgMiss++;
// Put memory back to free pool
ft1000_free_buffer(pdpram_blk, &freercvpool);
DEBUG("pdpram_blk::ft1000_get_buffer NULL\n");
}
}
else {
DEBUG("Out of memory in free receive command pool\n");
dev->app_info[i].nRxMsgMiss++;
}
}
}
break;
default:
pdpram_blk = ft1000_get_buffer (&freercvpool);
if (pdpram_blk != NULL) {
if ( ft1000_receive_cmd(dev, pdpram_blk->pbuffer, MAX_CMD_SQSIZE, &nxtph) ) {
ppseudo_hdr = (struct pseudo_hdr *)pdpram_blk->pbuffer;
// Search for correct application block
for (i=0; i<MAX_NUM_APP; i++) {
if (dev->app_info[i].app_id == ppseudo_hdr->portdest) {
break;
}
}
if (i == MAX_NUM_APP) {
DEBUG("FT1000:ft1000_parse_dpram_msg: No application matching id = %d\n", ppseudo_hdr->portdest);
// Put memory back to free pool
ft1000_free_buffer(pdpram_blk, &freercvpool);
}
else {
if (dev->app_info[i].NumOfMsg > MAX_MSG_LIMIT) {
// Put memory back to free pool
ft1000_free_buffer(pdpram_blk, &freercvpool);
}
else {
dev->app_info[i].nRxMsg++;
// Put message into the appropriate application block
list_add_tail(&pdpram_blk->list, &dev->app_info[i].app_sqlist);
dev->app_info[i].NumOfMsg++;
}
}
}
else {
// Put memory back to free pool
ft1000_free_buffer(pdpram_blk, &freercvpool);
}
}
else {
DEBUG("Out of memory in free receive command pool\n");
}
break;
}
}
else {
DEBUG("FT1000:dpc:Invalid total length for SlowQ = %d\n", size);
}
status = ft1000_write_register (dev, FT1000_DB_DPRAM_RX, FT1000_REG_DOORBELL);
}
else if (tempword & FT1000_DSP_ASIC_RESET) {
// Let's reset the ASIC from the Host side as well
status = ft1000_write_register (dev, ASIC_RESET_BIT, FT1000_REG_RESET);
status = ft1000_read_register (dev, &tempword, FT1000_REG_RESET);
i = 0;
while (tempword & ASIC_RESET_BIT) {
status = ft1000_read_register (dev, &tempword, FT1000_REG_RESET);
msleep(10);
i++;
if (i==100)
break;
}
if (i==100) {
DEBUG("Unable to reset ASIC\n");
return STATUS_SUCCESS;
}
msleep(10);
// Program WMARK register
status = ft1000_write_register (dev, 0x600, FT1000_REG_MAG_WATERMARK);
// clear ASIC reset doorbell
status = ft1000_write_register (dev, FT1000_DSP_ASIC_RESET, FT1000_REG_DOORBELL);
msleep(10);
}
else if (tempword & FT1000_ASIC_RESET_REQ) {
DEBUG("ft1000_poll: FT1000_REG_DOORBELL message type: FT1000_ASIC_RESET_REQ\n");
// clear ASIC reset request from DSP
status = ft1000_write_register (dev, FT1000_ASIC_RESET_REQ, FT1000_REG_DOORBELL);
status = ft1000_write_register (dev, HOST_INTF_BE, FT1000_REG_SUP_CTRL);
// copy dsp session record from Adapter block
status = ft1000_write_dpram32 (dev, 0, (u8 *)&info->DSPSess.Rec[0], 1024);
// Program WMARK register
status = ft1000_write_register (dev, 0x600, FT1000_REG_MAG_WATERMARK);
// ring doorbell to tell DSP that ASIC is out of reset
status = ft1000_write_register (dev, FT1000_ASIC_RESET_DSP, FT1000_REG_DOORBELL);
}
else if (tempword & FT1000_DB_COND_RESET) {
DEBUG("ft1000_poll: FT1000_REG_DOORBELL message type: FT1000_DB_COND_RESET\n");
if (dev->fAppMsgPend == 0) {
// Reset ASIC and DSP
status = ft1000_read_dpram16(dev, FT1000_MAG_DSP_TIMER0, (u8 *)&(info->DSP_TIME[0]), FT1000_MAG_DSP_TIMER0_INDX);
status = ft1000_read_dpram16(dev, FT1000_MAG_DSP_TIMER1, (u8 *)&(info->DSP_TIME[1]), FT1000_MAG_DSP_TIMER1_INDX);
status = ft1000_read_dpram16(dev, FT1000_MAG_DSP_TIMER2, (u8 *)&(info->DSP_TIME[2]), FT1000_MAG_DSP_TIMER2_INDX);
status = ft1000_read_dpram16(dev, FT1000_MAG_DSP_TIMER3, (u8 *)&(info->DSP_TIME[3]), FT1000_MAG_DSP_TIMER3_INDX);
info->CardReady = 0;
info->DrvErrNum = DSP_CONDRESET_INFO;
DEBUG("ft1000_hw:DSP conditional reset requested\n");
info->ft1000_reset(dev->net);
}
else {
dev->fProvComplete = 0;
dev->fCondResetPend = 1;
}
ft1000_write_register(dev, FT1000_DB_COND_RESET, FT1000_REG_DOORBELL);
}
}
return STATUS_SUCCESS;
}
| gpl-2.0 |
BrateloSlava/kernel_apq8064 | arch/arm/mach-msm/dal_remotetest.c | 3319 | 11008 | /* Copyright (c) 2008-2009, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
/*
* DAL remote test device test suite.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/debugfs.h>
#include "dal_remotetest.h"
#define BYTEBUF_LEN 64
#define rpc_error(num) \
do { \
errmask |= (1 << num); \
printk(KERN_INFO "%s: remote_unittest_%d failed (%d)\n", \
__func__, num, ret); \
} while (0)
#define verify_error(num, field) \
do { \
errmask |= (1 << num); \
printk(KERN_INFO "%s: remote_unittest_%d failed (%s)\n", \
__func__, num, field); \
} while (0)
static struct dentry *debugfs_dir_entry;
static struct dentry *debugfs_modem_entry;
static struct dentry *debugfs_dsp_entry;
static uint8_t in_bytebuf[BYTEBUF_LEN];
static uint8_t out_bytebuf[BYTEBUF_LEN];
static uint8_t out_bytebuf2[BYTEBUF_LEN];
static struct remote_test_data in_data;
static struct remote_test_data out_data;
static int block_until_cb = 1;
static void init_data(struct remote_test_data *data)
{
int i;
data->regular_event = REMOTE_UNITTEST_INPUT_HANDLE;
data->payload_event = REMOTE_UNITTEST_INPUT_HANDLE;
for (i = 0; i < 32; i++)
data->test[i] = i;
}
static int verify_data(struct remote_test_data *data)
{
int i;
if (data->regular_event != REMOTE_UNITTEST_INPUT_HANDLE ||
data->payload_event != REMOTE_UNITTEST_INPUT_HANDLE)
return -1;
for (i = 0; i < 32; i++)
if (data->test[i] != i)
return -1;
return 0;
}
static int verify_uint32_buffer(uint32_t *buf)
{
int i;
for (i = 0; i < 32; i++)
if (buf[i] != i)
return -1;
return 0;
}
static void init_bytebuf(uint8_t *bytebuf)
{
int i;
for (i = 0; i < BYTEBUF_LEN; i++)
bytebuf[i] = i & 0xff;
}
static int verify_bytebuf(uint8_t *bytebuf)
{
int i;
for (i = 0; i < BYTEBUF_LEN; i++)
if (bytebuf[i] != (i & 0xff))
return -1;
return 0;
}
static void test_cb(void *context, uint32_t param, void *data, uint32_t len)
{
block_until_cb = 0;
}
static int remotetest_exec(int dest, u64 *val)
{
void *dev_handle;
void *event_handles[3];
void *cb_handle;
int ret;
u64 errmask = 0;
uint32_t ouint;
uint32_t oalen;
/* test daldevice_attach */
ret = daldevice_attach(REMOTE_UNITTEST_DEVICEID, NULL,
dest, &dev_handle);
if (ret) {
printk(KERN_INFO "%s: failed to attach (%d)\n", __func__, ret);
*val = 0xffffffff;
return 0;
}
/* test remote_unittest_0 */
ret = remote_unittest_0(dev_handle, REMOTE_UNITTEST_INARG_1);
if (ret)
rpc_error(0);
/* test remote_unittest_1 */
ret = remote_unittest_1(dev_handle, REMOTE_UNITTEST_INARG_1,
REMOTE_UNITTEST_INARG_2);
if (ret)
rpc_error(1);
/* test remote_unittest_2 */
ouint = 0;
ret = remote_unittest_2(dev_handle, REMOTE_UNITTEST_INARG_1, &ouint);
if (ret)
rpc_error(2);
else if (ouint != REMOTE_UNITTEST_OUTARG_1)
verify_error(2, "ouint");
/* test remote_unittest_3 */
ret = remote_unittest_3(dev_handle, REMOTE_UNITTEST_INARG_1,
REMOTE_UNITTEST_INARG_2,
REMOTE_UNITTEST_INARG_3);
if (ret)
rpc_error(3);
/* test remote_unittest_4 */
ouint = 0;
ret = remote_unittest_4(dev_handle, REMOTE_UNITTEST_INARG_1,
REMOTE_UNITTEST_INARG_2, &ouint);
if (ret)
rpc_error(4);
else if (ouint != REMOTE_UNITTEST_OUTARG_1)
verify_error(4, "ouint");
/* test remote_unittest_5 */
init_data(&in_data);
ret = remote_unittest_5(dev_handle, &in_data, sizeof(in_data));
if (ret)
rpc_error(5);
/* test remote_unittest_6 */
init_data(&in_data);
ret = remote_unittest_6(dev_handle, REMOTE_UNITTEST_INARG_1,
&in_data.test, sizeof(in_data.test));
if (ret)
rpc_error(6);
/* test remote_unittest_7 */
init_data(&in_data);
memset(&out_data, 0, sizeof(out_data));
ret = remote_unittest_7(dev_handle, &in_data, sizeof(in_data),
&out_data.test, sizeof(out_data.test),
&oalen);
if (ret)
rpc_error(7);
else if (oalen != sizeof(out_data.test))
verify_error(7, "oalen");
else if (verify_uint32_buffer(out_data.test))
verify_error(7, "obuf");
/* test remote_unittest_8 */
init_bytebuf(in_bytebuf);
memset(&out_data, 0, sizeof(out_data));
ret = remote_unittest_8(dev_handle, in_bytebuf, sizeof(in_bytebuf),
&out_data, sizeof(out_data));
if (ret)
rpc_error(8);
else if (verify_data(&out_data))
verify_error(8, "obuf");
/* test remote_unittest_9 */
memset(&out_bytebuf, 0, sizeof(out_bytebuf));
ret = remote_unittest_9(dev_handle, out_bytebuf, sizeof(out_bytebuf));
if (ret)
rpc_error(9);
else if (verify_bytebuf(out_bytebuf))
verify_error(9, "obuf");
/* test remote_unittest_10 */
init_bytebuf(in_bytebuf);
memset(&out_bytebuf, 0, sizeof(out_bytebuf));
ret = remote_unittest_10(dev_handle, REMOTE_UNITTEST_INARG_1,
in_bytebuf, sizeof(in_bytebuf),
out_bytebuf, sizeof(out_bytebuf), &oalen);
if (ret)
rpc_error(10);
else if (oalen != sizeof(out_bytebuf))
verify_error(10, "oalen");
else if (verify_bytebuf(out_bytebuf))
verify_error(10, "obuf");
/* test remote_unittest_11 */
memset(&out_bytebuf, 0, sizeof(out_bytebuf));
ret = remote_unittest_11(dev_handle, REMOTE_UNITTEST_INARG_1,
out_bytebuf, sizeof(out_bytebuf));
if (ret)
rpc_error(11);
else if (verify_bytebuf(out_bytebuf))
verify_error(11, "obuf");
/* test remote_unittest_12 */
memset(&out_bytebuf, 0, sizeof(out_bytebuf));
ret = remote_unittest_12(dev_handle, REMOTE_UNITTEST_INARG_1,
out_bytebuf, sizeof(out_bytebuf), &oalen);
if (ret)
rpc_error(12);
else if (oalen != sizeof(out_bytebuf))
verify_error(12, "oalen");
else if (verify_bytebuf(out_bytebuf))
verify_error(12, "obuf");
/* test remote_unittest_13 */
init_data(&in_data);
memset(&out_data, 0, sizeof(out_data));
ret = remote_unittest_13(dev_handle, in_data.test, sizeof(in_data.test),
&in_data, sizeof(in_data),
&out_data, sizeof(out_data));
if (ret)
rpc_error(13);
else if (verify_data(&out_data))
verify_error(13, "obuf");
/* test remote_unittest_14 */
init_data(&in_data);
memset(out_bytebuf, 0, sizeof(out_bytebuf));
memset(out_bytebuf2, 0, sizeof(out_bytebuf2));
ret = remote_unittest_14(dev_handle,
in_data.test, sizeof(in_data.test),
out_bytebuf, sizeof(out_bytebuf),
out_bytebuf2, sizeof(out_bytebuf2), &oalen);
if (ret)
rpc_error(14);
else if (verify_bytebuf(out_bytebuf))
verify_error(14, "obuf");
else if (oalen != sizeof(out_bytebuf2))
verify_error(14, "oalen");
else if (verify_bytebuf(out_bytebuf2))
verify_error(14, "obuf2");
/* test remote_unittest_15 */
init_data(&in_data);
memset(out_bytebuf, 0, sizeof(out_bytebuf));
memset(&out_data, 0, sizeof(out_data));
ret = remote_unittest_15(dev_handle,
in_data.test, sizeof(in_data.test),
&in_data, sizeof(in_data),
&out_data, sizeof(out_data), &oalen,
out_bytebuf, sizeof(out_bytebuf));
if (ret)
rpc_error(15);
else if (oalen != sizeof(out_data))
verify_error(15, "oalen");
else if (verify_bytebuf(out_bytebuf))
verify_error(15, "obuf");
else if (verify_data(&out_data))
verify_error(15, "obuf2");
/* test setting up asynch events */
event_handles[0] = dalrpc_alloc_event(dev_handle);
event_handles[1] = dalrpc_alloc_event(dev_handle);
event_handles[2] = dalrpc_alloc_event(dev_handle);
cb_handle = dalrpc_alloc_cb(dev_handle, test_cb, &out_data);
in_data.regular_event = (uint32_t)event_handles[2];
in_data.payload_event = (uint32_t)cb_handle;
ret = remote_unittest_eventcfg(dev_handle, &in_data, sizeof(in_data));
if (ret) {
errmask |= (1 << 16);
printk(KERN_INFO "%s: failed to configure asynch (%d)\n",
__func__, ret);
}
/* test event */
ret = remote_unittest_eventtrig(dev_handle,
REMOTE_UNITTEST_REGULAR_EVENT);
if (ret) {
errmask |= (1 << 17);
printk(KERN_INFO "%s: failed to trigger event (%d)\n",
__func__, ret);
}
ret = dalrpc_event_wait(event_handles[2], 1000);
if (ret) {
errmask |= (1 << 18);
printk(KERN_INFO "%s: failed to receive event (%d)\n",
__func__, ret);
}
/* test event again */
ret = remote_unittest_eventtrig(dev_handle,
REMOTE_UNITTEST_REGULAR_EVENT);
if (ret) {
errmask |= (1 << 19);
printk(KERN_INFO "%s: failed to trigger event (%d)\n",
__func__, ret);
}
ret = dalrpc_event_wait_multiple(3, event_handles, 1000);
if (ret != 2) {
errmask |= (1 << 20);
printk(KERN_INFO "%s: failed to receive event (%d)\n",
__func__, ret);
}
/* test callback */
ret = remote_unittest_eventtrig(dev_handle,
REMOTE_UNITTEST_CALLBACK_EVENT);
if (ret) {
errmask |= (1 << 21);
printk(KERN_INFO "%s: failed to trigger callback (%d)\n",
__func__, ret);
} else
while (block_until_cb)
;
dalrpc_dealloc_cb(dev_handle, cb_handle);
dalrpc_dealloc_event(dev_handle, event_handles[0]);
dalrpc_dealloc_event(dev_handle, event_handles[1]);
dalrpc_dealloc_event(dev_handle, event_handles[2]);
/* test daldevice_detach */
ret = daldevice_detach(dev_handle);
if (ret) {
errmask |= (1 << 22);
printk(KERN_INFO "%s: failed to detach (%d)\n", __func__, ret);
}
printk(KERN_INFO "%s: remote_unittest complete\n", __func__);
*val = errmask;
return 0;
}
static int remotetest_modem_exec(void *data, u64 *val)
{
return remotetest_exec(DALRPC_DEST_MODEM, val);
}
static int remotetest_dsp_exec(void *data, u64 *val)
{
return remotetest_exec(DALRPC_DEST_QDSP, val);
}
DEFINE_SIMPLE_ATTRIBUTE(dal_modemtest_fops, remotetest_modem_exec,
NULL, "%llu\n");
DEFINE_SIMPLE_ATTRIBUTE(dal_dsptest_fops, remotetest_dsp_exec,
NULL, "%llu\n");
static int __init remotetest_init(void)
{
debugfs_dir_entry = debugfs_create_dir("dal", 0);
if (IS_ERR(debugfs_dir_entry))
return PTR_ERR(debugfs_dir_entry);
debugfs_modem_entry = debugfs_create_file("modem_test", 0444,
debugfs_dir_entry,
NULL, &dal_modemtest_fops);
if (IS_ERR(debugfs_modem_entry)) {
debugfs_remove(debugfs_dir_entry);
return PTR_ERR(debugfs_modem_entry);
}
debugfs_dsp_entry = debugfs_create_file("dsp_test", 0444,
debugfs_dir_entry,
NULL, &dal_dsptest_fops);
if (IS_ERR(debugfs_dsp_entry)) {
debugfs_remove(debugfs_modem_entry);
debugfs_remove(debugfs_dir_entry);
return PTR_ERR(debugfs_dsp_entry);
}
return 0;
}
static void __exit remotetest_exit(void)
{
debugfs_remove(debugfs_modem_entry);
debugfs_remove(debugfs_dsp_entry);
debugfs_remove(debugfs_dir_entry);
}
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("Test for DAL RPC");
MODULE_VERSION("1.0");
module_init(remotetest_init);
module_exit(remotetest_exit);
| gpl-2.0 |
lukier/linux-hi3518 | drivers/usb/host/fhci-tds.c | 4343 | 16917 | /*
* Freescale QUICC Engine USB Host Controller Driver
*
* Copyright (c) Freescale Semicondutor, Inc. 2006.
* Shlomi Gridish <gridish@freescale.com>
* Jerry Huang <Chang-Ming.Huang@freescale.com>
* Copyright (c) Logic Product Development, Inc. 2007
* Peter Barada <peterb@logicpd.com>
* Copyright (c) MontaVista Software, Inc. 2008.
* Anton Vorontsov <avorontsov@ru.mvista.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/types.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/list.h>
#include <linux/io.h>
#include <linux/usb.h>
#include <linux/usb/hcd.h>
#include "fhci.h"
#define DUMMY_BD_BUFFER 0xdeadbeef
#define DUMMY2_BD_BUFFER 0xbaadf00d
/* Transaction Descriptors bits */
#define TD_R 0x8000 /* ready bit */
#define TD_W 0x2000 /* wrap bit */
#define TD_I 0x1000 /* interrupt on completion */
#define TD_L 0x0800 /* last */
#define TD_TC 0x0400 /* transmit CRC */
#define TD_CNF 0x0200 /* CNF - Must be always 1 */
#define TD_LSP 0x0100 /* Low-speed transaction */
#define TD_PID 0x00c0 /* packet id */
#define TD_RXER 0x0020 /* Rx error or not */
#define TD_NAK 0x0010 /* No ack. */
#define TD_STAL 0x0008 /* Stall received */
#define TD_TO 0x0004 /* time out */
#define TD_UN 0x0002 /* underrun */
#define TD_NO 0x0010 /* Rx Non Octet Aligned Packet */
#define TD_AB 0x0008 /* Frame Aborted */
#define TD_CR 0x0004 /* CRC Error */
#define TD_OV 0x0002 /* Overrun */
#define TD_BOV 0x0001 /* Buffer Overrun */
#define TD_ERRORS (TD_NAK | TD_STAL | TD_TO | TD_UN | \
TD_NO | TD_AB | TD_CR | TD_OV | TD_BOV)
#define TD_PID_DATA0 0x0080 /* Data 0 toggle */
#define TD_PID_DATA1 0x00c0 /* Data 1 toggle */
#define TD_PID_TOGGLE 0x00c0 /* Data 0/1 toggle mask */
#define TD_TOK_SETUP 0x0000
#define TD_TOK_OUT 0x4000
#define TD_TOK_IN 0x8000
#define TD_ISO 0x1000
#define TD_ENDP 0x0780
#define TD_ADDR 0x007f
#define TD_ENDP_SHIFT 7
struct usb_td {
__be16 status;
__be16 length;
__be32 buf_ptr;
__be16 extra;
__be16 reserved;
};
static struct usb_td __iomem *next_bd(struct usb_td __iomem *base,
struct usb_td __iomem *td,
u16 status)
{
if (status & TD_W)
return base;
else
return ++td;
}
void fhci_push_dummy_bd(struct endpoint *ep)
{
if (ep->already_pushed_dummy_bd == false) {
u16 td_status = in_be16(&ep->empty_td->status);
out_be32(&ep->empty_td->buf_ptr, DUMMY_BD_BUFFER);
/* get the next TD in the ring */
ep->empty_td = next_bd(ep->td_base, ep->empty_td, td_status);
ep->already_pushed_dummy_bd = true;
}
}
/* destroy an USB endpoint */
void fhci_ep0_free(struct fhci_usb *usb)
{
struct endpoint *ep;
int size;
ep = usb->ep0;
if (ep) {
if (ep->td_base)
cpm_muram_free(cpm_muram_offset(ep->td_base));
if (kfifo_initialized(&ep->conf_frame_Q)) {
size = cq_howmany(&ep->conf_frame_Q);
for (; size; size--) {
struct packet *pkt = cq_get(&ep->conf_frame_Q);
kfree(pkt);
}
cq_delete(&ep->conf_frame_Q);
}
if (kfifo_initialized(&ep->empty_frame_Q)) {
size = cq_howmany(&ep->empty_frame_Q);
for (; size; size--) {
struct packet *pkt = cq_get(&ep->empty_frame_Q);
kfree(pkt);
}
cq_delete(&ep->empty_frame_Q);
}
if (kfifo_initialized(&ep->dummy_packets_Q)) {
size = cq_howmany(&ep->dummy_packets_Q);
for (; size; size--) {
u8 *buff = cq_get(&ep->dummy_packets_Q);
kfree(buff);
}
cq_delete(&ep->dummy_packets_Q);
}
kfree(ep);
usb->ep0 = NULL;
}
}
/*
* create the endpoint structure
*
* arguments:
* usb A pointer to the data structure of the USB
* data_mem The data memory partition(BUS)
* ring_len TD ring length
*/
u32 fhci_create_ep(struct fhci_usb *usb, enum fhci_mem_alloc data_mem,
u32 ring_len)
{
struct endpoint *ep;
struct usb_td __iomem *td;
unsigned long ep_offset;
char *err_for = "endpoint PRAM";
int ep_mem_size;
u32 i;
/* we need at least 3 TDs in the ring */
if (!(ring_len > 2)) {
fhci_err(usb->fhci, "illegal TD ring length parameters\n");
return -EINVAL;
}
ep = kzalloc(sizeof(*ep), GFP_KERNEL);
if (!ep)
return -ENOMEM;
ep_mem_size = ring_len * sizeof(*td) + sizeof(struct fhci_ep_pram);
ep_offset = cpm_muram_alloc(ep_mem_size, 32);
if (IS_ERR_VALUE(ep_offset))
goto err;
ep->td_base = cpm_muram_addr(ep_offset);
/* zero all queue pointers */
if (cq_new(&ep->conf_frame_Q, ring_len + 2) ||
cq_new(&ep->empty_frame_Q, ring_len + 2) ||
cq_new(&ep->dummy_packets_Q, ring_len + 2)) {
err_for = "frame_queues";
goto err;
}
for (i = 0; i < (ring_len + 1); i++) {
struct packet *pkt;
u8 *buff;
pkt = kmalloc(sizeof(*pkt), GFP_KERNEL);
if (!pkt) {
err_for = "frame";
goto err;
}
buff = kmalloc(1028 * sizeof(*buff), GFP_KERNEL);
if (!buff) {
kfree(pkt);
err_for = "buffer";
goto err;
}
cq_put(&ep->empty_frame_Q, pkt);
cq_put(&ep->dummy_packets_Q, buff);
}
/* we put the endpoint parameter RAM right behind the TD ring */
ep->ep_pram_ptr = (void __iomem *)ep->td_base + sizeof(*td) * ring_len;
ep->conf_td = ep->td_base;
ep->empty_td = ep->td_base;
ep->already_pushed_dummy_bd = false;
/* initialize tds */
td = ep->td_base;
for (i = 0; i < ring_len; i++) {
out_be32(&td->buf_ptr, 0);
out_be16(&td->status, 0);
out_be16(&td->length, 0);
out_be16(&td->extra, 0);
td++;
}
td--;
out_be16(&td->status, TD_W); /* for last TD set Wrap bit */
out_be16(&td->length, 0);
/* endpoint structure has been created */
usb->ep0 = ep;
return 0;
err:
fhci_ep0_free(usb);
kfree(ep);
fhci_err(usb->fhci, "no memory for the %s\n", err_for);
return -ENOMEM;
}
/*
* initialize the endpoint register according to the given parameters
*
* artuments:
* usb A pointer to the data strucutre of the USB
* ep A pointer to the endpoint structre
* data_mem The data memory partition(BUS)
*/
void fhci_init_ep_registers(struct fhci_usb *usb, struct endpoint *ep,
enum fhci_mem_alloc data_mem)
{
u8 rt;
/* set the endpoint registers according to the endpoint */
out_be16(&usb->fhci->regs->usb_usep[0],
USB_TRANS_CTR | USB_EP_MF | USB_EP_RTE);
out_be16(&usb->fhci->pram->ep_ptr[0],
cpm_muram_offset(ep->ep_pram_ptr));
rt = (BUS_MODE_BO_BE | BUS_MODE_GBL);
#ifdef MULTI_DATA_BUS
if (data_mem == MEM_SECONDARY)
rt |= BUS_MODE_DTB;
#endif
out_8(&ep->ep_pram_ptr->rx_func_code, rt);
out_8(&ep->ep_pram_ptr->tx_func_code, rt);
out_be16(&ep->ep_pram_ptr->rx_buff_len, 1028);
out_be16(&ep->ep_pram_ptr->rx_base, 0);
out_be16(&ep->ep_pram_ptr->tx_base, cpm_muram_offset(ep->td_base));
out_be16(&ep->ep_pram_ptr->rx_bd_ptr, 0);
out_be16(&ep->ep_pram_ptr->tx_bd_ptr, cpm_muram_offset(ep->td_base));
out_be32(&ep->ep_pram_ptr->tx_state, 0);
}
/*
* Collect the submitted frames and inform the application about them
* It is also preparing the TDs for new frames. If the Tx interrupts
* are disabled, the application should call that routine to get
* confirmation about the submitted frames. Otherwise, the routine is
* called from the interrupt service routine during the Tx interrupt.
* In that case the application is informed by calling the application
* specific 'fhci_transaction_confirm' routine
*/
static void fhci_td_transaction_confirm(struct fhci_usb *usb)
{
struct endpoint *ep = usb->ep0;
struct packet *pkt;
struct usb_td __iomem *td;
u16 extra_data;
u16 td_status;
u16 td_length;
u32 buf;
/*
* collect transmitted BDs from the chip. The routine clears all BDs
* with R bit = 0 and the pointer to data buffer is not NULL, that is
* BDs which point to the transmitted data buffer
*/
while (1) {
td = ep->conf_td;
td_status = in_be16(&td->status);
td_length = in_be16(&td->length);
buf = in_be32(&td->buf_ptr);
extra_data = in_be16(&td->extra);
/* check if the TD is empty */
if (!(!(td_status & TD_R) && ((td_status & ~TD_W) || buf)))
break;
/* check if it is a dummy buffer */
else if ((buf == DUMMY_BD_BUFFER) && !(td_status & ~TD_W))
break;
/* mark TD as empty */
clrbits16(&td->status, ~TD_W);
out_be16(&td->length, 0);
out_be32(&td->buf_ptr, 0);
out_be16(&td->extra, 0);
/* advance the TD pointer */
ep->conf_td = next_bd(ep->td_base, ep->conf_td, td_status);
/* check if it is a dummy buffer(type2) */
if ((buf == DUMMY2_BD_BUFFER) && !(td_status & ~TD_W))
continue;
pkt = cq_get(&ep->conf_frame_Q);
if (!pkt)
fhci_err(usb->fhci, "no frame to confirm\n");
if (td_status & TD_ERRORS) {
if (td_status & TD_RXER) {
if (td_status & TD_CR)
pkt->status = USB_TD_RX_ER_CRC;
else if (td_status & TD_AB)
pkt->status = USB_TD_RX_ER_BITSTUFF;
else if (td_status & TD_OV)
pkt->status = USB_TD_RX_ER_OVERUN;
else if (td_status & TD_BOV)
pkt->status = USB_TD_RX_DATA_OVERUN;
else if (td_status & TD_NO)
pkt->status = USB_TD_RX_ER_NONOCT;
else
fhci_err(usb->fhci, "illegal error "
"occurred\n");
} else if (td_status & TD_NAK)
pkt->status = USB_TD_TX_ER_NAK;
else if (td_status & TD_TO)
pkt->status = USB_TD_TX_ER_TIMEOUT;
else if (td_status & TD_UN)
pkt->status = USB_TD_TX_ER_UNDERUN;
else if (td_status & TD_STAL)
pkt->status = USB_TD_TX_ER_STALL;
else
fhci_err(usb->fhci, "illegal error occurred\n");
} else if ((extra_data & TD_TOK_IN) &&
pkt->len > td_length - CRC_SIZE) {
pkt->status = USB_TD_RX_DATA_UNDERUN;
}
if (extra_data & TD_TOK_IN)
pkt->len = td_length - CRC_SIZE;
else if (pkt->info & PKT_ZLP)
pkt->len = 0;
else
pkt->len = td_length;
fhci_transaction_confirm(usb, pkt);
}
}
/*
* Submitting a data frame to a specified endpoint of a USB device
* The frame is put in the driver's transmit queue for this endpoint
*
* Arguments:
* usb A pointer to the USB structure
* pkt A pointer to the user frame structure
* trans_type Transaction tyep - IN,OUT or SETUP
* dest_addr Device address - 0~127
* dest_ep Endpoint number of the device - 0~16
* trans_mode Pipe type - ISO,Interrupt,bulk or control
* dest_speed USB speed - Low speed or FULL speed
* data_toggle Data sequence toggle - 0 or 1
*/
u32 fhci_host_transaction(struct fhci_usb *usb,
struct packet *pkt,
enum fhci_ta_type trans_type,
u8 dest_addr,
u8 dest_ep,
enum fhci_tf_mode trans_mode,
enum fhci_speed dest_speed, u8 data_toggle)
{
struct endpoint *ep = usb->ep0;
struct usb_td __iomem *td;
u16 extra_data;
u16 td_status;
fhci_usb_disable_interrupt(usb);
/* start from the next BD that should be filled */
td = ep->empty_td;
td_status = in_be16(&td->status);
if (td_status & TD_R && in_be16(&td->length)) {
/* if the TD is not free */
fhci_usb_enable_interrupt(usb);
return -1;
}
/* get the next TD in the ring */
ep->empty_td = next_bd(ep->td_base, ep->empty_td, td_status);
fhci_usb_enable_interrupt(usb);
pkt->priv_data = td;
out_be32(&td->buf_ptr, virt_to_phys(pkt->data));
/* sets up transaction parameters - addr,endp,dir,and type */
extra_data = (dest_ep << TD_ENDP_SHIFT) | dest_addr;
switch (trans_type) {
case FHCI_TA_IN:
extra_data |= TD_TOK_IN;
break;
case FHCI_TA_OUT:
extra_data |= TD_TOK_OUT;
break;
case FHCI_TA_SETUP:
extra_data |= TD_TOK_SETUP;
break;
}
if (trans_mode == FHCI_TF_ISO)
extra_data |= TD_ISO;
out_be16(&td->extra, extra_data);
/* sets up the buffer descriptor */
td_status = ((td_status & TD_W) | TD_R | TD_L | TD_I | TD_CNF);
if (!(pkt->info & PKT_NO_CRC))
td_status |= TD_TC;
switch (trans_type) {
case FHCI_TA_IN:
if (data_toggle)
pkt->info |= PKT_PID_DATA1;
else
pkt->info |= PKT_PID_DATA0;
break;
default:
if (data_toggle) {
td_status |= TD_PID_DATA1;
pkt->info |= PKT_PID_DATA1;
} else {
td_status |= TD_PID_DATA0;
pkt->info |= PKT_PID_DATA0;
}
break;
}
if ((dest_speed == FHCI_LOW_SPEED) &&
(usb->port_status == FHCI_PORT_FULL))
td_status |= TD_LSP;
out_be16(&td->status, td_status);
/* set up buffer length */
if (trans_type == FHCI_TA_IN)
out_be16(&td->length, pkt->len + CRC_SIZE);
else
out_be16(&td->length, pkt->len);
/* put the frame to the confirmation queue */
cq_put(&ep->conf_frame_Q, pkt);
if (cq_howmany(&ep->conf_frame_Q) == 1)
out_8(&usb->fhci->regs->usb_uscom, USB_CMD_STR_FIFO);
return 0;
}
/* Reset the Tx BD ring */
void fhci_flush_bds(struct fhci_usb *usb)
{
u16 extra_data;
u16 td_status;
u32 buf;
struct usb_td __iomem *td;
struct endpoint *ep = usb->ep0;
td = ep->td_base;
while (1) {
td_status = in_be16(&td->status);
buf = in_be32(&td->buf_ptr);
extra_data = in_be16(&td->extra);
/* if the TD is not empty - we'll confirm it as Timeout */
if (td_status & TD_R)
out_be16(&td->status, (td_status & ~TD_R) | TD_TO);
/* if this TD is dummy - let's skip this TD */
else if (in_be32(&td->buf_ptr) == DUMMY_BD_BUFFER)
out_be32(&td->buf_ptr, DUMMY2_BD_BUFFER);
/* if this is the last TD - break */
if (td_status & TD_W)
break;
td++;
}
fhci_td_transaction_confirm(usb);
td = ep->td_base;
do {
out_be16(&td->status, 0);
out_be16(&td->length, 0);
out_be32(&td->buf_ptr, 0);
out_be16(&td->extra, 0);
td++;
} while (!(in_be16(&td->status) & TD_W));
out_be16(&td->status, TD_W); /* for last TD set Wrap bit */
out_be16(&td->length, 0);
out_be32(&td->buf_ptr, 0);
out_be16(&td->extra, 0);
out_be16(&ep->ep_pram_ptr->tx_bd_ptr,
in_be16(&ep->ep_pram_ptr->tx_base));
out_be32(&ep->ep_pram_ptr->tx_state, 0);
out_be16(&ep->ep_pram_ptr->tx_cnt, 0);
ep->empty_td = ep->td_base;
ep->conf_td = ep->td_base;
}
/*
* Flush all transmitted packets from TDs in the actual frame.
* This routine is called when something wrong with the controller and
* we want to get rid of the actual frame and start again next frame
*/
void fhci_flush_actual_frame(struct fhci_usb *usb)
{
u8 mode;
u16 tb_ptr;
u16 extra_data;
u16 td_status;
u32 buf_ptr;
struct usb_td __iomem *td;
struct endpoint *ep = usb->ep0;
/* disable the USB controller */
mode = in_8(&usb->fhci->regs->usb_usmod);
out_8(&usb->fhci->regs->usb_usmod, mode & ~USB_MODE_EN);
tb_ptr = in_be16(&ep->ep_pram_ptr->tx_bd_ptr);
td = cpm_muram_addr(tb_ptr);
td_status = in_be16(&td->status);
buf_ptr = in_be32(&td->buf_ptr);
extra_data = in_be16(&td->extra);
do {
if (td_status & TD_R) {
out_be16(&td->status, (td_status & ~TD_R) | TD_TO);
} else {
out_be32(&td->buf_ptr, 0);
ep->already_pushed_dummy_bd = false;
break;
}
/* advance the TD pointer */
td = next_bd(ep->td_base, td, td_status);
td_status = in_be16(&td->status);
buf_ptr = in_be32(&td->buf_ptr);
extra_data = in_be16(&td->extra);
} while ((td_status & TD_R) || buf_ptr);
fhci_td_transaction_confirm(usb);
out_be16(&ep->ep_pram_ptr->tx_bd_ptr,
in_be16(&ep->ep_pram_ptr->tx_base));
out_be32(&ep->ep_pram_ptr->tx_state, 0);
out_be16(&ep->ep_pram_ptr->tx_cnt, 0);
ep->empty_td = ep->td_base;
ep->conf_td = ep->td_base;
usb->actual_frame->frame_status = FRAME_TIMER_END_TRANSMISSION;
/* reset the event register */
out_be16(&usb->fhci->regs->usb_usber, 0xffff);
/* enable the USB controller */
out_8(&usb->fhci->regs->usb_usmod, mode | USB_MODE_EN);
}
/* handles Tx confirm and Tx error interrupt */
void fhci_tx_conf_interrupt(struct fhci_usb *usb)
{
fhci_td_transaction_confirm(usb);
/*
* Schedule another transaction to this frame only if we have
* already confirmed all transaction in the frame.
*/
if (((fhci_get_sof_timer_count(usb) < usb->max_frame_usage) ||
(usb->actual_frame->frame_status & FRAME_END_TRANSMISSION)) &&
(list_empty(&usb->actual_frame->tds_list)))
fhci_schedule_transactions(usb);
}
void fhci_host_transmit_actual_frame(struct fhci_usb *usb)
{
u16 tb_ptr;
u16 td_status;
struct usb_td __iomem *td;
struct endpoint *ep = usb->ep0;
tb_ptr = in_be16(&ep->ep_pram_ptr->tx_bd_ptr);
td = cpm_muram_addr(tb_ptr);
if (in_be32(&td->buf_ptr) == DUMMY_BD_BUFFER) {
struct usb_td __iomem *old_td = td;
ep->already_pushed_dummy_bd = false;
td_status = in_be16(&td->status);
/* gets the next TD in the ring */
td = next_bd(ep->td_base, td, td_status);
tb_ptr = cpm_muram_offset(td);
out_be16(&ep->ep_pram_ptr->tx_bd_ptr, tb_ptr);
/* start transmit only if we have something in the TDs */
if (in_be16(&td->status) & TD_R)
out_8(&usb->fhci->regs->usb_uscom, USB_CMD_STR_FIFO);
if (in_be32(&ep->conf_td->buf_ptr) == DUMMY_BD_BUFFER) {
out_be32(&old_td->buf_ptr, 0);
ep->conf_td = next_bd(ep->td_base, ep->conf_td,
td_status);
} else {
out_be32(&old_td->buf_ptr, DUMMY2_BD_BUFFER);
}
}
}
| gpl-2.0 |
TheKang/kernel_lge_hammerhead | drivers/scsi/bfa/bfad_bsg.c | 4855 | 88372 | /*
* Copyright (c) 2005-2010 Brocade Communications Systems, Inc.
* All rights reserved
* www.brocade.com
*
* Linux driver for Brocade Fibre Channel Host Bus Adapter.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License (GPL) 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/uaccess.h>
#include "bfad_drv.h"
#include "bfad_im.h"
#include "bfad_bsg.h"
BFA_TRC_FILE(LDRV, BSG);
int
bfad_iocmd_ioc_enable(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
int rc = 0;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
/* If IOC is not in disabled state - return */
if (!bfa_ioc_is_disabled(&bfad->bfa.ioc)) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_IOC_FAILURE;
return rc;
}
init_completion(&bfad->enable_comp);
bfa_iocfc_enable(&bfad->bfa);
iocmd->status = BFA_STATUS_OK;
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
wait_for_completion(&bfad->enable_comp);
return rc;
}
int
bfad_iocmd_ioc_disable(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
int rc = 0;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
if (bfad->disable_active) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return -EBUSY;
}
bfad->disable_active = BFA_TRUE;
init_completion(&bfad->disable_comp);
bfa_iocfc_disable(&bfad->bfa);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
wait_for_completion(&bfad->disable_comp);
bfad->disable_active = BFA_FALSE;
iocmd->status = BFA_STATUS_OK;
return rc;
}
static int
bfad_iocmd_ioc_get_info(struct bfad_s *bfad, void *cmd)
{
int i;
struct bfa_bsg_ioc_info_s *iocmd = (struct bfa_bsg_ioc_info_s *)cmd;
struct bfad_im_port_s *im_port;
struct bfa_port_attr_s pattr;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
bfa_fcport_get_attr(&bfad->bfa, &pattr);
iocmd->nwwn = pattr.nwwn;
iocmd->pwwn = pattr.pwwn;
iocmd->ioc_type = bfa_get_type(&bfad->bfa);
iocmd->mac = bfa_get_mac(&bfad->bfa);
iocmd->factory_mac = bfa_get_mfg_mac(&bfad->bfa);
bfa_get_adapter_serial_num(&bfad->bfa, iocmd->serialnum);
iocmd->factorynwwn = pattr.factorynwwn;
iocmd->factorypwwn = pattr.factorypwwn;
iocmd->bfad_num = bfad->inst_no;
im_port = bfad->pport.im_port;
iocmd->host = im_port->shost->host_no;
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
strcpy(iocmd->name, bfad->adapter_name);
strcpy(iocmd->port_name, bfad->port_name);
strcpy(iocmd->hwpath, bfad->pci_name);
/* set adapter hw path */
strcpy(iocmd->adapter_hwpath, bfad->pci_name);
i = strlen(iocmd->adapter_hwpath) - 1;
while (iocmd->adapter_hwpath[i] != '.')
i--;
iocmd->adapter_hwpath[i] = '\0';
iocmd->status = BFA_STATUS_OK;
return 0;
}
static int
bfad_iocmd_ioc_get_attr(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_ioc_attr_s *iocmd = (struct bfa_bsg_ioc_attr_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
bfa_ioc_get_attr(&bfad->bfa.ioc, &iocmd->ioc_attr);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
/* fill in driver attr info */
strcpy(iocmd->ioc_attr.driver_attr.driver, BFAD_DRIVER_NAME);
strncpy(iocmd->ioc_attr.driver_attr.driver_ver,
BFAD_DRIVER_VERSION, BFA_VERSION_LEN);
strcpy(iocmd->ioc_attr.driver_attr.fw_ver,
iocmd->ioc_attr.adapter_attr.fw_ver);
strcpy(iocmd->ioc_attr.driver_attr.bios_ver,
iocmd->ioc_attr.adapter_attr.optrom_ver);
/* copy chip rev info first otherwise it will be overwritten */
memcpy(bfad->pci_attr.chip_rev, iocmd->ioc_attr.pci_attr.chip_rev,
sizeof(bfad->pci_attr.chip_rev));
memcpy(&iocmd->ioc_attr.pci_attr, &bfad->pci_attr,
sizeof(struct bfa_ioc_pci_attr_s));
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_ioc_get_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_ioc_stats_s *iocmd = (struct bfa_bsg_ioc_stats_s *)cmd;
bfa_ioc_get_stats(&bfad->bfa, &iocmd->ioc_stats);
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_ioc_get_fwstats(struct bfad_s *bfad, void *cmd,
unsigned int payload_len)
{
struct bfa_bsg_ioc_fwstats_s *iocmd =
(struct bfa_bsg_ioc_fwstats_s *)cmd;
void *iocmd_bufptr;
unsigned long flags;
if (bfad_chk_iocmd_sz(payload_len,
sizeof(struct bfa_bsg_ioc_fwstats_s),
sizeof(struct bfa_fw_stats_s)) != BFA_STATUS_OK) {
iocmd->status = BFA_STATUS_VERSION_FAIL;
goto out;
}
iocmd_bufptr = (char *)iocmd + sizeof(struct bfa_bsg_ioc_fwstats_s);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_ioc_fw_stats_get(&bfad->bfa.ioc, iocmd_bufptr);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK) {
bfa_trc(bfad, iocmd->status);
goto out;
}
out:
bfa_trc(bfad, 0x6666);
return 0;
}
int
bfad_iocmd_ioc_reset_stats(struct bfad_s *bfad, void *cmd, unsigned int v_cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
unsigned long flags;
if (v_cmd == IOCMD_IOC_RESET_STATS) {
bfa_ioc_clear_stats(&bfad->bfa);
iocmd->status = BFA_STATUS_OK;
} else if (v_cmd == IOCMD_IOC_RESET_FWSTATS) {
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_ioc_fw_stats_clear(&bfad->bfa.ioc);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
}
return 0;
}
int
bfad_iocmd_ioc_set_name(struct bfad_s *bfad, void *cmd, unsigned int v_cmd)
{
struct bfa_bsg_ioc_name_s *iocmd = (struct bfa_bsg_ioc_name_s *) cmd;
if (v_cmd == IOCMD_IOC_SET_ADAPTER_NAME)
strcpy(bfad->adapter_name, iocmd->name);
else if (v_cmd == IOCMD_IOC_SET_PORT_NAME)
strcpy(bfad->port_name, iocmd->name);
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_iocfc_get_attr(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_iocfc_attr_s *iocmd = (struct bfa_bsg_iocfc_attr_s *)cmd;
iocmd->status = BFA_STATUS_OK;
bfa_iocfc_get_attr(&bfad->bfa, &iocmd->iocfc_attr);
return 0;
}
int
bfad_iocmd_iocfc_set_intr(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_iocfc_intr_s *iocmd = (struct bfa_bsg_iocfc_intr_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_iocfc_israttr_set(&bfad->bfa, &iocmd->attr);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
int
bfad_iocmd_port_enable(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_port_enable(&bfad->bfa.modules.port,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK) {
bfa_trc(bfad, iocmd->status);
return 0;
}
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
return 0;
}
int
bfad_iocmd_port_disable(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_port_disable(&bfad->bfa.modules.port,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK) {
bfa_trc(bfad, iocmd->status);
return 0;
}
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
return 0;
}
static int
bfad_iocmd_port_get_attr(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_port_attr_s *iocmd = (struct bfa_bsg_port_attr_s *)cmd;
struct bfa_lport_attr_s port_attr;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
bfa_fcport_get_attr(&bfad->bfa, &iocmd->attr);
bfa_fcs_lport_get_attr(&bfad->bfa_fcs.fabric.bport, &port_attr);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->attr.topology != BFA_PORT_TOPOLOGY_NONE)
iocmd->attr.pid = port_attr.pid;
else
iocmd->attr.pid = 0;
iocmd->attr.port_type = port_attr.port_type;
iocmd->attr.loopback = port_attr.loopback;
iocmd->attr.authfail = port_attr.authfail;
strncpy(iocmd->attr.port_symname.symname,
port_attr.port_cfg.sym_name.symname,
sizeof(port_attr.port_cfg.sym_name.symname));
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_port_get_stats(struct bfad_s *bfad, void *cmd,
unsigned int payload_len)
{
struct bfa_bsg_port_stats_s *iocmd = (struct bfa_bsg_port_stats_s *)cmd;
struct bfad_hal_comp fcomp;
void *iocmd_bufptr;
unsigned long flags;
if (bfad_chk_iocmd_sz(payload_len,
sizeof(struct bfa_bsg_port_stats_s),
sizeof(union bfa_port_stats_u)) != BFA_STATUS_OK) {
iocmd->status = BFA_STATUS_VERSION_FAIL;
return 0;
}
iocmd_bufptr = (char *)iocmd + sizeof(struct bfa_bsg_port_stats_s);
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_port_get_stats(&bfad->bfa.modules.port,
iocmd_bufptr, bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK) {
bfa_trc(bfad, iocmd->status);
goto out;
}
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_port_reset_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_port_clear_stats(&bfad->bfa.modules.port,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK) {
bfa_trc(bfad, iocmd->status);
return 0;
}
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
return 0;
}
int
bfad_iocmd_set_port_cfg(struct bfad_s *bfad, void *iocmd, unsigned int v_cmd)
{
struct bfa_bsg_port_cfg_s *cmd = (struct bfa_bsg_port_cfg_s *)iocmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
if (v_cmd == IOCMD_PORT_CFG_TOPO)
cmd->status = bfa_fcport_cfg_topology(&bfad->bfa, cmd->param);
else if (v_cmd == IOCMD_PORT_CFG_SPEED)
cmd->status = bfa_fcport_cfg_speed(&bfad->bfa, cmd->param);
else if (v_cmd == IOCMD_PORT_CFG_ALPA)
cmd->status = bfa_fcport_cfg_hardalpa(&bfad->bfa, cmd->param);
else if (v_cmd == IOCMD_PORT_CLR_ALPA)
cmd->status = bfa_fcport_clr_hardalpa(&bfad->bfa);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
int
bfad_iocmd_port_cfg_maxfrsize(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_port_cfg_maxfrsize_s *iocmd =
(struct bfa_bsg_port_cfg_maxfrsize_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_fcport_cfg_maxfrsize(&bfad->bfa, iocmd->maxfrsize);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
int
bfad_iocmd_port_cfg_bbsc(struct bfad_s *bfad, void *cmd, unsigned int v_cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
struct bfa_fcport_s *fcport = BFA_FCPORT_MOD(&bfad->bfa);
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
if (bfa_ioc_get_type(&bfad->bfa.ioc) == BFA_IOC_TYPE_FC) {
if (v_cmd == IOCMD_PORT_BBSC_ENABLE)
fcport->cfg.bb_scn_state = BFA_TRUE;
else if (v_cmd == IOCMD_PORT_BBSC_DISABLE)
fcport->cfg.bb_scn_state = BFA_FALSE;
}
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
return 0;
}
static int
bfad_iocmd_lport_get_attr(struct bfad_s *bfad, void *cmd)
{
struct bfa_fcs_lport_s *fcs_port;
struct bfa_bsg_lport_attr_s *iocmd = (struct bfa_bsg_lport_attr_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->pwwn);
if (fcs_port == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
goto out;
}
bfa_fcs_lport_get_attr(fcs_port, &iocmd->port_attr);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
int
bfad_iocmd_lport_get_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_fcs_lport_s *fcs_port;
struct bfa_bsg_lport_stats_s *iocmd =
(struct bfa_bsg_lport_stats_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->pwwn);
if (fcs_port == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
goto out;
}
bfa_fcs_lport_get_stats(fcs_port, &iocmd->port_stats);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
int
bfad_iocmd_lport_reset_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_fcs_lport_s *fcs_port;
struct bfa_bsg_reset_stats_s *iocmd =
(struct bfa_bsg_reset_stats_s *)cmd;
struct bfa_fcpim_s *fcpim = BFA_FCPIM(&bfad->bfa);
struct list_head *qe, *qen;
struct bfa_itnim_s *itnim;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->vpwwn);
if (fcs_port == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
goto out;
}
bfa_fcs_lport_clear_stats(fcs_port);
/* clear IO stats from all active itnims */
list_for_each_safe(qe, qen, &fcpim->itnim_q) {
itnim = (struct bfa_itnim_s *) qe;
if (itnim->rport->rport_info.lp_tag != fcs_port->lp_tag)
continue;
bfa_itnim_clear_stats(itnim);
}
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
int
bfad_iocmd_lport_get_iostats(struct bfad_s *bfad, void *cmd)
{
struct bfa_fcs_lport_s *fcs_port;
struct bfa_bsg_lport_iostats_s *iocmd =
(struct bfa_bsg_lport_iostats_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->pwwn);
if (fcs_port == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
goto out;
}
bfa_fcpim_port_iostats(&bfad->bfa, &iocmd->iostats,
fcs_port->lp_tag);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
int
bfad_iocmd_lport_get_rports(struct bfad_s *bfad, void *cmd,
unsigned int payload_len)
{
struct bfa_bsg_lport_get_rports_s *iocmd =
(struct bfa_bsg_lport_get_rports_s *)cmd;
struct bfa_fcs_lport_s *fcs_port;
unsigned long flags;
void *iocmd_bufptr;
if (iocmd->nrports == 0)
return -EINVAL;
if (bfad_chk_iocmd_sz(payload_len,
sizeof(struct bfa_bsg_lport_get_rports_s),
sizeof(wwn_t) * iocmd->nrports) != BFA_STATUS_OK) {
iocmd->status = BFA_STATUS_VERSION_FAIL;
return 0;
}
iocmd_bufptr = (char *)iocmd +
sizeof(struct bfa_bsg_lport_get_rports_s);
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->pwwn);
if (fcs_port == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
bfa_trc(bfad, 0);
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
goto out;
}
bfa_fcs_lport_get_rports(fcs_port, (wwn_t *)iocmd_bufptr,
&iocmd->nrports);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
int
bfad_iocmd_rport_get_attr(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_rport_attr_s *iocmd = (struct bfa_bsg_rport_attr_s *)cmd;
struct bfa_fcs_lport_s *fcs_port;
struct bfa_fcs_rport_s *fcs_rport;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->pwwn);
if (fcs_port == NULL) {
bfa_trc(bfad, 0);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
goto out;
}
fcs_rport = bfa_fcs_rport_lookup(fcs_port, iocmd->rpwwn);
if (fcs_rport == NULL) {
bfa_trc(bfad, 0);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_RWWN;
goto out;
}
bfa_fcs_rport_get_attr(fcs_rport, &iocmd->attr);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
static int
bfad_iocmd_rport_get_addr(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_rport_scsi_addr_s *iocmd =
(struct bfa_bsg_rport_scsi_addr_s *)cmd;
struct bfa_fcs_lport_s *fcs_port;
struct bfa_fcs_itnim_s *fcs_itnim;
struct bfad_itnim_s *drv_itnim;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->pwwn);
if (fcs_port == NULL) {
bfa_trc(bfad, 0);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
goto out;
}
fcs_itnim = bfa_fcs_itnim_lookup(fcs_port, iocmd->rpwwn);
if (fcs_itnim == NULL) {
bfa_trc(bfad, 0);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_RWWN;
goto out;
}
drv_itnim = fcs_itnim->itnim_drv;
if (drv_itnim && drv_itnim->im_port)
iocmd->host = drv_itnim->im_port->shost->host_no;
else {
bfa_trc(bfad, 0);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_RWWN;
goto out;
}
iocmd->target = drv_itnim->scsi_tgt_id;
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->bus = 0;
iocmd->lun = 0;
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
int
bfad_iocmd_rport_get_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_rport_stats_s *iocmd =
(struct bfa_bsg_rport_stats_s *)cmd;
struct bfa_fcs_lport_s *fcs_port;
struct bfa_fcs_rport_s *fcs_rport;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->pwwn);
if (fcs_port == NULL) {
bfa_trc(bfad, 0);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
goto out;
}
fcs_rport = bfa_fcs_rport_lookup(fcs_port, iocmd->rpwwn);
if (fcs_rport == NULL) {
bfa_trc(bfad, 0);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_RWWN;
goto out;
}
memcpy((void *)&iocmd->stats, (void *)&fcs_rport->stats,
sizeof(struct bfa_rport_stats_s));
memcpy((void *)&iocmd->stats.hal_stats,
(void *)&(bfa_fcs_rport_get_halrport(fcs_rport)->stats),
sizeof(struct bfa_rport_hal_stats_s));
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
int
bfad_iocmd_rport_clr_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_rport_reset_stats_s *iocmd =
(struct bfa_bsg_rport_reset_stats_s *)cmd;
struct bfa_fcs_lport_s *fcs_port;
struct bfa_fcs_rport_s *fcs_rport;
struct bfa_rport_s *rport;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->pwwn);
if (fcs_port == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
goto out;
}
fcs_rport = bfa_fcs_rport_lookup(fcs_port, iocmd->rpwwn);
if (fcs_rport == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_RWWN;
goto out;
}
memset((char *)&fcs_rport->stats, 0, sizeof(struct bfa_rport_stats_s));
rport = bfa_fcs_rport_get_halrport(fcs_rport);
memset(&rport->stats, 0, sizeof(rport->stats));
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
int
bfad_iocmd_rport_set_speed(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_rport_set_speed_s *iocmd =
(struct bfa_bsg_rport_set_speed_s *)cmd;
struct bfa_fcs_lport_s *fcs_port;
struct bfa_fcs_rport_s *fcs_rport;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->pwwn);
if (fcs_port == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
goto out;
}
fcs_rport = bfa_fcs_rport_lookup(fcs_port, iocmd->rpwwn);
if (fcs_rport == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_RWWN;
goto out;
}
fcs_rport->rpf.assigned_speed = iocmd->speed;
/* Set this speed in f/w only if the RPSC speed is not available */
if (fcs_rport->rpf.rpsc_speed == BFA_PORT_SPEED_UNKNOWN)
bfa_rport_speed(fcs_rport->bfa_rport, iocmd->speed);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
int
bfad_iocmd_vport_get_attr(struct bfad_s *bfad, void *cmd)
{
struct bfa_fcs_vport_s *fcs_vport;
struct bfa_bsg_vport_attr_s *iocmd = (struct bfa_bsg_vport_attr_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_vport = bfa_fcs_vport_lookup(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->vpwwn);
if (fcs_vport == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_VWWN;
goto out;
}
bfa_fcs_vport_get_attr(fcs_vport, &iocmd->vport_attr);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
int
bfad_iocmd_vport_get_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_fcs_vport_s *fcs_vport;
struct bfa_bsg_vport_stats_s *iocmd =
(struct bfa_bsg_vport_stats_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_vport = bfa_fcs_vport_lookup(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->vpwwn);
if (fcs_vport == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_VWWN;
goto out;
}
memcpy((void *)&iocmd->vport_stats, (void *)&fcs_vport->vport_stats,
sizeof(struct bfa_vport_stats_s));
memcpy((void *)&iocmd->vport_stats.port_stats,
(void *)&fcs_vport->lport.stats,
sizeof(struct bfa_lport_stats_s));
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
int
bfad_iocmd_vport_clr_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_fcs_vport_s *fcs_vport;
struct bfa_bsg_reset_stats_s *iocmd =
(struct bfa_bsg_reset_stats_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_vport = bfa_fcs_vport_lookup(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->vpwwn);
if (fcs_vport == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_VWWN;
goto out;
}
memset(&fcs_vport->vport_stats, 0, sizeof(struct bfa_vport_stats_s));
memset(&fcs_vport->lport.stats, 0, sizeof(struct bfa_lport_stats_s));
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
static int
bfad_iocmd_fabric_get_lports(struct bfad_s *bfad, void *cmd,
unsigned int payload_len)
{
struct bfa_bsg_fabric_get_lports_s *iocmd =
(struct bfa_bsg_fabric_get_lports_s *)cmd;
bfa_fcs_vf_t *fcs_vf;
uint32_t nports = iocmd->nports;
unsigned long flags;
void *iocmd_bufptr;
if (nports == 0) {
iocmd->status = BFA_STATUS_EINVAL;
goto out;
}
if (bfad_chk_iocmd_sz(payload_len,
sizeof(struct bfa_bsg_fabric_get_lports_s),
sizeof(wwn_t[iocmd->nports])) != BFA_STATUS_OK) {
iocmd->status = BFA_STATUS_VERSION_FAIL;
goto out;
}
iocmd_bufptr = (char *)iocmd +
sizeof(struct bfa_bsg_fabric_get_lports_s);
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_vf = bfa_fcs_vf_lookup(&bfad->bfa_fcs, iocmd->vf_id);
if (fcs_vf == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_VFID;
goto out;
}
bfa_fcs_vf_get_ports(fcs_vf, (wwn_t *)iocmd_bufptr, &nports);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->nports = nports;
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
int
bfad_iocmd_ratelim(struct bfad_s *bfad, unsigned int cmd, void *pcmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)pcmd;
struct bfa_fcport_s *fcport = BFA_FCPORT_MOD(&bfad->bfa);
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
if (cmd == IOCMD_RATELIM_ENABLE)
fcport->cfg.ratelimit = BFA_TRUE;
else if (cmd == IOCMD_RATELIM_DISABLE)
fcport->cfg.ratelimit = BFA_FALSE;
if (fcport->cfg.trl_def_speed == BFA_PORT_SPEED_UNKNOWN)
fcport->cfg.trl_def_speed = BFA_PORT_SPEED_1GBPS;
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_ratelim_speed(struct bfad_s *bfad, unsigned int cmd, void *pcmd)
{
struct bfa_bsg_trl_speed_s *iocmd = (struct bfa_bsg_trl_speed_s *)pcmd;
struct bfa_fcport_s *fcport = BFA_FCPORT_MOD(&bfad->bfa);
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
/* Auto and speeds greater than the supported speed, are invalid */
if ((iocmd->speed == BFA_PORT_SPEED_AUTO) ||
(iocmd->speed > fcport->speed_sup)) {
iocmd->status = BFA_STATUS_UNSUPP_SPEED;
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
fcport->cfg.trl_def_speed = iocmd->speed;
iocmd->status = BFA_STATUS_OK;
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
int
bfad_iocmd_cfg_fcpim(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_fcpim_s *iocmd = (struct bfa_bsg_fcpim_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
bfa_fcpim_path_tov_set(&bfad->bfa, iocmd->param);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_fcpim_get_modstats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_fcpim_modstats_s *iocmd =
(struct bfa_bsg_fcpim_modstats_s *)cmd;
struct bfa_fcpim_s *fcpim = BFA_FCPIM(&bfad->bfa);
struct list_head *qe, *qen;
struct bfa_itnim_s *itnim;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
/* accumulate IO stats from itnim */
memset((void *)&iocmd->modstats, 0, sizeof(struct bfa_itnim_iostats_s));
list_for_each_safe(qe, qen, &fcpim->itnim_q) {
itnim = (struct bfa_itnim_s *) qe;
bfa_fcpim_add_stats(&iocmd->modstats, &(itnim->stats));
}
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_fcpim_clr_modstats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_fcpim_modstatsclr_s *iocmd =
(struct bfa_bsg_fcpim_modstatsclr_s *)cmd;
struct bfa_fcpim_s *fcpim = BFA_FCPIM(&bfad->bfa);
struct list_head *qe, *qen;
struct bfa_itnim_s *itnim;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
list_for_each_safe(qe, qen, &fcpim->itnim_q) {
itnim = (struct bfa_itnim_s *) qe;
bfa_itnim_clear_stats(itnim);
}
memset(&fcpim->del_itn_stats, 0,
sizeof(struct bfa_fcpim_del_itn_stats_s));
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_fcpim_get_del_itn_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_fcpim_del_itn_stats_s *iocmd =
(struct bfa_bsg_fcpim_del_itn_stats_s *)cmd;
struct bfa_fcpim_s *fcpim = BFA_FCPIM(&bfad->bfa);
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
memcpy((void *)&iocmd->modstats, (void *)&fcpim->del_itn_stats,
sizeof(struct bfa_fcpim_del_itn_stats_s));
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
return 0;
}
static int
bfad_iocmd_itnim_get_attr(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_itnim_attr_s *iocmd = (struct bfa_bsg_itnim_attr_s *)cmd;
struct bfa_fcs_lport_s *fcs_port;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->lpwwn);
if (!fcs_port)
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
else
iocmd->status = bfa_fcs_itnim_attr_get(fcs_port,
iocmd->rpwwn, &iocmd->attr);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
static int
bfad_iocmd_itnim_get_iostats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_itnim_iostats_s *iocmd =
(struct bfa_bsg_itnim_iostats_s *)cmd;
struct bfa_fcs_lport_s *fcs_port;
struct bfa_fcs_itnim_s *itnim;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->lpwwn);
if (!fcs_port) {
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
bfa_trc(bfad, 0);
} else {
itnim = bfa_fcs_itnim_lookup(fcs_port, iocmd->rpwwn);
if (itnim == NULL)
iocmd->status = BFA_STATUS_UNKNOWN_RWWN;
else {
iocmd->status = BFA_STATUS_OK;
memcpy((void *)&iocmd->iostats, (void *)
&(bfa_fcs_itnim_get_halitn(itnim)->stats),
sizeof(struct bfa_itnim_iostats_s));
}
}
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
static int
bfad_iocmd_itnim_reset_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_rport_reset_stats_s *iocmd =
(struct bfa_bsg_rport_reset_stats_s *)cmd;
struct bfa_fcs_lport_s *fcs_port;
struct bfa_fcs_itnim_s *itnim;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->pwwn);
if (!fcs_port)
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
else {
itnim = bfa_fcs_itnim_lookup(fcs_port, iocmd->rpwwn);
if (itnim == NULL)
iocmd->status = BFA_STATUS_UNKNOWN_RWWN;
else {
iocmd->status = BFA_STATUS_OK;
bfa_fcs_itnim_stats_clear(fcs_port, iocmd->rpwwn);
bfa_itnim_clear_stats(bfa_fcs_itnim_get_halitn(itnim));
}
}
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
static int
bfad_iocmd_itnim_get_itnstats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_itnim_itnstats_s *iocmd =
(struct bfa_bsg_itnim_itnstats_s *)cmd;
struct bfa_fcs_lport_s *fcs_port;
struct bfa_fcs_itnim_s *itnim;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->lpwwn);
if (!fcs_port) {
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
bfa_trc(bfad, 0);
} else {
itnim = bfa_fcs_itnim_lookup(fcs_port, iocmd->rpwwn);
if (itnim == NULL)
iocmd->status = BFA_STATUS_UNKNOWN_RWWN;
else {
iocmd->status = BFA_STATUS_OK;
bfa_fcs_itnim_stats_get(fcs_port, iocmd->rpwwn,
&iocmd->itnstats);
}
}
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
int
bfad_iocmd_fcport_enable(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_fcport_enable(&bfad->bfa);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
int
bfad_iocmd_fcport_disable(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_fcport_disable(&bfad->bfa);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
int
bfad_iocmd_ioc_get_pcifn_cfg(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_pcifn_cfg_s *iocmd = (struct bfa_bsg_pcifn_cfg_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_ablk_query(&bfad->bfa.modules.ablk,
&iocmd->pcifn_cfg,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_pcifn_create(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_pcifn_s *iocmd = (struct bfa_bsg_pcifn_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_ablk_pf_create(&bfad->bfa.modules.ablk,
&iocmd->pcifn_id, iocmd->port,
iocmd->pcifn_class, iocmd->bandwidth,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_pcifn_delete(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_pcifn_s *iocmd = (struct bfa_bsg_pcifn_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_ablk_pf_delete(&bfad->bfa.modules.ablk,
iocmd->pcifn_id,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_pcifn_bw(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_pcifn_s *iocmd = (struct bfa_bsg_pcifn_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_ablk_pf_update(&bfad->bfa.modules.ablk,
iocmd->pcifn_id, iocmd->bandwidth,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
bfa_trc(bfad, iocmd->status);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
bfa_trc(bfad, iocmd->status);
out:
return 0;
}
int
bfad_iocmd_adapter_cfg_mode(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_adapter_cfg_mode_s *iocmd =
(struct bfa_bsg_adapter_cfg_mode_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags = 0;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_ablk_adapter_config(&bfad->bfa.modules.ablk,
iocmd->cfg.mode, iocmd->cfg.max_pf,
iocmd->cfg.max_vf, bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_port_cfg_mode(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_port_cfg_mode_s *iocmd =
(struct bfa_bsg_port_cfg_mode_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags = 0;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_ablk_port_config(&bfad->bfa.modules.ablk,
iocmd->instance, iocmd->cfg.mode,
iocmd->cfg.max_pf, iocmd->cfg.max_vf,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_ablk_optrom(struct bfad_s *bfad, unsigned int cmd, void *pcmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)pcmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
if (cmd == IOCMD_FLASH_ENABLE_OPTROM)
iocmd->status = bfa_ablk_optrom_en(&bfad->bfa.modules.ablk,
bfad_hcb_comp, &fcomp);
else
iocmd->status = bfa_ablk_optrom_dis(&bfad->bfa.modules.ablk,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_faa_query(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_faa_attr_s *iocmd = (struct bfa_bsg_faa_attr_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
iocmd->status = BFA_STATUS_OK;
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_faa_query(&bfad->bfa, &iocmd->faa_attr,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_cee_attr(struct bfad_s *bfad, void *cmd, unsigned int payload_len)
{
struct bfa_bsg_cee_attr_s *iocmd =
(struct bfa_bsg_cee_attr_s *)cmd;
void *iocmd_bufptr;
struct bfad_hal_comp cee_comp;
unsigned long flags;
if (bfad_chk_iocmd_sz(payload_len,
sizeof(struct bfa_bsg_cee_attr_s),
sizeof(struct bfa_cee_attr_s)) != BFA_STATUS_OK) {
iocmd->status = BFA_STATUS_VERSION_FAIL;
return 0;
}
iocmd_bufptr = (char *)iocmd + sizeof(struct bfa_bsg_cee_attr_s);
cee_comp.status = 0;
init_completion(&cee_comp.comp);
mutex_lock(&bfad_mutex);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_cee_get_attr(&bfad->bfa.modules.cee, iocmd_bufptr,
bfad_hcb_comp, &cee_comp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK) {
mutex_unlock(&bfad_mutex);
bfa_trc(bfad, 0x5555);
goto out;
}
wait_for_completion(&cee_comp.comp);
mutex_unlock(&bfad_mutex);
out:
return 0;
}
int
bfad_iocmd_cee_get_stats(struct bfad_s *bfad, void *cmd,
unsigned int payload_len)
{
struct bfa_bsg_cee_stats_s *iocmd =
(struct bfa_bsg_cee_stats_s *)cmd;
void *iocmd_bufptr;
struct bfad_hal_comp cee_comp;
unsigned long flags;
if (bfad_chk_iocmd_sz(payload_len,
sizeof(struct bfa_bsg_cee_stats_s),
sizeof(struct bfa_cee_stats_s)) != BFA_STATUS_OK) {
iocmd->status = BFA_STATUS_VERSION_FAIL;
return 0;
}
iocmd_bufptr = (char *)iocmd + sizeof(struct bfa_bsg_cee_stats_s);
cee_comp.status = 0;
init_completion(&cee_comp.comp);
mutex_lock(&bfad_mutex);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_cee_get_stats(&bfad->bfa.modules.cee, iocmd_bufptr,
bfad_hcb_comp, &cee_comp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK) {
mutex_unlock(&bfad_mutex);
bfa_trc(bfad, 0x5555);
goto out;
}
wait_for_completion(&cee_comp.comp);
mutex_unlock(&bfad_mutex);
out:
return 0;
}
int
bfad_iocmd_cee_reset_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_cee_reset_stats(&bfad->bfa.modules.cee, NULL, NULL);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
bfa_trc(bfad, 0x5555);
return 0;
}
int
bfad_iocmd_sfp_media(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_sfp_media_s *iocmd = (struct bfa_bsg_sfp_media_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_sfp_media(BFA_SFP_MOD(&bfad->bfa), &iocmd->media,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
bfa_trc(bfad, iocmd->status);
if (iocmd->status != BFA_STATUS_SFP_NOT_READY)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_sfp_speed(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_sfp_speed_s *iocmd = (struct bfa_bsg_sfp_speed_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_sfp_speed(BFA_SFP_MOD(&bfad->bfa), iocmd->speed,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
bfa_trc(bfad, iocmd->status);
if (iocmd->status != BFA_STATUS_SFP_NOT_READY)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_flash_get_attr(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_flash_attr_s *iocmd =
(struct bfa_bsg_flash_attr_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_flash_get_attr(BFA_FLASH(&bfad->bfa), &iocmd->attr,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_flash_erase_part(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_flash_s *iocmd = (struct bfa_bsg_flash_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_flash_erase_part(BFA_FLASH(&bfad->bfa), iocmd->type,
iocmd->instance, bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_flash_update_part(struct bfad_s *bfad, void *cmd,
unsigned int payload_len)
{
struct bfa_bsg_flash_s *iocmd = (struct bfa_bsg_flash_s *)cmd;
void *iocmd_bufptr;
struct bfad_hal_comp fcomp;
unsigned long flags;
if (bfad_chk_iocmd_sz(payload_len,
sizeof(struct bfa_bsg_flash_s),
iocmd->bufsz) != BFA_STATUS_OK) {
iocmd->status = BFA_STATUS_VERSION_FAIL;
return 0;
}
iocmd_bufptr = (char *)iocmd + sizeof(struct bfa_bsg_flash_s);
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_flash_update_part(BFA_FLASH(&bfad->bfa),
iocmd->type, iocmd->instance, iocmd_bufptr,
iocmd->bufsz, 0, bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_flash_read_part(struct bfad_s *bfad, void *cmd,
unsigned int payload_len)
{
struct bfa_bsg_flash_s *iocmd = (struct bfa_bsg_flash_s *)cmd;
struct bfad_hal_comp fcomp;
void *iocmd_bufptr;
unsigned long flags;
if (bfad_chk_iocmd_sz(payload_len,
sizeof(struct bfa_bsg_flash_s),
iocmd->bufsz) != BFA_STATUS_OK) {
iocmd->status = BFA_STATUS_VERSION_FAIL;
return 0;
}
iocmd_bufptr = (char *)iocmd + sizeof(struct bfa_bsg_flash_s);
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_flash_read_part(BFA_FLASH(&bfad->bfa), iocmd->type,
iocmd->instance, iocmd_bufptr, iocmd->bufsz, 0,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_diag_temp(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_diag_get_temp_s *iocmd =
(struct bfa_bsg_diag_get_temp_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_diag_tsensor_query(BFA_DIAG_MOD(&bfad->bfa),
&iocmd->result, bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
bfa_trc(bfad, iocmd->status);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_diag_memtest(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_diag_memtest_s *iocmd =
(struct bfa_bsg_diag_memtest_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_diag_memtest(BFA_DIAG_MOD(&bfad->bfa),
&iocmd->memtest, iocmd->pat,
&iocmd->result, bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
bfa_trc(bfad, iocmd->status);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_diag_loopback(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_diag_loopback_s *iocmd =
(struct bfa_bsg_diag_loopback_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_fcdiag_loopback(&bfad->bfa, iocmd->opmode,
iocmd->speed, iocmd->lpcnt, iocmd->pat,
&iocmd->result, bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
bfa_trc(bfad, iocmd->status);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_diag_fwping(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_diag_fwping_s *iocmd =
(struct bfa_bsg_diag_fwping_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_diag_fwping(BFA_DIAG_MOD(&bfad->bfa), iocmd->cnt,
iocmd->pattern, &iocmd->result,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
bfa_trc(bfad, iocmd->status);
if (iocmd->status != BFA_STATUS_OK)
goto out;
bfa_trc(bfad, 0x77771);
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_diag_queuetest(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_diag_qtest_s *iocmd = (struct bfa_bsg_diag_qtest_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_fcdiag_queuetest(&bfad->bfa, iocmd->force,
iocmd->queue, &iocmd->result,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_diag_sfp(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_sfp_show_s *iocmd =
(struct bfa_bsg_sfp_show_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_sfp_show(BFA_SFP_MOD(&bfad->bfa), &iocmd->sfp,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
bfa_trc(bfad, iocmd->status);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
bfa_trc(bfad, iocmd->status);
out:
return 0;
}
int
bfad_iocmd_diag_led(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_diag_led_s *iocmd = (struct bfa_bsg_diag_led_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_diag_ledtest(BFA_DIAG_MOD(&bfad->bfa),
&iocmd->ledtest);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
int
bfad_iocmd_diag_beacon_lport(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_diag_beacon_s *iocmd =
(struct bfa_bsg_diag_beacon_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_diag_beacon_port(BFA_DIAG_MOD(&bfad->bfa),
iocmd->beacon, iocmd->link_e2e_beacon,
iocmd->second);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
int
bfad_iocmd_diag_lb_stat(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_diag_lb_stat_s *iocmd =
(struct bfa_bsg_diag_lb_stat_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_fcdiag_lb_is_running(&bfad->bfa);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
bfa_trc(bfad, iocmd->status);
return 0;
}
int
bfad_iocmd_phy_get_attr(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_phy_attr_s *iocmd =
(struct bfa_bsg_phy_attr_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_phy_get_attr(BFA_PHY(&bfad->bfa), iocmd->instance,
&iocmd->attr, bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_phy_get_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_phy_stats_s *iocmd =
(struct bfa_bsg_phy_stats_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_phy_get_stats(BFA_PHY(&bfad->bfa), iocmd->instance,
&iocmd->stats, bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_phy_read(struct bfad_s *bfad, void *cmd, unsigned int payload_len)
{
struct bfa_bsg_phy_s *iocmd = (struct bfa_bsg_phy_s *)cmd;
struct bfad_hal_comp fcomp;
void *iocmd_bufptr;
unsigned long flags;
if (bfad_chk_iocmd_sz(payload_len,
sizeof(struct bfa_bsg_phy_s),
iocmd->bufsz) != BFA_STATUS_OK) {
iocmd->status = BFA_STATUS_VERSION_FAIL;
return 0;
}
iocmd_bufptr = (char *)iocmd + sizeof(struct bfa_bsg_phy_s);
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_phy_read(BFA_PHY(&bfad->bfa),
iocmd->instance, iocmd_bufptr, iocmd->bufsz,
0, bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
if (iocmd->status != BFA_STATUS_OK)
goto out;
out:
return 0;
}
int
bfad_iocmd_vhba_query(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_vhba_attr_s *iocmd =
(struct bfa_bsg_vhba_attr_s *)cmd;
struct bfa_vhba_attr_s *attr = &iocmd->attr;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
attr->pwwn = bfad->bfa.ioc.attr->pwwn;
attr->nwwn = bfad->bfa.ioc.attr->nwwn;
attr->plog_enabled = (bfa_boolean_t)bfad->bfa.plog->plog_enabled;
attr->io_profile = bfa_fcpim_get_io_profile(&bfad->bfa);
attr->path_tov = bfa_fcpim_path_tov_get(&bfad->bfa);
iocmd->status = BFA_STATUS_OK;
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
int
bfad_iocmd_phy_update(struct bfad_s *bfad, void *cmd, unsigned int payload_len)
{
struct bfa_bsg_phy_s *iocmd = (struct bfa_bsg_phy_s *)cmd;
void *iocmd_bufptr;
struct bfad_hal_comp fcomp;
unsigned long flags;
if (bfad_chk_iocmd_sz(payload_len,
sizeof(struct bfa_bsg_phy_s),
iocmd->bufsz) != BFA_STATUS_OK) {
iocmd->status = BFA_STATUS_VERSION_FAIL;
return 0;
}
iocmd_bufptr = (char *)iocmd + sizeof(struct bfa_bsg_phy_s);
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_phy_update(BFA_PHY(&bfad->bfa),
iocmd->instance, iocmd_bufptr, iocmd->bufsz,
0, bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_porglog_get(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_debug_s *iocmd = (struct bfa_bsg_debug_s *)cmd;
void *iocmd_bufptr;
if (iocmd->bufsz < sizeof(struct bfa_plog_s)) {
bfa_trc(bfad, sizeof(struct bfa_plog_s));
iocmd->status = BFA_STATUS_EINVAL;
goto out;
}
iocmd->status = BFA_STATUS_OK;
iocmd_bufptr = (char *)iocmd + sizeof(struct bfa_bsg_debug_s);
memcpy(iocmd_bufptr, (u8 *) &bfad->plog_buf, sizeof(struct bfa_plog_s));
out:
return 0;
}
#define BFA_DEBUG_FW_CORE_CHUNK_SZ 0x4000U /* 16K chunks for FW dump */
int
bfad_iocmd_debug_fw_core(struct bfad_s *bfad, void *cmd,
unsigned int payload_len)
{
struct bfa_bsg_debug_s *iocmd = (struct bfa_bsg_debug_s *)cmd;
void *iocmd_bufptr;
unsigned long flags;
u32 offset;
if (bfad_chk_iocmd_sz(payload_len, sizeof(struct bfa_bsg_debug_s),
BFA_DEBUG_FW_CORE_CHUNK_SZ) != BFA_STATUS_OK) {
iocmd->status = BFA_STATUS_VERSION_FAIL;
return 0;
}
if (iocmd->bufsz < BFA_DEBUG_FW_CORE_CHUNK_SZ ||
!IS_ALIGNED(iocmd->bufsz, sizeof(u16)) ||
!IS_ALIGNED(iocmd->offset, sizeof(u32))) {
bfa_trc(bfad, BFA_DEBUG_FW_CORE_CHUNK_SZ);
iocmd->status = BFA_STATUS_EINVAL;
goto out;
}
iocmd_bufptr = (char *)iocmd + sizeof(struct bfa_bsg_debug_s);
spin_lock_irqsave(&bfad->bfad_lock, flags);
offset = iocmd->offset;
iocmd->status = bfa_ioc_debug_fwcore(&bfad->bfa.ioc, iocmd_bufptr,
&offset, &iocmd->bufsz);
iocmd->offset = offset;
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
out:
return 0;
}
int
bfad_iocmd_debug_ctl(struct bfad_s *bfad, void *cmd, unsigned int v_cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
unsigned long flags;
if (v_cmd == IOCMD_DEBUG_FW_STATE_CLR) {
spin_lock_irqsave(&bfad->bfad_lock, flags);
bfad->bfa.ioc.dbg_fwsave_once = BFA_TRUE;
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
} else if (v_cmd == IOCMD_DEBUG_PORTLOG_CLR)
bfad->plog_buf.head = bfad->plog_buf.tail = 0;
else if (v_cmd == IOCMD_DEBUG_START_DTRC)
bfa_trc_init(bfad->trcmod);
else if (v_cmd == IOCMD_DEBUG_STOP_DTRC)
bfa_trc_stop(bfad->trcmod);
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_porglog_ctl(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_portlogctl_s *iocmd = (struct bfa_bsg_portlogctl_s *)cmd;
if (iocmd->ctl == BFA_TRUE)
bfad->plog_buf.plog_enabled = 1;
else
bfad->plog_buf.plog_enabled = 0;
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_fcpim_cfg_profile(struct bfad_s *bfad, void *cmd, unsigned int v_cmd)
{
struct bfa_bsg_fcpim_profile_s *iocmd =
(struct bfa_bsg_fcpim_profile_s *)cmd;
struct timeval tv;
unsigned long flags;
do_gettimeofday(&tv);
spin_lock_irqsave(&bfad->bfad_lock, flags);
if (v_cmd == IOCMD_FCPIM_PROFILE_ON)
iocmd->status = bfa_fcpim_profile_on(&bfad->bfa, tv.tv_sec);
else if (v_cmd == IOCMD_FCPIM_PROFILE_OFF)
iocmd->status = bfa_fcpim_profile_off(&bfad->bfa);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
static int
bfad_iocmd_itnim_get_ioprofile(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_itnim_ioprofile_s *iocmd =
(struct bfa_bsg_itnim_ioprofile_s *)cmd;
struct bfa_fcs_lport_s *fcs_port;
struct bfa_fcs_itnim_s *itnim;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->lpwwn);
if (!fcs_port)
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
else {
itnim = bfa_fcs_itnim_lookup(fcs_port, iocmd->rpwwn);
if (itnim == NULL)
iocmd->status = BFA_STATUS_UNKNOWN_RWWN;
else
iocmd->status = bfa_itnim_get_ioprofile(
bfa_fcs_itnim_get_halitn(itnim),
&iocmd->ioprofile);
}
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
int
bfad_iocmd_fcport_get_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_fcport_stats_s *iocmd =
(struct bfa_bsg_fcport_stats_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
struct bfa_cb_pending_q_s cb_qe;
init_completion(&fcomp.comp);
bfa_pending_q_init(&cb_qe, (bfa_cb_cbfn_t)bfad_hcb_comp,
&fcomp, &iocmd->stats);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_fcport_get_stats(&bfad->bfa, &cb_qe);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK) {
bfa_trc(bfad, iocmd->status);
goto out;
}
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_fcport_reset_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
struct bfa_cb_pending_q_s cb_qe;
init_completion(&fcomp.comp);
bfa_pending_q_init(&cb_qe, (bfa_cb_cbfn_t)bfad_hcb_comp, &fcomp, NULL);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_fcport_clear_stats(&bfad->bfa, &cb_qe);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK) {
bfa_trc(bfad, iocmd->status);
goto out;
}
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_boot_cfg(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_boot_s *iocmd = (struct bfa_bsg_boot_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_flash_update_part(BFA_FLASH(&bfad->bfa),
BFA_FLASH_PART_BOOT, PCI_FUNC(bfad->pcidev->devfn),
&iocmd->cfg, sizeof(struct bfa_boot_cfg_s), 0,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_boot_query(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_boot_s *iocmd = (struct bfa_bsg_boot_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_flash_read_part(BFA_FLASH(&bfad->bfa),
BFA_FLASH_PART_BOOT, PCI_FUNC(bfad->pcidev->devfn),
&iocmd->cfg, sizeof(struct bfa_boot_cfg_s), 0,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_preboot_query(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_preboot_s *iocmd = (struct bfa_bsg_preboot_s *)cmd;
struct bfi_iocfc_cfgrsp_s *cfgrsp = bfad->bfa.iocfc.cfgrsp;
struct bfa_boot_pbc_s *pbcfg = &iocmd->cfg;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
pbcfg->enable = cfgrsp->pbc_cfg.boot_enabled;
pbcfg->nbluns = cfgrsp->pbc_cfg.nbluns;
pbcfg->speed = cfgrsp->pbc_cfg.port_speed;
memcpy(pbcfg->pblun, cfgrsp->pbc_cfg.blun, sizeof(pbcfg->pblun));
iocmd->status = BFA_STATUS_OK;
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
int
bfad_iocmd_ethboot_cfg(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_ethboot_s *iocmd = (struct bfa_bsg_ethboot_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_flash_update_part(BFA_FLASH(&bfad->bfa),
BFA_FLASH_PART_PXECFG,
bfad->bfa.ioc.port_id, &iocmd->cfg,
sizeof(struct bfa_ethboot_cfg_s), 0,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_ethboot_query(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_ethboot_s *iocmd = (struct bfa_bsg_ethboot_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_flash_read_part(BFA_FLASH(&bfad->bfa),
BFA_FLASH_PART_PXECFG,
bfad->bfa.ioc.port_id, &iocmd->cfg,
sizeof(struct bfa_ethboot_cfg_s), 0,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_cfg_trunk(struct bfad_s *bfad, void *cmd, unsigned int v_cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
struct bfa_fcport_s *fcport = BFA_FCPORT_MOD(&bfad->bfa);
struct bfa_fcport_trunk_s *trunk = &fcport->trunk;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
if (v_cmd == IOCMD_TRUNK_ENABLE) {
trunk->attr.state = BFA_TRUNK_OFFLINE;
bfa_fcport_disable(&bfad->bfa);
fcport->cfg.trunked = BFA_TRUE;
} else if (v_cmd == IOCMD_TRUNK_DISABLE) {
trunk->attr.state = BFA_TRUNK_DISABLED;
bfa_fcport_disable(&bfad->bfa);
fcport->cfg.trunked = BFA_FALSE;
}
if (!bfa_fcport_is_disabled(&bfad->bfa))
bfa_fcport_enable(&bfad->bfa);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_trunk_get_attr(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_trunk_attr_s *iocmd = (struct bfa_bsg_trunk_attr_s *)cmd;
struct bfa_fcport_s *fcport = BFA_FCPORT_MOD(&bfad->bfa);
struct bfa_fcport_trunk_s *trunk = &fcport->trunk;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
memcpy((void *)&iocmd->attr, (void *)&trunk->attr,
sizeof(struct bfa_trunk_attr_s));
iocmd->attr.port_id = bfa_lps_get_base_pid(&bfad->bfa);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_qos(struct bfad_s *bfad, void *cmd, unsigned int v_cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
struct bfa_fcport_s *fcport = BFA_FCPORT_MOD(&bfad->bfa);
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
if (bfa_ioc_get_type(&bfad->bfa.ioc) == BFA_IOC_TYPE_FC) {
if (v_cmd == IOCMD_QOS_ENABLE)
fcport->cfg.qos_enabled = BFA_TRUE;
else if (v_cmd == IOCMD_QOS_DISABLE)
fcport->cfg.qos_enabled = BFA_FALSE;
}
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_qos_get_attr(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_qos_attr_s *iocmd = (struct bfa_bsg_qos_attr_s *)cmd;
struct bfa_fcport_s *fcport = BFA_FCPORT_MOD(&bfad->bfa);
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->attr.state = fcport->qos_attr.state;
iocmd->attr.total_bb_cr = be32_to_cpu(fcport->qos_attr.total_bb_cr);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_qos_get_vc_attr(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_qos_vc_attr_s *iocmd =
(struct bfa_bsg_qos_vc_attr_s *)cmd;
struct bfa_fcport_s *fcport = BFA_FCPORT_MOD(&bfad->bfa);
struct bfa_qos_vc_attr_s *bfa_vc_attr = &fcport->qos_vc_attr;
unsigned long flags;
u32 i = 0;
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->attr.total_vc_count = be16_to_cpu(bfa_vc_attr->total_vc_count);
iocmd->attr.shared_credit = be16_to_cpu(bfa_vc_attr->shared_credit);
iocmd->attr.elp_opmode_flags =
be32_to_cpu(bfa_vc_attr->elp_opmode_flags);
/* Individual VC info */
while (i < iocmd->attr.total_vc_count) {
iocmd->attr.vc_info[i].vc_credit =
bfa_vc_attr->vc_info[i].vc_credit;
iocmd->attr.vc_info[i].borrow_credit =
bfa_vc_attr->vc_info[i].borrow_credit;
iocmd->attr.vc_info[i].priority =
bfa_vc_attr->vc_info[i].priority;
i++;
}
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_qos_get_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_fcport_stats_s *iocmd =
(struct bfa_bsg_fcport_stats_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
struct bfa_cb_pending_q_s cb_qe;
init_completion(&fcomp.comp);
bfa_pending_q_init(&cb_qe, (bfa_cb_cbfn_t)bfad_hcb_comp,
&fcomp, &iocmd->stats);
spin_lock_irqsave(&bfad->bfad_lock, flags);
WARN_ON(!bfa_ioc_get_fcmode(&bfad->bfa.ioc));
iocmd->status = bfa_fcport_get_stats(&bfad->bfa, &cb_qe);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK) {
bfa_trc(bfad, iocmd->status);
goto out;
}
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_qos_reset_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
struct bfa_cb_pending_q_s cb_qe;
init_completion(&fcomp.comp);
bfa_pending_q_init(&cb_qe, (bfa_cb_cbfn_t)bfad_hcb_comp,
&fcomp, NULL);
spin_lock_irqsave(&bfad->bfad_lock, flags);
WARN_ON(!bfa_ioc_get_fcmode(&bfad->bfa.ioc));
iocmd->status = bfa_fcport_clear_stats(&bfad->bfa, &cb_qe);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK) {
bfa_trc(bfad, iocmd->status);
goto out;
}
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_vf_get_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_vf_stats_s *iocmd =
(struct bfa_bsg_vf_stats_s *)cmd;
struct bfa_fcs_fabric_s *fcs_vf;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_vf = bfa_fcs_vf_lookup(&bfad->bfa_fcs, iocmd->vf_id);
if (fcs_vf == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_VFID;
goto out;
}
memcpy((void *)&iocmd->stats, (void *)&fcs_vf->stats,
sizeof(struct bfa_vf_stats_s));
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
int
bfad_iocmd_vf_clr_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_vf_reset_stats_s *iocmd =
(struct bfa_bsg_vf_reset_stats_s *)cmd;
struct bfa_fcs_fabric_s *fcs_vf;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_vf = bfa_fcs_vf_lookup(&bfad->bfa_fcs, iocmd->vf_id);
if (fcs_vf == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_VFID;
goto out;
}
memset((void *)&fcs_vf->stats, 0, sizeof(struct bfa_vf_stats_s));
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
/* Function to reset the LUN SCAN mode */
static void
bfad_iocmd_lunmask_reset_lunscan_mode(struct bfad_s *bfad, int lunmask_cfg)
{
struct bfad_im_port_s *pport_im = bfad->pport.im_port;
struct bfad_vport_s *vport = NULL;
/* Set the scsi device LUN SCAN flags for base port */
bfad_reset_sdev_bflags(pport_im, lunmask_cfg);
/* Set the scsi device LUN SCAN flags for the vports */
list_for_each_entry(vport, &bfad->vport_list, list_entry)
bfad_reset_sdev_bflags(vport->drv_port.im_port, lunmask_cfg);
}
int
bfad_iocmd_lunmask(struct bfad_s *bfad, void *pcmd, unsigned int v_cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)pcmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
if (v_cmd == IOCMD_FCPIM_LUNMASK_ENABLE) {
iocmd->status = bfa_fcpim_lunmask_update(&bfad->bfa, BFA_TRUE);
/* Set the LUN Scanning mode to be Sequential scan */
if (iocmd->status == BFA_STATUS_OK)
bfad_iocmd_lunmask_reset_lunscan_mode(bfad, BFA_TRUE);
} else if (v_cmd == IOCMD_FCPIM_LUNMASK_DISABLE) {
iocmd->status = bfa_fcpim_lunmask_update(&bfad->bfa, BFA_FALSE);
/* Set the LUN Scanning mode to default REPORT_LUNS scan */
if (iocmd->status == BFA_STATUS_OK)
bfad_iocmd_lunmask_reset_lunscan_mode(bfad, BFA_FALSE);
} else if (v_cmd == IOCMD_FCPIM_LUNMASK_CLEAR)
iocmd->status = bfa_fcpim_lunmask_clear(&bfad->bfa);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
int
bfad_iocmd_fcpim_lunmask_query(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_fcpim_lunmask_query_s *iocmd =
(struct bfa_bsg_fcpim_lunmask_query_s *)cmd;
struct bfa_lunmask_cfg_s *lun_mask = &iocmd->lun_mask;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_fcpim_lunmask_query(&bfad->bfa, lun_mask);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
int
bfad_iocmd_fcpim_cfg_lunmask(struct bfad_s *bfad, void *cmd, unsigned int v_cmd)
{
struct bfa_bsg_fcpim_lunmask_s *iocmd =
(struct bfa_bsg_fcpim_lunmask_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
if (v_cmd == IOCMD_FCPIM_LUNMASK_ADD)
iocmd->status = bfa_fcpim_lunmask_add(&bfad->bfa, iocmd->vf_id,
&iocmd->pwwn, iocmd->rpwwn, iocmd->lun);
else if (v_cmd == IOCMD_FCPIM_LUNMASK_DELETE)
iocmd->status = bfa_fcpim_lunmask_delete(&bfad->bfa,
iocmd->vf_id, &iocmd->pwwn,
iocmd->rpwwn, iocmd->lun);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
static int
bfad_iocmd_handler(struct bfad_s *bfad, unsigned int cmd, void *iocmd,
unsigned int payload_len)
{
int rc = -EINVAL;
switch (cmd) {
case IOCMD_IOC_ENABLE:
rc = bfad_iocmd_ioc_enable(bfad, iocmd);
break;
case IOCMD_IOC_DISABLE:
rc = bfad_iocmd_ioc_disable(bfad, iocmd);
break;
case IOCMD_IOC_GET_INFO:
rc = bfad_iocmd_ioc_get_info(bfad, iocmd);
break;
case IOCMD_IOC_GET_ATTR:
rc = bfad_iocmd_ioc_get_attr(bfad, iocmd);
break;
case IOCMD_IOC_GET_STATS:
rc = bfad_iocmd_ioc_get_stats(bfad, iocmd);
break;
case IOCMD_IOC_GET_FWSTATS:
rc = bfad_iocmd_ioc_get_fwstats(bfad, iocmd, payload_len);
break;
case IOCMD_IOC_RESET_STATS:
case IOCMD_IOC_RESET_FWSTATS:
rc = bfad_iocmd_ioc_reset_stats(bfad, iocmd, cmd);
break;
case IOCMD_IOC_SET_ADAPTER_NAME:
case IOCMD_IOC_SET_PORT_NAME:
rc = bfad_iocmd_ioc_set_name(bfad, iocmd, cmd);
break;
case IOCMD_IOCFC_GET_ATTR:
rc = bfad_iocmd_iocfc_get_attr(bfad, iocmd);
break;
case IOCMD_IOCFC_SET_INTR:
rc = bfad_iocmd_iocfc_set_intr(bfad, iocmd);
break;
case IOCMD_PORT_ENABLE:
rc = bfad_iocmd_port_enable(bfad, iocmd);
break;
case IOCMD_PORT_DISABLE:
rc = bfad_iocmd_port_disable(bfad, iocmd);
break;
case IOCMD_PORT_GET_ATTR:
rc = bfad_iocmd_port_get_attr(bfad, iocmd);
break;
case IOCMD_PORT_GET_STATS:
rc = bfad_iocmd_port_get_stats(bfad, iocmd, payload_len);
break;
case IOCMD_PORT_RESET_STATS:
rc = bfad_iocmd_port_reset_stats(bfad, iocmd);
break;
case IOCMD_PORT_CFG_TOPO:
case IOCMD_PORT_CFG_SPEED:
case IOCMD_PORT_CFG_ALPA:
case IOCMD_PORT_CLR_ALPA:
rc = bfad_iocmd_set_port_cfg(bfad, iocmd, cmd);
break;
case IOCMD_PORT_CFG_MAXFRSZ:
rc = bfad_iocmd_port_cfg_maxfrsize(bfad, iocmd);
break;
case IOCMD_PORT_BBSC_ENABLE:
case IOCMD_PORT_BBSC_DISABLE:
rc = bfad_iocmd_port_cfg_bbsc(bfad, iocmd, cmd);
break;
case IOCMD_LPORT_GET_ATTR:
rc = bfad_iocmd_lport_get_attr(bfad, iocmd);
break;
case IOCMD_LPORT_GET_STATS:
rc = bfad_iocmd_lport_get_stats(bfad, iocmd);
break;
case IOCMD_LPORT_RESET_STATS:
rc = bfad_iocmd_lport_reset_stats(bfad, iocmd);
break;
case IOCMD_LPORT_GET_IOSTATS:
rc = bfad_iocmd_lport_get_iostats(bfad, iocmd);
break;
case IOCMD_LPORT_GET_RPORTS:
rc = bfad_iocmd_lport_get_rports(bfad, iocmd, payload_len);
break;
case IOCMD_RPORT_GET_ATTR:
rc = bfad_iocmd_rport_get_attr(bfad, iocmd);
break;
case IOCMD_RPORT_GET_ADDR:
rc = bfad_iocmd_rport_get_addr(bfad, iocmd);
break;
case IOCMD_RPORT_GET_STATS:
rc = bfad_iocmd_rport_get_stats(bfad, iocmd);
break;
case IOCMD_RPORT_RESET_STATS:
rc = bfad_iocmd_rport_clr_stats(bfad, iocmd);
break;
case IOCMD_RPORT_SET_SPEED:
rc = bfad_iocmd_rport_set_speed(bfad, iocmd);
break;
case IOCMD_VPORT_GET_ATTR:
rc = bfad_iocmd_vport_get_attr(bfad, iocmd);
break;
case IOCMD_VPORT_GET_STATS:
rc = bfad_iocmd_vport_get_stats(bfad, iocmd);
break;
case IOCMD_VPORT_RESET_STATS:
rc = bfad_iocmd_vport_clr_stats(bfad, iocmd);
break;
case IOCMD_FABRIC_GET_LPORTS:
rc = bfad_iocmd_fabric_get_lports(bfad, iocmd, payload_len);
break;
case IOCMD_RATELIM_ENABLE:
case IOCMD_RATELIM_DISABLE:
rc = bfad_iocmd_ratelim(bfad, cmd, iocmd);
break;
case IOCMD_RATELIM_DEF_SPEED:
rc = bfad_iocmd_ratelim_speed(bfad, cmd, iocmd);
break;
case IOCMD_FCPIM_FAILOVER:
rc = bfad_iocmd_cfg_fcpim(bfad, iocmd);
break;
case IOCMD_FCPIM_MODSTATS:
rc = bfad_iocmd_fcpim_get_modstats(bfad, iocmd);
break;
case IOCMD_FCPIM_MODSTATSCLR:
rc = bfad_iocmd_fcpim_clr_modstats(bfad, iocmd);
break;
case IOCMD_FCPIM_DEL_ITN_STATS:
rc = bfad_iocmd_fcpim_get_del_itn_stats(bfad, iocmd);
break;
case IOCMD_ITNIM_GET_ATTR:
rc = bfad_iocmd_itnim_get_attr(bfad, iocmd);
break;
case IOCMD_ITNIM_GET_IOSTATS:
rc = bfad_iocmd_itnim_get_iostats(bfad, iocmd);
break;
case IOCMD_ITNIM_RESET_STATS:
rc = bfad_iocmd_itnim_reset_stats(bfad, iocmd);
break;
case IOCMD_ITNIM_GET_ITNSTATS:
rc = bfad_iocmd_itnim_get_itnstats(bfad, iocmd);
break;
case IOCMD_FCPORT_ENABLE:
rc = bfad_iocmd_fcport_enable(bfad, iocmd);
break;
case IOCMD_FCPORT_DISABLE:
rc = bfad_iocmd_fcport_disable(bfad, iocmd);
break;
case IOCMD_IOC_PCIFN_CFG:
rc = bfad_iocmd_ioc_get_pcifn_cfg(bfad, iocmd);
break;
case IOCMD_PCIFN_CREATE:
rc = bfad_iocmd_pcifn_create(bfad, iocmd);
break;
case IOCMD_PCIFN_DELETE:
rc = bfad_iocmd_pcifn_delete(bfad, iocmd);
break;
case IOCMD_PCIFN_BW:
rc = bfad_iocmd_pcifn_bw(bfad, iocmd);
break;
case IOCMD_ADAPTER_CFG_MODE:
rc = bfad_iocmd_adapter_cfg_mode(bfad, iocmd);
break;
case IOCMD_PORT_CFG_MODE:
rc = bfad_iocmd_port_cfg_mode(bfad, iocmd);
break;
case IOCMD_FLASH_ENABLE_OPTROM:
case IOCMD_FLASH_DISABLE_OPTROM:
rc = bfad_iocmd_ablk_optrom(bfad, cmd, iocmd);
break;
case IOCMD_FAA_QUERY:
rc = bfad_iocmd_faa_query(bfad, iocmd);
break;
case IOCMD_CEE_GET_ATTR:
rc = bfad_iocmd_cee_attr(bfad, iocmd, payload_len);
break;
case IOCMD_CEE_GET_STATS:
rc = bfad_iocmd_cee_get_stats(bfad, iocmd, payload_len);
break;
case IOCMD_CEE_RESET_STATS:
rc = bfad_iocmd_cee_reset_stats(bfad, iocmd);
break;
case IOCMD_SFP_MEDIA:
rc = bfad_iocmd_sfp_media(bfad, iocmd);
break;
case IOCMD_SFP_SPEED:
rc = bfad_iocmd_sfp_speed(bfad, iocmd);
break;
case IOCMD_FLASH_GET_ATTR:
rc = bfad_iocmd_flash_get_attr(bfad, iocmd);
break;
case IOCMD_FLASH_ERASE_PART:
rc = bfad_iocmd_flash_erase_part(bfad, iocmd);
break;
case IOCMD_FLASH_UPDATE_PART:
rc = bfad_iocmd_flash_update_part(bfad, iocmd, payload_len);
break;
case IOCMD_FLASH_READ_PART:
rc = bfad_iocmd_flash_read_part(bfad, iocmd, payload_len);
break;
case IOCMD_DIAG_TEMP:
rc = bfad_iocmd_diag_temp(bfad, iocmd);
break;
case IOCMD_DIAG_MEMTEST:
rc = bfad_iocmd_diag_memtest(bfad, iocmd);
break;
case IOCMD_DIAG_LOOPBACK:
rc = bfad_iocmd_diag_loopback(bfad, iocmd);
break;
case IOCMD_DIAG_FWPING:
rc = bfad_iocmd_diag_fwping(bfad, iocmd);
break;
case IOCMD_DIAG_QUEUETEST:
rc = bfad_iocmd_diag_queuetest(bfad, iocmd);
break;
case IOCMD_DIAG_SFP:
rc = bfad_iocmd_diag_sfp(bfad, iocmd);
break;
case IOCMD_DIAG_LED:
rc = bfad_iocmd_diag_led(bfad, iocmd);
break;
case IOCMD_DIAG_BEACON_LPORT:
rc = bfad_iocmd_diag_beacon_lport(bfad, iocmd);
break;
case IOCMD_DIAG_LB_STAT:
rc = bfad_iocmd_diag_lb_stat(bfad, iocmd);
break;
case IOCMD_PHY_GET_ATTR:
rc = bfad_iocmd_phy_get_attr(bfad, iocmd);
break;
case IOCMD_PHY_GET_STATS:
rc = bfad_iocmd_phy_get_stats(bfad, iocmd);
break;
case IOCMD_PHY_UPDATE_FW:
rc = bfad_iocmd_phy_update(bfad, iocmd, payload_len);
break;
case IOCMD_PHY_READ_FW:
rc = bfad_iocmd_phy_read(bfad, iocmd, payload_len);
break;
case IOCMD_VHBA_QUERY:
rc = bfad_iocmd_vhba_query(bfad, iocmd);
break;
case IOCMD_DEBUG_PORTLOG:
rc = bfad_iocmd_porglog_get(bfad, iocmd);
break;
case IOCMD_DEBUG_FW_CORE:
rc = bfad_iocmd_debug_fw_core(bfad, iocmd, payload_len);
break;
case IOCMD_DEBUG_FW_STATE_CLR:
case IOCMD_DEBUG_PORTLOG_CLR:
case IOCMD_DEBUG_START_DTRC:
case IOCMD_DEBUG_STOP_DTRC:
rc = bfad_iocmd_debug_ctl(bfad, iocmd, cmd);
break;
case IOCMD_DEBUG_PORTLOG_CTL:
rc = bfad_iocmd_porglog_ctl(bfad, iocmd);
break;
case IOCMD_FCPIM_PROFILE_ON:
case IOCMD_FCPIM_PROFILE_OFF:
rc = bfad_iocmd_fcpim_cfg_profile(bfad, iocmd, cmd);
break;
case IOCMD_ITNIM_GET_IOPROFILE:
rc = bfad_iocmd_itnim_get_ioprofile(bfad, iocmd);
break;
case IOCMD_FCPORT_GET_STATS:
rc = bfad_iocmd_fcport_get_stats(bfad, iocmd);
break;
case IOCMD_FCPORT_RESET_STATS:
rc = bfad_iocmd_fcport_reset_stats(bfad, iocmd);
break;
case IOCMD_BOOT_CFG:
rc = bfad_iocmd_boot_cfg(bfad, iocmd);
break;
case IOCMD_BOOT_QUERY:
rc = bfad_iocmd_boot_query(bfad, iocmd);
break;
case IOCMD_PREBOOT_QUERY:
rc = bfad_iocmd_preboot_query(bfad, iocmd);
break;
case IOCMD_ETHBOOT_CFG:
rc = bfad_iocmd_ethboot_cfg(bfad, iocmd);
break;
case IOCMD_ETHBOOT_QUERY:
rc = bfad_iocmd_ethboot_query(bfad, iocmd);
break;
case IOCMD_TRUNK_ENABLE:
case IOCMD_TRUNK_DISABLE:
rc = bfad_iocmd_cfg_trunk(bfad, iocmd, cmd);
break;
case IOCMD_TRUNK_GET_ATTR:
rc = bfad_iocmd_trunk_get_attr(bfad, iocmd);
break;
case IOCMD_QOS_ENABLE:
case IOCMD_QOS_DISABLE:
rc = bfad_iocmd_qos(bfad, iocmd, cmd);
break;
case IOCMD_QOS_GET_ATTR:
rc = bfad_iocmd_qos_get_attr(bfad, iocmd);
break;
case IOCMD_QOS_GET_VC_ATTR:
rc = bfad_iocmd_qos_get_vc_attr(bfad, iocmd);
break;
case IOCMD_QOS_GET_STATS:
rc = bfad_iocmd_qos_get_stats(bfad, iocmd);
break;
case IOCMD_QOS_RESET_STATS:
rc = bfad_iocmd_qos_reset_stats(bfad, iocmd);
break;
case IOCMD_VF_GET_STATS:
rc = bfad_iocmd_vf_get_stats(bfad, iocmd);
break;
case IOCMD_VF_RESET_STATS:
rc = bfad_iocmd_vf_clr_stats(bfad, iocmd);
break;
case IOCMD_FCPIM_LUNMASK_ENABLE:
case IOCMD_FCPIM_LUNMASK_DISABLE:
case IOCMD_FCPIM_LUNMASK_CLEAR:
rc = bfad_iocmd_lunmask(bfad, iocmd, cmd);
break;
case IOCMD_FCPIM_LUNMASK_QUERY:
rc = bfad_iocmd_fcpim_lunmask_query(bfad, iocmd);
break;
case IOCMD_FCPIM_LUNMASK_ADD:
case IOCMD_FCPIM_LUNMASK_DELETE:
rc = bfad_iocmd_fcpim_cfg_lunmask(bfad, iocmd, cmd);
break;
default:
rc = -EINVAL;
break;
}
return rc;
}
static int
bfad_im_bsg_vendor_request(struct fc_bsg_job *job)
{
uint32_t vendor_cmd = job->request->rqst_data.h_vendor.vendor_cmd[0];
struct bfad_im_port_s *im_port =
(struct bfad_im_port_s *) job->shost->hostdata[0];
struct bfad_s *bfad = im_port->bfad;
struct request_queue *request_q = job->req->q;
void *payload_kbuf;
int rc = -EINVAL;
/*
* Set the BSG device request_queue size to 256 to support
* payloads larger than 512*1024K bytes.
*/
blk_queue_max_segments(request_q, 256);
/* Allocate a temp buffer to hold the passed in user space command */
payload_kbuf = kzalloc(job->request_payload.payload_len, GFP_KERNEL);
if (!payload_kbuf) {
rc = -ENOMEM;
goto out;
}
/* Copy the sg_list passed in to a linear buffer: holds the cmnd data */
sg_copy_to_buffer(job->request_payload.sg_list,
job->request_payload.sg_cnt, payload_kbuf,
job->request_payload.payload_len);
/* Invoke IOCMD handler - to handle all the vendor command requests */
rc = bfad_iocmd_handler(bfad, vendor_cmd, payload_kbuf,
job->request_payload.payload_len);
if (rc != BFA_STATUS_OK)
goto error;
/* Copy the response data to the job->reply_payload sg_list */
sg_copy_from_buffer(job->reply_payload.sg_list,
job->reply_payload.sg_cnt,
payload_kbuf,
job->reply_payload.payload_len);
/* free the command buffer */
kfree(payload_kbuf);
/* Fill the BSG job reply data */
job->reply_len = job->reply_payload.payload_len;
job->reply->reply_payload_rcv_len = job->reply_payload.payload_len;
job->reply->result = rc;
job->job_done(job);
return rc;
error:
/* free the command buffer */
kfree(payload_kbuf);
out:
job->reply->result = rc;
job->reply_len = sizeof(uint32_t);
job->reply->reply_payload_rcv_len = 0;
return rc;
}
/* FC passthru call backs */
u64
bfad_fcxp_get_req_sgaddr_cb(void *bfad_fcxp, int sgeid)
{
struct bfad_fcxp *drv_fcxp = bfad_fcxp;
struct bfa_sge_s *sge;
u64 addr;
sge = drv_fcxp->req_sge + sgeid;
addr = (u64)(size_t) sge->sg_addr;
return addr;
}
u32
bfad_fcxp_get_req_sglen_cb(void *bfad_fcxp, int sgeid)
{
struct bfad_fcxp *drv_fcxp = bfad_fcxp;
struct bfa_sge_s *sge;
sge = drv_fcxp->req_sge + sgeid;
return sge->sg_len;
}
u64
bfad_fcxp_get_rsp_sgaddr_cb(void *bfad_fcxp, int sgeid)
{
struct bfad_fcxp *drv_fcxp = bfad_fcxp;
struct bfa_sge_s *sge;
u64 addr;
sge = drv_fcxp->rsp_sge + sgeid;
addr = (u64)(size_t) sge->sg_addr;
return addr;
}
u32
bfad_fcxp_get_rsp_sglen_cb(void *bfad_fcxp, int sgeid)
{
struct bfad_fcxp *drv_fcxp = bfad_fcxp;
struct bfa_sge_s *sge;
sge = drv_fcxp->rsp_sge + sgeid;
return sge->sg_len;
}
void
bfad_send_fcpt_cb(void *bfad_fcxp, struct bfa_fcxp_s *fcxp, void *cbarg,
bfa_status_t req_status, u32 rsp_len, u32 resid_len,
struct fchs_s *rsp_fchs)
{
struct bfad_fcxp *drv_fcxp = bfad_fcxp;
drv_fcxp->req_status = req_status;
drv_fcxp->rsp_len = rsp_len;
/* bfa_fcxp will be automatically freed by BFA */
drv_fcxp->bfa_fcxp = NULL;
complete(&drv_fcxp->comp);
}
struct bfad_buf_info *
bfad_fcxp_map_sg(struct bfad_s *bfad, void *payload_kbuf,
uint32_t payload_len, uint32_t *num_sgles)
{
struct bfad_buf_info *buf_base, *buf_info;
struct bfa_sge_s *sg_table;
int sge_num = 1;
buf_base = kzalloc((sizeof(struct bfad_buf_info) +
sizeof(struct bfa_sge_s)) * sge_num, GFP_KERNEL);
if (!buf_base)
return NULL;
sg_table = (struct bfa_sge_s *) (((uint8_t *)buf_base) +
(sizeof(struct bfad_buf_info) * sge_num));
/* Allocate dma coherent memory */
buf_info = buf_base;
buf_info->size = payload_len;
buf_info->virt = dma_alloc_coherent(&bfad->pcidev->dev, buf_info->size,
&buf_info->phys, GFP_KERNEL);
if (!buf_info->virt)
goto out_free_mem;
/* copy the linear bsg buffer to buf_info */
memset(buf_info->virt, 0, buf_info->size);
memcpy(buf_info->virt, payload_kbuf, buf_info->size);
/*
* Setup SG table
*/
sg_table->sg_len = buf_info->size;
sg_table->sg_addr = (void *)(size_t) buf_info->phys;
*num_sgles = sge_num;
return buf_base;
out_free_mem:
kfree(buf_base);
return NULL;
}
void
bfad_fcxp_free_mem(struct bfad_s *bfad, struct bfad_buf_info *buf_base,
uint32_t num_sgles)
{
int i;
struct bfad_buf_info *buf_info = buf_base;
if (buf_base) {
for (i = 0; i < num_sgles; buf_info++, i++) {
if (buf_info->virt != NULL)
dma_free_coherent(&bfad->pcidev->dev,
buf_info->size, buf_info->virt,
buf_info->phys);
}
kfree(buf_base);
}
}
int
bfad_fcxp_bsg_send(struct fc_bsg_job *job, struct bfad_fcxp *drv_fcxp,
bfa_bsg_fcpt_t *bsg_fcpt)
{
struct bfa_fcxp_s *hal_fcxp;
struct bfad_s *bfad = drv_fcxp->port->bfad;
unsigned long flags;
uint8_t lp_tag;
spin_lock_irqsave(&bfad->bfad_lock, flags);
/* Allocate bfa_fcxp structure */
hal_fcxp = bfa_fcxp_alloc(drv_fcxp, &bfad->bfa,
drv_fcxp->num_req_sgles,
drv_fcxp->num_rsp_sgles,
bfad_fcxp_get_req_sgaddr_cb,
bfad_fcxp_get_req_sglen_cb,
bfad_fcxp_get_rsp_sgaddr_cb,
bfad_fcxp_get_rsp_sglen_cb);
if (!hal_fcxp) {
bfa_trc(bfad, 0);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return BFA_STATUS_ENOMEM;
}
drv_fcxp->bfa_fcxp = hal_fcxp;
lp_tag = bfa_lps_get_tag_from_pid(&bfad->bfa, bsg_fcpt->fchs.s_id);
bfa_fcxp_send(hal_fcxp, drv_fcxp->bfa_rport, bsg_fcpt->vf_id, lp_tag,
bsg_fcpt->cts, bsg_fcpt->cos,
job->request_payload.payload_len,
&bsg_fcpt->fchs, bfad_send_fcpt_cb, bfad,
job->reply_payload.payload_len, bsg_fcpt->tsecs);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return BFA_STATUS_OK;
}
int
bfad_im_bsg_els_ct_request(struct fc_bsg_job *job)
{
struct bfa_bsg_data *bsg_data;
struct bfad_im_port_s *im_port =
(struct bfad_im_port_s *) job->shost->hostdata[0];
struct bfad_s *bfad = im_port->bfad;
bfa_bsg_fcpt_t *bsg_fcpt;
struct bfad_fcxp *drv_fcxp;
struct bfa_fcs_lport_s *fcs_port;
struct bfa_fcs_rport_s *fcs_rport;
uint32_t command_type = job->request->msgcode;
unsigned long flags;
struct bfad_buf_info *rsp_buf_info;
void *req_kbuf = NULL, *rsp_kbuf = NULL;
int rc = -EINVAL;
job->reply_len = sizeof(uint32_t); /* Atleast uint32_t reply_len */
job->reply->reply_payload_rcv_len = 0;
/* Get the payload passed in from userspace */
bsg_data = (struct bfa_bsg_data *) (((char *)job->request) +
sizeof(struct fc_bsg_request));
if (bsg_data == NULL)
goto out;
/*
* Allocate buffer for bsg_fcpt and do a copy_from_user op for payload
* buffer of size bsg_data->payload_len
*/
bsg_fcpt = kzalloc(bsg_data->payload_len, GFP_KERNEL);
if (!bsg_fcpt)
goto out;
if (copy_from_user((uint8_t *)bsg_fcpt, bsg_data->payload,
bsg_data->payload_len)) {
kfree(bsg_fcpt);
goto out;
}
drv_fcxp = kzalloc(sizeof(struct bfad_fcxp), GFP_KERNEL);
if (drv_fcxp == NULL) {
kfree(bsg_fcpt);
rc = -ENOMEM;
goto out;
}
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs, bsg_fcpt->vf_id,
bsg_fcpt->lpwwn);
if (fcs_port == NULL) {
bsg_fcpt->status = BFA_STATUS_UNKNOWN_LWWN;
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
goto out_free_mem;
}
/* Check if the port is online before sending FC Passthru cmd */
if (!bfa_fcs_lport_is_online(fcs_port)) {
bsg_fcpt->status = BFA_STATUS_PORT_OFFLINE;
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
goto out_free_mem;
}
drv_fcxp->port = fcs_port->bfad_port;
if (drv_fcxp->port->bfad == 0)
drv_fcxp->port->bfad = bfad;
/* Fetch the bfa_rport - if nexus needed */
if (command_type == FC_BSG_HST_ELS_NOLOGIN ||
command_type == FC_BSG_HST_CT) {
/* BSG HST commands: no nexus needed */
drv_fcxp->bfa_rport = NULL;
} else if (command_type == FC_BSG_RPT_ELS ||
command_type == FC_BSG_RPT_CT) {
/* BSG RPT commands: nexus needed */
fcs_rport = bfa_fcs_lport_get_rport_by_pwwn(fcs_port,
bsg_fcpt->dpwwn);
if (fcs_rport == NULL) {
bsg_fcpt->status = BFA_STATUS_UNKNOWN_RWWN;
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
goto out_free_mem;
}
drv_fcxp->bfa_rport = fcs_rport->bfa_rport;
} else { /* Unknown BSG msgcode; return -EINVAL */
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
goto out_free_mem;
}
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
/* allocate memory for req / rsp buffers */
req_kbuf = kzalloc(job->request_payload.payload_len, GFP_KERNEL);
if (!req_kbuf) {
printk(KERN_INFO "bfa %s: fcpt request buffer alloc failed\n",
bfad->pci_name);
rc = -ENOMEM;
goto out_free_mem;
}
rsp_kbuf = kzalloc(job->reply_payload.payload_len, GFP_KERNEL);
if (!rsp_kbuf) {
printk(KERN_INFO "bfa %s: fcpt response buffer alloc failed\n",
bfad->pci_name);
rc = -ENOMEM;
goto out_free_mem;
}
/* map req sg - copy the sg_list passed in to the linear buffer */
sg_copy_to_buffer(job->request_payload.sg_list,
job->request_payload.sg_cnt, req_kbuf,
job->request_payload.payload_len);
drv_fcxp->reqbuf_info = bfad_fcxp_map_sg(bfad, req_kbuf,
job->request_payload.payload_len,
&drv_fcxp->num_req_sgles);
if (!drv_fcxp->reqbuf_info) {
printk(KERN_INFO "bfa %s: fcpt request fcxp_map_sg failed\n",
bfad->pci_name);
rc = -ENOMEM;
goto out_free_mem;
}
drv_fcxp->req_sge = (struct bfa_sge_s *)
(((uint8_t *)drv_fcxp->reqbuf_info) +
(sizeof(struct bfad_buf_info) *
drv_fcxp->num_req_sgles));
/* map rsp sg */
drv_fcxp->rspbuf_info = bfad_fcxp_map_sg(bfad, rsp_kbuf,
job->reply_payload.payload_len,
&drv_fcxp->num_rsp_sgles);
if (!drv_fcxp->rspbuf_info) {
printk(KERN_INFO "bfa %s: fcpt response fcxp_map_sg failed\n",
bfad->pci_name);
rc = -ENOMEM;
goto out_free_mem;
}
rsp_buf_info = (struct bfad_buf_info *)drv_fcxp->rspbuf_info;
drv_fcxp->rsp_sge = (struct bfa_sge_s *)
(((uint8_t *)drv_fcxp->rspbuf_info) +
(sizeof(struct bfad_buf_info) *
drv_fcxp->num_rsp_sgles));
/* fcxp send */
init_completion(&drv_fcxp->comp);
rc = bfad_fcxp_bsg_send(job, drv_fcxp, bsg_fcpt);
if (rc == BFA_STATUS_OK) {
wait_for_completion(&drv_fcxp->comp);
bsg_fcpt->status = drv_fcxp->req_status;
} else {
bsg_fcpt->status = rc;
goto out_free_mem;
}
/* fill the job->reply data */
if (drv_fcxp->req_status == BFA_STATUS_OK) {
job->reply_len = drv_fcxp->rsp_len;
job->reply->reply_payload_rcv_len = drv_fcxp->rsp_len;
job->reply->reply_data.ctels_reply.status = FC_CTELS_STATUS_OK;
} else {
job->reply->reply_payload_rcv_len =
sizeof(struct fc_bsg_ctels_reply);
job->reply_len = sizeof(uint32_t);
job->reply->reply_data.ctels_reply.status =
FC_CTELS_STATUS_REJECT;
}
/* Copy the response data to the reply_payload sg list */
sg_copy_from_buffer(job->reply_payload.sg_list,
job->reply_payload.sg_cnt,
(uint8_t *)rsp_buf_info->virt,
job->reply_payload.payload_len);
out_free_mem:
bfad_fcxp_free_mem(bfad, drv_fcxp->rspbuf_info,
drv_fcxp->num_rsp_sgles);
bfad_fcxp_free_mem(bfad, drv_fcxp->reqbuf_info,
drv_fcxp->num_req_sgles);
kfree(req_kbuf);
kfree(rsp_kbuf);
/* Need a copy to user op */
if (copy_to_user(bsg_data->payload, (void *) bsg_fcpt,
bsg_data->payload_len))
rc = -EIO;
kfree(bsg_fcpt);
kfree(drv_fcxp);
out:
job->reply->result = rc;
if (rc == BFA_STATUS_OK)
job->job_done(job);
return rc;
}
int
bfad_im_bsg_request(struct fc_bsg_job *job)
{
uint32_t rc = BFA_STATUS_OK;
switch (job->request->msgcode) {
case FC_BSG_HST_VENDOR:
/* Process BSG HST Vendor requests */
rc = bfad_im_bsg_vendor_request(job);
break;
case FC_BSG_HST_ELS_NOLOGIN:
case FC_BSG_RPT_ELS:
case FC_BSG_HST_CT:
case FC_BSG_RPT_CT:
/* Process BSG ELS/CT commands */
rc = bfad_im_bsg_els_ct_request(job);
break;
default:
job->reply->result = rc = -EINVAL;
job->reply->reply_payload_rcv_len = 0;
break;
}
return rc;
}
int
bfad_im_bsg_timeout(struct fc_bsg_job *job)
{
/* Don't complete the BSG job request - return -EAGAIN
* to reset bsg job timeout : for ELS/CT pass thru we
* already have timer to track the request.
*/
return -EAGAIN;
}
| gpl-2.0 |
OnePlusOSS/android_kernel_oneplus_msm8974 | drivers/staging/sbe-2t3e3/io.c | 4855 | 10580 | /*
* SBE 2T3E3 synchronous serial card driver for Linux
*
* Copyright (C) 2009-2010 Krzysztof Halasa <khc@pm.waw.pl>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License
* as published by the Free Software Foundation.
*
* This code is based on a driver written by SBE Inc.
*/
#include <linux/ip.h>
#include "2t3e3.h"
#include "ctrl.h"
/* All access to registers done via the 21143 on port 0 must be
* protected via the card->bootrom_lock. */
/* priviate define to be used here only - must be protected by card->bootrom_lock */
#define cpld_write_nolock(channel, reg, val) \
bootrom_write((channel), CPLD_MAP_REG(reg, channel), val)
u32 cpld_read(struct channel *channel, u32 reg)
{
unsigned long flags;
u32 val;
spin_lock_irqsave(&channel->card->bootrom_lock, flags);
val = bootrom_read((channel), CPLD_MAP_REG(reg, channel));
spin_unlock_irqrestore(&channel->card->bootrom_lock, flags);
return val;
}
/****************************************
* Access via BootROM port
****************************************/
u32 bootrom_read(struct channel *channel, u32 reg)
{
unsigned long addr = channel->card->bootrom_addr;
u32 result;
/* select BootROM address */
dc_write(addr, SBE_2T3E3_21143_REG_BOOT_ROM_PROGRAMMING_ADDRESS, reg & 0x3FFFF);
/* select reading from BootROM */
dc_write(addr, SBE_2T3E3_21143_REG_BOOT_ROM_SERIAL_ROM_AND_MII_MANAGEMENT,
SBE_2T3E3_21143_VAL_READ_OPERATION |
SBE_2T3E3_21143_VAL_BOOT_ROM_SELECT);
udelay(2); /* 20 PCI cycles */
/* read from BootROM */
result = dc_read(addr, SBE_2T3E3_21143_REG_BOOT_ROM_SERIAL_ROM_AND_MII_MANAGEMENT) & 0xff;
/* reset CSR9 */
dc_write(addr, SBE_2T3E3_21143_REG_BOOT_ROM_SERIAL_ROM_AND_MII_MANAGEMENT, 0);
return result;
}
void bootrom_write(struct channel *channel, u32 reg, u32 val)
{
unsigned long addr = channel->card->bootrom_addr;
/* select BootROM address */
dc_write(addr, SBE_2T3E3_21143_REG_BOOT_ROM_PROGRAMMING_ADDRESS, reg & 0x3FFFF);
/* select writting to BootROM */
dc_write(addr, SBE_2T3E3_21143_REG_BOOT_ROM_SERIAL_ROM_AND_MII_MANAGEMENT,
SBE_2T3E3_21143_VAL_WRITE_OPERATION |
SBE_2T3E3_21143_VAL_BOOT_ROM_SELECT |
(val & 0xff));
udelay(2); /* 20 PCI cycles */
/* reset CSR9 */
dc_write(addr, SBE_2T3E3_21143_REG_BOOT_ROM_SERIAL_ROM_AND_MII_MANAGEMENT, 0);
}
/****************************************
* Access via Serial I/O port
****************************************/
static u32 serialrom_read_bit(struct channel *channel)
{
unsigned long addr = channel->card->bootrom_addr;
u32 bit;
dc_write(addr, SBE_2T3E3_21143_REG_BOOT_ROM_SERIAL_ROM_AND_MII_MANAGEMENT,
SBE_2T3E3_21143_VAL_READ_OPERATION |
SBE_2T3E3_21143_VAL_SERIAL_ROM_SELECT |
SBE_2T3E3_21143_VAL_SERIAL_ROM_CLOCK |
SBE_2T3E3_21143_VAL_SERIAL_ROM_CHIP_SELECT); /* clock high */
bit = (dc_read(addr, SBE_2T3E3_21143_REG_BOOT_ROM_SERIAL_ROM_AND_MII_MANAGEMENT) &
SBE_2T3E3_21143_VAL_SERIAL_ROM_DATA_OUT) > 0 ? 1 : 0;
dc_write(addr, SBE_2T3E3_21143_REG_BOOT_ROM_SERIAL_ROM_AND_MII_MANAGEMENT,
SBE_2T3E3_21143_VAL_READ_OPERATION |
SBE_2T3E3_21143_VAL_SERIAL_ROM_SELECT |
SBE_2T3E3_21143_VAL_SERIAL_ROM_CHIP_SELECT); /* clock low */
return bit;
}
static void serialrom_write_bit(struct channel *channel, u32 bit)
{
unsigned long addr = channel->card->bootrom_addr;
u32 lastbit = -1;
bit &= 1;
if (bit != lastbit) {
dc_write(addr, SBE_2T3E3_21143_REG_BOOT_ROM_SERIAL_ROM_AND_MII_MANAGEMENT,
SBE_2T3E3_21143_VAL_WRITE_OPERATION |
SBE_2T3E3_21143_VAL_SERIAL_ROM_SELECT |
SBE_2T3E3_21143_VAL_SERIAL_ROM_CHIP_SELECT |
(bit << 2)); /* clock low */
lastbit = bit;
}
dc_write(addr, SBE_2T3E3_21143_REG_BOOT_ROM_SERIAL_ROM_AND_MII_MANAGEMENT,
SBE_2T3E3_21143_VAL_WRITE_OPERATION |
SBE_2T3E3_21143_VAL_SERIAL_ROM_SELECT |
SBE_2T3E3_21143_VAL_SERIAL_ROM_CLOCK |
SBE_2T3E3_21143_VAL_SERIAL_ROM_CHIP_SELECT |
(bit << 2)); /* clock high */
dc_write(addr, SBE_2T3E3_21143_REG_BOOT_ROM_SERIAL_ROM_AND_MII_MANAGEMENT,
SBE_2T3E3_21143_VAL_WRITE_OPERATION |
SBE_2T3E3_21143_VAL_SERIAL_ROM_SELECT |
SBE_2T3E3_21143_VAL_SERIAL_ROM_CHIP_SELECT |
(bit << 2)); /* clock low */
}
/****************************************
* Access to SerialROM (eeprom)
****************************************/
u32 t3e3_eeprom_read_word(struct channel *channel, u32 address)
{
unsigned long addr = channel->card->bootrom_addr;
u32 i, val;
unsigned long flags;
address &= 0x3f;
spin_lock_irqsave(&channel->card->bootrom_lock, flags);
/* select correct Serial Chip */
cpld_write_nolock(channel, SBE_2T3E3_CPLD_REG_SERIAL_CHIP_SELECT,
SBE_2T3E3_CPLD_VAL_EEPROM_SELECT);
/* select reading from Serial I/O Bus */
dc_write(addr, SBE_2T3E3_21143_REG_BOOT_ROM_SERIAL_ROM_AND_MII_MANAGEMENT,
SBE_2T3E3_21143_VAL_READ_OPERATION |
SBE_2T3E3_21143_VAL_SERIAL_ROM_SELECT |
SBE_2T3E3_21143_VAL_SERIAL_ROM_CHIP_SELECT); /* clock low */
/* select read operation */
serialrom_write_bit(channel, 0);
serialrom_write_bit(channel, 1);
serialrom_write_bit(channel, 1);
serialrom_write_bit(channel, 0);
for (i = 0x20; i; i >>= 1)
serialrom_write_bit(channel, address & i ? 1 : 0);
val = 0;
for (i = 0x8000; i; i >>= 1)
val |= (serialrom_read_bit(channel) ? i : 0);
/* Reset 21143's CSR9 */
dc_write(addr, SBE_2T3E3_21143_REG_BOOT_ROM_SERIAL_ROM_AND_MII_MANAGEMENT,
SBE_2T3E3_21143_VAL_READ_OPERATION |
SBE_2T3E3_21143_VAL_SERIAL_ROM_SELECT |
SBE_2T3E3_21143_VAL_SERIAL_ROM_CHIP_SELECT); /* clock low */
dc_write(addr, SBE_2T3E3_21143_REG_BOOT_ROM_SERIAL_ROM_AND_MII_MANAGEMENT, 0);
/* Unselect Serial Chip */
cpld_write_nolock(channel, SBE_2T3E3_CPLD_REG_SERIAL_CHIP_SELECT, 0);
spin_unlock_irqrestore(&channel->card->bootrom_lock, flags);
return ntohs(val);
}
/****************************************
* Access to Framer
****************************************/
u32 exar7250_read(struct channel *channel, u32 reg)
{
u32 result;
unsigned long flags;
#if 0
switch (reg) {
case SBE_2T3E3_FRAMER_REG_OPERATING_MODE:
return channel->framer_regs[reg];
break;
default:
}
#endif
spin_lock_irqsave(&channel->card->bootrom_lock, flags);
result = bootrom_read(channel, cpld_reg_map[SBE_2T3E3_CPLD_REG_FRAMER_BASE_ADDRESS]
[channel->h.slot] + (t3e3_framer_reg_map[reg] << 2));
spin_unlock_irqrestore(&channel->card->bootrom_lock, flags);
return result;
}
void exar7250_write(struct channel *channel, u32 reg, u32 val)
{
unsigned long flags;
val &= 0xff;
channel->framer_regs[reg] = val;
spin_lock_irqsave(&channel->card->bootrom_lock, flags);
bootrom_write(channel, cpld_reg_map[SBE_2T3E3_CPLD_REG_FRAMER_BASE_ADDRESS]
[channel->h.slot] + (t3e3_framer_reg_map[reg] << 2), val);
spin_unlock_irqrestore(&channel->card->bootrom_lock, flags);
}
/****************************************
* Access to LIU
****************************************/
u32 exar7300_read(struct channel *channel, u32 reg)
{
unsigned long addr = channel->card->bootrom_addr, flags;
u32 i, val;
#if 0
switch (reg) {
case SBE_2T3E3_LIU_REG_REG1:
case SBE_2T3E3_LIU_REG_REG2:
case SBE_2T3E3_LIU_REG_REG3:
case SBE_2T3E3_LIU_REG_REG4:
return channel->liu_regs[reg];
break;
default:
}
#endif
/* select correct Serial Chip */
spin_lock_irqsave(&channel->card->bootrom_lock, flags);
cpld_write_nolock(channel, SBE_2T3E3_CPLD_REG_SERIAL_CHIP_SELECT,
cpld_val_map[SBE_2T3E3_CPLD_VAL_LIU_SELECT][channel->h.slot]);
/* select reading from Serial I/O Bus */
dc_write(addr, SBE_2T3E3_21143_REG_BOOT_ROM_SERIAL_ROM_AND_MII_MANAGEMENT,
SBE_2T3E3_21143_VAL_READ_OPERATION |
SBE_2T3E3_21143_VAL_SERIAL_ROM_SELECT |
SBE_2T3E3_21143_VAL_SERIAL_ROM_CHIP_SELECT); /* clock low */
/* select read operation */
serialrom_write_bit(channel, 1);
/* Exar7300 register address is 4 bit long */
reg = t3e3_liu_reg_map[reg];
for (i = 0; i < 4; i++, reg >>= 1) /* 4 bits of SerialROM address */
serialrom_write_bit(channel, reg & 1);
for (i = 0; i < 3; i++) /* remaining 3 bits of SerialROM address */
serialrom_write_bit(channel, 0);
val = 0; /* Exar7300 register value is 5 bit long */
for (i = 0; i < 8; i++) /* 8 bits of SerialROM value */
val += (serialrom_read_bit(channel) << i);
/* Reset 21143's CSR9 */
dc_write(addr, SBE_2T3E3_21143_REG_BOOT_ROM_SERIAL_ROM_AND_MII_MANAGEMENT,
SBE_2T3E3_21143_VAL_READ_OPERATION |
SBE_2T3E3_21143_VAL_SERIAL_ROM_SELECT |
SBE_2T3E3_21143_VAL_SERIAL_ROM_CHIP_SELECT); /* clock low */
dc_write(addr, SBE_2T3E3_21143_REG_BOOT_ROM_SERIAL_ROM_AND_MII_MANAGEMENT, 0);
/* Unselect Serial Chip */
cpld_write_nolock(channel, SBE_2T3E3_CPLD_REG_SERIAL_CHIP_SELECT, 0);
spin_unlock_irqrestore(&channel->card->bootrom_lock, flags);
return val;
}
void exar7300_write(struct channel *channel, u32 reg, u32 val)
{
unsigned long addr = channel->card->bootrom_addr, flags;
u32 i;
channel->liu_regs[reg] = val;
/* select correct Serial Chip */
spin_lock_irqsave(&channel->card->bootrom_lock, flags);
cpld_write_nolock(channel, SBE_2T3E3_CPLD_REG_SERIAL_CHIP_SELECT,
cpld_val_map[SBE_2T3E3_CPLD_VAL_LIU_SELECT][channel->h.slot]);
/* select writting to Serial I/O Bus */
dc_write(addr, SBE_2T3E3_21143_REG_BOOT_ROM_SERIAL_ROM_AND_MII_MANAGEMENT,
SBE_2T3E3_21143_VAL_WRITE_OPERATION |
SBE_2T3E3_21143_VAL_SERIAL_ROM_SELECT |
SBE_2T3E3_21143_VAL_SERIAL_ROM_CHIP_SELECT); /* clock low */
/* select write operation */
serialrom_write_bit(channel, 0);
/* Exar7300 register address is 4 bit long */
reg = t3e3_liu_reg_map[reg];
for (i = 0; i < 4; i++) { /* 4 bits */
serialrom_write_bit(channel, reg & 1);
reg >>= 1;
}
for (i = 0; i < 3; i++) /* remaining 3 bits of SerialROM address */
serialrom_write_bit(channel, 0);
/* Exar7300 register value is 5 bit long */
for (i = 0; i < 5; i++) {
serialrom_write_bit(channel, val & 1);
val >>= 1;
}
for (i = 0; i < 3; i++) /* remaining 3 bits of SerialROM value */
serialrom_write_bit(channel, 0);
/* Reset 21143_CSR9 */
dc_write(addr, SBE_2T3E3_21143_REG_BOOT_ROM_SERIAL_ROM_AND_MII_MANAGEMENT,
SBE_2T3E3_21143_VAL_WRITE_OPERATION |
SBE_2T3E3_21143_VAL_SERIAL_ROM_SELECT |
SBE_2T3E3_21143_VAL_SERIAL_ROM_CHIP_SELECT); /* clock low */
dc_write(addr, SBE_2T3E3_21143_REG_BOOT_ROM_SERIAL_ROM_AND_MII_MANAGEMENT, 0);
/* Unselect Serial Chip */
cpld_write_nolock(channel, SBE_2T3E3_CPLD_REG_SERIAL_CHIP_SELECT, 0);
spin_unlock_irqrestore(&channel->card->bootrom_lock, flags);
}
| gpl-2.0 |
drewis/android_kernel_msm | drivers/xen/platform-pci.c | 4855 | 4665 | /******************************************************************************
* platform-pci.c
*
* Xen platform PCI device driver
* Copyright (c) 2005, Intel Corporation.
* Copyright (c) 2007, XenSource Inc.
* Copyright (c) 2010, Citrix
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307 USA.
*
*/
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <xen/platform_pci.h>
#include <xen/grant_table.h>
#include <xen/xenbus.h>
#include <xen/events.h>
#include <xen/hvm.h>
#include <xen/xen-ops.h>
#define DRV_NAME "xen-platform-pci"
MODULE_AUTHOR("ssmith@xensource.com and stefano.stabellini@eu.citrix.com");
MODULE_DESCRIPTION("Xen platform PCI device");
MODULE_LICENSE("GPL");
static unsigned long platform_mmio;
static unsigned long platform_mmio_alloc;
static unsigned long platform_mmiolen;
static uint64_t callback_via;
unsigned long alloc_xen_mmio(unsigned long len)
{
unsigned long addr;
addr = platform_mmio + platform_mmio_alloc;
platform_mmio_alloc += len;
BUG_ON(platform_mmio_alloc > platform_mmiolen);
return addr;
}
static uint64_t get_callback_via(struct pci_dev *pdev)
{
u8 pin;
int irq;
irq = pdev->irq;
if (irq < 16)
return irq; /* ISA IRQ */
pin = pdev->pin;
/* We don't know the GSI. Specify the PCI INTx line instead. */
return ((uint64_t)0x01 << 56) | /* PCI INTx identifier */
((uint64_t)pci_domain_nr(pdev->bus) << 32) |
((uint64_t)pdev->bus->number << 16) |
((uint64_t)(pdev->devfn & 0xff) << 8) |
((uint64_t)(pin - 1) & 3);
}
static irqreturn_t do_hvm_evtchn_intr(int irq, void *dev_id)
{
xen_hvm_evtchn_do_upcall();
return IRQ_HANDLED;
}
static int xen_allocate_irq(struct pci_dev *pdev)
{
return request_irq(pdev->irq, do_hvm_evtchn_intr,
IRQF_DISABLED | IRQF_NOBALANCING | IRQF_TRIGGER_RISING,
"xen-platform-pci", pdev);
}
static int platform_pci_resume(struct pci_dev *pdev)
{
int err;
if (xen_have_vector_callback)
return 0;
err = xen_set_callback_via(callback_via);
if (err) {
dev_err(&pdev->dev, "platform_pci_resume failure!\n");
return err;
}
return 0;
}
static int __devinit platform_pci_init(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
int i, ret;
long ioaddr;
long mmio_addr, mmio_len;
unsigned int max_nr_gframes;
i = pci_enable_device(pdev);
if (i)
return i;
ioaddr = pci_resource_start(pdev, 0);
mmio_addr = pci_resource_start(pdev, 1);
mmio_len = pci_resource_len(pdev, 1);
if (mmio_addr == 0 || ioaddr == 0) {
dev_err(&pdev->dev, "no resources found\n");
ret = -ENOENT;
goto pci_out;
}
ret = pci_request_region(pdev, 1, DRV_NAME);
if (ret < 0)
goto pci_out;
ret = pci_request_region(pdev, 0, DRV_NAME);
if (ret < 0)
goto mem_out;
platform_mmio = mmio_addr;
platform_mmiolen = mmio_len;
if (!xen_have_vector_callback) {
ret = xen_allocate_irq(pdev);
if (ret) {
dev_warn(&pdev->dev, "request_irq failed err=%d\n", ret);
goto out;
}
callback_via = get_callback_via(pdev);
ret = xen_set_callback_via(callback_via);
if (ret) {
dev_warn(&pdev->dev, "Unable to set the evtchn callback "
"err=%d\n", ret);
goto out;
}
}
max_nr_gframes = gnttab_max_grant_frames();
xen_hvm_resume_frames = alloc_xen_mmio(PAGE_SIZE * max_nr_gframes);
ret = gnttab_init();
if (ret)
goto out;
xenbus_probe(NULL);
return 0;
out:
pci_release_region(pdev, 0);
mem_out:
pci_release_region(pdev, 1);
pci_out:
pci_disable_device(pdev);
return ret;
}
static struct pci_device_id platform_pci_tbl[] __devinitdata = {
{PCI_VENDOR_ID_XEN, PCI_DEVICE_ID_XEN_PLATFORM,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{0,}
};
MODULE_DEVICE_TABLE(pci, platform_pci_tbl);
static struct pci_driver platform_driver = {
.name = DRV_NAME,
.probe = platform_pci_init,
.id_table = platform_pci_tbl,
#ifdef CONFIG_PM
.resume_early = platform_pci_resume,
#endif
};
static int __init platform_pci_module_init(void)
{
return pci_register_driver(&platform_driver);
}
module_init(platform_pci_module_init);
| gpl-2.0 |
davidmueller13/Audax_Kernel | drivers/scsi/bfa/bfad_bsg.c | 4855 | 88372 | /*
* Copyright (c) 2005-2010 Brocade Communications Systems, Inc.
* All rights reserved
* www.brocade.com
*
* Linux driver for Brocade Fibre Channel Host Bus Adapter.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License (GPL) 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/uaccess.h>
#include "bfad_drv.h"
#include "bfad_im.h"
#include "bfad_bsg.h"
BFA_TRC_FILE(LDRV, BSG);
int
bfad_iocmd_ioc_enable(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
int rc = 0;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
/* If IOC is not in disabled state - return */
if (!bfa_ioc_is_disabled(&bfad->bfa.ioc)) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_IOC_FAILURE;
return rc;
}
init_completion(&bfad->enable_comp);
bfa_iocfc_enable(&bfad->bfa);
iocmd->status = BFA_STATUS_OK;
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
wait_for_completion(&bfad->enable_comp);
return rc;
}
int
bfad_iocmd_ioc_disable(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
int rc = 0;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
if (bfad->disable_active) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return -EBUSY;
}
bfad->disable_active = BFA_TRUE;
init_completion(&bfad->disable_comp);
bfa_iocfc_disable(&bfad->bfa);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
wait_for_completion(&bfad->disable_comp);
bfad->disable_active = BFA_FALSE;
iocmd->status = BFA_STATUS_OK;
return rc;
}
static int
bfad_iocmd_ioc_get_info(struct bfad_s *bfad, void *cmd)
{
int i;
struct bfa_bsg_ioc_info_s *iocmd = (struct bfa_bsg_ioc_info_s *)cmd;
struct bfad_im_port_s *im_port;
struct bfa_port_attr_s pattr;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
bfa_fcport_get_attr(&bfad->bfa, &pattr);
iocmd->nwwn = pattr.nwwn;
iocmd->pwwn = pattr.pwwn;
iocmd->ioc_type = bfa_get_type(&bfad->bfa);
iocmd->mac = bfa_get_mac(&bfad->bfa);
iocmd->factory_mac = bfa_get_mfg_mac(&bfad->bfa);
bfa_get_adapter_serial_num(&bfad->bfa, iocmd->serialnum);
iocmd->factorynwwn = pattr.factorynwwn;
iocmd->factorypwwn = pattr.factorypwwn;
iocmd->bfad_num = bfad->inst_no;
im_port = bfad->pport.im_port;
iocmd->host = im_port->shost->host_no;
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
strcpy(iocmd->name, bfad->adapter_name);
strcpy(iocmd->port_name, bfad->port_name);
strcpy(iocmd->hwpath, bfad->pci_name);
/* set adapter hw path */
strcpy(iocmd->adapter_hwpath, bfad->pci_name);
i = strlen(iocmd->adapter_hwpath) - 1;
while (iocmd->adapter_hwpath[i] != '.')
i--;
iocmd->adapter_hwpath[i] = '\0';
iocmd->status = BFA_STATUS_OK;
return 0;
}
static int
bfad_iocmd_ioc_get_attr(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_ioc_attr_s *iocmd = (struct bfa_bsg_ioc_attr_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
bfa_ioc_get_attr(&bfad->bfa.ioc, &iocmd->ioc_attr);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
/* fill in driver attr info */
strcpy(iocmd->ioc_attr.driver_attr.driver, BFAD_DRIVER_NAME);
strncpy(iocmd->ioc_attr.driver_attr.driver_ver,
BFAD_DRIVER_VERSION, BFA_VERSION_LEN);
strcpy(iocmd->ioc_attr.driver_attr.fw_ver,
iocmd->ioc_attr.adapter_attr.fw_ver);
strcpy(iocmd->ioc_attr.driver_attr.bios_ver,
iocmd->ioc_attr.adapter_attr.optrom_ver);
/* copy chip rev info first otherwise it will be overwritten */
memcpy(bfad->pci_attr.chip_rev, iocmd->ioc_attr.pci_attr.chip_rev,
sizeof(bfad->pci_attr.chip_rev));
memcpy(&iocmd->ioc_attr.pci_attr, &bfad->pci_attr,
sizeof(struct bfa_ioc_pci_attr_s));
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_ioc_get_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_ioc_stats_s *iocmd = (struct bfa_bsg_ioc_stats_s *)cmd;
bfa_ioc_get_stats(&bfad->bfa, &iocmd->ioc_stats);
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_ioc_get_fwstats(struct bfad_s *bfad, void *cmd,
unsigned int payload_len)
{
struct bfa_bsg_ioc_fwstats_s *iocmd =
(struct bfa_bsg_ioc_fwstats_s *)cmd;
void *iocmd_bufptr;
unsigned long flags;
if (bfad_chk_iocmd_sz(payload_len,
sizeof(struct bfa_bsg_ioc_fwstats_s),
sizeof(struct bfa_fw_stats_s)) != BFA_STATUS_OK) {
iocmd->status = BFA_STATUS_VERSION_FAIL;
goto out;
}
iocmd_bufptr = (char *)iocmd + sizeof(struct bfa_bsg_ioc_fwstats_s);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_ioc_fw_stats_get(&bfad->bfa.ioc, iocmd_bufptr);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK) {
bfa_trc(bfad, iocmd->status);
goto out;
}
out:
bfa_trc(bfad, 0x6666);
return 0;
}
int
bfad_iocmd_ioc_reset_stats(struct bfad_s *bfad, void *cmd, unsigned int v_cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
unsigned long flags;
if (v_cmd == IOCMD_IOC_RESET_STATS) {
bfa_ioc_clear_stats(&bfad->bfa);
iocmd->status = BFA_STATUS_OK;
} else if (v_cmd == IOCMD_IOC_RESET_FWSTATS) {
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_ioc_fw_stats_clear(&bfad->bfa.ioc);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
}
return 0;
}
int
bfad_iocmd_ioc_set_name(struct bfad_s *bfad, void *cmd, unsigned int v_cmd)
{
struct bfa_bsg_ioc_name_s *iocmd = (struct bfa_bsg_ioc_name_s *) cmd;
if (v_cmd == IOCMD_IOC_SET_ADAPTER_NAME)
strcpy(bfad->adapter_name, iocmd->name);
else if (v_cmd == IOCMD_IOC_SET_PORT_NAME)
strcpy(bfad->port_name, iocmd->name);
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_iocfc_get_attr(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_iocfc_attr_s *iocmd = (struct bfa_bsg_iocfc_attr_s *)cmd;
iocmd->status = BFA_STATUS_OK;
bfa_iocfc_get_attr(&bfad->bfa, &iocmd->iocfc_attr);
return 0;
}
int
bfad_iocmd_iocfc_set_intr(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_iocfc_intr_s *iocmd = (struct bfa_bsg_iocfc_intr_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_iocfc_israttr_set(&bfad->bfa, &iocmd->attr);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
int
bfad_iocmd_port_enable(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_port_enable(&bfad->bfa.modules.port,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK) {
bfa_trc(bfad, iocmd->status);
return 0;
}
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
return 0;
}
int
bfad_iocmd_port_disable(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_port_disable(&bfad->bfa.modules.port,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK) {
bfa_trc(bfad, iocmd->status);
return 0;
}
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
return 0;
}
static int
bfad_iocmd_port_get_attr(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_port_attr_s *iocmd = (struct bfa_bsg_port_attr_s *)cmd;
struct bfa_lport_attr_s port_attr;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
bfa_fcport_get_attr(&bfad->bfa, &iocmd->attr);
bfa_fcs_lport_get_attr(&bfad->bfa_fcs.fabric.bport, &port_attr);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->attr.topology != BFA_PORT_TOPOLOGY_NONE)
iocmd->attr.pid = port_attr.pid;
else
iocmd->attr.pid = 0;
iocmd->attr.port_type = port_attr.port_type;
iocmd->attr.loopback = port_attr.loopback;
iocmd->attr.authfail = port_attr.authfail;
strncpy(iocmd->attr.port_symname.symname,
port_attr.port_cfg.sym_name.symname,
sizeof(port_attr.port_cfg.sym_name.symname));
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_port_get_stats(struct bfad_s *bfad, void *cmd,
unsigned int payload_len)
{
struct bfa_bsg_port_stats_s *iocmd = (struct bfa_bsg_port_stats_s *)cmd;
struct bfad_hal_comp fcomp;
void *iocmd_bufptr;
unsigned long flags;
if (bfad_chk_iocmd_sz(payload_len,
sizeof(struct bfa_bsg_port_stats_s),
sizeof(union bfa_port_stats_u)) != BFA_STATUS_OK) {
iocmd->status = BFA_STATUS_VERSION_FAIL;
return 0;
}
iocmd_bufptr = (char *)iocmd + sizeof(struct bfa_bsg_port_stats_s);
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_port_get_stats(&bfad->bfa.modules.port,
iocmd_bufptr, bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK) {
bfa_trc(bfad, iocmd->status);
goto out;
}
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_port_reset_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_port_clear_stats(&bfad->bfa.modules.port,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK) {
bfa_trc(bfad, iocmd->status);
return 0;
}
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
return 0;
}
int
bfad_iocmd_set_port_cfg(struct bfad_s *bfad, void *iocmd, unsigned int v_cmd)
{
struct bfa_bsg_port_cfg_s *cmd = (struct bfa_bsg_port_cfg_s *)iocmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
if (v_cmd == IOCMD_PORT_CFG_TOPO)
cmd->status = bfa_fcport_cfg_topology(&bfad->bfa, cmd->param);
else if (v_cmd == IOCMD_PORT_CFG_SPEED)
cmd->status = bfa_fcport_cfg_speed(&bfad->bfa, cmd->param);
else if (v_cmd == IOCMD_PORT_CFG_ALPA)
cmd->status = bfa_fcport_cfg_hardalpa(&bfad->bfa, cmd->param);
else if (v_cmd == IOCMD_PORT_CLR_ALPA)
cmd->status = bfa_fcport_clr_hardalpa(&bfad->bfa);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
int
bfad_iocmd_port_cfg_maxfrsize(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_port_cfg_maxfrsize_s *iocmd =
(struct bfa_bsg_port_cfg_maxfrsize_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_fcport_cfg_maxfrsize(&bfad->bfa, iocmd->maxfrsize);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
int
bfad_iocmd_port_cfg_bbsc(struct bfad_s *bfad, void *cmd, unsigned int v_cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
struct bfa_fcport_s *fcport = BFA_FCPORT_MOD(&bfad->bfa);
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
if (bfa_ioc_get_type(&bfad->bfa.ioc) == BFA_IOC_TYPE_FC) {
if (v_cmd == IOCMD_PORT_BBSC_ENABLE)
fcport->cfg.bb_scn_state = BFA_TRUE;
else if (v_cmd == IOCMD_PORT_BBSC_DISABLE)
fcport->cfg.bb_scn_state = BFA_FALSE;
}
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
return 0;
}
static int
bfad_iocmd_lport_get_attr(struct bfad_s *bfad, void *cmd)
{
struct bfa_fcs_lport_s *fcs_port;
struct bfa_bsg_lport_attr_s *iocmd = (struct bfa_bsg_lport_attr_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->pwwn);
if (fcs_port == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
goto out;
}
bfa_fcs_lport_get_attr(fcs_port, &iocmd->port_attr);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
int
bfad_iocmd_lport_get_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_fcs_lport_s *fcs_port;
struct bfa_bsg_lport_stats_s *iocmd =
(struct bfa_bsg_lport_stats_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->pwwn);
if (fcs_port == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
goto out;
}
bfa_fcs_lport_get_stats(fcs_port, &iocmd->port_stats);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
int
bfad_iocmd_lport_reset_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_fcs_lport_s *fcs_port;
struct bfa_bsg_reset_stats_s *iocmd =
(struct bfa_bsg_reset_stats_s *)cmd;
struct bfa_fcpim_s *fcpim = BFA_FCPIM(&bfad->bfa);
struct list_head *qe, *qen;
struct bfa_itnim_s *itnim;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->vpwwn);
if (fcs_port == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
goto out;
}
bfa_fcs_lport_clear_stats(fcs_port);
/* clear IO stats from all active itnims */
list_for_each_safe(qe, qen, &fcpim->itnim_q) {
itnim = (struct bfa_itnim_s *) qe;
if (itnim->rport->rport_info.lp_tag != fcs_port->lp_tag)
continue;
bfa_itnim_clear_stats(itnim);
}
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
int
bfad_iocmd_lport_get_iostats(struct bfad_s *bfad, void *cmd)
{
struct bfa_fcs_lport_s *fcs_port;
struct bfa_bsg_lport_iostats_s *iocmd =
(struct bfa_bsg_lport_iostats_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->pwwn);
if (fcs_port == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
goto out;
}
bfa_fcpim_port_iostats(&bfad->bfa, &iocmd->iostats,
fcs_port->lp_tag);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
int
bfad_iocmd_lport_get_rports(struct bfad_s *bfad, void *cmd,
unsigned int payload_len)
{
struct bfa_bsg_lport_get_rports_s *iocmd =
(struct bfa_bsg_lport_get_rports_s *)cmd;
struct bfa_fcs_lport_s *fcs_port;
unsigned long flags;
void *iocmd_bufptr;
if (iocmd->nrports == 0)
return -EINVAL;
if (bfad_chk_iocmd_sz(payload_len,
sizeof(struct bfa_bsg_lport_get_rports_s),
sizeof(wwn_t) * iocmd->nrports) != BFA_STATUS_OK) {
iocmd->status = BFA_STATUS_VERSION_FAIL;
return 0;
}
iocmd_bufptr = (char *)iocmd +
sizeof(struct bfa_bsg_lport_get_rports_s);
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->pwwn);
if (fcs_port == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
bfa_trc(bfad, 0);
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
goto out;
}
bfa_fcs_lport_get_rports(fcs_port, (wwn_t *)iocmd_bufptr,
&iocmd->nrports);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
int
bfad_iocmd_rport_get_attr(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_rport_attr_s *iocmd = (struct bfa_bsg_rport_attr_s *)cmd;
struct bfa_fcs_lport_s *fcs_port;
struct bfa_fcs_rport_s *fcs_rport;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->pwwn);
if (fcs_port == NULL) {
bfa_trc(bfad, 0);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
goto out;
}
fcs_rport = bfa_fcs_rport_lookup(fcs_port, iocmd->rpwwn);
if (fcs_rport == NULL) {
bfa_trc(bfad, 0);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_RWWN;
goto out;
}
bfa_fcs_rport_get_attr(fcs_rport, &iocmd->attr);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
static int
bfad_iocmd_rport_get_addr(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_rport_scsi_addr_s *iocmd =
(struct bfa_bsg_rport_scsi_addr_s *)cmd;
struct bfa_fcs_lport_s *fcs_port;
struct bfa_fcs_itnim_s *fcs_itnim;
struct bfad_itnim_s *drv_itnim;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->pwwn);
if (fcs_port == NULL) {
bfa_trc(bfad, 0);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
goto out;
}
fcs_itnim = bfa_fcs_itnim_lookup(fcs_port, iocmd->rpwwn);
if (fcs_itnim == NULL) {
bfa_trc(bfad, 0);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_RWWN;
goto out;
}
drv_itnim = fcs_itnim->itnim_drv;
if (drv_itnim && drv_itnim->im_port)
iocmd->host = drv_itnim->im_port->shost->host_no;
else {
bfa_trc(bfad, 0);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_RWWN;
goto out;
}
iocmd->target = drv_itnim->scsi_tgt_id;
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->bus = 0;
iocmd->lun = 0;
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
int
bfad_iocmd_rport_get_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_rport_stats_s *iocmd =
(struct bfa_bsg_rport_stats_s *)cmd;
struct bfa_fcs_lport_s *fcs_port;
struct bfa_fcs_rport_s *fcs_rport;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->pwwn);
if (fcs_port == NULL) {
bfa_trc(bfad, 0);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
goto out;
}
fcs_rport = bfa_fcs_rport_lookup(fcs_port, iocmd->rpwwn);
if (fcs_rport == NULL) {
bfa_trc(bfad, 0);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_RWWN;
goto out;
}
memcpy((void *)&iocmd->stats, (void *)&fcs_rport->stats,
sizeof(struct bfa_rport_stats_s));
memcpy((void *)&iocmd->stats.hal_stats,
(void *)&(bfa_fcs_rport_get_halrport(fcs_rport)->stats),
sizeof(struct bfa_rport_hal_stats_s));
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
int
bfad_iocmd_rport_clr_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_rport_reset_stats_s *iocmd =
(struct bfa_bsg_rport_reset_stats_s *)cmd;
struct bfa_fcs_lport_s *fcs_port;
struct bfa_fcs_rport_s *fcs_rport;
struct bfa_rport_s *rport;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->pwwn);
if (fcs_port == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
goto out;
}
fcs_rport = bfa_fcs_rport_lookup(fcs_port, iocmd->rpwwn);
if (fcs_rport == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_RWWN;
goto out;
}
memset((char *)&fcs_rport->stats, 0, sizeof(struct bfa_rport_stats_s));
rport = bfa_fcs_rport_get_halrport(fcs_rport);
memset(&rport->stats, 0, sizeof(rport->stats));
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
int
bfad_iocmd_rport_set_speed(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_rport_set_speed_s *iocmd =
(struct bfa_bsg_rport_set_speed_s *)cmd;
struct bfa_fcs_lport_s *fcs_port;
struct bfa_fcs_rport_s *fcs_rport;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->pwwn);
if (fcs_port == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
goto out;
}
fcs_rport = bfa_fcs_rport_lookup(fcs_port, iocmd->rpwwn);
if (fcs_rport == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_RWWN;
goto out;
}
fcs_rport->rpf.assigned_speed = iocmd->speed;
/* Set this speed in f/w only if the RPSC speed is not available */
if (fcs_rport->rpf.rpsc_speed == BFA_PORT_SPEED_UNKNOWN)
bfa_rport_speed(fcs_rport->bfa_rport, iocmd->speed);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
int
bfad_iocmd_vport_get_attr(struct bfad_s *bfad, void *cmd)
{
struct bfa_fcs_vport_s *fcs_vport;
struct bfa_bsg_vport_attr_s *iocmd = (struct bfa_bsg_vport_attr_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_vport = bfa_fcs_vport_lookup(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->vpwwn);
if (fcs_vport == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_VWWN;
goto out;
}
bfa_fcs_vport_get_attr(fcs_vport, &iocmd->vport_attr);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
int
bfad_iocmd_vport_get_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_fcs_vport_s *fcs_vport;
struct bfa_bsg_vport_stats_s *iocmd =
(struct bfa_bsg_vport_stats_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_vport = bfa_fcs_vport_lookup(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->vpwwn);
if (fcs_vport == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_VWWN;
goto out;
}
memcpy((void *)&iocmd->vport_stats, (void *)&fcs_vport->vport_stats,
sizeof(struct bfa_vport_stats_s));
memcpy((void *)&iocmd->vport_stats.port_stats,
(void *)&fcs_vport->lport.stats,
sizeof(struct bfa_lport_stats_s));
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
int
bfad_iocmd_vport_clr_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_fcs_vport_s *fcs_vport;
struct bfa_bsg_reset_stats_s *iocmd =
(struct bfa_bsg_reset_stats_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_vport = bfa_fcs_vport_lookup(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->vpwwn);
if (fcs_vport == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_VWWN;
goto out;
}
memset(&fcs_vport->vport_stats, 0, sizeof(struct bfa_vport_stats_s));
memset(&fcs_vport->lport.stats, 0, sizeof(struct bfa_lport_stats_s));
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
static int
bfad_iocmd_fabric_get_lports(struct bfad_s *bfad, void *cmd,
unsigned int payload_len)
{
struct bfa_bsg_fabric_get_lports_s *iocmd =
(struct bfa_bsg_fabric_get_lports_s *)cmd;
bfa_fcs_vf_t *fcs_vf;
uint32_t nports = iocmd->nports;
unsigned long flags;
void *iocmd_bufptr;
if (nports == 0) {
iocmd->status = BFA_STATUS_EINVAL;
goto out;
}
if (bfad_chk_iocmd_sz(payload_len,
sizeof(struct bfa_bsg_fabric_get_lports_s),
sizeof(wwn_t[iocmd->nports])) != BFA_STATUS_OK) {
iocmd->status = BFA_STATUS_VERSION_FAIL;
goto out;
}
iocmd_bufptr = (char *)iocmd +
sizeof(struct bfa_bsg_fabric_get_lports_s);
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_vf = bfa_fcs_vf_lookup(&bfad->bfa_fcs, iocmd->vf_id);
if (fcs_vf == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_VFID;
goto out;
}
bfa_fcs_vf_get_ports(fcs_vf, (wwn_t *)iocmd_bufptr, &nports);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->nports = nports;
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
int
bfad_iocmd_ratelim(struct bfad_s *bfad, unsigned int cmd, void *pcmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)pcmd;
struct bfa_fcport_s *fcport = BFA_FCPORT_MOD(&bfad->bfa);
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
if (cmd == IOCMD_RATELIM_ENABLE)
fcport->cfg.ratelimit = BFA_TRUE;
else if (cmd == IOCMD_RATELIM_DISABLE)
fcport->cfg.ratelimit = BFA_FALSE;
if (fcport->cfg.trl_def_speed == BFA_PORT_SPEED_UNKNOWN)
fcport->cfg.trl_def_speed = BFA_PORT_SPEED_1GBPS;
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_ratelim_speed(struct bfad_s *bfad, unsigned int cmd, void *pcmd)
{
struct bfa_bsg_trl_speed_s *iocmd = (struct bfa_bsg_trl_speed_s *)pcmd;
struct bfa_fcport_s *fcport = BFA_FCPORT_MOD(&bfad->bfa);
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
/* Auto and speeds greater than the supported speed, are invalid */
if ((iocmd->speed == BFA_PORT_SPEED_AUTO) ||
(iocmd->speed > fcport->speed_sup)) {
iocmd->status = BFA_STATUS_UNSUPP_SPEED;
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
fcport->cfg.trl_def_speed = iocmd->speed;
iocmd->status = BFA_STATUS_OK;
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
int
bfad_iocmd_cfg_fcpim(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_fcpim_s *iocmd = (struct bfa_bsg_fcpim_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
bfa_fcpim_path_tov_set(&bfad->bfa, iocmd->param);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_fcpim_get_modstats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_fcpim_modstats_s *iocmd =
(struct bfa_bsg_fcpim_modstats_s *)cmd;
struct bfa_fcpim_s *fcpim = BFA_FCPIM(&bfad->bfa);
struct list_head *qe, *qen;
struct bfa_itnim_s *itnim;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
/* accumulate IO stats from itnim */
memset((void *)&iocmd->modstats, 0, sizeof(struct bfa_itnim_iostats_s));
list_for_each_safe(qe, qen, &fcpim->itnim_q) {
itnim = (struct bfa_itnim_s *) qe;
bfa_fcpim_add_stats(&iocmd->modstats, &(itnim->stats));
}
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_fcpim_clr_modstats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_fcpim_modstatsclr_s *iocmd =
(struct bfa_bsg_fcpim_modstatsclr_s *)cmd;
struct bfa_fcpim_s *fcpim = BFA_FCPIM(&bfad->bfa);
struct list_head *qe, *qen;
struct bfa_itnim_s *itnim;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
list_for_each_safe(qe, qen, &fcpim->itnim_q) {
itnim = (struct bfa_itnim_s *) qe;
bfa_itnim_clear_stats(itnim);
}
memset(&fcpim->del_itn_stats, 0,
sizeof(struct bfa_fcpim_del_itn_stats_s));
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_fcpim_get_del_itn_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_fcpim_del_itn_stats_s *iocmd =
(struct bfa_bsg_fcpim_del_itn_stats_s *)cmd;
struct bfa_fcpim_s *fcpim = BFA_FCPIM(&bfad->bfa);
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
memcpy((void *)&iocmd->modstats, (void *)&fcpim->del_itn_stats,
sizeof(struct bfa_fcpim_del_itn_stats_s));
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
return 0;
}
static int
bfad_iocmd_itnim_get_attr(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_itnim_attr_s *iocmd = (struct bfa_bsg_itnim_attr_s *)cmd;
struct bfa_fcs_lport_s *fcs_port;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->lpwwn);
if (!fcs_port)
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
else
iocmd->status = bfa_fcs_itnim_attr_get(fcs_port,
iocmd->rpwwn, &iocmd->attr);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
static int
bfad_iocmd_itnim_get_iostats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_itnim_iostats_s *iocmd =
(struct bfa_bsg_itnim_iostats_s *)cmd;
struct bfa_fcs_lport_s *fcs_port;
struct bfa_fcs_itnim_s *itnim;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->lpwwn);
if (!fcs_port) {
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
bfa_trc(bfad, 0);
} else {
itnim = bfa_fcs_itnim_lookup(fcs_port, iocmd->rpwwn);
if (itnim == NULL)
iocmd->status = BFA_STATUS_UNKNOWN_RWWN;
else {
iocmd->status = BFA_STATUS_OK;
memcpy((void *)&iocmd->iostats, (void *)
&(bfa_fcs_itnim_get_halitn(itnim)->stats),
sizeof(struct bfa_itnim_iostats_s));
}
}
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
static int
bfad_iocmd_itnim_reset_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_rport_reset_stats_s *iocmd =
(struct bfa_bsg_rport_reset_stats_s *)cmd;
struct bfa_fcs_lport_s *fcs_port;
struct bfa_fcs_itnim_s *itnim;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->pwwn);
if (!fcs_port)
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
else {
itnim = bfa_fcs_itnim_lookup(fcs_port, iocmd->rpwwn);
if (itnim == NULL)
iocmd->status = BFA_STATUS_UNKNOWN_RWWN;
else {
iocmd->status = BFA_STATUS_OK;
bfa_fcs_itnim_stats_clear(fcs_port, iocmd->rpwwn);
bfa_itnim_clear_stats(bfa_fcs_itnim_get_halitn(itnim));
}
}
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
static int
bfad_iocmd_itnim_get_itnstats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_itnim_itnstats_s *iocmd =
(struct bfa_bsg_itnim_itnstats_s *)cmd;
struct bfa_fcs_lport_s *fcs_port;
struct bfa_fcs_itnim_s *itnim;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->lpwwn);
if (!fcs_port) {
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
bfa_trc(bfad, 0);
} else {
itnim = bfa_fcs_itnim_lookup(fcs_port, iocmd->rpwwn);
if (itnim == NULL)
iocmd->status = BFA_STATUS_UNKNOWN_RWWN;
else {
iocmd->status = BFA_STATUS_OK;
bfa_fcs_itnim_stats_get(fcs_port, iocmd->rpwwn,
&iocmd->itnstats);
}
}
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
int
bfad_iocmd_fcport_enable(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_fcport_enable(&bfad->bfa);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
int
bfad_iocmd_fcport_disable(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_fcport_disable(&bfad->bfa);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
int
bfad_iocmd_ioc_get_pcifn_cfg(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_pcifn_cfg_s *iocmd = (struct bfa_bsg_pcifn_cfg_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_ablk_query(&bfad->bfa.modules.ablk,
&iocmd->pcifn_cfg,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_pcifn_create(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_pcifn_s *iocmd = (struct bfa_bsg_pcifn_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_ablk_pf_create(&bfad->bfa.modules.ablk,
&iocmd->pcifn_id, iocmd->port,
iocmd->pcifn_class, iocmd->bandwidth,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_pcifn_delete(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_pcifn_s *iocmd = (struct bfa_bsg_pcifn_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_ablk_pf_delete(&bfad->bfa.modules.ablk,
iocmd->pcifn_id,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_pcifn_bw(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_pcifn_s *iocmd = (struct bfa_bsg_pcifn_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_ablk_pf_update(&bfad->bfa.modules.ablk,
iocmd->pcifn_id, iocmd->bandwidth,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
bfa_trc(bfad, iocmd->status);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
bfa_trc(bfad, iocmd->status);
out:
return 0;
}
int
bfad_iocmd_adapter_cfg_mode(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_adapter_cfg_mode_s *iocmd =
(struct bfa_bsg_adapter_cfg_mode_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags = 0;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_ablk_adapter_config(&bfad->bfa.modules.ablk,
iocmd->cfg.mode, iocmd->cfg.max_pf,
iocmd->cfg.max_vf, bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_port_cfg_mode(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_port_cfg_mode_s *iocmd =
(struct bfa_bsg_port_cfg_mode_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags = 0;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_ablk_port_config(&bfad->bfa.modules.ablk,
iocmd->instance, iocmd->cfg.mode,
iocmd->cfg.max_pf, iocmd->cfg.max_vf,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_ablk_optrom(struct bfad_s *bfad, unsigned int cmd, void *pcmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)pcmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
if (cmd == IOCMD_FLASH_ENABLE_OPTROM)
iocmd->status = bfa_ablk_optrom_en(&bfad->bfa.modules.ablk,
bfad_hcb_comp, &fcomp);
else
iocmd->status = bfa_ablk_optrom_dis(&bfad->bfa.modules.ablk,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_faa_query(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_faa_attr_s *iocmd = (struct bfa_bsg_faa_attr_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
iocmd->status = BFA_STATUS_OK;
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_faa_query(&bfad->bfa, &iocmd->faa_attr,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_cee_attr(struct bfad_s *bfad, void *cmd, unsigned int payload_len)
{
struct bfa_bsg_cee_attr_s *iocmd =
(struct bfa_bsg_cee_attr_s *)cmd;
void *iocmd_bufptr;
struct bfad_hal_comp cee_comp;
unsigned long flags;
if (bfad_chk_iocmd_sz(payload_len,
sizeof(struct bfa_bsg_cee_attr_s),
sizeof(struct bfa_cee_attr_s)) != BFA_STATUS_OK) {
iocmd->status = BFA_STATUS_VERSION_FAIL;
return 0;
}
iocmd_bufptr = (char *)iocmd + sizeof(struct bfa_bsg_cee_attr_s);
cee_comp.status = 0;
init_completion(&cee_comp.comp);
mutex_lock(&bfad_mutex);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_cee_get_attr(&bfad->bfa.modules.cee, iocmd_bufptr,
bfad_hcb_comp, &cee_comp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK) {
mutex_unlock(&bfad_mutex);
bfa_trc(bfad, 0x5555);
goto out;
}
wait_for_completion(&cee_comp.comp);
mutex_unlock(&bfad_mutex);
out:
return 0;
}
int
bfad_iocmd_cee_get_stats(struct bfad_s *bfad, void *cmd,
unsigned int payload_len)
{
struct bfa_bsg_cee_stats_s *iocmd =
(struct bfa_bsg_cee_stats_s *)cmd;
void *iocmd_bufptr;
struct bfad_hal_comp cee_comp;
unsigned long flags;
if (bfad_chk_iocmd_sz(payload_len,
sizeof(struct bfa_bsg_cee_stats_s),
sizeof(struct bfa_cee_stats_s)) != BFA_STATUS_OK) {
iocmd->status = BFA_STATUS_VERSION_FAIL;
return 0;
}
iocmd_bufptr = (char *)iocmd + sizeof(struct bfa_bsg_cee_stats_s);
cee_comp.status = 0;
init_completion(&cee_comp.comp);
mutex_lock(&bfad_mutex);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_cee_get_stats(&bfad->bfa.modules.cee, iocmd_bufptr,
bfad_hcb_comp, &cee_comp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK) {
mutex_unlock(&bfad_mutex);
bfa_trc(bfad, 0x5555);
goto out;
}
wait_for_completion(&cee_comp.comp);
mutex_unlock(&bfad_mutex);
out:
return 0;
}
int
bfad_iocmd_cee_reset_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_cee_reset_stats(&bfad->bfa.modules.cee, NULL, NULL);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
bfa_trc(bfad, 0x5555);
return 0;
}
int
bfad_iocmd_sfp_media(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_sfp_media_s *iocmd = (struct bfa_bsg_sfp_media_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_sfp_media(BFA_SFP_MOD(&bfad->bfa), &iocmd->media,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
bfa_trc(bfad, iocmd->status);
if (iocmd->status != BFA_STATUS_SFP_NOT_READY)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_sfp_speed(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_sfp_speed_s *iocmd = (struct bfa_bsg_sfp_speed_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_sfp_speed(BFA_SFP_MOD(&bfad->bfa), iocmd->speed,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
bfa_trc(bfad, iocmd->status);
if (iocmd->status != BFA_STATUS_SFP_NOT_READY)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_flash_get_attr(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_flash_attr_s *iocmd =
(struct bfa_bsg_flash_attr_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_flash_get_attr(BFA_FLASH(&bfad->bfa), &iocmd->attr,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_flash_erase_part(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_flash_s *iocmd = (struct bfa_bsg_flash_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_flash_erase_part(BFA_FLASH(&bfad->bfa), iocmd->type,
iocmd->instance, bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_flash_update_part(struct bfad_s *bfad, void *cmd,
unsigned int payload_len)
{
struct bfa_bsg_flash_s *iocmd = (struct bfa_bsg_flash_s *)cmd;
void *iocmd_bufptr;
struct bfad_hal_comp fcomp;
unsigned long flags;
if (bfad_chk_iocmd_sz(payload_len,
sizeof(struct bfa_bsg_flash_s),
iocmd->bufsz) != BFA_STATUS_OK) {
iocmd->status = BFA_STATUS_VERSION_FAIL;
return 0;
}
iocmd_bufptr = (char *)iocmd + sizeof(struct bfa_bsg_flash_s);
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_flash_update_part(BFA_FLASH(&bfad->bfa),
iocmd->type, iocmd->instance, iocmd_bufptr,
iocmd->bufsz, 0, bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_flash_read_part(struct bfad_s *bfad, void *cmd,
unsigned int payload_len)
{
struct bfa_bsg_flash_s *iocmd = (struct bfa_bsg_flash_s *)cmd;
struct bfad_hal_comp fcomp;
void *iocmd_bufptr;
unsigned long flags;
if (bfad_chk_iocmd_sz(payload_len,
sizeof(struct bfa_bsg_flash_s),
iocmd->bufsz) != BFA_STATUS_OK) {
iocmd->status = BFA_STATUS_VERSION_FAIL;
return 0;
}
iocmd_bufptr = (char *)iocmd + sizeof(struct bfa_bsg_flash_s);
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_flash_read_part(BFA_FLASH(&bfad->bfa), iocmd->type,
iocmd->instance, iocmd_bufptr, iocmd->bufsz, 0,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_diag_temp(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_diag_get_temp_s *iocmd =
(struct bfa_bsg_diag_get_temp_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_diag_tsensor_query(BFA_DIAG_MOD(&bfad->bfa),
&iocmd->result, bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
bfa_trc(bfad, iocmd->status);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_diag_memtest(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_diag_memtest_s *iocmd =
(struct bfa_bsg_diag_memtest_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_diag_memtest(BFA_DIAG_MOD(&bfad->bfa),
&iocmd->memtest, iocmd->pat,
&iocmd->result, bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
bfa_trc(bfad, iocmd->status);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_diag_loopback(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_diag_loopback_s *iocmd =
(struct bfa_bsg_diag_loopback_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_fcdiag_loopback(&bfad->bfa, iocmd->opmode,
iocmd->speed, iocmd->lpcnt, iocmd->pat,
&iocmd->result, bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
bfa_trc(bfad, iocmd->status);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_diag_fwping(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_diag_fwping_s *iocmd =
(struct bfa_bsg_diag_fwping_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_diag_fwping(BFA_DIAG_MOD(&bfad->bfa), iocmd->cnt,
iocmd->pattern, &iocmd->result,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
bfa_trc(bfad, iocmd->status);
if (iocmd->status != BFA_STATUS_OK)
goto out;
bfa_trc(bfad, 0x77771);
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_diag_queuetest(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_diag_qtest_s *iocmd = (struct bfa_bsg_diag_qtest_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_fcdiag_queuetest(&bfad->bfa, iocmd->force,
iocmd->queue, &iocmd->result,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_diag_sfp(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_sfp_show_s *iocmd =
(struct bfa_bsg_sfp_show_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_sfp_show(BFA_SFP_MOD(&bfad->bfa), &iocmd->sfp,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
bfa_trc(bfad, iocmd->status);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
bfa_trc(bfad, iocmd->status);
out:
return 0;
}
int
bfad_iocmd_diag_led(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_diag_led_s *iocmd = (struct bfa_bsg_diag_led_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_diag_ledtest(BFA_DIAG_MOD(&bfad->bfa),
&iocmd->ledtest);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
int
bfad_iocmd_diag_beacon_lport(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_diag_beacon_s *iocmd =
(struct bfa_bsg_diag_beacon_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_diag_beacon_port(BFA_DIAG_MOD(&bfad->bfa),
iocmd->beacon, iocmd->link_e2e_beacon,
iocmd->second);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
int
bfad_iocmd_diag_lb_stat(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_diag_lb_stat_s *iocmd =
(struct bfa_bsg_diag_lb_stat_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_fcdiag_lb_is_running(&bfad->bfa);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
bfa_trc(bfad, iocmd->status);
return 0;
}
int
bfad_iocmd_phy_get_attr(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_phy_attr_s *iocmd =
(struct bfa_bsg_phy_attr_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_phy_get_attr(BFA_PHY(&bfad->bfa), iocmd->instance,
&iocmd->attr, bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_phy_get_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_phy_stats_s *iocmd =
(struct bfa_bsg_phy_stats_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_phy_get_stats(BFA_PHY(&bfad->bfa), iocmd->instance,
&iocmd->stats, bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_phy_read(struct bfad_s *bfad, void *cmd, unsigned int payload_len)
{
struct bfa_bsg_phy_s *iocmd = (struct bfa_bsg_phy_s *)cmd;
struct bfad_hal_comp fcomp;
void *iocmd_bufptr;
unsigned long flags;
if (bfad_chk_iocmd_sz(payload_len,
sizeof(struct bfa_bsg_phy_s),
iocmd->bufsz) != BFA_STATUS_OK) {
iocmd->status = BFA_STATUS_VERSION_FAIL;
return 0;
}
iocmd_bufptr = (char *)iocmd + sizeof(struct bfa_bsg_phy_s);
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_phy_read(BFA_PHY(&bfad->bfa),
iocmd->instance, iocmd_bufptr, iocmd->bufsz,
0, bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
if (iocmd->status != BFA_STATUS_OK)
goto out;
out:
return 0;
}
int
bfad_iocmd_vhba_query(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_vhba_attr_s *iocmd =
(struct bfa_bsg_vhba_attr_s *)cmd;
struct bfa_vhba_attr_s *attr = &iocmd->attr;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
attr->pwwn = bfad->bfa.ioc.attr->pwwn;
attr->nwwn = bfad->bfa.ioc.attr->nwwn;
attr->plog_enabled = (bfa_boolean_t)bfad->bfa.plog->plog_enabled;
attr->io_profile = bfa_fcpim_get_io_profile(&bfad->bfa);
attr->path_tov = bfa_fcpim_path_tov_get(&bfad->bfa);
iocmd->status = BFA_STATUS_OK;
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
int
bfad_iocmd_phy_update(struct bfad_s *bfad, void *cmd, unsigned int payload_len)
{
struct bfa_bsg_phy_s *iocmd = (struct bfa_bsg_phy_s *)cmd;
void *iocmd_bufptr;
struct bfad_hal_comp fcomp;
unsigned long flags;
if (bfad_chk_iocmd_sz(payload_len,
sizeof(struct bfa_bsg_phy_s),
iocmd->bufsz) != BFA_STATUS_OK) {
iocmd->status = BFA_STATUS_VERSION_FAIL;
return 0;
}
iocmd_bufptr = (char *)iocmd + sizeof(struct bfa_bsg_phy_s);
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_phy_update(BFA_PHY(&bfad->bfa),
iocmd->instance, iocmd_bufptr, iocmd->bufsz,
0, bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_porglog_get(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_debug_s *iocmd = (struct bfa_bsg_debug_s *)cmd;
void *iocmd_bufptr;
if (iocmd->bufsz < sizeof(struct bfa_plog_s)) {
bfa_trc(bfad, sizeof(struct bfa_plog_s));
iocmd->status = BFA_STATUS_EINVAL;
goto out;
}
iocmd->status = BFA_STATUS_OK;
iocmd_bufptr = (char *)iocmd + sizeof(struct bfa_bsg_debug_s);
memcpy(iocmd_bufptr, (u8 *) &bfad->plog_buf, sizeof(struct bfa_plog_s));
out:
return 0;
}
#define BFA_DEBUG_FW_CORE_CHUNK_SZ 0x4000U /* 16K chunks for FW dump */
int
bfad_iocmd_debug_fw_core(struct bfad_s *bfad, void *cmd,
unsigned int payload_len)
{
struct bfa_bsg_debug_s *iocmd = (struct bfa_bsg_debug_s *)cmd;
void *iocmd_bufptr;
unsigned long flags;
u32 offset;
if (bfad_chk_iocmd_sz(payload_len, sizeof(struct bfa_bsg_debug_s),
BFA_DEBUG_FW_CORE_CHUNK_SZ) != BFA_STATUS_OK) {
iocmd->status = BFA_STATUS_VERSION_FAIL;
return 0;
}
if (iocmd->bufsz < BFA_DEBUG_FW_CORE_CHUNK_SZ ||
!IS_ALIGNED(iocmd->bufsz, sizeof(u16)) ||
!IS_ALIGNED(iocmd->offset, sizeof(u32))) {
bfa_trc(bfad, BFA_DEBUG_FW_CORE_CHUNK_SZ);
iocmd->status = BFA_STATUS_EINVAL;
goto out;
}
iocmd_bufptr = (char *)iocmd + sizeof(struct bfa_bsg_debug_s);
spin_lock_irqsave(&bfad->bfad_lock, flags);
offset = iocmd->offset;
iocmd->status = bfa_ioc_debug_fwcore(&bfad->bfa.ioc, iocmd_bufptr,
&offset, &iocmd->bufsz);
iocmd->offset = offset;
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
out:
return 0;
}
int
bfad_iocmd_debug_ctl(struct bfad_s *bfad, void *cmd, unsigned int v_cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
unsigned long flags;
if (v_cmd == IOCMD_DEBUG_FW_STATE_CLR) {
spin_lock_irqsave(&bfad->bfad_lock, flags);
bfad->bfa.ioc.dbg_fwsave_once = BFA_TRUE;
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
} else if (v_cmd == IOCMD_DEBUG_PORTLOG_CLR)
bfad->plog_buf.head = bfad->plog_buf.tail = 0;
else if (v_cmd == IOCMD_DEBUG_START_DTRC)
bfa_trc_init(bfad->trcmod);
else if (v_cmd == IOCMD_DEBUG_STOP_DTRC)
bfa_trc_stop(bfad->trcmod);
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_porglog_ctl(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_portlogctl_s *iocmd = (struct bfa_bsg_portlogctl_s *)cmd;
if (iocmd->ctl == BFA_TRUE)
bfad->plog_buf.plog_enabled = 1;
else
bfad->plog_buf.plog_enabled = 0;
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_fcpim_cfg_profile(struct bfad_s *bfad, void *cmd, unsigned int v_cmd)
{
struct bfa_bsg_fcpim_profile_s *iocmd =
(struct bfa_bsg_fcpim_profile_s *)cmd;
struct timeval tv;
unsigned long flags;
do_gettimeofday(&tv);
spin_lock_irqsave(&bfad->bfad_lock, flags);
if (v_cmd == IOCMD_FCPIM_PROFILE_ON)
iocmd->status = bfa_fcpim_profile_on(&bfad->bfa, tv.tv_sec);
else if (v_cmd == IOCMD_FCPIM_PROFILE_OFF)
iocmd->status = bfa_fcpim_profile_off(&bfad->bfa);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
static int
bfad_iocmd_itnim_get_ioprofile(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_itnim_ioprofile_s *iocmd =
(struct bfa_bsg_itnim_ioprofile_s *)cmd;
struct bfa_fcs_lport_s *fcs_port;
struct bfa_fcs_itnim_s *itnim;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs,
iocmd->vf_id, iocmd->lpwwn);
if (!fcs_port)
iocmd->status = BFA_STATUS_UNKNOWN_LWWN;
else {
itnim = bfa_fcs_itnim_lookup(fcs_port, iocmd->rpwwn);
if (itnim == NULL)
iocmd->status = BFA_STATUS_UNKNOWN_RWWN;
else
iocmd->status = bfa_itnim_get_ioprofile(
bfa_fcs_itnim_get_halitn(itnim),
&iocmd->ioprofile);
}
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
int
bfad_iocmd_fcport_get_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_fcport_stats_s *iocmd =
(struct bfa_bsg_fcport_stats_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
struct bfa_cb_pending_q_s cb_qe;
init_completion(&fcomp.comp);
bfa_pending_q_init(&cb_qe, (bfa_cb_cbfn_t)bfad_hcb_comp,
&fcomp, &iocmd->stats);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_fcport_get_stats(&bfad->bfa, &cb_qe);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK) {
bfa_trc(bfad, iocmd->status);
goto out;
}
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_fcport_reset_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
struct bfa_cb_pending_q_s cb_qe;
init_completion(&fcomp.comp);
bfa_pending_q_init(&cb_qe, (bfa_cb_cbfn_t)bfad_hcb_comp, &fcomp, NULL);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_fcport_clear_stats(&bfad->bfa, &cb_qe);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK) {
bfa_trc(bfad, iocmd->status);
goto out;
}
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_boot_cfg(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_boot_s *iocmd = (struct bfa_bsg_boot_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_flash_update_part(BFA_FLASH(&bfad->bfa),
BFA_FLASH_PART_BOOT, PCI_FUNC(bfad->pcidev->devfn),
&iocmd->cfg, sizeof(struct bfa_boot_cfg_s), 0,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_boot_query(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_boot_s *iocmd = (struct bfa_bsg_boot_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_flash_read_part(BFA_FLASH(&bfad->bfa),
BFA_FLASH_PART_BOOT, PCI_FUNC(bfad->pcidev->devfn),
&iocmd->cfg, sizeof(struct bfa_boot_cfg_s), 0,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_preboot_query(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_preboot_s *iocmd = (struct bfa_bsg_preboot_s *)cmd;
struct bfi_iocfc_cfgrsp_s *cfgrsp = bfad->bfa.iocfc.cfgrsp;
struct bfa_boot_pbc_s *pbcfg = &iocmd->cfg;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
pbcfg->enable = cfgrsp->pbc_cfg.boot_enabled;
pbcfg->nbluns = cfgrsp->pbc_cfg.nbluns;
pbcfg->speed = cfgrsp->pbc_cfg.port_speed;
memcpy(pbcfg->pblun, cfgrsp->pbc_cfg.blun, sizeof(pbcfg->pblun));
iocmd->status = BFA_STATUS_OK;
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
int
bfad_iocmd_ethboot_cfg(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_ethboot_s *iocmd = (struct bfa_bsg_ethboot_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_flash_update_part(BFA_FLASH(&bfad->bfa),
BFA_FLASH_PART_PXECFG,
bfad->bfa.ioc.port_id, &iocmd->cfg,
sizeof(struct bfa_ethboot_cfg_s), 0,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_ethboot_query(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_ethboot_s *iocmd = (struct bfa_bsg_ethboot_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
init_completion(&fcomp.comp);
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_flash_read_part(BFA_FLASH(&bfad->bfa),
BFA_FLASH_PART_PXECFG,
bfad->bfa.ioc.port_id, &iocmd->cfg,
sizeof(struct bfa_ethboot_cfg_s), 0,
bfad_hcb_comp, &fcomp);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK)
goto out;
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_cfg_trunk(struct bfad_s *bfad, void *cmd, unsigned int v_cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
struct bfa_fcport_s *fcport = BFA_FCPORT_MOD(&bfad->bfa);
struct bfa_fcport_trunk_s *trunk = &fcport->trunk;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
if (v_cmd == IOCMD_TRUNK_ENABLE) {
trunk->attr.state = BFA_TRUNK_OFFLINE;
bfa_fcport_disable(&bfad->bfa);
fcport->cfg.trunked = BFA_TRUE;
} else if (v_cmd == IOCMD_TRUNK_DISABLE) {
trunk->attr.state = BFA_TRUNK_DISABLED;
bfa_fcport_disable(&bfad->bfa);
fcport->cfg.trunked = BFA_FALSE;
}
if (!bfa_fcport_is_disabled(&bfad->bfa))
bfa_fcport_enable(&bfad->bfa);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_trunk_get_attr(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_trunk_attr_s *iocmd = (struct bfa_bsg_trunk_attr_s *)cmd;
struct bfa_fcport_s *fcport = BFA_FCPORT_MOD(&bfad->bfa);
struct bfa_fcport_trunk_s *trunk = &fcport->trunk;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
memcpy((void *)&iocmd->attr, (void *)&trunk->attr,
sizeof(struct bfa_trunk_attr_s));
iocmd->attr.port_id = bfa_lps_get_base_pid(&bfad->bfa);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_qos(struct bfad_s *bfad, void *cmd, unsigned int v_cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
struct bfa_fcport_s *fcport = BFA_FCPORT_MOD(&bfad->bfa);
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
if (bfa_ioc_get_type(&bfad->bfa.ioc) == BFA_IOC_TYPE_FC) {
if (v_cmd == IOCMD_QOS_ENABLE)
fcport->cfg.qos_enabled = BFA_TRUE;
else if (v_cmd == IOCMD_QOS_DISABLE)
fcport->cfg.qos_enabled = BFA_FALSE;
}
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_qos_get_attr(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_qos_attr_s *iocmd = (struct bfa_bsg_qos_attr_s *)cmd;
struct bfa_fcport_s *fcport = BFA_FCPORT_MOD(&bfad->bfa);
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->attr.state = fcport->qos_attr.state;
iocmd->attr.total_bb_cr = be32_to_cpu(fcport->qos_attr.total_bb_cr);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_qos_get_vc_attr(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_qos_vc_attr_s *iocmd =
(struct bfa_bsg_qos_vc_attr_s *)cmd;
struct bfa_fcport_s *fcport = BFA_FCPORT_MOD(&bfad->bfa);
struct bfa_qos_vc_attr_s *bfa_vc_attr = &fcport->qos_vc_attr;
unsigned long flags;
u32 i = 0;
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->attr.total_vc_count = be16_to_cpu(bfa_vc_attr->total_vc_count);
iocmd->attr.shared_credit = be16_to_cpu(bfa_vc_attr->shared_credit);
iocmd->attr.elp_opmode_flags =
be32_to_cpu(bfa_vc_attr->elp_opmode_flags);
/* Individual VC info */
while (i < iocmd->attr.total_vc_count) {
iocmd->attr.vc_info[i].vc_credit =
bfa_vc_attr->vc_info[i].vc_credit;
iocmd->attr.vc_info[i].borrow_credit =
bfa_vc_attr->vc_info[i].borrow_credit;
iocmd->attr.vc_info[i].priority =
bfa_vc_attr->vc_info[i].priority;
i++;
}
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
return 0;
}
int
bfad_iocmd_qos_get_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_fcport_stats_s *iocmd =
(struct bfa_bsg_fcport_stats_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
struct bfa_cb_pending_q_s cb_qe;
init_completion(&fcomp.comp);
bfa_pending_q_init(&cb_qe, (bfa_cb_cbfn_t)bfad_hcb_comp,
&fcomp, &iocmd->stats);
spin_lock_irqsave(&bfad->bfad_lock, flags);
WARN_ON(!bfa_ioc_get_fcmode(&bfad->bfa.ioc));
iocmd->status = bfa_fcport_get_stats(&bfad->bfa, &cb_qe);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK) {
bfa_trc(bfad, iocmd->status);
goto out;
}
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_qos_reset_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)cmd;
struct bfad_hal_comp fcomp;
unsigned long flags;
struct bfa_cb_pending_q_s cb_qe;
init_completion(&fcomp.comp);
bfa_pending_q_init(&cb_qe, (bfa_cb_cbfn_t)bfad_hcb_comp,
&fcomp, NULL);
spin_lock_irqsave(&bfad->bfad_lock, flags);
WARN_ON(!bfa_ioc_get_fcmode(&bfad->bfa.ioc));
iocmd->status = bfa_fcport_clear_stats(&bfad->bfa, &cb_qe);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
if (iocmd->status != BFA_STATUS_OK) {
bfa_trc(bfad, iocmd->status);
goto out;
}
wait_for_completion(&fcomp.comp);
iocmd->status = fcomp.status;
out:
return 0;
}
int
bfad_iocmd_vf_get_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_vf_stats_s *iocmd =
(struct bfa_bsg_vf_stats_s *)cmd;
struct bfa_fcs_fabric_s *fcs_vf;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_vf = bfa_fcs_vf_lookup(&bfad->bfa_fcs, iocmd->vf_id);
if (fcs_vf == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_VFID;
goto out;
}
memcpy((void *)&iocmd->stats, (void *)&fcs_vf->stats,
sizeof(struct bfa_vf_stats_s));
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
int
bfad_iocmd_vf_clr_stats(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_vf_reset_stats_s *iocmd =
(struct bfa_bsg_vf_reset_stats_s *)cmd;
struct bfa_fcs_fabric_s *fcs_vf;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_vf = bfa_fcs_vf_lookup(&bfad->bfa_fcs, iocmd->vf_id);
if (fcs_vf == NULL) {
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_UNKNOWN_VFID;
goto out;
}
memset((void *)&fcs_vf->stats, 0, sizeof(struct bfa_vf_stats_s));
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
iocmd->status = BFA_STATUS_OK;
out:
return 0;
}
/* Function to reset the LUN SCAN mode */
static void
bfad_iocmd_lunmask_reset_lunscan_mode(struct bfad_s *bfad, int lunmask_cfg)
{
struct bfad_im_port_s *pport_im = bfad->pport.im_port;
struct bfad_vport_s *vport = NULL;
/* Set the scsi device LUN SCAN flags for base port */
bfad_reset_sdev_bflags(pport_im, lunmask_cfg);
/* Set the scsi device LUN SCAN flags for the vports */
list_for_each_entry(vport, &bfad->vport_list, list_entry)
bfad_reset_sdev_bflags(vport->drv_port.im_port, lunmask_cfg);
}
int
bfad_iocmd_lunmask(struct bfad_s *bfad, void *pcmd, unsigned int v_cmd)
{
struct bfa_bsg_gen_s *iocmd = (struct bfa_bsg_gen_s *)pcmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
if (v_cmd == IOCMD_FCPIM_LUNMASK_ENABLE) {
iocmd->status = bfa_fcpim_lunmask_update(&bfad->bfa, BFA_TRUE);
/* Set the LUN Scanning mode to be Sequential scan */
if (iocmd->status == BFA_STATUS_OK)
bfad_iocmd_lunmask_reset_lunscan_mode(bfad, BFA_TRUE);
} else if (v_cmd == IOCMD_FCPIM_LUNMASK_DISABLE) {
iocmd->status = bfa_fcpim_lunmask_update(&bfad->bfa, BFA_FALSE);
/* Set the LUN Scanning mode to default REPORT_LUNS scan */
if (iocmd->status == BFA_STATUS_OK)
bfad_iocmd_lunmask_reset_lunscan_mode(bfad, BFA_FALSE);
} else if (v_cmd == IOCMD_FCPIM_LUNMASK_CLEAR)
iocmd->status = bfa_fcpim_lunmask_clear(&bfad->bfa);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
int
bfad_iocmd_fcpim_lunmask_query(struct bfad_s *bfad, void *cmd)
{
struct bfa_bsg_fcpim_lunmask_query_s *iocmd =
(struct bfa_bsg_fcpim_lunmask_query_s *)cmd;
struct bfa_lunmask_cfg_s *lun_mask = &iocmd->lun_mask;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
iocmd->status = bfa_fcpim_lunmask_query(&bfad->bfa, lun_mask);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
int
bfad_iocmd_fcpim_cfg_lunmask(struct bfad_s *bfad, void *cmd, unsigned int v_cmd)
{
struct bfa_bsg_fcpim_lunmask_s *iocmd =
(struct bfa_bsg_fcpim_lunmask_s *)cmd;
unsigned long flags;
spin_lock_irqsave(&bfad->bfad_lock, flags);
if (v_cmd == IOCMD_FCPIM_LUNMASK_ADD)
iocmd->status = bfa_fcpim_lunmask_add(&bfad->bfa, iocmd->vf_id,
&iocmd->pwwn, iocmd->rpwwn, iocmd->lun);
else if (v_cmd == IOCMD_FCPIM_LUNMASK_DELETE)
iocmd->status = bfa_fcpim_lunmask_delete(&bfad->bfa,
iocmd->vf_id, &iocmd->pwwn,
iocmd->rpwwn, iocmd->lun);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return 0;
}
static int
bfad_iocmd_handler(struct bfad_s *bfad, unsigned int cmd, void *iocmd,
unsigned int payload_len)
{
int rc = -EINVAL;
switch (cmd) {
case IOCMD_IOC_ENABLE:
rc = bfad_iocmd_ioc_enable(bfad, iocmd);
break;
case IOCMD_IOC_DISABLE:
rc = bfad_iocmd_ioc_disable(bfad, iocmd);
break;
case IOCMD_IOC_GET_INFO:
rc = bfad_iocmd_ioc_get_info(bfad, iocmd);
break;
case IOCMD_IOC_GET_ATTR:
rc = bfad_iocmd_ioc_get_attr(bfad, iocmd);
break;
case IOCMD_IOC_GET_STATS:
rc = bfad_iocmd_ioc_get_stats(bfad, iocmd);
break;
case IOCMD_IOC_GET_FWSTATS:
rc = bfad_iocmd_ioc_get_fwstats(bfad, iocmd, payload_len);
break;
case IOCMD_IOC_RESET_STATS:
case IOCMD_IOC_RESET_FWSTATS:
rc = bfad_iocmd_ioc_reset_stats(bfad, iocmd, cmd);
break;
case IOCMD_IOC_SET_ADAPTER_NAME:
case IOCMD_IOC_SET_PORT_NAME:
rc = bfad_iocmd_ioc_set_name(bfad, iocmd, cmd);
break;
case IOCMD_IOCFC_GET_ATTR:
rc = bfad_iocmd_iocfc_get_attr(bfad, iocmd);
break;
case IOCMD_IOCFC_SET_INTR:
rc = bfad_iocmd_iocfc_set_intr(bfad, iocmd);
break;
case IOCMD_PORT_ENABLE:
rc = bfad_iocmd_port_enable(bfad, iocmd);
break;
case IOCMD_PORT_DISABLE:
rc = bfad_iocmd_port_disable(bfad, iocmd);
break;
case IOCMD_PORT_GET_ATTR:
rc = bfad_iocmd_port_get_attr(bfad, iocmd);
break;
case IOCMD_PORT_GET_STATS:
rc = bfad_iocmd_port_get_stats(bfad, iocmd, payload_len);
break;
case IOCMD_PORT_RESET_STATS:
rc = bfad_iocmd_port_reset_stats(bfad, iocmd);
break;
case IOCMD_PORT_CFG_TOPO:
case IOCMD_PORT_CFG_SPEED:
case IOCMD_PORT_CFG_ALPA:
case IOCMD_PORT_CLR_ALPA:
rc = bfad_iocmd_set_port_cfg(bfad, iocmd, cmd);
break;
case IOCMD_PORT_CFG_MAXFRSZ:
rc = bfad_iocmd_port_cfg_maxfrsize(bfad, iocmd);
break;
case IOCMD_PORT_BBSC_ENABLE:
case IOCMD_PORT_BBSC_DISABLE:
rc = bfad_iocmd_port_cfg_bbsc(bfad, iocmd, cmd);
break;
case IOCMD_LPORT_GET_ATTR:
rc = bfad_iocmd_lport_get_attr(bfad, iocmd);
break;
case IOCMD_LPORT_GET_STATS:
rc = bfad_iocmd_lport_get_stats(bfad, iocmd);
break;
case IOCMD_LPORT_RESET_STATS:
rc = bfad_iocmd_lport_reset_stats(bfad, iocmd);
break;
case IOCMD_LPORT_GET_IOSTATS:
rc = bfad_iocmd_lport_get_iostats(bfad, iocmd);
break;
case IOCMD_LPORT_GET_RPORTS:
rc = bfad_iocmd_lport_get_rports(bfad, iocmd, payload_len);
break;
case IOCMD_RPORT_GET_ATTR:
rc = bfad_iocmd_rport_get_attr(bfad, iocmd);
break;
case IOCMD_RPORT_GET_ADDR:
rc = bfad_iocmd_rport_get_addr(bfad, iocmd);
break;
case IOCMD_RPORT_GET_STATS:
rc = bfad_iocmd_rport_get_stats(bfad, iocmd);
break;
case IOCMD_RPORT_RESET_STATS:
rc = bfad_iocmd_rport_clr_stats(bfad, iocmd);
break;
case IOCMD_RPORT_SET_SPEED:
rc = bfad_iocmd_rport_set_speed(bfad, iocmd);
break;
case IOCMD_VPORT_GET_ATTR:
rc = bfad_iocmd_vport_get_attr(bfad, iocmd);
break;
case IOCMD_VPORT_GET_STATS:
rc = bfad_iocmd_vport_get_stats(bfad, iocmd);
break;
case IOCMD_VPORT_RESET_STATS:
rc = bfad_iocmd_vport_clr_stats(bfad, iocmd);
break;
case IOCMD_FABRIC_GET_LPORTS:
rc = bfad_iocmd_fabric_get_lports(bfad, iocmd, payload_len);
break;
case IOCMD_RATELIM_ENABLE:
case IOCMD_RATELIM_DISABLE:
rc = bfad_iocmd_ratelim(bfad, cmd, iocmd);
break;
case IOCMD_RATELIM_DEF_SPEED:
rc = bfad_iocmd_ratelim_speed(bfad, cmd, iocmd);
break;
case IOCMD_FCPIM_FAILOVER:
rc = bfad_iocmd_cfg_fcpim(bfad, iocmd);
break;
case IOCMD_FCPIM_MODSTATS:
rc = bfad_iocmd_fcpim_get_modstats(bfad, iocmd);
break;
case IOCMD_FCPIM_MODSTATSCLR:
rc = bfad_iocmd_fcpim_clr_modstats(bfad, iocmd);
break;
case IOCMD_FCPIM_DEL_ITN_STATS:
rc = bfad_iocmd_fcpim_get_del_itn_stats(bfad, iocmd);
break;
case IOCMD_ITNIM_GET_ATTR:
rc = bfad_iocmd_itnim_get_attr(bfad, iocmd);
break;
case IOCMD_ITNIM_GET_IOSTATS:
rc = bfad_iocmd_itnim_get_iostats(bfad, iocmd);
break;
case IOCMD_ITNIM_RESET_STATS:
rc = bfad_iocmd_itnim_reset_stats(bfad, iocmd);
break;
case IOCMD_ITNIM_GET_ITNSTATS:
rc = bfad_iocmd_itnim_get_itnstats(bfad, iocmd);
break;
case IOCMD_FCPORT_ENABLE:
rc = bfad_iocmd_fcport_enable(bfad, iocmd);
break;
case IOCMD_FCPORT_DISABLE:
rc = bfad_iocmd_fcport_disable(bfad, iocmd);
break;
case IOCMD_IOC_PCIFN_CFG:
rc = bfad_iocmd_ioc_get_pcifn_cfg(bfad, iocmd);
break;
case IOCMD_PCIFN_CREATE:
rc = bfad_iocmd_pcifn_create(bfad, iocmd);
break;
case IOCMD_PCIFN_DELETE:
rc = bfad_iocmd_pcifn_delete(bfad, iocmd);
break;
case IOCMD_PCIFN_BW:
rc = bfad_iocmd_pcifn_bw(bfad, iocmd);
break;
case IOCMD_ADAPTER_CFG_MODE:
rc = bfad_iocmd_adapter_cfg_mode(bfad, iocmd);
break;
case IOCMD_PORT_CFG_MODE:
rc = bfad_iocmd_port_cfg_mode(bfad, iocmd);
break;
case IOCMD_FLASH_ENABLE_OPTROM:
case IOCMD_FLASH_DISABLE_OPTROM:
rc = bfad_iocmd_ablk_optrom(bfad, cmd, iocmd);
break;
case IOCMD_FAA_QUERY:
rc = bfad_iocmd_faa_query(bfad, iocmd);
break;
case IOCMD_CEE_GET_ATTR:
rc = bfad_iocmd_cee_attr(bfad, iocmd, payload_len);
break;
case IOCMD_CEE_GET_STATS:
rc = bfad_iocmd_cee_get_stats(bfad, iocmd, payload_len);
break;
case IOCMD_CEE_RESET_STATS:
rc = bfad_iocmd_cee_reset_stats(bfad, iocmd);
break;
case IOCMD_SFP_MEDIA:
rc = bfad_iocmd_sfp_media(bfad, iocmd);
break;
case IOCMD_SFP_SPEED:
rc = bfad_iocmd_sfp_speed(bfad, iocmd);
break;
case IOCMD_FLASH_GET_ATTR:
rc = bfad_iocmd_flash_get_attr(bfad, iocmd);
break;
case IOCMD_FLASH_ERASE_PART:
rc = bfad_iocmd_flash_erase_part(bfad, iocmd);
break;
case IOCMD_FLASH_UPDATE_PART:
rc = bfad_iocmd_flash_update_part(bfad, iocmd, payload_len);
break;
case IOCMD_FLASH_READ_PART:
rc = bfad_iocmd_flash_read_part(bfad, iocmd, payload_len);
break;
case IOCMD_DIAG_TEMP:
rc = bfad_iocmd_diag_temp(bfad, iocmd);
break;
case IOCMD_DIAG_MEMTEST:
rc = bfad_iocmd_diag_memtest(bfad, iocmd);
break;
case IOCMD_DIAG_LOOPBACK:
rc = bfad_iocmd_diag_loopback(bfad, iocmd);
break;
case IOCMD_DIAG_FWPING:
rc = bfad_iocmd_diag_fwping(bfad, iocmd);
break;
case IOCMD_DIAG_QUEUETEST:
rc = bfad_iocmd_diag_queuetest(bfad, iocmd);
break;
case IOCMD_DIAG_SFP:
rc = bfad_iocmd_diag_sfp(bfad, iocmd);
break;
case IOCMD_DIAG_LED:
rc = bfad_iocmd_diag_led(bfad, iocmd);
break;
case IOCMD_DIAG_BEACON_LPORT:
rc = bfad_iocmd_diag_beacon_lport(bfad, iocmd);
break;
case IOCMD_DIAG_LB_STAT:
rc = bfad_iocmd_diag_lb_stat(bfad, iocmd);
break;
case IOCMD_PHY_GET_ATTR:
rc = bfad_iocmd_phy_get_attr(bfad, iocmd);
break;
case IOCMD_PHY_GET_STATS:
rc = bfad_iocmd_phy_get_stats(bfad, iocmd);
break;
case IOCMD_PHY_UPDATE_FW:
rc = bfad_iocmd_phy_update(bfad, iocmd, payload_len);
break;
case IOCMD_PHY_READ_FW:
rc = bfad_iocmd_phy_read(bfad, iocmd, payload_len);
break;
case IOCMD_VHBA_QUERY:
rc = bfad_iocmd_vhba_query(bfad, iocmd);
break;
case IOCMD_DEBUG_PORTLOG:
rc = bfad_iocmd_porglog_get(bfad, iocmd);
break;
case IOCMD_DEBUG_FW_CORE:
rc = bfad_iocmd_debug_fw_core(bfad, iocmd, payload_len);
break;
case IOCMD_DEBUG_FW_STATE_CLR:
case IOCMD_DEBUG_PORTLOG_CLR:
case IOCMD_DEBUG_START_DTRC:
case IOCMD_DEBUG_STOP_DTRC:
rc = bfad_iocmd_debug_ctl(bfad, iocmd, cmd);
break;
case IOCMD_DEBUG_PORTLOG_CTL:
rc = bfad_iocmd_porglog_ctl(bfad, iocmd);
break;
case IOCMD_FCPIM_PROFILE_ON:
case IOCMD_FCPIM_PROFILE_OFF:
rc = bfad_iocmd_fcpim_cfg_profile(bfad, iocmd, cmd);
break;
case IOCMD_ITNIM_GET_IOPROFILE:
rc = bfad_iocmd_itnim_get_ioprofile(bfad, iocmd);
break;
case IOCMD_FCPORT_GET_STATS:
rc = bfad_iocmd_fcport_get_stats(bfad, iocmd);
break;
case IOCMD_FCPORT_RESET_STATS:
rc = bfad_iocmd_fcport_reset_stats(bfad, iocmd);
break;
case IOCMD_BOOT_CFG:
rc = bfad_iocmd_boot_cfg(bfad, iocmd);
break;
case IOCMD_BOOT_QUERY:
rc = bfad_iocmd_boot_query(bfad, iocmd);
break;
case IOCMD_PREBOOT_QUERY:
rc = bfad_iocmd_preboot_query(bfad, iocmd);
break;
case IOCMD_ETHBOOT_CFG:
rc = bfad_iocmd_ethboot_cfg(bfad, iocmd);
break;
case IOCMD_ETHBOOT_QUERY:
rc = bfad_iocmd_ethboot_query(bfad, iocmd);
break;
case IOCMD_TRUNK_ENABLE:
case IOCMD_TRUNK_DISABLE:
rc = bfad_iocmd_cfg_trunk(bfad, iocmd, cmd);
break;
case IOCMD_TRUNK_GET_ATTR:
rc = bfad_iocmd_trunk_get_attr(bfad, iocmd);
break;
case IOCMD_QOS_ENABLE:
case IOCMD_QOS_DISABLE:
rc = bfad_iocmd_qos(bfad, iocmd, cmd);
break;
case IOCMD_QOS_GET_ATTR:
rc = bfad_iocmd_qos_get_attr(bfad, iocmd);
break;
case IOCMD_QOS_GET_VC_ATTR:
rc = bfad_iocmd_qos_get_vc_attr(bfad, iocmd);
break;
case IOCMD_QOS_GET_STATS:
rc = bfad_iocmd_qos_get_stats(bfad, iocmd);
break;
case IOCMD_QOS_RESET_STATS:
rc = bfad_iocmd_qos_reset_stats(bfad, iocmd);
break;
case IOCMD_VF_GET_STATS:
rc = bfad_iocmd_vf_get_stats(bfad, iocmd);
break;
case IOCMD_VF_RESET_STATS:
rc = bfad_iocmd_vf_clr_stats(bfad, iocmd);
break;
case IOCMD_FCPIM_LUNMASK_ENABLE:
case IOCMD_FCPIM_LUNMASK_DISABLE:
case IOCMD_FCPIM_LUNMASK_CLEAR:
rc = bfad_iocmd_lunmask(bfad, iocmd, cmd);
break;
case IOCMD_FCPIM_LUNMASK_QUERY:
rc = bfad_iocmd_fcpim_lunmask_query(bfad, iocmd);
break;
case IOCMD_FCPIM_LUNMASK_ADD:
case IOCMD_FCPIM_LUNMASK_DELETE:
rc = bfad_iocmd_fcpim_cfg_lunmask(bfad, iocmd, cmd);
break;
default:
rc = -EINVAL;
break;
}
return rc;
}
static int
bfad_im_bsg_vendor_request(struct fc_bsg_job *job)
{
uint32_t vendor_cmd = job->request->rqst_data.h_vendor.vendor_cmd[0];
struct bfad_im_port_s *im_port =
(struct bfad_im_port_s *) job->shost->hostdata[0];
struct bfad_s *bfad = im_port->bfad;
struct request_queue *request_q = job->req->q;
void *payload_kbuf;
int rc = -EINVAL;
/*
* Set the BSG device request_queue size to 256 to support
* payloads larger than 512*1024K bytes.
*/
blk_queue_max_segments(request_q, 256);
/* Allocate a temp buffer to hold the passed in user space command */
payload_kbuf = kzalloc(job->request_payload.payload_len, GFP_KERNEL);
if (!payload_kbuf) {
rc = -ENOMEM;
goto out;
}
/* Copy the sg_list passed in to a linear buffer: holds the cmnd data */
sg_copy_to_buffer(job->request_payload.sg_list,
job->request_payload.sg_cnt, payload_kbuf,
job->request_payload.payload_len);
/* Invoke IOCMD handler - to handle all the vendor command requests */
rc = bfad_iocmd_handler(bfad, vendor_cmd, payload_kbuf,
job->request_payload.payload_len);
if (rc != BFA_STATUS_OK)
goto error;
/* Copy the response data to the job->reply_payload sg_list */
sg_copy_from_buffer(job->reply_payload.sg_list,
job->reply_payload.sg_cnt,
payload_kbuf,
job->reply_payload.payload_len);
/* free the command buffer */
kfree(payload_kbuf);
/* Fill the BSG job reply data */
job->reply_len = job->reply_payload.payload_len;
job->reply->reply_payload_rcv_len = job->reply_payload.payload_len;
job->reply->result = rc;
job->job_done(job);
return rc;
error:
/* free the command buffer */
kfree(payload_kbuf);
out:
job->reply->result = rc;
job->reply_len = sizeof(uint32_t);
job->reply->reply_payload_rcv_len = 0;
return rc;
}
/* FC passthru call backs */
u64
bfad_fcxp_get_req_sgaddr_cb(void *bfad_fcxp, int sgeid)
{
struct bfad_fcxp *drv_fcxp = bfad_fcxp;
struct bfa_sge_s *sge;
u64 addr;
sge = drv_fcxp->req_sge + sgeid;
addr = (u64)(size_t) sge->sg_addr;
return addr;
}
u32
bfad_fcxp_get_req_sglen_cb(void *bfad_fcxp, int sgeid)
{
struct bfad_fcxp *drv_fcxp = bfad_fcxp;
struct bfa_sge_s *sge;
sge = drv_fcxp->req_sge + sgeid;
return sge->sg_len;
}
u64
bfad_fcxp_get_rsp_sgaddr_cb(void *bfad_fcxp, int sgeid)
{
struct bfad_fcxp *drv_fcxp = bfad_fcxp;
struct bfa_sge_s *sge;
u64 addr;
sge = drv_fcxp->rsp_sge + sgeid;
addr = (u64)(size_t) sge->sg_addr;
return addr;
}
u32
bfad_fcxp_get_rsp_sglen_cb(void *bfad_fcxp, int sgeid)
{
struct bfad_fcxp *drv_fcxp = bfad_fcxp;
struct bfa_sge_s *sge;
sge = drv_fcxp->rsp_sge + sgeid;
return sge->sg_len;
}
void
bfad_send_fcpt_cb(void *bfad_fcxp, struct bfa_fcxp_s *fcxp, void *cbarg,
bfa_status_t req_status, u32 rsp_len, u32 resid_len,
struct fchs_s *rsp_fchs)
{
struct bfad_fcxp *drv_fcxp = bfad_fcxp;
drv_fcxp->req_status = req_status;
drv_fcxp->rsp_len = rsp_len;
/* bfa_fcxp will be automatically freed by BFA */
drv_fcxp->bfa_fcxp = NULL;
complete(&drv_fcxp->comp);
}
struct bfad_buf_info *
bfad_fcxp_map_sg(struct bfad_s *bfad, void *payload_kbuf,
uint32_t payload_len, uint32_t *num_sgles)
{
struct bfad_buf_info *buf_base, *buf_info;
struct bfa_sge_s *sg_table;
int sge_num = 1;
buf_base = kzalloc((sizeof(struct bfad_buf_info) +
sizeof(struct bfa_sge_s)) * sge_num, GFP_KERNEL);
if (!buf_base)
return NULL;
sg_table = (struct bfa_sge_s *) (((uint8_t *)buf_base) +
(sizeof(struct bfad_buf_info) * sge_num));
/* Allocate dma coherent memory */
buf_info = buf_base;
buf_info->size = payload_len;
buf_info->virt = dma_alloc_coherent(&bfad->pcidev->dev, buf_info->size,
&buf_info->phys, GFP_KERNEL);
if (!buf_info->virt)
goto out_free_mem;
/* copy the linear bsg buffer to buf_info */
memset(buf_info->virt, 0, buf_info->size);
memcpy(buf_info->virt, payload_kbuf, buf_info->size);
/*
* Setup SG table
*/
sg_table->sg_len = buf_info->size;
sg_table->sg_addr = (void *)(size_t) buf_info->phys;
*num_sgles = sge_num;
return buf_base;
out_free_mem:
kfree(buf_base);
return NULL;
}
void
bfad_fcxp_free_mem(struct bfad_s *bfad, struct bfad_buf_info *buf_base,
uint32_t num_sgles)
{
int i;
struct bfad_buf_info *buf_info = buf_base;
if (buf_base) {
for (i = 0; i < num_sgles; buf_info++, i++) {
if (buf_info->virt != NULL)
dma_free_coherent(&bfad->pcidev->dev,
buf_info->size, buf_info->virt,
buf_info->phys);
}
kfree(buf_base);
}
}
int
bfad_fcxp_bsg_send(struct fc_bsg_job *job, struct bfad_fcxp *drv_fcxp,
bfa_bsg_fcpt_t *bsg_fcpt)
{
struct bfa_fcxp_s *hal_fcxp;
struct bfad_s *bfad = drv_fcxp->port->bfad;
unsigned long flags;
uint8_t lp_tag;
spin_lock_irqsave(&bfad->bfad_lock, flags);
/* Allocate bfa_fcxp structure */
hal_fcxp = bfa_fcxp_alloc(drv_fcxp, &bfad->bfa,
drv_fcxp->num_req_sgles,
drv_fcxp->num_rsp_sgles,
bfad_fcxp_get_req_sgaddr_cb,
bfad_fcxp_get_req_sglen_cb,
bfad_fcxp_get_rsp_sgaddr_cb,
bfad_fcxp_get_rsp_sglen_cb);
if (!hal_fcxp) {
bfa_trc(bfad, 0);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return BFA_STATUS_ENOMEM;
}
drv_fcxp->bfa_fcxp = hal_fcxp;
lp_tag = bfa_lps_get_tag_from_pid(&bfad->bfa, bsg_fcpt->fchs.s_id);
bfa_fcxp_send(hal_fcxp, drv_fcxp->bfa_rport, bsg_fcpt->vf_id, lp_tag,
bsg_fcpt->cts, bsg_fcpt->cos,
job->request_payload.payload_len,
&bsg_fcpt->fchs, bfad_send_fcpt_cb, bfad,
job->reply_payload.payload_len, bsg_fcpt->tsecs);
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
return BFA_STATUS_OK;
}
int
bfad_im_bsg_els_ct_request(struct fc_bsg_job *job)
{
struct bfa_bsg_data *bsg_data;
struct bfad_im_port_s *im_port =
(struct bfad_im_port_s *) job->shost->hostdata[0];
struct bfad_s *bfad = im_port->bfad;
bfa_bsg_fcpt_t *bsg_fcpt;
struct bfad_fcxp *drv_fcxp;
struct bfa_fcs_lport_s *fcs_port;
struct bfa_fcs_rport_s *fcs_rport;
uint32_t command_type = job->request->msgcode;
unsigned long flags;
struct bfad_buf_info *rsp_buf_info;
void *req_kbuf = NULL, *rsp_kbuf = NULL;
int rc = -EINVAL;
job->reply_len = sizeof(uint32_t); /* Atleast uint32_t reply_len */
job->reply->reply_payload_rcv_len = 0;
/* Get the payload passed in from userspace */
bsg_data = (struct bfa_bsg_data *) (((char *)job->request) +
sizeof(struct fc_bsg_request));
if (bsg_data == NULL)
goto out;
/*
* Allocate buffer for bsg_fcpt and do a copy_from_user op for payload
* buffer of size bsg_data->payload_len
*/
bsg_fcpt = kzalloc(bsg_data->payload_len, GFP_KERNEL);
if (!bsg_fcpt)
goto out;
if (copy_from_user((uint8_t *)bsg_fcpt, bsg_data->payload,
bsg_data->payload_len)) {
kfree(bsg_fcpt);
goto out;
}
drv_fcxp = kzalloc(sizeof(struct bfad_fcxp), GFP_KERNEL);
if (drv_fcxp == NULL) {
kfree(bsg_fcpt);
rc = -ENOMEM;
goto out;
}
spin_lock_irqsave(&bfad->bfad_lock, flags);
fcs_port = bfa_fcs_lookup_port(&bfad->bfa_fcs, bsg_fcpt->vf_id,
bsg_fcpt->lpwwn);
if (fcs_port == NULL) {
bsg_fcpt->status = BFA_STATUS_UNKNOWN_LWWN;
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
goto out_free_mem;
}
/* Check if the port is online before sending FC Passthru cmd */
if (!bfa_fcs_lport_is_online(fcs_port)) {
bsg_fcpt->status = BFA_STATUS_PORT_OFFLINE;
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
goto out_free_mem;
}
drv_fcxp->port = fcs_port->bfad_port;
if (drv_fcxp->port->bfad == 0)
drv_fcxp->port->bfad = bfad;
/* Fetch the bfa_rport - if nexus needed */
if (command_type == FC_BSG_HST_ELS_NOLOGIN ||
command_type == FC_BSG_HST_CT) {
/* BSG HST commands: no nexus needed */
drv_fcxp->bfa_rport = NULL;
} else if (command_type == FC_BSG_RPT_ELS ||
command_type == FC_BSG_RPT_CT) {
/* BSG RPT commands: nexus needed */
fcs_rport = bfa_fcs_lport_get_rport_by_pwwn(fcs_port,
bsg_fcpt->dpwwn);
if (fcs_rport == NULL) {
bsg_fcpt->status = BFA_STATUS_UNKNOWN_RWWN;
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
goto out_free_mem;
}
drv_fcxp->bfa_rport = fcs_rport->bfa_rport;
} else { /* Unknown BSG msgcode; return -EINVAL */
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
goto out_free_mem;
}
spin_unlock_irqrestore(&bfad->bfad_lock, flags);
/* allocate memory for req / rsp buffers */
req_kbuf = kzalloc(job->request_payload.payload_len, GFP_KERNEL);
if (!req_kbuf) {
printk(KERN_INFO "bfa %s: fcpt request buffer alloc failed\n",
bfad->pci_name);
rc = -ENOMEM;
goto out_free_mem;
}
rsp_kbuf = kzalloc(job->reply_payload.payload_len, GFP_KERNEL);
if (!rsp_kbuf) {
printk(KERN_INFO "bfa %s: fcpt response buffer alloc failed\n",
bfad->pci_name);
rc = -ENOMEM;
goto out_free_mem;
}
/* map req sg - copy the sg_list passed in to the linear buffer */
sg_copy_to_buffer(job->request_payload.sg_list,
job->request_payload.sg_cnt, req_kbuf,
job->request_payload.payload_len);
drv_fcxp->reqbuf_info = bfad_fcxp_map_sg(bfad, req_kbuf,
job->request_payload.payload_len,
&drv_fcxp->num_req_sgles);
if (!drv_fcxp->reqbuf_info) {
printk(KERN_INFO "bfa %s: fcpt request fcxp_map_sg failed\n",
bfad->pci_name);
rc = -ENOMEM;
goto out_free_mem;
}
drv_fcxp->req_sge = (struct bfa_sge_s *)
(((uint8_t *)drv_fcxp->reqbuf_info) +
(sizeof(struct bfad_buf_info) *
drv_fcxp->num_req_sgles));
/* map rsp sg */
drv_fcxp->rspbuf_info = bfad_fcxp_map_sg(bfad, rsp_kbuf,
job->reply_payload.payload_len,
&drv_fcxp->num_rsp_sgles);
if (!drv_fcxp->rspbuf_info) {
printk(KERN_INFO "bfa %s: fcpt response fcxp_map_sg failed\n",
bfad->pci_name);
rc = -ENOMEM;
goto out_free_mem;
}
rsp_buf_info = (struct bfad_buf_info *)drv_fcxp->rspbuf_info;
drv_fcxp->rsp_sge = (struct bfa_sge_s *)
(((uint8_t *)drv_fcxp->rspbuf_info) +
(sizeof(struct bfad_buf_info) *
drv_fcxp->num_rsp_sgles));
/* fcxp send */
init_completion(&drv_fcxp->comp);
rc = bfad_fcxp_bsg_send(job, drv_fcxp, bsg_fcpt);
if (rc == BFA_STATUS_OK) {
wait_for_completion(&drv_fcxp->comp);
bsg_fcpt->status = drv_fcxp->req_status;
} else {
bsg_fcpt->status = rc;
goto out_free_mem;
}
/* fill the job->reply data */
if (drv_fcxp->req_status == BFA_STATUS_OK) {
job->reply_len = drv_fcxp->rsp_len;
job->reply->reply_payload_rcv_len = drv_fcxp->rsp_len;
job->reply->reply_data.ctels_reply.status = FC_CTELS_STATUS_OK;
} else {
job->reply->reply_payload_rcv_len =
sizeof(struct fc_bsg_ctels_reply);
job->reply_len = sizeof(uint32_t);
job->reply->reply_data.ctels_reply.status =
FC_CTELS_STATUS_REJECT;
}
/* Copy the response data to the reply_payload sg list */
sg_copy_from_buffer(job->reply_payload.sg_list,
job->reply_payload.sg_cnt,
(uint8_t *)rsp_buf_info->virt,
job->reply_payload.payload_len);
out_free_mem:
bfad_fcxp_free_mem(bfad, drv_fcxp->rspbuf_info,
drv_fcxp->num_rsp_sgles);
bfad_fcxp_free_mem(bfad, drv_fcxp->reqbuf_info,
drv_fcxp->num_req_sgles);
kfree(req_kbuf);
kfree(rsp_kbuf);
/* Need a copy to user op */
if (copy_to_user(bsg_data->payload, (void *) bsg_fcpt,
bsg_data->payload_len))
rc = -EIO;
kfree(bsg_fcpt);
kfree(drv_fcxp);
out:
job->reply->result = rc;
if (rc == BFA_STATUS_OK)
job->job_done(job);
return rc;
}
int
bfad_im_bsg_request(struct fc_bsg_job *job)
{
uint32_t rc = BFA_STATUS_OK;
switch (job->request->msgcode) {
case FC_BSG_HST_VENDOR:
/* Process BSG HST Vendor requests */
rc = bfad_im_bsg_vendor_request(job);
break;
case FC_BSG_HST_ELS_NOLOGIN:
case FC_BSG_RPT_ELS:
case FC_BSG_HST_CT:
case FC_BSG_RPT_CT:
/* Process BSG ELS/CT commands */
rc = bfad_im_bsg_els_ct_request(job);
break;
default:
job->reply->result = rc = -EINVAL;
job->reply->reply_payload_rcv_len = 0;
break;
}
return rc;
}
int
bfad_im_bsg_timeout(struct fc_bsg_job *job)
{
/* Don't complete the BSG job request - return -EAGAIN
* to reset bsg job timeout : for ELS/CT pass thru we
* already have timer to track the request.
*/
return -EAGAIN;
}
| gpl-2.0 |
googyanas/Googy-Max3-Kernel | sound/pci/ymfpci/ymfpci_main.c | 4855 | 73287 | /*
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
* Routines for control of YMF724/740/744/754 chips
*
* 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/delay.h>
#include <linux/firmware.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/pci.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/mutex.h>
#include <linux/module.h>
#include <sound/core.h>
#include <sound/control.h>
#include <sound/info.h>
#include <sound/tlv.h>
#include <sound/ymfpci.h>
#include <sound/asoundef.h>
#include <sound/mpu401.h>
#include <asm/io.h>
#include <asm/byteorder.h>
/*
* common I/O routines
*/
static void snd_ymfpci_irq_wait(struct snd_ymfpci *chip);
static inline u8 snd_ymfpci_readb(struct snd_ymfpci *chip, u32 offset)
{
return readb(chip->reg_area_virt + offset);
}
static inline void snd_ymfpci_writeb(struct snd_ymfpci *chip, u32 offset, u8 val)
{
writeb(val, chip->reg_area_virt + offset);
}
static inline u16 snd_ymfpci_readw(struct snd_ymfpci *chip, u32 offset)
{
return readw(chip->reg_area_virt + offset);
}
static inline void snd_ymfpci_writew(struct snd_ymfpci *chip, u32 offset, u16 val)
{
writew(val, chip->reg_area_virt + offset);
}
static inline u32 snd_ymfpci_readl(struct snd_ymfpci *chip, u32 offset)
{
return readl(chip->reg_area_virt + offset);
}
static inline void snd_ymfpci_writel(struct snd_ymfpci *chip, u32 offset, u32 val)
{
writel(val, chip->reg_area_virt + offset);
}
static int snd_ymfpci_codec_ready(struct snd_ymfpci *chip, int secondary)
{
unsigned long end_time;
u32 reg = secondary ? YDSXGR_SECSTATUSADR : YDSXGR_PRISTATUSADR;
end_time = jiffies + msecs_to_jiffies(750);
do {
if ((snd_ymfpci_readw(chip, reg) & 0x8000) == 0)
return 0;
schedule_timeout_uninterruptible(1);
} while (time_before(jiffies, end_time));
snd_printk(KERN_ERR "codec_ready: codec %i is not ready [0x%x]\n", secondary, snd_ymfpci_readw(chip, reg));
return -EBUSY;
}
static void snd_ymfpci_codec_write(struct snd_ac97 *ac97, u16 reg, u16 val)
{
struct snd_ymfpci *chip = ac97->private_data;
u32 cmd;
snd_ymfpci_codec_ready(chip, 0);
cmd = ((YDSXG_AC97WRITECMD | reg) << 16) | val;
snd_ymfpci_writel(chip, YDSXGR_AC97CMDDATA, cmd);
}
static u16 snd_ymfpci_codec_read(struct snd_ac97 *ac97, u16 reg)
{
struct snd_ymfpci *chip = ac97->private_data;
if (snd_ymfpci_codec_ready(chip, 0))
return ~0;
snd_ymfpci_writew(chip, YDSXGR_AC97CMDADR, YDSXG_AC97READCMD | reg);
if (snd_ymfpci_codec_ready(chip, 0))
return ~0;
if (chip->device_id == PCI_DEVICE_ID_YAMAHA_744 && chip->rev < 2) {
int i;
for (i = 0; i < 600; i++)
snd_ymfpci_readw(chip, YDSXGR_PRISTATUSDATA);
}
return snd_ymfpci_readw(chip, YDSXGR_PRISTATUSDATA);
}
/*
* Misc routines
*/
static u32 snd_ymfpci_calc_delta(u32 rate)
{
switch (rate) {
case 8000: return 0x02aaab00;
case 11025: return 0x03accd00;
case 16000: return 0x05555500;
case 22050: return 0x07599a00;
case 32000: return 0x0aaaab00;
case 44100: return 0x0eb33300;
default: return ((rate << 16) / 375) << 5;
}
}
static u32 def_rate[8] = {
100, 2000, 8000, 11025, 16000, 22050, 32000, 48000
};
static u32 snd_ymfpci_calc_lpfK(u32 rate)
{
u32 i;
static u32 val[8] = {
0x00570000, 0x06AA0000, 0x18B20000, 0x20930000,
0x2B9A0000, 0x35A10000, 0x3EAA0000, 0x40000000
};
if (rate == 44100)
return 0x40000000; /* FIXME: What's the right value? */
for (i = 0; i < 8; i++)
if (rate <= def_rate[i])
return val[i];
return val[0];
}
static u32 snd_ymfpci_calc_lpfQ(u32 rate)
{
u32 i;
static u32 val[8] = {
0x35280000, 0x34A70000, 0x32020000, 0x31770000,
0x31390000, 0x31C90000, 0x33D00000, 0x40000000
};
if (rate == 44100)
return 0x370A0000;
for (i = 0; i < 8; i++)
if (rate <= def_rate[i])
return val[i];
return val[0];
}
/*
* Hardware start management
*/
static void snd_ymfpci_hw_start(struct snd_ymfpci *chip)
{
unsigned long flags;
spin_lock_irqsave(&chip->reg_lock, flags);
if (chip->start_count++ > 0)
goto __end;
snd_ymfpci_writel(chip, YDSXGR_MODE,
snd_ymfpci_readl(chip, YDSXGR_MODE) | 3);
chip->active_bank = snd_ymfpci_readl(chip, YDSXGR_CTRLSELECT) & 1;
__end:
spin_unlock_irqrestore(&chip->reg_lock, flags);
}
static void snd_ymfpci_hw_stop(struct snd_ymfpci *chip)
{
unsigned long flags;
long timeout = 1000;
spin_lock_irqsave(&chip->reg_lock, flags);
if (--chip->start_count > 0)
goto __end;
snd_ymfpci_writel(chip, YDSXGR_MODE,
snd_ymfpci_readl(chip, YDSXGR_MODE) & ~3);
while (timeout-- > 0) {
if ((snd_ymfpci_readl(chip, YDSXGR_STATUS) & 2) == 0)
break;
}
if (atomic_read(&chip->interrupt_sleep_count)) {
atomic_set(&chip->interrupt_sleep_count, 0);
wake_up(&chip->interrupt_sleep);
}
__end:
spin_unlock_irqrestore(&chip->reg_lock, flags);
}
/*
* Playback voice management
*/
static int voice_alloc(struct snd_ymfpci *chip,
enum snd_ymfpci_voice_type type, int pair,
struct snd_ymfpci_voice **rvoice)
{
struct snd_ymfpci_voice *voice, *voice2;
int idx;
*rvoice = NULL;
for (idx = 0; idx < YDSXG_PLAYBACK_VOICES; idx += pair ? 2 : 1) {
voice = &chip->voices[idx];
voice2 = pair ? &chip->voices[idx+1] : NULL;
if (voice->use || (voice2 && voice2->use))
continue;
voice->use = 1;
if (voice2)
voice2->use = 1;
switch (type) {
case YMFPCI_PCM:
voice->pcm = 1;
if (voice2)
voice2->pcm = 1;
break;
case YMFPCI_SYNTH:
voice->synth = 1;
break;
case YMFPCI_MIDI:
voice->midi = 1;
break;
}
snd_ymfpci_hw_start(chip);
if (voice2)
snd_ymfpci_hw_start(chip);
*rvoice = voice;
return 0;
}
return -ENOMEM;
}
static int snd_ymfpci_voice_alloc(struct snd_ymfpci *chip,
enum snd_ymfpci_voice_type type, int pair,
struct snd_ymfpci_voice **rvoice)
{
unsigned long flags;
int result;
if (snd_BUG_ON(!rvoice))
return -EINVAL;
if (snd_BUG_ON(pair && type != YMFPCI_PCM))
return -EINVAL;
spin_lock_irqsave(&chip->voice_lock, flags);
for (;;) {
result = voice_alloc(chip, type, pair, rvoice);
if (result == 0 || type != YMFPCI_PCM)
break;
/* TODO: synth/midi voice deallocation */
break;
}
spin_unlock_irqrestore(&chip->voice_lock, flags);
return result;
}
static int snd_ymfpci_voice_free(struct snd_ymfpci *chip, struct snd_ymfpci_voice *pvoice)
{
unsigned long flags;
if (snd_BUG_ON(!pvoice))
return -EINVAL;
snd_ymfpci_hw_stop(chip);
spin_lock_irqsave(&chip->voice_lock, flags);
if (pvoice->number == chip->src441_used) {
chip->src441_used = -1;
pvoice->ypcm->use_441_slot = 0;
}
pvoice->use = pvoice->pcm = pvoice->synth = pvoice->midi = 0;
pvoice->ypcm = NULL;
pvoice->interrupt = NULL;
spin_unlock_irqrestore(&chip->voice_lock, flags);
return 0;
}
/*
* PCM part
*/
static void snd_ymfpci_pcm_interrupt(struct snd_ymfpci *chip, struct snd_ymfpci_voice *voice)
{
struct snd_ymfpci_pcm *ypcm;
u32 pos, delta;
if ((ypcm = voice->ypcm) == NULL)
return;
if (ypcm->substream == NULL)
return;
spin_lock(&chip->reg_lock);
if (ypcm->running) {
pos = le32_to_cpu(voice->bank[chip->active_bank].start);
if (pos < ypcm->last_pos)
delta = pos + (ypcm->buffer_size - ypcm->last_pos);
else
delta = pos - ypcm->last_pos;
ypcm->period_pos += delta;
ypcm->last_pos = pos;
if (ypcm->period_pos >= ypcm->period_size) {
/*
printk(KERN_DEBUG
"done - active_bank = 0x%x, start = 0x%x\n",
chip->active_bank,
voice->bank[chip->active_bank].start);
*/
ypcm->period_pos %= ypcm->period_size;
spin_unlock(&chip->reg_lock);
snd_pcm_period_elapsed(ypcm->substream);
spin_lock(&chip->reg_lock);
}
if (unlikely(ypcm->update_pcm_vol)) {
unsigned int subs = ypcm->substream->number;
unsigned int next_bank = 1 - chip->active_bank;
struct snd_ymfpci_playback_bank *bank;
u32 volume;
bank = &voice->bank[next_bank];
volume = cpu_to_le32(chip->pcm_mixer[subs].left << 15);
bank->left_gain_end = volume;
if (ypcm->output_rear)
bank->eff2_gain_end = volume;
if (ypcm->voices[1])
bank = &ypcm->voices[1]->bank[next_bank];
volume = cpu_to_le32(chip->pcm_mixer[subs].right << 15);
bank->right_gain_end = volume;
if (ypcm->output_rear)
bank->eff3_gain_end = volume;
ypcm->update_pcm_vol--;
}
}
spin_unlock(&chip->reg_lock);
}
static void snd_ymfpci_pcm_capture_interrupt(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm = runtime->private_data;
struct snd_ymfpci *chip = ypcm->chip;
u32 pos, delta;
spin_lock(&chip->reg_lock);
if (ypcm->running) {
pos = le32_to_cpu(chip->bank_capture[ypcm->capture_bank_number][chip->active_bank]->start) >> ypcm->shift;
if (pos < ypcm->last_pos)
delta = pos + (ypcm->buffer_size - ypcm->last_pos);
else
delta = pos - ypcm->last_pos;
ypcm->period_pos += delta;
ypcm->last_pos = pos;
if (ypcm->period_pos >= ypcm->period_size) {
ypcm->period_pos %= ypcm->period_size;
/*
printk(KERN_DEBUG
"done - active_bank = 0x%x, start = 0x%x\n",
chip->active_bank,
voice->bank[chip->active_bank].start);
*/
spin_unlock(&chip->reg_lock);
snd_pcm_period_elapsed(substream);
spin_lock(&chip->reg_lock);
}
}
spin_unlock(&chip->reg_lock);
}
static int snd_ymfpci_playback_trigger(struct snd_pcm_substream *substream,
int cmd)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_ymfpci_pcm *ypcm = substream->runtime->private_data;
struct snd_kcontrol *kctl = NULL;
int result = 0;
spin_lock(&chip->reg_lock);
if (ypcm->voices[0] == NULL) {
result = -EINVAL;
goto __unlock;
}
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
case SNDRV_PCM_TRIGGER_RESUME:
chip->ctrl_playback[ypcm->voices[0]->number + 1] = cpu_to_le32(ypcm->voices[0]->bank_addr);
if (ypcm->voices[1] != NULL && !ypcm->use_441_slot)
chip->ctrl_playback[ypcm->voices[1]->number + 1] = cpu_to_le32(ypcm->voices[1]->bank_addr);
ypcm->running = 1;
break;
case SNDRV_PCM_TRIGGER_STOP:
if (substream->pcm == chip->pcm && !ypcm->use_441_slot) {
kctl = chip->pcm_mixer[substream->number].ctl;
kctl->vd[0].access |= SNDRV_CTL_ELEM_ACCESS_INACTIVE;
}
/* fall through */
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
case SNDRV_PCM_TRIGGER_SUSPEND:
chip->ctrl_playback[ypcm->voices[0]->number + 1] = 0;
if (ypcm->voices[1] != NULL && !ypcm->use_441_slot)
chip->ctrl_playback[ypcm->voices[1]->number + 1] = 0;
ypcm->running = 0;
break;
default:
result = -EINVAL;
break;
}
__unlock:
spin_unlock(&chip->reg_lock);
if (kctl)
snd_ctl_notify(chip->card, SNDRV_CTL_EVENT_MASK_INFO, &kctl->id);
return result;
}
static int snd_ymfpci_capture_trigger(struct snd_pcm_substream *substream,
int cmd)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_ymfpci_pcm *ypcm = substream->runtime->private_data;
int result = 0;
u32 tmp;
spin_lock(&chip->reg_lock);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
case SNDRV_PCM_TRIGGER_RESUME:
tmp = snd_ymfpci_readl(chip, YDSXGR_MAPOFREC) | (1 << ypcm->capture_bank_number);
snd_ymfpci_writel(chip, YDSXGR_MAPOFREC, tmp);
ypcm->running = 1;
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
case SNDRV_PCM_TRIGGER_SUSPEND:
tmp = snd_ymfpci_readl(chip, YDSXGR_MAPOFREC) & ~(1 << ypcm->capture_bank_number);
snd_ymfpci_writel(chip, YDSXGR_MAPOFREC, tmp);
ypcm->running = 0;
break;
default:
result = -EINVAL;
break;
}
spin_unlock(&chip->reg_lock);
return result;
}
static int snd_ymfpci_pcm_voice_alloc(struct snd_ymfpci_pcm *ypcm, int voices)
{
int err;
if (ypcm->voices[1] != NULL && voices < 2) {
snd_ymfpci_voice_free(ypcm->chip, ypcm->voices[1]);
ypcm->voices[1] = NULL;
}
if (voices == 1 && ypcm->voices[0] != NULL)
return 0; /* already allocated */
if (voices == 2 && ypcm->voices[0] != NULL && ypcm->voices[1] != NULL)
return 0; /* already allocated */
if (voices > 1) {
if (ypcm->voices[0] != NULL && ypcm->voices[1] == NULL) {
snd_ymfpci_voice_free(ypcm->chip, ypcm->voices[0]);
ypcm->voices[0] = NULL;
}
}
err = snd_ymfpci_voice_alloc(ypcm->chip, YMFPCI_PCM, voices > 1, &ypcm->voices[0]);
if (err < 0)
return err;
ypcm->voices[0]->ypcm = ypcm;
ypcm->voices[0]->interrupt = snd_ymfpci_pcm_interrupt;
if (voices > 1) {
ypcm->voices[1] = &ypcm->chip->voices[ypcm->voices[0]->number + 1];
ypcm->voices[1]->ypcm = ypcm;
}
return 0;
}
static void snd_ymfpci_pcm_init_voice(struct snd_ymfpci_pcm *ypcm, unsigned int voiceidx,
struct snd_pcm_runtime *runtime,
int has_pcm_volume)
{
struct snd_ymfpci_voice *voice = ypcm->voices[voiceidx];
u32 format;
u32 delta = snd_ymfpci_calc_delta(runtime->rate);
u32 lpfQ = snd_ymfpci_calc_lpfQ(runtime->rate);
u32 lpfK = snd_ymfpci_calc_lpfK(runtime->rate);
struct snd_ymfpci_playback_bank *bank;
unsigned int nbank;
u32 vol_left, vol_right;
u8 use_left, use_right;
unsigned long flags;
if (snd_BUG_ON(!voice))
return;
if (runtime->channels == 1) {
use_left = 1;
use_right = 1;
} else {
use_left = (voiceidx & 1) == 0;
use_right = !use_left;
}
if (has_pcm_volume) {
vol_left = cpu_to_le32(ypcm->chip->pcm_mixer
[ypcm->substream->number].left << 15);
vol_right = cpu_to_le32(ypcm->chip->pcm_mixer
[ypcm->substream->number].right << 15);
} else {
vol_left = cpu_to_le32(0x40000000);
vol_right = cpu_to_le32(0x40000000);
}
spin_lock_irqsave(&ypcm->chip->voice_lock, flags);
format = runtime->channels == 2 ? 0x00010000 : 0;
if (snd_pcm_format_width(runtime->format) == 8)
format |= 0x80000000;
else if (ypcm->chip->device_id == PCI_DEVICE_ID_YAMAHA_754 &&
runtime->rate == 44100 && runtime->channels == 2 &&
voiceidx == 0 && (ypcm->chip->src441_used == -1 ||
ypcm->chip->src441_used == voice->number)) {
ypcm->chip->src441_used = voice->number;
ypcm->use_441_slot = 1;
format |= 0x10000000;
}
if (ypcm->chip->src441_used == voice->number &&
(format & 0x10000000) == 0) {
ypcm->chip->src441_used = -1;
ypcm->use_441_slot = 0;
}
if (runtime->channels == 2 && (voiceidx & 1) != 0)
format |= 1;
spin_unlock_irqrestore(&ypcm->chip->voice_lock, flags);
for (nbank = 0; nbank < 2; nbank++) {
bank = &voice->bank[nbank];
memset(bank, 0, sizeof(*bank));
bank->format = cpu_to_le32(format);
bank->base = cpu_to_le32(runtime->dma_addr);
bank->loop_end = cpu_to_le32(ypcm->buffer_size);
bank->lpfQ = cpu_to_le32(lpfQ);
bank->delta =
bank->delta_end = cpu_to_le32(delta);
bank->lpfK =
bank->lpfK_end = cpu_to_le32(lpfK);
bank->eg_gain =
bank->eg_gain_end = cpu_to_le32(0x40000000);
if (ypcm->output_front) {
if (use_left) {
bank->left_gain =
bank->left_gain_end = vol_left;
}
if (use_right) {
bank->right_gain =
bank->right_gain_end = vol_right;
}
}
if (ypcm->output_rear) {
if (!ypcm->swap_rear) {
if (use_left) {
bank->eff2_gain =
bank->eff2_gain_end = vol_left;
}
if (use_right) {
bank->eff3_gain =
bank->eff3_gain_end = vol_right;
}
} else {
/* The SPDIF out channels seem to be swapped, so we have
* to swap them here, too. The rear analog out channels
* will be wrong, but otherwise AC3 would not work.
*/
if (use_left) {
bank->eff3_gain =
bank->eff3_gain_end = vol_left;
}
if (use_right) {
bank->eff2_gain =
bank->eff2_gain_end = vol_right;
}
}
}
}
}
static int __devinit snd_ymfpci_ac3_init(struct snd_ymfpci *chip)
{
if (snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, snd_dma_pci_data(chip->pci),
4096, &chip->ac3_tmp_base) < 0)
return -ENOMEM;
chip->bank_effect[3][0]->base =
chip->bank_effect[3][1]->base = cpu_to_le32(chip->ac3_tmp_base.addr);
chip->bank_effect[3][0]->loop_end =
chip->bank_effect[3][1]->loop_end = cpu_to_le32(1024);
chip->bank_effect[4][0]->base =
chip->bank_effect[4][1]->base = cpu_to_le32(chip->ac3_tmp_base.addr + 2048);
chip->bank_effect[4][0]->loop_end =
chip->bank_effect[4][1]->loop_end = cpu_to_le32(1024);
spin_lock_irq(&chip->reg_lock);
snd_ymfpci_writel(chip, YDSXGR_MAPOFEFFECT,
snd_ymfpci_readl(chip, YDSXGR_MAPOFEFFECT) | 3 << 3);
spin_unlock_irq(&chip->reg_lock);
return 0;
}
static int snd_ymfpci_ac3_done(struct snd_ymfpci *chip)
{
spin_lock_irq(&chip->reg_lock);
snd_ymfpci_writel(chip, YDSXGR_MAPOFEFFECT,
snd_ymfpci_readl(chip, YDSXGR_MAPOFEFFECT) & ~(3 << 3));
spin_unlock_irq(&chip->reg_lock);
// snd_ymfpci_irq_wait(chip);
if (chip->ac3_tmp_base.area) {
snd_dma_free_pages(&chip->ac3_tmp_base);
chip->ac3_tmp_base.area = NULL;
}
return 0;
}
static int snd_ymfpci_playback_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm = runtime->private_data;
int err;
if ((err = snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params))) < 0)
return err;
if ((err = snd_ymfpci_pcm_voice_alloc(ypcm, params_channels(hw_params))) < 0)
return err;
return 0;
}
static int snd_ymfpci_playback_hw_free(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm;
if (runtime->private_data == NULL)
return 0;
ypcm = runtime->private_data;
/* wait, until the PCI operations are not finished */
snd_ymfpci_irq_wait(chip);
snd_pcm_lib_free_pages(substream);
if (ypcm->voices[1]) {
snd_ymfpci_voice_free(chip, ypcm->voices[1]);
ypcm->voices[1] = NULL;
}
if (ypcm->voices[0]) {
snd_ymfpci_voice_free(chip, ypcm->voices[0]);
ypcm->voices[0] = NULL;
}
return 0;
}
static int snd_ymfpci_playback_prepare(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm = runtime->private_data;
struct snd_kcontrol *kctl;
unsigned int nvoice;
ypcm->period_size = runtime->period_size;
ypcm->buffer_size = runtime->buffer_size;
ypcm->period_pos = 0;
ypcm->last_pos = 0;
for (nvoice = 0; nvoice < runtime->channels; nvoice++)
snd_ymfpci_pcm_init_voice(ypcm, nvoice, runtime,
substream->pcm == chip->pcm);
if (substream->pcm == chip->pcm && !ypcm->use_441_slot) {
kctl = chip->pcm_mixer[substream->number].ctl;
kctl->vd[0].access &= ~SNDRV_CTL_ELEM_ACCESS_INACTIVE;
snd_ctl_notify(chip->card, SNDRV_CTL_EVENT_MASK_INFO, &kctl->id);
}
return 0;
}
static int snd_ymfpci_capture_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
return snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params));
}
static int snd_ymfpci_capture_hw_free(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
/* wait, until the PCI operations are not finished */
snd_ymfpci_irq_wait(chip);
return snd_pcm_lib_free_pages(substream);
}
static int snd_ymfpci_capture_prepare(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm = runtime->private_data;
struct snd_ymfpci_capture_bank * bank;
int nbank;
u32 rate, format;
ypcm->period_size = runtime->period_size;
ypcm->buffer_size = runtime->buffer_size;
ypcm->period_pos = 0;
ypcm->last_pos = 0;
ypcm->shift = 0;
rate = ((48000 * 4096) / runtime->rate) - 1;
format = 0;
if (runtime->channels == 2) {
format |= 2;
ypcm->shift++;
}
if (snd_pcm_format_width(runtime->format) == 8)
format |= 1;
else
ypcm->shift++;
switch (ypcm->capture_bank_number) {
case 0:
snd_ymfpci_writel(chip, YDSXGR_RECFORMAT, format);
snd_ymfpci_writel(chip, YDSXGR_RECSLOTSR, rate);
break;
case 1:
snd_ymfpci_writel(chip, YDSXGR_ADCFORMAT, format);
snd_ymfpci_writel(chip, YDSXGR_ADCSLOTSR, rate);
break;
}
for (nbank = 0; nbank < 2; nbank++) {
bank = chip->bank_capture[ypcm->capture_bank_number][nbank];
bank->base = cpu_to_le32(runtime->dma_addr);
bank->loop_end = cpu_to_le32(ypcm->buffer_size << ypcm->shift);
bank->start = 0;
bank->num_of_loops = 0;
}
return 0;
}
static snd_pcm_uframes_t snd_ymfpci_playback_pointer(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm = runtime->private_data;
struct snd_ymfpci_voice *voice = ypcm->voices[0];
if (!(ypcm->running && voice))
return 0;
return le32_to_cpu(voice->bank[chip->active_bank].start);
}
static snd_pcm_uframes_t snd_ymfpci_capture_pointer(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm = runtime->private_data;
if (!ypcm->running)
return 0;
return le32_to_cpu(chip->bank_capture[ypcm->capture_bank_number][chip->active_bank]->start) >> ypcm->shift;
}
static void snd_ymfpci_irq_wait(struct snd_ymfpci *chip)
{
wait_queue_t wait;
int loops = 4;
while (loops-- > 0) {
if ((snd_ymfpci_readl(chip, YDSXGR_MODE) & 3) == 0)
continue;
init_waitqueue_entry(&wait, current);
add_wait_queue(&chip->interrupt_sleep, &wait);
atomic_inc(&chip->interrupt_sleep_count);
schedule_timeout_uninterruptible(msecs_to_jiffies(50));
remove_wait_queue(&chip->interrupt_sleep, &wait);
}
}
static irqreturn_t snd_ymfpci_interrupt(int irq, void *dev_id)
{
struct snd_ymfpci *chip = dev_id;
u32 status, nvoice, mode;
struct snd_ymfpci_voice *voice;
status = snd_ymfpci_readl(chip, YDSXGR_STATUS);
if (status & 0x80000000) {
chip->active_bank = snd_ymfpci_readl(chip, YDSXGR_CTRLSELECT) & 1;
spin_lock(&chip->voice_lock);
for (nvoice = 0; nvoice < YDSXG_PLAYBACK_VOICES; nvoice++) {
voice = &chip->voices[nvoice];
if (voice->interrupt)
voice->interrupt(chip, voice);
}
for (nvoice = 0; nvoice < YDSXG_CAPTURE_VOICES; nvoice++) {
if (chip->capture_substream[nvoice])
snd_ymfpci_pcm_capture_interrupt(chip->capture_substream[nvoice]);
}
#if 0
for (nvoice = 0; nvoice < YDSXG_EFFECT_VOICES; nvoice++) {
if (chip->effect_substream[nvoice])
snd_ymfpci_pcm_effect_interrupt(chip->effect_substream[nvoice]);
}
#endif
spin_unlock(&chip->voice_lock);
spin_lock(&chip->reg_lock);
snd_ymfpci_writel(chip, YDSXGR_STATUS, 0x80000000);
mode = snd_ymfpci_readl(chip, YDSXGR_MODE) | 2;
snd_ymfpci_writel(chip, YDSXGR_MODE, mode);
spin_unlock(&chip->reg_lock);
if (atomic_read(&chip->interrupt_sleep_count)) {
atomic_set(&chip->interrupt_sleep_count, 0);
wake_up(&chip->interrupt_sleep);
}
}
status = snd_ymfpci_readw(chip, YDSXGR_INTFLAG);
if (status & 1) {
if (chip->timer)
snd_timer_interrupt(chip->timer, chip->timer_ticks);
}
snd_ymfpci_writew(chip, YDSXGR_INTFLAG, status);
if (chip->rawmidi)
snd_mpu401_uart_interrupt(irq, chip->rawmidi->private_data);
return IRQ_HANDLED;
}
static struct snd_pcm_hardware snd_ymfpci_playback =
{
.info = (SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_PAUSE |
SNDRV_PCM_INFO_RESUME),
.formats = SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_48000,
.rate_min = 8000,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = 256 * 1024, /* FIXME: enough? */
.period_bytes_min = 64,
.period_bytes_max = 256 * 1024, /* FIXME: enough? */
.periods_min = 3,
.periods_max = 1024,
.fifo_size = 0,
};
static struct snd_pcm_hardware snd_ymfpci_capture =
{
.info = (SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_PAUSE |
SNDRV_PCM_INFO_RESUME),
.formats = SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_48000,
.rate_min = 8000,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = 256 * 1024, /* FIXME: enough? */
.period_bytes_min = 64,
.period_bytes_max = 256 * 1024, /* FIXME: enough? */
.periods_min = 3,
.periods_max = 1024,
.fifo_size = 0,
};
static void snd_ymfpci_pcm_free_substream(struct snd_pcm_runtime *runtime)
{
kfree(runtime->private_data);
}
static int snd_ymfpci_playback_open_1(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm;
int err;
runtime->hw = snd_ymfpci_playback;
/* FIXME? True value is 256/48 = 5.33333 ms */
err = snd_pcm_hw_constraint_minmax(runtime,
SNDRV_PCM_HW_PARAM_PERIOD_TIME,
5334, UINT_MAX);
if (err < 0)
return err;
err = snd_pcm_hw_rule_noresample(runtime, 48000);
if (err < 0)
return err;
ypcm = kzalloc(sizeof(*ypcm), GFP_KERNEL);
if (ypcm == NULL)
return -ENOMEM;
ypcm->chip = chip;
ypcm->type = PLAYBACK_VOICE;
ypcm->substream = substream;
runtime->private_data = ypcm;
runtime->private_free = snd_ymfpci_pcm_free_substream;
return 0;
}
/* call with spinlock held */
static void ymfpci_open_extension(struct snd_ymfpci *chip)
{
if (! chip->rear_opened) {
if (! chip->spdif_opened) /* set AC3 */
snd_ymfpci_writel(chip, YDSXGR_MODE,
snd_ymfpci_readl(chip, YDSXGR_MODE) | (1 << 30));
/* enable second codec (4CHEN) */
snd_ymfpci_writew(chip, YDSXGR_SECCONFIG,
(snd_ymfpci_readw(chip, YDSXGR_SECCONFIG) & ~0x0330) | 0x0010);
}
}
/* call with spinlock held */
static void ymfpci_close_extension(struct snd_ymfpci *chip)
{
if (! chip->rear_opened) {
if (! chip->spdif_opened)
snd_ymfpci_writel(chip, YDSXGR_MODE,
snd_ymfpci_readl(chip, YDSXGR_MODE) & ~(1 << 30));
snd_ymfpci_writew(chip, YDSXGR_SECCONFIG,
(snd_ymfpci_readw(chip, YDSXGR_SECCONFIG) & ~0x0330) & ~0x0010);
}
}
static int snd_ymfpci_playback_open(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm;
int err;
if ((err = snd_ymfpci_playback_open_1(substream)) < 0)
return err;
ypcm = runtime->private_data;
ypcm->output_front = 1;
ypcm->output_rear = chip->mode_dup4ch ? 1 : 0;
ypcm->swap_rear = 0;
spin_lock_irq(&chip->reg_lock);
if (ypcm->output_rear) {
ymfpci_open_extension(chip);
chip->rear_opened++;
}
spin_unlock_irq(&chip->reg_lock);
return 0;
}
static int snd_ymfpci_playback_spdif_open(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm;
int err;
if ((err = snd_ymfpci_playback_open_1(substream)) < 0)
return err;
ypcm = runtime->private_data;
ypcm->output_front = 0;
ypcm->output_rear = 1;
ypcm->swap_rear = 1;
spin_lock_irq(&chip->reg_lock);
snd_ymfpci_writew(chip, YDSXGR_SPDIFOUTCTRL,
snd_ymfpci_readw(chip, YDSXGR_SPDIFOUTCTRL) | 2);
ymfpci_open_extension(chip);
chip->spdif_pcm_bits = chip->spdif_bits;
snd_ymfpci_writew(chip, YDSXGR_SPDIFOUTSTATUS, chip->spdif_pcm_bits);
chip->spdif_opened++;
spin_unlock_irq(&chip->reg_lock);
chip->spdif_pcm_ctl->vd[0].access &= ~SNDRV_CTL_ELEM_ACCESS_INACTIVE;
snd_ctl_notify(chip->card, SNDRV_CTL_EVENT_MASK_VALUE |
SNDRV_CTL_EVENT_MASK_INFO, &chip->spdif_pcm_ctl->id);
return 0;
}
static int snd_ymfpci_playback_4ch_open(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm;
int err;
if ((err = snd_ymfpci_playback_open_1(substream)) < 0)
return err;
ypcm = runtime->private_data;
ypcm->output_front = 0;
ypcm->output_rear = 1;
ypcm->swap_rear = 0;
spin_lock_irq(&chip->reg_lock);
ymfpci_open_extension(chip);
chip->rear_opened++;
spin_unlock_irq(&chip->reg_lock);
return 0;
}
static int snd_ymfpci_capture_open(struct snd_pcm_substream *substream,
u32 capture_bank_number)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm;
int err;
runtime->hw = snd_ymfpci_capture;
/* FIXME? True value is 256/48 = 5.33333 ms */
err = snd_pcm_hw_constraint_minmax(runtime,
SNDRV_PCM_HW_PARAM_PERIOD_TIME,
5334, UINT_MAX);
if (err < 0)
return err;
err = snd_pcm_hw_rule_noresample(runtime, 48000);
if (err < 0)
return err;
ypcm = kzalloc(sizeof(*ypcm), GFP_KERNEL);
if (ypcm == NULL)
return -ENOMEM;
ypcm->chip = chip;
ypcm->type = capture_bank_number + CAPTURE_REC;
ypcm->substream = substream;
ypcm->capture_bank_number = capture_bank_number;
chip->capture_substream[capture_bank_number] = substream;
runtime->private_data = ypcm;
runtime->private_free = snd_ymfpci_pcm_free_substream;
snd_ymfpci_hw_start(chip);
return 0;
}
static int snd_ymfpci_capture_rec_open(struct snd_pcm_substream *substream)
{
return snd_ymfpci_capture_open(substream, 0);
}
static int snd_ymfpci_capture_ac97_open(struct snd_pcm_substream *substream)
{
return snd_ymfpci_capture_open(substream, 1);
}
static int snd_ymfpci_playback_close_1(struct snd_pcm_substream *substream)
{
return 0;
}
static int snd_ymfpci_playback_close(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_ymfpci_pcm *ypcm = substream->runtime->private_data;
spin_lock_irq(&chip->reg_lock);
if (ypcm->output_rear && chip->rear_opened > 0) {
chip->rear_opened--;
ymfpci_close_extension(chip);
}
spin_unlock_irq(&chip->reg_lock);
return snd_ymfpci_playback_close_1(substream);
}
static int snd_ymfpci_playback_spdif_close(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
spin_lock_irq(&chip->reg_lock);
chip->spdif_opened = 0;
ymfpci_close_extension(chip);
snd_ymfpci_writew(chip, YDSXGR_SPDIFOUTCTRL,
snd_ymfpci_readw(chip, YDSXGR_SPDIFOUTCTRL) & ~2);
snd_ymfpci_writew(chip, YDSXGR_SPDIFOUTSTATUS, chip->spdif_bits);
spin_unlock_irq(&chip->reg_lock);
chip->spdif_pcm_ctl->vd[0].access |= SNDRV_CTL_ELEM_ACCESS_INACTIVE;
snd_ctl_notify(chip->card, SNDRV_CTL_EVENT_MASK_VALUE |
SNDRV_CTL_EVENT_MASK_INFO, &chip->spdif_pcm_ctl->id);
return snd_ymfpci_playback_close_1(substream);
}
static int snd_ymfpci_playback_4ch_close(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
spin_lock_irq(&chip->reg_lock);
if (chip->rear_opened > 0) {
chip->rear_opened--;
ymfpci_close_extension(chip);
}
spin_unlock_irq(&chip->reg_lock);
return snd_ymfpci_playback_close_1(substream);
}
static int snd_ymfpci_capture_close(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm = runtime->private_data;
if (ypcm != NULL) {
chip->capture_substream[ypcm->capture_bank_number] = NULL;
snd_ymfpci_hw_stop(chip);
}
return 0;
}
static struct snd_pcm_ops snd_ymfpci_playback_ops = {
.open = snd_ymfpci_playback_open,
.close = snd_ymfpci_playback_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_ymfpci_playback_hw_params,
.hw_free = snd_ymfpci_playback_hw_free,
.prepare = snd_ymfpci_playback_prepare,
.trigger = snd_ymfpci_playback_trigger,
.pointer = snd_ymfpci_playback_pointer,
};
static struct snd_pcm_ops snd_ymfpci_capture_rec_ops = {
.open = snd_ymfpci_capture_rec_open,
.close = snd_ymfpci_capture_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_ymfpci_capture_hw_params,
.hw_free = snd_ymfpci_capture_hw_free,
.prepare = snd_ymfpci_capture_prepare,
.trigger = snd_ymfpci_capture_trigger,
.pointer = snd_ymfpci_capture_pointer,
};
int __devinit snd_ymfpci_pcm(struct snd_ymfpci *chip, int device, struct snd_pcm ** rpcm)
{
struct snd_pcm *pcm;
int err;
if (rpcm)
*rpcm = NULL;
if ((err = snd_pcm_new(chip->card, "YMFPCI", device, 32, 1, &pcm)) < 0)
return err;
pcm->private_data = chip;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_ymfpci_playback_ops);
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_ymfpci_capture_rec_ops);
/* global setup */
pcm->info_flags = 0;
strcpy(pcm->name, "YMFPCI");
chip->pcm = pcm;
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data(chip->pci), 64*1024, 256*1024);
if (rpcm)
*rpcm = pcm;
return 0;
}
static struct snd_pcm_ops snd_ymfpci_capture_ac97_ops = {
.open = snd_ymfpci_capture_ac97_open,
.close = snd_ymfpci_capture_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_ymfpci_capture_hw_params,
.hw_free = snd_ymfpci_capture_hw_free,
.prepare = snd_ymfpci_capture_prepare,
.trigger = snd_ymfpci_capture_trigger,
.pointer = snd_ymfpci_capture_pointer,
};
int __devinit snd_ymfpci_pcm2(struct snd_ymfpci *chip, int device, struct snd_pcm ** rpcm)
{
struct snd_pcm *pcm;
int err;
if (rpcm)
*rpcm = NULL;
if ((err = snd_pcm_new(chip->card, "YMFPCI - PCM2", device, 0, 1, &pcm)) < 0)
return err;
pcm->private_data = chip;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_ymfpci_capture_ac97_ops);
/* global setup */
pcm->info_flags = 0;
sprintf(pcm->name, "YMFPCI - %s",
chip->device_id == PCI_DEVICE_ID_YAMAHA_754 ? "Direct Recording" : "AC'97");
chip->pcm2 = pcm;
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data(chip->pci), 64*1024, 256*1024);
if (rpcm)
*rpcm = pcm;
return 0;
}
static struct snd_pcm_ops snd_ymfpci_playback_spdif_ops = {
.open = snd_ymfpci_playback_spdif_open,
.close = snd_ymfpci_playback_spdif_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_ymfpci_playback_hw_params,
.hw_free = snd_ymfpci_playback_hw_free,
.prepare = snd_ymfpci_playback_prepare,
.trigger = snd_ymfpci_playback_trigger,
.pointer = snd_ymfpci_playback_pointer,
};
int __devinit snd_ymfpci_pcm_spdif(struct snd_ymfpci *chip, int device, struct snd_pcm ** rpcm)
{
struct snd_pcm *pcm;
int err;
if (rpcm)
*rpcm = NULL;
if ((err = snd_pcm_new(chip->card, "YMFPCI - IEC958", device, 1, 0, &pcm)) < 0)
return err;
pcm->private_data = chip;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_ymfpci_playback_spdif_ops);
/* global setup */
pcm->info_flags = 0;
strcpy(pcm->name, "YMFPCI - IEC958");
chip->pcm_spdif = pcm;
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data(chip->pci), 64*1024, 256*1024);
if (rpcm)
*rpcm = pcm;
return 0;
}
static struct snd_pcm_ops snd_ymfpci_playback_4ch_ops = {
.open = snd_ymfpci_playback_4ch_open,
.close = snd_ymfpci_playback_4ch_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_ymfpci_playback_hw_params,
.hw_free = snd_ymfpci_playback_hw_free,
.prepare = snd_ymfpci_playback_prepare,
.trigger = snd_ymfpci_playback_trigger,
.pointer = snd_ymfpci_playback_pointer,
};
int __devinit snd_ymfpci_pcm_4ch(struct snd_ymfpci *chip, int device, struct snd_pcm ** rpcm)
{
struct snd_pcm *pcm;
int err;
if (rpcm)
*rpcm = NULL;
if ((err = snd_pcm_new(chip->card, "YMFPCI - Rear", device, 1, 0, &pcm)) < 0)
return err;
pcm->private_data = chip;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_ymfpci_playback_4ch_ops);
/* global setup */
pcm->info_flags = 0;
strcpy(pcm->name, "YMFPCI - Rear PCM");
chip->pcm_4ch = pcm;
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data(chip->pci), 64*1024, 256*1024);
if (rpcm)
*rpcm = pcm;
return 0;
}
static int snd_ymfpci_spdif_default_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958;
uinfo->count = 1;
return 0;
}
static int snd_ymfpci_spdif_default_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
spin_lock_irq(&chip->reg_lock);
ucontrol->value.iec958.status[0] = (chip->spdif_bits >> 0) & 0xff;
ucontrol->value.iec958.status[1] = (chip->spdif_bits >> 8) & 0xff;
ucontrol->value.iec958.status[3] = IEC958_AES3_CON_FS_48000;
spin_unlock_irq(&chip->reg_lock);
return 0;
}
static int snd_ymfpci_spdif_default_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
unsigned int val;
int change;
val = ((ucontrol->value.iec958.status[0] & 0x3e) << 0) |
(ucontrol->value.iec958.status[1] << 8);
spin_lock_irq(&chip->reg_lock);
change = chip->spdif_bits != val;
chip->spdif_bits = val;
if ((snd_ymfpci_readw(chip, YDSXGR_SPDIFOUTCTRL) & 1) && chip->pcm_spdif == NULL)
snd_ymfpci_writew(chip, YDSXGR_SPDIFOUTSTATUS, chip->spdif_bits);
spin_unlock_irq(&chip->reg_lock);
return change;
}
static struct snd_kcontrol_new snd_ymfpci_spdif_default __devinitdata =
{
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,DEFAULT),
.info = snd_ymfpci_spdif_default_info,
.get = snd_ymfpci_spdif_default_get,
.put = snd_ymfpci_spdif_default_put
};
static int snd_ymfpci_spdif_mask_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958;
uinfo->count = 1;
return 0;
}
static int snd_ymfpci_spdif_mask_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
spin_lock_irq(&chip->reg_lock);
ucontrol->value.iec958.status[0] = 0x3e;
ucontrol->value.iec958.status[1] = 0xff;
spin_unlock_irq(&chip->reg_lock);
return 0;
}
static struct snd_kcontrol_new snd_ymfpci_spdif_mask __devinitdata =
{
.access = SNDRV_CTL_ELEM_ACCESS_READ,
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,CON_MASK),
.info = snd_ymfpci_spdif_mask_info,
.get = snd_ymfpci_spdif_mask_get,
};
static int snd_ymfpci_spdif_stream_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958;
uinfo->count = 1;
return 0;
}
static int snd_ymfpci_spdif_stream_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
spin_lock_irq(&chip->reg_lock);
ucontrol->value.iec958.status[0] = (chip->spdif_pcm_bits >> 0) & 0xff;
ucontrol->value.iec958.status[1] = (chip->spdif_pcm_bits >> 8) & 0xff;
ucontrol->value.iec958.status[3] = IEC958_AES3_CON_FS_48000;
spin_unlock_irq(&chip->reg_lock);
return 0;
}
static int snd_ymfpci_spdif_stream_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
unsigned int val;
int change;
val = ((ucontrol->value.iec958.status[0] & 0x3e) << 0) |
(ucontrol->value.iec958.status[1] << 8);
spin_lock_irq(&chip->reg_lock);
change = chip->spdif_pcm_bits != val;
chip->spdif_pcm_bits = val;
if ((snd_ymfpci_readw(chip, YDSXGR_SPDIFOUTCTRL) & 2))
snd_ymfpci_writew(chip, YDSXGR_SPDIFOUTSTATUS, chip->spdif_pcm_bits);
spin_unlock_irq(&chip->reg_lock);
return change;
}
static struct snd_kcontrol_new snd_ymfpci_spdif_stream __devinitdata =
{
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE | SNDRV_CTL_ELEM_ACCESS_INACTIVE,
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,PCM_STREAM),
.info = snd_ymfpci_spdif_stream_info,
.get = snd_ymfpci_spdif_stream_get,
.put = snd_ymfpci_spdif_stream_put
};
static int snd_ymfpci_drec_source_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *info)
{
static const char *const texts[3] = {"AC'97", "IEC958", "ZV Port"};
return snd_ctl_enum_info(info, 1, 3, texts);
}
static int snd_ymfpci_drec_source_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *value)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
u16 reg;
spin_lock_irq(&chip->reg_lock);
reg = snd_ymfpci_readw(chip, YDSXGR_GLOBALCTRL);
spin_unlock_irq(&chip->reg_lock);
if (!(reg & 0x100))
value->value.enumerated.item[0] = 0;
else
value->value.enumerated.item[0] = 1 + ((reg & 0x200) != 0);
return 0;
}
static int snd_ymfpci_drec_source_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *value)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
u16 reg, old_reg;
spin_lock_irq(&chip->reg_lock);
old_reg = snd_ymfpci_readw(chip, YDSXGR_GLOBALCTRL);
if (value->value.enumerated.item[0] == 0)
reg = old_reg & ~0x100;
else
reg = (old_reg & ~0x300) | 0x100 | ((value->value.enumerated.item[0] == 2) << 9);
snd_ymfpci_writew(chip, YDSXGR_GLOBALCTRL, reg);
spin_unlock_irq(&chip->reg_lock);
return reg != old_reg;
}
static struct snd_kcontrol_new snd_ymfpci_drec_source __devinitdata = {
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Direct Recording Source",
.info = snd_ymfpci_drec_source_info,
.get = snd_ymfpci_drec_source_get,
.put = snd_ymfpci_drec_source_put
};
/*
* Mixer controls
*/
#define YMFPCI_SINGLE(xname, xindex, reg, shift) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, .index = xindex, \
.info = snd_ymfpci_info_single, \
.get = snd_ymfpci_get_single, .put = snd_ymfpci_put_single, \
.private_value = ((reg) | ((shift) << 16)) }
#define snd_ymfpci_info_single snd_ctl_boolean_mono_info
static int snd_ymfpci_get_single(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
int reg = kcontrol->private_value & 0xffff;
unsigned int shift = (kcontrol->private_value >> 16) & 0xff;
unsigned int mask = 1;
switch (reg) {
case YDSXGR_SPDIFOUTCTRL: break;
case YDSXGR_SPDIFINCTRL: break;
default: return -EINVAL;
}
ucontrol->value.integer.value[0] =
(snd_ymfpci_readl(chip, reg) >> shift) & mask;
return 0;
}
static int snd_ymfpci_put_single(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
int reg = kcontrol->private_value & 0xffff;
unsigned int shift = (kcontrol->private_value >> 16) & 0xff;
unsigned int mask = 1;
int change;
unsigned int val, oval;
switch (reg) {
case YDSXGR_SPDIFOUTCTRL: break;
case YDSXGR_SPDIFINCTRL: break;
default: return -EINVAL;
}
val = (ucontrol->value.integer.value[0] & mask);
val <<= shift;
spin_lock_irq(&chip->reg_lock);
oval = snd_ymfpci_readl(chip, reg);
val = (oval & ~(mask << shift)) | val;
change = val != oval;
snd_ymfpci_writel(chip, reg, val);
spin_unlock_irq(&chip->reg_lock);
return change;
}
static const DECLARE_TLV_DB_LINEAR(db_scale_native, TLV_DB_GAIN_MUTE, 0);
#define YMFPCI_DOUBLE(xname, xindex, reg) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, .index = xindex, \
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE | SNDRV_CTL_ELEM_ACCESS_TLV_READ, \
.info = snd_ymfpci_info_double, \
.get = snd_ymfpci_get_double, .put = snd_ymfpci_put_double, \
.private_value = reg, \
.tlv = { .p = db_scale_native } }
static int snd_ymfpci_info_double(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
unsigned int reg = kcontrol->private_value;
if (reg < 0x80 || reg >= 0xc0)
return -EINVAL;
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = 16383;
return 0;
}
static int snd_ymfpci_get_double(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
unsigned int reg = kcontrol->private_value;
unsigned int shift_left = 0, shift_right = 16, mask = 16383;
unsigned int val;
if (reg < 0x80 || reg >= 0xc0)
return -EINVAL;
spin_lock_irq(&chip->reg_lock);
val = snd_ymfpci_readl(chip, reg);
spin_unlock_irq(&chip->reg_lock);
ucontrol->value.integer.value[0] = (val >> shift_left) & mask;
ucontrol->value.integer.value[1] = (val >> shift_right) & mask;
return 0;
}
static int snd_ymfpci_put_double(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
unsigned int reg = kcontrol->private_value;
unsigned int shift_left = 0, shift_right = 16, mask = 16383;
int change;
unsigned int val1, val2, oval;
if (reg < 0x80 || reg >= 0xc0)
return -EINVAL;
val1 = ucontrol->value.integer.value[0] & mask;
val2 = ucontrol->value.integer.value[1] & mask;
val1 <<= shift_left;
val2 <<= shift_right;
spin_lock_irq(&chip->reg_lock);
oval = snd_ymfpci_readl(chip, reg);
val1 = (oval & ~((mask << shift_left) | (mask << shift_right))) | val1 | val2;
change = val1 != oval;
snd_ymfpci_writel(chip, reg, val1);
spin_unlock_irq(&chip->reg_lock);
return change;
}
static int snd_ymfpci_put_nativedacvol(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
unsigned int reg = YDSXGR_NATIVEDACOUTVOL;
unsigned int reg2 = YDSXGR_BUF441OUTVOL;
int change;
unsigned int value, oval;
value = ucontrol->value.integer.value[0] & 0x3fff;
value |= (ucontrol->value.integer.value[1] & 0x3fff) << 16;
spin_lock_irq(&chip->reg_lock);
oval = snd_ymfpci_readl(chip, reg);
change = value != oval;
snd_ymfpci_writel(chip, reg, value);
snd_ymfpci_writel(chip, reg2, value);
spin_unlock_irq(&chip->reg_lock);
return change;
}
/*
* 4ch duplication
*/
#define snd_ymfpci_info_dup4ch snd_ctl_boolean_mono_info
static int snd_ymfpci_get_dup4ch(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
ucontrol->value.integer.value[0] = chip->mode_dup4ch;
return 0;
}
static int snd_ymfpci_put_dup4ch(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
int change;
change = (ucontrol->value.integer.value[0] != chip->mode_dup4ch);
if (change)
chip->mode_dup4ch = !!ucontrol->value.integer.value[0];
return change;
}
static struct snd_kcontrol_new snd_ymfpci_dup4ch __devinitdata = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "4ch Duplication",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.info = snd_ymfpci_info_dup4ch,
.get = snd_ymfpci_get_dup4ch,
.put = snd_ymfpci_put_dup4ch,
};
static struct snd_kcontrol_new snd_ymfpci_controls[] __devinitdata = {
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Wave Playback Volume",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_TLV_READ,
.info = snd_ymfpci_info_double,
.get = snd_ymfpci_get_double,
.put = snd_ymfpci_put_nativedacvol,
.private_value = YDSXGR_NATIVEDACOUTVOL,
.tlv = { .p = db_scale_native },
},
YMFPCI_DOUBLE("Wave Capture Volume", 0, YDSXGR_NATIVEDACLOOPVOL),
YMFPCI_DOUBLE("Digital Capture Volume", 0, YDSXGR_NATIVEDACINVOL),
YMFPCI_DOUBLE("Digital Capture Volume", 1, YDSXGR_NATIVEADCINVOL),
YMFPCI_DOUBLE("ADC Playback Volume", 0, YDSXGR_PRIADCOUTVOL),
YMFPCI_DOUBLE("ADC Capture Volume", 0, YDSXGR_PRIADCLOOPVOL),
YMFPCI_DOUBLE("ADC Playback Volume", 1, YDSXGR_SECADCOUTVOL),
YMFPCI_DOUBLE("ADC Capture Volume", 1, YDSXGR_SECADCLOOPVOL),
YMFPCI_DOUBLE("FM Legacy Playback Volume", 0, YDSXGR_LEGACYOUTVOL),
YMFPCI_DOUBLE(SNDRV_CTL_NAME_IEC958("AC97 ", PLAYBACK,VOLUME), 0, YDSXGR_ZVOUTVOL),
YMFPCI_DOUBLE(SNDRV_CTL_NAME_IEC958("", CAPTURE,VOLUME), 0, YDSXGR_ZVLOOPVOL),
YMFPCI_DOUBLE(SNDRV_CTL_NAME_IEC958("AC97 ",PLAYBACK,VOLUME), 1, YDSXGR_SPDIFOUTVOL),
YMFPCI_DOUBLE(SNDRV_CTL_NAME_IEC958("",CAPTURE,VOLUME), 1, YDSXGR_SPDIFLOOPVOL),
YMFPCI_SINGLE(SNDRV_CTL_NAME_IEC958("",PLAYBACK,SWITCH), 0, YDSXGR_SPDIFOUTCTRL, 0),
YMFPCI_SINGLE(SNDRV_CTL_NAME_IEC958("",CAPTURE,SWITCH), 0, YDSXGR_SPDIFINCTRL, 0),
YMFPCI_SINGLE(SNDRV_CTL_NAME_IEC958("Loop",NONE,NONE), 0, YDSXGR_SPDIFINCTRL, 4),
};
/*
* GPIO
*/
static int snd_ymfpci_get_gpio_out(struct snd_ymfpci *chip, int pin)
{
u16 reg, mode;
unsigned long flags;
spin_lock_irqsave(&chip->reg_lock, flags);
reg = snd_ymfpci_readw(chip, YDSXGR_GPIOFUNCENABLE);
reg &= ~(1 << (pin + 8));
reg |= (1 << pin);
snd_ymfpci_writew(chip, YDSXGR_GPIOFUNCENABLE, reg);
/* set the level mode for input line */
mode = snd_ymfpci_readw(chip, YDSXGR_GPIOTYPECONFIG);
mode &= ~(3 << (pin * 2));
snd_ymfpci_writew(chip, YDSXGR_GPIOTYPECONFIG, mode);
snd_ymfpci_writew(chip, YDSXGR_GPIOFUNCENABLE, reg | (1 << (pin + 8)));
mode = snd_ymfpci_readw(chip, YDSXGR_GPIOINSTATUS);
spin_unlock_irqrestore(&chip->reg_lock, flags);
return (mode >> pin) & 1;
}
static int snd_ymfpci_set_gpio_out(struct snd_ymfpci *chip, int pin, int enable)
{
u16 reg;
unsigned long flags;
spin_lock_irqsave(&chip->reg_lock, flags);
reg = snd_ymfpci_readw(chip, YDSXGR_GPIOFUNCENABLE);
reg &= ~(1 << pin);
reg &= ~(1 << (pin + 8));
snd_ymfpci_writew(chip, YDSXGR_GPIOFUNCENABLE, reg);
snd_ymfpci_writew(chip, YDSXGR_GPIOOUTCTRL, enable << pin);
snd_ymfpci_writew(chip, YDSXGR_GPIOFUNCENABLE, reg | (1 << (pin + 8)));
spin_unlock_irqrestore(&chip->reg_lock, flags);
return 0;
}
#define snd_ymfpci_gpio_sw_info snd_ctl_boolean_mono_info
static int snd_ymfpci_gpio_sw_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
int pin = (int)kcontrol->private_value;
ucontrol->value.integer.value[0] = snd_ymfpci_get_gpio_out(chip, pin);
return 0;
}
static int snd_ymfpci_gpio_sw_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
int pin = (int)kcontrol->private_value;
if (snd_ymfpci_get_gpio_out(chip, pin) != ucontrol->value.integer.value[0]) {
snd_ymfpci_set_gpio_out(chip, pin, !!ucontrol->value.integer.value[0]);
ucontrol->value.integer.value[0] = snd_ymfpci_get_gpio_out(chip, pin);
return 1;
}
return 0;
}
static struct snd_kcontrol_new snd_ymfpci_rear_shared __devinitdata = {
.name = "Shared Rear/Line-In Switch",
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.info = snd_ymfpci_gpio_sw_info,
.get = snd_ymfpci_gpio_sw_get,
.put = snd_ymfpci_gpio_sw_put,
.private_value = 2,
};
/*
* PCM voice volume
*/
static int snd_ymfpci_pcm_vol_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = 0x8000;
return 0;
}
static int snd_ymfpci_pcm_vol_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
unsigned int subs = kcontrol->id.subdevice;
ucontrol->value.integer.value[0] = chip->pcm_mixer[subs].left;
ucontrol->value.integer.value[1] = chip->pcm_mixer[subs].right;
return 0;
}
static int snd_ymfpci_pcm_vol_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
unsigned int subs = kcontrol->id.subdevice;
struct snd_pcm_substream *substream;
unsigned long flags;
if (ucontrol->value.integer.value[0] != chip->pcm_mixer[subs].left ||
ucontrol->value.integer.value[1] != chip->pcm_mixer[subs].right) {
chip->pcm_mixer[subs].left = ucontrol->value.integer.value[0];
chip->pcm_mixer[subs].right = ucontrol->value.integer.value[1];
if (chip->pcm_mixer[subs].left > 0x8000)
chip->pcm_mixer[subs].left = 0x8000;
if (chip->pcm_mixer[subs].right > 0x8000)
chip->pcm_mixer[subs].right = 0x8000;
substream = (struct snd_pcm_substream *)kcontrol->private_value;
spin_lock_irqsave(&chip->voice_lock, flags);
if (substream->runtime && substream->runtime->private_data) {
struct snd_ymfpci_pcm *ypcm = substream->runtime->private_data;
if (!ypcm->use_441_slot)
ypcm->update_pcm_vol = 2;
}
spin_unlock_irqrestore(&chip->voice_lock, flags);
return 1;
}
return 0;
}
static struct snd_kcontrol_new snd_ymfpci_pcm_volume __devinitdata = {
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = "PCM Playback Volume",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_INACTIVE,
.info = snd_ymfpci_pcm_vol_info,
.get = snd_ymfpci_pcm_vol_get,
.put = snd_ymfpci_pcm_vol_put,
};
/*
* Mixer routines
*/
static void snd_ymfpci_mixer_free_ac97_bus(struct snd_ac97_bus *bus)
{
struct snd_ymfpci *chip = bus->private_data;
chip->ac97_bus = NULL;
}
static void snd_ymfpci_mixer_free_ac97(struct snd_ac97 *ac97)
{
struct snd_ymfpci *chip = ac97->private_data;
chip->ac97 = NULL;
}
int __devinit snd_ymfpci_mixer(struct snd_ymfpci *chip, int rear_switch)
{
struct snd_ac97_template ac97;
struct snd_kcontrol *kctl;
struct snd_pcm_substream *substream;
unsigned int idx;
int err;
static struct snd_ac97_bus_ops ops = {
.write = snd_ymfpci_codec_write,
.read = snd_ymfpci_codec_read,
};
if ((err = snd_ac97_bus(chip->card, 0, &ops, chip, &chip->ac97_bus)) < 0)
return err;
chip->ac97_bus->private_free = snd_ymfpci_mixer_free_ac97_bus;
chip->ac97_bus->no_vra = 1; /* YMFPCI doesn't need VRA */
memset(&ac97, 0, sizeof(ac97));
ac97.private_data = chip;
ac97.private_free = snd_ymfpci_mixer_free_ac97;
if ((err = snd_ac97_mixer(chip->ac97_bus, &ac97, &chip->ac97)) < 0)
return err;
/* to be sure */
snd_ac97_update_bits(chip->ac97, AC97_EXTENDED_STATUS,
AC97_EA_VRA|AC97_EA_VRM, 0);
for (idx = 0; idx < ARRAY_SIZE(snd_ymfpci_controls); idx++) {
if ((err = snd_ctl_add(chip->card, snd_ctl_new1(&snd_ymfpci_controls[idx], chip))) < 0)
return err;
}
if (chip->ac97->ext_id & AC97_EI_SDAC) {
kctl = snd_ctl_new1(&snd_ymfpci_dup4ch, chip);
err = snd_ctl_add(chip->card, kctl);
if (err < 0)
return err;
}
/* add S/PDIF control */
if (snd_BUG_ON(!chip->pcm_spdif))
return -ENXIO;
if ((err = snd_ctl_add(chip->card, kctl = snd_ctl_new1(&snd_ymfpci_spdif_default, chip))) < 0)
return err;
kctl->id.device = chip->pcm_spdif->device;
if ((err = snd_ctl_add(chip->card, kctl = snd_ctl_new1(&snd_ymfpci_spdif_mask, chip))) < 0)
return err;
kctl->id.device = chip->pcm_spdif->device;
if ((err = snd_ctl_add(chip->card, kctl = snd_ctl_new1(&snd_ymfpci_spdif_stream, chip))) < 0)
return err;
kctl->id.device = chip->pcm_spdif->device;
chip->spdif_pcm_ctl = kctl;
/* direct recording source */
if (chip->device_id == PCI_DEVICE_ID_YAMAHA_754 &&
(err = snd_ctl_add(chip->card, kctl = snd_ctl_new1(&snd_ymfpci_drec_source, chip))) < 0)
return err;
/*
* shared rear/line-in
*/
if (rear_switch) {
if ((err = snd_ctl_add(chip->card, snd_ctl_new1(&snd_ymfpci_rear_shared, chip))) < 0)
return err;
}
/* per-voice volume */
substream = chip->pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream;
for (idx = 0; idx < 32; ++idx) {
kctl = snd_ctl_new1(&snd_ymfpci_pcm_volume, chip);
if (!kctl)
return -ENOMEM;
kctl->id.device = chip->pcm->device;
kctl->id.subdevice = idx;
kctl->private_value = (unsigned long)substream;
if ((err = snd_ctl_add(chip->card, kctl)) < 0)
return err;
chip->pcm_mixer[idx].left = 0x8000;
chip->pcm_mixer[idx].right = 0x8000;
chip->pcm_mixer[idx].ctl = kctl;
substream = substream->next;
}
return 0;
}
/*
* timer
*/
static int snd_ymfpci_timer_start(struct snd_timer *timer)
{
struct snd_ymfpci *chip;
unsigned long flags;
unsigned int count;
chip = snd_timer_chip(timer);
spin_lock_irqsave(&chip->reg_lock, flags);
if (timer->sticks > 1) {
chip->timer_ticks = timer->sticks;
count = timer->sticks - 1;
} else {
/*
* Divisor 1 is not allowed; fake it by using divisor 2 and
* counting two ticks for each interrupt.
*/
chip->timer_ticks = 2;
count = 2 - 1;
}
snd_ymfpci_writew(chip, YDSXGR_TIMERCOUNT, count);
snd_ymfpci_writeb(chip, YDSXGR_TIMERCTRL, 0x03);
spin_unlock_irqrestore(&chip->reg_lock, flags);
return 0;
}
static int snd_ymfpci_timer_stop(struct snd_timer *timer)
{
struct snd_ymfpci *chip;
unsigned long flags;
chip = snd_timer_chip(timer);
spin_lock_irqsave(&chip->reg_lock, flags);
snd_ymfpci_writeb(chip, YDSXGR_TIMERCTRL, 0x00);
spin_unlock_irqrestore(&chip->reg_lock, flags);
return 0;
}
static int snd_ymfpci_timer_precise_resolution(struct snd_timer *timer,
unsigned long *num, unsigned long *den)
{
*num = 1;
*den = 96000;
return 0;
}
static struct snd_timer_hardware snd_ymfpci_timer_hw = {
.flags = SNDRV_TIMER_HW_AUTO,
.resolution = 10417, /* 1 / 96 kHz = 10.41666...us */
.ticks = 0x10000,
.start = snd_ymfpci_timer_start,
.stop = snd_ymfpci_timer_stop,
.precise_resolution = snd_ymfpci_timer_precise_resolution,
};
int __devinit snd_ymfpci_timer(struct snd_ymfpci *chip, int device)
{
struct snd_timer *timer = NULL;
struct snd_timer_id tid;
int err;
tid.dev_class = SNDRV_TIMER_CLASS_CARD;
tid.dev_sclass = SNDRV_TIMER_SCLASS_NONE;
tid.card = chip->card->number;
tid.device = device;
tid.subdevice = 0;
if ((err = snd_timer_new(chip->card, "YMFPCI", &tid, &timer)) >= 0) {
strcpy(timer->name, "YMFPCI timer");
timer->private_data = chip;
timer->hw = snd_ymfpci_timer_hw;
}
chip->timer = timer;
return err;
}
/*
* proc interface
*/
static void snd_ymfpci_proc_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_ymfpci *chip = entry->private_data;
int i;
snd_iprintf(buffer, "YMFPCI\n\n");
for (i = 0; i <= YDSXGR_WORKBASE; i += 4)
snd_iprintf(buffer, "%04x: %04x\n", i, snd_ymfpci_readl(chip, i));
}
static int __devinit snd_ymfpci_proc_init(struct snd_card *card, struct snd_ymfpci *chip)
{
struct snd_info_entry *entry;
if (! snd_card_proc_new(card, "ymfpci", &entry))
snd_info_set_text_ops(entry, chip, snd_ymfpci_proc_read);
return 0;
}
/*
* initialization routines
*/
static void snd_ymfpci_aclink_reset(struct pci_dev * pci)
{
u8 cmd;
pci_read_config_byte(pci, PCIR_DSXG_CTRL, &cmd);
#if 0 // force to reset
if (cmd & 0x03) {
#endif
pci_write_config_byte(pci, PCIR_DSXG_CTRL, cmd & 0xfc);
pci_write_config_byte(pci, PCIR_DSXG_CTRL, cmd | 0x03);
pci_write_config_byte(pci, PCIR_DSXG_CTRL, cmd & 0xfc);
pci_write_config_word(pci, PCIR_DSXG_PWRCTRL1, 0);
pci_write_config_word(pci, PCIR_DSXG_PWRCTRL2, 0);
#if 0
}
#endif
}
static void snd_ymfpci_enable_dsp(struct snd_ymfpci *chip)
{
snd_ymfpci_writel(chip, YDSXGR_CONFIG, 0x00000001);
}
static void snd_ymfpci_disable_dsp(struct snd_ymfpci *chip)
{
u32 val;
int timeout = 1000;
val = snd_ymfpci_readl(chip, YDSXGR_CONFIG);
if (val)
snd_ymfpci_writel(chip, YDSXGR_CONFIG, 0x00000000);
while (timeout-- > 0) {
val = snd_ymfpci_readl(chip, YDSXGR_STATUS);
if ((val & 0x00000002) == 0)
break;
}
}
static int snd_ymfpci_request_firmware(struct snd_ymfpci *chip)
{
int err, is_1e;
const char *name;
err = request_firmware(&chip->dsp_microcode, "yamaha/ds1_dsp.fw",
&chip->pci->dev);
if (err >= 0) {
if (chip->dsp_microcode->size != YDSXG_DSPLENGTH) {
snd_printk(KERN_ERR "DSP microcode has wrong size\n");
err = -EINVAL;
}
}
if (err < 0)
return err;
is_1e = chip->device_id == PCI_DEVICE_ID_YAMAHA_724F ||
chip->device_id == PCI_DEVICE_ID_YAMAHA_740C ||
chip->device_id == PCI_DEVICE_ID_YAMAHA_744 ||
chip->device_id == PCI_DEVICE_ID_YAMAHA_754;
name = is_1e ? "yamaha/ds1e_ctrl.fw" : "yamaha/ds1_ctrl.fw";
err = request_firmware(&chip->controller_microcode, name,
&chip->pci->dev);
if (err >= 0) {
if (chip->controller_microcode->size != YDSXG_CTRLLENGTH) {
snd_printk(KERN_ERR "controller microcode"
" has wrong size\n");
err = -EINVAL;
}
}
if (err < 0)
return err;
return 0;
}
MODULE_FIRMWARE("yamaha/ds1_dsp.fw");
MODULE_FIRMWARE("yamaha/ds1_ctrl.fw");
MODULE_FIRMWARE("yamaha/ds1e_ctrl.fw");
static void snd_ymfpci_download_image(struct snd_ymfpci *chip)
{
int i;
u16 ctrl;
const __le32 *inst;
snd_ymfpci_writel(chip, YDSXGR_NATIVEDACOUTVOL, 0x00000000);
snd_ymfpci_disable_dsp(chip);
snd_ymfpci_writel(chip, YDSXGR_MODE, 0x00010000);
snd_ymfpci_writel(chip, YDSXGR_MODE, 0x00000000);
snd_ymfpci_writel(chip, YDSXGR_MAPOFREC, 0x00000000);
snd_ymfpci_writel(chip, YDSXGR_MAPOFEFFECT, 0x00000000);
snd_ymfpci_writel(chip, YDSXGR_PLAYCTRLBASE, 0x00000000);
snd_ymfpci_writel(chip, YDSXGR_RECCTRLBASE, 0x00000000);
snd_ymfpci_writel(chip, YDSXGR_EFFCTRLBASE, 0x00000000);
ctrl = snd_ymfpci_readw(chip, YDSXGR_GLOBALCTRL);
snd_ymfpci_writew(chip, YDSXGR_GLOBALCTRL, ctrl & ~0x0007);
/* setup DSP instruction code */
inst = (const __le32 *)chip->dsp_microcode->data;
for (i = 0; i < YDSXG_DSPLENGTH / 4; i++)
snd_ymfpci_writel(chip, YDSXGR_DSPINSTRAM + (i << 2),
le32_to_cpu(inst[i]));
/* setup control instruction code */
inst = (const __le32 *)chip->controller_microcode->data;
for (i = 0; i < YDSXG_CTRLLENGTH / 4; i++)
snd_ymfpci_writel(chip, YDSXGR_CTRLINSTRAM + (i << 2),
le32_to_cpu(inst[i]));
snd_ymfpci_enable_dsp(chip);
}
static int __devinit snd_ymfpci_memalloc(struct snd_ymfpci *chip)
{
long size, playback_ctrl_size;
int voice, bank, reg;
u8 *ptr;
dma_addr_t ptr_addr;
playback_ctrl_size = 4 + 4 * YDSXG_PLAYBACK_VOICES;
chip->bank_size_playback = snd_ymfpci_readl(chip, YDSXGR_PLAYCTRLSIZE) << 2;
chip->bank_size_capture = snd_ymfpci_readl(chip, YDSXGR_RECCTRLSIZE) << 2;
chip->bank_size_effect = snd_ymfpci_readl(chip, YDSXGR_EFFCTRLSIZE) << 2;
chip->work_size = YDSXG_DEFAULT_WORK_SIZE;
size = ALIGN(playback_ctrl_size, 0x100) +
ALIGN(chip->bank_size_playback * 2 * YDSXG_PLAYBACK_VOICES, 0x100) +
ALIGN(chip->bank_size_capture * 2 * YDSXG_CAPTURE_VOICES, 0x100) +
ALIGN(chip->bank_size_effect * 2 * YDSXG_EFFECT_VOICES, 0x100) +
chip->work_size;
/* work_ptr must be aligned to 256 bytes, but it's already
covered with the kernel page allocation mechanism */
if (snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, snd_dma_pci_data(chip->pci),
size, &chip->work_ptr) < 0)
return -ENOMEM;
ptr = chip->work_ptr.area;
ptr_addr = chip->work_ptr.addr;
memset(ptr, 0, size); /* for sure */
chip->bank_base_playback = ptr;
chip->bank_base_playback_addr = ptr_addr;
chip->ctrl_playback = (u32 *)ptr;
chip->ctrl_playback[0] = cpu_to_le32(YDSXG_PLAYBACK_VOICES);
ptr += ALIGN(playback_ctrl_size, 0x100);
ptr_addr += ALIGN(playback_ctrl_size, 0x100);
for (voice = 0; voice < YDSXG_PLAYBACK_VOICES; voice++) {
chip->voices[voice].number = voice;
chip->voices[voice].bank = (struct snd_ymfpci_playback_bank *)ptr;
chip->voices[voice].bank_addr = ptr_addr;
for (bank = 0; bank < 2; bank++) {
chip->bank_playback[voice][bank] = (struct snd_ymfpci_playback_bank *)ptr;
ptr += chip->bank_size_playback;
ptr_addr += chip->bank_size_playback;
}
}
ptr = (char *)ALIGN((unsigned long)ptr, 0x100);
ptr_addr = ALIGN(ptr_addr, 0x100);
chip->bank_base_capture = ptr;
chip->bank_base_capture_addr = ptr_addr;
for (voice = 0; voice < YDSXG_CAPTURE_VOICES; voice++)
for (bank = 0; bank < 2; bank++) {
chip->bank_capture[voice][bank] = (struct snd_ymfpci_capture_bank *)ptr;
ptr += chip->bank_size_capture;
ptr_addr += chip->bank_size_capture;
}
ptr = (char *)ALIGN((unsigned long)ptr, 0x100);
ptr_addr = ALIGN(ptr_addr, 0x100);
chip->bank_base_effect = ptr;
chip->bank_base_effect_addr = ptr_addr;
for (voice = 0; voice < YDSXG_EFFECT_VOICES; voice++)
for (bank = 0; bank < 2; bank++) {
chip->bank_effect[voice][bank] = (struct snd_ymfpci_effect_bank *)ptr;
ptr += chip->bank_size_effect;
ptr_addr += chip->bank_size_effect;
}
ptr = (char *)ALIGN((unsigned long)ptr, 0x100);
ptr_addr = ALIGN(ptr_addr, 0x100);
chip->work_base = ptr;
chip->work_base_addr = ptr_addr;
snd_BUG_ON(ptr + chip->work_size !=
chip->work_ptr.area + chip->work_ptr.bytes);
snd_ymfpci_writel(chip, YDSXGR_PLAYCTRLBASE, chip->bank_base_playback_addr);
snd_ymfpci_writel(chip, YDSXGR_RECCTRLBASE, chip->bank_base_capture_addr);
snd_ymfpci_writel(chip, YDSXGR_EFFCTRLBASE, chip->bank_base_effect_addr);
snd_ymfpci_writel(chip, YDSXGR_WORKBASE, chip->work_base_addr);
snd_ymfpci_writel(chip, YDSXGR_WORKSIZE, chip->work_size >> 2);
/* S/PDIF output initialization */
chip->spdif_bits = chip->spdif_pcm_bits = SNDRV_PCM_DEFAULT_CON_SPDIF & 0xffff;
snd_ymfpci_writew(chip, YDSXGR_SPDIFOUTCTRL, 0);
snd_ymfpci_writew(chip, YDSXGR_SPDIFOUTSTATUS, chip->spdif_bits);
/* S/PDIF input initialization */
snd_ymfpci_writew(chip, YDSXGR_SPDIFINCTRL, 0);
/* digital mixer setup */
for (reg = 0x80; reg < 0xc0; reg += 4)
snd_ymfpci_writel(chip, reg, 0);
snd_ymfpci_writel(chip, YDSXGR_NATIVEDACOUTVOL, 0x3fff3fff);
snd_ymfpci_writel(chip, YDSXGR_BUF441OUTVOL, 0x3fff3fff);
snd_ymfpci_writel(chip, YDSXGR_ZVOUTVOL, 0x3fff3fff);
snd_ymfpci_writel(chip, YDSXGR_SPDIFOUTVOL, 0x3fff3fff);
snd_ymfpci_writel(chip, YDSXGR_NATIVEADCINVOL, 0x3fff3fff);
snd_ymfpci_writel(chip, YDSXGR_NATIVEDACINVOL, 0x3fff3fff);
snd_ymfpci_writel(chip, YDSXGR_PRIADCLOOPVOL, 0x3fff3fff);
snd_ymfpci_writel(chip, YDSXGR_LEGACYOUTVOL, 0x3fff3fff);
return 0;
}
static int snd_ymfpci_free(struct snd_ymfpci *chip)
{
u16 ctrl;
if (snd_BUG_ON(!chip))
return -EINVAL;
if (chip->res_reg_area) { /* don't touch busy hardware */
snd_ymfpci_writel(chip, YDSXGR_NATIVEDACOUTVOL, 0);
snd_ymfpci_writel(chip, YDSXGR_BUF441OUTVOL, 0);
snd_ymfpci_writel(chip, YDSXGR_LEGACYOUTVOL, 0);
snd_ymfpci_writel(chip, YDSXGR_STATUS, ~0);
snd_ymfpci_disable_dsp(chip);
snd_ymfpci_writel(chip, YDSXGR_PLAYCTRLBASE, 0);
snd_ymfpci_writel(chip, YDSXGR_RECCTRLBASE, 0);
snd_ymfpci_writel(chip, YDSXGR_EFFCTRLBASE, 0);
snd_ymfpci_writel(chip, YDSXGR_WORKBASE, 0);
snd_ymfpci_writel(chip, YDSXGR_WORKSIZE, 0);
ctrl = snd_ymfpci_readw(chip, YDSXGR_GLOBALCTRL);
snd_ymfpci_writew(chip, YDSXGR_GLOBALCTRL, ctrl & ~0x0007);
}
snd_ymfpci_ac3_done(chip);
/* Set PCI device to D3 state */
#if 0
/* FIXME: temporarily disabled, otherwise we cannot fire up
* the chip again unless reboot. ACPI bug?
*/
pci_set_power_state(chip->pci, 3);
#endif
#ifdef CONFIG_PM
vfree(chip->saved_regs);
#endif
if (chip->irq >= 0)
free_irq(chip->irq, chip);
release_and_free_resource(chip->mpu_res);
release_and_free_resource(chip->fm_res);
snd_ymfpci_free_gameport(chip);
if (chip->reg_area_virt)
iounmap(chip->reg_area_virt);
if (chip->work_ptr.area)
snd_dma_free_pages(&chip->work_ptr);
release_and_free_resource(chip->res_reg_area);
pci_write_config_word(chip->pci, 0x40, chip->old_legacy_ctrl);
pci_disable_device(chip->pci);
release_firmware(chip->dsp_microcode);
release_firmware(chip->controller_microcode);
kfree(chip);
return 0;
}
static int snd_ymfpci_dev_free(struct snd_device *device)
{
struct snd_ymfpci *chip = device->device_data;
return snd_ymfpci_free(chip);
}
#ifdef CONFIG_PM
static int saved_regs_index[] = {
/* spdif */
YDSXGR_SPDIFOUTCTRL,
YDSXGR_SPDIFOUTSTATUS,
YDSXGR_SPDIFINCTRL,
/* volumes */
YDSXGR_PRIADCLOOPVOL,
YDSXGR_NATIVEDACINVOL,
YDSXGR_NATIVEDACOUTVOL,
YDSXGR_BUF441OUTVOL,
YDSXGR_NATIVEADCINVOL,
YDSXGR_SPDIFLOOPVOL,
YDSXGR_SPDIFOUTVOL,
YDSXGR_ZVOUTVOL,
YDSXGR_LEGACYOUTVOL,
/* address bases */
YDSXGR_PLAYCTRLBASE,
YDSXGR_RECCTRLBASE,
YDSXGR_EFFCTRLBASE,
YDSXGR_WORKBASE,
/* capture set up */
YDSXGR_MAPOFREC,
YDSXGR_RECFORMAT,
YDSXGR_RECSLOTSR,
YDSXGR_ADCFORMAT,
YDSXGR_ADCSLOTSR,
};
#define YDSXGR_NUM_SAVED_REGS ARRAY_SIZE(saved_regs_index)
int snd_ymfpci_suspend(struct pci_dev *pci, pm_message_t state)
{
struct snd_card *card = pci_get_drvdata(pci);
struct snd_ymfpci *chip = card->private_data;
unsigned int i;
snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
snd_pcm_suspend_all(chip->pcm);
snd_pcm_suspend_all(chip->pcm2);
snd_pcm_suspend_all(chip->pcm_spdif);
snd_pcm_suspend_all(chip->pcm_4ch);
snd_ac97_suspend(chip->ac97);
for (i = 0; i < YDSXGR_NUM_SAVED_REGS; i++)
chip->saved_regs[i] = snd_ymfpci_readl(chip, saved_regs_index[i]);
chip->saved_ydsxgr_mode = snd_ymfpci_readl(chip, YDSXGR_MODE);
pci_read_config_word(chip->pci, PCIR_DSXG_LEGACY,
&chip->saved_dsxg_legacy);
pci_read_config_word(chip->pci, PCIR_DSXG_ELEGACY,
&chip->saved_dsxg_elegacy);
snd_ymfpci_writel(chip, YDSXGR_NATIVEDACOUTVOL, 0);
snd_ymfpci_writel(chip, YDSXGR_BUF441OUTVOL, 0);
snd_ymfpci_disable_dsp(chip);
pci_disable_device(pci);
pci_save_state(pci);
pci_set_power_state(pci, pci_choose_state(pci, state));
return 0;
}
int snd_ymfpci_resume(struct pci_dev *pci)
{
struct snd_card *card = pci_get_drvdata(pci);
struct snd_ymfpci *chip = card->private_data;
unsigned int i;
pci_set_power_state(pci, PCI_D0);
pci_restore_state(pci);
if (pci_enable_device(pci) < 0) {
printk(KERN_ERR "ymfpci: pci_enable_device failed, "
"disabling device\n");
snd_card_disconnect(card);
return -EIO;
}
pci_set_master(pci);
snd_ymfpci_aclink_reset(pci);
snd_ymfpci_codec_ready(chip, 0);
snd_ymfpci_download_image(chip);
udelay(100);
for (i = 0; i < YDSXGR_NUM_SAVED_REGS; i++)
snd_ymfpci_writel(chip, saved_regs_index[i], chip->saved_regs[i]);
snd_ac97_resume(chip->ac97);
pci_write_config_word(chip->pci, PCIR_DSXG_LEGACY,
chip->saved_dsxg_legacy);
pci_write_config_word(chip->pci, PCIR_DSXG_ELEGACY,
chip->saved_dsxg_elegacy);
/* start hw again */
if (chip->start_count > 0) {
spin_lock_irq(&chip->reg_lock);
snd_ymfpci_writel(chip, YDSXGR_MODE, chip->saved_ydsxgr_mode);
chip->active_bank = snd_ymfpci_readl(chip, YDSXGR_CTRLSELECT);
spin_unlock_irq(&chip->reg_lock);
}
snd_power_change_state(card, SNDRV_CTL_POWER_D0);
return 0;
}
#endif /* CONFIG_PM */
int __devinit snd_ymfpci_create(struct snd_card *card,
struct pci_dev * pci,
unsigned short old_legacy_ctrl,
struct snd_ymfpci ** rchip)
{
struct snd_ymfpci *chip;
int err;
static struct snd_device_ops ops = {
.dev_free = snd_ymfpci_dev_free,
};
*rchip = NULL;
/* enable PCI device */
if ((err = pci_enable_device(pci)) < 0)
return err;
chip = kzalloc(sizeof(*chip), GFP_KERNEL);
if (chip == NULL) {
pci_disable_device(pci);
return -ENOMEM;
}
chip->old_legacy_ctrl = old_legacy_ctrl;
spin_lock_init(&chip->reg_lock);
spin_lock_init(&chip->voice_lock);
init_waitqueue_head(&chip->interrupt_sleep);
atomic_set(&chip->interrupt_sleep_count, 0);
chip->card = card;
chip->pci = pci;
chip->irq = -1;
chip->device_id = pci->device;
chip->rev = pci->revision;
chip->reg_area_phys = pci_resource_start(pci, 0);
chip->reg_area_virt = ioremap_nocache(chip->reg_area_phys, 0x8000);
pci_set_master(pci);
chip->src441_used = -1;
if ((chip->res_reg_area = request_mem_region(chip->reg_area_phys, 0x8000, "YMFPCI")) == NULL) {
snd_printk(KERN_ERR "unable to grab memory region 0x%lx-0x%lx\n", chip->reg_area_phys, chip->reg_area_phys + 0x8000 - 1);
snd_ymfpci_free(chip);
return -EBUSY;
}
if (request_irq(pci->irq, snd_ymfpci_interrupt, IRQF_SHARED,
KBUILD_MODNAME, chip)) {
snd_printk(KERN_ERR "unable to grab IRQ %d\n", pci->irq);
snd_ymfpci_free(chip);
return -EBUSY;
}
chip->irq = pci->irq;
snd_ymfpci_aclink_reset(pci);
if (snd_ymfpci_codec_ready(chip, 0) < 0) {
snd_ymfpci_free(chip);
return -EIO;
}
err = snd_ymfpci_request_firmware(chip);
if (err < 0) {
snd_printk(KERN_ERR "firmware request failed: %d\n", err);
snd_ymfpci_free(chip);
return err;
}
snd_ymfpci_download_image(chip);
udelay(100); /* seems we need a delay after downloading image.. */
if (snd_ymfpci_memalloc(chip) < 0) {
snd_ymfpci_free(chip);
return -EIO;
}
if ((err = snd_ymfpci_ac3_init(chip)) < 0) {
snd_ymfpci_free(chip);
return err;
}
#ifdef CONFIG_PM
chip->saved_regs = vmalloc(YDSXGR_NUM_SAVED_REGS * sizeof(u32));
if (chip->saved_regs == NULL) {
snd_ymfpci_free(chip);
return -ENOMEM;
}
#endif
if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops)) < 0) {
snd_ymfpci_free(chip);
return err;
}
snd_ymfpci_proc_init(card, chip);
snd_card_set_dev(card, &pci->dev);
*rchip = chip;
return 0;
}
| gpl-2.0 |
CyanogenMod/android_kernel_samsung_d2 | sound/pci/ymfpci/ymfpci_main.c | 4855 | 73287 | /*
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
* Routines for control of YMF724/740/744/754 chips
*
* 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/delay.h>
#include <linux/firmware.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/pci.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/mutex.h>
#include <linux/module.h>
#include <sound/core.h>
#include <sound/control.h>
#include <sound/info.h>
#include <sound/tlv.h>
#include <sound/ymfpci.h>
#include <sound/asoundef.h>
#include <sound/mpu401.h>
#include <asm/io.h>
#include <asm/byteorder.h>
/*
* common I/O routines
*/
static void snd_ymfpci_irq_wait(struct snd_ymfpci *chip);
static inline u8 snd_ymfpci_readb(struct snd_ymfpci *chip, u32 offset)
{
return readb(chip->reg_area_virt + offset);
}
static inline void snd_ymfpci_writeb(struct snd_ymfpci *chip, u32 offset, u8 val)
{
writeb(val, chip->reg_area_virt + offset);
}
static inline u16 snd_ymfpci_readw(struct snd_ymfpci *chip, u32 offset)
{
return readw(chip->reg_area_virt + offset);
}
static inline void snd_ymfpci_writew(struct snd_ymfpci *chip, u32 offset, u16 val)
{
writew(val, chip->reg_area_virt + offset);
}
static inline u32 snd_ymfpci_readl(struct snd_ymfpci *chip, u32 offset)
{
return readl(chip->reg_area_virt + offset);
}
static inline void snd_ymfpci_writel(struct snd_ymfpci *chip, u32 offset, u32 val)
{
writel(val, chip->reg_area_virt + offset);
}
static int snd_ymfpci_codec_ready(struct snd_ymfpci *chip, int secondary)
{
unsigned long end_time;
u32 reg = secondary ? YDSXGR_SECSTATUSADR : YDSXGR_PRISTATUSADR;
end_time = jiffies + msecs_to_jiffies(750);
do {
if ((snd_ymfpci_readw(chip, reg) & 0x8000) == 0)
return 0;
schedule_timeout_uninterruptible(1);
} while (time_before(jiffies, end_time));
snd_printk(KERN_ERR "codec_ready: codec %i is not ready [0x%x]\n", secondary, snd_ymfpci_readw(chip, reg));
return -EBUSY;
}
static void snd_ymfpci_codec_write(struct snd_ac97 *ac97, u16 reg, u16 val)
{
struct snd_ymfpci *chip = ac97->private_data;
u32 cmd;
snd_ymfpci_codec_ready(chip, 0);
cmd = ((YDSXG_AC97WRITECMD | reg) << 16) | val;
snd_ymfpci_writel(chip, YDSXGR_AC97CMDDATA, cmd);
}
static u16 snd_ymfpci_codec_read(struct snd_ac97 *ac97, u16 reg)
{
struct snd_ymfpci *chip = ac97->private_data;
if (snd_ymfpci_codec_ready(chip, 0))
return ~0;
snd_ymfpci_writew(chip, YDSXGR_AC97CMDADR, YDSXG_AC97READCMD | reg);
if (snd_ymfpci_codec_ready(chip, 0))
return ~0;
if (chip->device_id == PCI_DEVICE_ID_YAMAHA_744 && chip->rev < 2) {
int i;
for (i = 0; i < 600; i++)
snd_ymfpci_readw(chip, YDSXGR_PRISTATUSDATA);
}
return snd_ymfpci_readw(chip, YDSXGR_PRISTATUSDATA);
}
/*
* Misc routines
*/
static u32 snd_ymfpci_calc_delta(u32 rate)
{
switch (rate) {
case 8000: return 0x02aaab00;
case 11025: return 0x03accd00;
case 16000: return 0x05555500;
case 22050: return 0x07599a00;
case 32000: return 0x0aaaab00;
case 44100: return 0x0eb33300;
default: return ((rate << 16) / 375) << 5;
}
}
static u32 def_rate[8] = {
100, 2000, 8000, 11025, 16000, 22050, 32000, 48000
};
static u32 snd_ymfpci_calc_lpfK(u32 rate)
{
u32 i;
static u32 val[8] = {
0x00570000, 0x06AA0000, 0x18B20000, 0x20930000,
0x2B9A0000, 0x35A10000, 0x3EAA0000, 0x40000000
};
if (rate == 44100)
return 0x40000000; /* FIXME: What's the right value? */
for (i = 0; i < 8; i++)
if (rate <= def_rate[i])
return val[i];
return val[0];
}
static u32 snd_ymfpci_calc_lpfQ(u32 rate)
{
u32 i;
static u32 val[8] = {
0x35280000, 0x34A70000, 0x32020000, 0x31770000,
0x31390000, 0x31C90000, 0x33D00000, 0x40000000
};
if (rate == 44100)
return 0x370A0000;
for (i = 0; i < 8; i++)
if (rate <= def_rate[i])
return val[i];
return val[0];
}
/*
* Hardware start management
*/
static void snd_ymfpci_hw_start(struct snd_ymfpci *chip)
{
unsigned long flags;
spin_lock_irqsave(&chip->reg_lock, flags);
if (chip->start_count++ > 0)
goto __end;
snd_ymfpci_writel(chip, YDSXGR_MODE,
snd_ymfpci_readl(chip, YDSXGR_MODE) | 3);
chip->active_bank = snd_ymfpci_readl(chip, YDSXGR_CTRLSELECT) & 1;
__end:
spin_unlock_irqrestore(&chip->reg_lock, flags);
}
static void snd_ymfpci_hw_stop(struct snd_ymfpci *chip)
{
unsigned long flags;
long timeout = 1000;
spin_lock_irqsave(&chip->reg_lock, flags);
if (--chip->start_count > 0)
goto __end;
snd_ymfpci_writel(chip, YDSXGR_MODE,
snd_ymfpci_readl(chip, YDSXGR_MODE) & ~3);
while (timeout-- > 0) {
if ((snd_ymfpci_readl(chip, YDSXGR_STATUS) & 2) == 0)
break;
}
if (atomic_read(&chip->interrupt_sleep_count)) {
atomic_set(&chip->interrupt_sleep_count, 0);
wake_up(&chip->interrupt_sleep);
}
__end:
spin_unlock_irqrestore(&chip->reg_lock, flags);
}
/*
* Playback voice management
*/
static int voice_alloc(struct snd_ymfpci *chip,
enum snd_ymfpci_voice_type type, int pair,
struct snd_ymfpci_voice **rvoice)
{
struct snd_ymfpci_voice *voice, *voice2;
int idx;
*rvoice = NULL;
for (idx = 0; idx < YDSXG_PLAYBACK_VOICES; idx += pair ? 2 : 1) {
voice = &chip->voices[idx];
voice2 = pair ? &chip->voices[idx+1] : NULL;
if (voice->use || (voice2 && voice2->use))
continue;
voice->use = 1;
if (voice2)
voice2->use = 1;
switch (type) {
case YMFPCI_PCM:
voice->pcm = 1;
if (voice2)
voice2->pcm = 1;
break;
case YMFPCI_SYNTH:
voice->synth = 1;
break;
case YMFPCI_MIDI:
voice->midi = 1;
break;
}
snd_ymfpci_hw_start(chip);
if (voice2)
snd_ymfpci_hw_start(chip);
*rvoice = voice;
return 0;
}
return -ENOMEM;
}
static int snd_ymfpci_voice_alloc(struct snd_ymfpci *chip,
enum snd_ymfpci_voice_type type, int pair,
struct snd_ymfpci_voice **rvoice)
{
unsigned long flags;
int result;
if (snd_BUG_ON(!rvoice))
return -EINVAL;
if (snd_BUG_ON(pair && type != YMFPCI_PCM))
return -EINVAL;
spin_lock_irqsave(&chip->voice_lock, flags);
for (;;) {
result = voice_alloc(chip, type, pair, rvoice);
if (result == 0 || type != YMFPCI_PCM)
break;
/* TODO: synth/midi voice deallocation */
break;
}
spin_unlock_irqrestore(&chip->voice_lock, flags);
return result;
}
static int snd_ymfpci_voice_free(struct snd_ymfpci *chip, struct snd_ymfpci_voice *pvoice)
{
unsigned long flags;
if (snd_BUG_ON(!pvoice))
return -EINVAL;
snd_ymfpci_hw_stop(chip);
spin_lock_irqsave(&chip->voice_lock, flags);
if (pvoice->number == chip->src441_used) {
chip->src441_used = -1;
pvoice->ypcm->use_441_slot = 0;
}
pvoice->use = pvoice->pcm = pvoice->synth = pvoice->midi = 0;
pvoice->ypcm = NULL;
pvoice->interrupt = NULL;
spin_unlock_irqrestore(&chip->voice_lock, flags);
return 0;
}
/*
* PCM part
*/
static void snd_ymfpci_pcm_interrupt(struct snd_ymfpci *chip, struct snd_ymfpci_voice *voice)
{
struct snd_ymfpci_pcm *ypcm;
u32 pos, delta;
if ((ypcm = voice->ypcm) == NULL)
return;
if (ypcm->substream == NULL)
return;
spin_lock(&chip->reg_lock);
if (ypcm->running) {
pos = le32_to_cpu(voice->bank[chip->active_bank].start);
if (pos < ypcm->last_pos)
delta = pos + (ypcm->buffer_size - ypcm->last_pos);
else
delta = pos - ypcm->last_pos;
ypcm->period_pos += delta;
ypcm->last_pos = pos;
if (ypcm->period_pos >= ypcm->period_size) {
/*
printk(KERN_DEBUG
"done - active_bank = 0x%x, start = 0x%x\n",
chip->active_bank,
voice->bank[chip->active_bank].start);
*/
ypcm->period_pos %= ypcm->period_size;
spin_unlock(&chip->reg_lock);
snd_pcm_period_elapsed(ypcm->substream);
spin_lock(&chip->reg_lock);
}
if (unlikely(ypcm->update_pcm_vol)) {
unsigned int subs = ypcm->substream->number;
unsigned int next_bank = 1 - chip->active_bank;
struct snd_ymfpci_playback_bank *bank;
u32 volume;
bank = &voice->bank[next_bank];
volume = cpu_to_le32(chip->pcm_mixer[subs].left << 15);
bank->left_gain_end = volume;
if (ypcm->output_rear)
bank->eff2_gain_end = volume;
if (ypcm->voices[1])
bank = &ypcm->voices[1]->bank[next_bank];
volume = cpu_to_le32(chip->pcm_mixer[subs].right << 15);
bank->right_gain_end = volume;
if (ypcm->output_rear)
bank->eff3_gain_end = volume;
ypcm->update_pcm_vol--;
}
}
spin_unlock(&chip->reg_lock);
}
static void snd_ymfpci_pcm_capture_interrupt(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm = runtime->private_data;
struct snd_ymfpci *chip = ypcm->chip;
u32 pos, delta;
spin_lock(&chip->reg_lock);
if (ypcm->running) {
pos = le32_to_cpu(chip->bank_capture[ypcm->capture_bank_number][chip->active_bank]->start) >> ypcm->shift;
if (pos < ypcm->last_pos)
delta = pos + (ypcm->buffer_size - ypcm->last_pos);
else
delta = pos - ypcm->last_pos;
ypcm->period_pos += delta;
ypcm->last_pos = pos;
if (ypcm->period_pos >= ypcm->period_size) {
ypcm->period_pos %= ypcm->period_size;
/*
printk(KERN_DEBUG
"done - active_bank = 0x%x, start = 0x%x\n",
chip->active_bank,
voice->bank[chip->active_bank].start);
*/
spin_unlock(&chip->reg_lock);
snd_pcm_period_elapsed(substream);
spin_lock(&chip->reg_lock);
}
}
spin_unlock(&chip->reg_lock);
}
static int snd_ymfpci_playback_trigger(struct snd_pcm_substream *substream,
int cmd)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_ymfpci_pcm *ypcm = substream->runtime->private_data;
struct snd_kcontrol *kctl = NULL;
int result = 0;
spin_lock(&chip->reg_lock);
if (ypcm->voices[0] == NULL) {
result = -EINVAL;
goto __unlock;
}
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
case SNDRV_PCM_TRIGGER_RESUME:
chip->ctrl_playback[ypcm->voices[0]->number + 1] = cpu_to_le32(ypcm->voices[0]->bank_addr);
if (ypcm->voices[1] != NULL && !ypcm->use_441_slot)
chip->ctrl_playback[ypcm->voices[1]->number + 1] = cpu_to_le32(ypcm->voices[1]->bank_addr);
ypcm->running = 1;
break;
case SNDRV_PCM_TRIGGER_STOP:
if (substream->pcm == chip->pcm && !ypcm->use_441_slot) {
kctl = chip->pcm_mixer[substream->number].ctl;
kctl->vd[0].access |= SNDRV_CTL_ELEM_ACCESS_INACTIVE;
}
/* fall through */
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
case SNDRV_PCM_TRIGGER_SUSPEND:
chip->ctrl_playback[ypcm->voices[0]->number + 1] = 0;
if (ypcm->voices[1] != NULL && !ypcm->use_441_slot)
chip->ctrl_playback[ypcm->voices[1]->number + 1] = 0;
ypcm->running = 0;
break;
default:
result = -EINVAL;
break;
}
__unlock:
spin_unlock(&chip->reg_lock);
if (kctl)
snd_ctl_notify(chip->card, SNDRV_CTL_EVENT_MASK_INFO, &kctl->id);
return result;
}
static int snd_ymfpci_capture_trigger(struct snd_pcm_substream *substream,
int cmd)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_ymfpci_pcm *ypcm = substream->runtime->private_data;
int result = 0;
u32 tmp;
spin_lock(&chip->reg_lock);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
case SNDRV_PCM_TRIGGER_RESUME:
tmp = snd_ymfpci_readl(chip, YDSXGR_MAPOFREC) | (1 << ypcm->capture_bank_number);
snd_ymfpci_writel(chip, YDSXGR_MAPOFREC, tmp);
ypcm->running = 1;
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
case SNDRV_PCM_TRIGGER_SUSPEND:
tmp = snd_ymfpci_readl(chip, YDSXGR_MAPOFREC) & ~(1 << ypcm->capture_bank_number);
snd_ymfpci_writel(chip, YDSXGR_MAPOFREC, tmp);
ypcm->running = 0;
break;
default:
result = -EINVAL;
break;
}
spin_unlock(&chip->reg_lock);
return result;
}
static int snd_ymfpci_pcm_voice_alloc(struct snd_ymfpci_pcm *ypcm, int voices)
{
int err;
if (ypcm->voices[1] != NULL && voices < 2) {
snd_ymfpci_voice_free(ypcm->chip, ypcm->voices[1]);
ypcm->voices[1] = NULL;
}
if (voices == 1 && ypcm->voices[0] != NULL)
return 0; /* already allocated */
if (voices == 2 && ypcm->voices[0] != NULL && ypcm->voices[1] != NULL)
return 0; /* already allocated */
if (voices > 1) {
if (ypcm->voices[0] != NULL && ypcm->voices[1] == NULL) {
snd_ymfpci_voice_free(ypcm->chip, ypcm->voices[0]);
ypcm->voices[0] = NULL;
}
}
err = snd_ymfpci_voice_alloc(ypcm->chip, YMFPCI_PCM, voices > 1, &ypcm->voices[0]);
if (err < 0)
return err;
ypcm->voices[0]->ypcm = ypcm;
ypcm->voices[0]->interrupt = snd_ymfpci_pcm_interrupt;
if (voices > 1) {
ypcm->voices[1] = &ypcm->chip->voices[ypcm->voices[0]->number + 1];
ypcm->voices[1]->ypcm = ypcm;
}
return 0;
}
static void snd_ymfpci_pcm_init_voice(struct snd_ymfpci_pcm *ypcm, unsigned int voiceidx,
struct snd_pcm_runtime *runtime,
int has_pcm_volume)
{
struct snd_ymfpci_voice *voice = ypcm->voices[voiceidx];
u32 format;
u32 delta = snd_ymfpci_calc_delta(runtime->rate);
u32 lpfQ = snd_ymfpci_calc_lpfQ(runtime->rate);
u32 lpfK = snd_ymfpci_calc_lpfK(runtime->rate);
struct snd_ymfpci_playback_bank *bank;
unsigned int nbank;
u32 vol_left, vol_right;
u8 use_left, use_right;
unsigned long flags;
if (snd_BUG_ON(!voice))
return;
if (runtime->channels == 1) {
use_left = 1;
use_right = 1;
} else {
use_left = (voiceidx & 1) == 0;
use_right = !use_left;
}
if (has_pcm_volume) {
vol_left = cpu_to_le32(ypcm->chip->pcm_mixer
[ypcm->substream->number].left << 15);
vol_right = cpu_to_le32(ypcm->chip->pcm_mixer
[ypcm->substream->number].right << 15);
} else {
vol_left = cpu_to_le32(0x40000000);
vol_right = cpu_to_le32(0x40000000);
}
spin_lock_irqsave(&ypcm->chip->voice_lock, flags);
format = runtime->channels == 2 ? 0x00010000 : 0;
if (snd_pcm_format_width(runtime->format) == 8)
format |= 0x80000000;
else if (ypcm->chip->device_id == PCI_DEVICE_ID_YAMAHA_754 &&
runtime->rate == 44100 && runtime->channels == 2 &&
voiceidx == 0 && (ypcm->chip->src441_used == -1 ||
ypcm->chip->src441_used == voice->number)) {
ypcm->chip->src441_used = voice->number;
ypcm->use_441_slot = 1;
format |= 0x10000000;
}
if (ypcm->chip->src441_used == voice->number &&
(format & 0x10000000) == 0) {
ypcm->chip->src441_used = -1;
ypcm->use_441_slot = 0;
}
if (runtime->channels == 2 && (voiceidx & 1) != 0)
format |= 1;
spin_unlock_irqrestore(&ypcm->chip->voice_lock, flags);
for (nbank = 0; nbank < 2; nbank++) {
bank = &voice->bank[nbank];
memset(bank, 0, sizeof(*bank));
bank->format = cpu_to_le32(format);
bank->base = cpu_to_le32(runtime->dma_addr);
bank->loop_end = cpu_to_le32(ypcm->buffer_size);
bank->lpfQ = cpu_to_le32(lpfQ);
bank->delta =
bank->delta_end = cpu_to_le32(delta);
bank->lpfK =
bank->lpfK_end = cpu_to_le32(lpfK);
bank->eg_gain =
bank->eg_gain_end = cpu_to_le32(0x40000000);
if (ypcm->output_front) {
if (use_left) {
bank->left_gain =
bank->left_gain_end = vol_left;
}
if (use_right) {
bank->right_gain =
bank->right_gain_end = vol_right;
}
}
if (ypcm->output_rear) {
if (!ypcm->swap_rear) {
if (use_left) {
bank->eff2_gain =
bank->eff2_gain_end = vol_left;
}
if (use_right) {
bank->eff3_gain =
bank->eff3_gain_end = vol_right;
}
} else {
/* The SPDIF out channels seem to be swapped, so we have
* to swap them here, too. The rear analog out channels
* will be wrong, but otherwise AC3 would not work.
*/
if (use_left) {
bank->eff3_gain =
bank->eff3_gain_end = vol_left;
}
if (use_right) {
bank->eff2_gain =
bank->eff2_gain_end = vol_right;
}
}
}
}
}
static int __devinit snd_ymfpci_ac3_init(struct snd_ymfpci *chip)
{
if (snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, snd_dma_pci_data(chip->pci),
4096, &chip->ac3_tmp_base) < 0)
return -ENOMEM;
chip->bank_effect[3][0]->base =
chip->bank_effect[3][1]->base = cpu_to_le32(chip->ac3_tmp_base.addr);
chip->bank_effect[3][0]->loop_end =
chip->bank_effect[3][1]->loop_end = cpu_to_le32(1024);
chip->bank_effect[4][0]->base =
chip->bank_effect[4][1]->base = cpu_to_le32(chip->ac3_tmp_base.addr + 2048);
chip->bank_effect[4][0]->loop_end =
chip->bank_effect[4][1]->loop_end = cpu_to_le32(1024);
spin_lock_irq(&chip->reg_lock);
snd_ymfpci_writel(chip, YDSXGR_MAPOFEFFECT,
snd_ymfpci_readl(chip, YDSXGR_MAPOFEFFECT) | 3 << 3);
spin_unlock_irq(&chip->reg_lock);
return 0;
}
static int snd_ymfpci_ac3_done(struct snd_ymfpci *chip)
{
spin_lock_irq(&chip->reg_lock);
snd_ymfpci_writel(chip, YDSXGR_MAPOFEFFECT,
snd_ymfpci_readl(chip, YDSXGR_MAPOFEFFECT) & ~(3 << 3));
spin_unlock_irq(&chip->reg_lock);
// snd_ymfpci_irq_wait(chip);
if (chip->ac3_tmp_base.area) {
snd_dma_free_pages(&chip->ac3_tmp_base);
chip->ac3_tmp_base.area = NULL;
}
return 0;
}
static int snd_ymfpci_playback_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm = runtime->private_data;
int err;
if ((err = snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params))) < 0)
return err;
if ((err = snd_ymfpci_pcm_voice_alloc(ypcm, params_channels(hw_params))) < 0)
return err;
return 0;
}
static int snd_ymfpci_playback_hw_free(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm;
if (runtime->private_data == NULL)
return 0;
ypcm = runtime->private_data;
/* wait, until the PCI operations are not finished */
snd_ymfpci_irq_wait(chip);
snd_pcm_lib_free_pages(substream);
if (ypcm->voices[1]) {
snd_ymfpci_voice_free(chip, ypcm->voices[1]);
ypcm->voices[1] = NULL;
}
if (ypcm->voices[0]) {
snd_ymfpci_voice_free(chip, ypcm->voices[0]);
ypcm->voices[0] = NULL;
}
return 0;
}
static int snd_ymfpci_playback_prepare(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm = runtime->private_data;
struct snd_kcontrol *kctl;
unsigned int nvoice;
ypcm->period_size = runtime->period_size;
ypcm->buffer_size = runtime->buffer_size;
ypcm->period_pos = 0;
ypcm->last_pos = 0;
for (nvoice = 0; nvoice < runtime->channels; nvoice++)
snd_ymfpci_pcm_init_voice(ypcm, nvoice, runtime,
substream->pcm == chip->pcm);
if (substream->pcm == chip->pcm && !ypcm->use_441_slot) {
kctl = chip->pcm_mixer[substream->number].ctl;
kctl->vd[0].access &= ~SNDRV_CTL_ELEM_ACCESS_INACTIVE;
snd_ctl_notify(chip->card, SNDRV_CTL_EVENT_MASK_INFO, &kctl->id);
}
return 0;
}
static int snd_ymfpci_capture_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
return snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params));
}
static int snd_ymfpci_capture_hw_free(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
/* wait, until the PCI operations are not finished */
snd_ymfpci_irq_wait(chip);
return snd_pcm_lib_free_pages(substream);
}
static int snd_ymfpci_capture_prepare(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm = runtime->private_data;
struct snd_ymfpci_capture_bank * bank;
int nbank;
u32 rate, format;
ypcm->period_size = runtime->period_size;
ypcm->buffer_size = runtime->buffer_size;
ypcm->period_pos = 0;
ypcm->last_pos = 0;
ypcm->shift = 0;
rate = ((48000 * 4096) / runtime->rate) - 1;
format = 0;
if (runtime->channels == 2) {
format |= 2;
ypcm->shift++;
}
if (snd_pcm_format_width(runtime->format) == 8)
format |= 1;
else
ypcm->shift++;
switch (ypcm->capture_bank_number) {
case 0:
snd_ymfpci_writel(chip, YDSXGR_RECFORMAT, format);
snd_ymfpci_writel(chip, YDSXGR_RECSLOTSR, rate);
break;
case 1:
snd_ymfpci_writel(chip, YDSXGR_ADCFORMAT, format);
snd_ymfpci_writel(chip, YDSXGR_ADCSLOTSR, rate);
break;
}
for (nbank = 0; nbank < 2; nbank++) {
bank = chip->bank_capture[ypcm->capture_bank_number][nbank];
bank->base = cpu_to_le32(runtime->dma_addr);
bank->loop_end = cpu_to_le32(ypcm->buffer_size << ypcm->shift);
bank->start = 0;
bank->num_of_loops = 0;
}
return 0;
}
static snd_pcm_uframes_t snd_ymfpci_playback_pointer(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm = runtime->private_data;
struct snd_ymfpci_voice *voice = ypcm->voices[0];
if (!(ypcm->running && voice))
return 0;
return le32_to_cpu(voice->bank[chip->active_bank].start);
}
static snd_pcm_uframes_t snd_ymfpci_capture_pointer(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm = runtime->private_data;
if (!ypcm->running)
return 0;
return le32_to_cpu(chip->bank_capture[ypcm->capture_bank_number][chip->active_bank]->start) >> ypcm->shift;
}
static void snd_ymfpci_irq_wait(struct snd_ymfpci *chip)
{
wait_queue_t wait;
int loops = 4;
while (loops-- > 0) {
if ((snd_ymfpci_readl(chip, YDSXGR_MODE) & 3) == 0)
continue;
init_waitqueue_entry(&wait, current);
add_wait_queue(&chip->interrupt_sleep, &wait);
atomic_inc(&chip->interrupt_sleep_count);
schedule_timeout_uninterruptible(msecs_to_jiffies(50));
remove_wait_queue(&chip->interrupt_sleep, &wait);
}
}
static irqreturn_t snd_ymfpci_interrupt(int irq, void *dev_id)
{
struct snd_ymfpci *chip = dev_id;
u32 status, nvoice, mode;
struct snd_ymfpci_voice *voice;
status = snd_ymfpci_readl(chip, YDSXGR_STATUS);
if (status & 0x80000000) {
chip->active_bank = snd_ymfpci_readl(chip, YDSXGR_CTRLSELECT) & 1;
spin_lock(&chip->voice_lock);
for (nvoice = 0; nvoice < YDSXG_PLAYBACK_VOICES; nvoice++) {
voice = &chip->voices[nvoice];
if (voice->interrupt)
voice->interrupt(chip, voice);
}
for (nvoice = 0; nvoice < YDSXG_CAPTURE_VOICES; nvoice++) {
if (chip->capture_substream[nvoice])
snd_ymfpci_pcm_capture_interrupt(chip->capture_substream[nvoice]);
}
#if 0
for (nvoice = 0; nvoice < YDSXG_EFFECT_VOICES; nvoice++) {
if (chip->effect_substream[nvoice])
snd_ymfpci_pcm_effect_interrupt(chip->effect_substream[nvoice]);
}
#endif
spin_unlock(&chip->voice_lock);
spin_lock(&chip->reg_lock);
snd_ymfpci_writel(chip, YDSXGR_STATUS, 0x80000000);
mode = snd_ymfpci_readl(chip, YDSXGR_MODE) | 2;
snd_ymfpci_writel(chip, YDSXGR_MODE, mode);
spin_unlock(&chip->reg_lock);
if (atomic_read(&chip->interrupt_sleep_count)) {
atomic_set(&chip->interrupt_sleep_count, 0);
wake_up(&chip->interrupt_sleep);
}
}
status = snd_ymfpci_readw(chip, YDSXGR_INTFLAG);
if (status & 1) {
if (chip->timer)
snd_timer_interrupt(chip->timer, chip->timer_ticks);
}
snd_ymfpci_writew(chip, YDSXGR_INTFLAG, status);
if (chip->rawmidi)
snd_mpu401_uart_interrupt(irq, chip->rawmidi->private_data);
return IRQ_HANDLED;
}
static struct snd_pcm_hardware snd_ymfpci_playback =
{
.info = (SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_PAUSE |
SNDRV_PCM_INFO_RESUME),
.formats = SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_48000,
.rate_min = 8000,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = 256 * 1024, /* FIXME: enough? */
.period_bytes_min = 64,
.period_bytes_max = 256 * 1024, /* FIXME: enough? */
.periods_min = 3,
.periods_max = 1024,
.fifo_size = 0,
};
static struct snd_pcm_hardware snd_ymfpci_capture =
{
.info = (SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_PAUSE |
SNDRV_PCM_INFO_RESUME),
.formats = SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_48000,
.rate_min = 8000,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = 256 * 1024, /* FIXME: enough? */
.period_bytes_min = 64,
.period_bytes_max = 256 * 1024, /* FIXME: enough? */
.periods_min = 3,
.periods_max = 1024,
.fifo_size = 0,
};
static void snd_ymfpci_pcm_free_substream(struct snd_pcm_runtime *runtime)
{
kfree(runtime->private_data);
}
static int snd_ymfpci_playback_open_1(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm;
int err;
runtime->hw = snd_ymfpci_playback;
/* FIXME? True value is 256/48 = 5.33333 ms */
err = snd_pcm_hw_constraint_minmax(runtime,
SNDRV_PCM_HW_PARAM_PERIOD_TIME,
5334, UINT_MAX);
if (err < 0)
return err;
err = snd_pcm_hw_rule_noresample(runtime, 48000);
if (err < 0)
return err;
ypcm = kzalloc(sizeof(*ypcm), GFP_KERNEL);
if (ypcm == NULL)
return -ENOMEM;
ypcm->chip = chip;
ypcm->type = PLAYBACK_VOICE;
ypcm->substream = substream;
runtime->private_data = ypcm;
runtime->private_free = snd_ymfpci_pcm_free_substream;
return 0;
}
/* call with spinlock held */
static void ymfpci_open_extension(struct snd_ymfpci *chip)
{
if (! chip->rear_opened) {
if (! chip->spdif_opened) /* set AC3 */
snd_ymfpci_writel(chip, YDSXGR_MODE,
snd_ymfpci_readl(chip, YDSXGR_MODE) | (1 << 30));
/* enable second codec (4CHEN) */
snd_ymfpci_writew(chip, YDSXGR_SECCONFIG,
(snd_ymfpci_readw(chip, YDSXGR_SECCONFIG) & ~0x0330) | 0x0010);
}
}
/* call with spinlock held */
static void ymfpci_close_extension(struct snd_ymfpci *chip)
{
if (! chip->rear_opened) {
if (! chip->spdif_opened)
snd_ymfpci_writel(chip, YDSXGR_MODE,
snd_ymfpci_readl(chip, YDSXGR_MODE) & ~(1 << 30));
snd_ymfpci_writew(chip, YDSXGR_SECCONFIG,
(snd_ymfpci_readw(chip, YDSXGR_SECCONFIG) & ~0x0330) & ~0x0010);
}
}
static int snd_ymfpci_playback_open(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm;
int err;
if ((err = snd_ymfpci_playback_open_1(substream)) < 0)
return err;
ypcm = runtime->private_data;
ypcm->output_front = 1;
ypcm->output_rear = chip->mode_dup4ch ? 1 : 0;
ypcm->swap_rear = 0;
spin_lock_irq(&chip->reg_lock);
if (ypcm->output_rear) {
ymfpci_open_extension(chip);
chip->rear_opened++;
}
spin_unlock_irq(&chip->reg_lock);
return 0;
}
static int snd_ymfpci_playback_spdif_open(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm;
int err;
if ((err = snd_ymfpci_playback_open_1(substream)) < 0)
return err;
ypcm = runtime->private_data;
ypcm->output_front = 0;
ypcm->output_rear = 1;
ypcm->swap_rear = 1;
spin_lock_irq(&chip->reg_lock);
snd_ymfpci_writew(chip, YDSXGR_SPDIFOUTCTRL,
snd_ymfpci_readw(chip, YDSXGR_SPDIFOUTCTRL) | 2);
ymfpci_open_extension(chip);
chip->spdif_pcm_bits = chip->spdif_bits;
snd_ymfpci_writew(chip, YDSXGR_SPDIFOUTSTATUS, chip->spdif_pcm_bits);
chip->spdif_opened++;
spin_unlock_irq(&chip->reg_lock);
chip->spdif_pcm_ctl->vd[0].access &= ~SNDRV_CTL_ELEM_ACCESS_INACTIVE;
snd_ctl_notify(chip->card, SNDRV_CTL_EVENT_MASK_VALUE |
SNDRV_CTL_EVENT_MASK_INFO, &chip->spdif_pcm_ctl->id);
return 0;
}
static int snd_ymfpci_playback_4ch_open(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm;
int err;
if ((err = snd_ymfpci_playback_open_1(substream)) < 0)
return err;
ypcm = runtime->private_data;
ypcm->output_front = 0;
ypcm->output_rear = 1;
ypcm->swap_rear = 0;
spin_lock_irq(&chip->reg_lock);
ymfpci_open_extension(chip);
chip->rear_opened++;
spin_unlock_irq(&chip->reg_lock);
return 0;
}
static int snd_ymfpci_capture_open(struct snd_pcm_substream *substream,
u32 capture_bank_number)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm;
int err;
runtime->hw = snd_ymfpci_capture;
/* FIXME? True value is 256/48 = 5.33333 ms */
err = snd_pcm_hw_constraint_minmax(runtime,
SNDRV_PCM_HW_PARAM_PERIOD_TIME,
5334, UINT_MAX);
if (err < 0)
return err;
err = snd_pcm_hw_rule_noresample(runtime, 48000);
if (err < 0)
return err;
ypcm = kzalloc(sizeof(*ypcm), GFP_KERNEL);
if (ypcm == NULL)
return -ENOMEM;
ypcm->chip = chip;
ypcm->type = capture_bank_number + CAPTURE_REC;
ypcm->substream = substream;
ypcm->capture_bank_number = capture_bank_number;
chip->capture_substream[capture_bank_number] = substream;
runtime->private_data = ypcm;
runtime->private_free = snd_ymfpci_pcm_free_substream;
snd_ymfpci_hw_start(chip);
return 0;
}
static int snd_ymfpci_capture_rec_open(struct snd_pcm_substream *substream)
{
return snd_ymfpci_capture_open(substream, 0);
}
static int snd_ymfpci_capture_ac97_open(struct snd_pcm_substream *substream)
{
return snd_ymfpci_capture_open(substream, 1);
}
static int snd_ymfpci_playback_close_1(struct snd_pcm_substream *substream)
{
return 0;
}
static int snd_ymfpci_playback_close(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_ymfpci_pcm *ypcm = substream->runtime->private_data;
spin_lock_irq(&chip->reg_lock);
if (ypcm->output_rear && chip->rear_opened > 0) {
chip->rear_opened--;
ymfpci_close_extension(chip);
}
spin_unlock_irq(&chip->reg_lock);
return snd_ymfpci_playback_close_1(substream);
}
static int snd_ymfpci_playback_spdif_close(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
spin_lock_irq(&chip->reg_lock);
chip->spdif_opened = 0;
ymfpci_close_extension(chip);
snd_ymfpci_writew(chip, YDSXGR_SPDIFOUTCTRL,
snd_ymfpci_readw(chip, YDSXGR_SPDIFOUTCTRL) & ~2);
snd_ymfpci_writew(chip, YDSXGR_SPDIFOUTSTATUS, chip->spdif_bits);
spin_unlock_irq(&chip->reg_lock);
chip->spdif_pcm_ctl->vd[0].access |= SNDRV_CTL_ELEM_ACCESS_INACTIVE;
snd_ctl_notify(chip->card, SNDRV_CTL_EVENT_MASK_VALUE |
SNDRV_CTL_EVENT_MASK_INFO, &chip->spdif_pcm_ctl->id);
return snd_ymfpci_playback_close_1(substream);
}
static int snd_ymfpci_playback_4ch_close(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
spin_lock_irq(&chip->reg_lock);
if (chip->rear_opened > 0) {
chip->rear_opened--;
ymfpci_close_extension(chip);
}
spin_unlock_irq(&chip->reg_lock);
return snd_ymfpci_playback_close_1(substream);
}
static int snd_ymfpci_capture_close(struct snd_pcm_substream *substream)
{
struct snd_ymfpci *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_ymfpci_pcm *ypcm = runtime->private_data;
if (ypcm != NULL) {
chip->capture_substream[ypcm->capture_bank_number] = NULL;
snd_ymfpci_hw_stop(chip);
}
return 0;
}
static struct snd_pcm_ops snd_ymfpci_playback_ops = {
.open = snd_ymfpci_playback_open,
.close = snd_ymfpci_playback_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_ymfpci_playback_hw_params,
.hw_free = snd_ymfpci_playback_hw_free,
.prepare = snd_ymfpci_playback_prepare,
.trigger = snd_ymfpci_playback_trigger,
.pointer = snd_ymfpci_playback_pointer,
};
static struct snd_pcm_ops snd_ymfpci_capture_rec_ops = {
.open = snd_ymfpci_capture_rec_open,
.close = snd_ymfpci_capture_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_ymfpci_capture_hw_params,
.hw_free = snd_ymfpci_capture_hw_free,
.prepare = snd_ymfpci_capture_prepare,
.trigger = snd_ymfpci_capture_trigger,
.pointer = snd_ymfpci_capture_pointer,
};
int __devinit snd_ymfpci_pcm(struct snd_ymfpci *chip, int device, struct snd_pcm ** rpcm)
{
struct snd_pcm *pcm;
int err;
if (rpcm)
*rpcm = NULL;
if ((err = snd_pcm_new(chip->card, "YMFPCI", device, 32, 1, &pcm)) < 0)
return err;
pcm->private_data = chip;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_ymfpci_playback_ops);
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_ymfpci_capture_rec_ops);
/* global setup */
pcm->info_flags = 0;
strcpy(pcm->name, "YMFPCI");
chip->pcm = pcm;
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data(chip->pci), 64*1024, 256*1024);
if (rpcm)
*rpcm = pcm;
return 0;
}
static struct snd_pcm_ops snd_ymfpci_capture_ac97_ops = {
.open = snd_ymfpci_capture_ac97_open,
.close = snd_ymfpci_capture_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_ymfpci_capture_hw_params,
.hw_free = snd_ymfpci_capture_hw_free,
.prepare = snd_ymfpci_capture_prepare,
.trigger = snd_ymfpci_capture_trigger,
.pointer = snd_ymfpci_capture_pointer,
};
int __devinit snd_ymfpci_pcm2(struct snd_ymfpci *chip, int device, struct snd_pcm ** rpcm)
{
struct snd_pcm *pcm;
int err;
if (rpcm)
*rpcm = NULL;
if ((err = snd_pcm_new(chip->card, "YMFPCI - PCM2", device, 0, 1, &pcm)) < 0)
return err;
pcm->private_data = chip;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_ymfpci_capture_ac97_ops);
/* global setup */
pcm->info_flags = 0;
sprintf(pcm->name, "YMFPCI - %s",
chip->device_id == PCI_DEVICE_ID_YAMAHA_754 ? "Direct Recording" : "AC'97");
chip->pcm2 = pcm;
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data(chip->pci), 64*1024, 256*1024);
if (rpcm)
*rpcm = pcm;
return 0;
}
static struct snd_pcm_ops snd_ymfpci_playback_spdif_ops = {
.open = snd_ymfpci_playback_spdif_open,
.close = snd_ymfpci_playback_spdif_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_ymfpci_playback_hw_params,
.hw_free = snd_ymfpci_playback_hw_free,
.prepare = snd_ymfpci_playback_prepare,
.trigger = snd_ymfpci_playback_trigger,
.pointer = snd_ymfpci_playback_pointer,
};
int __devinit snd_ymfpci_pcm_spdif(struct snd_ymfpci *chip, int device, struct snd_pcm ** rpcm)
{
struct snd_pcm *pcm;
int err;
if (rpcm)
*rpcm = NULL;
if ((err = snd_pcm_new(chip->card, "YMFPCI - IEC958", device, 1, 0, &pcm)) < 0)
return err;
pcm->private_data = chip;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_ymfpci_playback_spdif_ops);
/* global setup */
pcm->info_flags = 0;
strcpy(pcm->name, "YMFPCI - IEC958");
chip->pcm_spdif = pcm;
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data(chip->pci), 64*1024, 256*1024);
if (rpcm)
*rpcm = pcm;
return 0;
}
static struct snd_pcm_ops snd_ymfpci_playback_4ch_ops = {
.open = snd_ymfpci_playback_4ch_open,
.close = snd_ymfpci_playback_4ch_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_ymfpci_playback_hw_params,
.hw_free = snd_ymfpci_playback_hw_free,
.prepare = snd_ymfpci_playback_prepare,
.trigger = snd_ymfpci_playback_trigger,
.pointer = snd_ymfpci_playback_pointer,
};
int __devinit snd_ymfpci_pcm_4ch(struct snd_ymfpci *chip, int device, struct snd_pcm ** rpcm)
{
struct snd_pcm *pcm;
int err;
if (rpcm)
*rpcm = NULL;
if ((err = snd_pcm_new(chip->card, "YMFPCI - Rear", device, 1, 0, &pcm)) < 0)
return err;
pcm->private_data = chip;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_ymfpci_playback_4ch_ops);
/* global setup */
pcm->info_flags = 0;
strcpy(pcm->name, "YMFPCI - Rear PCM");
chip->pcm_4ch = pcm;
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
snd_dma_pci_data(chip->pci), 64*1024, 256*1024);
if (rpcm)
*rpcm = pcm;
return 0;
}
static int snd_ymfpci_spdif_default_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958;
uinfo->count = 1;
return 0;
}
static int snd_ymfpci_spdif_default_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
spin_lock_irq(&chip->reg_lock);
ucontrol->value.iec958.status[0] = (chip->spdif_bits >> 0) & 0xff;
ucontrol->value.iec958.status[1] = (chip->spdif_bits >> 8) & 0xff;
ucontrol->value.iec958.status[3] = IEC958_AES3_CON_FS_48000;
spin_unlock_irq(&chip->reg_lock);
return 0;
}
static int snd_ymfpci_spdif_default_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
unsigned int val;
int change;
val = ((ucontrol->value.iec958.status[0] & 0x3e) << 0) |
(ucontrol->value.iec958.status[1] << 8);
spin_lock_irq(&chip->reg_lock);
change = chip->spdif_bits != val;
chip->spdif_bits = val;
if ((snd_ymfpci_readw(chip, YDSXGR_SPDIFOUTCTRL) & 1) && chip->pcm_spdif == NULL)
snd_ymfpci_writew(chip, YDSXGR_SPDIFOUTSTATUS, chip->spdif_bits);
spin_unlock_irq(&chip->reg_lock);
return change;
}
static struct snd_kcontrol_new snd_ymfpci_spdif_default __devinitdata =
{
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,DEFAULT),
.info = snd_ymfpci_spdif_default_info,
.get = snd_ymfpci_spdif_default_get,
.put = snd_ymfpci_spdif_default_put
};
static int snd_ymfpci_spdif_mask_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958;
uinfo->count = 1;
return 0;
}
static int snd_ymfpci_spdif_mask_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
spin_lock_irq(&chip->reg_lock);
ucontrol->value.iec958.status[0] = 0x3e;
ucontrol->value.iec958.status[1] = 0xff;
spin_unlock_irq(&chip->reg_lock);
return 0;
}
static struct snd_kcontrol_new snd_ymfpci_spdif_mask __devinitdata =
{
.access = SNDRV_CTL_ELEM_ACCESS_READ,
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,CON_MASK),
.info = snd_ymfpci_spdif_mask_info,
.get = snd_ymfpci_spdif_mask_get,
};
static int snd_ymfpci_spdif_stream_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958;
uinfo->count = 1;
return 0;
}
static int snd_ymfpci_spdif_stream_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
spin_lock_irq(&chip->reg_lock);
ucontrol->value.iec958.status[0] = (chip->spdif_pcm_bits >> 0) & 0xff;
ucontrol->value.iec958.status[1] = (chip->spdif_pcm_bits >> 8) & 0xff;
ucontrol->value.iec958.status[3] = IEC958_AES3_CON_FS_48000;
spin_unlock_irq(&chip->reg_lock);
return 0;
}
static int snd_ymfpci_spdif_stream_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
unsigned int val;
int change;
val = ((ucontrol->value.iec958.status[0] & 0x3e) << 0) |
(ucontrol->value.iec958.status[1] << 8);
spin_lock_irq(&chip->reg_lock);
change = chip->spdif_pcm_bits != val;
chip->spdif_pcm_bits = val;
if ((snd_ymfpci_readw(chip, YDSXGR_SPDIFOUTCTRL) & 2))
snd_ymfpci_writew(chip, YDSXGR_SPDIFOUTSTATUS, chip->spdif_pcm_bits);
spin_unlock_irq(&chip->reg_lock);
return change;
}
static struct snd_kcontrol_new snd_ymfpci_spdif_stream __devinitdata =
{
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE | SNDRV_CTL_ELEM_ACCESS_INACTIVE,
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,PCM_STREAM),
.info = snd_ymfpci_spdif_stream_info,
.get = snd_ymfpci_spdif_stream_get,
.put = snd_ymfpci_spdif_stream_put
};
static int snd_ymfpci_drec_source_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *info)
{
static const char *const texts[3] = {"AC'97", "IEC958", "ZV Port"};
return snd_ctl_enum_info(info, 1, 3, texts);
}
static int snd_ymfpci_drec_source_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *value)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
u16 reg;
spin_lock_irq(&chip->reg_lock);
reg = snd_ymfpci_readw(chip, YDSXGR_GLOBALCTRL);
spin_unlock_irq(&chip->reg_lock);
if (!(reg & 0x100))
value->value.enumerated.item[0] = 0;
else
value->value.enumerated.item[0] = 1 + ((reg & 0x200) != 0);
return 0;
}
static int snd_ymfpci_drec_source_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *value)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
u16 reg, old_reg;
spin_lock_irq(&chip->reg_lock);
old_reg = snd_ymfpci_readw(chip, YDSXGR_GLOBALCTRL);
if (value->value.enumerated.item[0] == 0)
reg = old_reg & ~0x100;
else
reg = (old_reg & ~0x300) | 0x100 | ((value->value.enumerated.item[0] == 2) << 9);
snd_ymfpci_writew(chip, YDSXGR_GLOBALCTRL, reg);
spin_unlock_irq(&chip->reg_lock);
return reg != old_reg;
}
static struct snd_kcontrol_new snd_ymfpci_drec_source __devinitdata = {
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Direct Recording Source",
.info = snd_ymfpci_drec_source_info,
.get = snd_ymfpci_drec_source_get,
.put = snd_ymfpci_drec_source_put
};
/*
* Mixer controls
*/
#define YMFPCI_SINGLE(xname, xindex, reg, shift) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, .index = xindex, \
.info = snd_ymfpci_info_single, \
.get = snd_ymfpci_get_single, .put = snd_ymfpci_put_single, \
.private_value = ((reg) | ((shift) << 16)) }
#define snd_ymfpci_info_single snd_ctl_boolean_mono_info
static int snd_ymfpci_get_single(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
int reg = kcontrol->private_value & 0xffff;
unsigned int shift = (kcontrol->private_value >> 16) & 0xff;
unsigned int mask = 1;
switch (reg) {
case YDSXGR_SPDIFOUTCTRL: break;
case YDSXGR_SPDIFINCTRL: break;
default: return -EINVAL;
}
ucontrol->value.integer.value[0] =
(snd_ymfpci_readl(chip, reg) >> shift) & mask;
return 0;
}
static int snd_ymfpci_put_single(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
int reg = kcontrol->private_value & 0xffff;
unsigned int shift = (kcontrol->private_value >> 16) & 0xff;
unsigned int mask = 1;
int change;
unsigned int val, oval;
switch (reg) {
case YDSXGR_SPDIFOUTCTRL: break;
case YDSXGR_SPDIFINCTRL: break;
default: return -EINVAL;
}
val = (ucontrol->value.integer.value[0] & mask);
val <<= shift;
spin_lock_irq(&chip->reg_lock);
oval = snd_ymfpci_readl(chip, reg);
val = (oval & ~(mask << shift)) | val;
change = val != oval;
snd_ymfpci_writel(chip, reg, val);
spin_unlock_irq(&chip->reg_lock);
return change;
}
static const DECLARE_TLV_DB_LINEAR(db_scale_native, TLV_DB_GAIN_MUTE, 0);
#define YMFPCI_DOUBLE(xname, xindex, reg) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, .index = xindex, \
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE | SNDRV_CTL_ELEM_ACCESS_TLV_READ, \
.info = snd_ymfpci_info_double, \
.get = snd_ymfpci_get_double, .put = snd_ymfpci_put_double, \
.private_value = reg, \
.tlv = { .p = db_scale_native } }
static int snd_ymfpci_info_double(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo)
{
unsigned int reg = kcontrol->private_value;
if (reg < 0x80 || reg >= 0xc0)
return -EINVAL;
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = 16383;
return 0;
}
static int snd_ymfpci_get_double(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
unsigned int reg = kcontrol->private_value;
unsigned int shift_left = 0, shift_right = 16, mask = 16383;
unsigned int val;
if (reg < 0x80 || reg >= 0xc0)
return -EINVAL;
spin_lock_irq(&chip->reg_lock);
val = snd_ymfpci_readl(chip, reg);
spin_unlock_irq(&chip->reg_lock);
ucontrol->value.integer.value[0] = (val >> shift_left) & mask;
ucontrol->value.integer.value[1] = (val >> shift_right) & mask;
return 0;
}
static int snd_ymfpci_put_double(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
unsigned int reg = kcontrol->private_value;
unsigned int shift_left = 0, shift_right = 16, mask = 16383;
int change;
unsigned int val1, val2, oval;
if (reg < 0x80 || reg >= 0xc0)
return -EINVAL;
val1 = ucontrol->value.integer.value[0] & mask;
val2 = ucontrol->value.integer.value[1] & mask;
val1 <<= shift_left;
val2 <<= shift_right;
spin_lock_irq(&chip->reg_lock);
oval = snd_ymfpci_readl(chip, reg);
val1 = (oval & ~((mask << shift_left) | (mask << shift_right))) | val1 | val2;
change = val1 != oval;
snd_ymfpci_writel(chip, reg, val1);
spin_unlock_irq(&chip->reg_lock);
return change;
}
static int snd_ymfpci_put_nativedacvol(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
unsigned int reg = YDSXGR_NATIVEDACOUTVOL;
unsigned int reg2 = YDSXGR_BUF441OUTVOL;
int change;
unsigned int value, oval;
value = ucontrol->value.integer.value[0] & 0x3fff;
value |= (ucontrol->value.integer.value[1] & 0x3fff) << 16;
spin_lock_irq(&chip->reg_lock);
oval = snd_ymfpci_readl(chip, reg);
change = value != oval;
snd_ymfpci_writel(chip, reg, value);
snd_ymfpci_writel(chip, reg2, value);
spin_unlock_irq(&chip->reg_lock);
return change;
}
/*
* 4ch duplication
*/
#define snd_ymfpci_info_dup4ch snd_ctl_boolean_mono_info
static int snd_ymfpci_get_dup4ch(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
ucontrol->value.integer.value[0] = chip->mode_dup4ch;
return 0;
}
static int snd_ymfpci_put_dup4ch(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
int change;
change = (ucontrol->value.integer.value[0] != chip->mode_dup4ch);
if (change)
chip->mode_dup4ch = !!ucontrol->value.integer.value[0];
return change;
}
static struct snd_kcontrol_new snd_ymfpci_dup4ch __devinitdata = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "4ch Duplication",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.info = snd_ymfpci_info_dup4ch,
.get = snd_ymfpci_get_dup4ch,
.put = snd_ymfpci_put_dup4ch,
};
static struct snd_kcontrol_new snd_ymfpci_controls[] __devinitdata = {
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Wave Playback Volume",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_TLV_READ,
.info = snd_ymfpci_info_double,
.get = snd_ymfpci_get_double,
.put = snd_ymfpci_put_nativedacvol,
.private_value = YDSXGR_NATIVEDACOUTVOL,
.tlv = { .p = db_scale_native },
},
YMFPCI_DOUBLE("Wave Capture Volume", 0, YDSXGR_NATIVEDACLOOPVOL),
YMFPCI_DOUBLE("Digital Capture Volume", 0, YDSXGR_NATIVEDACINVOL),
YMFPCI_DOUBLE("Digital Capture Volume", 1, YDSXGR_NATIVEADCINVOL),
YMFPCI_DOUBLE("ADC Playback Volume", 0, YDSXGR_PRIADCOUTVOL),
YMFPCI_DOUBLE("ADC Capture Volume", 0, YDSXGR_PRIADCLOOPVOL),
YMFPCI_DOUBLE("ADC Playback Volume", 1, YDSXGR_SECADCOUTVOL),
YMFPCI_DOUBLE("ADC Capture Volume", 1, YDSXGR_SECADCLOOPVOL),
YMFPCI_DOUBLE("FM Legacy Playback Volume", 0, YDSXGR_LEGACYOUTVOL),
YMFPCI_DOUBLE(SNDRV_CTL_NAME_IEC958("AC97 ", PLAYBACK,VOLUME), 0, YDSXGR_ZVOUTVOL),
YMFPCI_DOUBLE(SNDRV_CTL_NAME_IEC958("", CAPTURE,VOLUME), 0, YDSXGR_ZVLOOPVOL),
YMFPCI_DOUBLE(SNDRV_CTL_NAME_IEC958("AC97 ",PLAYBACK,VOLUME), 1, YDSXGR_SPDIFOUTVOL),
YMFPCI_DOUBLE(SNDRV_CTL_NAME_IEC958("",CAPTURE,VOLUME), 1, YDSXGR_SPDIFLOOPVOL),
YMFPCI_SINGLE(SNDRV_CTL_NAME_IEC958("",PLAYBACK,SWITCH), 0, YDSXGR_SPDIFOUTCTRL, 0),
YMFPCI_SINGLE(SNDRV_CTL_NAME_IEC958("",CAPTURE,SWITCH), 0, YDSXGR_SPDIFINCTRL, 0),
YMFPCI_SINGLE(SNDRV_CTL_NAME_IEC958("Loop",NONE,NONE), 0, YDSXGR_SPDIFINCTRL, 4),
};
/*
* GPIO
*/
static int snd_ymfpci_get_gpio_out(struct snd_ymfpci *chip, int pin)
{
u16 reg, mode;
unsigned long flags;
spin_lock_irqsave(&chip->reg_lock, flags);
reg = snd_ymfpci_readw(chip, YDSXGR_GPIOFUNCENABLE);
reg &= ~(1 << (pin + 8));
reg |= (1 << pin);
snd_ymfpci_writew(chip, YDSXGR_GPIOFUNCENABLE, reg);
/* set the level mode for input line */
mode = snd_ymfpci_readw(chip, YDSXGR_GPIOTYPECONFIG);
mode &= ~(3 << (pin * 2));
snd_ymfpci_writew(chip, YDSXGR_GPIOTYPECONFIG, mode);
snd_ymfpci_writew(chip, YDSXGR_GPIOFUNCENABLE, reg | (1 << (pin + 8)));
mode = snd_ymfpci_readw(chip, YDSXGR_GPIOINSTATUS);
spin_unlock_irqrestore(&chip->reg_lock, flags);
return (mode >> pin) & 1;
}
static int snd_ymfpci_set_gpio_out(struct snd_ymfpci *chip, int pin, int enable)
{
u16 reg;
unsigned long flags;
spin_lock_irqsave(&chip->reg_lock, flags);
reg = snd_ymfpci_readw(chip, YDSXGR_GPIOFUNCENABLE);
reg &= ~(1 << pin);
reg &= ~(1 << (pin + 8));
snd_ymfpci_writew(chip, YDSXGR_GPIOFUNCENABLE, reg);
snd_ymfpci_writew(chip, YDSXGR_GPIOOUTCTRL, enable << pin);
snd_ymfpci_writew(chip, YDSXGR_GPIOFUNCENABLE, reg | (1 << (pin + 8)));
spin_unlock_irqrestore(&chip->reg_lock, flags);
return 0;
}
#define snd_ymfpci_gpio_sw_info snd_ctl_boolean_mono_info
static int snd_ymfpci_gpio_sw_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
int pin = (int)kcontrol->private_value;
ucontrol->value.integer.value[0] = snd_ymfpci_get_gpio_out(chip, pin);
return 0;
}
static int snd_ymfpci_gpio_sw_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
int pin = (int)kcontrol->private_value;
if (snd_ymfpci_get_gpio_out(chip, pin) != ucontrol->value.integer.value[0]) {
snd_ymfpci_set_gpio_out(chip, pin, !!ucontrol->value.integer.value[0]);
ucontrol->value.integer.value[0] = snd_ymfpci_get_gpio_out(chip, pin);
return 1;
}
return 0;
}
static struct snd_kcontrol_new snd_ymfpci_rear_shared __devinitdata = {
.name = "Shared Rear/Line-In Switch",
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.info = snd_ymfpci_gpio_sw_info,
.get = snd_ymfpci_gpio_sw_get,
.put = snd_ymfpci_gpio_sw_put,
.private_value = 2,
};
/*
* PCM voice volume
*/
static int snd_ymfpci_pcm_vol_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = 0x8000;
return 0;
}
static int snd_ymfpci_pcm_vol_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
unsigned int subs = kcontrol->id.subdevice;
ucontrol->value.integer.value[0] = chip->pcm_mixer[subs].left;
ucontrol->value.integer.value[1] = chip->pcm_mixer[subs].right;
return 0;
}
static int snd_ymfpci_pcm_vol_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ymfpci *chip = snd_kcontrol_chip(kcontrol);
unsigned int subs = kcontrol->id.subdevice;
struct snd_pcm_substream *substream;
unsigned long flags;
if (ucontrol->value.integer.value[0] != chip->pcm_mixer[subs].left ||
ucontrol->value.integer.value[1] != chip->pcm_mixer[subs].right) {
chip->pcm_mixer[subs].left = ucontrol->value.integer.value[0];
chip->pcm_mixer[subs].right = ucontrol->value.integer.value[1];
if (chip->pcm_mixer[subs].left > 0x8000)
chip->pcm_mixer[subs].left = 0x8000;
if (chip->pcm_mixer[subs].right > 0x8000)
chip->pcm_mixer[subs].right = 0x8000;
substream = (struct snd_pcm_substream *)kcontrol->private_value;
spin_lock_irqsave(&chip->voice_lock, flags);
if (substream->runtime && substream->runtime->private_data) {
struct snd_ymfpci_pcm *ypcm = substream->runtime->private_data;
if (!ypcm->use_441_slot)
ypcm->update_pcm_vol = 2;
}
spin_unlock_irqrestore(&chip->voice_lock, flags);
return 1;
}
return 0;
}
static struct snd_kcontrol_new snd_ymfpci_pcm_volume __devinitdata = {
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.name = "PCM Playback Volume",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_INACTIVE,
.info = snd_ymfpci_pcm_vol_info,
.get = snd_ymfpci_pcm_vol_get,
.put = snd_ymfpci_pcm_vol_put,
};
/*
* Mixer routines
*/
static void snd_ymfpci_mixer_free_ac97_bus(struct snd_ac97_bus *bus)
{
struct snd_ymfpci *chip = bus->private_data;
chip->ac97_bus = NULL;
}
static void snd_ymfpci_mixer_free_ac97(struct snd_ac97 *ac97)
{
struct snd_ymfpci *chip = ac97->private_data;
chip->ac97 = NULL;
}
int __devinit snd_ymfpci_mixer(struct snd_ymfpci *chip, int rear_switch)
{
struct snd_ac97_template ac97;
struct snd_kcontrol *kctl;
struct snd_pcm_substream *substream;
unsigned int idx;
int err;
static struct snd_ac97_bus_ops ops = {
.write = snd_ymfpci_codec_write,
.read = snd_ymfpci_codec_read,
};
if ((err = snd_ac97_bus(chip->card, 0, &ops, chip, &chip->ac97_bus)) < 0)
return err;
chip->ac97_bus->private_free = snd_ymfpci_mixer_free_ac97_bus;
chip->ac97_bus->no_vra = 1; /* YMFPCI doesn't need VRA */
memset(&ac97, 0, sizeof(ac97));
ac97.private_data = chip;
ac97.private_free = snd_ymfpci_mixer_free_ac97;
if ((err = snd_ac97_mixer(chip->ac97_bus, &ac97, &chip->ac97)) < 0)
return err;
/* to be sure */
snd_ac97_update_bits(chip->ac97, AC97_EXTENDED_STATUS,
AC97_EA_VRA|AC97_EA_VRM, 0);
for (idx = 0; idx < ARRAY_SIZE(snd_ymfpci_controls); idx++) {
if ((err = snd_ctl_add(chip->card, snd_ctl_new1(&snd_ymfpci_controls[idx], chip))) < 0)
return err;
}
if (chip->ac97->ext_id & AC97_EI_SDAC) {
kctl = snd_ctl_new1(&snd_ymfpci_dup4ch, chip);
err = snd_ctl_add(chip->card, kctl);
if (err < 0)
return err;
}
/* add S/PDIF control */
if (snd_BUG_ON(!chip->pcm_spdif))
return -ENXIO;
if ((err = snd_ctl_add(chip->card, kctl = snd_ctl_new1(&snd_ymfpci_spdif_default, chip))) < 0)
return err;
kctl->id.device = chip->pcm_spdif->device;
if ((err = snd_ctl_add(chip->card, kctl = snd_ctl_new1(&snd_ymfpci_spdif_mask, chip))) < 0)
return err;
kctl->id.device = chip->pcm_spdif->device;
if ((err = snd_ctl_add(chip->card, kctl = snd_ctl_new1(&snd_ymfpci_spdif_stream, chip))) < 0)
return err;
kctl->id.device = chip->pcm_spdif->device;
chip->spdif_pcm_ctl = kctl;
/* direct recording source */
if (chip->device_id == PCI_DEVICE_ID_YAMAHA_754 &&
(err = snd_ctl_add(chip->card, kctl = snd_ctl_new1(&snd_ymfpci_drec_source, chip))) < 0)
return err;
/*
* shared rear/line-in
*/
if (rear_switch) {
if ((err = snd_ctl_add(chip->card, snd_ctl_new1(&snd_ymfpci_rear_shared, chip))) < 0)
return err;
}
/* per-voice volume */
substream = chip->pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream;
for (idx = 0; idx < 32; ++idx) {
kctl = snd_ctl_new1(&snd_ymfpci_pcm_volume, chip);
if (!kctl)
return -ENOMEM;
kctl->id.device = chip->pcm->device;
kctl->id.subdevice = idx;
kctl->private_value = (unsigned long)substream;
if ((err = snd_ctl_add(chip->card, kctl)) < 0)
return err;
chip->pcm_mixer[idx].left = 0x8000;
chip->pcm_mixer[idx].right = 0x8000;
chip->pcm_mixer[idx].ctl = kctl;
substream = substream->next;
}
return 0;
}
/*
* timer
*/
static int snd_ymfpci_timer_start(struct snd_timer *timer)
{
struct snd_ymfpci *chip;
unsigned long flags;
unsigned int count;
chip = snd_timer_chip(timer);
spin_lock_irqsave(&chip->reg_lock, flags);
if (timer->sticks > 1) {
chip->timer_ticks = timer->sticks;
count = timer->sticks - 1;
} else {
/*
* Divisor 1 is not allowed; fake it by using divisor 2 and
* counting two ticks for each interrupt.
*/
chip->timer_ticks = 2;
count = 2 - 1;
}
snd_ymfpci_writew(chip, YDSXGR_TIMERCOUNT, count);
snd_ymfpci_writeb(chip, YDSXGR_TIMERCTRL, 0x03);
spin_unlock_irqrestore(&chip->reg_lock, flags);
return 0;
}
static int snd_ymfpci_timer_stop(struct snd_timer *timer)
{
struct snd_ymfpci *chip;
unsigned long flags;
chip = snd_timer_chip(timer);
spin_lock_irqsave(&chip->reg_lock, flags);
snd_ymfpci_writeb(chip, YDSXGR_TIMERCTRL, 0x00);
spin_unlock_irqrestore(&chip->reg_lock, flags);
return 0;
}
static int snd_ymfpci_timer_precise_resolution(struct snd_timer *timer,
unsigned long *num, unsigned long *den)
{
*num = 1;
*den = 96000;
return 0;
}
static struct snd_timer_hardware snd_ymfpci_timer_hw = {
.flags = SNDRV_TIMER_HW_AUTO,
.resolution = 10417, /* 1 / 96 kHz = 10.41666...us */
.ticks = 0x10000,
.start = snd_ymfpci_timer_start,
.stop = snd_ymfpci_timer_stop,
.precise_resolution = snd_ymfpci_timer_precise_resolution,
};
int __devinit snd_ymfpci_timer(struct snd_ymfpci *chip, int device)
{
struct snd_timer *timer = NULL;
struct snd_timer_id tid;
int err;
tid.dev_class = SNDRV_TIMER_CLASS_CARD;
tid.dev_sclass = SNDRV_TIMER_SCLASS_NONE;
tid.card = chip->card->number;
tid.device = device;
tid.subdevice = 0;
if ((err = snd_timer_new(chip->card, "YMFPCI", &tid, &timer)) >= 0) {
strcpy(timer->name, "YMFPCI timer");
timer->private_data = chip;
timer->hw = snd_ymfpci_timer_hw;
}
chip->timer = timer;
return err;
}
/*
* proc interface
*/
static void snd_ymfpci_proc_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_ymfpci *chip = entry->private_data;
int i;
snd_iprintf(buffer, "YMFPCI\n\n");
for (i = 0; i <= YDSXGR_WORKBASE; i += 4)
snd_iprintf(buffer, "%04x: %04x\n", i, snd_ymfpci_readl(chip, i));
}
static int __devinit snd_ymfpci_proc_init(struct snd_card *card, struct snd_ymfpci *chip)
{
struct snd_info_entry *entry;
if (! snd_card_proc_new(card, "ymfpci", &entry))
snd_info_set_text_ops(entry, chip, snd_ymfpci_proc_read);
return 0;
}
/*
* initialization routines
*/
static void snd_ymfpci_aclink_reset(struct pci_dev * pci)
{
u8 cmd;
pci_read_config_byte(pci, PCIR_DSXG_CTRL, &cmd);
#if 0 // force to reset
if (cmd & 0x03) {
#endif
pci_write_config_byte(pci, PCIR_DSXG_CTRL, cmd & 0xfc);
pci_write_config_byte(pci, PCIR_DSXG_CTRL, cmd | 0x03);
pci_write_config_byte(pci, PCIR_DSXG_CTRL, cmd & 0xfc);
pci_write_config_word(pci, PCIR_DSXG_PWRCTRL1, 0);
pci_write_config_word(pci, PCIR_DSXG_PWRCTRL2, 0);
#if 0
}
#endif
}
static void snd_ymfpci_enable_dsp(struct snd_ymfpci *chip)
{
snd_ymfpci_writel(chip, YDSXGR_CONFIG, 0x00000001);
}
static void snd_ymfpci_disable_dsp(struct snd_ymfpci *chip)
{
u32 val;
int timeout = 1000;
val = snd_ymfpci_readl(chip, YDSXGR_CONFIG);
if (val)
snd_ymfpci_writel(chip, YDSXGR_CONFIG, 0x00000000);
while (timeout-- > 0) {
val = snd_ymfpci_readl(chip, YDSXGR_STATUS);
if ((val & 0x00000002) == 0)
break;
}
}
static int snd_ymfpci_request_firmware(struct snd_ymfpci *chip)
{
int err, is_1e;
const char *name;
err = request_firmware(&chip->dsp_microcode, "yamaha/ds1_dsp.fw",
&chip->pci->dev);
if (err >= 0) {
if (chip->dsp_microcode->size != YDSXG_DSPLENGTH) {
snd_printk(KERN_ERR "DSP microcode has wrong size\n");
err = -EINVAL;
}
}
if (err < 0)
return err;
is_1e = chip->device_id == PCI_DEVICE_ID_YAMAHA_724F ||
chip->device_id == PCI_DEVICE_ID_YAMAHA_740C ||
chip->device_id == PCI_DEVICE_ID_YAMAHA_744 ||
chip->device_id == PCI_DEVICE_ID_YAMAHA_754;
name = is_1e ? "yamaha/ds1e_ctrl.fw" : "yamaha/ds1_ctrl.fw";
err = request_firmware(&chip->controller_microcode, name,
&chip->pci->dev);
if (err >= 0) {
if (chip->controller_microcode->size != YDSXG_CTRLLENGTH) {
snd_printk(KERN_ERR "controller microcode"
" has wrong size\n");
err = -EINVAL;
}
}
if (err < 0)
return err;
return 0;
}
MODULE_FIRMWARE("yamaha/ds1_dsp.fw");
MODULE_FIRMWARE("yamaha/ds1_ctrl.fw");
MODULE_FIRMWARE("yamaha/ds1e_ctrl.fw");
static void snd_ymfpci_download_image(struct snd_ymfpci *chip)
{
int i;
u16 ctrl;
const __le32 *inst;
snd_ymfpci_writel(chip, YDSXGR_NATIVEDACOUTVOL, 0x00000000);
snd_ymfpci_disable_dsp(chip);
snd_ymfpci_writel(chip, YDSXGR_MODE, 0x00010000);
snd_ymfpci_writel(chip, YDSXGR_MODE, 0x00000000);
snd_ymfpci_writel(chip, YDSXGR_MAPOFREC, 0x00000000);
snd_ymfpci_writel(chip, YDSXGR_MAPOFEFFECT, 0x00000000);
snd_ymfpci_writel(chip, YDSXGR_PLAYCTRLBASE, 0x00000000);
snd_ymfpci_writel(chip, YDSXGR_RECCTRLBASE, 0x00000000);
snd_ymfpci_writel(chip, YDSXGR_EFFCTRLBASE, 0x00000000);
ctrl = snd_ymfpci_readw(chip, YDSXGR_GLOBALCTRL);
snd_ymfpci_writew(chip, YDSXGR_GLOBALCTRL, ctrl & ~0x0007);
/* setup DSP instruction code */
inst = (const __le32 *)chip->dsp_microcode->data;
for (i = 0; i < YDSXG_DSPLENGTH / 4; i++)
snd_ymfpci_writel(chip, YDSXGR_DSPINSTRAM + (i << 2),
le32_to_cpu(inst[i]));
/* setup control instruction code */
inst = (const __le32 *)chip->controller_microcode->data;
for (i = 0; i < YDSXG_CTRLLENGTH / 4; i++)
snd_ymfpci_writel(chip, YDSXGR_CTRLINSTRAM + (i << 2),
le32_to_cpu(inst[i]));
snd_ymfpci_enable_dsp(chip);
}
static int __devinit snd_ymfpci_memalloc(struct snd_ymfpci *chip)
{
long size, playback_ctrl_size;
int voice, bank, reg;
u8 *ptr;
dma_addr_t ptr_addr;
playback_ctrl_size = 4 + 4 * YDSXG_PLAYBACK_VOICES;
chip->bank_size_playback = snd_ymfpci_readl(chip, YDSXGR_PLAYCTRLSIZE) << 2;
chip->bank_size_capture = snd_ymfpci_readl(chip, YDSXGR_RECCTRLSIZE) << 2;
chip->bank_size_effect = snd_ymfpci_readl(chip, YDSXGR_EFFCTRLSIZE) << 2;
chip->work_size = YDSXG_DEFAULT_WORK_SIZE;
size = ALIGN(playback_ctrl_size, 0x100) +
ALIGN(chip->bank_size_playback * 2 * YDSXG_PLAYBACK_VOICES, 0x100) +
ALIGN(chip->bank_size_capture * 2 * YDSXG_CAPTURE_VOICES, 0x100) +
ALIGN(chip->bank_size_effect * 2 * YDSXG_EFFECT_VOICES, 0x100) +
chip->work_size;
/* work_ptr must be aligned to 256 bytes, but it's already
covered with the kernel page allocation mechanism */
if (snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, snd_dma_pci_data(chip->pci),
size, &chip->work_ptr) < 0)
return -ENOMEM;
ptr = chip->work_ptr.area;
ptr_addr = chip->work_ptr.addr;
memset(ptr, 0, size); /* for sure */
chip->bank_base_playback = ptr;
chip->bank_base_playback_addr = ptr_addr;
chip->ctrl_playback = (u32 *)ptr;
chip->ctrl_playback[0] = cpu_to_le32(YDSXG_PLAYBACK_VOICES);
ptr += ALIGN(playback_ctrl_size, 0x100);
ptr_addr += ALIGN(playback_ctrl_size, 0x100);
for (voice = 0; voice < YDSXG_PLAYBACK_VOICES; voice++) {
chip->voices[voice].number = voice;
chip->voices[voice].bank = (struct snd_ymfpci_playback_bank *)ptr;
chip->voices[voice].bank_addr = ptr_addr;
for (bank = 0; bank < 2; bank++) {
chip->bank_playback[voice][bank] = (struct snd_ymfpci_playback_bank *)ptr;
ptr += chip->bank_size_playback;
ptr_addr += chip->bank_size_playback;
}
}
ptr = (char *)ALIGN((unsigned long)ptr, 0x100);
ptr_addr = ALIGN(ptr_addr, 0x100);
chip->bank_base_capture = ptr;
chip->bank_base_capture_addr = ptr_addr;
for (voice = 0; voice < YDSXG_CAPTURE_VOICES; voice++)
for (bank = 0; bank < 2; bank++) {
chip->bank_capture[voice][bank] = (struct snd_ymfpci_capture_bank *)ptr;
ptr += chip->bank_size_capture;
ptr_addr += chip->bank_size_capture;
}
ptr = (char *)ALIGN((unsigned long)ptr, 0x100);
ptr_addr = ALIGN(ptr_addr, 0x100);
chip->bank_base_effect = ptr;
chip->bank_base_effect_addr = ptr_addr;
for (voice = 0; voice < YDSXG_EFFECT_VOICES; voice++)
for (bank = 0; bank < 2; bank++) {
chip->bank_effect[voice][bank] = (struct snd_ymfpci_effect_bank *)ptr;
ptr += chip->bank_size_effect;
ptr_addr += chip->bank_size_effect;
}
ptr = (char *)ALIGN((unsigned long)ptr, 0x100);
ptr_addr = ALIGN(ptr_addr, 0x100);
chip->work_base = ptr;
chip->work_base_addr = ptr_addr;
snd_BUG_ON(ptr + chip->work_size !=
chip->work_ptr.area + chip->work_ptr.bytes);
snd_ymfpci_writel(chip, YDSXGR_PLAYCTRLBASE, chip->bank_base_playback_addr);
snd_ymfpci_writel(chip, YDSXGR_RECCTRLBASE, chip->bank_base_capture_addr);
snd_ymfpci_writel(chip, YDSXGR_EFFCTRLBASE, chip->bank_base_effect_addr);
snd_ymfpci_writel(chip, YDSXGR_WORKBASE, chip->work_base_addr);
snd_ymfpci_writel(chip, YDSXGR_WORKSIZE, chip->work_size >> 2);
/* S/PDIF output initialization */
chip->spdif_bits = chip->spdif_pcm_bits = SNDRV_PCM_DEFAULT_CON_SPDIF & 0xffff;
snd_ymfpci_writew(chip, YDSXGR_SPDIFOUTCTRL, 0);
snd_ymfpci_writew(chip, YDSXGR_SPDIFOUTSTATUS, chip->spdif_bits);
/* S/PDIF input initialization */
snd_ymfpci_writew(chip, YDSXGR_SPDIFINCTRL, 0);
/* digital mixer setup */
for (reg = 0x80; reg < 0xc0; reg += 4)
snd_ymfpci_writel(chip, reg, 0);
snd_ymfpci_writel(chip, YDSXGR_NATIVEDACOUTVOL, 0x3fff3fff);
snd_ymfpci_writel(chip, YDSXGR_BUF441OUTVOL, 0x3fff3fff);
snd_ymfpci_writel(chip, YDSXGR_ZVOUTVOL, 0x3fff3fff);
snd_ymfpci_writel(chip, YDSXGR_SPDIFOUTVOL, 0x3fff3fff);
snd_ymfpci_writel(chip, YDSXGR_NATIVEADCINVOL, 0x3fff3fff);
snd_ymfpci_writel(chip, YDSXGR_NATIVEDACINVOL, 0x3fff3fff);
snd_ymfpci_writel(chip, YDSXGR_PRIADCLOOPVOL, 0x3fff3fff);
snd_ymfpci_writel(chip, YDSXGR_LEGACYOUTVOL, 0x3fff3fff);
return 0;
}
static int snd_ymfpci_free(struct snd_ymfpci *chip)
{
u16 ctrl;
if (snd_BUG_ON(!chip))
return -EINVAL;
if (chip->res_reg_area) { /* don't touch busy hardware */
snd_ymfpci_writel(chip, YDSXGR_NATIVEDACOUTVOL, 0);
snd_ymfpci_writel(chip, YDSXGR_BUF441OUTVOL, 0);
snd_ymfpci_writel(chip, YDSXGR_LEGACYOUTVOL, 0);
snd_ymfpci_writel(chip, YDSXGR_STATUS, ~0);
snd_ymfpci_disable_dsp(chip);
snd_ymfpci_writel(chip, YDSXGR_PLAYCTRLBASE, 0);
snd_ymfpci_writel(chip, YDSXGR_RECCTRLBASE, 0);
snd_ymfpci_writel(chip, YDSXGR_EFFCTRLBASE, 0);
snd_ymfpci_writel(chip, YDSXGR_WORKBASE, 0);
snd_ymfpci_writel(chip, YDSXGR_WORKSIZE, 0);
ctrl = snd_ymfpci_readw(chip, YDSXGR_GLOBALCTRL);
snd_ymfpci_writew(chip, YDSXGR_GLOBALCTRL, ctrl & ~0x0007);
}
snd_ymfpci_ac3_done(chip);
/* Set PCI device to D3 state */
#if 0
/* FIXME: temporarily disabled, otherwise we cannot fire up
* the chip again unless reboot. ACPI bug?
*/
pci_set_power_state(chip->pci, 3);
#endif
#ifdef CONFIG_PM
vfree(chip->saved_regs);
#endif
if (chip->irq >= 0)
free_irq(chip->irq, chip);
release_and_free_resource(chip->mpu_res);
release_and_free_resource(chip->fm_res);
snd_ymfpci_free_gameport(chip);
if (chip->reg_area_virt)
iounmap(chip->reg_area_virt);
if (chip->work_ptr.area)
snd_dma_free_pages(&chip->work_ptr);
release_and_free_resource(chip->res_reg_area);
pci_write_config_word(chip->pci, 0x40, chip->old_legacy_ctrl);
pci_disable_device(chip->pci);
release_firmware(chip->dsp_microcode);
release_firmware(chip->controller_microcode);
kfree(chip);
return 0;
}
static int snd_ymfpci_dev_free(struct snd_device *device)
{
struct snd_ymfpci *chip = device->device_data;
return snd_ymfpci_free(chip);
}
#ifdef CONFIG_PM
static int saved_regs_index[] = {
/* spdif */
YDSXGR_SPDIFOUTCTRL,
YDSXGR_SPDIFOUTSTATUS,
YDSXGR_SPDIFINCTRL,
/* volumes */
YDSXGR_PRIADCLOOPVOL,
YDSXGR_NATIVEDACINVOL,
YDSXGR_NATIVEDACOUTVOL,
YDSXGR_BUF441OUTVOL,
YDSXGR_NATIVEADCINVOL,
YDSXGR_SPDIFLOOPVOL,
YDSXGR_SPDIFOUTVOL,
YDSXGR_ZVOUTVOL,
YDSXGR_LEGACYOUTVOL,
/* address bases */
YDSXGR_PLAYCTRLBASE,
YDSXGR_RECCTRLBASE,
YDSXGR_EFFCTRLBASE,
YDSXGR_WORKBASE,
/* capture set up */
YDSXGR_MAPOFREC,
YDSXGR_RECFORMAT,
YDSXGR_RECSLOTSR,
YDSXGR_ADCFORMAT,
YDSXGR_ADCSLOTSR,
};
#define YDSXGR_NUM_SAVED_REGS ARRAY_SIZE(saved_regs_index)
int snd_ymfpci_suspend(struct pci_dev *pci, pm_message_t state)
{
struct snd_card *card = pci_get_drvdata(pci);
struct snd_ymfpci *chip = card->private_data;
unsigned int i;
snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
snd_pcm_suspend_all(chip->pcm);
snd_pcm_suspend_all(chip->pcm2);
snd_pcm_suspend_all(chip->pcm_spdif);
snd_pcm_suspend_all(chip->pcm_4ch);
snd_ac97_suspend(chip->ac97);
for (i = 0; i < YDSXGR_NUM_SAVED_REGS; i++)
chip->saved_regs[i] = snd_ymfpci_readl(chip, saved_regs_index[i]);
chip->saved_ydsxgr_mode = snd_ymfpci_readl(chip, YDSXGR_MODE);
pci_read_config_word(chip->pci, PCIR_DSXG_LEGACY,
&chip->saved_dsxg_legacy);
pci_read_config_word(chip->pci, PCIR_DSXG_ELEGACY,
&chip->saved_dsxg_elegacy);
snd_ymfpci_writel(chip, YDSXGR_NATIVEDACOUTVOL, 0);
snd_ymfpci_writel(chip, YDSXGR_BUF441OUTVOL, 0);
snd_ymfpci_disable_dsp(chip);
pci_disable_device(pci);
pci_save_state(pci);
pci_set_power_state(pci, pci_choose_state(pci, state));
return 0;
}
int snd_ymfpci_resume(struct pci_dev *pci)
{
struct snd_card *card = pci_get_drvdata(pci);
struct snd_ymfpci *chip = card->private_data;
unsigned int i;
pci_set_power_state(pci, PCI_D0);
pci_restore_state(pci);
if (pci_enable_device(pci) < 0) {
printk(KERN_ERR "ymfpci: pci_enable_device failed, "
"disabling device\n");
snd_card_disconnect(card);
return -EIO;
}
pci_set_master(pci);
snd_ymfpci_aclink_reset(pci);
snd_ymfpci_codec_ready(chip, 0);
snd_ymfpci_download_image(chip);
udelay(100);
for (i = 0; i < YDSXGR_NUM_SAVED_REGS; i++)
snd_ymfpci_writel(chip, saved_regs_index[i], chip->saved_regs[i]);
snd_ac97_resume(chip->ac97);
pci_write_config_word(chip->pci, PCIR_DSXG_LEGACY,
chip->saved_dsxg_legacy);
pci_write_config_word(chip->pci, PCIR_DSXG_ELEGACY,
chip->saved_dsxg_elegacy);
/* start hw again */
if (chip->start_count > 0) {
spin_lock_irq(&chip->reg_lock);
snd_ymfpci_writel(chip, YDSXGR_MODE, chip->saved_ydsxgr_mode);
chip->active_bank = snd_ymfpci_readl(chip, YDSXGR_CTRLSELECT);
spin_unlock_irq(&chip->reg_lock);
}
snd_power_change_state(card, SNDRV_CTL_POWER_D0);
return 0;
}
#endif /* CONFIG_PM */
int __devinit snd_ymfpci_create(struct snd_card *card,
struct pci_dev * pci,
unsigned short old_legacy_ctrl,
struct snd_ymfpci ** rchip)
{
struct snd_ymfpci *chip;
int err;
static struct snd_device_ops ops = {
.dev_free = snd_ymfpci_dev_free,
};
*rchip = NULL;
/* enable PCI device */
if ((err = pci_enable_device(pci)) < 0)
return err;
chip = kzalloc(sizeof(*chip), GFP_KERNEL);
if (chip == NULL) {
pci_disable_device(pci);
return -ENOMEM;
}
chip->old_legacy_ctrl = old_legacy_ctrl;
spin_lock_init(&chip->reg_lock);
spin_lock_init(&chip->voice_lock);
init_waitqueue_head(&chip->interrupt_sleep);
atomic_set(&chip->interrupt_sleep_count, 0);
chip->card = card;
chip->pci = pci;
chip->irq = -1;
chip->device_id = pci->device;
chip->rev = pci->revision;
chip->reg_area_phys = pci_resource_start(pci, 0);
chip->reg_area_virt = ioremap_nocache(chip->reg_area_phys, 0x8000);
pci_set_master(pci);
chip->src441_used = -1;
if ((chip->res_reg_area = request_mem_region(chip->reg_area_phys, 0x8000, "YMFPCI")) == NULL) {
snd_printk(KERN_ERR "unable to grab memory region 0x%lx-0x%lx\n", chip->reg_area_phys, chip->reg_area_phys + 0x8000 - 1);
snd_ymfpci_free(chip);
return -EBUSY;
}
if (request_irq(pci->irq, snd_ymfpci_interrupt, IRQF_SHARED,
KBUILD_MODNAME, chip)) {
snd_printk(KERN_ERR "unable to grab IRQ %d\n", pci->irq);
snd_ymfpci_free(chip);
return -EBUSY;
}
chip->irq = pci->irq;
snd_ymfpci_aclink_reset(pci);
if (snd_ymfpci_codec_ready(chip, 0) < 0) {
snd_ymfpci_free(chip);
return -EIO;
}
err = snd_ymfpci_request_firmware(chip);
if (err < 0) {
snd_printk(KERN_ERR "firmware request failed: %d\n", err);
snd_ymfpci_free(chip);
return err;
}
snd_ymfpci_download_image(chip);
udelay(100); /* seems we need a delay after downloading image.. */
if (snd_ymfpci_memalloc(chip) < 0) {
snd_ymfpci_free(chip);
return -EIO;
}
if ((err = snd_ymfpci_ac3_init(chip)) < 0) {
snd_ymfpci_free(chip);
return err;
}
#ifdef CONFIG_PM
chip->saved_regs = vmalloc(YDSXGR_NUM_SAVED_REGS * sizeof(u32));
if (chip->saved_regs == NULL) {
snd_ymfpci_free(chip);
return -ENOMEM;
}
#endif
if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops)) < 0) {
snd_ymfpci_free(chip);
return err;
}
snd_ymfpci_proc_init(card, chip);
snd_card_set_dev(card, &pci->dev);
*rchip = chip;
return 0;
}
| gpl-2.0 |
zetalabs/linux-3.4-sunxi | arch/arm/mach-pxa/colibri-pxa320.c | 4855 | 6488 | /*
* arch/arm/mach-pxa/colibri-pxa320.c
*
* Support for Toradex PXA320/310 based Colibri module
*
* Daniel Mack <daniel@caiaq.de>
* Matthias Meier <matthias.j.meier@gmx.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/init.h>
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/interrupt.h>
#include <linux/usb/gpio_vbus.h>
#include <asm/mach-types.h>
#include <asm/sizes.h>
#include <asm/mach/arch.h>
#include <asm/mach/irq.h>
#include <mach/pxa320.h>
#include <mach/colibri.h>
#include <mach/pxafb.h>
#include <mach/ohci.h>
#include <mach/audio.h>
#include <mach/pxa27x-udc.h>
#include <mach/udc.h>
#include "generic.h"
#include "devices.h"
#ifdef CONFIG_MACH_COLIBRI_EVALBOARD
static mfp_cfg_t colibri_pxa320_evalboard_pin_config[] __initdata = {
/* MMC */
GPIO22_MMC1_CLK,
GPIO23_MMC1_CMD,
GPIO18_MMC1_DAT0,
GPIO19_MMC1_DAT1,
GPIO20_MMC1_DAT2,
GPIO21_MMC1_DAT3,
GPIO28_GPIO, /* SD detect */
/* UART 1 configuration (may be set by bootloader) */
GPIO99_UART1_CTS,
GPIO104_UART1_RTS,
GPIO97_UART1_RXD,
GPIO98_UART1_TXD,
GPIO101_UART1_DTR,
GPIO103_UART1_DSR,
GPIO100_UART1_DCD,
GPIO102_UART1_RI,
/* UART 2 configuration */
GPIO109_UART2_CTS,
GPIO112_UART2_RTS,
GPIO110_UART2_RXD,
GPIO111_UART2_TXD,
/* UART 3 configuration */
GPIO30_UART3_RXD,
GPIO31_UART3_TXD,
/* UHC */
GPIO2_2_USBH_PEN,
GPIO3_2_USBH_PWR,
/* I2C */
GPIO32_I2C_SCL,
GPIO33_I2C_SDA,
/* PCMCIA */
MFP_CFG(GPIO59, AF7), /* PRST ; AF7 to tristate */
MFP_CFG(GPIO61, AF7), /* PCE1 ; AF7 to tristate */
MFP_CFG(GPIO60, AF7), /* PCE2 ; AF7 to tristate */
MFP_CFG(GPIO62, AF7), /* PCD ; AF7 to tristate */
MFP_CFG(GPIO56, AF7), /* PSKTSEL ; AF7 to tristate */
GPIO27_GPIO, /* RDnWR ; input/tristate */
GPIO50_GPIO, /* PREG ; input/tristate */
GPIO2_RDY,
GPIO5_NPIOR,
GPIO6_NPIOW,
GPIO7_NPIOS16,
GPIO8_NPWAIT,
GPIO29_GPIO, /* PRDY (READY GPIO) */
GPIO57_GPIO, /* PPEN (POWER GPIO) */
GPIO81_GPIO, /* PCD (DETECT GPIO) */
GPIO77_GPIO, /* PRST (RESET GPIO) */
GPIO53_GPIO, /* PBVD1 */
GPIO79_GPIO, /* PBVD2 */
GPIO54_GPIO, /* POE */
};
#else
static mfp_cfg_t colibri_pxa320_evalboard_pin_config[] __initdata = {};
#endif
#if defined(CONFIG_AX88796)
#define COLIBRI_ETH_IRQ_GPIO mfp_to_gpio(GPIO36_GPIO)
/*
* Asix AX88796 Ethernet
*/
static struct ax_plat_data colibri_asix_platdata = {
.flags = 0, /* defined later */
.wordlength = 2,
};
static struct resource colibri_asix_resource[] = {
[0] = {
.start = PXA3xx_CS2_PHYS,
.end = PXA3xx_CS2_PHYS + (0x20 * 2) - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = PXA_GPIO_TO_IRQ(COLIBRI_ETH_IRQ_GPIO),
.end = PXA_GPIO_TO_IRQ(COLIBRI_ETH_IRQ_GPIO),
.flags = IORESOURCE_IRQ | IRQF_TRIGGER_FALLING,
}
};
static struct platform_device asix_device = {
.name = "ax88796",
.id = 0,
.num_resources = ARRAY_SIZE(colibri_asix_resource),
.resource = colibri_asix_resource,
.dev = {
.platform_data = &colibri_asix_platdata
}
};
static mfp_cfg_t colibri_pxa320_eth_pin_config[] __initdata = {
GPIO3_nCS2, /* AX88796 chip select */
GPIO36_GPIO | MFP_PULL_HIGH /* AX88796 IRQ */
};
static void __init colibri_pxa320_init_eth(void)
{
colibri_pxa3xx_init_eth(&colibri_asix_platdata);
pxa3xx_mfp_config(ARRAY_AND_SIZE(colibri_pxa320_eth_pin_config));
platform_device_register(&asix_device);
}
#else
static inline void __init colibri_pxa320_init_eth(void) {}
#endif /* CONFIG_AX88796 */
#if defined(CONFIG_USB_PXA27X)||defined(CONFIG_USB_PXA27X_MODULE)
static struct gpio_vbus_mach_info colibri_pxa320_gpio_vbus_info = {
.gpio_vbus = mfp_to_gpio(MFP_PIN_GPIO96),
.gpio_pullup = -1,
};
static struct platform_device colibri_pxa320_gpio_vbus = {
.name = "gpio-vbus",
.id = -1,
.dev = {
.platform_data = &colibri_pxa320_gpio_vbus_info,
},
};
static void colibri_pxa320_udc_command(int cmd)
{
if (cmd == PXA2XX_UDC_CMD_CONNECT)
UP2OCR = UP2OCR_HXOE | UP2OCR_DPPUE;
else if (cmd == PXA2XX_UDC_CMD_DISCONNECT)
UP2OCR = UP2OCR_HXOE;
}
static struct pxa2xx_udc_mach_info colibri_pxa320_udc_info __initdata = {
.udc_command = colibri_pxa320_udc_command,
.gpio_pullup = -1,
};
static void __init colibri_pxa320_init_udc(void)
{
pxa_set_udc_info(&colibri_pxa320_udc_info);
platform_device_register(&colibri_pxa320_gpio_vbus);
}
#else
static inline void colibri_pxa320_init_udc(void) {}
#endif
#if defined(CONFIG_FB_PXA) || defined(CONFIG_FB_PXA_MODULE)
static mfp_cfg_t colibri_pxa320_lcd_pin_config[] __initdata = {
GPIO6_2_LCD_LDD_0,
GPIO7_2_LCD_LDD_1,
GPIO8_2_LCD_LDD_2,
GPIO9_2_LCD_LDD_3,
GPIO10_2_LCD_LDD_4,
GPIO11_2_LCD_LDD_5,
GPIO12_2_LCD_LDD_6,
GPIO13_2_LCD_LDD_7,
GPIO63_LCD_LDD_8,
GPIO64_LCD_LDD_9,
GPIO65_LCD_LDD_10,
GPIO66_LCD_LDD_11,
GPIO67_LCD_LDD_12,
GPIO68_LCD_LDD_13,
GPIO69_LCD_LDD_14,
GPIO70_LCD_LDD_15,
GPIO71_LCD_LDD_16,
GPIO72_LCD_LDD_17,
GPIO73_LCD_CS_N,
GPIO74_LCD_VSYNC,
GPIO14_2_LCD_FCLK,
GPIO15_2_LCD_LCLK,
GPIO16_2_LCD_PCLK,
GPIO17_2_LCD_BIAS,
};
static void __init colibri_pxa320_init_lcd(void)
{
pxa3xx_mfp_config(ARRAY_AND_SIZE(colibri_pxa320_lcd_pin_config));
}
#else
static inline void colibri_pxa320_init_lcd(void) {}
#endif
#if defined(CONFIG_SND_AC97_CODEC) || \
defined(CONFIG_SND_AC97_CODEC_MODULE)
static mfp_cfg_t colibri_pxa320_ac97_pin_config[] __initdata = {
GPIO34_AC97_SYSCLK,
GPIO35_AC97_SDATA_IN_0,
GPIO37_AC97_SDATA_OUT,
GPIO38_AC97_SYNC,
GPIO39_AC97_BITCLK,
GPIO40_AC97_nACRESET
};
static inline void __init colibri_pxa320_init_ac97(void)
{
pxa3xx_mfp_config(ARRAY_AND_SIZE(colibri_pxa320_ac97_pin_config));
pxa_set_ac97_info(NULL);
}
#else
static inline void colibri_pxa320_init_ac97(void) {}
#endif
void __init colibri_pxa320_init(void)
{
colibri_pxa320_init_eth();
colibri_pxa3xx_init_nand();
colibri_pxa320_init_lcd();
colibri_pxa3xx_init_lcd(mfp_to_gpio(GPIO49_GPIO));
colibri_pxa320_init_ac97();
colibri_pxa320_init_udc();
/* Evalboard init */
pxa3xx_mfp_config(ARRAY_AND_SIZE(colibri_pxa320_evalboard_pin_config));
colibri_evalboard_init();
}
MACHINE_START(COLIBRI320, "Toradex Colibri PXA320")
.atag_offset = 0x100,
.init_machine = colibri_pxa320_init,
.map_io = pxa3xx_map_io,
.nr_irqs = PXA_NR_IRQS,
.init_irq = pxa3xx_init_irq,
.handle_irq = pxa3xx_handle_irq,
.timer = &pxa_timer,
.restart = pxa_restart,
MACHINE_END
| gpl-2.0 |
SnowDroid/kernel_lge_hammerhead | arch/cris/arch-v32/drivers/mach-fs/gpio.c | 6903 | 25475 | /*
* ETRAX CRISv32 general port I/O device
*
* Copyright (c) 1999-2006 Axis Communications AB
*
* Authors: Bjorn Wesen (initial version)
* Ola Knutsson (LED handling)
* Johan Adolfsson (read/set directions, write, port G,
* port to ETRAX FS.
*
*/
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/ioport.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/string.h>
#include <linux/poll.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/spinlock.h>
#include <linux/mutex.h>
#include <asm/etraxgpio.h>
#include <hwregs/reg_map.h>
#include <hwregs/reg_rdwr.h>
#include <hwregs/gio_defs.h>
#include <hwregs/intr_vect_defs.h>
#include <asm/io.h>
#include <asm/irq.h>
#ifdef CONFIG_ETRAX_VIRTUAL_GPIO
#include "../i2c.h"
#define VIRT_I2C_ADDR 0x40
#endif
/* The following gio ports on ETRAX FS is available:
* pa 8 bits, supports interrupts off, hi, low, set, posedge, negedge anyedge
* pb 18 bits
* pc 18 bits
* pd 18 bits
* pe 18 bits
* each port has a rw_px_dout, r_px_din and rw_px_oe register.
*/
#define GPIO_MAJOR 120 /* experimental MAJOR number */
#define D(x)
#if 0
static int dp_cnt;
#define DP(x) \
do { \
dp_cnt++; \
if (dp_cnt % 1000 == 0) \
x; \
} while (0)
#else
#define DP(x)
#endif
static DEFINE_MUTEX(gpio_mutex);
static char gpio_name[] = "etrax gpio";
#if 0
static wait_queue_head_t *gpio_wq;
#endif
#ifdef CONFIG_ETRAX_VIRTUAL_GPIO
static int virtual_gpio_ioctl(struct file *file, unsigned int cmd,
unsigned long arg);
#endif
static long gpio_ioctl(struct file *file, unsigned int cmd, unsigned long arg);
static ssize_t gpio_write(struct file *file, const char *buf, size_t count,
loff_t *off);
static int gpio_open(struct inode *inode, struct file *filp);
static int gpio_release(struct inode *inode, struct file *filp);
static unsigned int gpio_poll(struct file *filp,
struct poll_table_struct *wait);
/* private data per open() of this driver */
struct gpio_private {
struct gpio_private *next;
/* The IO_CFG_WRITE_MODE_VALUE only support 8 bits: */
unsigned char clk_mask;
unsigned char data_mask;
unsigned char write_msb;
unsigned char pad1;
/* These fields are generic */
unsigned long highalarm, lowalarm;
wait_queue_head_t alarm_wq;
int minor;
};
/* linked list of alarms to check for */
static struct gpio_private *alarmlist;
static int gpio_some_alarms; /* Set if someone uses alarm */
static unsigned long gpio_pa_high_alarms;
static unsigned long gpio_pa_low_alarms;
static DEFINE_SPINLOCK(alarm_lock);
#define NUM_PORTS (GPIO_MINOR_LAST+1)
#define GIO_REG_RD_ADDR(reg) \
(volatile unsigned long *)(regi_gio + REG_RD_ADDR_gio_##reg)
#define GIO_REG_WR_ADDR(reg) \
(volatile unsigned long *)(regi_gio + REG_RD_ADDR_gio_##reg)
unsigned long led_dummy;
#ifdef CONFIG_ETRAX_VIRTUAL_GPIO
static unsigned long virtual_dummy;
static unsigned long virtual_rw_pv_oe = CONFIG_ETRAX_DEF_GIO_PV_OE;
static unsigned short cached_virtual_gpio_read;
#endif
static volatile unsigned long *data_out[NUM_PORTS] = {
GIO_REG_WR_ADDR(rw_pa_dout),
GIO_REG_WR_ADDR(rw_pb_dout),
&led_dummy,
GIO_REG_WR_ADDR(rw_pc_dout),
GIO_REG_WR_ADDR(rw_pd_dout),
GIO_REG_WR_ADDR(rw_pe_dout),
#ifdef CONFIG_ETRAX_VIRTUAL_GPIO
&virtual_dummy,
#endif
};
static volatile unsigned long *data_in[NUM_PORTS] = {
GIO_REG_RD_ADDR(r_pa_din),
GIO_REG_RD_ADDR(r_pb_din),
&led_dummy,
GIO_REG_RD_ADDR(r_pc_din),
GIO_REG_RD_ADDR(r_pd_din),
GIO_REG_RD_ADDR(r_pe_din),
#ifdef CONFIG_ETRAX_VIRTUAL_GPIO
&virtual_dummy,
#endif
};
static unsigned long changeable_dir[NUM_PORTS] = {
CONFIG_ETRAX_PA_CHANGEABLE_DIR,
CONFIG_ETRAX_PB_CHANGEABLE_DIR,
0,
CONFIG_ETRAX_PC_CHANGEABLE_DIR,
CONFIG_ETRAX_PD_CHANGEABLE_DIR,
CONFIG_ETRAX_PE_CHANGEABLE_DIR,
#ifdef CONFIG_ETRAX_VIRTUAL_GPIO
CONFIG_ETRAX_PV_CHANGEABLE_DIR,
#endif
};
static unsigned long changeable_bits[NUM_PORTS] = {
CONFIG_ETRAX_PA_CHANGEABLE_BITS,
CONFIG_ETRAX_PB_CHANGEABLE_BITS,
0,
CONFIG_ETRAX_PC_CHANGEABLE_BITS,
CONFIG_ETRAX_PD_CHANGEABLE_BITS,
CONFIG_ETRAX_PE_CHANGEABLE_BITS,
#ifdef CONFIG_ETRAX_VIRTUAL_GPIO
CONFIG_ETRAX_PV_CHANGEABLE_BITS,
#endif
};
static volatile unsigned long *dir_oe[NUM_PORTS] = {
GIO_REG_WR_ADDR(rw_pa_oe),
GIO_REG_WR_ADDR(rw_pb_oe),
&led_dummy,
GIO_REG_WR_ADDR(rw_pc_oe),
GIO_REG_WR_ADDR(rw_pd_oe),
GIO_REG_WR_ADDR(rw_pe_oe),
#ifdef CONFIG_ETRAX_VIRTUAL_GPIO
&virtual_rw_pv_oe,
#endif
};
static unsigned int gpio_poll(struct file *file, struct poll_table_struct *wait)
{
unsigned int mask = 0;
struct gpio_private *priv = file->private_data;
unsigned long data;
poll_wait(file, &priv->alarm_wq, wait);
if (priv->minor == GPIO_MINOR_A) {
reg_gio_rw_intr_cfg intr_cfg;
unsigned long tmp;
unsigned long flags;
local_irq_save(flags);
data = REG_TYPE_CONV(unsigned long, reg_gio_r_pa_din,
REG_RD(gio, regi_gio, r_pa_din));
/* PA has support for interrupt
* lets activate high for those low and with highalarm set
*/
intr_cfg = REG_RD(gio, regi_gio, rw_intr_cfg);
tmp = ~data & priv->highalarm & 0xFF;
if (tmp & (1 << 0))
intr_cfg.pa0 = regk_gio_hi;
if (tmp & (1 << 1))
intr_cfg.pa1 = regk_gio_hi;
if (tmp & (1 << 2))
intr_cfg.pa2 = regk_gio_hi;
if (tmp & (1 << 3))
intr_cfg.pa3 = regk_gio_hi;
if (tmp & (1 << 4))
intr_cfg.pa4 = regk_gio_hi;
if (tmp & (1 << 5))
intr_cfg.pa5 = regk_gio_hi;
if (tmp & (1 << 6))
intr_cfg.pa6 = regk_gio_hi;
if (tmp & (1 << 7))
intr_cfg.pa7 = regk_gio_hi;
/*
* lets activate low for those high and with lowalarm set
*/
tmp = data & priv->lowalarm & 0xFF;
if (tmp & (1 << 0))
intr_cfg.pa0 = regk_gio_lo;
if (tmp & (1 << 1))
intr_cfg.pa1 = regk_gio_lo;
if (tmp & (1 << 2))
intr_cfg.pa2 = regk_gio_lo;
if (tmp & (1 << 3))
intr_cfg.pa3 = regk_gio_lo;
if (tmp & (1 << 4))
intr_cfg.pa4 = regk_gio_lo;
if (tmp & (1 << 5))
intr_cfg.pa5 = regk_gio_lo;
if (tmp & (1 << 6))
intr_cfg.pa6 = regk_gio_lo;
if (tmp & (1 << 7))
intr_cfg.pa7 = regk_gio_lo;
REG_WR(gio, regi_gio, rw_intr_cfg, intr_cfg);
local_irq_restore(flags);
} else if (priv->minor <= GPIO_MINOR_E)
data = *data_in[priv->minor];
else
return 0;
if ((data & priv->highalarm) || (~data & priv->lowalarm))
mask = POLLIN|POLLRDNORM;
DP(printk(KERN_DEBUG "gpio_poll ready: mask 0x%08X\n", mask));
return mask;
}
int etrax_gpio_wake_up_check(void)
{
struct gpio_private *priv;
unsigned long data = 0;
unsigned long flags;
int ret = 0;
spin_lock_irqsave(&alarm_lock, flags);
priv = alarmlist;
while (priv) {
#ifdef CONFIG_ETRAX_VIRTUAL_GPIO
if (priv->minor == GPIO_MINOR_V)
data = (unsigned long)cached_virtual_gpio_read;
else {
data = *data_in[priv->minor];
if (priv->minor == GPIO_MINOR_A)
priv->lowalarm |= (1 << CONFIG_ETRAX_VIRTUAL_GPIO_INTERRUPT_PA_PIN);
}
#else
data = *data_in[priv->minor];
#endif
if ((data & priv->highalarm) ||
(~data & priv->lowalarm)) {
DP(printk(KERN_DEBUG
"etrax_gpio_wake_up_check %i\n", priv->minor));
wake_up_interruptible(&priv->alarm_wq);
ret = 1;
}
priv = priv->next;
}
spin_unlock_irqrestore(&alarm_lock, flags);
return ret;
}
static irqreturn_t
gpio_poll_timer_interrupt(int irq, void *dev_id)
{
if (gpio_some_alarms)
return IRQ_RETVAL(etrax_gpio_wake_up_check());
return IRQ_NONE;
}
static irqreturn_t
gpio_pa_interrupt(int irq, void *dev_id)
{
reg_gio_rw_intr_mask intr_mask;
reg_gio_r_masked_intr masked_intr;
reg_gio_rw_ack_intr ack_intr;
unsigned long tmp;
unsigned long tmp2;
#ifdef CONFIG_ETRAX_VIRTUAL_GPIO
unsigned char enable_gpiov_ack = 0;
#endif
/* Find what PA interrupts are active */
masked_intr = REG_RD(gio, regi_gio, r_masked_intr);
tmp = REG_TYPE_CONV(unsigned long, reg_gio_r_masked_intr, masked_intr);
/* Find those that we have enabled */
spin_lock(&alarm_lock);
tmp &= (gpio_pa_high_alarms | gpio_pa_low_alarms);
spin_unlock(&alarm_lock);
#ifdef CONFIG_ETRAX_VIRTUAL_GPIO
/* Something changed on virtual GPIO. Interrupt is acked by
* reading the device.
*/
if (tmp & (1 << CONFIG_ETRAX_VIRTUAL_GPIO_INTERRUPT_PA_PIN)) {
i2c_read(VIRT_I2C_ADDR, (void *)&cached_virtual_gpio_read,
sizeof(cached_virtual_gpio_read));
enable_gpiov_ack = 1;
}
#endif
/* Ack them */
ack_intr = REG_TYPE_CONV(reg_gio_rw_ack_intr, unsigned long, tmp);
REG_WR(gio, regi_gio, rw_ack_intr, ack_intr);
/* Disable those interrupts.. */
intr_mask = REG_RD(gio, regi_gio, rw_intr_mask);
tmp2 = REG_TYPE_CONV(unsigned long, reg_gio_rw_intr_mask, intr_mask);
tmp2 &= ~tmp;
#ifdef CONFIG_ETRAX_VIRTUAL_GPIO
/* Do not disable interrupt on virtual GPIO. Changes on virtual
* pins are only noticed by an interrupt.
*/
if (enable_gpiov_ack)
tmp2 |= (1 << CONFIG_ETRAX_VIRTUAL_GPIO_INTERRUPT_PA_PIN);
#endif
intr_mask = REG_TYPE_CONV(reg_gio_rw_intr_mask, unsigned long, tmp2);
REG_WR(gio, regi_gio, rw_intr_mask, intr_mask);
if (gpio_some_alarms)
return IRQ_RETVAL(etrax_gpio_wake_up_check());
return IRQ_NONE;
}
static ssize_t gpio_write(struct file *file, const char *buf, size_t count,
loff_t *off)
{
struct gpio_private *priv = file->private_data;
unsigned char data, clk_mask, data_mask, write_msb;
unsigned long flags;
unsigned long shadow;
volatile unsigned long *port;
ssize_t retval = count;
/* Only bits 0-7 may be used for write operations but allow all
devices except leds... */
#ifdef CONFIG_ETRAX_VIRTUAL_GPIO
if (priv->minor == GPIO_MINOR_V)
return -EFAULT;
#endif
if (priv->minor == GPIO_MINOR_LEDS)
return -EFAULT;
if (!access_ok(VERIFY_READ, buf, count))
return -EFAULT;
clk_mask = priv->clk_mask;
data_mask = priv->data_mask;
/* It must have been configured using the IO_CFG_WRITE_MODE */
/* Perhaps a better error code? */
if (clk_mask == 0 || data_mask == 0)
return -EPERM;
write_msb = priv->write_msb;
D(printk(KERN_DEBUG "gpio_write: %lu to data 0x%02X clk 0x%02X "
"msb: %i\n", count, data_mask, clk_mask, write_msb));
port = data_out[priv->minor];
while (count--) {
int i;
data = *buf++;
if (priv->write_msb) {
for (i = 7; i >= 0; i--) {
local_irq_save(flags);
shadow = *port;
*port = shadow &= ~clk_mask;
if (data & 1<<i)
*port = shadow |= data_mask;
else
*port = shadow &= ~data_mask;
/* For FPGA: min 5.0ns (DCC) before CCLK high */
*port = shadow |= clk_mask;
local_irq_restore(flags);
}
} else {
for (i = 0; i <= 7; i++) {
local_irq_save(flags);
shadow = *port;
*port = shadow &= ~clk_mask;
if (data & 1<<i)
*port = shadow |= data_mask;
else
*port = shadow &= ~data_mask;
/* For FPGA: min 5.0ns (DCC) before CCLK high */
*port = shadow |= clk_mask;
local_irq_restore(flags);
}
}
}
return retval;
}
static int
gpio_open(struct inode *inode, struct file *filp)
{
struct gpio_private *priv;
int p = iminor(inode);
if (p > GPIO_MINOR_LAST)
return -EINVAL;
priv = kmalloc(sizeof(struct gpio_private), GFP_KERNEL);
if (!priv)
return -ENOMEM;
mutex_lock(&gpio_mutex);
memset(priv, 0, sizeof(*priv));
priv->minor = p;
/* initialize the io/alarm struct */
priv->clk_mask = 0;
priv->data_mask = 0;
priv->highalarm = 0;
priv->lowalarm = 0;
init_waitqueue_head(&priv->alarm_wq);
filp->private_data = (void *)priv;
/* link it into our alarmlist */
spin_lock_irq(&alarm_lock);
priv->next = alarmlist;
alarmlist = priv;
spin_unlock_irq(&alarm_lock);
mutex_unlock(&gpio_mutex);
return 0;
}
static int
gpio_release(struct inode *inode, struct file *filp)
{
struct gpio_private *p;
struct gpio_private *todel;
/* local copies while updating them: */
unsigned long a_high, a_low;
unsigned long some_alarms;
/* unlink from alarmlist and free the private structure */
spin_lock_irq(&alarm_lock);
p = alarmlist;
todel = filp->private_data;
if (p == todel) {
alarmlist = todel->next;
} else {
while (p->next != todel)
p = p->next;
p->next = todel->next;
}
kfree(todel);
/* Check if there are still any alarms set */
p = alarmlist;
some_alarms = 0;
a_high = 0;
a_low = 0;
while (p) {
if (p->minor == GPIO_MINOR_A) {
#ifdef CONFIG_ETRAX_VIRTUAL_GPIO
p->lowalarm |= (1 << CONFIG_ETRAX_VIRTUAL_GPIO_INTERRUPT_PA_PIN);
#endif
a_high |= p->highalarm;
a_low |= p->lowalarm;
}
if (p->highalarm | p->lowalarm)
some_alarms = 1;
p = p->next;
}
#ifdef CONFIG_ETRAX_VIRTUAL_GPIO
/* Variables 'some_alarms' and 'a_low' needs to be set here again
* to ensure that interrupt for virtual GPIO is handled.
*/
some_alarms = 1;
a_low |= (1 << CONFIG_ETRAX_VIRTUAL_GPIO_INTERRUPT_PA_PIN);
#endif
gpio_some_alarms = some_alarms;
gpio_pa_high_alarms = a_high;
gpio_pa_low_alarms = a_low;
spin_unlock_irq(&alarm_lock);
return 0;
}
/* Main device API. ioctl's to read/set/clear bits, as well as to
* set alarms to wait for using a subsequent select().
*/
inline unsigned long setget_input(struct gpio_private *priv, unsigned long arg)
{
/* Set direction 0=unchanged 1=input,
* return mask with 1=input
*/
unsigned long flags;
unsigned long dir_shadow;
local_irq_save(flags);
dir_shadow = *dir_oe[priv->minor];
dir_shadow &= ~(arg & changeable_dir[priv->minor]);
*dir_oe[priv->minor] = dir_shadow;
local_irq_restore(flags);
if (priv->minor == GPIO_MINOR_A)
dir_shadow ^= 0xFF; /* Only 8 bits */
#ifdef CONFIG_ETRAX_VIRTUAL_GPIO
else if (priv->minor == GPIO_MINOR_V)
dir_shadow ^= 0xFFFF; /* Only 16 bits */
#endif
else
dir_shadow ^= 0x3FFFF; /* Only 18 bits */
return dir_shadow;
} /* setget_input */
inline unsigned long setget_output(struct gpio_private *priv, unsigned long arg)
{
unsigned long flags;
unsigned long dir_shadow;
local_irq_save(flags);
dir_shadow = *dir_oe[priv->minor];
dir_shadow |= (arg & changeable_dir[priv->minor]);
*dir_oe[priv->minor] = dir_shadow;
local_irq_restore(flags);
return dir_shadow;
} /* setget_output */
static int gpio_leds_ioctl(unsigned int cmd, unsigned long arg);
static int
gpio_ioctl_unlocked(struct file *file, unsigned int cmd, unsigned long arg)
{
unsigned long flags;
unsigned long val;
unsigned long shadow;
struct gpio_private *priv = file->private_data;
if (_IOC_TYPE(cmd) != ETRAXGPIO_IOCTYPE)
return -EINVAL;
#ifdef CONFIG_ETRAX_VIRTUAL_GPIO
if (priv->minor == GPIO_MINOR_V)
return virtual_gpio_ioctl(file, cmd, arg);
#endif
switch (_IOC_NR(cmd)) {
case IO_READBITS: /* Use IO_READ_INBITS and IO_READ_OUTBITS instead */
/* Read the port. */
return *data_in[priv->minor];
break;
case IO_SETBITS:
local_irq_save(flags);
/* Set changeable bits with a 1 in arg. */
shadow = *data_out[priv->minor];
shadow |= (arg & changeable_bits[priv->minor]);
*data_out[priv->minor] = shadow;
local_irq_restore(flags);
break;
case IO_CLRBITS:
local_irq_save(flags);
/* Clear changeable bits with a 1 in arg. */
shadow = *data_out[priv->minor];
shadow &= ~(arg & changeable_bits[priv->minor]);
*data_out[priv->minor] = shadow;
local_irq_restore(flags);
break;
case IO_HIGHALARM:
/* Set alarm when bits with 1 in arg go high. */
priv->highalarm |= arg;
spin_lock_irqsave(&alarm_lock, flags);
gpio_some_alarms = 1;
if (priv->minor == GPIO_MINOR_A)
gpio_pa_high_alarms |= arg;
spin_unlock_irqrestore(&alarm_lock, flags);
break;
case IO_LOWALARM:
/* Set alarm when bits with 1 in arg go low. */
priv->lowalarm |= arg;
spin_lock_irqsave(&alarm_lock, flags);
gpio_some_alarms = 1;
if (priv->minor == GPIO_MINOR_A)
gpio_pa_low_alarms |= arg;
spin_unlock_irqrestore(&alarm_lock, flags);
break;
case IO_CLRALARM:
/* Clear alarm for bits with 1 in arg. */
priv->highalarm &= ~arg;
priv->lowalarm &= ~arg;
spin_lock_irqsave(&alarm_lock, flags);
if (priv->minor == GPIO_MINOR_A) {
if (gpio_pa_high_alarms & arg ||
gpio_pa_low_alarms & arg)
/* Must update the gpio_pa_*alarms masks */
;
}
spin_unlock_irqrestore(&alarm_lock, flags);
break;
case IO_READDIR: /* Use IO_SETGET_INPUT/OUTPUT instead! */
/* Read direction 0=input 1=output */
return *dir_oe[priv->minor];
case IO_SETINPUT: /* Use IO_SETGET_INPUT instead! */
/* Set direction 0=unchanged 1=input,
* return mask with 1=input
*/
return setget_input(priv, arg);
break;
case IO_SETOUTPUT: /* Use IO_SETGET_OUTPUT instead! */
/* Set direction 0=unchanged 1=output,
* return mask with 1=output
*/
return setget_output(priv, arg);
case IO_CFG_WRITE_MODE:
{
unsigned long dir_shadow;
dir_shadow = *dir_oe[priv->minor];
priv->clk_mask = arg & 0xFF;
priv->data_mask = (arg >> 8) & 0xFF;
priv->write_msb = (arg >> 16) & 0x01;
/* Check if we're allowed to change the bits and
* the direction is correct
*/
if (!((priv->clk_mask & changeable_bits[priv->minor]) &&
(priv->data_mask & changeable_bits[priv->minor]) &&
(priv->clk_mask & dir_shadow) &&
(priv->data_mask & dir_shadow))) {
priv->clk_mask = 0;
priv->data_mask = 0;
return -EPERM;
}
break;
}
case IO_READ_INBITS:
/* *arg is result of reading the input pins */
val = *data_in[priv->minor];
if (copy_to_user((unsigned long *)arg, &val, sizeof(val)))
return -EFAULT;
return 0;
break;
case IO_READ_OUTBITS:
/* *arg is result of reading the output shadow */
val = *data_out[priv->minor];
if (copy_to_user((unsigned long *)arg, &val, sizeof(val)))
return -EFAULT;
break;
case IO_SETGET_INPUT:
/* bits set in *arg is set to input,
* *arg updated with current input pins.
*/
if (copy_from_user(&val, (unsigned long *)arg, sizeof(val)))
return -EFAULT;
val = setget_input(priv, val);
if (copy_to_user((unsigned long *)arg, &val, sizeof(val)))
return -EFAULT;
break;
case IO_SETGET_OUTPUT:
/* bits set in *arg is set to output,
* *arg updated with current output pins.
*/
if (copy_from_user(&val, (unsigned long *)arg, sizeof(val)))
return -EFAULT;
val = setget_output(priv, val);
if (copy_to_user((unsigned long *)arg, &val, sizeof(val)))
return -EFAULT;
break;
default:
if (priv->minor == GPIO_MINOR_LEDS)
return gpio_leds_ioctl(cmd, arg);
else
return -EINVAL;
} /* switch */
return 0;
}
static long gpio_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
long ret;
mutex_lock(&gpio_mutex);
ret = gpio_ioctl_unlocked(file, cmd, arg);
mutex_unlock(&gpio_mutex);
return ret;
}
#ifdef CONFIG_ETRAX_VIRTUAL_GPIO
static int
virtual_gpio_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
unsigned long flags;
unsigned short val;
unsigned short shadow;
struct gpio_private *priv = file->private_data;
switch (_IOC_NR(cmd)) {
case IO_SETBITS:
local_irq_save(flags);
/* Set changeable bits with a 1 in arg. */
i2c_read(VIRT_I2C_ADDR, (void *)&shadow, sizeof(shadow));
shadow |= ~*dir_oe[priv->minor];
shadow |= (arg & changeable_bits[priv->minor]);
i2c_write(VIRT_I2C_ADDR, (void *)&shadow, sizeof(shadow));
local_irq_restore(flags);
break;
case IO_CLRBITS:
local_irq_save(flags);
/* Clear changeable bits with a 1 in arg. */
i2c_read(VIRT_I2C_ADDR, (void *)&shadow, sizeof(shadow));
shadow |= ~*dir_oe[priv->minor];
shadow &= ~(arg & changeable_bits[priv->minor]);
i2c_write(VIRT_I2C_ADDR, (void *)&shadow, sizeof(shadow));
local_irq_restore(flags);
break;
case IO_HIGHALARM:
/* Set alarm when bits with 1 in arg go high. */
priv->highalarm |= arg;
spin_lock(&alarm_lock);
gpio_some_alarms = 1;
spin_unlock(&alarm_lock);
break;
case IO_LOWALARM:
/* Set alarm when bits with 1 in arg go low. */
priv->lowalarm |= arg;
spin_lock(&alarm_lock);
gpio_some_alarms = 1;
spin_unlock(&alarm_lock);
break;
case IO_CLRALARM:
/* Clear alarm for bits with 1 in arg. */
priv->highalarm &= ~arg;
priv->lowalarm &= ~arg;
spin_lock(&alarm_lock);
spin_unlock(&alarm_lock);
break;
case IO_CFG_WRITE_MODE:
{
unsigned long dir_shadow;
dir_shadow = *dir_oe[priv->minor];
priv->clk_mask = arg & 0xFF;
priv->data_mask = (arg >> 8) & 0xFF;
priv->write_msb = (arg >> 16) & 0x01;
/* Check if we're allowed to change the bits and
* the direction is correct
*/
if (!((priv->clk_mask & changeable_bits[priv->minor]) &&
(priv->data_mask & changeable_bits[priv->minor]) &&
(priv->clk_mask & dir_shadow) &&
(priv->data_mask & dir_shadow))) {
priv->clk_mask = 0;
priv->data_mask = 0;
return -EPERM;
}
break;
}
case IO_READ_INBITS:
/* *arg is result of reading the input pins */
val = cached_virtual_gpio_read;
val &= ~*dir_oe[priv->minor];
if (copy_to_user((unsigned long *)arg, &val, sizeof(val)))
return -EFAULT;
return 0;
break;
case IO_READ_OUTBITS:
/* *arg is result of reading the output shadow */
i2c_read(VIRT_I2C_ADDR, (void *)&val, sizeof(val));
val &= *dir_oe[priv->minor];
if (copy_to_user((unsigned long *)arg, &val, sizeof(val)))
return -EFAULT;
break;
case IO_SETGET_INPUT:
{
/* bits set in *arg is set to input,
* *arg updated with current input pins.
*/
unsigned short input_mask = ~*dir_oe[priv->minor];
if (copy_from_user(&val, (unsigned long *)arg, sizeof(val)))
return -EFAULT;
val = setget_input(priv, val);
if (copy_to_user((unsigned long *)arg, &val, sizeof(val)))
return -EFAULT;
if ((input_mask & val) != input_mask) {
/* Input pins changed. All ports desired as input
* should be set to logic 1.
*/
unsigned short change = input_mask ^ val;
i2c_read(VIRT_I2C_ADDR, (void *)&shadow,
sizeof(shadow));
shadow &= ~change;
shadow |= val;
i2c_write(VIRT_I2C_ADDR, (void *)&shadow,
sizeof(shadow));
}
break;
}
case IO_SETGET_OUTPUT:
/* bits set in *arg is set to output,
* *arg updated with current output pins.
*/
if (copy_from_user(&val, (unsigned long *)arg, sizeof(val)))
return -EFAULT;
val = setget_output(priv, val);
if (copy_to_user((unsigned long *)arg, &val, sizeof(val)))
return -EFAULT;
break;
default:
return -EINVAL;
} /* switch */
return 0;
}
#endif /* CONFIG_ETRAX_VIRTUAL_GPIO */
static int
gpio_leds_ioctl(unsigned int cmd, unsigned long arg)
{
unsigned char green;
unsigned char red;
switch (_IOC_NR(cmd)) {
case IO_LEDACTIVE_SET:
green = ((unsigned char) arg) & 1;
red = (((unsigned char) arg) >> 1) & 1;
CRIS_LED_ACTIVE_SET_G(green);
CRIS_LED_ACTIVE_SET_R(red);
break;
default:
return -EINVAL;
} /* switch */
return 0;
}
static const struct file_operations gpio_fops = {
.owner = THIS_MODULE,
.poll = gpio_poll,
.unlocked_ioctl = gpio_ioctl,
.write = gpio_write,
.open = gpio_open,
.release = gpio_release,
.llseek = noop_llseek,
};
#ifdef CONFIG_ETRAX_VIRTUAL_GPIO
static void
virtual_gpio_init(void)
{
reg_gio_rw_intr_cfg intr_cfg;
reg_gio_rw_intr_mask intr_mask;
unsigned short shadow;
shadow = ~virtual_rw_pv_oe; /* Input ports should be set to logic 1 */
shadow |= CONFIG_ETRAX_DEF_GIO_PV_OUT;
i2c_write(VIRT_I2C_ADDR, (void *)&shadow, sizeof(shadow));
/* Set interrupt mask and on what state the interrupt shall trigger.
* For virtual gpio the interrupt shall trigger on logic '0'.
*/
intr_cfg = REG_RD(gio, regi_gio, rw_intr_cfg);
intr_mask = REG_RD(gio, regi_gio, rw_intr_mask);
switch (CONFIG_ETRAX_VIRTUAL_GPIO_INTERRUPT_PA_PIN) {
case 0:
intr_cfg.pa0 = regk_gio_lo;
intr_mask.pa0 = regk_gio_yes;
break;
case 1:
intr_cfg.pa1 = regk_gio_lo;
intr_mask.pa1 = regk_gio_yes;
break;
case 2:
intr_cfg.pa2 = regk_gio_lo;
intr_mask.pa2 = regk_gio_yes;
break;
case 3:
intr_cfg.pa3 = regk_gio_lo;
intr_mask.pa3 = regk_gio_yes;
break;
case 4:
intr_cfg.pa4 = regk_gio_lo;
intr_mask.pa4 = regk_gio_yes;
break;
case 5:
intr_cfg.pa5 = regk_gio_lo;
intr_mask.pa5 = regk_gio_yes;
break;
case 6:
intr_cfg.pa6 = regk_gio_lo;
intr_mask.pa6 = regk_gio_yes;
break;
case 7:
intr_cfg.pa7 = regk_gio_lo;
intr_mask.pa7 = regk_gio_yes;
break;
}
REG_WR(gio, regi_gio, rw_intr_cfg, intr_cfg);
REG_WR(gio, regi_gio, rw_intr_mask, intr_mask);
gpio_pa_low_alarms |= (1 << CONFIG_ETRAX_VIRTUAL_GPIO_INTERRUPT_PA_PIN);
gpio_some_alarms = 1;
}
#endif
/* main driver initialization routine, called from mem.c */
static __init int
gpio_init(void)
{
int res;
/* do the formalities */
res = register_chrdev(GPIO_MAJOR, gpio_name, &gpio_fops);
if (res < 0) {
printk(KERN_ERR "gpio: couldn't get a major number.\n");
return res;
}
/* Clear all leds */
CRIS_LED_NETWORK_GRP0_SET(0);
CRIS_LED_NETWORK_GRP1_SET(0);
CRIS_LED_ACTIVE_SET(0);
CRIS_LED_DISK_READ(0);
CRIS_LED_DISK_WRITE(0);
printk(KERN_INFO "ETRAX FS GPIO driver v2.5, (c) 2003-2007 "
"Axis Communications AB\n");
/* We call etrax_gpio_wake_up_check() from timer interrupt and
* from cpu_idle() in kernel/process.c
* The check in cpu_idle() reduces latency from ~15 ms to ~6 ms
* in some tests.
*/
if (request_irq(TIMER0_INTR_VECT, gpio_poll_timer_interrupt,
IRQF_SHARED | IRQF_DISABLED, "gpio poll", &alarmlist))
printk(KERN_ERR "timer0 irq for gpio\n");
if (request_irq(GIO_INTR_VECT, gpio_pa_interrupt,
IRQF_SHARED | IRQF_DISABLED, "gpio PA", &alarmlist))
printk(KERN_ERR "PA irq for gpio\n");
#ifdef CONFIG_ETRAX_VIRTUAL_GPIO
virtual_gpio_init();
#endif
return res;
}
/* this makes sure that gpio_init is called during kernel boot */
module_init(gpio_init);
| gpl-2.0 |
klabit87/jflte_vzw_of1 | sound/pci/oxygen/oxygen_mixer.c | 7415 | 31796 | /*
* C-Media CMI8788 driver - mixer code
*
* Copyright (c) Clemens Ladisch <clemens@ladisch.de>
*
*
* This driver is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2.
*
* This driver 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 driver; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/mutex.h>
#include <sound/ac97_codec.h>
#include <sound/asoundef.h>
#include <sound/control.h>
#include <sound/tlv.h>
#include "oxygen.h"
#include "cm9780.h"
static int dac_volume_info(struct snd_kcontrol *ctl,
struct snd_ctl_elem_info *info)
{
struct oxygen *chip = ctl->private_data;
info->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
info->count = chip->model.dac_channels_mixer;
info->value.integer.min = chip->model.dac_volume_min;
info->value.integer.max = chip->model.dac_volume_max;
return 0;
}
static int dac_volume_get(struct snd_kcontrol *ctl,
struct snd_ctl_elem_value *value)
{
struct oxygen *chip = ctl->private_data;
unsigned int i;
mutex_lock(&chip->mutex);
for (i = 0; i < chip->model.dac_channels_mixer; ++i)
value->value.integer.value[i] = chip->dac_volume[i];
mutex_unlock(&chip->mutex);
return 0;
}
static int dac_volume_put(struct snd_kcontrol *ctl,
struct snd_ctl_elem_value *value)
{
struct oxygen *chip = ctl->private_data;
unsigned int i;
int changed;
changed = 0;
mutex_lock(&chip->mutex);
for (i = 0; i < chip->model.dac_channels_mixer; ++i)
if (value->value.integer.value[i] != chip->dac_volume[i]) {
chip->dac_volume[i] = value->value.integer.value[i];
changed = 1;
}
if (changed)
chip->model.update_dac_volume(chip);
mutex_unlock(&chip->mutex);
return changed;
}
static int dac_mute_get(struct snd_kcontrol *ctl,
struct snd_ctl_elem_value *value)
{
struct oxygen *chip = ctl->private_data;
mutex_lock(&chip->mutex);
value->value.integer.value[0] = !chip->dac_mute;
mutex_unlock(&chip->mutex);
return 0;
}
static int dac_mute_put(struct snd_kcontrol *ctl,
struct snd_ctl_elem_value *value)
{
struct oxygen *chip = ctl->private_data;
int changed;
mutex_lock(&chip->mutex);
changed = !value->value.integer.value[0] != chip->dac_mute;
if (changed) {
chip->dac_mute = !value->value.integer.value[0];
chip->model.update_dac_mute(chip);
}
mutex_unlock(&chip->mutex);
return changed;
}
static unsigned int upmix_item_count(struct oxygen *chip)
{
if (chip->model.dac_channels_pcm < 8)
return 2;
else if (chip->model.update_center_lfe_mix)
return 5;
else
return 3;
}
static int upmix_info(struct snd_kcontrol *ctl, struct snd_ctl_elem_info *info)
{
static const char *const names[5] = {
"Front",
"Front+Surround",
"Front+Surround+Back",
"Front+Surround+Center/LFE",
"Front+Surround+Center/LFE+Back",
};
struct oxygen *chip = ctl->private_data;
unsigned int count = upmix_item_count(chip);
return snd_ctl_enum_info(info, 1, count, names);
}
static int upmix_get(struct snd_kcontrol *ctl, struct snd_ctl_elem_value *value)
{
struct oxygen *chip = ctl->private_data;
mutex_lock(&chip->mutex);
value->value.enumerated.item[0] = chip->dac_routing;
mutex_unlock(&chip->mutex);
return 0;
}
void oxygen_update_dac_routing(struct oxygen *chip)
{
/* DAC 0: front, DAC 1: surround, DAC 2: center/LFE, DAC 3: back */
static const unsigned int reg_values[5] = {
/* stereo -> front */
(0 << OXYGEN_PLAY_DAC0_SOURCE_SHIFT) |
(1 << OXYGEN_PLAY_DAC1_SOURCE_SHIFT) |
(2 << OXYGEN_PLAY_DAC2_SOURCE_SHIFT) |
(3 << OXYGEN_PLAY_DAC3_SOURCE_SHIFT),
/* stereo -> front+surround */
(0 << OXYGEN_PLAY_DAC0_SOURCE_SHIFT) |
(0 << OXYGEN_PLAY_DAC1_SOURCE_SHIFT) |
(2 << OXYGEN_PLAY_DAC2_SOURCE_SHIFT) |
(3 << OXYGEN_PLAY_DAC3_SOURCE_SHIFT),
/* stereo -> front+surround+back */
(0 << OXYGEN_PLAY_DAC0_SOURCE_SHIFT) |
(0 << OXYGEN_PLAY_DAC1_SOURCE_SHIFT) |
(2 << OXYGEN_PLAY_DAC2_SOURCE_SHIFT) |
(0 << OXYGEN_PLAY_DAC3_SOURCE_SHIFT),
/* stereo -> front+surround+center/LFE */
(0 << OXYGEN_PLAY_DAC0_SOURCE_SHIFT) |
(0 << OXYGEN_PLAY_DAC1_SOURCE_SHIFT) |
(0 << OXYGEN_PLAY_DAC2_SOURCE_SHIFT) |
(3 << OXYGEN_PLAY_DAC3_SOURCE_SHIFT),
/* stereo -> front+surround+center/LFE+back */
(0 << OXYGEN_PLAY_DAC0_SOURCE_SHIFT) |
(0 << OXYGEN_PLAY_DAC1_SOURCE_SHIFT) |
(0 << OXYGEN_PLAY_DAC2_SOURCE_SHIFT) |
(0 << OXYGEN_PLAY_DAC3_SOURCE_SHIFT),
};
u8 channels;
unsigned int reg_value;
channels = oxygen_read8(chip, OXYGEN_PLAY_CHANNELS) &
OXYGEN_PLAY_CHANNELS_MASK;
if (channels == OXYGEN_PLAY_CHANNELS_2)
reg_value = reg_values[chip->dac_routing];
else if (channels == OXYGEN_PLAY_CHANNELS_8)
/* in 7.1 mode, "rear" channels go to the "back" jack */
reg_value = (0 << OXYGEN_PLAY_DAC0_SOURCE_SHIFT) |
(3 << OXYGEN_PLAY_DAC1_SOURCE_SHIFT) |
(2 << OXYGEN_PLAY_DAC2_SOURCE_SHIFT) |
(1 << OXYGEN_PLAY_DAC3_SOURCE_SHIFT);
else
reg_value = (0 << OXYGEN_PLAY_DAC0_SOURCE_SHIFT) |
(1 << OXYGEN_PLAY_DAC1_SOURCE_SHIFT) |
(2 << OXYGEN_PLAY_DAC2_SOURCE_SHIFT) |
(3 << OXYGEN_PLAY_DAC3_SOURCE_SHIFT);
if (chip->model.adjust_dac_routing)
reg_value = chip->model.adjust_dac_routing(chip, reg_value);
oxygen_write16_masked(chip, OXYGEN_PLAY_ROUTING, reg_value,
OXYGEN_PLAY_DAC0_SOURCE_MASK |
OXYGEN_PLAY_DAC1_SOURCE_MASK |
OXYGEN_PLAY_DAC2_SOURCE_MASK |
OXYGEN_PLAY_DAC3_SOURCE_MASK);
if (chip->model.update_center_lfe_mix)
chip->model.update_center_lfe_mix(chip, chip->dac_routing > 2);
}
static int upmix_put(struct snd_kcontrol *ctl, struct snd_ctl_elem_value *value)
{
struct oxygen *chip = ctl->private_data;
unsigned int count = upmix_item_count(chip);
int changed;
if (value->value.enumerated.item[0] >= count)
return -EINVAL;
mutex_lock(&chip->mutex);
changed = value->value.enumerated.item[0] != chip->dac_routing;
if (changed) {
chip->dac_routing = value->value.enumerated.item[0];
oxygen_update_dac_routing(chip);
}
mutex_unlock(&chip->mutex);
return changed;
}
static int spdif_switch_get(struct snd_kcontrol *ctl,
struct snd_ctl_elem_value *value)
{
struct oxygen *chip = ctl->private_data;
mutex_lock(&chip->mutex);
value->value.integer.value[0] = chip->spdif_playback_enable;
mutex_unlock(&chip->mutex);
return 0;
}
static unsigned int oxygen_spdif_rate(unsigned int oxygen_rate)
{
switch (oxygen_rate) {
case OXYGEN_RATE_32000:
return IEC958_AES3_CON_FS_32000 << OXYGEN_SPDIF_CS_RATE_SHIFT;
case OXYGEN_RATE_44100:
return IEC958_AES3_CON_FS_44100 << OXYGEN_SPDIF_CS_RATE_SHIFT;
default: /* OXYGEN_RATE_48000 */
return IEC958_AES3_CON_FS_48000 << OXYGEN_SPDIF_CS_RATE_SHIFT;
case OXYGEN_RATE_64000:
return 0xb << OXYGEN_SPDIF_CS_RATE_SHIFT;
case OXYGEN_RATE_88200:
return IEC958_AES3_CON_FS_88200 << OXYGEN_SPDIF_CS_RATE_SHIFT;
case OXYGEN_RATE_96000:
return IEC958_AES3_CON_FS_96000 << OXYGEN_SPDIF_CS_RATE_SHIFT;
case OXYGEN_RATE_176400:
return IEC958_AES3_CON_FS_176400 << OXYGEN_SPDIF_CS_RATE_SHIFT;
case OXYGEN_RATE_192000:
return IEC958_AES3_CON_FS_192000 << OXYGEN_SPDIF_CS_RATE_SHIFT;
}
}
void oxygen_update_spdif_source(struct oxygen *chip)
{
u32 old_control, new_control;
u16 old_routing, new_routing;
unsigned int oxygen_rate;
old_control = oxygen_read32(chip, OXYGEN_SPDIF_CONTROL);
old_routing = oxygen_read16(chip, OXYGEN_PLAY_ROUTING);
if (chip->pcm_active & (1 << PCM_SPDIF)) {
new_control = old_control | OXYGEN_SPDIF_OUT_ENABLE;
new_routing = (old_routing & ~OXYGEN_PLAY_SPDIF_MASK)
| OXYGEN_PLAY_SPDIF_SPDIF;
oxygen_rate = (old_control >> OXYGEN_SPDIF_OUT_RATE_SHIFT)
& OXYGEN_I2S_RATE_MASK;
/* S/PDIF rate was already set by the caller */
} else if ((chip->pcm_active & (1 << PCM_MULTICH)) &&
chip->spdif_playback_enable) {
new_routing = (old_routing & ~OXYGEN_PLAY_SPDIF_MASK)
| OXYGEN_PLAY_SPDIF_MULTICH_01;
oxygen_rate = oxygen_read16(chip, OXYGEN_I2S_MULTICH_FORMAT)
& OXYGEN_I2S_RATE_MASK;
new_control = (old_control & ~OXYGEN_SPDIF_OUT_RATE_MASK) |
(oxygen_rate << OXYGEN_SPDIF_OUT_RATE_SHIFT) |
OXYGEN_SPDIF_OUT_ENABLE;
} else {
new_control = old_control & ~OXYGEN_SPDIF_OUT_ENABLE;
new_routing = old_routing;
oxygen_rate = OXYGEN_RATE_44100;
}
if (old_routing != new_routing) {
oxygen_write32(chip, OXYGEN_SPDIF_CONTROL,
new_control & ~OXYGEN_SPDIF_OUT_ENABLE);
oxygen_write16(chip, OXYGEN_PLAY_ROUTING, new_routing);
}
if (new_control & OXYGEN_SPDIF_OUT_ENABLE)
oxygen_write32(chip, OXYGEN_SPDIF_OUTPUT_BITS,
oxygen_spdif_rate(oxygen_rate) |
((chip->pcm_active & (1 << PCM_SPDIF)) ?
chip->spdif_pcm_bits : chip->spdif_bits));
oxygen_write32(chip, OXYGEN_SPDIF_CONTROL, new_control);
}
static int spdif_switch_put(struct snd_kcontrol *ctl,
struct snd_ctl_elem_value *value)
{
struct oxygen *chip = ctl->private_data;
int changed;
mutex_lock(&chip->mutex);
changed = value->value.integer.value[0] != chip->spdif_playback_enable;
if (changed) {
chip->spdif_playback_enable = !!value->value.integer.value[0];
spin_lock_irq(&chip->reg_lock);
oxygen_update_spdif_source(chip);
spin_unlock_irq(&chip->reg_lock);
}
mutex_unlock(&chip->mutex);
return changed;
}
static int spdif_info(struct snd_kcontrol *ctl, struct snd_ctl_elem_info *info)
{
info->type = SNDRV_CTL_ELEM_TYPE_IEC958;
info->count = 1;
return 0;
}
static void oxygen_to_iec958(u32 bits, struct snd_ctl_elem_value *value)
{
value->value.iec958.status[0] =
bits & (OXYGEN_SPDIF_NONAUDIO | OXYGEN_SPDIF_C |
OXYGEN_SPDIF_PREEMPHASIS);
value->value.iec958.status[1] = /* category and original */
bits >> OXYGEN_SPDIF_CATEGORY_SHIFT;
}
static u32 iec958_to_oxygen(struct snd_ctl_elem_value *value)
{
u32 bits;
bits = value->value.iec958.status[0] &
(OXYGEN_SPDIF_NONAUDIO | OXYGEN_SPDIF_C |
OXYGEN_SPDIF_PREEMPHASIS);
bits |= value->value.iec958.status[1] << OXYGEN_SPDIF_CATEGORY_SHIFT;
if (bits & OXYGEN_SPDIF_NONAUDIO)
bits |= OXYGEN_SPDIF_V;
return bits;
}
static inline void write_spdif_bits(struct oxygen *chip, u32 bits)
{
oxygen_write32_masked(chip, OXYGEN_SPDIF_OUTPUT_BITS, bits,
OXYGEN_SPDIF_NONAUDIO |
OXYGEN_SPDIF_C |
OXYGEN_SPDIF_PREEMPHASIS |
OXYGEN_SPDIF_CATEGORY_MASK |
OXYGEN_SPDIF_ORIGINAL |
OXYGEN_SPDIF_V);
}
static int spdif_default_get(struct snd_kcontrol *ctl,
struct snd_ctl_elem_value *value)
{
struct oxygen *chip = ctl->private_data;
mutex_lock(&chip->mutex);
oxygen_to_iec958(chip->spdif_bits, value);
mutex_unlock(&chip->mutex);
return 0;
}
static int spdif_default_put(struct snd_kcontrol *ctl,
struct snd_ctl_elem_value *value)
{
struct oxygen *chip = ctl->private_data;
u32 new_bits;
int changed;
new_bits = iec958_to_oxygen(value);
mutex_lock(&chip->mutex);
changed = new_bits != chip->spdif_bits;
if (changed) {
chip->spdif_bits = new_bits;
if (!(chip->pcm_active & (1 << PCM_SPDIF)))
write_spdif_bits(chip, new_bits);
}
mutex_unlock(&chip->mutex);
return changed;
}
static int spdif_mask_get(struct snd_kcontrol *ctl,
struct snd_ctl_elem_value *value)
{
value->value.iec958.status[0] = IEC958_AES0_NONAUDIO |
IEC958_AES0_CON_NOT_COPYRIGHT | IEC958_AES0_CON_EMPHASIS;
value->value.iec958.status[1] =
IEC958_AES1_CON_CATEGORY | IEC958_AES1_CON_ORIGINAL;
return 0;
}
static int spdif_pcm_get(struct snd_kcontrol *ctl,
struct snd_ctl_elem_value *value)
{
struct oxygen *chip = ctl->private_data;
mutex_lock(&chip->mutex);
oxygen_to_iec958(chip->spdif_pcm_bits, value);
mutex_unlock(&chip->mutex);
return 0;
}
static int spdif_pcm_put(struct snd_kcontrol *ctl,
struct snd_ctl_elem_value *value)
{
struct oxygen *chip = ctl->private_data;
u32 new_bits;
int changed;
new_bits = iec958_to_oxygen(value);
mutex_lock(&chip->mutex);
changed = new_bits != chip->spdif_pcm_bits;
if (changed) {
chip->spdif_pcm_bits = new_bits;
if (chip->pcm_active & (1 << PCM_SPDIF))
write_spdif_bits(chip, new_bits);
}
mutex_unlock(&chip->mutex);
return changed;
}
static int spdif_input_mask_get(struct snd_kcontrol *ctl,
struct snd_ctl_elem_value *value)
{
value->value.iec958.status[0] = 0xff;
value->value.iec958.status[1] = 0xff;
value->value.iec958.status[2] = 0xff;
value->value.iec958.status[3] = 0xff;
return 0;
}
static int spdif_input_default_get(struct snd_kcontrol *ctl,
struct snd_ctl_elem_value *value)
{
struct oxygen *chip = ctl->private_data;
u32 bits;
bits = oxygen_read32(chip, OXYGEN_SPDIF_INPUT_BITS);
value->value.iec958.status[0] = bits;
value->value.iec958.status[1] = bits >> 8;
value->value.iec958.status[2] = bits >> 16;
value->value.iec958.status[3] = bits >> 24;
return 0;
}
static int spdif_bit_switch_get(struct snd_kcontrol *ctl,
struct snd_ctl_elem_value *value)
{
struct oxygen *chip = ctl->private_data;
u32 bit = ctl->private_value;
value->value.integer.value[0] =
!!(oxygen_read32(chip, OXYGEN_SPDIF_CONTROL) & bit);
return 0;
}
static int spdif_bit_switch_put(struct snd_kcontrol *ctl,
struct snd_ctl_elem_value *value)
{
struct oxygen *chip = ctl->private_data;
u32 bit = ctl->private_value;
u32 oldreg, newreg;
int changed;
spin_lock_irq(&chip->reg_lock);
oldreg = oxygen_read32(chip, OXYGEN_SPDIF_CONTROL);
if (value->value.integer.value[0])
newreg = oldreg | bit;
else
newreg = oldreg & ~bit;
changed = newreg != oldreg;
if (changed)
oxygen_write32(chip, OXYGEN_SPDIF_CONTROL, newreg);
spin_unlock_irq(&chip->reg_lock);
return changed;
}
static int monitor_volume_info(struct snd_kcontrol *ctl,
struct snd_ctl_elem_info *info)
{
info->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
info->count = 1;
info->value.integer.min = 0;
info->value.integer.max = 1;
return 0;
}
static int monitor_get(struct snd_kcontrol *ctl,
struct snd_ctl_elem_value *value)
{
struct oxygen *chip = ctl->private_data;
u8 bit = ctl->private_value;
int invert = ctl->private_value & (1 << 8);
value->value.integer.value[0] =
!!invert ^ !!(oxygen_read8(chip, OXYGEN_ADC_MONITOR) & bit);
return 0;
}
static int monitor_put(struct snd_kcontrol *ctl,
struct snd_ctl_elem_value *value)
{
struct oxygen *chip = ctl->private_data;
u8 bit = ctl->private_value;
int invert = ctl->private_value & (1 << 8);
u8 oldreg, newreg;
int changed;
spin_lock_irq(&chip->reg_lock);
oldreg = oxygen_read8(chip, OXYGEN_ADC_MONITOR);
if ((!!value->value.integer.value[0] ^ !!invert) != 0)
newreg = oldreg | bit;
else
newreg = oldreg & ~bit;
changed = newreg != oldreg;
if (changed)
oxygen_write8(chip, OXYGEN_ADC_MONITOR, newreg);
spin_unlock_irq(&chip->reg_lock);
return changed;
}
static int ac97_switch_get(struct snd_kcontrol *ctl,
struct snd_ctl_elem_value *value)
{
struct oxygen *chip = ctl->private_data;
unsigned int codec = (ctl->private_value >> 24) & 1;
unsigned int index = ctl->private_value & 0xff;
unsigned int bitnr = (ctl->private_value >> 8) & 0xff;
int invert = ctl->private_value & (1 << 16);
u16 reg;
mutex_lock(&chip->mutex);
reg = oxygen_read_ac97(chip, codec, index);
mutex_unlock(&chip->mutex);
if (!(reg & (1 << bitnr)) ^ !invert)
value->value.integer.value[0] = 1;
else
value->value.integer.value[0] = 0;
return 0;
}
static void mute_ac97_ctl(struct oxygen *chip, unsigned int control)
{
unsigned int priv_idx;
u16 value;
if (!chip->controls[control])
return;
priv_idx = chip->controls[control]->private_value & 0xff;
value = oxygen_read_ac97(chip, 0, priv_idx);
if (!(value & 0x8000)) {
oxygen_write_ac97(chip, 0, priv_idx, value | 0x8000);
if (chip->model.ac97_switch)
chip->model.ac97_switch(chip, priv_idx, 0x8000);
snd_ctl_notify(chip->card, SNDRV_CTL_EVENT_MASK_VALUE,
&chip->controls[control]->id);
}
}
static int ac97_switch_put(struct snd_kcontrol *ctl,
struct snd_ctl_elem_value *value)
{
struct oxygen *chip = ctl->private_data;
unsigned int codec = (ctl->private_value >> 24) & 1;
unsigned int index = ctl->private_value & 0xff;
unsigned int bitnr = (ctl->private_value >> 8) & 0xff;
int invert = ctl->private_value & (1 << 16);
u16 oldreg, newreg;
int change;
mutex_lock(&chip->mutex);
oldreg = oxygen_read_ac97(chip, codec, index);
newreg = oldreg;
if (!value->value.integer.value[0] ^ !invert)
newreg |= 1 << bitnr;
else
newreg &= ~(1 << bitnr);
change = newreg != oldreg;
if (change) {
oxygen_write_ac97(chip, codec, index, newreg);
if (codec == 0 && chip->model.ac97_switch)
chip->model.ac97_switch(chip, index, newreg & 0x8000);
if (index == AC97_LINE) {
oxygen_write_ac97_masked(chip, 0, CM9780_GPIO_STATUS,
newreg & 0x8000 ?
CM9780_GPO0 : 0, CM9780_GPO0);
if (!(newreg & 0x8000)) {
mute_ac97_ctl(chip, CONTROL_MIC_CAPTURE_SWITCH);
mute_ac97_ctl(chip, CONTROL_CD_CAPTURE_SWITCH);
mute_ac97_ctl(chip, CONTROL_AUX_CAPTURE_SWITCH);
}
} else if ((index == AC97_MIC || index == AC97_CD ||
index == AC97_VIDEO || index == AC97_AUX) &&
bitnr == 15 && !(newreg & 0x8000)) {
mute_ac97_ctl(chip, CONTROL_LINE_CAPTURE_SWITCH);
oxygen_write_ac97_masked(chip, 0, CM9780_GPIO_STATUS,
CM9780_GPO0, CM9780_GPO0);
}
}
mutex_unlock(&chip->mutex);
return change;
}
static int ac97_volume_info(struct snd_kcontrol *ctl,
struct snd_ctl_elem_info *info)
{
int stereo = (ctl->private_value >> 16) & 1;
info->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
info->count = stereo ? 2 : 1;
info->value.integer.min = 0;
info->value.integer.max = 0x1f;
return 0;
}
static int ac97_volume_get(struct snd_kcontrol *ctl,
struct snd_ctl_elem_value *value)
{
struct oxygen *chip = ctl->private_data;
unsigned int codec = (ctl->private_value >> 24) & 1;
int stereo = (ctl->private_value >> 16) & 1;
unsigned int index = ctl->private_value & 0xff;
u16 reg;
mutex_lock(&chip->mutex);
reg = oxygen_read_ac97(chip, codec, index);
mutex_unlock(&chip->mutex);
if (!stereo) {
value->value.integer.value[0] = 31 - (reg & 0x1f);
} else {
value->value.integer.value[0] = 31 - ((reg >> 8) & 0x1f);
value->value.integer.value[1] = 31 - (reg & 0x1f);
}
return 0;
}
static int ac97_volume_put(struct snd_kcontrol *ctl,
struct snd_ctl_elem_value *value)
{
struct oxygen *chip = ctl->private_data;
unsigned int codec = (ctl->private_value >> 24) & 1;
int stereo = (ctl->private_value >> 16) & 1;
unsigned int index = ctl->private_value & 0xff;
u16 oldreg, newreg;
int change;
mutex_lock(&chip->mutex);
oldreg = oxygen_read_ac97(chip, codec, index);
if (!stereo) {
newreg = oldreg & ~0x1f;
newreg |= 31 - (value->value.integer.value[0] & 0x1f);
} else {
newreg = oldreg & ~0x1f1f;
newreg |= (31 - (value->value.integer.value[0] & 0x1f)) << 8;
newreg |= 31 - (value->value.integer.value[1] & 0x1f);
}
change = newreg != oldreg;
if (change)
oxygen_write_ac97(chip, codec, index, newreg);
mutex_unlock(&chip->mutex);
return change;
}
static int mic_fmic_source_info(struct snd_kcontrol *ctl,
struct snd_ctl_elem_info *info)
{
static const char *const names[] = { "Mic Jack", "Front Panel" };
return snd_ctl_enum_info(info, 1, 2, names);
}
static int mic_fmic_source_get(struct snd_kcontrol *ctl,
struct snd_ctl_elem_value *value)
{
struct oxygen *chip = ctl->private_data;
mutex_lock(&chip->mutex);
value->value.enumerated.item[0] =
!!(oxygen_read_ac97(chip, 0, CM9780_JACK) & CM9780_FMIC2MIC);
mutex_unlock(&chip->mutex);
return 0;
}
static int mic_fmic_source_put(struct snd_kcontrol *ctl,
struct snd_ctl_elem_value *value)
{
struct oxygen *chip = ctl->private_data;
u16 oldreg, newreg;
int change;
mutex_lock(&chip->mutex);
oldreg = oxygen_read_ac97(chip, 0, CM9780_JACK);
if (value->value.enumerated.item[0])
newreg = oldreg | CM9780_FMIC2MIC;
else
newreg = oldreg & ~CM9780_FMIC2MIC;
change = newreg != oldreg;
if (change)
oxygen_write_ac97(chip, 0, CM9780_JACK, newreg);
mutex_unlock(&chip->mutex);
return change;
}
static int ac97_fp_rec_volume_info(struct snd_kcontrol *ctl,
struct snd_ctl_elem_info *info)
{
info->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
info->count = 2;
info->value.integer.min = 0;
info->value.integer.max = 7;
return 0;
}
static int ac97_fp_rec_volume_get(struct snd_kcontrol *ctl,
struct snd_ctl_elem_value *value)
{
struct oxygen *chip = ctl->private_data;
u16 reg;
mutex_lock(&chip->mutex);
reg = oxygen_read_ac97(chip, 1, AC97_REC_GAIN);
mutex_unlock(&chip->mutex);
value->value.integer.value[0] = reg & 7;
value->value.integer.value[1] = (reg >> 8) & 7;
return 0;
}
static int ac97_fp_rec_volume_put(struct snd_kcontrol *ctl,
struct snd_ctl_elem_value *value)
{
struct oxygen *chip = ctl->private_data;
u16 oldreg, newreg;
int change;
mutex_lock(&chip->mutex);
oldreg = oxygen_read_ac97(chip, 1, AC97_REC_GAIN);
newreg = oldreg & ~0x0707;
newreg = newreg | (value->value.integer.value[0] & 7);
newreg = newreg | ((value->value.integer.value[0] & 7) << 8);
change = newreg != oldreg;
if (change)
oxygen_write_ac97(chip, 1, AC97_REC_GAIN, newreg);
mutex_unlock(&chip->mutex);
return change;
}
#define AC97_SWITCH(xname, codec, index, bitnr, invert) { \
.iface = SNDRV_CTL_ELEM_IFACE_MIXER, \
.name = xname, \
.info = snd_ctl_boolean_mono_info, \
.get = ac97_switch_get, \
.put = ac97_switch_put, \
.private_value = ((codec) << 24) | ((invert) << 16) | \
((bitnr) << 8) | (index), \
}
#define AC97_VOLUME(xname, codec, index, stereo) { \
.iface = SNDRV_CTL_ELEM_IFACE_MIXER, \
.name = xname, \
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE | \
SNDRV_CTL_ELEM_ACCESS_TLV_READ, \
.info = ac97_volume_info, \
.get = ac97_volume_get, \
.put = ac97_volume_put, \
.tlv = { .p = ac97_db_scale, }, \
.private_value = ((codec) << 24) | ((stereo) << 16) | (index), \
}
static DECLARE_TLV_DB_SCALE(monitor_db_scale, -600, 600, 0);
static DECLARE_TLV_DB_SCALE(ac97_db_scale, -3450, 150, 0);
static DECLARE_TLV_DB_SCALE(ac97_rec_db_scale, 0, 150, 0);
static const struct snd_kcontrol_new controls[] = {
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Master Playback Volume",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.info = dac_volume_info,
.get = dac_volume_get,
.put = dac_volume_put,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Master Playback Switch",
.info = snd_ctl_boolean_mono_info,
.get = dac_mute_get,
.put = dac_mute_put,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Stereo Upmixing",
.info = upmix_info,
.get = upmix_get,
.put = upmix_put,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = SNDRV_CTL_NAME_IEC958("", PLAYBACK, SWITCH),
.info = snd_ctl_boolean_mono_info,
.get = spdif_switch_get,
.put = spdif_switch_put,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.device = 1,
.name = SNDRV_CTL_NAME_IEC958("", PLAYBACK, DEFAULT),
.info = spdif_info,
.get = spdif_default_get,
.put = spdif_default_put,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.device = 1,
.name = SNDRV_CTL_NAME_IEC958("", PLAYBACK, CON_MASK),
.access = SNDRV_CTL_ELEM_ACCESS_READ,
.info = spdif_info,
.get = spdif_mask_get,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.device = 1,
.name = SNDRV_CTL_NAME_IEC958("", PLAYBACK, PCM_STREAM),
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_INACTIVE,
.info = spdif_info,
.get = spdif_pcm_get,
.put = spdif_pcm_put,
},
};
static const struct snd_kcontrol_new spdif_input_controls[] = {
{
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.device = 1,
.name = SNDRV_CTL_NAME_IEC958("", CAPTURE, MASK),
.access = SNDRV_CTL_ELEM_ACCESS_READ,
.info = spdif_info,
.get = spdif_input_mask_get,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_PCM,
.device = 1,
.name = SNDRV_CTL_NAME_IEC958("", CAPTURE, DEFAULT),
.access = SNDRV_CTL_ELEM_ACCESS_READ,
.info = spdif_info,
.get = spdif_input_default_get,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = SNDRV_CTL_NAME_IEC958("Loopback ", NONE, SWITCH),
.info = snd_ctl_boolean_mono_info,
.get = spdif_bit_switch_get,
.put = spdif_bit_switch_put,
.private_value = OXYGEN_SPDIF_LOOPBACK,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = SNDRV_CTL_NAME_IEC958("Validity Check ",CAPTURE,SWITCH),
.info = snd_ctl_boolean_mono_info,
.get = spdif_bit_switch_get,
.put = spdif_bit_switch_put,
.private_value = OXYGEN_SPDIF_SPDVALID,
},
};
static const struct {
unsigned int pcm_dev;
struct snd_kcontrol_new controls[2];
} monitor_controls[] = {
{
.pcm_dev = CAPTURE_0_FROM_I2S_1,
.controls = {
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Analog Input Monitor Playback Switch",
.info = snd_ctl_boolean_mono_info,
.get = monitor_get,
.put = monitor_put,
.private_value = OXYGEN_ADC_MONITOR_A,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Analog Input Monitor Playback Volume",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_TLV_READ,
.info = monitor_volume_info,
.get = monitor_get,
.put = monitor_put,
.private_value = OXYGEN_ADC_MONITOR_A_HALF_VOL
| (1 << 8),
.tlv = { .p = monitor_db_scale, },
},
},
},
{
.pcm_dev = CAPTURE_0_FROM_I2S_2,
.controls = {
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Analog Input Monitor Playback Switch",
.info = snd_ctl_boolean_mono_info,
.get = monitor_get,
.put = monitor_put,
.private_value = OXYGEN_ADC_MONITOR_B,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Analog Input Monitor Playback Volume",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_TLV_READ,
.info = monitor_volume_info,
.get = monitor_get,
.put = monitor_put,
.private_value = OXYGEN_ADC_MONITOR_B_HALF_VOL
| (1 << 8),
.tlv = { .p = monitor_db_scale, },
},
},
},
{
.pcm_dev = CAPTURE_2_FROM_I2S_2,
.controls = {
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Analog Input Monitor Playback Switch",
.index = 1,
.info = snd_ctl_boolean_mono_info,
.get = monitor_get,
.put = monitor_put,
.private_value = OXYGEN_ADC_MONITOR_B,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Analog Input Monitor Playback Volume",
.index = 1,
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_TLV_READ,
.info = monitor_volume_info,
.get = monitor_get,
.put = monitor_put,
.private_value = OXYGEN_ADC_MONITOR_B_HALF_VOL
| (1 << 8),
.tlv = { .p = monitor_db_scale, },
},
},
},
{
.pcm_dev = CAPTURE_1_FROM_SPDIF,
.controls = {
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Digital Input Monitor Playback Switch",
.info = snd_ctl_boolean_mono_info,
.get = monitor_get,
.put = monitor_put,
.private_value = OXYGEN_ADC_MONITOR_C,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Digital Input Monitor Playback Volume",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_TLV_READ,
.info = monitor_volume_info,
.get = monitor_get,
.put = monitor_put,
.private_value = OXYGEN_ADC_MONITOR_C_HALF_VOL
| (1 << 8),
.tlv = { .p = monitor_db_scale, },
},
},
},
};
static const struct snd_kcontrol_new ac97_controls[] = {
AC97_VOLUME("Mic Capture Volume", 0, AC97_MIC, 0),
AC97_SWITCH("Mic Capture Switch", 0, AC97_MIC, 15, 1),
AC97_SWITCH("Mic Boost (+20dB)", 0, AC97_MIC, 6, 0),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Mic Source Capture Enum",
.info = mic_fmic_source_info,
.get = mic_fmic_source_get,
.put = mic_fmic_source_put,
},
AC97_SWITCH("Line Capture Switch", 0, AC97_LINE, 15, 1),
AC97_VOLUME("CD Capture Volume", 0, AC97_CD, 1),
AC97_SWITCH("CD Capture Switch", 0, AC97_CD, 15, 1),
AC97_VOLUME("Aux Capture Volume", 0, AC97_AUX, 1),
AC97_SWITCH("Aux Capture Switch", 0, AC97_AUX, 15, 1),
};
static const struct snd_kcontrol_new ac97_fp_controls[] = {
AC97_VOLUME("Front Panel Playback Volume", 1, AC97_HEADPHONE, 1),
AC97_SWITCH("Front Panel Playback Switch", 1, AC97_HEADPHONE, 15, 1),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Front Panel Capture Volume",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_TLV_READ,
.info = ac97_fp_rec_volume_info,
.get = ac97_fp_rec_volume_get,
.put = ac97_fp_rec_volume_put,
.tlv = { .p = ac97_rec_db_scale, },
},
AC97_SWITCH("Front Panel Capture Switch", 1, AC97_REC_GAIN, 15, 1),
};
static void oxygen_any_ctl_free(struct snd_kcontrol *ctl)
{
struct oxygen *chip = ctl->private_data;
unsigned int i;
/* I'm too lazy to write a function for each control :-) */
for (i = 0; i < ARRAY_SIZE(chip->controls); ++i)
chip->controls[i] = NULL;
}
static int add_controls(struct oxygen *chip,
const struct snd_kcontrol_new controls[],
unsigned int count)
{
static const char *const known_ctl_names[CONTROL_COUNT] = {
[CONTROL_SPDIF_PCM] =
SNDRV_CTL_NAME_IEC958("", PLAYBACK, PCM_STREAM),
[CONTROL_SPDIF_INPUT_BITS] =
SNDRV_CTL_NAME_IEC958("", CAPTURE, DEFAULT),
[CONTROL_MIC_CAPTURE_SWITCH] = "Mic Capture Switch",
[CONTROL_LINE_CAPTURE_SWITCH] = "Line Capture Switch",
[CONTROL_CD_CAPTURE_SWITCH] = "CD Capture Switch",
[CONTROL_AUX_CAPTURE_SWITCH] = "Aux Capture Switch",
};
unsigned int i, j;
struct snd_kcontrol_new template;
struct snd_kcontrol *ctl;
int err;
for (i = 0; i < count; ++i) {
template = controls[i];
if (chip->model.control_filter) {
err = chip->model.control_filter(&template);
if (err < 0)
return err;
if (err == 1)
continue;
}
if (!strcmp(template.name, "Stereo Upmixing") &&
chip->model.dac_channels_pcm == 2)
continue;
if (!strcmp(template.name, "Mic Source Capture Enum") &&
!(chip->model.device_config & AC97_FMIC_SWITCH))
continue;
if (!strncmp(template.name, "CD Capture ", 11) &&
!(chip->model.device_config & AC97_CD_INPUT))
continue;
if (!strcmp(template.name, "Master Playback Volume") &&
chip->model.dac_tlv) {
template.tlv.p = chip->model.dac_tlv;
template.access |= SNDRV_CTL_ELEM_ACCESS_TLV_READ;
}
ctl = snd_ctl_new1(&template, chip);
if (!ctl)
return -ENOMEM;
err = snd_ctl_add(chip->card, ctl);
if (err < 0)
return err;
for (j = 0; j < CONTROL_COUNT; ++j)
if (!strcmp(ctl->id.name, known_ctl_names[j])) {
chip->controls[j] = ctl;
ctl->private_free = oxygen_any_ctl_free;
}
}
return 0;
}
int oxygen_mixer_init(struct oxygen *chip)
{
unsigned int i;
int err;
err = add_controls(chip, controls, ARRAY_SIZE(controls));
if (err < 0)
return err;
if (chip->model.device_config & CAPTURE_1_FROM_SPDIF) {
err = add_controls(chip, spdif_input_controls,
ARRAY_SIZE(spdif_input_controls));
if (err < 0)
return err;
}
for (i = 0; i < ARRAY_SIZE(monitor_controls); ++i) {
if (!(chip->model.device_config & monitor_controls[i].pcm_dev))
continue;
err = add_controls(chip, monitor_controls[i].controls,
ARRAY_SIZE(monitor_controls[i].controls));
if (err < 0)
return err;
}
if (chip->has_ac97_0) {
err = add_controls(chip, ac97_controls,
ARRAY_SIZE(ac97_controls));
if (err < 0)
return err;
}
if (chip->has_ac97_1) {
err = add_controls(chip, ac97_fp_controls,
ARRAY_SIZE(ac97_fp_controls));
if (err < 0)
return err;
}
return chip->model.mixer_init ? chip->model.mixer_init(chip) : 0;
}
| gpl-2.0 |
abev66/linux-kernel-vta2-ns | drivers/video/cg6.c | 8183 | 22315 | /* cg6.c: CGSIX (GX, GXplus, TGX) frame buffer driver
*
* Copyright (C) 2003, 2006 David S. Miller (davem@davemloft.net)
* Copyright (C) 1996,1998 Jakub Jelinek (jj@ultra.linux.cz)
* Copyright (C) 1996 Miguel de Icaza (miguel@nuclecu.unam.mx)
* Copyright (C) 1996 Eddie C. Dost (ecd@skynet.be)
*
* Driver layout based loosely on tgafb.c, see that file for credits.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/fb.h>
#include <linux/mm.h>
#include <linux/of_device.h>
#include <asm/io.h>
#include <asm/fbio.h>
#include "sbuslib.h"
/*
* Local functions.
*/
static int cg6_setcolreg(unsigned, unsigned, unsigned, unsigned,
unsigned, struct fb_info *);
static int cg6_blank(int, struct fb_info *);
static void cg6_imageblit(struct fb_info *, const struct fb_image *);
static void cg6_fillrect(struct fb_info *, const struct fb_fillrect *);
static void cg6_copyarea(struct fb_info *info, const struct fb_copyarea *area);
static int cg6_sync(struct fb_info *);
static int cg6_mmap(struct fb_info *, struct vm_area_struct *);
static int cg6_ioctl(struct fb_info *, unsigned int, unsigned long);
static int cg6_pan_display(struct fb_var_screeninfo *, struct fb_info *);
/*
* Frame buffer operations
*/
static struct fb_ops cg6_ops = {
.owner = THIS_MODULE,
.fb_setcolreg = cg6_setcolreg,
.fb_blank = cg6_blank,
.fb_pan_display = cg6_pan_display,
.fb_fillrect = cg6_fillrect,
.fb_copyarea = cg6_copyarea,
.fb_imageblit = cg6_imageblit,
.fb_sync = cg6_sync,
.fb_mmap = cg6_mmap,
.fb_ioctl = cg6_ioctl,
#ifdef CONFIG_COMPAT
.fb_compat_ioctl = sbusfb_compat_ioctl,
#endif
};
/* Offset of interesting structures in the OBIO space */
/*
* Brooktree is the video dac and is funny to program on the cg6.
* (it's even funnier on the cg3)
* The FBC could be the frame buffer control
* The FHC could is the frame buffer hardware control.
*/
#define CG6_ROM_OFFSET 0x0UL
#define CG6_BROOKTREE_OFFSET 0x200000UL
#define CG6_DHC_OFFSET 0x240000UL
#define CG6_ALT_OFFSET 0x280000UL
#define CG6_FHC_OFFSET 0x300000UL
#define CG6_THC_OFFSET 0x301000UL
#define CG6_FBC_OFFSET 0x700000UL
#define CG6_TEC_OFFSET 0x701000UL
#define CG6_RAM_OFFSET 0x800000UL
/* FHC definitions */
#define CG6_FHC_FBID_SHIFT 24
#define CG6_FHC_FBID_MASK 255
#define CG6_FHC_REV_SHIFT 20
#define CG6_FHC_REV_MASK 15
#define CG6_FHC_FROP_DISABLE (1 << 19)
#define CG6_FHC_ROW_DISABLE (1 << 18)
#define CG6_FHC_SRC_DISABLE (1 << 17)
#define CG6_FHC_DST_DISABLE (1 << 16)
#define CG6_FHC_RESET (1 << 15)
#define CG6_FHC_LITTLE_ENDIAN (1 << 13)
#define CG6_FHC_RES_MASK (3 << 11)
#define CG6_FHC_1024 (0 << 11)
#define CG6_FHC_1152 (1 << 11)
#define CG6_FHC_1280 (2 << 11)
#define CG6_FHC_1600 (3 << 11)
#define CG6_FHC_CPU_MASK (3 << 9)
#define CG6_FHC_CPU_SPARC (0 << 9)
#define CG6_FHC_CPU_68020 (1 << 9)
#define CG6_FHC_CPU_386 (2 << 9)
#define CG6_FHC_TEST (1 << 8)
#define CG6_FHC_TEST_X_SHIFT 4
#define CG6_FHC_TEST_X_MASK 15
#define CG6_FHC_TEST_Y_SHIFT 0
#define CG6_FHC_TEST_Y_MASK 15
/* FBC mode definitions */
#define CG6_FBC_BLIT_IGNORE 0x00000000
#define CG6_FBC_BLIT_NOSRC 0x00100000
#define CG6_FBC_BLIT_SRC 0x00200000
#define CG6_FBC_BLIT_ILLEGAL 0x00300000
#define CG6_FBC_BLIT_MASK 0x00300000
#define CG6_FBC_VBLANK 0x00080000
#define CG6_FBC_MODE_IGNORE 0x00000000
#define CG6_FBC_MODE_COLOR8 0x00020000
#define CG6_FBC_MODE_COLOR1 0x00040000
#define CG6_FBC_MODE_HRMONO 0x00060000
#define CG6_FBC_MODE_MASK 0x00060000
#define CG6_FBC_DRAW_IGNORE 0x00000000
#define CG6_FBC_DRAW_RENDER 0x00008000
#define CG6_FBC_DRAW_PICK 0x00010000
#define CG6_FBC_DRAW_ILLEGAL 0x00018000
#define CG6_FBC_DRAW_MASK 0x00018000
#define CG6_FBC_BWRITE0_IGNORE 0x00000000
#define CG6_FBC_BWRITE0_ENABLE 0x00002000
#define CG6_FBC_BWRITE0_DISABLE 0x00004000
#define CG6_FBC_BWRITE0_ILLEGAL 0x00006000
#define CG6_FBC_BWRITE0_MASK 0x00006000
#define CG6_FBC_BWRITE1_IGNORE 0x00000000
#define CG6_FBC_BWRITE1_ENABLE 0x00000800
#define CG6_FBC_BWRITE1_DISABLE 0x00001000
#define CG6_FBC_BWRITE1_ILLEGAL 0x00001800
#define CG6_FBC_BWRITE1_MASK 0x00001800
#define CG6_FBC_BREAD_IGNORE 0x00000000
#define CG6_FBC_BREAD_0 0x00000200
#define CG6_FBC_BREAD_1 0x00000400
#define CG6_FBC_BREAD_ILLEGAL 0x00000600
#define CG6_FBC_BREAD_MASK 0x00000600
#define CG6_FBC_BDISP_IGNORE 0x00000000
#define CG6_FBC_BDISP_0 0x00000080
#define CG6_FBC_BDISP_1 0x00000100
#define CG6_FBC_BDISP_ILLEGAL 0x00000180
#define CG6_FBC_BDISP_MASK 0x00000180
#define CG6_FBC_INDEX_MOD 0x00000040
#define CG6_FBC_INDEX_MASK 0x00000030
/* THC definitions */
#define CG6_THC_MISC_REV_SHIFT 16
#define CG6_THC_MISC_REV_MASK 15
#define CG6_THC_MISC_RESET (1 << 12)
#define CG6_THC_MISC_VIDEO (1 << 10)
#define CG6_THC_MISC_SYNC (1 << 9)
#define CG6_THC_MISC_VSYNC (1 << 8)
#define CG6_THC_MISC_SYNC_ENAB (1 << 7)
#define CG6_THC_MISC_CURS_RES (1 << 6)
#define CG6_THC_MISC_INT_ENAB (1 << 5)
#define CG6_THC_MISC_INT (1 << 4)
#define CG6_THC_MISC_INIT 0x9f
#define CG6_THC_CURSOFF ((65536-32) | ((65536-32) << 16))
/* The contents are unknown */
struct cg6_tec {
int tec_matrix;
int tec_clip;
int tec_vdc;
};
struct cg6_thc {
u32 thc_pad0[512];
u32 thc_hs; /* hsync timing */
u32 thc_hsdvs;
u32 thc_hd;
u32 thc_vs; /* vsync timing */
u32 thc_vd;
u32 thc_refresh;
u32 thc_misc;
u32 thc_pad1[56];
u32 thc_cursxy; /* cursor x,y position (16 bits each) */
u32 thc_cursmask[32]; /* cursor mask bits */
u32 thc_cursbits[32]; /* what to show where mask enabled */
};
struct cg6_fbc {
u32 xxx0[1];
u32 mode;
u32 clip;
u32 xxx1[1];
u32 s;
u32 draw;
u32 blit;
u32 font;
u32 xxx2[24];
u32 x0, y0, z0, color0;
u32 x1, y1, z1, color1;
u32 x2, y2, z2, color2;
u32 x3, y3, z3, color3;
u32 offx, offy;
u32 xxx3[2];
u32 incx, incy;
u32 xxx4[2];
u32 clipminx, clipminy;
u32 xxx5[2];
u32 clipmaxx, clipmaxy;
u32 xxx6[2];
u32 fg;
u32 bg;
u32 alu;
u32 pm;
u32 pixelm;
u32 xxx7[2];
u32 patalign;
u32 pattern[8];
u32 xxx8[432];
u32 apointx, apointy, apointz;
u32 xxx9[1];
u32 rpointx, rpointy, rpointz;
u32 xxx10[5];
u32 pointr, pointg, pointb, pointa;
u32 alinex, aliney, alinez;
u32 xxx11[1];
u32 rlinex, rliney, rlinez;
u32 xxx12[5];
u32 liner, lineg, lineb, linea;
u32 atrix, atriy, atriz;
u32 xxx13[1];
u32 rtrix, rtriy, rtriz;
u32 xxx14[5];
u32 trir, trig, trib, tria;
u32 aquadx, aquady, aquadz;
u32 xxx15[1];
u32 rquadx, rquady, rquadz;
u32 xxx16[5];
u32 quadr, quadg, quadb, quada;
u32 arectx, arecty, arectz;
u32 xxx17[1];
u32 rrectx, rrecty, rrectz;
u32 xxx18[5];
u32 rectr, rectg, rectb, recta;
};
struct bt_regs {
u32 addr;
u32 color_map;
u32 control;
u32 cursor;
};
struct cg6_par {
spinlock_t lock;
struct bt_regs __iomem *bt;
struct cg6_fbc __iomem *fbc;
struct cg6_thc __iomem *thc;
struct cg6_tec __iomem *tec;
u32 __iomem *fhc;
u32 flags;
#define CG6_FLAG_BLANKED 0x00000001
unsigned long which_io;
};
static int cg6_sync(struct fb_info *info)
{
struct cg6_par *par = (struct cg6_par *)info->par;
struct cg6_fbc __iomem *fbc = par->fbc;
int limit = 10000;
do {
if (!(sbus_readl(&fbc->s) & 0x10000000))
break;
udelay(10);
} while (--limit > 0);
return 0;
}
static void cg6_switch_from_graph(struct cg6_par *par)
{
struct cg6_thc __iomem *thc = par->thc;
unsigned long flags;
spin_lock_irqsave(&par->lock, flags);
/* Hide the cursor. */
sbus_writel(CG6_THC_CURSOFF, &thc->thc_cursxy);
spin_unlock_irqrestore(&par->lock, flags);
}
static int cg6_pan_display(struct fb_var_screeninfo *var, struct fb_info *info)
{
struct cg6_par *par = (struct cg6_par *)info->par;
/* We just use this to catch switches out of
* graphics mode.
*/
cg6_switch_from_graph(par);
if (var->xoffset || var->yoffset || var->vmode)
return -EINVAL;
return 0;
}
/**
* cg6_fillrect - Draws a rectangle on the screen.
*
* @info: frame buffer structure that represents a single frame buffer
* @rect: structure defining the rectagle and operation.
*/
static void cg6_fillrect(struct fb_info *info, const struct fb_fillrect *rect)
{
struct cg6_par *par = (struct cg6_par *)info->par;
struct cg6_fbc __iomem *fbc = par->fbc;
unsigned long flags;
s32 val;
/* CG6 doesn't handle ROP_XOR */
spin_lock_irqsave(&par->lock, flags);
cg6_sync(info);
sbus_writel(rect->color, &fbc->fg);
sbus_writel(~(u32)0, &fbc->pixelm);
sbus_writel(0xea80ff00, &fbc->alu);
sbus_writel(0, &fbc->s);
sbus_writel(0, &fbc->clip);
sbus_writel(~(u32)0, &fbc->pm);
sbus_writel(rect->dy, &fbc->arecty);
sbus_writel(rect->dx, &fbc->arectx);
sbus_writel(rect->dy + rect->height, &fbc->arecty);
sbus_writel(rect->dx + rect->width, &fbc->arectx);
do {
val = sbus_readl(&fbc->draw);
} while (val < 0 && (val & 0x20000000));
spin_unlock_irqrestore(&par->lock, flags);
}
/**
* cg6_copyarea - Copies one area of the screen to another area.
*
* @info: frame buffer structure that represents a single frame buffer
* @area: Structure providing the data to copy the framebuffer contents
* from one region to another.
*
* This drawing operation copies a rectangular area from one area of the
* screen to another area.
*/
static void cg6_copyarea(struct fb_info *info, const struct fb_copyarea *area)
{
struct cg6_par *par = (struct cg6_par *)info->par;
struct cg6_fbc __iomem *fbc = par->fbc;
unsigned long flags;
int i;
spin_lock_irqsave(&par->lock, flags);
cg6_sync(info);
sbus_writel(0xff, &fbc->fg);
sbus_writel(0x00, &fbc->bg);
sbus_writel(~0, &fbc->pixelm);
sbus_writel(0xe880cccc, &fbc->alu);
sbus_writel(0, &fbc->s);
sbus_writel(0, &fbc->clip);
sbus_writel(area->sy, &fbc->y0);
sbus_writel(area->sx, &fbc->x0);
sbus_writel(area->sy + area->height - 1, &fbc->y1);
sbus_writel(area->sx + area->width - 1, &fbc->x1);
sbus_writel(area->dy, &fbc->y2);
sbus_writel(area->dx, &fbc->x2);
sbus_writel(area->dy + area->height - 1, &fbc->y3);
sbus_writel(area->dx + area->width - 1, &fbc->x3);
do {
i = sbus_readl(&fbc->blit);
} while (i < 0 && (i & 0x20000000));
spin_unlock_irqrestore(&par->lock, flags);
}
/**
* cg6_imageblit - Copies a image from system memory to the screen.
*
* @info: frame buffer structure that represents a single frame buffer
* @image: structure defining the image.
*/
static void cg6_imageblit(struct fb_info *info, const struct fb_image *image)
{
struct cg6_par *par = (struct cg6_par *)info->par;
struct cg6_fbc __iomem *fbc = par->fbc;
const u8 *data = image->data;
unsigned long flags;
u32 x, y;
int i, width;
if (image->depth > 1) {
cfb_imageblit(info, image);
return;
}
spin_lock_irqsave(&par->lock, flags);
cg6_sync(info);
sbus_writel(image->fg_color, &fbc->fg);
sbus_writel(image->bg_color, &fbc->bg);
sbus_writel(0x140000, &fbc->mode);
sbus_writel(0xe880fc30, &fbc->alu);
sbus_writel(~(u32)0, &fbc->pixelm);
sbus_writel(0, &fbc->s);
sbus_writel(0, &fbc->clip);
sbus_writel(0xff, &fbc->pm);
sbus_writel(32, &fbc->incx);
sbus_writel(0, &fbc->incy);
x = image->dx;
y = image->dy;
for (i = 0; i < image->height; i++) {
width = image->width;
while (width >= 32) {
u32 val;
sbus_writel(y, &fbc->y0);
sbus_writel(x, &fbc->x0);
sbus_writel(x + 32 - 1, &fbc->x1);
val = ((u32)data[0] << 24) |
((u32)data[1] << 16) |
((u32)data[2] << 8) |
((u32)data[3] << 0);
sbus_writel(val, &fbc->font);
data += 4;
x += 32;
width -= 32;
}
if (width) {
u32 val;
sbus_writel(y, &fbc->y0);
sbus_writel(x, &fbc->x0);
sbus_writel(x + width - 1, &fbc->x1);
if (width <= 8) {
val = (u32) data[0] << 24;
data += 1;
} else if (width <= 16) {
val = ((u32) data[0] << 24) |
((u32) data[1] << 16);
data += 2;
} else {
val = ((u32) data[0] << 24) |
((u32) data[1] << 16) |
((u32) data[2] << 8);
data += 3;
}
sbus_writel(val, &fbc->font);
}
y += 1;
x = image->dx;
}
spin_unlock_irqrestore(&par->lock, flags);
}
/**
* cg6_setcolreg - Sets a color register.
*
* @regno: boolean, 0 copy local, 1 get_user() function
* @red: frame buffer colormap structure
* @green: The green value which can be up to 16 bits wide
* @blue: The blue value which can be up to 16 bits wide.
* @transp: If supported the alpha value which can be up to 16 bits wide.
* @info: frame buffer info structure
*/
static int cg6_setcolreg(unsigned regno,
unsigned red, unsigned green, unsigned blue,
unsigned transp, struct fb_info *info)
{
struct cg6_par *par = (struct cg6_par *)info->par;
struct bt_regs __iomem *bt = par->bt;
unsigned long flags;
if (regno >= 256)
return 1;
red >>= 8;
green >>= 8;
blue >>= 8;
spin_lock_irqsave(&par->lock, flags);
sbus_writel((u32)regno << 24, &bt->addr);
sbus_writel((u32)red << 24, &bt->color_map);
sbus_writel((u32)green << 24, &bt->color_map);
sbus_writel((u32)blue << 24, &bt->color_map);
spin_unlock_irqrestore(&par->lock, flags);
return 0;
}
/**
* cg6_blank - Blanks the display.
*
* @blank_mode: the blank mode we want.
* @info: frame buffer structure that represents a single frame buffer
*/
static int cg6_blank(int blank, struct fb_info *info)
{
struct cg6_par *par = (struct cg6_par *)info->par;
struct cg6_thc __iomem *thc = par->thc;
unsigned long flags;
u32 val;
spin_lock_irqsave(&par->lock, flags);
val = sbus_readl(&thc->thc_misc);
switch (blank) {
case FB_BLANK_UNBLANK: /* Unblanking */
val |= CG6_THC_MISC_VIDEO;
par->flags &= ~CG6_FLAG_BLANKED;
break;
case FB_BLANK_NORMAL: /* Normal blanking */
case FB_BLANK_VSYNC_SUSPEND: /* VESA blank (vsync off) */
case FB_BLANK_HSYNC_SUSPEND: /* VESA blank (hsync off) */
case FB_BLANK_POWERDOWN: /* Poweroff */
val &= ~CG6_THC_MISC_VIDEO;
par->flags |= CG6_FLAG_BLANKED;
break;
}
sbus_writel(val, &thc->thc_misc);
spin_unlock_irqrestore(&par->lock, flags);
return 0;
}
static struct sbus_mmap_map cg6_mmap_map[] = {
{
.voff = CG6_FBC,
.poff = CG6_FBC_OFFSET,
.size = PAGE_SIZE
},
{
.voff = CG6_TEC,
.poff = CG6_TEC_OFFSET,
.size = PAGE_SIZE
},
{
.voff = CG6_BTREGS,
.poff = CG6_BROOKTREE_OFFSET,
.size = PAGE_SIZE
},
{
.voff = CG6_FHC,
.poff = CG6_FHC_OFFSET,
.size = PAGE_SIZE
},
{
.voff = CG6_THC,
.poff = CG6_THC_OFFSET,
.size = PAGE_SIZE
},
{
.voff = CG6_ROM,
.poff = CG6_ROM_OFFSET,
.size = 0x10000
},
{
.voff = CG6_RAM,
.poff = CG6_RAM_OFFSET,
.size = SBUS_MMAP_FBSIZE(1)
},
{
.voff = CG6_DHC,
.poff = CG6_DHC_OFFSET,
.size = 0x40000
},
{ .size = 0 }
};
static int cg6_mmap(struct fb_info *info, struct vm_area_struct *vma)
{
struct cg6_par *par = (struct cg6_par *)info->par;
return sbusfb_mmap_helper(cg6_mmap_map,
info->fix.smem_start, info->fix.smem_len,
par->which_io, vma);
}
static int cg6_ioctl(struct fb_info *info, unsigned int cmd, unsigned long arg)
{
return sbusfb_ioctl_helper(cmd, arg, info,
FBTYPE_SUNFAST_COLOR, 8, info->fix.smem_len);
}
/*
* Initialisation
*/
static void __devinit cg6_init_fix(struct fb_info *info, int linebytes)
{
struct cg6_par *par = (struct cg6_par *)info->par;
const char *cg6_cpu_name, *cg6_card_name;
u32 conf;
conf = sbus_readl(par->fhc);
switch (conf & CG6_FHC_CPU_MASK) {
case CG6_FHC_CPU_SPARC:
cg6_cpu_name = "sparc";
break;
case CG6_FHC_CPU_68020:
cg6_cpu_name = "68020";
break;
default:
cg6_cpu_name = "i386";
break;
};
if (((conf >> CG6_FHC_REV_SHIFT) & CG6_FHC_REV_MASK) >= 11) {
if (info->fix.smem_len <= 0x100000)
cg6_card_name = "TGX";
else
cg6_card_name = "TGX+";
} else {
if (info->fix.smem_len <= 0x100000)
cg6_card_name = "GX";
else
cg6_card_name = "GX+";
}
sprintf(info->fix.id, "%s %s", cg6_card_name, cg6_cpu_name);
info->fix.id[sizeof(info->fix.id) - 1] = 0;
info->fix.type = FB_TYPE_PACKED_PIXELS;
info->fix.visual = FB_VISUAL_PSEUDOCOLOR;
info->fix.line_length = linebytes;
info->fix.accel = FB_ACCEL_SUN_CGSIX;
}
/* Initialize Brooktree DAC */
static void __devinit cg6_bt_init(struct cg6_par *par)
{
struct bt_regs __iomem *bt = par->bt;
sbus_writel(0x04 << 24, &bt->addr); /* color planes */
sbus_writel(0xff << 24, &bt->control);
sbus_writel(0x05 << 24, &bt->addr);
sbus_writel(0x00 << 24, &bt->control);
sbus_writel(0x06 << 24, &bt->addr); /* overlay plane */
sbus_writel(0x73 << 24, &bt->control);
sbus_writel(0x07 << 24, &bt->addr);
sbus_writel(0x00 << 24, &bt->control);
}
static void __devinit cg6_chip_init(struct fb_info *info)
{
struct cg6_par *par = (struct cg6_par *)info->par;
struct cg6_tec __iomem *tec = par->tec;
struct cg6_fbc __iomem *fbc = par->fbc;
struct cg6_thc __iomem *thc = par->thc;
u32 rev, conf, mode;
int i;
/* Hide the cursor. */
sbus_writel(CG6_THC_CURSOFF, &thc->thc_cursxy);
/* Turn off stuff in the Transform Engine. */
sbus_writel(0, &tec->tec_matrix);
sbus_writel(0, &tec->tec_clip);
sbus_writel(0, &tec->tec_vdc);
/* Take care of bugs in old revisions. */
rev = (sbus_readl(par->fhc) >> CG6_FHC_REV_SHIFT) & CG6_FHC_REV_MASK;
if (rev < 5) {
conf = (sbus_readl(par->fhc) & CG6_FHC_RES_MASK) |
CG6_FHC_CPU_68020 | CG6_FHC_TEST |
(11 << CG6_FHC_TEST_X_SHIFT) |
(11 << CG6_FHC_TEST_Y_SHIFT);
if (rev < 2)
conf |= CG6_FHC_DST_DISABLE;
sbus_writel(conf, par->fhc);
}
/* Set things in the FBC. Bad things appear to happen if we do
* back to back store/loads on the mode register, so copy it
* out instead. */
mode = sbus_readl(&fbc->mode);
do {
i = sbus_readl(&fbc->s);
} while (i & 0x10000000);
mode &= ~(CG6_FBC_BLIT_MASK | CG6_FBC_MODE_MASK |
CG6_FBC_DRAW_MASK | CG6_FBC_BWRITE0_MASK |
CG6_FBC_BWRITE1_MASK | CG6_FBC_BREAD_MASK |
CG6_FBC_BDISP_MASK);
mode |= (CG6_FBC_BLIT_SRC | CG6_FBC_MODE_COLOR8 |
CG6_FBC_DRAW_RENDER | CG6_FBC_BWRITE0_ENABLE |
CG6_FBC_BWRITE1_DISABLE | CG6_FBC_BREAD_0 |
CG6_FBC_BDISP_0);
sbus_writel(mode, &fbc->mode);
sbus_writel(0, &fbc->clip);
sbus_writel(0, &fbc->offx);
sbus_writel(0, &fbc->offy);
sbus_writel(0, &fbc->clipminx);
sbus_writel(0, &fbc->clipminy);
sbus_writel(info->var.xres - 1, &fbc->clipmaxx);
sbus_writel(info->var.yres - 1, &fbc->clipmaxy);
}
static void cg6_unmap_regs(struct platform_device *op, struct fb_info *info,
struct cg6_par *par)
{
if (par->fbc)
of_iounmap(&op->resource[0], par->fbc, 4096);
if (par->tec)
of_iounmap(&op->resource[0], par->tec, sizeof(struct cg6_tec));
if (par->thc)
of_iounmap(&op->resource[0], par->thc, sizeof(struct cg6_thc));
if (par->bt)
of_iounmap(&op->resource[0], par->bt, sizeof(struct bt_regs));
if (par->fhc)
of_iounmap(&op->resource[0], par->fhc, sizeof(u32));
if (info->screen_base)
of_iounmap(&op->resource[0], info->screen_base,
info->fix.smem_len);
}
static int __devinit cg6_probe(struct platform_device *op)
{
struct device_node *dp = op->dev.of_node;
struct fb_info *info;
struct cg6_par *par;
int linebytes, err;
int dblbuf;
info = framebuffer_alloc(sizeof(struct cg6_par), &op->dev);
err = -ENOMEM;
if (!info)
goto out_err;
par = info->par;
spin_lock_init(&par->lock);
info->fix.smem_start = op->resource[0].start;
par->which_io = op->resource[0].flags & IORESOURCE_BITS;
sbusfb_fill_var(&info->var, dp, 8);
info->var.red.length = 8;
info->var.green.length = 8;
info->var.blue.length = 8;
linebytes = of_getintprop_default(dp, "linebytes",
info->var.xres);
info->fix.smem_len = PAGE_ALIGN(linebytes * info->var.yres);
dblbuf = of_getintprop_default(dp, "dblbuf", 0);
if (dblbuf)
info->fix.smem_len *= 4;
par->fbc = of_ioremap(&op->resource[0], CG6_FBC_OFFSET,
4096, "cgsix fbc");
par->tec = of_ioremap(&op->resource[0], CG6_TEC_OFFSET,
sizeof(struct cg6_tec), "cgsix tec");
par->thc = of_ioremap(&op->resource[0], CG6_THC_OFFSET,
sizeof(struct cg6_thc), "cgsix thc");
par->bt = of_ioremap(&op->resource[0], CG6_BROOKTREE_OFFSET,
sizeof(struct bt_regs), "cgsix dac");
par->fhc = of_ioremap(&op->resource[0], CG6_FHC_OFFSET,
sizeof(u32), "cgsix fhc");
info->flags = FBINFO_DEFAULT | FBINFO_HWACCEL_IMAGEBLIT |
FBINFO_HWACCEL_COPYAREA | FBINFO_HWACCEL_FILLRECT |
FBINFO_READS_FAST;
info->fbops = &cg6_ops;
info->screen_base = of_ioremap(&op->resource[0], CG6_RAM_OFFSET,
info->fix.smem_len, "cgsix ram");
if (!par->fbc || !par->tec || !par->thc ||
!par->bt || !par->fhc || !info->screen_base)
goto out_unmap_regs;
info->var.accel_flags = FB_ACCELF_TEXT;
cg6_bt_init(par);
cg6_chip_init(info);
cg6_blank(FB_BLANK_UNBLANK, info);
if (fb_alloc_cmap(&info->cmap, 256, 0))
goto out_unmap_regs;
fb_set_cmap(&info->cmap, info);
cg6_init_fix(info, linebytes);
err = register_framebuffer(info);
if (err < 0)
goto out_dealloc_cmap;
dev_set_drvdata(&op->dev, info);
printk(KERN_INFO "%s: CGsix [%s] at %lx:%lx\n",
dp->full_name, info->fix.id,
par->which_io, info->fix.smem_start);
return 0;
out_dealloc_cmap:
fb_dealloc_cmap(&info->cmap);
out_unmap_regs:
cg6_unmap_regs(op, info, par);
framebuffer_release(info);
out_err:
return err;
}
static int __devexit cg6_remove(struct platform_device *op)
{
struct fb_info *info = dev_get_drvdata(&op->dev);
struct cg6_par *par = info->par;
unregister_framebuffer(info);
fb_dealloc_cmap(&info->cmap);
cg6_unmap_regs(op, info, par);
framebuffer_release(info);
dev_set_drvdata(&op->dev, NULL);
return 0;
}
static const struct of_device_id cg6_match[] = {
{
.name = "cgsix",
},
{
.name = "cgthree+",
},
{},
};
MODULE_DEVICE_TABLE(of, cg6_match);
static struct platform_driver cg6_driver = {
.driver = {
.name = "cg6",
.owner = THIS_MODULE,
.of_match_table = cg6_match,
},
.probe = cg6_probe,
.remove = __devexit_p(cg6_remove),
};
static int __init cg6_init(void)
{
if (fb_get_options("cg6fb", NULL))
return -ENODEV;
return platform_driver_register(&cg6_driver);
}
static void __exit cg6_exit(void)
{
platform_driver_unregister(&cg6_driver);
}
module_init(cg6_init);
module_exit(cg6_exit);
MODULE_DESCRIPTION("framebuffer driver for CGsix chipsets");
MODULE_AUTHOR("David S. Miller <davem@davemloft.net>");
MODULE_VERSION("2.0");
MODULE_LICENSE("GPL");
| gpl-2.0 |
slz/samsung-kernel-msm7x30 | arch/arm/plat-s3c24xx/s3c2410-cpufreq-utils.c | 9719 | 1752 | /* linux/arch/arm/plat-s3c24xx/s3c2410-cpufreq-utils.c
*
* Copyright (c) 2009 Simtec Electronics
* http://armlinux.simtec.co.uk/
* Ben Dooks <ben@simtec.co.uk>
*
* S3C24XX CPU Frequency scaling - utils for S3C2410/S3C2440/S3C2442
*
* 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/errno.h>
#include <linux/cpufreq.h>
#include <linux/io.h>
#include <mach/map.h>
#include <mach/regs-mem.h>
#include <mach/regs-clock.h>
#include <plat/cpu-freq-core.h>
/**
* s3c2410_cpufreq_setrefresh - set SDRAM refresh value
* @cfg: The frequency configuration
*
* Set the SDRAM refresh value appropriately for the configured
* frequency.
*/
void s3c2410_cpufreq_setrefresh(struct s3c_cpufreq_config *cfg)
{
struct s3c_cpufreq_board *board = cfg->board;
unsigned long refresh;
unsigned long refval;
/* Reduce both the refresh time (in ns) and the frequency (in MHz)
* down to ensure that we do not overflow 32 bit numbers.
*
* This should work for HCLK up to 133MHz and refresh period up
* to 30usec.
*/
refresh = (cfg->freq.hclk / 100) * (board->refresh / 10);
refresh = DIV_ROUND_UP(refresh, (1000 * 1000)); /* apply scale */
refresh = (1 << 11) + 1 - refresh;
s3c_freq_dbg("%s: refresh value %lu\n", __func__, refresh);
refval = __raw_readl(S3C2410_REFRESH);
refval &= ~((1 << 12) - 1);
refval |= refresh;
__raw_writel(refval, S3C2410_REFRESH);
}
/**
* s3c2410_set_fvco - set the PLL value
* @cfg: The frequency configuration
*/
void s3c2410_set_fvco(struct s3c_cpufreq_config *cfg)
{
__raw_writel(cfg->pll.index, S3C2410_MPLLCON);
}
| gpl-2.0 |
pierdebeer/AudaxPlus_Kernel | drivers/media/v4l2-core/videobuf2-vmalloc.c | 248 | 6383 | /*
* videobuf2-vmalloc.c - vmalloc memory allocator for videobuf2
*
* Copyright (C) 2010 Samsung Electronics
*
* Author: Pawel Osciak <pawel@osciak.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.
*/
#include <linux/io.h>
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <media/videobuf2-core.h>
#include <media/videobuf2-vmalloc.h>
#include <media/videobuf2-memops.h>
struct vb2_vmalloc_buf {
void *vaddr;
struct page **pages;
struct vm_area_struct *vma;
int write;
unsigned long size;
unsigned int n_pages;
atomic_t refcount;
struct vb2_vmarea_handler handler;
struct dma_buf *dbuf;
};
static void vb2_vmalloc_put(void *buf_priv);
static void *vb2_vmalloc_alloc(void *alloc_ctx, unsigned long size, int write,
int plane, gfp_t gfp_flags)
{
struct vb2_vmalloc_buf *buf;
buf = kzalloc(sizeof(*buf), GFP_KERNEL | gfp_flags);
if (!buf)
return NULL;
buf->size = size;
buf->vaddr = vmalloc_user(buf->size);
buf->handler.refcount = &buf->refcount;
buf->handler.put = vb2_vmalloc_put;
buf->handler.arg = buf;
if (!buf->vaddr) {
pr_debug("vmalloc of size %ld failed\n", buf->size);
kfree(buf);
return NULL;
}
atomic_inc(&buf->refcount);
return buf;
}
static void vb2_vmalloc_put(void *buf_priv)
{
struct vb2_vmalloc_buf *buf = buf_priv;
if (atomic_dec_and_test(&buf->refcount)) {
vfree(buf->vaddr);
kfree(buf);
}
}
static void *vb2_vmalloc_get_userptr(void *alloc_ctx, unsigned long vaddr,
unsigned long size, int write, int plane)
{
struct vb2_vmalloc_buf *buf;
unsigned long first, last;
int n_pages, offset;
struct vm_area_struct *vma;
dma_addr_t physp;
buf = kzalloc(sizeof(*buf), GFP_KERNEL);
if (!buf)
return NULL;
buf->write = write;
offset = vaddr & ~PAGE_MASK;
buf->size = size;
vma = find_vma(current->mm, vaddr);
if (vma && (vma->vm_flags & VM_PFNMAP) && (vma->vm_pgoff)) {
if (vb2_get_contig_userptr(vaddr, size, &vma, &physp))
goto fail_pages_array_alloc;
buf->vma = vma;
buf->vaddr = ioremap_nocache(physp, size);
if (!buf->vaddr)
goto fail_pages_array_alloc;
} else {
first = vaddr >> PAGE_SHIFT;
last = (vaddr + size - 1) >> PAGE_SHIFT;
buf->n_pages = last - first + 1;
buf->pages = kzalloc(buf->n_pages * sizeof(struct page *),
GFP_KERNEL);
if (!buf->pages)
goto fail_pages_array_alloc;
/* current->mm->mmap_sem is taken by videobuf2 core */
n_pages = get_user_pages(current, current->mm,
vaddr & PAGE_MASK, buf->n_pages,
write, 1, /* force */
buf->pages, NULL);
if (n_pages != buf->n_pages)
goto fail_get_user_pages;
buf->vaddr = vm_map_ram(buf->pages, buf->n_pages, -1,
PAGE_KERNEL);
if (!buf->vaddr)
goto fail_get_user_pages;
}
buf->vaddr += offset;
return buf;
fail_get_user_pages:
pr_debug("get_user_pages requested/got: %d/%d]\n", n_pages,
buf->n_pages);
while (--n_pages >= 0)
put_page(buf->pages[n_pages]);
kfree(buf->pages);
fail_pages_array_alloc:
kfree(buf);
return NULL;
}
static void vb2_vmalloc_put_userptr(void *buf_priv)
{
struct vb2_vmalloc_buf *buf = buf_priv;
unsigned long vaddr = (unsigned long)buf->vaddr & PAGE_MASK;
unsigned int i;
if (buf->pages) {
if (vaddr)
vm_unmap_ram((void *)vaddr, buf->n_pages);
for (i = 0; i < buf->n_pages; ++i) {
if (buf->write)
set_page_dirty_lock(buf->pages[i]);
put_page(buf->pages[i]);
}
kfree(buf->pages);
} else {
if (buf->vma)
vb2_put_vma(buf->vma);
iounmap(buf->vaddr);
}
kfree(buf);
}
static void *vb2_vmalloc_vaddr(void *buf_priv)
{
struct vb2_vmalloc_buf *buf = buf_priv;
if (!buf->vaddr) {
pr_err("Address of an unallocated plane requested "
"or cannot map user pointer\n");
return NULL;
}
return buf->vaddr;
}
static unsigned int vb2_vmalloc_num_users(void *buf_priv)
{
struct vb2_vmalloc_buf *buf = buf_priv;
return atomic_read(&buf->refcount);
}
static int vb2_vmalloc_mmap(void *buf_priv, struct vm_area_struct *vma)
{
struct vb2_vmalloc_buf *buf = buf_priv;
int ret;
if (!buf) {
pr_err("No memory to map\n");
return -EINVAL;
}
ret = remap_vmalloc_range(vma, buf->vaddr, 0);
if (ret) {
pr_err("Remapping vmalloc memory, error: %d\n", ret);
return ret;
}
/*
* Make sure that vm_areas for 2 buffers won't be merged together
*/
vma->vm_flags |= VM_DONTEXPAND;
/*
* Use common vm_area operations to track buffer refcount.
*/
vma->vm_private_data = &buf->handler;
vma->vm_ops = &vb2_common_vm_ops;
vma->vm_ops->open(vma);
return 0;
}
/*********************************************/
/* callbacks for DMABUF buffers */
/*********************************************/
static int vb2_vmalloc_map_dmabuf(void *mem_priv, int plane)
{
struct vb2_vmalloc_buf *buf = mem_priv;
buf->vaddr = dma_buf_vmap(buf->dbuf);
return buf->vaddr ? 0 : -EFAULT;
}
static void vb2_vmalloc_unmap_dmabuf(void *mem_priv)
{
struct vb2_vmalloc_buf *buf = mem_priv;
dma_buf_vunmap(buf->dbuf, buf->vaddr);
buf->vaddr = NULL;
}
static void vb2_vmalloc_detach_dmabuf(void *mem_priv)
{
struct vb2_vmalloc_buf *buf = mem_priv;
if (buf->vaddr)
dma_buf_vunmap(buf->dbuf, buf->vaddr);
kfree(buf);
}
static void *vb2_vmalloc_attach_dmabuf(void *alloc_ctx, struct dma_buf *dbuf,
unsigned long size, int write)
{
struct vb2_vmalloc_buf *buf;
if (dbuf->size < size)
return ERR_PTR(-EFAULT);
buf = kzalloc(sizeof(*buf), GFP_KERNEL);
if (!buf)
return ERR_PTR(-ENOMEM);
buf->dbuf = dbuf;
buf->write = write;
buf->size = size;
return buf;
}
const struct vb2_mem_ops vb2_vmalloc_memops = {
.alloc = vb2_vmalloc_alloc,
.put = vb2_vmalloc_put,
.get_userptr = vb2_vmalloc_get_userptr,
.put_userptr = vb2_vmalloc_put_userptr,
.map_dmabuf = vb2_vmalloc_map_dmabuf,
.unmap_dmabuf = vb2_vmalloc_unmap_dmabuf,
.attach_dmabuf = vb2_vmalloc_attach_dmabuf,
.detach_dmabuf = vb2_vmalloc_detach_dmabuf,
.vaddr = vb2_vmalloc_vaddr,
.mmap = vb2_vmalloc_mmap,
.num_users = vb2_vmalloc_num_users,
};
EXPORT_SYMBOL_GPL(vb2_vmalloc_memops);
MODULE_DESCRIPTION("vmalloc memory handling routines for videobuf2");
MODULE_AUTHOR("Pawel Osciak <pawel@osciak.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
ankurmittal/OS-u2fs | drivers/hwmon/ds1621.c | 248 | 9407 | /*
ds1621.c - Part of lm_sensors, Linux kernel modules for hardware
monitoring
Christian W. Zuckschwerdt <zany@triq.net> 2000-11-23
based on lm75.c by Frodo Looijaard <frodol@dds.nl>
Ported to Linux 2.6 by Aurelien Jarno <aurelien@aurel32.net> with
the help of 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>
#include <linux/sysfs.h>
#include "lm75.h"
/* Addresses to scan */
static const unsigned short normal_i2c[] = { 0x48, 0x49, 0x4a, 0x4b, 0x4c,
0x4d, 0x4e, 0x4f, I2C_CLIENT_END };
/* Insmod parameters */
static int polarity = -1;
module_param(polarity, int, 0);
MODULE_PARM_DESC(polarity, "Output's polarity: 0 = active high, 1 = active low");
/* Many DS1621 constants specified below */
/* Config register used for detection */
/* 7 6 5 4 3 2 1 0 */
/* |Done|THF |TLF |NVB | X | X |POL |1SHOT| */
#define DS1621_REG_CONFIG_NVB 0x10
#define DS1621_REG_CONFIG_POLARITY 0x02
#define DS1621_REG_CONFIG_1SHOT 0x01
#define DS1621_REG_CONFIG_DONE 0x80
/* The DS1621 registers */
static const u8 DS1621_REG_TEMP[3] = {
0xAA, /* input, word, RO */
0xA2, /* min, word, RW */
0xA1, /* max, word, RW */
};
#define DS1621_REG_CONF 0xAC /* byte, RW */
#define DS1621_COM_START 0xEE /* no data */
#define DS1621_COM_STOP 0x22 /* no data */
/* The DS1621 configuration register */
#define DS1621_ALARM_TEMP_HIGH 0x40
#define DS1621_ALARM_TEMP_LOW 0x20
/* Conversions */
#define ALARMS_FROM_REG(val) ((val) & \
(DS1621_ALARM_TEMP_HIGH | DS1621_ALARM_TEMP_LOW))
/* Each client has this additional data */
struct ds1621_data {
struct device *hwmon_dev;
struct mutex update_lock;
char valid; /* !=0 if following fields are valid */
unsigned long last_updated; /* In jiffies */
u16 temp[3]; /* Register values, word */
u8 conf; /* Register encoding, combined */
};
static void ds1621_init_client(struct i2c_client *client)
{
u8 conf, new_conf;
new_conf = conf = i2c_smbus_read_byte_data(client, DS1621_REG_CONF);
/* switch to continuous conversion mode */
new_conf &= ~DS1621_REG_CONFIG_1SHOT;
/* setup output polarity */
if (polarity == 0)
new_conf &= ~DS1621_REG_CONFIG_POLARITY;
else if (polarity == 1)
new_conf |= DS1621_REG_CONFIG_POLARITY;
if (conf != new_conf)
i2c_smbus_write_byte_data(client, DS1621_REG_CONF, new_conf);
/* start conversion */
i2c_smbus_write_byte(client, DS1621_COM_START);
}
static struct ds1621_data *ds1621_update_client(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct ds1621_data *data = i2c_get_clientdata(client);
u8 new_conf;
mutex_lock(&data->update_lock);
if (time_after(jiffies, data->last_updated + HZ + HZ / 2)
|| !data->valid) {
int i;
dev_dbg(&client->dev, "Starting ds1621 update\n");
data->conf = i2c_smbus_read_byte_data(client, DS1621_REG_CONF);
for (i = 0; i < ARRAY_SIZE(data->temp); i++)
data->temp[i] = i2c_smbus_read_word_swapped(client,
DS1621_REG_TEMP[i]);
/* reset alarms if necessary */
new_conf = data->conf;
if (data->temp[0] > data->temp[1]) /* input > min */
new_conf &= ~DS1621_ALARM_TEMP_LOW;
if (data->temp[0] < data->temp[2]) /* input < max */
new_conf &= ~DS1621_ALARM_TEMP_HIGH;
if (data->conf != new_conf)
i2c_smbus_write_byte_data(client, DS1621_REG_CONF,
new_conf);
data->last_updated = jiffies;
data->valid = 1;
}
mutex_unlock(&data->update_lock);
return data;
}
static ssize_t show_temp(struct device *dev, struct device_attribute *da,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(da);
struct ds1621_data *data = ds1621_update_client(dev);
return sprintf(buf, "%d\n",
LM75_TEMP_FROM_REG(data->temp[attr->index]));
}
static ssize_t set_temp(struct device *dev, struct device_attribute *da,
const char *buf, size_t count)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(da);
struct i2c_client *client = to_i2c_client(dev);
struct ds1621_data *data = i2c_get_clientdata(client);
u16 val = LM75_TEMP_TO_REG(simple_strtol(buf, NULL, 10));
mutex_lock(&data->update_lock);
data->temp[attr->index] = val;
i2c_smbus_write_word_swapped(client, DS1621_REG_TEMP[attr->index],
data->temp[attr->index]);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_alarms(struct device *dev, struct device_attribute *da,
char *buf)
{
struct ds1621_data *data = ds1621_update_client(dev);
return sprintf(buf, "%d\n", ALARMS_FROM_REG(data->conf));
}
static ssize_t show_alarm(struct device *dev, struct device_attribute *da,
char *buf)
{
struct sensor_device_attribute *attr = to_sensor_dev_attr(da);
struct ds1621_data *data = ds1621_update_client(dev);
return sprintf(buf, "%d\n", !!(data->conf & attr->index));
}
static DEVICE_ATTR(alarms, S_IRUGO, show_alarms, NULL);
static SENSOR_DEVICE_ATTR(temp1_input, S_IRUGO, show_temp, NULL, 0);
static SENSOR_DEVICE_ATTR(temp1_min, S_IWUSR | S_IRUGO, show_temp, set_temp, 1);
static SENSOR_DEVICE_ATTR(temp1_max, S_IWUSR | S_IRUGO, show_temp, set_temp, 2);
static SENSOR_DEVICE_ATTR(temp1_min_alarm, S_IRUGO, show_alarm, NULL,
DS1621_ALARM_TEMP_LOW);
static SENSOR_DEVICE_ATTR(temp1_max_alarm, S_IRUGO, show_alarm, NULL,
DS1621_ALARM_TEMP_HIGH);
static struct attribute *ds1621_attributes[] = {
&sensor_dev_attr_temp1_input.dev_attr.attr,
&sensor_dev_attr_temp1_min.dev_attr.attr,
&sensor_dev_attr_temp1_max.dev_attr.attr,
&sensor_dev_attr_temp1_min_alarm.dev_attr.attr,
&sensor_dev_attr_temp1_max_alarm.dev_attr.attr,
&dev_attr_alarms.attr,
NULL
};
static const struct attribute_group ds1621_group = {
.attrs = ds1621_attributes,
};
/* Return 0 if detection is successful, -ENODEV otherwise */
static int ds1621_detect(struct i2c_client *client,
struct i2c_board_info *info)
{
struct i2c_adapter *adapter = client->adapter;
int conf, temp;
int i;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA
| I2C_FUNC_SMBUS_WORD_DATA
| I2C_FUNC_SMBUS_WRITE_BYTE))
return -ENODEV;
/* Now, we do the remaining detection. It is lousy. */
/* The NVB bit should be low if no EEPROM write has been requested
during the latest 10ms, which is highly improbable in our case. */
conf = i2c_smbus_read_byte_data(client, DS1621_REG_CONF);
if (conf < 0 || conf & DS1621_REG_CONFIG_NVB)
return -ENODEV;
/* The 7 lowest bits of a temperature should always be 0. */
for (i = 0; i < ARRAY_SIZE(DS1621_REG_TEMP); i++) {
temp = i2c_smbus_read_word_data(client, DS1621_REG_TEMP[i]);
if (temp < 0 || (temp & 0x7f00))
return -ENODEV;
}
strlcpy(info->type, "ds1621", I2C_NAME_SIZE);
return 0;
}
static int ds1621_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct ds1621_data *data;
int err;
data = kzalloc(sizeof(struct ds1621_data), GFP_KERNEL);
if (!data) {
err = -ENOMEM;
goto exit;
}
i2c_set_clientdata(client, data);
mutex_init(&data->update_lock);
/* Initialize the DS1621 chip */
ds1621_init_client(client);
/* Register sysfs hooks */
if ((err = sysfs_create_group(&client->dev.kobj, &ds1621_group)))
goto exit_free;
data->hwmon_dev = hwmon_device_register(&client->dev);
if (IS_ERR(data->hwmon_dev)) {
err = PTR_ERR(data->hwmon_dev);
goto exit_remove_files;
}
return 0;
exit_remove_files:
sysfs_remove_group(&client->dev.kobj, &ds1621_group);
exit_free:
kfree(data);
exit:
return err;
}
static int ds1621_remove(struct i2c_client *client)
{
struct ds1621_data *data = i2c_get_clientdata(client);
hwmon_device_unregister(data->hwmon_dev);
sysfs_remove_group(&client->dev.kobj, &ds1621_group);
kfree(data);
return 0;
}
static const struct i2c_device_id ds1621_id[] = {
{ "ds1621", 0 },
{ "ds1625", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, ds1621_id);
/* This is the driver that will be inserted */
static struct i2c_driver ds1621_driver = {
.class = I2C_CLASS_HWMON,
.driver = {
.name = "ds1621",
},
.probe = ds1621_probe,
.remove = ds1621_remove,
.id_table = ds1621_id,
.detect = ds1621_detect,
.address_list = normal_i2c,
};
static int __init ds1621_init(void)
{
return i2c_add_driver(&ds1621_driver);
}
static void __exit ds1621_exit(void)
{
i2c_del_driver(&ds1621_driver);
}
MODULE_AUTHOR("Christian W. Zuckschwerdt <zany@triq.net>");
MODULE_DESCRIPTION("DS1621 driver");
MODULE_LICENSE("GPL");
module_init(ds1621_init);
module_exit(ds1621_exit);
| gpl-2.0 |
nadlabak/kernel | drivers/net/sungem.c | 504 | 82185 | /* $Id: sungem.c,v 1.44.2.22 2002/03/13 01:18:12 davem Exp $
* sungem.c: Sun GEM ethernet driver.
*
* Copyright (C) 2000, 2001, 2002, 2003 David S. Miller (davem@redhat.com)
*
* Support for Apple GMAC and assorted PHYs, WOL, Power Management
* (C) 2001,2002,2003 Benjamin Herrenscmidt (benh@kernel.crashing.org)
* (C) 2004,2005 Benjamin Herrenscmidt, IBM Corp.
*
* NAPI and NETPOLL support
* (C) 2004 by Eric Lemoine (eric.lemoine@gmail.com)
*
* TODO:
* - Now that the driver was significantly simplified, I need to rework
* the locking. I'm sure we don't need _2_ spinlocks, and we probably
* can avoid taking most of them for so long period of time (and schedule
* instead). The main issues at this point are caused by the netdev layer
* though:
*
* gem_change_mtu() and gem_set_multicast() are called with a read_lock()
* help by net/core/dev.c, thus they can't schedule. That means they can't
* call napi_disable() neither, thus force gem_poll() to keep a spinlock
* where it could have been dropped. change_mtu especially would love also to
* be able to msleep instead of horrid locked delays when resetting the HW,
* but that read_lock() makes it impossible, unless I defer it's action to
* the reset task, which means it'll be asynchronous (won't take effect until
* the system schedules a bit).
*
* Also, it would probably be possible to also remove most of the long-life
* locking in open/resume code path (gem_reinit_chip) by beeing more careful
* about when we can start taking interrupts or get xmit() called...
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/fcntl.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/in.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/pci.h>
#include <linux/dma-mapping.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/mii.h>
#include <linux/ethtool.h>
#include <linux/crc32.h>
#include <linux/random.h>
#include <linux/workqueue.h>
#include <linux/if_vlan.h>
#include <linux/bitops.h>
#include <linux/mutex.h>
#include <linux/mm.h>
#include <asm/system.h>
#include <asm/io.h>
#include <asm/byteorder.h>
#include <asm/uaccess.h>
#include <asm/irq.h>
#ifdef CONFIG_SPARC
#include <asm/idprom.h>
#include <asm/prom.h>
#endif
#ifdef CONFIG_PPC_PMAC
#include <asm/pci-bridge.h>
#include <asm/prom.h>
#include <asm/machdep.h>
#include <asm/pmac_feature.h>
#endif
#include "sungem_phy.h"
#include "sungem.h"
/* Stripping FCS is causing problems, disabled for now */
#undef STRIP_FCS
#define DEFAULT_MSG (NETIF_MSG_DRV | \
NETIF_MSG_PROBE | \
NETIF_MSG_LINK)
#define ADVERTISE_MASK (SUPPORTED_10baseT_Half | SUPPORTED_10baseT_Full | \
SUPPORTED_100baseT_Half | SUPPORTED_100baseT_Full | \
SUPPORTED_1000baseT_Half | SUPPORTED_1000baseT_Full | \
SUPPORTED_Pause | SUPPORTED_Autoneg)
#define DRV_NAME "sungem"
#define DRV_VERSION "0.98"
#define DRV_RELDATE "8/24/03"
#define DRV_AUTHOR "David S. Miller (davem@redhat.com)"
static char version[] __devinitdata =
DRV_NAME ".c:v" DRV_VERSION " " DRV_RELDATE " " DRV_AUTHOR "\n";
MODULE_AUTHOR(DRV_AUTHOR);
MODULE_DESCRIPTION("Sun GEM Gbit ethernet driver");
MODULE_LICENSE("GPL");
#define GEM_MODULE_NAME "gem"
#define PFX GEM_MODULE_NAME ": "
static struct pci_device_id gem_pci_tbl[] = {
{ PCI_VENDOR_ID_SUN, PCI_DEVICE_ID_SUN_GEM,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
/* These models only differ from the original GEM in
* that their tx/rx fifos are of a different size and
* they only support 10/100 speeds. -DaveM
*
* Apple's GMAC does support gigabit on machines with
* the BCM54xx PHYs. -BenH
*/
{ PCI_VENDOR_ID_SUN, PCI_DEVICE_ID_SUN_RIO_GEM,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
{ PCI_VENDOR_ID_APPLE, PCI_DEVICE_ID_APPLE_UNI_N_GMAC,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
{ PCI_VENDOR_ID_APPLE, PCI_DEVICE_ID_APPLE_UNI_N_GMACP,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
{ PCI_VENDOR_ID_APPLE, PCI_DEVICE_ID_APPLE_UNI_N_GMAC2,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
{ PCI_VENDOR_ID_APPLE, PCI_DEVICE_ID_APPLE_K2_GMAC,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
{ PCI_VENDOR_ID_APPLE, PCI_DEVICE_ID_APPLE_SH_SUNGEM,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
{ PCI_VENDOR_ID_APPLE, PCI_DEVICE_ID_APPLE_IPID2_GMAC,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0UL },
{0, }
};
MODULE_DEVICE_TABLE(pci, gem_pci_tbl);
static u16 __phy_read(struct gem *gp, int phy_addr, int reg)
{
u32 cmd;
int limit = 10000;
cmd = (1 << 30);
cmd |= (2 << 28);
cmd |= (phy_addr << 23) & MIF_FRAME_PHYAD;
cmd |= (reg << 18) & MIF_FRAME_REGAD;
cmd |= (MIF_FRAME_TAMSB);
writel(cmd, gp->regs + MIF_FRAME);
while (--limit) {
cmd = readl(gp->regs + MIF_FRAME);
if (cmd & MIF_FRAME_TALSB)
break;
udelay(10);
}
if (!limit)
cmd = 0xffff;
return cmd & MIF_FRAME_DATA;
}
static inline int _phy_read(struct net_device *dev, int mii_id, int reg)
{
struct gem *gp = netdev_priv(dev);
return __phy_read(gp, mii_id, reg);
}
static inline u16 phy_read(struct gem *gp, int reg)
{
return __phy_read(gp, gp->mii_phy_addr, reg);
}
static void __phy_write(struct gem *gp, int phy_addr, int reg, u16 val)
{
u32 cmd;
int limit = 10000;
cmd = (1 << 30);
cmd |= (1 << 28);
cmd |= (phy_addr << 23) & MIF_FRAME_PHYAD;
cmd |= (reg << 18) & MIF_FRAME_REGAD;
cmd |= (MIF_FRAME_TAMSB);
cmd |= (val & MIF_FRAME_DATA);
writel(cmd, gp->regs + MIF_FRAME);
while (limit--) {
cmd = readl(gp->regs + MIF_FRAME);
if (cmd & MIF_FRAME_TALSB)
break;
udelay(10);
}
}
static inline void _phy_write(struct net_device *dev, int mii_id, int reg, int val)
{
struct gem *gp = netdev_priv(dev);
__phy_write(gp, mii_id, reg, val & 0xffff);
}
static inline void phy_write(struct gem *gp, int reg, u16 val)
{
__phy_write(gp, gp->mii_phy_addr, reg, val);
}
static inline void gem_enable_ints(struct gem *gp)
{
/* Enable all interrupts but TXDONE */
writel(GREG_STAT_TXDONE, gp->regs + GREG_IMASK);
}
static inline void gem_disable_ints(struct gem *gp)
{
/* Disable all interrupts, including TXDONE */
writel(GREG_STAT_NAPI | GREG_STAT_TXDONE, gp->regs + GREG_IMASK);
}
static void gem_get_cell(struct gem *gp)
{
BUG_ON(gp->cell_enabled < 0);
gp->cell_enabled++;
#ifdef CONFIG_PPC_PMAC
if (gp->cell_enabled == 1) {
mb();
pmac_call_feature(PMAC_FTR_GMAC_ENABLE, gp->of_node, 0, 1);
udelay(10);
}
#endif /* CONFIG_PPC_PMAC */
}
/* Turn off the chip's clock */
static void gem_put_cell(struct gem *gp)
{
BUG_ON(gp->cell_enabled <= 0);
gp->cell_enabled--;
#ifdef CONFIG_PPC_PMAC
if (gp->cell_enabled == 0) {
mb();
pmac_call_feature(PMAC_FTR_GMAC_ENABLE, gp->of_node, 0, 0);
udelay(10);
}
#endif /* CONFIG_PPC_PMAC */
}
static void gem_handle_mif_event(struct gem *gp, u32 reg_val, u32 changed_bits)
{
if (netif_msg_intr(gp))
printk(KERN_DEBUG "%s: mif interrupt\n", gp->dev->name);
}
static int gem_pcs_interrupt(struct net_device *dev, struct gem *gp, u32 gem_status)
{
u32 pcs_istat = readl(gp->regs + PCS_ISTAT);
u32 pcs_miistat;
if (netif_msg_intr(gp))
printk(KERN_DEBUG "%s: pcs interrupt, pcs_istat: 0x%x\n",
gp->dev->name, pcs_istat);
if (!(pcs_istat & PCS_ISTAT_LSC)) {
printk(KERN_ERR "%s: PCS irq but no link status change???\n",
dev->name);
return 0;
}
/* The link status bit latches on zero, so you must
* read it twice in such a case to see a transition
* to the link being up.
*/
pcs_miistat = readl(gp->regs + PCS_MIISTAT);
if (!(pcs_miistat & PCS_MIISTAT_LS))
pcs_miistat |=
(readl(gp->regs + PCS_MIISTAT) &
PCS_MIISTAT_LS);
if (pcs_miistat & PCS_MIISTAT_ANC) {
/* The remote-fault indication is only valid
* when autoneg has completed.
*/
if (pcs_miistat & PCS_MIISTAT_RF)
printk(KERN_INFO "%s: PCS AutoNEG complete, "
"RemoteFault\n", dev->name);
else
printk(KERN_INFO "%s: PCS AutoNEG complete.\n",
dev->name);
}
if (pcs_miistat & PCS_MIISTAT_LS) {
printk(KERN_INFO "%s: PCS link is now up.\n",
dev->name);
netif_carrier_on(gp->dev);
} else {
printk(KERN_INFO "%s: PCS link is now down.\n",
dev->name);
netif_carrier_off(gp->dev);
/* If this happens and the link timer is not running,
* reset so we re-negotiate.
*/
if (!timer_pending(&gp->link_timer))
return 1;
}
return 0;
}
static int gem_txmac_interrupt(struct net_device *dev, struct gem *gp, u32 gem_status)
{
u32 txmac_stat = readl(gp->regs + MAC_TXSTAT);
if (netif_msg_intr(gp))
printk(KERN_DEBUG "%s: txmac interrupt, txmac_stat: 0x%x\n",
gp->dev->name, txmac_stat);
/* Defer timer expiration is quite normal,
* don't even log the event.
*/
if ((txmac_stat & MAC_TXSTAT_DTE) &&
!(txmac_stat & ~MAC_TXSTAT_DTE))
return 0;
if (txmac_stat & MAC_TXSTAT_URUN) {
printk(KERN_ERR "%s: TX MAC xmit underrun.\n",
dev->name);
gp->net_stats.tx_fifo_errors++;
}
if (txmac_stat & MAC_TXSTAT_MPE) {
printk(KERN_ERR "%s: TX MAC max packet size error.\n",
dev->name);
gp->net_stats.tx_errors++;
}
/* The rest are all cases of one of the 16-bit TX
* counters expiring.
*/
if (txmac_stat & MAC_TXSTAT_NCE)
gp->net_stats.collisions += 0x10000;
if (txmac_stat & MAC_TXSTAT_ECE) {
gp->net_stats.tx_aborted_errors += 0x10000;
gp->net_stats.collisions += 0x10000;
}
if (txmac_stat & MAC_TXSTAT_LCE) {
gp->net_stats.tx_aborted_errors += 0x10000;
gp->net_stats.collisions += 0x10000;
}
/* We do not keep track of MAC_TXSTAT_FCE and
* MAC_TXSTAT_PCE events.
*/
return 0;
}
/* When we get a RX fifo overflow, the RX unit in GEM is probably hung
* so we do the following.
*
* If any part of the reset goes wrong, we return 1 and that causes the
* whole chip to be reset.
*/
static int gem_rxmac_reset(struct gem *gp)
{
struct net_device *dev = gp->dev;
int limit, i;
u64 desc_dma;
u32 val;
/* First, reset & disable MAC RX. */
writel(MAC_RXRST_CMD, gp->regs + MAC_RXRST);
for (limit = 0; limit < 5000; limit++) {
if (!(readl(gp->regs + MAC_RXRST) & MAC_RXRST_CMD))
break;
udelay(10);
}
if (limit == 5000) {
printk(KERN_ERR "%s: RX MAC will not reset, resetting whole "
"chip.\n", dev->name);
return 1;
}
writel(gp->mac_rx_cfg & ~MAC_RXCFG_ENAB,
gp->regs + MAC_RXCFG);
for (limit = 0; limit < 5000; limit++) {
if (!(readl(gp->regs + MAC_RXCFG) & MAC_RXCFG_ENAB))
break;
udelay(10);
}
if (limit == 5000) {
printk(KERN_ERR "%s: RX MAC will not disable, resetting whole "
"chip.\n", dev->name);
return 1;
}
/* Second, disable RX DMA. */
writel(0, gp->regs + RXDMA_CFG);
for (limit = 0; limit < 5000; limit++) {
if (!(readl(gp->regs + RXDMA_CFG) & RXDMA_CFG_ENABLE))
break;
udelay(10);
}
if (limit == 5000) {
printk(KERN_ERR "%s: RX DMA will not disable, resetting whole "
"chip.\n", dev->name);
return 1;
}
udelay(5000);
/* Execute RX reset command. */
writel(gp->swrst_base | GREG_SWRST_RXRST,
gp->regs + GREG_SWRST);
for (limit = 0; limit < 5000; limit++) {
if (!(readl(gp->regs + GREG_SWRST) & GREG_SWRST_RXRST))
break;
udelay(10);
}
if (limit == 5000) {
printk(KERN_ERR "%s: RX reset command will not execute, resetting "
"whole chip.\n", dev->name);
return 1;
}
/* Refresh the RX ring. */
for (i = 0; i < RX_RING_SIZE; i++) {
struct gem_rxd *rxd = &gp->init_block->rxd[i];
if (gp->rx_skbs[i] == NULL) {
printk(KERN_ERR "%s: Parts of RX ring empty, resetting "
"whole chip.\n", dev->name);
return 1;
}
rxd->status_word = cpu_to_le64(RXDCTRL_FRESH(gp));
}
gp->rx_new = gp->rx_old = 0;
/* Now we must reprogram the rest of RX unit. */
desc_dma = (u64) gp->gblock_dvma;
desc_dma += (INIT_BLOCK_TX_RING_SIZE * sizeof(struct gem_txd));
writel(desc_dma >> 32, gp->regs + RXDMA_DBHI);
writel(desc_dma & 0xffffffff, gp->regs + RXDMA_DBLOW);
writel(RX_RING_SIZE - 4, gp->regs + RXDMA_KICK);
val = (RXDMA_CFG_BASE | (RX_OFFSET << 10) |
((14 / 2) << 13) | RXDMA_CFG_FTHRESH_128);
writel(val, gp->regs + RXDMA_CFG);
if (readl(gp->regs + GREG_BIFCFG) & GREG_BIFCFG_M66EN)
writel(((5 & RXDMA_BLANK_IPKTS) |
((8 << 12) & RXDMA_BLANK_ITIME)),
gp->regs + RXDMA_BLANK);
else
writel(((5 & RXDMA_BLANK_IPKTS) |
((4 << 12) & RXDMA_BLANK_ITIME)),
gp->regs + RXDMA_BLANK);
val = (((gp->rx_pause_off / 64) << 0) & RXDMA_PTHRESH_OFF);
val |= (((gp->rx_pause_on / 64) << 12) & RXDMA_PTHRESH_ON);
writel(val, gp->regs + RXDMA_PTHRESH);
val = readl(gp->regs + RXDMA_CFG);
writel(val | RXDMA_CFG_ENABLE, gp->regs + RXDMA_CFG);
writel(MAC_RXSTAT_RCV, gp->regs + MAC_RXMASK);
val = readl(gp->regs + MAC_RXCFG);
writel(val | MAC_RXCFG_ENAB, gp->regs + MAC_RXCFG);
return 0;
}
static int gem_rxmac_interrupt(struct net_device *dev, struct gem *gp, u32 gem_status)
{
u32 rxmac_stat = readl(gp->regs + MAC_RXSTAT);
int ret = 0;
if (netif_msg_intr(gp))
printk(KERN_DEBUG "%s: rxmac interrupt, rxmac_stat: 0x%x\n",
gp->dev->name, rxmac_stat);
if (rxmac_stat & MAC_RXSTAT_OFLW) {
u32 smac = readl(gp->regs + MAC_SMACHINE);
printk(KERN_ERR "%s: RX MAC fifo overflow smac[%08x].\n",
dev->name, smac);
gp->net_stats.rx_over_errors++;
gp->net_stats.rx_fifo_errors++;
ret = gem_rxmac_reset(gp);
}
if (rxmac_stat & MAC_RXSTAT_ACE)
gp->net_stats.rx_frame_errors += 0x10000;
if (rxmac_stat & MAC_RXSTAT_CCE)
gp->net_stats.rx_crc_errors += 0x10000;
if (rxmac_stat & MAC_RXSTAT_LCE)
gp->net_stats.rx_length_errors += 0x10000;
/* We do not track MAC_RXSTAT_FCE and MAC_RXSTAT_VCE
* events.
*/
return ret;
}
static int gem_mac_interrupt(struct net_device *dev, struct gem *gp, u32 gem_status)
{
u32 mac_cstat = readl(gp->regs + MAC_CSTAT);
if (netif_msg_intr(gp))
printk(KERN_DEBUG "%s: mac interrupt, mac_cstat: 0x%x\n",
gp->dev->name, mac_cstat);
/* This interrupt is just for pause frame and pause
* tracking. It is useful for diagnostics and debug
* but probably by default we will mask these events.
*/
if (mac_cstat & MAC_CSTAT_PS)
gp->pause_entered++;
if (mac_cstat & MAC_CSTAT_PRCV)
gp->pause_last_time_recvd = (mac_cstat >> 16);
return 0;
}
static int gem_mif_interrupt(struct net_device *dev, struct gem *gp, u32 gem_status)
{
u32 mif_status = readl(gp->regs + MIF_STATUS);
u32 reg_val, changed_bits;
reg_val = (mif_status & MIF_STATUS_DATA) >> 16;
changed_bits = (mif_status & MIF_STATUS_STAT);
gem_handle_mif_event(gp, reg_val, changed_bits);
return 0;
}
static int gem_pci_interrupt(struct net_device *dev, struct gem *gp, u32 gem_status)
{
u32 pci_estat = readl(gp->regs + GREG_PCIESTAT);
if (gp->pdev->vendor == PCI_VENDOR_ID_SUN &&
gp->pdev->device == PCI_DEVICE_ID_SUN_GEM) {
printk(KERN_ERR "%s: PCI error [%04x] ",
dev->name, pci_estat);
if (pci_estat & GREG_PCIESTAT_BADACK)
printk("<No ACK64# during ABS64 cycle> ");
if (pci_estat & GREG_PCIESTAT_DTRTO)
printk("<Delayed transaction timeout> ");
if (pci_estat & GREG_PCIESTAT_OTHER)
printk("<other>");
printk("\n");
} else {
pci_estat |= GREG_PCIESTAT_OTHER;
printk(KERN_ERR "%s: PCI error\n", dev->name);
}
if (pci_estat & GREG_PCIESTAT_OTHER) {
u16 pci_cfg_stat;
/* Interrogate PCI config space for the
* true cause.
*/
pci_read_config_word(gp->pdev, PCI_STATUS,
&pci_cfg_stat);
printk(KERN_ERR "%s: Read PCI cfg space status [%04x]\n",
dev->name, pci_cfg_stat);
if (pci_cfg_stat & PCI_STATUS_PARITY)
printk(KERN_ERR "%s: PCI parity error detected.\n",
dev->name);
if (pci_cfg_stat & PCI_STATUS_SIG_TARGET_ABORT)
printk(KERN_ERR "%s: PCI target abort.\n",
dev->name);
if (pci_cfg_stat & PCI_STATUS_REC_TARGET_ABORT)
printk(KERN_ERR "%s: PCI master acks target abort.\n",
dev->name);
if (pci_cfg_stat & PCI_STATUS_REC_MASTER_ABORT)
printk(KERN_ERR "%s: PCI master abort.\n",
dev->name);
if (pci_cfg_stat & PCI_STATUS_SIG_SYSTEM_ERROR)
printk(KERN_ERR "%s: PCI system error SERR#.\n",
dev->name);
if (pci_cfg_stat & PCI_STATUS_DETECTED_PARITY)
printk(KERN_ERR "%s: PCI parity error.\n",
dev->name);
/* Write the error bits back to clear them. */
pci_cfg_stat &= (PCI_STATUS_PARITY |
PCI_STATUS_SIG_TARGET_ABORT |
PCI_STATUS_REC_TARGET_ABORT |
PCI_STATUS_REC_MASTER_ABORT |
PCI_STATUS_SIG_SYSTEM_ERROR |
PCI_STATUS_DETECTED_PARITY);
pci_write_config_word(gp->pdev,
PCI_STATUS, pci_cfg_stat);
}
/* For all PCI errors, we should reset the chip. */
return 1;
}
/* All non-normal interrupt conditions get serviced here.
* Returns non-zero if we should just exit the interrupt
* handler right now (ie. if we reset the card which invalidates
* all of the other original irq status bits).
*/
static int gem_abnormal_irq(struct net_device *dev, struct gem *gp, u32 gem_status)
{
if (gem_status & GREG_STAT_RXNOBUF) {
/* Frame arrived, no free RX buffers available. */
if (netif_msg_rx_err(gp))
printk(KERN_DEBUG "%s: no buffer for rx frame\n",
gp->dev->name);
gp->net_stats.rx_dropped++;
}
if (gem_status & GREG_STAT_RXTAGERR) {
/* corrupt RX tag framing */
if (netif_msg_rx_err(gp))
printk(KERN_DEBUG "%s: corrupt rx tag framing\n",
gp->dev->name);
gp->net_stats.rx_errors++;
goto do_reset;
}
if (gem_status & GREG_STAT_PCS) {
if (gem_pcs_interrupt(dev, gp, gem_status))
goto do_reset;
}
if (gem_status & GREG_STAT_TXMAC) {
if (gem_txmac_interrupt(dev, gp, gem_status))
goto do_reset;
}
if (gem_status & GREG_STAT_RXMAC) {
if (gem_rxmac_interrupt(dev, gp, gem_status))
goto do_reset;
}
if (gem_status & GREG_STAT_MAC) {
if (gem_mac_interrupt(dev, gp, gem_status))
goto do_reset;
}
if (gem_status & GREG_STAT_MIF) {
if (gem_mif_interrupt(dev, gp, gem_status))
goto do_reset;
}
if (gem_status & GREG_STAT_PCIERR) {
if (gem_pci_interrupt(dev, gp, gem_status))
goto do_reset;
}
return 0;
do_reset:
gp->reset_task_pending = 1;
schedule_work(&gp->reset_task);
return 1;
}
static __inline__ void gem_tx(struct net_device *dev, struct gem *gp, u32 gem_status)
{
int entry, limit;
if (netif_msg_intr(gp))
printk(KERN_DEBUG "%s: tx interrupt, gem_status: 0x%x\n",
gp->dev->name, gem_status);
entry = gp->tx_old;
limit = ((gem_status & GREG_STAT_TXNR) >> GREG_STAT_TXNR_SHIFT);
while (entry != limit) {
struct sk_buff *skb;
struct gem_txd *txd;
dma_addr_t dma_addr;
u32 dma_len;
int frag;
if (netif_msg_tx_done(gp))
printk(KERN_DEBUG "%s: tx done, slot %d\n",
gp->dev->name, entry);
skb = gp->tx_skbs[entry];
if (skb_shinfo(skb)->nr_frags) {
int last = entry + skb_shinfo(skb)->nr_frags;
int walk = entry;
int incomplete = 0;
last &= (TX_RING_SIZE - 1);
for (;;) {
walk = NEXT_TX(walk);
if (walk == limit)
incomplete = 1;
if (walk == last)
break;
}
if (incomplete)
break;
}
gp->tx_skbs[entry] = NULL;
gp->net_stats.tx_bytes += skb->len;
for (frag = 0; frag <= skb_shinfo(skb)->nr_frags; frag++) {
txd = &gp->init_block->txd[entry];
dma_addr = le64_to_cpu(txd->buffer);
dma_len = le64_to_cpu(txd->control_word) & TXDCTRL_BUFSZ;
pci_unmap_page(gp->pdev, dma_addr, dma_len, PCI_DMA_TODEVICE);
entry = NEXT_TX(entry);
}
gp->net_stats.tx_packets++;
dev_kfree_skb_irq(skb);
}
gp->tx_old = entry;
if (netif_queue_stopped(dev) &&
TX_BUFFS_AVAIL(gp) > (MAX_SKB_FRAGS + 1))
netif_wake_queue(dev);
}
static __inline__ void gem_post_rxds(struct gem *gp, int limit)
{
int cluster_start, curr, count, kick;
cluster_start = curr = (gp->rx_new & ~(4 - 1));
count = 0;
kick = -1;
wmb();
while (curr != limit) {
curr = NEXT_RX(curr);
if (++count == 4) {
struct gem_rxd *rxd =
&gp->init_block->rxd[cluster_start];
for (;;) {
rxd->status_word = cpu_to_le64(RXDCTRL_FRESH(gp));
rxd++;
cluster_start = NEXT_RX(cluster_start);
if (cluster_start == curr)
break;
}
kick = curr;
count = 0;
}
}
if (kick >= 0) {
mb();
writel(kick, gp->regs + RXDMA_KICK);
}
}
static int gem_rx(struct gem *gp, int work_to_do)
{
int entry, drops, work_done = 0;
u32 done;
__sum16 csum;
if (netif_msg_rx_status(gp))
printk(KERN_DEBUG "%s: rx interrupt, done: %d, rx_new: %d\n",
gp->dev->name, readl(gp->regs + RXDMA_DONE), gp->rx_new);
entry = gp->rx_new;
drops = 0;
done = readl(gp->regs + RXDMA_DONE);
for (;;) {
struct gem_rxd *rxd = &gp->init_block->rxd[entry];
struct sk_buff *skb;
u64 status = le64_to_cpu(rxd->status_word);
dma_addr_t dma_addr;
int len;
if ((status & RXDCTRL_OWN) != 0)
break;
if (work_done >= RX_RING_SIZE || work_done >= work_to_do)
break;
/* When writing back RX descriptor, GEM writes status
* then buffer address, possibly in seperate transactions.
* If we don't wait for the chip to write both, we could
* post a new buffer to this descriptor then have GEM spam
* on the buffer address. We sync on the RX completion
* register to prevent this from happening.
*/
if (entry == done) {
done = readl(gp->regs + RXDMA_DONE);
if (entry == done)
break;
}
/* We can now account for the work we're about to do */
work_done++;
skb = gp->rx_skbs[entry];
len = (status & RXDCTRL_BUFSZ) >> 16;
if ((len < ETH_ZLEN) || (status & RXDCTRL_BAD)) {
gp->net_stats.rx_errors++;
if (len < ETH_ZLEN)
gp->net_stats.rx_length_errors++;
if (len & RXDCTRL_BAD)
gp->net_stats.rx_crc_errors++;
/* We'll just return it to GEM. */
drop_it:
gp->net_stats.rx_dropped++;
goto next;
}
dma_addr = le64_to_cpu(rxd->buffer);
if (len > RX_COPY_THRESHOLD) {
struct sk_buff *new_skb;
new_skb = gem_alloc_skb(RX_BUF_ALLOC_SIZE(gp), GFP_ATOMIC);
if (new_skb == NULL) {
drops++;
goto drop_it;
}
pci_unmap_page(gp->pdev, dma_addr,
RX_BUF_ALLOC_SIZE(gp),
PCI_DMA_FROMDEVICE);
gp->rx_skbs[entry] = new_skb;
new_skb->dev = gp->dev;
skb_put(new_skb, (gp->rx_buf_sz + RX_OFFSET));
rxd->buffer = cpu_to_le64(pci_map_page(gp->pdev,
virt_to_page(new_skb->data),
offset_in_page(new_skb->data),
RX_BUF_ALLOC_SIZE(gp),
PCI_DMA_FROMDEVICE));
skb_reserve(new_skb, RX_OFFSET);
/* Trim the original skb for the netif. */
skb_trim(skb, len);
} else {
struct sk_buff *copy_skb = dev_alloc_skb(len + 2);
if (copy_skb == NULL) {
drops++;
goto drop_it;
}
skb_reserve(copy_skb, 2);
skb_put(copy_skb, len);
pci_dma_sync_single_for_cpu(gp->pdev, dma_addr, len, PCI_DMA_FROMDEVICE);
skb_copy_from_linear_data(skb, copy_skb->data, len);
pci_dma_sync_single_for_device(gp->pdev, dma_addr, len, PCI_DMA_FROMDEVICE);
/* We'll reuse the original ring buffer. */
skb = copy_skb;
}
csum = (__force __sum16)htons((status & RXDCTRL_TCPCSUM) ^ 0xffff);
skb->csum = csum_unfold(csum);
skb->ip_summed = CHECKSUM_COMPLETE;
skb->protocol = eth_type_trans(skb, gp->dev);
netif_receive_skb(skb);
gp->net_stats.rx_packets++;
gp->net_stats.rx_bytes += len;
next:
entry = NEXT_RX(entry);
}
gem_post_rxds(gp, entry);
gp->rx_new = entry;
if (drops)
printk(KERN_INFO "%s: Memory squeeze, deferring packet.\n",
gp->dev->name);
return work_done;
}
static int gem_poll(struct napi_struct *napi, int budget)
{
struct gem *gp = container_of(napi, struct gem, napi);
struct net_device *dev = gp->dev;
unsigned long flags;
int work_done;
/*
* NAPI locking nightmare: See comment at head of driver
*/
spin_lock_irqsave(&gp->lock, flags);
work_done = 0;
do {
/* Handle anomalies */
if (gp->status & GREG_STAT_ABNORMAL) {
if (gem_abnormal_irq(dev, gp, gp->status))
break;
}
/* Run TX completion thread */
spin_lock(&gp->tx_lock);
gem_tx(dev, gp, gp->status);
spin_unlock(&gp->tx_lock);
spin_unlock_irqrestore(&gp->lock, flags);
/* Run RX thread. We don't use any locking here,
* code willing to do bad things - like cleaning the
* rx ring - must call napi_disable(), which
* schedule_timeout()'s if polling is already disabled.
*/
work_done += gem_rx(gp, budget - work_done);
if (work_done >= budget)
return work_done;
spin_lock_irqsave(&gp->lock, flags);
gp->status = readl(gp->regs + GREG_STAT);
} while (gp->status & GREG_STAT_NAPI);
__napi_complete(napi);
gem_enable_ints(gp);
spin_unlock_irqrestore(&gp->lock, flags);
return work_done;
}
static irqreturn_t gem_interrupt(int irq, void *dev_id)
{
struct net_device *dev = dev_id;
struct gem *gp = netdev_priv(dev);
unsigned long flags;
/* Swallow interrupts when shutting the chip down, though
* that shouldn't happen, we should have done free_irq() at
* this point...
*/
if (!gp->running)
return IRQ_HANDLED;
spin_lock_irqsave(&gp->lock, flags);
if (napi_schedule_prep(&gp->napi)) {
u32 gem_status = readl(gp->regs + GREG_STAT);
if (gem_status == 0) {
napi_enable(&gp->napi);
spin_unlock_irqrestore(&gp->lock, flags);
return IRQ_NONE;
}
gp->status = gem_status;
gem_disable_ints(gp);
__napi_schedule(&gp->napi);
}
spin_unlock_irqrestore(&gp->lock, flags);
/* If polling was disabled at the time we received that
* interrupt, we may return IRQ_HANDLED here while we
* should return IRQ_NONE. No big deal...
*/
return IRQ_HANDLED;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void gem_poll_controller(struct net_device *dev)
{
/* gem_interrupt is safe to reentrance so no need
* to disable_irq here.
*/
gem_interrupt(dev->irq, dev);
}
#endif
static void gem_tx_timeout(struct net_device *dev)
{
struct gem *gp = netdev_priv(dev);
printk(KERN_ERR "%s: transmit timed out, resetting\n", dev->name);
if (!gp->running) {
printk("%s: hrm.. hw not running !\n", dev->name);
return;
}
printk(KERN_ERR "%s: TX_STATE[%08x:%08x:%08x]\n",
dev->name,
readl(gp->regs + TXDMA_CFG),
readl(gp->regs + MAC_TXSTAT),
readl(gp->regs + MAC_TXCFG));
printk(KERN_ERR "%s: RX_STATE[%08x:%08x:%08x]\n",
dev->name,
readl(gp->regs + RXDMA_CFG),
readl(gp->regs + MAC_RXSTAT),
readl(gp->regs + MAC_RXCFG));
spin_lock_irq(&gp->lock);
spin_lock(&gp->tx_lock);
gp->reset_task_pending = 1;
schedule_work(&gp->reset_task);
spin_unlock(&gp->tx_lock);
spin_unlock_irq(&gp->lock);
}
static __inline__ int gem_intme(int entry)
{
/* Algorithm: IRQ every 1/2 of descriptors. */
if (!(entry & ((TX_RING_SIZE>>1)-1)))
return 1;
return 0;
}
static netdev_tx_t gem_start_xmit(struct sk_buff *skb,
struct net_device *dev)
{
struct gem *gp = netdev_priv(dev);
int entry;
u64 ctrl;
unsigned long flags;
ctrl = 0;
if (skb->ip_summed == CHECKSUM_PARTIAL) {
const u64 csum_start_off = skb_transport_offset(skb);
const u64 csum_stuff_off = csum_start_off + skb->csum_offset;
ctrl = (TXDCTRL_CENAB |
(csum_start_off << 15) |
(csum_stuff_off << 21));
}
local_irq_save(flags);
if (!spin_trylock(&gp->tx_lock)) {
/* Tell upper layer to requeue */
local_irq_restore(flags);
return NETDEV_TX_LOCKED;
}
/* We raced with gem_do_stop() */
if (!gp->running) {
spin_unlock_irqrestore(&gp->tx_lock, flags);
return NETDEV_TX_BUSY;
}
/* This is a hard error, log it. */
if (TX_BUFFS_AVAIL(gp) <= (skb_shinfo(skb)->nr_frags + 1)) {
netif_stop_queue(dev);
spin_unlock_irqrestore(&gp->tx_lock, flags);
printk(KERN_ERR PFX "%s: BUG! Tx Ring full when queue awake!\n",
dev->name);
return NETDEV_TX_BUSY;
}
entry = gp->tx_new;
gp->tx_skbs[entry] = skb;
if (skb_shinfo(skb)->nr_frags == 0) {
struct gem_txd *txd = &gp->init_block->txd[entry];
dma_addr_t mapping;
u32 len;
len = skb->len;
mapping = pci_map_page(gp->pdev,
virt_to_page(skb->data),
offset_in_page(skb->data),
len, PCI_DMA_TODEVICE);
ctrl |= TXDCTRL_SOF | TXDCTRL_EOF | len;
if (gem_intme(entry))
ctrl |= TXDCTRL_INTME;
txd->buffer = cpu_to_le64(mapping);
wmb();
txd->control_word = cpu_to_le64(ctrl);
entry = NEXT_TX(entry);
} else {
struct gem_txd *txd;
u32 first_len;
u64 intme;
dma_addr_t first_mapping;
int frag, first_entry = entry;
intme = 0;
if (gem_intme(entry))
intme |= TXDCTRL_INTME;
/* We must give this initial chunk to the device last.
* Otherwise we could race with the device.
*/
first_len = skb_headlen(skb);
first_mapping = pci_map_page(gp->pdev, virt_to_page(skb->data),
offset_in_page(skb->data),
first_len, PCI_DMA_TODEVICE);
entry = NEXT_TX(entry);
for (frag = 0; frag < skb_shinfo(skb)->nr_frags; frag++) {
skb_frag_t *this_frag = &skb_shinfo(skb)->frags[frag];
u32 len;
dma_addr_t mapping;
u64 this_ctrl;
len = this_frag->size;
mapping = pci_map_page(gp->pdev,
this_frag->page,
this_frag->page_offset,
len, PCI_DMA_TODEVICE);
this_ctrl = ctrl;
if (frag == skb_shinfo(skb)->nr_frags - 1)
this_ctrl |= TXDCTRL_EOF;
txd = &gp->init_block->txd[entry];
txd->buffer = cpu_to_le64(mapping);
wmb();
txd->control_word = cpu_to_le64(this_ctrl | len);
if (gem_intme(entry))
intme |= TXDCTRL_INTME;
entry = NEXT_TX(entry);
}
txd = &gp->init_block->txd[first_entry];
txd->buffer = cpu_to_le64(first_mapping);
wmb();
txd->control_word =
cpu_to_le64(ctrl | TXDCTRL_SOF | intme | first_len);
}
gp->tx_new = entry;
if (TX_BUFFS_AVAIL(gp) <= (MAX_SKB_FRAGS + 1))
netif_stop_queue(dev);
if (netif_msg_tx_queued(gp))
printk(KERN_DEBUG "%s: tx queued, slot %d, skblen %d\n",
dev->name, entry, skb->len);
mb();
writel(gp->tx_new, gp->regs + TXDMA_KICK);
spin_unlock_irqrestore(&gp->tx_lock, flags);
dev->trans_start = jiffies;
return NETDEV_TX_OK;
}
static void gem_pcs_reset(struct gem *gp)
{
int limit;
u32 val;
/* Reset PCS unit. */
val = readl(gp->regs + PCS_MIICTRL);
val |= PCS_MIICTRL_RST;
writel(val, gp->regs + PCS_MIICTRL);
limit = 32;
while (readl(gp->regs + PCS_MIICTRL) & PCS_MIICTRL_RST) {
udelay(100);
if (limit-- <= 0)
break;
}
if (limit < 0)
printk(KERN_WARNING "%s: PCS reset bit would not clear.\n",
gp->dev->name);
}
static void gem_pcs_reinit_adv(struct gem *gp)
{
u32 val;
/* Make sure PCS is disabled while changing advertisement
* configuration.
*/
val = readl(gp->regs + PCS_CFG);
val &= ~(PCS_CFG_ENABLE | PCS_CFG_TO);
writel(val, gp->regs + PCS_CFG);
/* Advertise all capabilities except assymetric
* pause.
*/
val = readl(gp->regs + PCS_MIIADV);
val |= (PCS_MIIADV_FD | PCS_MIIADV_HD |
PCS_MIIADV_SP | PCS_MIIADV_AP);
writel(val, gp->regs + PCS_MIIADV);
/* Enable and restart auto-negotiation, disable wrapback/loopback,
* and re-enable PCS.
*/
val = readl(gp->regs + PCS_MIICTRL);
val |= (PCS_MIICTRL_RAN | PCS_MIICTRL_ANE);
val &= ~PCS_MIICTRL_WB;
writel(val, gp->regs + PCS_MIICTRL);
val = readl(gp->regs + PCS_CFG);
val |= PCS_CFG_ENABLE;
writel(val, gp->regs + PCS_CFG);
/* Make sure serialink loopback is off. The meaning
* of this bit is logically inverted based upon whether
* you are in Serialink or SERDES mode.
*/
val = readl(gp->regs + PCS_SCTRL);
if (gp->phy_type == phy_serialink)
val &= ~PCS_SCTRL_LOOP;
else
val |= PCS_SCTRL_LOOP;
writel(val, gp->regs + PCS_SCTRL);
}
#define STOP_TRIES 32
/* Must be invoked under gp->lock and gp->tx_lock. */
static void gem_reset(struct gem *gp)
{
int limit;
u32 val;
/* Make sure we won't get any more interrupts */
writel(0xffffffff, gp->regs + GREG_IMASK);
/* Reset the chip */
writel(gp->swrst_base | GREG_SWRST_TXRST | GREG_SWRST_RXRST,
gp->regs + GREG_SWRST);
limit = STOP_TRIES;
do {
udelay(20);
val = readl(gp->regs + GREG_SWRST);
if (limit-- <= 0)
break;
} while (val & (GREG_SWRST_TXRST | GREG_SWRST_RXRST));
if (limit < 0)
printk(KERN_ERR "%s: SW reset is ghetto.\n", gp->dev->name);
if (gp->phy_type == phy_serialink || gp->phy_type == phy_serdes)
gem_pcs_reinit_adv(gp);
}
/* Must be invoked under gp->lock and gp->tx_lock. */
static void gem_start_dma(struct gem *gp)
{
u32 val;
/* We are ready to rock, turn everything on. */
val = readl(gp->regs + TXDMA_CFG);
writel(val | TXDMA_CFG_ENABLE, gp->regs + TXDMA_CFG);
val = readl(gp->regs + RXDMA_CFG);
writel(val | RXDMA_CFG_ENABLE, gp->regs + RXDMA_CFG);
val = readl(gp->regs + MAC_TXCFG);
writel(val | MAC_TXCFG_ENAB, gp->regs + MAC_TXCFG);
val = readl(gp->regs + MAC_RXCFG);
writel(val | MAC_RXCFG_ENAB, gp->regs + MAC_RXCFG);
(void) readl(gp->regs + MAC_RXCFG);
udelay(100);
gem_enable_ints(gp);
writel(RX_RING_SIZE - 4, gp->regs + RXDMA_KICK);
}
/* Must be invoked under gp->lock and gp->tx_lock. DMA won't be
* actually stopped before about 4ms tho ...
*/
static void gem_stop_dma(struct gem *gp)
{
u32 val;
/* We are done rocking, turn everything off. */
val = readl(gp->regs + TXDMA_CFG);
writel(val & ~TXDMA_CFG_ENABLE, gp->regs + TXDMA_CFG);
val = readl(gp->regs + RXDMA_CFG);
writel(val & ~RXDMA_CFG_ENABLE, gp->regs + RXDMA_CFG);
val = readl(gp->regs + MAC_TXCFG);
writel(val & ~MAC_TXCFG_ENAB, gp->regs + MAC_TXCFG);
val = readl(gp->regs + MAC_RXCFG);
writel(val & ~MAC_RXCFG_ENAB, gp->regs + MAC_RXCFG);
(void) readl(gp->regs + MAC_RXCFG);
/* Need to wait a bit ... done by the caller */
}
/* Must be invoked under gp->lock and gp->tx_lock. */
// XXX dbl check what that function should do when called on PCS PHY
static void gem_begin_auto_negotiation(struct gem *gp, struct ethtool_cmd *ep)
{
u32 advertise, features;
int autoneg;
int speed;
int duplex;
if (gp->phy_type != phy_mii_mdio0 &&
gp->phy_type != phy_mii_mdio1)
goto non_mii;
/* Setup advertise */
if (found_mii_phy(gp))
features = gp->phy_mii.def->features;
else
features = 0;
advertise = features & ADVERTISE_MASK;
if (gp->phy_mii.advertising != 0)
advertise &= gp->phy_mii.advertising;
autoneg = gp->want_autoneg;
speed = gp->phy_mii.speed;
duplex = gp->phy_mii.duplex;
/* Setup link parameters */
if (!ep)
goto start_aneg;
if (ep->autoneg == AUTONEG_ENABLE) {
advertise = ep->advertising;
autoneg = 1;
} else {
autoneg = 0;
speed = ep->speed;
duplex = ep->duplex;
}
start_aneg:
/* Sanitize settings based on PHY capabilities */
if ((features & SUPPORTED_Autoneg) == 0)
autoneg = 0;
if (speed == SPEED_1000 &&
!(features & (SUPPORTED_1000baseT_Half | SUPPORTED_1000baseT_Full)))
speed = SPEED_100;
if (speed == SPEED_100 &&
!(features & (SUPPORTED_100baseT_Half | SUPPORTED_100baseT_Full)))
speed = SPEED_10;
if (duplex == DUPLEX_FULL &&
!(features & (SUPPORTED_1000baseT_Full |
SUPPORTED_100baseT_Full |
SUPPORTED_10baseT_Full)))
duplex = DUPLEX_HALF;
if (speed == 0)
speed = SPEED_10;
/* If we are asleep, we don't try to actually setup the PHY, we
* just store the settings
*/
if (gp->asleep) {
gp->phy_mii.autoneg = gp->want_autoneg = autoneg;
gp->phy_mii.speed = speed;
gp->phy_mii.duplex = duplex;
return;
}
/* Configure PHY & start aneg */
gp->want_autoneg = autoneg;
if (autoneg) {
if (found_mii_phy(gp))
gp->phy_mii.def->ops->setup_aneg(&gp->phy_mii, advertise);
gp->lstate = link_aneg;
} else {
if (found_mii_phy(gp))
gp->phy_mii.def->ops->setup_forced(&gp->phy_mii, speed, duplex);
gp->lstate = link_force_ok;
}
non_mii:
gp->timer_ticks = 0;
mod_timer(&gp->link_timer, jiffies + ((12 * HZ) / 10));
}
/* A link-up condition has occurred, initialize and enable the
* rest of the chip.
*
* Must be invoked under gp->lock and gp->tx_lock.
*/
static int gem_set_link_modes(struct gem *gp)
{
u32 val;
int full_duplex, speed, pause;
full_duplex = 0;
speed = SPEED_10;
pause = 0;
if (found_mii_phy(gp)) {
if (gp->phy_mii.def->ops->read_link(&gp->phy_mii))
return 1;
full_duplex = (gp->phy_mii.duplex == DUPLEX_FULL);
speed = gp->phy_mii.speed;
pause = gp->phy_mii.pause;
} else if (gp->phy_type == phy_serialink ||
gp->phy_type == phy_serdes) {
u32 pcs_lpa = readl(gp->regs + PCS_MIILP);
if ((pcs_lpa & PCS_MIIADV_FD) || gp->phy_type == phy_serdes)
full_duplex = 1;
speed = SPEED_1000;
}
if (netif_msg_link(gp))
printk(KERN_INFO "%s: Link is up at %d Mbps, %s-duplex.\n",
gp->dev->name, speed, (full_duplex ? "full" : "half"));
if (!gp->running)
return 0;
val = (MAC_TXCFG_EIPG0 | MAC_TXCFG_NGU);
if (full_duplex) {
val |= (MAC_TXCFG_ICS | MAC_TXCFG_ICOLL);
} else {
/* MAC_TXCFG_NBO must be zero. */
}
writel(val, gp->regs + MAC_TXCFG);
val = (MAC_XIFCFG_OE | MAC_XIFCFG_LLED);
if (!full_duplex &&
(gp->phy_type == phy_mii_mdio0 ||
gp->phy_type == phy_mii_mdio1)) {
val |= MAC_XIFCFG_DISE;
} else if (full_duplex) {
val |= MAC_XIFCFG_FLED;
}
if (speed == SPEED_1000)
val |= (MAC_XIFCFG_GMII);
writel(val, gp->regs + MAC_XIFCFG);
/* If gigabit and half-duplex, enable carrier extension
* mode. Else, disable it.
*/
if (speed == SPEED_1000 && !full_duplex) {
val = readl(gp->regs + MAC_TXCFG);
writel(val | MAC_TXCFG_TCE, gp->regs + MAC_TXCFG);
val = readl(gp->regs + MAC_RXCFG);
writel(val | MAC_RXCFG_RCE, gp->regs + MAC_RXCFG);
} else {
val = readl(gp->regs + MAC_TXCFG);
writel(val & ~MAC_TXCFG_TCE, gp->regs + MAC_TXCFG);
val = readl(gp->regs + MAC_RXCFG);
writel(val & ~MAC_RXCFG_RCE, gp->regs + MAC_RXCFG);
}
if (gp->phy_type == phy_serialink ||
gp->phy_type == phy_serdes) {
u32 pcs_lpa = readl(gp->regs + PCS_MIILP);
if (pcs_lpa & (PCS_MIIADV_SP | PCS_MIIADV_AP))
pause = 1;
}
if (netif_msg_link(gp)) {
if (pause) {
printk(KERN_INFO "%s: Pause is enabled "
"(rxfifo: %d off: %d on: %d)\n",
gp->dev->name,
gp->rx_fifo_sz,
gp->rx_pause_off,
gp->rx_pause_on);
} else {
printk(KERN_INFO "%s: Pause is disabled\n",
gp->dev->name);
}
}
if (!full_duplex)
writel(512, gp->regs + MAC_STIME);
else
writel(64, gp->regs + MAC_STIME);
val = readl(gp->regs + MAC_MCCFG);
if (pause)
val |= (MAC_MCCFG_SPE | MAC_MCCFG_RPE);
else
val &= ~(MAC_MCCFG_SPE | MAC_MCCFG_RPE);
writel(val, gp->regs + MAC_MCCFG);
gem_start_dma(gp);
return 0;
}
/* Must be invoked under gp->lock and gp->tx_lock. */
static int gem_mdio_link_not_up(struct gem *gp)
{
switch (gp->lstate) {
case link_force_ret:
if (netif_msg_link(gp))
printk(KERN_INFO "%s: Autoneg failed again, keeping"
" forced mode\n", gp->dev->name);
gp->phy_mii.def->ops->setup_forced(&gp->phy_mii,
gp->last_forced_speed, DUPLEX_HALF);
gp->timer_ticks = 5;
gp->lstate = link_force_ok;
return 0;
case link_aneg:
/* We try forced modes after a failed aneg only on PHYs that don't
* have "magic_aneg" bit set, which means they internally do the
* while forced-mode thingy. On these, we just restart aneg
*/
if (gp->phy_mii.def->magic_aneg)
return 1;
if (netif_msg_link(gp))
printk(KERN_INFO "%s: switching to forced 100bt\n",
gp->dev->name);
/* Try forced modes. */
gp->phy_mii.def->ops->setup_forced(&gp->phy_mii, SPEED_100,
DUPLEX_HALF);
gp->timer_ticks = 5;
gp->lstate = link_force_try;
return 0;
case link_force_try:
/* Downgrade from 100 to 10 Mbps if necessary.
* If already at 10Mbps, warn user about the
* situation every 10 ticks.
*/
if (gp->phy_mii.speed == SPEED_100) {
gp->phy_mii.def->ops->setup_forced(&gp->phy_mii, SPEED_10,
DUPLEX_HALF);
gp->timer_ticks = 5;
if (netif_msg_link(gp))
printk(KERN_INFO "%s: switching to forced 10bt\n",
gp->dev->name);
return 0;
} else
return 1;
default:
return 0;
}
}
static void gem_link_timer(unsigned long data)
{
struct gem *gp = (struct gem *) data;
int restart_aneg = 0;
if (gp->asleep)
return;
spin_lock_irq(&gp->lock);
spin_lock(&gp->tx_lock);
gem_get_cell(gp);
/* If the reset task is still pending, we just
* reschedule the link timer
*/
if (gp->reset_task_pending)
goto restart;
if (gp->phy_type == phy_serialink ||
gp->phy_type == phy_serdes) {
u32 val = readl(gp->regs + PCS_MIISTAT);
if (!(val & PCS_MIISTAT_LS))
val = readl(gp->regs + PCS_MIISTAT);
if ((val & PCS_MIISTAT_LS) != 0) {
if (gp->lstate == link_up)
goto restart;
gp->lstate = link_up;
netif_carrier_on(gp->dev);
(void)gem_set_link_modes(gp);
}
goto restart;
}
if (found_mii_phy(gp) && gp->phy_mii.def->ops->poll_link(&gp->phy_mii)) {
/* Ok, here we got a link. If we had it due to a forced
* fallback, and we were configured for autoneg, we do
* retry a short autoneg pass. If you know your hub is
* broken, use ethtool ;)
*/
if (gp->lstate == link_force_try && gp->want_autoneg) {
gp->lstate = link_force_ret;
gp->last_forced_speed = gp->phy_mii.speed;
gp->timer_ticks = 5;
if (netif_msg_link(gp))
printk(KERN_INFO "%s: Got link after fallback, retrying"
" autoneg once...\n", gp->dev->name);
gp->phy_mii.def->ops->setup_aneg(&gp->phy_mii, gp->phy_mii.advertising);
} else if (gp->lstate != link_up) {
gp->lstate = link_up;
netif_carrier_on(gp->dev);
if (gem_set_link_modes(gp))
restart_aneg = 1;
}
} else {
/* If the link was previously up, we restart the
* whole process
*/
if (gp->lstate == link_up) {
gp->lstate = link_down;
if (netif_msg_link(gp))
printk(KERN_INFO "%s: Link down\n",
gp->dev->name);
netif_carrier_off(gp->dev);
gp->reset_task_pending = 1;
schedule_work(&gp->reset_task);
restart_aneg = 1;
} else if (++gp->timer_ticks > 10) {
if (found_mii_phy(gp))
restart_aneg = gem_mdio_link_not_up(gp);
else
restart_aneg = 1;
}
}
if (restart_aneg) {
gem_begin_auto_negotiation(gp, NULL);
goto out_unlock;
}
restart:
mod_timer(&gp->link_timer, jiffies + ((12 * HZ) / 10));
out_unlock:
gem_put_cell(gp);
spin_unlock(&gp->tx_lock);
spin_unlock_irq(&gp->lock);
}
/* Must be invoked under gp->lock and gp->tx_lock. */
static void gem_clean_rings(struct gem *gp)
{
struct gem_init_block *gb = gp->init_block;
struct sk_buff *skb;
int i;
dma_addr_t dma_addr;
for (i = 0; i < RX_RING_SIZE; i++) {
struct gem_rxd *rxd;
rxd = &gb->rxd[i];
if (gp->rx_skbs[i] != NULL) {
skb = gp->rx_skbs[i];
dma_addr = le64_to_cpu(rxd->buffer);
pci_unmap_page(gp->pdev, dma_addr,
RX_BUF_ALLOC_SIZE(gp),
PCI_DMA_FROMDEVICE);
dev_kfree_skb_any(skb);
gp->rx_skbs[i] = NULL;
}
rxd->status_word = 0;
wmb();
rxd->buffer = 0;
}
for (i = 0; i < TX_RING_SIZE; i++) {
if (gp->tx_skbs[i] != NULL) {
struct gem_txd *txd;
int frag;
skb = gp->tx_skbs[i];
gp->tx_skbs[i] = NULL;
for (frag = 0; frag <= skb_shinfo(skb)->nr_frags; frag++) {
int ent = i & (TX_RING_SIZE - 1);
txd = &gb->txd[ent];
dma_addr = le64_to_cpu(txd->buffer);
pci_unmap_page(gp->pdev, dma_addr,
le64_to_cpu(txd->control_word) &
TXDCTRL_BUFSZ, PCI_DMA_TODEVICE);
if (frag != skb_shinfo(skb)->nr_frags)
i++;
}
dev_kfree_skb_any(skb);
}
}
}
/* Must be invoked under gp->lock and gp->tx_lock. */
static void gem_init_rings(struct gem *gp)
{
struct gem_init_block *gb = gp->init_block;
struct net_device *dev = gp->dev;
int i;
dma_addr_t dma_addr;
gp->rx_new = gp->rx_old = gp->tx_new = gp->tx_old = 0;
gem_clean_rings(gp);
gp->rx_buf_sz = max(dev->mtu + ETH_HLEN + VLAN_HLEN,
(unsigned)VLAN_ETH_FRAME_LEN);
for (i = 0; i < RX_RING_SIZE; i++) {
struct sk_buff *skb;
struct gem_rxd *rxd = &gb->rxd[i];
skb = gem_alloc_skb(RX_BUF_ALLOC_SIZE(gp), GFP_ATOMIC);
if (!skb) {
rxd->buffer = 0;
rxd->status_word = 0;
continue;
}
gp->rx_skbs[i] = skb;
skb->dev = dev;
skb_put(skb, (gp->rx_buf_sz + RX_OFFSET));
dma_addr = pci_map_page(gp->pdev,
virt_to_page(skb->data),
offset_in_page(skb->data),
RX_BUF_ALLOC_SIZE(gp),
PCI_DMA_FROMDEVICE);
rxd->buffer = cpu_to_le64(dma_addr);
wmb();
rxd->status_word = cpu_to_le64(RXDCTRL_FRESH(gp));
skb_reserve(skb, RX_OFFSET);
}
for (i = 0; i < TX_RING_SIZE; i++) {
struct gem_txd *txd = &gb->txd[i];
txd->control_word = 0;
wmb();
txd->buffer = 0;
}
wmb();
}
/* Init PHY interface and start link poll state machine */
static void gem_init_phy(struct gem *gp)
{
u32 mifcfg;
/* Revert MIF CFG setting done on stop_phy */
mifcfg = readl(gp->regs + MIF_CFG);
mifcfg &= ~MIF_CFG_BBMODE;
writel(mifcfg, gp->regs + MIF_CFG);
if (gp->pdev->vendor == PCI_VENDOR_ID_APPLE) {
int i;
/* Those delay sucks, the HW seem to love them though, I'll
* serisouly consider breaking some locks here to be able
* to schedule instead
*/
for (i = 0; i < 3; i++) {
#ifdef CONFIG_PPC_PMAC
pmac_call_feature(PMAC_FTR_GMAC_PHY_RESET, gp->of_node, 0, 0);
msleep(20);
#endif
/* Some PHYs used by apple have problem getting back to us,
* we do an additional reset here
*/
phy_write(gp, MII_BMCR, BMCR_RESET);
msleep(20);
if (phy_read(gp, MII_BMCR) != 0xffff)
break;
if (i == 2)
printk(KERN_WARNING "%s: GMAC PHY not responding !\n",
gp->dev->name);
}
}
if (gp->pdev->vendor == PCI_VENDOR_ID_SUN &&
gp->pdev->device == PCI_DEVICE_ID_SUN_GEM) {
u32 val;
/* Init datapath mode register. */
if (gp->phy_type == phy_mii_mdio0 ||
gp->phy_type == phy_mii_mdio1) {
val = PCS_DMODE_MGM;
} else if (gp->phy_type == phy_serialink) {
val = PCS_DMODE_SM | PCS_DMODE_GMOE;
} else {
val = PCS_DMODE_ESM;
}
writel(val, gp->regs + PCS_DMODE);
}
if (gp->phy_type == phy_mii_mdio0 ||
gp->phy_type == phy_mii_mdio1) {
// XXX check for errors
mii_phy_probe(&gp->phy_mii, gp->mii_phy_addr);
/* Init PHY */
if (gp->phy_mii.def && gp->phy_mii.def->ops->init)
gp->phy_mii.def->ops->init(&gp->phy_mii);
} else {
gem_pcs_reset(gp);
gem_pcs_reinit_adv(gp);
}
/* Default aneg parameters */
gp->timer_ticks = 0;
gp->lstate = link_down;
netif_carrier_off(gp->dev);
/* Can I advertise gigabit here ? I'd need BCM PHY docs... */
spin_lock_irq(&gp->lock);
gem_begin_auto_negotiation(gp, NULL);
spin_unlock_irq(&gp->lock);
}
/* Must be invoked under gp->lock and gp->tx_lock. */
static void gem_init_dma(struct gem *gp)
{
u64 desc_dma = (u64) gp->gblock_dvma;
u32 val;
val = (TXDMA_CFG_BASE | (0x7ff << 10) | TXDMA_CFG_PMODE);
writel(val, gp->regs + TXDMA_CFG);
writel(desc_dma >> 32, gp->regs + TXDMA_DBHI);
writel(desc_dma & 0xffffffff, gp->regs + TXDMA_DBLOW);
desc_dma += (INIT_BLOCK_TX_RING_SIZE * sizeof(struct gem_txd));
writel(0, gp->regs + TXDMA_KICK);
val = (RXDMA_CFG_BASE | (RX_OFFSET << 10) |
((14 / 2) << 13) | RXDMA_CFG_FTHRESH_128);
writel(val, gp->regs + RXDMA_CFG);
writel(desc_dma >> 32, gp->regs + RXDMA_DBHI);
writel(desc_dma & 0xffffffff, gp->regs + RXDMA_DBLOW);
writel(RX_RING_SIZE - 4, gp->regs + RXDMA_KICK);
val = (((gp->rx_pause_off / 64) << 0) & RXDMA_PTHRESH_OFF);
val |= (((gp->rx_pause_on / 64) << 12) & RXDMA_PTHRESH_ON);
writel(val, gp->regs + RXDMA_PTHRESH);
if (readl(gp->regs + GREG_BIFCFG) & GREG_BIFCFG_M66EN)
writel(((5 & RXDMA_BLANK_IPKTS) |
((8 << 12) & RXDMA_BLANK_ITIME)),
gp->regs + RXDMA_BLANK);
else
writel(((5 & RXDMA_BLANK_IPKTS) |
((4 << 12) & RXDMA_BLANK_ITIME)),
gp->regs + RXDMA_BLANK);
}
/* Must be invoked under gp->lock and gp->tx_lock. */
static u32 gem_setup_multicast(struct gem *gp)
{
u32 rxcfg = 0;
int i;
if ((gp->dev->flags & IFF_ALLMULTI) ||
(gp->dev->mc_count > 256)) {
for (i=0; i<16; i++)
writel(0xffff, gp->regs + MAC_HASH0 + (i << 2));
rxcfg |= MAC_RXCFG_HFE;
} else if (gp->dev->flags & IFF_PROMISC) {
rxcfg |= MAC_RXCFG_PROM;
} else {
u16 hash_table[16];
u32 crc;
struct dev_mc_list *dmi = gp->dev->mc_list;
int i;
for (i = 0; i < 16; i++)
hash_table[i] = 0;
for (i = 0; i < gp->dev->mc_count; i++) {
char *addrs = dmi->dmi_addr;
dmi = dmi->next;
if (!(*addrs & 1))
continue;
crc = ether_crc_le(6, addrs);
crc >>= 24;
hash_table[crc >> 4] |= 1 << (15 - (crc & 0xf));
}
for (i=0; i<16; i++)
writel(hash_table[i], gp->regs + MAC_HASH0 + (i << 2));
rxcfg |= MAC_RXCFG_HFE;
}
return rxcfg;
}
/* Must be invoked under gp->lock and gp->tx_lock. */
static void gem_init_mac(struct gem *gp)
{
unsigned char *e = &gp->dev->dev_addr[0];
writel(0x1bf0, gp->regs + MAC_SNDPAUSE);
writel(0x00, gp->regs + MAC_IPG0);
writel(0x08, gp->regs + MAC_IPG1);
writel(0x04, gp->regs + MAC_IPG2);
writel(0x40, gp->regs + MAC_STIME);
writel(0x40, gp->regs + MAC_MINFSZ);
/* Ethernet payload + header + FCS + optional VLAN tag. */
writel(0x20000000 | (gp->rx_buf_sz + 4), gp->regs + MAC_MAXFSZ);
writel(0x07, gp->regs + MAC_PASIZE);
writel(0x04, gp->regs + MAC_JAMSIZE);
writel(0x10, gp->regs + MAC_ATTLIM);
writel(0x8808, gp->regs + MAC_MCTYPE);
writel((e[5] | (e[4] << 8)) & 0x3ff, gp->regs + MAC_RANDSEED);
writel((e[4] << 8) | e[5], gp->regs + MAC_ADDR0);
writel((e[2] << 8) | e[3], gp->regs + MAC_ADDR1);
writel((e[0] << 8) | e[1], gp->regs + MAC_ADDR2);
writel(0, gp->regs + MAC_ADDR3);
writel(0, gp->regs + MAC_ADDR4);
writel(0, gp->regs + MAC_ADDR5);
writel(0x0001, gp->regs + MAC_ADDR6);
writel(0xc200, gp->regs + MAC_ADDR7);
writel(0x0180, gp->regs + MAC_ADDR8);
writel(0, gp->regs + MAC_AFILT0);
writel(0, gp->regs + MAC_AFILT1);
writel(0, gp->regs + MAC_AFILT2);
writel(0, gp->regs + MAC_AF21MSK);
writel(0, gp->regs + MAC_AF0MSK);
gp->mac_rx_cfg = gem_setup_multicast(gp);
#ifdef STRIP_FCS
gp->mac_rx_cfg |= MAC_RXCFG_SFCS;
#endif
writel(0, gp->regs + MAC_NCOLL);
writel(0, gp->regs + MAC_FASUCC);
writel(0, gp->regs + MAC_ECOLL);
writel(0, gp->regs + MAC_LCOLL);
writel(0, gp->regs + MAC_DTIMER);
writel(0, gp->regs + MAC_PATMPS);
writel(0, gp->regs + MAC_RFCTR);
writel(0, gp->regs + MAC_LERR);
writel(0, gp->regs + MAC_AERR);
writel(0, gp->regs + MAC_FCSERR);
writel(0, gp->regs + MAC_RXCVERR);
/* Clear RX/TX/MAC/XIF config, we will set these up and enable
* them once a link is established.
*/
writel(0, gp->regs + MAC_TXCFG);
writel(gp->mac_rx_cfg, gp->regs + MAC_RXCFG);
writel(0, gp->regs + MAC_MCCFG);
writel(0, gp->regs + MAC_XIFCFG);
/* Setup MAC interrupts. We want to get all of the interesting
* counter expiration events, but we do not want to hear about
* normal rx/tx as the DMA engine tells us that.
*/
writel(MAC_TXSTAT_XMIT, gp->regs + MAC_TXMASK);
writel(MAC_RXSTAT_RCV, gp->regs + MAC_RXMASK);
/* Don't enable even the PAUSE interrupts for now, we
* make no use of those events other than to record them.
*/
writel(0xffffffff, gp->regs + MAC_MCMASK);
/* Don't enable GEM's WOL in normal operations
*/
if (gp->has_wol)
writel(0, gp->regs + WOL_WAKECSR);
}
/* Must be invoked under gp->lock and gp->tx_lock. */
static void gem_init_pause_thresholds(struct gem *gp)
{
u32 cfg;
/* Calculate pause thresholds. Setting the OFF threshold to the
* full RX fifo size effectively disables PAUSE generation which
* is what we do for 10/100 only GEMs which have FIFOs too small
* to make real gains from PAUSE.
*/
if (gp->rx_fifo_sz <= (2 * 1024)) {
gp->rx_pause_off = gp->rx_pause_on = gp->rx_fifo_sz;
} else {
int max_frame = (gp->rx_buf_sz + 4 + 64) & ~63;
int off = (gp->rx_fifo_sz - (max_frame * 2));
int on = off - max_frame;
gp->rx_pause_off = off;
gp->rx_pause_on = on;
}
/* Configure the chip "burst" DMA mode & enable some
* HW bug fixes on Apple version
*/
cfg = 0;
if (gp->pdev->vendor == PCI_VENDOR_ID_APPLE)
cfg |= GREG_CFG_RONPAULBIT | GREG_CFG_ENBUG2FIX;
#if !defined(CONFIG_SPARC64) && !defined(CONFIG_ALPHA)
cfg |= GREG_CFG_IBURST;
#endif
cfg |= ((31 << 1) & GREG_CFG_TXDMALIM);
cfg |= ((31 << 6) & GREG_CFG_RXDMALIM);
writel(cfg, gp->regs + GREG_CFG);
/* If Infinite Burst didn't stick, then use different
* thresholds (and Apple bug fixes don't exist)
*/
if (!(readl(gp->regs + GREG_CFG) & GREG_CFG_IBURST)) {
cfg = ((2 << 1) & GREG_CFG_TXDMALIM);
cfg |= ((8 << 6) & GREG_CFG_RXDMALIM);
writel(cfg, gp->regs + GREG_CFG);
}
}
static int gem_check_invariants(struct gem *gp)
{
struct pci_dev *pdev = gp->pdev;
u32 mif_cfg;
/* On Apple's sungem, we can't rely on registers as the chip
* was been powered down by the firmware. The PHY is looked
* up later on.
*/
if (pdev->vendor == PCI_VENDOR_ID_APPLE) {
gp->phy_type = phy_mii_mdio0;
gp->tx_fifo_sz = readl(gp->regs + TXDMA_FSZ) * 64;
gp->rx_fifo_sz = readl(gp->regs + RXDMA_FSZ) * 64;
gp->swrst_base = 0;
mif_cfg = readl(gp->regs + MIF_CFG);
mif_cfg &= ~(MIF_CFG_PSELECT|MIF_CFG_POLL|MIF_CFG_BBMODE|MIF_CFG_MDI1);
mif_cfg |= MIF_CFG_MDI0;
writel(mif_cfg, gp->regs + MIF_CFG);
writel(PCS_DMODE_MGM, gp->regs + PCS_DMODE);
writel(MAC_XIFCFG_OE, gp->regs + MAC_XIFCFG);
/* We hard-code the PHY address so we can properly bring it out of
* reset later on, we can't really probe it at this point, though
* that isn't an issue.
*/
if (gp->pdev->device == PCI_DEVICE_ID_APPLE_K2_GMAC)
gp->mii_phy_addr = 1;
else
gp->mii_phy_addr = 0;
return 0;
}
mif_cfg = readl(gp->regs + MIF_CFG);
if (pdev->vendor == PCI_VENDOR_ID_SUN &&
pdev->device == PCI_DEVICE_ID_SUN_RIO_GEM) {
/* One of the MII PHYs _must_ be present
* as this chip has no gigabit PHY.
*/
if ((mif_cfg & (MIF_CFG_MDI0 | MIF_CFG_MDI1)) == 0) {
printk(KERN_ERR PFX "RIO GEM lacks MII phy, mif_cfg[%08x]\n",
mif_cfg);
return -1;
}
}
/* Determine initial PHY interface type guess. MDIO1 is the
* external PHY and thus takes precedence over MDIO0.
*/
if (mif_cfg & MIF_CFG_MDI1) {
gp->phy_type = phy_mii_mdio1;
mif_cfg |= MIF_CFG_PSELECT;
writel(mif_cfg, gp->regs + MIF_CFG);
} else if (mif_cfg & MIF_CFG_MDI0) {
gp->phy_type = phy_mii_mdio0;
mif_cfg &= ~MIF_CFG_PSELECT;
writel(mif_cfg, gp->regs + MIF_CFG);
} else {
#ifdef CONFIG_SPARC
const char *p;
p = of_get_property(gp->of_node, "shared-pins", NULL);
if (p && !strcmp(p, "serdes"))
gp->phy_type = phy_serdes;
else
#endif
gp->phy_type = phy_serialink;
}
if (gp->phy_type == phy_mii_mdio1 ||
gp->phy_type == phy_mii_mdio0) {
int i;
for (i = 0; i < 32; i++) {
gp->mii_phy_addr = i;
if (phy_read(gp, MII_BMCR) != 0xffff)
break;
}
if (i == 32) {
if (pdev->device != PCI_DEVICE_ID_SUN_GEM) {
printk(KERN_ERR PFX "RIO MII phy will not respond.\n");
return -1;
}
gp->phy_type = phy_serdes;
}
}
/* Fetch the FIFO configurations now too. */
gp->tx_fifo_sz = readl(gp->regs + TXDMA_FSZ) * 64;
gp->rx_fifo_sz = readl(gp->regs + RXDMA_FSZ) * 64;
if (pdev->vendor == PCI_VENDOR_ID_SUN) {
if (pdev->device == PCI_DEVICE_ID_SUN_GEM) {
if (gp->tx_fifo_sz != (9 * 1024) ||
gp->rx_fifo_sz != (20 * 1024)) {
printk(KERN_ERR PFX "GEM has bogus fifo sizes tx(%d) rx(%d)\n",
gp->tx_fifo_sz, gp->rx_fifo_sz);
return -1;
}
gp->swrst_base = 0;
} else {
if (gp->tx_fifo_sz != (2 * 1024) ||
gp->rx_fifo_sz != (2 * 1024)) {
printk(KERN_ERR PFX "RIO GEM has bogus fifo sizes tx(%d) rx(%d)\n",
gp->tx_fifo_sz, gp->rx_fifo_sz);
return -1;
}
gp->swrst_base = (64 / 4) << GREG_SWRST_CACHE_SHIFT;
}
}
return 0;
}
/* Must be invoked under gp->lock and gp->tx_lock. */
static void gem_reinit_chip(struct gem *gp)
{
/* Reset the chip */
gem_reset(gp);
/* Make sure ints are disabled */
gem_disable_ints(gp);
/* Allocate & setup ring buffers */
gem_init_rings(gp);
/* Configure pause thresholds */
gem_init_pause_thresholds(gp);
/* Init DMA & MAC engines */
gem_init_dma(gp);
gem_init_mac(gp);
}
/* Must be invoked with no lock held. */
static void gem_stop_phy(struct gem *gp, int wol)
{
u32 mifcfg;
unsigned long flags;
/* Let the chip settle down a bit, it seems that helps
* for sleep mode on some models
*/
msleep(10);
/* Make sure we aren't polling PHY status change. We
* don't currently use that feature though
*/
mifcfg = readl(gp->regs + MIF_CFG);
mifcfg &= ~MIF_CFG_POLL;
writel(mifcfg, gp->regs + MIF_CFG);
if (wol && gp->has_wol) {
unsigned char *e = &gp->dev->dev_addr[0];
u32 csr;
/* Setup wake-on-lan for MAGIC packet */
writel(MAC_RXCFG_HFE | MAC_RXCFG_SFCS | MAC_RXCFG_ENAB,
gp->regs + MAC_RXCFG);
writel((e[4] << 8) | e[5], gp->regs + WOL_MATCH0);
writel((e[2] << 8) | e[3], gp->regs + WOL_MATCH1);
writel((e[0] << 8) | e[1], gp->regs + WOL_MATCH2);
writel(WOL_MCOUNT_N | WOL_MCOUNT_M, gp->regs + WOL_MCOUNT);
csr = WOL_WAKECSR_ENABLE;
if ((readl(gp->regs + MAC_XIFCFG) & MAC_XIFCFG_GMII) == 0)
csr |= WOL_WAKECSR_MII;
writel(csr, gp->regs + WOL_WAKECSR);
} else {
writel(0, gp->regs + MAC_RXCFG);
(void)readl(gp->regs + MAC_RXCFG);
/* Machine sleep will die in strange ways if we
* dont wait a bit here, looks like the chip takes
* some time to really shut down
*/
msleep(10);
}
writel(0, gp->regs + MAC_TXCFG);
writel(0, gp->regs + MAC_XIFCFG);
writel(0, gp->regs + TXDMA_CFG);
writel(0, gp->regs + RXDMA_CFG);
if (!wol) {
spin_lock_irqsave(&gp->lock, flags);
spin_lock(&gp->tx_lock);
gem_reset(gp);
writel(MAC_TXRST_CMD, gp->regs + MAC_TXRST);
writel(MAC_RXRST_CMD, gp->regs + MAC_RXRST);
spin_unlock(&gp->tx_lock);
spin_unlock_irqrestore(&gp->lock, flags);
/* No need to take the lock here */
if (found_mii_phy(gp) && gp->phy_mii.def->ops->suspend)
gp->phy_mii.def->ops->suspend(&gp->phy_mii);
/* According to Apple, we must set the MDIO pins to this begnign
* state or we may 1) eat more current, 2) damage some PHYs
*/
writel(mifcfg | MIF_CFG_BBMODE, gp->regs + MIF_CFG);
writel(0, gp->regs + MIF_BBCLK);
writel(0, gp->regs + MIF_BBDATA);
writel(0, gp->regs + MIF_BBOENAB);
writel(MAC_XIFCFG_GMII | MAC_XIFCFG_LBCK, gp->regs + MAC_XIFCFG);
(void) readl(gp->regs + MAC_XIFCFG);
}
}
static int gem_do_start(struct net_device *dev)
{
struct gem *gp = netdev_priv(dev);
unsigned long flags;
spin_lock_irqsave(&gp->lock, flags);
spin_lock(&gp->tx_lock);
/* Enable the cell */
gem_get_cell(gp);
/* Init & setup chip hardware */
gem_reinit_chip(gp);
gp->running = 1;
napi_enable(&gp->napi);
if (gp->lstate == link_up) {
netif_carrier_on(gp->dev);
gem_set_link_modes(gp);
}
netif_wake_queue(gp->dev);
spin_unlock(&gp->tx_lock);
spin_unlock_irqrestore(&gp->lock, flags);
if (request_irq(gp->pdev->irq, gem_interrupt,
IRQF_SHARED, dev->name, (void *)dev)) {
printk(KERN_ERR "%s: failed to request irq !\n", gp->dev->name);
spin_lock_irqsave(&gp->lock, flags);
spin_lock(&gp->tx_lock);
napi_disable(&gp->napi);
gp->running = 0;
gem_reset(gp);
gem_clean_rings(gp);
gem_put_cell(gp);
spin_unlock(&gp->tx_lock);
spin_unlock_irqrestore(&gp->lock, flags);
return -EAGAIN;
}
return 0;
}
static void gem_do_stop(struct net_device *dev, int wol)
{
struct gem *gp = netdev_priv(dev);
unsigned long flags;
spin_lock_irqsave(&gp->lock, flags);
spin_lock(&gp->tx_lock);
gp->running = 0;
/* Stop netif queue */
netif_stop_queue(dev);
/* Make sure ints are disabled */
gem_disable_ints(gp);
/* We can drop the lock now */
spin_unlock(&gp->tx_lock);
spin_unlock_irqrestore(&gp->lock, flags);
/* If we are going to sleep with WOL */
gem_stop_dma(gp);
msleep(10);
if (!wol)
gem_reset(gp);
msleep(10);
/* Get rid of rings */
gem_clean_rings(gp);
/* No irq needed anymore */
free_irq(gp->pdev->irq, (void *) dev);
/* Cell not needed neither if no WOL */
if (!wol) {
spin_lock_irqsave(&gp->lock, flags);
gem_put_cell(gp);
spin_unlock_irqrestore(&gp->lock, flags);
}
}
static void gem_reset_task(struct work_struct *work)
{
struct gem *gp = container_of(work, struct gem, reset_task);
mutex_lock(&gp->pm_mutex);
if (gp->opened)
napi_disable(&gp->napi);
spin_lock_irq(&gp->lock);
spin_lock(&gp->tx_lock);
if (gp->running) {
netif_stop_queue(gp->dev);
/* Reset the chip & rings */
gem_reinit_chip(gp);
if (gp->lstate == link_up)
gem_set_link_modes(gp);
netif_wake_queue(gp->dev);
}
gp->reset_task_pending = 0;
spin_unlock(&gp->tx_lock);
spin_unlock_irq(&gp->lock);
if (gp->opened)
napi_enable(&gp->napi);
mutex_unlock(&gp->pm_mutex);
}
static int gem_open(struct net_device *dev)
{
struct gem *gp = netdev_priv(dev);
int rc = 0;
mutex_lock(&gp->pm_mutex);
/* We need the cell enabled */
if (!gp->asleep)
rc = gem_do_start(dev);
gp->opened = (rc == 0);
mutex_unlock(&gp->pm_mutex);
return rc;
}
static int gem_close(struct net_device *dev)
{
struct gem *gp = netdev_priv(dev);
mutex_lock(&gp->pm_mutex);
napi_disable(&gp->napi);
gp->opened = 0;
if (!gp->asleep)
gem_do_stop(dev, 0);
mutex_unlock(&gp->pm_mutex);
return 0;
}
#ifdef CONFIG_PM
static int gem_suspend(struct pci_dev *pdev, pm_message_t state)
{
struct net_device *dev = pci_get_drvdata(pdev);
struct gem *gp = netdev_priv(dev);
unsigned long flags;
mutex_lock(&gp->pm_mutex);
printk(KERN_INFO "%s: suspending, WakeOnLan %s\n",
dev->name,
(gp->wake_on_lan && gp->opened) ? "enabled" : "disabled");
/* Keep the cell enabled during the entire operation */
spin_lock_irqsave(&gp->lock, flags);
spin_lock(&gp->tx_lock);
gem_get_cell(gp);
spin_unlock(&gp->tx_lock);
spin_unlock_irqrestore(&gp->lock, flags);
/* If the driver is opened, we stop the MAC */
if (gp->opened) {
napi_disable(&gp->napi);
/* Stop traffic, mark us closed */
netif_device_detach(dev);
/* Switch off MAC, remember WOL setting */
gp->asleep_wol = gp->wake_on_lan;
gem_do_stop(dev, gp->asleep_wol);
} else
gp->asleep_wol = 0;
/* Mark us asleep */
gp->asleep = 1;
wmb();
/* Stop the link timer */
del_timer_sync(&gp->link_timer);
/* Now we release the mutex to not block the reset task who
* can take it too. We are marked asleep, so there will be no
* conflict here
*/
mutex_unlock(&gp->pm_mutex);
/* Wait for a pending reset task to complete */
while (gp->reset_task_pending)
yield();
flush_scheduled_work();
/* Shut the PHY down eventually and setup WOL */
gem_stop_phy(gp, gp->asleep_wol);
/* Make sure bus master is disabled */
pci_disable_device(gp->pdev);
/* Release the cell, no need to take a lock at this point since
* nothing else can happen now
*/
gem_put_cell(gp);
return 0;
}
static int gem_resume(struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev);
struct gem *gp = netdev_priv(dev);
unsigned long flags;
printk(KERN_INFO "%s: resuming\n", dev->name);
mutex_lock(&gp->pm_mutex);
/* Keep the cell enabled during the entire operation, no need to
* take a lock here tho since nothing else can happen while we are
* marked asleep
*/
gem_get_cell(gp);
/* Make sure PCI access and bus master are enabled */
if (pci_enable_device(gp->pdev)) {
printk(KERN_ERR "%s: Can't re-enable chip !\n",
dev->name);
/* Put cell and forget it for now, it will be considered as
* still asleep, a new sleep cycle may bring it back
*/
gem_put_cell(gp);
mutex_unlock(&gp->pm_mutex);
return 0;
}
pci_set_master(gp->pdev);
/* Reset everything */
gem_reset(gp);
/* Mark us woken up */
gp->asleep = 0;
wmb();
/* Bring the PHY back. Again, lock is useless at this point as
* nothing can be happening until we restart the whole thing
*/
gem_init_phy(gp);
/* If we were opened, bring everything back */
if (gp->opened) {
/* Restart MAC */
gem_do_start(dev);
/* Re-attach net device */
netif_device_attach(dev);
}
spin_lock_irqsave(&gp->lock, flags);
spin_lock(&gp->tx_lock);
/* If we had WOL enabled, the cell clock was never turned off during
* sleep, so we end up beeing unbalanced. Fix that here
*/
if (gp->asleep_wol)
gem_put_cell(gp);
/* This function doesn't need to hold the cell, it will be held if the
* driver is open by gem_do_start().
*/
gem_put_cell(gp);
spin_unlock(&gp->tx_lock);
spin_unlock_irqrestore(&gp->lock, flags);
mutex_unlock(&gp->pm_mutex);
return 0;
}
#endif /* CONFIG_PM */
static struct net_device_stats *gem_get_stats(struct net_device *dev)
{
struct gem *gp = netdev_priv(dev);
struct net_device_stats *stats = &gp->net_stats;
spin_lock_irq(&gp->lock);
spin_lock(&gp->tx_lock);
/* I have seen this being called while the PM was in progress,
* so we shield against this
*/
if (gp->running) {
stats->rx_crc_errors += readl(gp->regs + MAC_FCSERR);
writel(0, gp->regs + MAC_FCSERR);
stats->rx_frame_errors += readl(gp->regs + MAC_AERR);
writel(0, gp->regs + MAC_AERR);
stats->rx_length_errors += readl(gp->regs + MAC_LERR);
writel(0, gp->regs + MAC_LERR);
stats->tx_aborted_errors += readl(gp->regs + MAC_ECOLL);
stats->collisions +=
(readl(gp->regs + MAC_ECOLL) +
readl(gp->regs + MAC_LCOLL));
writel(0, gp->regs + MAC_ECOLL);
writel(0, gp->regs + MAC_LCOLL);
}
spin_unlock(&gp->tx_lock);
spin_unlock_irq(&gp->lock);
return &gp->net_stats;
}
static int gem_set_mac_address(struct net_device *dev, void *addr)
{
struct sockaddr *macaddr = (struct sockaddr *) addr;
struct gem *gp = netdev_priv(dev);
unsigned char *e = &dev->dev_addr[0];
if (!is_valid_ether_addr(macaddr->sa_data))
return -EADDRNOTAVAIL;
if (!netif_running(dev) || !netif_device_present(dev)) {
/* We'll just catch it later when the
* device is up'd or resumed.
*/
memcpy(dev->dev_addr, macaddr->sa_data, dev->addr_len);
return 0;
}
mutex_lock(&gp->pm_mutex);
memcpy(dev->dev_addr, macaddr->sa_data, dev->addr_len);
if (gp->running) {
writel((e[4] << 8) | e[5], gp->regs + MAC_ADDR0);
writel((e[2] << 8) | e[3], gp->regs + MAC_ADDR1);
writel((e[0] << 8) | e[1], gp->regs + MAC_ADDR2);
}
mutex_unlock(&gp->pm_mutex);
return 0;
}
static void gem_set_multicast(struct net_device *dev)
{
struct gem *gp = netdev_priv(dev);
u32 rxcfg, rxcfg_new;
int limit = 10000;
spin_lock_irq(&gp->lock);
spin_lock(&gp->tx_lock);
if (!gp->running)
goto bail;
netif_stop_queue(dev);
rxcfg = readl(gp->regs + MAC_RXCFG);
rxcfg_new = gem_setup_multicast(gp);
#ifdef STRIP_FCS
rxcfg_new |= MAC_RXCFG_SFCS;
#endif
gp->mac_rx_cfg = rxcfg_new;
writel(rxcfg & ~MAC_RXCFG_ENAB, gp->regs + MAC_RXCFG);
while (readl(gp->regs + MAC_RXCFG) & MAC_RXCFG_ENAB) {
if (!limit--)
break;
udelay(10);
}
rxcfg &= ~(MAC_RXCFG_PROM | MAC_RXCFG_HFE);
rxcfg |= rxcfg_new;
writel(rxcfg, gp->regs + MAC_RXCFG);
netif_wake_queue(dev);
bail:
spin_unlock(&gp->tx_lock);
spin_unlock_irq(&gp->lock);
}
/* Jumbo-grams don't seem to work :-( */
#define GEM_MIN_MTU 68
#if 1
#define GEM_MAX_MTU 1500
#else
#define GEM_MAX_MTU 9000
#endif
static int gem_change_mtu(struct net_device *dev, int new_mtu)
{
struct gem *gp = netdev_priv(dev);
if (new_mtu < GEM_MIN_MTU || new_mtu > GEM_MAX_MTU)
return -EINVAL;
if (!netif_running(dev) || !netif_device_present(dev)) {
/* We'll just catch it later when the
* device is up'd or resumed.
*/
dev->mtu = new_mtu;
return 0;
}
mutex_lock(&gp->pm_mutex);
spin_lock_irq(&gp->lock);
spin_lock(&gp->tx_lock);
dev->mtu = new_mtu;
if (gp->running) {
gem_reinit_chip(gp);
if (gp->lstate == link_up)
gem_set_link_modes(gp);
}
spin_unlock(&gp->tx_lock);
spin_unlock_irq(&gp->lock);
mutex_unlock(&gp->pm_mutex);
return 0;
}
static void gem_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
{
struct gem *gp = netdev_priv(dev);
strcpy(info->driver, DRV_NAME);
strcpy(info->version, DRV_VERSION);
strcpy(info->bus_info, pci_name(gp->pdev));
}
static int gem_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct gem *gp = netdev_priv(dev);
if (gp->phy_type == phy_mii_mdio0 ||
gp->phy_type == phy_mii_mdio1) {
if (gp->phy_mii.def)
cmd->supported = gp->phy_mii.def->features;
else
cmd->supported = (SUPPORTED_10baseT_Half |
SUPPORTED_10baseT_Full);
/* XXX hardcoded stuff for now */
cmd->port = PORT_MII;
cmd->transceiver = XCVR_EXTERNAL;
cmd->phy_address = 0; /* XXX fixed PHYAD */
/* Return current PHY settings */
spin_lock_irq(&gp->lock);
cmd->autoneg = gp->want_autoneg;
cmd->speed = gp->phy_mii.speed;
cmd->duplex = gp->phy_mii.duplex;
cmd->advertising = gp->phy_mii.advertising;
/* If we started with a forced mode, we don't have a default
* advertise set, we need to return something sensible so
* userland can re-enable autoneg properly.
*/
if (cmd->advertising == 0)
cmd->advertising = cmd->supported;
spin_unlock_irq(&gp->lock);
} else { // XXX PCS ?
cmd->supported =
(SUPPORTED_10baseT_Half | SUPPORTED_10baseT_Full |
SUPPORTED_100baseT_Half | SUPPORTED_100baseT_Full |
SUPPORTED_Autoneg);
cmd->advertising = cmd->supported;
cmd->speed = 0;
cmd->duplex = cmd->port = cmd->phy_address =
cmd->transceiver = cmd->autoneg = 0;
/* serdes means usually a Fibre connector, with most fixed */
if (gp->phy_type == phy_serdes) {
cmd->port = PORT_FIBRE;
cmd->supported = (SUPPORTED_1000baseT_Half |
SUPPORTED_1000baseT_Full |
SUPPORTED_FIBRE | SUPPORTED_Autoneg |
SUPPORTED_Pause | SUPPORTED_Asym_Pause);
cmd->advertising = cmd->supported;
cmd->transceiver = XCVR_INTERNAL;
if (gp->lstate == link_up)
cmd->speed = SPEED_1000;
cmd->duplex = DUPLEX_FULL;
cmd->autoneg = 1;
}
}
cmd->maxtxpkt = cmd->maxrxpkt = 0;
return 0;
}
static int gem_set_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct gem *gp = netdev_priv(dev);
/* Verify the settings we care about. */
if (cmd->autoneg != AUTONEG_ENABLE &&
cmd->autoneg != AUTONEG_DISABLE)
return -EINVAL;
if (cmd->autoneg == AUTONEG_ENABLE &&
cmd->advertising == 0)
return -EINVAL;
if (cmd->autoneg == AUTONEG_DISABLE &&
((cmd->speed != SPEED_1000 &&
cmd->speed != SPEED_100 &&
cmd->speed != SPEED_10) ||
(cmd->duplex != DUPLEX_HALF &&
cmd->duplex != DUPLEX_FULL)))
return -EINVAL;
/* Apply settings and restart link process. */
spin_lock_irq(&gp->lock);
gem_get_cell(gp);
gem_begin_auto_negotiation(gp, cmd);
gem_put_cell(gp);
spin_unlock_irq(&gp->lock);
return 0;
}
static int gem_nway_reset(struct net_device *dev)
{
struct gem *gp = netdev_priv(dev);
if (!gp->want_autoneg)
return -EINVAL;
/* Restart link process. */
spin_lock_irq(&gp->lock);
gem_get_cell(gp);
gem_begin_auto_negotiation(gp, NULL);
gem_put_cell(gp);
spin_unlock_irq(&gp->lock);
return 0;
}
static u32 gem_get_msglevel(struct net_device *dev)
{
struct gem *gp = netdev_priv(dev);
return gp->msg_enable;
}
static void gem_set_msglevel(struct net_device *dev, u32 value)
{
struct gem *gp = netdev_priv(dev);
gp->msg_enable = value;
}
/* Add more when I understand how to program the chip */
/* like WAKE_UCAST | WAKE_MCAST | WAKE_BCAST */
#define WOL_SUPPORTED_MASK (WAKE_MAGIC)
static void gem_get_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
struct gem *gp = netdev_priv(dev);
/* Add more when I understand how to program the chip */
if (gp->has_wol) {
wol->supported = WOL_SUPPORTED_MASK;
wol->wolopts = gp->wake_on_lan;
} else {
wol->supported = 0;
wol->wolopts = 0;
}
}
static int gem_set_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
struct gem *gp = netdev_priv(dev);
if (!gp->has_wol)
return -EOPNOTSUPP;
gp->wake_on_lan = wol->wolopts & WOL_SUPPORTED_MASK;
return 0;
}
static const struct ethtool_ops gem_ethtool_ops = {
.get_drvinfo = gem_get_drvinfo,
.get_link = ethtool_op_get_link,
.get_settings = gem_get_settings,
.set_settings = gem_set_settings,
.nway_reset = gem_nway_reset,
.get_msglevel = gem_get_msglevel,
.set_msglevel = gem_set_msglevel,
.get_wol = gem_get_wol,
.set_wol = gem_set_wol,
};
static int gem_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
struct gem *gp = netdev_priv(dev);
struct mii_ioctl_data *data = if_mii(ifr);
int rc = -EOPNOTSUPP;
unsigned long flags;
/* Hold the PM mutex while doing ioctl's or we may collide
* with power management.
*/
mutex_lock(&gp->pm_mutex);
spin_lock_irqsave(&gp->lock, flags);
gem_get_cell(gp);
spin_unlock_irqrestore(&gp->lock, flags);
switch (cmd) {
case SIOCGMIIPHY: /* Get address of MII PHY in use. */
data->phy_id = gp->mii_phy_addr;
/* Fallthrough... */
case SIOCGMIIREG: /* Read MII PHY register. */
if (!gp->running)
rc = -EAGAIN;
else {
data->val_out = __phy_read(gp, data->phy_id & 0x1f,
data->reg_num & 0x1f);
rc = 0;
}
break;
case SIOCSMIIREG: /* Write MII PHY register. */
if (!gp->running)
rc = -EAGAIN;
else {
__phy_write(gp, data->phy_id & 0x1f, data->reg_num & 0x1f,
data->val_in);
rc = 0;
}
break;
};
spin_lock_irqsave(&gp->lock, flags);
gem_put_cell(gp);
spin_unlock_irqrestore(&gp->lock, flags);
mutex_unlock(&gp->pm_mutex);
return rc;
}
#if (!defined(CONFIG_SPARC) && !defined(CONFIG_PPC_PMAC))
/* Fetch MAC address from vital product data of PCI ROM. */
static int find_eth_addr_in_vpd(void __iomem *rom_base, int len, unsigned char *dev_addr)
{
int this_offset;
for (this_offset = 0x20; this_offset < len; this_offset++) {
void __iomem *p = rom_base + this_offset;
int i;
if (readb(p + 0) != 0x90 ||
readb(p + 1) != 0x00 ||
readb(p + 2) != 0x09 ||
readb(p + 3) != 0x4e ||
readb(p + 4) != 0x41 ||
readb(p + 5) != 0x06)
continue;
this_offset += 6;
p += 6;
for (i = 0; i < 6; i++)
dev_addr[i] = readb(p + i);
return 1;
}
return 0;
}
static void get_gem_mac_nonobp(struct pci_dev *pdev, unsigned char *dev_addr)
{
size_t size;
void __iomem *p = pci_map_rom(pdev, &size);
if (p) {
int found;
found = readb(p) == 0x55 &&
readb(p + 1) == 0xaa &&
find_eth_addr_in_vpd(p, (64 * 1024), dev_addr);
pci_unmap_rom(pdev, p);
if (found)
return;
}
/* Sun MAC prefix then 3 random bytes. */
dev_addr[0] = 0x08;
dev_addr[1] = 0x00;
dev_addr[2] = 0x20;
get_random_bytes(dev_addr + 3, 3);
return;
}
#endif /* not Sparc and not PPC */
static int __devinit gem_get_device_address(struct gem *gp)
{
#if defined(CONFIG_SPARC) || defined(CONFIG_PPC_PMAC)
struct net_device *dev = gp->dev;
const unsigned char *addr;
addr = of_get_property(gp->of_node, "local-mac-address", NULL);
if (addr == NULL) {
#ifdef CONFIG_SPARC
addr = idprom->id_ethaddr;
#else
printk("\n");
printk(KERN_ERR "%s: can't get mac-address\n", dev->name);
return -1;
#endif
}
memcpy(dev->dev_addr, addr, 6);
#else
get_gem_mac_nonobp(gp->pdev, gp->dev->dev_addr);
#endif
return 0;
}
static void gem_remove_one(struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev);
if (dev) {
struct gem *gp = netdev_priv(dev);
unregister_netdev(dev);
/* Stop the link timer */
del_timer_sync(&gp->link_timer);
/* We shouldn't need any locking here */
gem_get_cell(gp);
/* Wait for a pending reset task to complete */
while (gp->reset_task_pending)
yield();
flush_scheduled_work();
/* Shut the PHY down */
gem_stop_phy(gp, 0);
gem_put_cell(gp);
/* Make sure bus master is disabled */
pci_disable_device(gp->pdev);
/* Free resources */
pci_free_consistent(pdev,
sizeof(struct gem_init_block),
gp->init_block,
gp->gblock_dvma);
iounmap(gp->regs);
pci_release_regions(pdev);
free_netdev(dev);
pci_set_drvdata(pdev, NULL);
}
}
static const struct net_device_ops gem_netdev_ops = {
.ndo_open = gem_open,
.ndo_stop = gem_close,
.ndo_start_xmit = gem_start_xmit,
.ndo_get_stats = gem_get_stats,
.ndo_set_multicast_list = gem_set_multicast,
.ndo_do_ioctl = gem_ioctl,
.ndo_tx_timeout = gem_tx_timeout,
.ndo_change_mtu = gem_change_mtu,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = gem_set_mac_address,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = gem_poll_controller,
#endif
};
static int __devinit gem_init_one(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
static int gem_version_printed = 0;
unsigned long gemreg_base, gemreg_len;
struct net_device *dev;
struct gem *gp;
int err, pci_using_dac;
if (gem_version_printed++ == 0)
printk(KERN_INFO "%s", version);
/* Apple gmac note: during probe, the chip is powered up by
* the arch code to allow the code below to work (and to let
* the chip be probed on the config space. It won't stay powered
* up until the interface is brought up however, so we can't rely
* on register configuration done at this point.
*/
err = pci_enable_device(pdev);
if (err) {
printk(KERN_ERR PFX "Cannot enable MMIO operation, "
"aborting.\n");
return err;
}
pci_set_master(pdev);
/* Configure DMA attributes. */
/* All of the GEM documentation states that 64-bit DMA addressing
* is fully supported and should work just fine. However the
* front end for RIO based GEMs is different and only supports
* 32-bit addressing.
*
* For now we assume the various PPC GEMs are 32-bit only as well.
*/
if (pdev->vendor == PCI_VENDOR_ID_SUN &&
pdev->device == PCI_DEVICE_ID_SUN_GEM &&
!pci_set_dma_mask(pdev, DMA_BIT_MASK(64))) {
pci_using_dac = 1;
} else {
err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (err) {
printk(KERN_ERR PFX "No usable DMA configuration, "
"aborting.\n");
goto err_disable_device;
}
pci_using_dac = 0;
}
gemreg_base = pci_resource_start(pdev, 0);
gemreg_len = pci_resource_len(pdev, 0);
if ((pci_resource_flags(pdev, 0) & IORESOURCE_IO) != 0) {
printk(KERN_ERR PFX "Cannot find proper PCI device "
"base address, aborting.\n");
err = -ENODEV;
goto err_disable_device;
}
dev = alloc_etherdev(sizeof(*gp));
if (!dev) {
printk(KERN_ERR PFX "Etherdev alloc failed, aborting.\n");
err = -ENOMEM;
goto err_disable_device;
}
SET_NETDEV_DEV(dev, &pdev->dev);
gp = netdev_priv(dev);
err = pci_request_regions(pdev, DRV_NAME);
if (err) {
printk(KERN_ERR PFX "Cannot obtain PCI resources, "
"aborting.\n");
goto err_out_free_netdev;
}
gp->pdev = pdev;
dev->base_addr = (long) pdev;
gp->dev = dev;
gp->msg_enable = DEFAULT_MSG;
spin_lock_init(&gp->lock);
spin_lock_init(&gp->tx_lock);
mutex_init(&gp->pm_mutex);
init_timer(&gp->link_timer);
gp->link_timer.function = gem_link_timer;
gp->link_timer.data = (unsigned long) gp;
INIT_WORK(&gp->reset_task, gem_reset_task);
gp->lstate = link_down;
gp->timer_ticks = 0;
netif_carrier_off(dev);
gp->regs = ioremap(gemreg_base, gemreg_len);
if (!gp->regs) {
printk(KERN_ERR PFX "Cannot map device registers, "
"aborting.\n");
err = -EIO;
goto err_out_free_res;
}
/* On Apple, we want a reference to the Open Firmware device-tree
* node. We use it for clock control.
*/
#if defined(CONFIG_PPC_PMAC) || defined(CONFIG_SPARC)
gp->of_node = pci_device_to_OF_node(pdev);
#endif
/* Only Apple version supports WOL afaik */
if (pdev->vendor == PCI_VENDOR_ID_APPLE)
gp->has_wol = 1;
/* Make sure cell is enabled */
gem_get_cell(gp);
/* Make sure everything is stopped and in init state */
gem_reset(gp);
/* Fill up the mii_phy structure (even if we won't use it) */
gp->phy_mii.dev = dev;
gp->phy_mii.mdio_read = _phy_read;
gp->phy_mii.mdio_write = _phy_write;
#ifdef CONFIG_PPC_PMAC
gp->phy_mii.platform_data = gp->of_node;
#endif
/* By default, we start with autoneg */
gp->want_autoneg = 1;
/* Check fifo sizes, PHY type, etc... */
if (gem_check_invariants(gp)) {
err = -ENODEV;
goto err_out_iounmap;
}
/* It is guaranteed that the returned buffer will be at least
* PAGE_SIZE aligned.
*/
gp->init_block = (struct gem_init_block *)
pci_alloc_consistent(pdev, sizeof(struct gem_init_block),
&gp->gblock_dvma);
if (!gp->init_block) {
printk(KERN_ERR PFX "Cannot allocate init block, "
"aborting.\n");
err = -ENOMEM;
goto err_out_iounmap;
}
if (gem_get_device_address(gp))
goto err_out_free_consistent;
dev->netdev_ops = &gem_netdev_ops;
netif_napi_add(dev, &gp->napi, gem_poll, 64);
dev->ethtool_ops = &gem_ethtool_ops;
dev->watchdog_timeo = 5 * HZ;
dev->irq = pdev->irq;
dev->dma = 0;
/* Set that now, in case PM kicks in now */
pci_set_drvdata(pdev, dev);
/* Detect & init PHY, start autoneg, we release the cell now
* too, it will be managed by whoever needs it
*/
gem_init_phy(gp);
spin_lock_irq(&gp->lock);
gem_put_cell(gp);
spin_unlock_irq(&gp->lock);
/* Register with kernel */
if (register_netdev(dev)) {
printk(KERN_ERR PFX "Cannot register net device, "
"aborting.\n");
err = -ENOMEM;
goto err_out_free_consistent;
}
printk(KERN_INFO "%s: Sun GEM (PCI) 10/100/1000BaseT Ethernet %pM\n",
dev->name, dev->dev_addr);
if (gp->phy_type == phy_mii_mdio0 ||
gp->phy_type == phy_mii_mdio1)
printk(KERN_INFO "%s: Found %s PHY\n", dev->name,
gp->phy_mii.def ? gp->phy_mii.def->name : "no");
/* GEM can do it all... */
dev->features |= NETIF_F_SG | NETIF_F_HW_CSUM | NETIF_F_LLTX;
if (pci_using_dac)
dev->features |= NETIF_F_HIGHDMA;
return 0;
err_out_free_consistent:
gem_remove_one(pdev);
err_out_iounmap:
gem_put_cell(gp);
iounmap(gp->regs);
err_out_free_res:
pci_release_regions(pdev);
err_out_free_netdev:
free_netdev(dev);
err_disable_device:
pci_disable_device(pdev);
return err;
}
static struct pci_driver gem_driver = {
.name = GEM_MODULE_NAME,
.id_table = gem_pci_tbl,
.probe = gem_init_one,
.remove = gem_remove_one,
#ifdef CONFIG_PM
.suspend = gem_suspend,
.resume = gem_resume,
#endif /* CONFIG_PM */
};
static int __init gem_init(void)
{
return pci_register_driver(&gem_driver);
}
static void __exit gem_cleanup(void)
{
pci_unregister_driver(&gem_driver);
}
module_init(gem_init);
module_exit(gem_cleanup);
| gpl-2.0 |
XXLRay/linux-2.6.32-rhel6.x86_64 | arch/arm/plat-s3c64xx/dma.c | 504 | 16666 | /* linux/arch/arm/plat-s3c64xx/dma.c
*
* Copyright 2009 Openmoko, Inc.
* Copyright 2009 Simtec Electronics
* Ben Dooks <ben@simtec.co.uk>
* http://armlinux.simtec.co.uk/
*
* S3C64XX DMA core
*
* 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/interrupt.h>
#include <linux/dmapool.h>
#include <linux/sysdev.h>
#include <linux/errno.h>
#include <linux/delay.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/io.h>
#include <mach/dma.h>
#include <mach/map.h>
#include <mach/irqs.h>
#include <plat/dma-plat.h>
#include <plat/regs-sys.h>
#include <asm/hardware/pl080.h>
/* dma channel state information */
struct s3c64xx_dmac {
struct sys_device sysdev;
struct clk *clk;
void __iomem *regs;
struct s3c2410_dma_chan *channels;
enum dma_ch chanbase;
};
/* pool to provide LLI buffers */
static struct dma_pool *dma_pool;
/* Debug configuration and code */
static unsigned char debug_show_buffs = 0;
static void dbg_showchan(struct s3c2410_dma_chan *chan)
{
pr_debug("DMA%d: %08x->%08x L %08x C %08x,%08x S %08x\n",
chan->number,
readl(chan->regs + PL080_CH_SRC_ADDR),
readl(chan->regs + PL080_CH_DST_ADDR),
readl(chan->regs + PL080_CH_LLI),
readl(chan->regs + PL080_CH_CONTROL),
readl(chan->regs + PL080S_CH_CONTROL2),
readl(chan->regs + PL080S_CH_CONFIG));
}
static void show_lli(struct pl080s_lli *lli)
{
pr_debug("LLI[%p] %08x->%08x, NL %08x C %08x,%08x\n",
lli, lli->src_addr, lli->dst_addr, lli->next_lli,
lli->control0, lli->control1);
}
static void dbg_showbuffs(struct s3c2410_dma_chan *chan)
{
struct s3c64xx_dma_buff *ptr;
struct s3c64xx_dma_buff *end;
pr_debug("DMA%d: buffs next %p, curr %p, end %p\n",
chan->number, chan->next, chan->curr, chan->end);
ptr = chan->next;
end = chan->end;
if (debug_show_buffs) {
for (; ptr != NULL; ptr = ptr->next) {
pr_debug("DMA%d: %08x ",
chan->number, ptr->lli_dma);
show_lli(ptr->lli);
}
}
}
/* End of Debug */
static struct s3c2410_dma_chan *s3c64xx_dma_map_channel(unsigned int channel)
{
struct s3c2410_dma_chan *chan;
unsigned int start, offs;
start = 0;
if (channel >= DMACH_PCM1_TX)
start = 8;
for (offs = 0; offs < 8; offs++) {
chan = &s3c2410_chans[start + offs];
if (!chan->in_use)
goto found;
}
return NULL;
found:
s3c_dma_chan_map[channel] = chan;
return chan;
}
int s3c2410_dma_config(unsigned int channel, int xferunit)
{
struct s3c2410_dma_chan *chan = s3c_dma_lookup_channel(channel);
if (chan == NULL)
return -EINVAL;
switch (xferunit) {
case 1:
chan->hw_width = 0;
break;
case 2:
chan->hw_width = 1;
break;
case 4:
chan->hw_width = 2;
break;
default:
printk(KERN_ERR "%s: illegal width %d\n", __func__, xferunit);
return -EINVAL;
}
return 0;
}
EXPORT_SYMBOL(s3c2410_dma_config);
static void s3c64xx_dma_fill_lli(struct s3c2410_dma_chan *chan,
struct pl080s_lli *lli,
dma_addr_t data, int size)
{
dma_addr_t src, dst;
u32 control0, control1;
switch (chan->source) {
case S3C2410_DMASRC_HW:
src = chan->dev_addr;
dst = data;
control0 = PL080_CONTROL_SRC_AHB2;
control0 |= PL080_CONTROL_DST_INCR;
break;
case S3C2410_DMASRC_MEM:
src = data;
dst = chan->dev_addr;
control0 = PL080_CONTROL_DST_AHB2;
control0 |= PL080_CONTROL_SRC_INCR;
break;
default:
BUG();
}
/* note, we do not currently setup any of the burst controls */
control1 = size >> chan->hw_width; /* size in no of xfers */
control0 |= PL080_CONTROL_PROT_SYS; /* always in priv. mode */
control0 |= PL080_CONTROL_TC_IRQ_EN; /* always fire IRQ */
control0 |= (u32)chan->hw_width << PL080_CONTROL_DWIDTH_SHIFT;
control0 |= (u32)chan->hw_width << PL080_CONTROL_SWIDTH_SHIFT;
lli->src_addr = src;
lli->dst_addr = dst;
lli->next_lli = 0;
lli->control0 = control0;
lli->control1 = control1;
}
static void s3c64xx_lli_to_regs(struct s3c2410_dma_chan *chan,
struct pl080s_lli *lli)
{
void __iomem *regs = chan->regs;
pr_debug("%s: LLI %p => regs\n", __func__, lli);
show_lli(lli);
writel(lli->src_addr, regs + PL080_CH_SRC_ADDR);
writel(lli->dst_addr, regs + PL080_CH_DST_ADDR);
writel(lli->next_lli, regs + PL080_CH_LLI);
writel(lli->control0, regs + PL080_CH_CONTROL);
writel(lli->control1, regs + PL080S_CH_CONTROL2);
}
static int s3c64xx_dma_start(struct s3c2410_dma_chan *chan)
{
struct s3c64xx_dmac *dmac = chan->dmac;
u32 config;
u32 bit = chan->bit;
dbg_showchan(chan);
pr_debug("%s: clearing interrupts\n", __func__);
/* clear interrupts */
writel(bit, dmac->regs + PL080_TC_CLEAR);
writel(bit, dmac->regs + PL080_ERR_CLEAR);
pr_debug("%s: starting channel\n", __func__);
config = readl(chan->regs + PL080S_CH_CONFIG);
config |= PL080_CONFIG_ENABLE;
pr_debug("%s: writing config %08x\n", __func__, config);
writel(config, chan->regs + PL080S_CH_CONFIG);
return 0;
}
static int s3c64xx_dma_stop(struct s3c2410_dma_chan *chan)
{
u32 config;
int timeout;
pr_debug("%s: stopping channel\n", __func__);
dbg_showchan(chan);
config = readl(chan->regs + PL080S_CH_CONFIG);
config |= PL080_CONFIG_HALT;
writel(config, chan->regs + PL080S_CH_CONFIG);
timeout = 1000;
do {
config = readl(chan->regs + PL080S_CH_CONFIG);
pr_debug("%s: %d - config %08x\n", __func__, timeout, config);
if (config & PL080_CONFIG_ACTIVE)
udelay(10);
else
break;
} while (--timeout > 0);
if (config & PL080_CONFIG_ACTIVE) {
printk(KERN_ERR "%s: channel still active\n", __func__);
return -EFAULT;
}
config = readl(chan->regs + PL080S_CH_CONFIG);
config &= ~PL080_CONFIG_ENABLE;
writel(config, chan->regs + PL080S_CH_CONFIG);
return 0;
}
static inline void s3c64xx_dma_bufffdone(struct s3c2410_dma_chan *chan,
struct s3c64xx_dma_buff *buf,
enum s3c2410_dma_buffresult result)
{
if (chan->callback_fn != NULL)
(chan->callback_fn)(chan, buf->pw, 0, result);
}
static void s3c64xx_dma_freebuff(struct s3c64xx_dma_buff *buff)
{
dma_pool_free(dma_pool, buff->lli, buff->lli_dma);
kfree(buff);
}
static int s3c64xx_dma_flush(struct s3c2410_dma_chan *chan)
{
struct s3c64xx_dma_buff *buff, *next;
u32 config;
dbg_showchan(chan);
pr_debug("%s: flushing channel\n", __func__);
config = readl(chan->regs + PL080S_CH_CONFIG);
config &= ~PL080_CONFIG_ENABLE;
writel(config, chan->regs + PL080S_CH_CONFIG);
/* dump all the buffers associated with this channel */
for (buff = chan->curr; buff != NULL; buff = next) {
next = buff->next;
pr_debug("%s: buff %p (next %p)\n", __func__, buff, buff->next);
s3c64xx_dma_bufffdone(chan, buff, S3C2410_RES_ABORT);
s3c64xx_dma_freebuff(buff);
}
chan->curr = chan->next = chan->end = NULL;
return 0;
}
int s3c2410_dma_ctrl(unsigned int channel, enum s3c2410_chan_op op)
{
struct s3c2410_dma_chan *chan = s3c_dma_lookup_channel(channel);
WARN_ON(!chan);
if (!chan)
return -EINVAL;
switch (op) {
case S3C2410_DMAOP_START:
return s3c64xx_dma_start(chan);
case S3C2410_DMAOP_STOP:
return s3c64xx_dma_stop(chan);
case S3C2410_DMAOP_FLUSH:
return s3c64xx_dma_flush(chan);
/* belive PAUSE/RESUME are no-ops */
case S3C2410_DMAOP_PAUSE:
case S3C2410_DMAOP_RESUME:
case S3C2410_DMAOP_STARTED:
case S3C2410_DMAOP_TIMEOUT:
return 0;
}
return -ENOENT;
}
EXPORT_SYMBOL(s3c2410_dma_ctrl);
/* s3c2410_dma_enque
*
*/
int s3c2410_dma_enqueue(unsigned int channel, void *id,
dma_addr_t data, int size)
{
struct s3c2410_dma_chan *chan = s3c_dma_lookup_channel(channel);
struct s3c64xx_dma_buff *next;
struct s3c64xx_dma_buff *buff;
struct pl080s_lli *lli;
unsigned long flags;
int ret;
WARN_ON(!chan);
if (!chan)
return -EINVAL;
buff = kzalloc(sizeof(struct s3c64xx_dma_buff), GFP_ATOMIC);
if (!buff) {
printk(KERN_ERR "%s: no memory for buffer\n", __func__);
return -ENOMEM;
}
lli = dma_pool_alloc(dma_pool, GFP_ATOMIC, &buff->lli_dma);
if (!lli) {
printk(KERN_ERR "%s: no memory for lli\n", __func__);
ret = -ENOMEM;
goto err_buff;
}
pr_debug("%s: buff %p, dp %08x lli (%p, %08x) %d\n",
__func__, buff, data, lli, (u32)buff->lli_dma, size);
buff->lli = lli;
buff->pw = id;
s3c64xx_dma_fill_lli(chan, lli, data, size);
local_irq_save(flags);
if ((next = chan->next) != NULL) {
struct s3c64xx_dma_buff *end = chan->end;
struct pl080s_lli *endlli = end->lli;
pr_debug("enquing onto channel\n");
end->next = buff;
endlli->next_lli = buff->lli_dma;
if (chan->flags & S3C2410_DMAF_CIRCULAR) {
struct s3c64xx_dma_buff *curr = chan->curr;
lli->next_lli = curr->lli_dma;
}
if (next == chan->curr) {
writel(buff->lli_dma, chan->regs + PL080_CH_LLI);
chan->next = buff;
}
show_lli(endlli);
chan->end = buff;
} else {
pr_debug("enquing onto empty channel\n");
chan->curr = buff;
chan->next = buff;
chan->end = buff;
s3c64xx_lli_to_regs(chan, lli);
}
local_irq_restore(flags);
show_lli(lli);
dbg_showchan(chan);
dbg_showbuffs(chan);
return 0;
err_buff:
kfree(buff);
return ret;
}
EXPORT_SYMBOL(s3c2410_dma_enqueue);
int s3c2410_dma_devconfig(int channel,
enum s3c2410_dmasrc source,
unsigned long devaddr)
{
struct s3c2410_dma_chan *chan = s3c_dma_lookup_channel(channel);
u32 peripheral;
u32 config = 0;
pr_debug("%s: channel %d, source %d, dev %08lx, chan %p\n",
__func__, channel, source, devaddr, chan);
WARN_ON(!chan);
if (!chan)
return -EINVAL;
peripheral = (chan->peripheral & 0xf);
chan->source = source;
chan->dev_addr = devaddr;
pr_debug("%s: peripheral %d\n", __func__, peripheral);
switch (source) {
case S3C2410_DMASRC_HW:
config = 2 << PL080_CONFIG_FLOW_CONTROL_SHIFT;
config |= peripheral << PL080_CONFIG_SRC_SEL_SHIFT;
break;
case S3C2410_DMASRC_MEM:
config = 1 << PL080_CONFIG_FLOW_CONTROL_SHIFT;
config |= peripheral << PL080_CONFIG_DST_SEL_SHIFT;
break;
default:
printk(KERN_ERR "%s: bad source\n", __func__);
return -EINVAL;
}
/* allow TC and ERR interrupts */
config |= PL080_CONFIG_TC_IRQ_MASK;
config |= PL080_CONFIG_ERR_IRQ_MASK;
pr_debug("%s: config %08x\n", __func__, config);
writel(config, chan->regs + PL080S_CH_CONFIG);
return 0;
}
EXPORT_SYMBOL(s3c2410_dma_devconfig);
int s3c2410_dma_getposition(unsigned int channel,
dma_addr_t *src, dma_addr_t *dst)
{
struct s3c2410_dma_chan *chan = s3c_dma_lookup_channel(channel);
WARN_ON(!chan);
if (!chan)
return -EINVAL;
if (src != NULL)
*src = readl(chan->regs + PL080_CH_SRC_ADDR);
if (dst != NULL)
*dst = readl(chan->regs + PL080_CH_DST_ADDR);
return 0;
}
EXPORT_SYMBOL(s3c2410_dma_getposition);
/* s3c2410_request_dma
*
* get control of an dma channel
*/
int s3c2410_dma_request(unsigned int channel,
struct s3c2410_dma_client *client,
void *dev)
{
struct s3c2410_dma_chan *chan;
unsigned long flags;
pr_debug("dma%d: s3c2410_request_dma: client=%s, dev=%p\n",
channel, client->name, dev);
local_irq_save(flags);
chan = s3c64xx_dma_map_channel(channel);
if (chan == NULL) {
local_irq_restore(flags);
return -EBUSY;
}
dbg_showchan(chan);
chan->client = client;
chan->in_use = 1;
chan->peripheral = channel;
local_irq_restore(flags);
/* need to setup */
pr_debug("%s: channel initialised, %p\n", __func__, chan);
return chan->number | DMACH_LOW_LEVEL;
}
EXPORT_SYMBOL(s3c2410_dma_request);
/* s3c2410_dma_free
*
* release the given channel back to the system, will stop and flush
* any outstanding transfers, and ensure the channel is ready for the
* next claimant.
*
* Note, although a warning is currently printed if the freeing client
* info is not the same as the registrant's client info, the free is still
* allowed to go through.
*/
int s3c2410_dma_free(unsigned int channel, struct s3c2410_dma_client *client)
{
struct s3c2410_dma_chan *chan = s3c_dma_lookup_channel(channel);
unsigned long flags;
if (chan == NULL)
return -EINVAL;
local_irq_save(flags);
if (chan->client != client) {
printk(KERN_WARNING "dma%d: possible free from different client (channel %p, passed %p)\n",
channel, chan->client, client);
}
/* sort out stopping and freeing the channel */
chan->client = NULL;
chan->in_use = 0;
if (!(channel & DMACH_LOW_LEVEL))
s3c_dma_chan_map[channel] = NULL;
local_irq_restore(flags);
return 0;
}
EXPORT_SYMBOL(s3c2410_dma_free);
static irqreturn_t s3c64xx_dma_irq(int irq, void *pw)
{
struct s3c64xx_dmac *dmac = pw;
struct s3c2410_dma_chan *chan;
enum s3c2410_dma_buffresult res;
u32 tcstat, errstat;
u32 bit;
int offs;
tcstat = readl(dmac->regs + PL080_TC_STATUS);
errstat = readl(dmac->regs + PL080_ERR_STATUS);
for (offs = 0, bit = 1; offs < 8; offs++, bit <<= 1) {
struct s3c64xx_dma_buff *buff;
if (!(errstat & bit) && !(tcstat & bit))
continue;
chan = dmac->channels + offs;
res = S3C2410_RES_ERR;
if (tcstat & bit) {
writel(bit, dmac->regs + PL080_TC_CLEAR);
res = S3C2410_RES_OK;
}
if (errstat & bit)
writel(bit, dmac->regs + PL080_ERR_CLEAR);
/* 'next' points to the buffer that is next to the
* currently active buffer.
* For CIRCULAR queues, 'next' will be same as 'curr'
* when 'end' is the active buffer.
*/
buff = chan->curr;
while (buff && buff != chan->next
&& buff->next != chan->next)
buff = buff->next;
if (!buff)
BUG();
if (buff == chan->next)
buff = chan->end;
s3c64xx_dma_bufffdone(chan, buff, res);
/* Free the node and update curr, if non-circular queue */
if (!(chan->flags & S3C2410_DMAF_CIRCULAR)) {
chan->curr = buff->next;
s3c64xx_dma_freebuff(buff);
}
/* Update 'next' */
buff = chan->next;
if (chan->next == chan->end) {
chan->next = chan->curr;
if (!(chan->flags & S3C2410_DMAF_CIRCULAR))
chan->end = NULL;
} else {
chan->next = buff->next;
}
}
return IRQ_HANDLED;
}
static struct sysdev_class dma_sysclass = {
.name = "s3c64xx-dma",
};
static int s3c64xx_dma_init1(int chno, enum dma_ch chbase,
int irq, unsigned int base)
{
struct s3c2410_dma_chan *chptr = &s3c2410_chans[chno];
struct s3c64xx_dmac *dmac;
char clkname[16];
void __iomem *regs;
void __iomem *regptr;
int err, ch;
dmac = kzalloc(sizeof(struct s3c64xx_dmac), GFP_KERNEL);
if (!dmac) {
printk(KERN_ERR "%s: failed to alloc mem\n", __func__);
return -ENOMEM;
}
dmac->sysdev.id = chno / 8;
dmac->sysdev.cls = &dma_sysclass;
err = sysdev_register(&dmac->sysdev);
if (err) {
printk(KERN_ERR "%s: failed to register sysdevice\n", __func__);
goto err_alloc;
}
regs = ioremap(base, 0x200);
if (!regs) {
printk(KERN_ERR "%s: failed to ioremap()\n", __func__);
err = -ENXIO;
goto err_dev;
}
snprintf(clkname, sizeof(clkname), "dma%d", dmac->sysdev.id);
dmac->clk = clk_get(NULL, clkname);
if (IS_ERR(dmac->clk)) {
printk(KERN_ERR "%s: failed to get clock %s\n", __func__, clkname);
err = PTR_ERR(dmac->clk);
goto err_map;
}
clk_enable(dmac->clk);
dmac->regs = regs;
dmac->chanbase = chbase;
dmac->channels = chptr;
err = request_irq(irq, s3c64xx_dma_irq, 0, "DMA", dmac);
if (err < 0) {
printk(KERN_ERR "%s: failed to get irq\n", __func__);
goto err_clk;
}
regptr = regs + PL080_Cx_BASE(0);
for (ch = 0; ch < 8; ch++, chno++, chptr++) {
printk(KERN_INFO "%s: registering DMA %d (%p)\n",
__func__, chno, regptr);
chptr->bit = 1 << ch;
chptr->number = chno;
chptr->dmac = dmac;
chptr->regs = regptr;
regptr += PL008_Cx_STRIDE;
}
/* for the moment, permanently enable the controller */
writel(PL080_CONFIG_ENABLE, regs + PL080_CONFIG);
printk(KERN_INFO "PL080: IRQ %d, at %p\n", irq, regs);
return 0;
err_clk:
clk_disable(dmac->clk);
clk_put(dmac->clk);
err_map:
iounmap(regs);
err_dev:
sysdev_unregister(&dmac->sysdev);
err_alloc:
kfree(dmac);
return err;
}
static int __init s3c64xx_dma_init(void)
{
int ret;
printk(KERN_INFO "%s: Registering DMA channels\n", __func__);
dma_pool = dma_pool_create("DMA-LLI", NULL, sizeof(struct pl080s_lli), 16, 0);
if (!dma_pool) {
printk(KERN_ERR "%s: failed to create pool\n", __func__);
return -ENOMEM;
}
ret = sysdev_class_register(&dma_sysclass);
if (ret) {
printk(KERN_ERR "%s: failed to create sysclass\n", __func__);
return -ENOMEM;
}
/* Set all DMA configuration to be DMA, not SDMA */
writel(0xffffff, S3C_SYSREG(0x110));
/* Register standard DMA controlers */
s3c64xx_dma_init1(0, DMACH_UART0, IRQ_DMA0, 0x75000000);
s3c64xx_dma_init1(8, DMACH_PCM1_TX, IRQ_DMA1, 0x75100000);
return 0;
}
arch_initcall(s3c64xx_dma_init);
| gpl-2.0 |
anak1n/hercules_kerenl_jugs | drivers/net/bnx2x_main.c | 760 | 380860 | /* bnx2x_main.c: Broadcom Everest network driver.
*
* Copyright (c) 2007-2010 Broadcom 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.
*
* Maintained by: Eilon Greenstein <eilong@broadcom.com>
* Written by: Eliezer Tamir
* Based on code from Michael Chan's bnx2 driver
* UDP CSUM errata workaround by Arik Gendelman
* Slowpath and fastpath rework by Vladislav Zolotarov
* Statistics and Link management by Yitchak Gertner
*
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/device.h> /* for dev_info() */
#include <linux/timer.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/interrupt.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/dma-mapping.h>
#include <linux/bitops.h>
#include <linux/irq.h>
#include <linux/delay.h>
#include <asm/byteorder.h>
#include <linux/time.h>
#include <linux/ethtool.h>
#include <linux/mii.h>
#include <linux/if_vlan.h>
#include <net/ip.h>
#include <net/tcp.h>
#include <net/checksum.h>
#include <net/ip6_checksum.h>
#include <linux/workqueue.h>
#include <linux/crc32.h>
#include <linux/crc32c.h>
#include <linux/prefetch.h>
#include <linux/zlib.h>
#include <linux/io.h>
#include <linux/stringify.h>
#include "bnx2x.h"
#include "bnx2x_init.h"
#include "bnx2x_init_ops.h"
#include "bnx2x_dump.h"
#define DRV_MODULE_VERSION "1.52.53-2"
#define DRV_MODULE_RELDATE "2010/21/07"
#define BNX2X_BC_VER 0x040200
#include <linux/firmware.h>
#include "bnx2x_fw_file_hdr.h"
/* FW files */
#define FW_FILE_VERSION \
__stringify(BCM_5710_FW_MAJOR_VERSION) "." \
__stringify(BCM_5710_FW_MINOR_VERSION) "." \
__stringify(BCM_5710_FW_REVISION_VERSION) "." \
__stringify(BCM_5710_FW_ENGINEERING_VERSION)
#define FW_FILE_NAME_E1 "bnx2x-e1-" FW_FILE_VERSION ".fw"
#define FW_FILE_NAME_E1H "bnx2x-e1h-" FW_FILE_VERSION ".fw"
/* Time in jiffies before concluding the transmitter is hung */
#define TX_TIMEOUT (5*HZ)
static char version[] __devinitdata =
"Broadcom NetXtreme II 5771x 10Gigabit Ethernet Driver "
DRV_MODULE_NAME " " DRV_MODULE_VERSION " (" DRV_MODULE_RELDATE ")\n";
MODULE_AUTHOR("Eliezer Tamir");
MODULE_DESCRIPTION("Broadcom NetXtreme II BCM57710/57711/57711E Driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_MODULE_VERSION);
MODULE_FIRMWARE(FW_FILE_NAME_E1);
MODULE_FIRMWARE(FW_FILE_NAME_E1H);
static int multi_mode = 1;
module_param(multi_mode, int, 0);
MODULE_PARM_DESC(multi_mode, " Multi queue mode "
"(0 Disable; 1 Enable (default))");
static int num_queues;
module_param(num_queues, int, 0);
MODULE_PARM_DESC(num_queues, " Number of queues for multi_mode=1"
" (default is as a number of CPUs)");
static int disable_tpa;
module_param(disable_tpa, int, 0);
MODULE_PARM_DESC(disable_tpa, " Disable the TPA (LRO) feature");
static int int_mode;
module_param(int_mode, int, 0);
MODULE_PARM_DESC(int_mode, " Force interrupt mode other then MSI-X "
"(1 INT#x; 2 MSI)");
static int dropless_fc;
module_param(dropless_fc, int, 0);
MODULE_PARM_DESC(dropless_fc, " Pause on exhausted host ring");
static int poll;
module_param(poll, int, 0);
MODULE_PARM_DESC(poll, " Use polling (for debug)");
static int mrrs = -1;
module_param(mrrs, int, 0);
MODULE_PARM_DESC(mrrs, " Force Max Read Req Size (0..3) (for debug)");
static int debug;
module_param(debug, int, 0);
MODULE_PARM_DESC(debug, " Default debug msglevel");
static int load_count[3]; /* 0-common, 1-port0, 2-port1 */
static struct workqueue_struct *bnx2x_wq;
enum bnx2x_board_type {
BCM57710 = 0,
BCM57711 = 1,
BCM57711E = 2,
};
/* indexed by board_type, above */
static struct {
char *name;
} board_info[] __devinitdata = {
{ "Broadcom NetXtreme II BCM57710 XGb" },
{ "Broadcom NetXtreme II BCM57711 XGb" },
{ "Broadcom NetXtreme II BCM57711E XGb" }
};
static DEFINE_PCI_DEVICE_TABLE(bnx2x_pci_tbl) = {
{ PCI_VDEVICE(BROADCOM, PCI_DEVICE_ID_NX2_57710), BCM57710 },
{ PCI_VDEVICE(BROADCOM, PCI_DEVICE_ID_NX2_57711), BCM57711 },
{ PCI_VDEVICE(BROADCOM, PCI_DEVICE_ID_NX2_57711E), BCM57711E },
{ 0 }
};
MODULE_DEVICE_TABLE(pci, bnx2x_pci_tbl);
/****************************************************************************
* General service functions
****************************************************************************/
/* used only at init
* locking is done by mcp
*/
void bnx2x_reg_wr_ind(struct bnx2x *bp, u32 addr, u32 val)
{
pci_write_config_dword(bp->pdev, PCICFG_GRC_ADDRESS, addr);
pci_write_config_dword(bp->pdev, PCICFG_GRC_DATA, val);
pci_write_config_dword(bp->pdev, PCICFG_GRC_ADDRESS,
PCICFG_VENDOR_ID_OFFSET);
}
static u32 bnx2x_reg_rd_ind(struct bnx2x *bp, u32 addr)
{
u32 val;
pci_write_config_dword(bp->pdev, PCICFG_GRC_ADDRESS, addr);
pci_read_config_dword(bp->pdev, PCICFG_GRC_DATA, &val);
pci_write_config_dword(bp->pdev, PCICFG_GRC_ADDRESS,
PCICFG_VENDOR_ID_OFFSET);
return val;
}
static const u32 dmae_reg_go_c[] = {
DMAE_REG_GO_C0, DMAE_REG_GO_C1, DMAE_REG_GO_C2, DMAE_REG_GO_C3,
DMAE_REG_GO_C4, DMAE_REG_GO_C5, DMAE_REG_GO_C6, DMAE_REG_GO_C7,
DMAE_REG_GO_C8, DMAE_REG_GO_C9, DMAE_REG_GO_C10, DMAE_REG_GO_C11,
DMAE_REG_GO_C12, DMAE_REG_GO_C13, DMAE_REG_GO_C14, DMAE_REG_GO_C15
};
/* copy command into DMAE command memory and set DMAE command go */
static void bnx2x_post_dmae(struct bnx2x *bp, struct dmae_command *dmae,
int idx)
{
u32 cmd_offset;
int i;
cmd_offset = (DMAE_REG_CMD_MEM + sizeof(struct dmae_command) * idx);
for (i = 0; i < (sizeof(struct dmae_command)/4); i++) {
REG_WR(bp, cmd_offset + i*4, *(((u32 *)dmae) + i));
DP(BNX2X_MSG_OFF, "DMAE cmd[%d].%d (0x%08x) : 0x%08x\n",
idx, i, cmd_offset + i*4, *(((u32 *)dmae) + i));
}
REG_WR(bp, dmae_reg_go_c[idx], 1);
}
void bnx2x_write_dmae(struct bnx2x *bp, dma_addr_t dma_addr, u32 dst_addr,
u32 len32)
{
struct dmae_command dmae;
u32 *wb_comp = bnx2x_sp(bp, wb_comp);
int cnt = 200;
if (!bp->dmae_ready) {
u32 *data = bnx2x_sp(bp, wb_data[0]);
DP(BNX2X_MSG_OFF, "DMAE is not ready (dst_addr %08x len32 %d)"
" using indirect\n", dst_addr, len32);
bnx2x_init_ind_wr(bp, dst_addr, data, len32);
return;
}
memset(&dmae, 0, sizeof(struct dmae_command));
dmae.opcode = (DMAE_CMD_SRC_PCI | DMAE_CMD_DST_GRC |
DMAE_CMD_C_DST_PCI | DMAE_CMD_C_ENABLE |
DMAE_CMD_SRC_RESET | DMAE_CMD_DST_RESET |
#ifdef __BIG_ENDIAN
DMAE_CMD_ENDIANITY_B_DW_SWAP |
#else
DMAE_CMD_ENDIANITY_DW_SWAP |
#endif
(BP_PORT(bp) ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0) |
(BP_E1HVN(bp) << DMAE_CMD_E1HVN_SHIFT));
dmae.src_addr_lo = U64_LO(dma_addr);
dmae.src_addr_hi = U64_HI(dma_addr);
dmae.dst_addr_lo = dst_addr >> 2;
dmae.dst_addr_hi = 0;
dmae.len = len32;
dmae.comp_addr_lo = U64_LO(bnx2x_sp_mapping(bp, wb_comp));
dmae.comp_addr_hi = U64_HI(bnx2x_sp_mapping(bp, wb_comp));
dmae.comp_val = DMAE_COMP_VAL;
DP(BNX2X_MSG_OFF, "DMAE: opcode 0x%08x\n"
DP_LEVEL "src_addr [%x:%08x] len [%d *4] "
"dst_addr [%x:%08x (%08x)]\n"
DP_LEVEL "comp_addr [%x:%08x] comp_val 0x%08x\n",
dmae.opcode, dmae.src_addr_hi, dmae.src_addr_lo,
dmae.len, dmae.dst_addr_hi, dmae.dst_addr_lo, dst_addr,
dmae.comp_addr_hi, dmae.comp_addr_lo, dmae.comp_val);
DP(BNX2X_MSG_OFF, "data [0x%08x 0x%08x 0x%08x 0x%08x]\n",
bp->slowpath->wb_data[0], bp->slowpath->wb_data[1],
bp->slowpath->wb_data[2], bp->slowpath->wb_data[3]);
mutex_lock(&bp->dmae_mutex);
*wb_comp = 0;
bnx2x_post_dmae(bp, &dmae, INIT_DMAE_C(bp));
udelay(5);
while (*wb_comp != DMAE_COMP_VAL) {
DP(BNX2X_MSG_OFF, "wb_comp 0x%08x\n", *wb_comp);
if (!cnt) {
BNX2X_ERR("DMAE timeout!\n");
break;
}
cnt--;
/* adjust delay for emulation/FPGA */
if (CHIP_REV_IS_SLOW(bp))
msleep(100);
else
udelay(5);
}
mutex_unlock(&bp->dmae_mutex);
}
void bnx2x_read_dmae(struct bnx2x *bp, u32 src_addr, u32 len32)
{
struct dmae_command dmae;
u32 *wb_comp = bnx2x_sp(bp, wb_comp);
int cnt = 200;
if (!bp->dmae_ready) {
u32 *data = bnx2x_sp(bp, wb_data[0]);
int i;
DP(BNX2X_MSG_OFF, "DMAE is not ready (src_addr %08x len32 %d)"
" using indirect\n", src_addr, len32);
for (i = 0; i < len32; i++)
data[i] = bnx2x_reg_rd_ind(bp, src_addr + i*4);
return;
}
memset(&dmae, 0, sizeof(struct dmae_command));
dmae.opcode = (DMAE_CMD_SRC_GRC | DMAE_CMD_DST_PCI |
DMAE_CMD_C_DST_PCI | DMAE_CMD_C_ENABLE |
DMAE_CMD_SRC_RESET | DMAE_CMD_DST_RESET |
#ifdef __BIG_ENDIAN
DMAE_CMD_ENDIANITY_B_DW_SWAP |
#else
DMAE_CMD_ENDIANITY_DW_SWAP |
#endif
(BP_PORT(bp) ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0) |
(BP_E1HVN(bp) << DMAE_CMD_E1HVN_SHIFT));
dmae.src_addr_lo = src_addr >> 2;
dmae.src_addr_hi = 0;
dmae.dst_addr_lo = U64_LO(bnx2x_sp_mapping(bp, wb_data));
dmae.dst_addr_hi = U64_HI(bnx2x_sp_mapping(bp, wb_data));
dmae.len = len32;
dmae.comp_addr_lo = U64_LO(bnx2x_sp_mapping(bp, wb_comp));
dmae.comp_addr_hi = U64_HI(bnx2x_sp_mapping(bp, wb_comp));
dmae.comp_val = DMAE_COMP_VAL;
DP(BNX2X_MSG_OFF, "DMAE: opcode 0x%08x\n"
DP_LEVEL "src_addr [%x:%08x] len [%d *4] "
"dst_addr [%x:%08x (%08x)]\n"
DP_LEVEL "comp_addr [%x:%08x] comp_val 0x%08x\n",
dmae.opcode, dmae.src_addr_hi, dmae.src_addr_lo,
dmae.len, dmae.dst_addr_hi, dmae.dst_addr_lo, src_addr,
dmae.comp_addr_hi, dmae.comp_addr_lo, dmae.comp_val);
mutex_lock(&bp->dmae_mutex);
memset(bnx2x_sp(bp, wb_data[0]), 0, sizeof(u32) * 4);
*wb_comp = 0;
bnx2x_post_dmae(bp, &dmae, INIT_DMAE_C(bp));
udelay(5);
while (*wb_comp != DMAE_COMP_VAL) {
if (!cnt) {
BNX2X_ERR("DMAE timeout!\n");
break;
}
cnt--;
/* adjust delay for emulation/FPGA */
if (CHIP_REV_IS_SLOW(bp))
msleep(100);
else
udelay(5);
}
DP(BNX2X_MSG_OFF, "data [0x%08x 0x%08x 0x%08x 0x%08x]\n",
bp->slowpath->wb_data[0], bp->slowpath->wb_data[1],
bp->slowpath->wb_data[2], bp->slowpath->wb_data[3]);
mutex_unlock(&bp->dmae_mutex);
}
void bnx2x_write_dmae_phys_len(struct bnx2x *bp, dma_addr_t phys_addr,
u32 addr, u32 len)
{
int dmae_wr_max = DMAE_LEN32_WR_MAX(bp);
int offset = 0;
while (len > dmae_wr_max) {
bnx2x_write_dmae(bp, phys_addr + offset,
addr + offset, dmae_wr_max);
offset += dmae_wr_max * 4;
len -= dmae_wr_max;
}
bnx2x_write_dmae(bp, phys_addr + offset, addr + offset, len);
}
/* used only for slowpath so not inlined */
static void bnx2x_wb_wr(struct bnx2x *bp, int reg, u32 val_hi, u32 val_lo)
{
u32 wb_write[2];
wb_write[0] = val_hi;
wb_write[1] = val_lo;
REG_WR_DMAE(bp, reg, wb_write, 2);
}
#ifdef USE_WB_RD
static u64 bnx2x_wb_rd(struct bnx2x *bp, int reg)
{
u32 wb_data[2];
REG_RD_DMAE(bp, reg, wb_data, 2);
return HILO_U64(wb_data[0], wb_data[1]);
}
#endif
static int bnx2x_mc_assert(struct bnx2x *bp)
{
char last_idx;
int i, rc = 0;
u32 row0, row1, row2, row3;
/* XSTORM */
last_idx = REG_RD8(bp, BAR_XSTRORM_INTMEM +
XSTORM_ASSERT_LIST_INDEX_OFFSET);
if (last_idx)
BNX2X_ERR("XSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
/* print the asserts */
for (i = 0; i < STROM_ASSERT_ARRAY_SIZE; i++) {
row0 = REG_RD(bp, BAR_XSTRORM_INTMEM +
XSTORM_ASSERT_LIST_OFFSET(i));
row1 = REG_RD(bp, BAR_XSTRORM_INTMEM +
XSTORM_ASSERT_LIST_OFFSET(i) + 4);
row2 = REG_RD(bp, BAR_XSTRORM_INTMEM +
XSTORM_ASSERT_LIST_OFFSET(i) + 8);
row3 = REG_RD(bp, BAR_XSTRORM_INTMEM +
XSTORM_ASSERT_LIST_OFFSET(i) + 12);
if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
BNX2X_ERR("XSTORM_ASSERT_INDEX 0x%x = 0x%08x"
" 0x%08x 0x%08x 0x%08x\n",
i, row3, row2, row1, row0);
rc++;
} else {
break;
}
}
/* TSTORM */
last_idx = REG_RD8(bp, BAR_TSTRORM_INTMEM +
TSTORM_ASSERT_LIST_INDEX_OFFSET);
if (last_idx)
BNX2X_ERR("TSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
/* print the asserts */
for (i = 0; i < STROM_ASSERT_ARRAY_SIZE; i++) {
row0 = REG_RD(bp, BAR_TSTRORM_INTMEM +
TSTORM_ASSERT_LIST_OFFSET(i));
row1 = REG_RD(bp, BAR_TSTRORM_INTMEM +
TSTORM_ASSERT_LIST_OFFSET(i) + 4);
row2 = REG_RD(bp, BAR_TSTRORM_INTMEM +
TSTORM_ASSERT_LIST_OFFSET(i) + 8);
row3 = REG_RD(bp, BAR_TSTRORM_INTMEM +
TSTORM_ASSERT_LIST_OFFSET(i) + 12);
if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
BNX2X_ERR("TSTORM_ASSERT_INDEX 0x%x = 0x%08x"
" 0x%08x 0x%08x 0x%08x\n",
i, row3, row2, row1, row0);
rc++;
} else {
break;
}
}
/* CSTORM */
last_idx = REG_RD8(bp, BAR_CSTRORM_INTMEM +
CSTORM_ASSERT_LIST_INDEX_OFFSET);
if (last_idx)
BNX2X_ERR("CSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
/* print the asserts */
for (i = 0; i < STROM_ASSERT_ARRAY_SIZE; i++) {
row0 = REG_RD(bp, BAR_CSTRORM_INTMEM +
CSTORM_ASSERT_LIST_OFFSET(i));
row1 = REG_RD(bp, BAR_CSTRORM_INTMEM +
CSTORM_ASSERT_LIST_OFFSET(i) + 4);
row2 = REG_RD(bp, BAR_CSTRORM_INTMEM +
CSTORM_ASSERT_LIST_OFFSET(i) + 8);
row3 = REG_RD(bp, BAR_CSTRORM_INTMEM +
CSTORM_ASSERT_LIST_OFFSET(i) + 12);
if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
BNX2X_ERR("CSTORM_ASSERT_INDEX 0x%x = 0x%08x"
" 0x%08x 0x%08x 0x%08x\n",
i, row3, row2, row1, row0);
rc++;
} else {
break;
}
}
/* USTORM */
last_idx = REG_RD8(bp, BAR_USTRORM_INTMEM +
USTORM_ASSERT_LIST_INDEX_OFFSET);
if (last_idx)
BNX2X_ERR("USTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
/* print the asserts */
for (i = 0; i < STROM_ASSERT_ARRAY_SIZE; i++) {
row0 = REG_RD(bp, BAR_USTRORM_INTMEM +
USTORM_ASSERT_LIST_OFFSET(i));
row1 = REG_RD(bp, BAR_USTRORM_INTMEM +
USTORM_ASSERT_LIST_OFFSET(i) + 4);
row2 = REG_RD(bp, BAR_USTRORM_INTMEM +
USTORM_ASSERT_LIST_OFFSET(i) + 8);
row3 = REG_RD(bp, BAR_USTRORM_INTMEM +
USTORM_ASSERT_LIST_OFFSET(i) + 12);
if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
BNX2X_ERR("USTORM_ASSERT_INDEX 0x%x = 0x%08x"
" 0x%08x 0x%08x 0x%08x\n",
i, row3, row2, row1, row0);
rc++;
} else {
break;
}
}
return rc;
}
static void bnx2x_fw_dump(struct bnx2x *bp)
{
u32 addr;
u32 mark, offset;
__be32 data[9];
int word;
if (BP_NOMCP(bp)) {
BNX2X_ERR("NO MCP - can not dump\n");
return;
}
addr = bp->common.shmem_base - 0x0800 + 4;
mark = REG_RD(bp, addr);
mark = MCP_REG_MCPR_SCRATCH + ((mark + 0x3) & ~0x3) - 0x08000000;
pr_err("begin fw dump (mark 0x%x)\n", mark);
pr_err("");
for (offset = mark; offset <= bp->common.shmem_base; offset += 0x8*4) {
for (word = 0; word < 8; word++)
data[word] = htonl(REG_RD(bp, offset + 4*word));
data[8] = 0x0;
pr_cont("%s", (char *)data);
}
for (offset = addr + 4; offset <= mark; offset += 0x8*4) {
for (word = 0; word < 8; word++)
data[word] = htonl(REG_RD(bp, offset + 4*word));
data[8] = 0x0;
pr_cont("%s", (char *)data);
}
pr_err("end of fw dump\n");
}
static void bnx2x_panic_dump(struct bnx2x *bp)
{
int i;
u16 j, start, end;
bp->stats_state = STATS_STATE_DISABLED;
DP(BNX2X_MSG_STATS, "stats_state - DISABLED\n");
BNX2X_ERR("begin crash dump -----------------\n");
/* Indices */
/* Common */
BNX2X_ERR("def_c_idx(0x%x) def_u_idx(0x%x) def_x_idx(0x%x)"
" def_t_idx(0x%x) def_att_idx(0x%x) attn_state(0x%x)"
" spq_prod_idx(0x%x)\n",
bp->def_c_idx, bp->def_u_idx, bp->def_x_idx, bp->def_t_idx,
bp->def_att_idx, bp->attn_state, bp->spq_prod_idx);
/* Rx */
for_each_queue(bp, i) {
struct bnx2x_fastpath *fp = &bp->fp[i];
BNX2X_ERR("fp%d: rx_bd_prod(0x%x) rx_bd_cons(0x%x)"
" *rx_bd_cons_sb(0x%x) rx_comp_prod(0x%x)"
" rx_comp_cons(0x%x) *rx_cons_sb(0x%x)\n",
i, fp->rx_bd_prod, fp->rx_bd_cons,
le16_to_cpu(*fp->rx_bd_cons_sb), fp->rx_comp_prod,
fp->rx_comp_cons, le16_to_cpu(*fp->rx_cons_sb));
BNX2X_ERR(" rx_sge_prod(0x%x) last_max_sge(0x%x)"
" fp_u_idx(0x%x) *sb_u_idx(0x%x)\n",
fp->rx_sge_prod, fp->last_max_sge,
le16_to_cpu(fp->fp_u_idx),
fp->status_blk->u_status_block.status_block_index);
}
/* Tx */
for_each_queue(bp, i) {
struct bnx2x_fastpath *fp = &bp->fp[i];
BNX2X_ERR("fp%d: tx_pkt_prod(0x%x) tx_pkt_cons(0x%x)"
" tx_bd_prod(0x%x) tx_bd_cons(0x%x)"
" *tx_cons_sb(0x%x)\n",
i, fp->tx_pkt_prod, fp->tx_pkt_cons, fp->tx_bd_prod,
fp->tx_bd_cons, le16_to_cpu(*fp->tx_cons_sb));
BNX2X_ERR(" fp_c_idx(0x%x) *sb_c_idx(0x%x)"
" tx_db_prod(0x%x)\n", le16_to_cpu(fp->fp_c_idx),
fp->status_blk->c_status_block.status_block_index,
fp->tx_db.data.prod);
}
/* Rings */
/* Rx */
for_each_queue(bp, i) {
struct bnx2x_fastpath *fp = &bp->fp[i];
start = RX_BD(le16_to_cpu(*fp->rx_cons_sb) - 10);
end = RX_BD(le16_to_cpu(*fp->rx_cons_sb) + 503);
for (j = start; j != end; j = RX_BD(j + 1)) {
u32 *rx_bd = (u32 *)&fp->rx_desc_ring[j];
struct sw_rx_bd *sw_bd = &fp->rx_buf_ring[j];
BNX2X_ERR("fp%d: rx_bd[%x]=[%x:%x] sw_bd=[%p]\n",
i, j, rx_bd[1], rx_bd[0], sw_bd->skb);
}
start = RX_SGE(fp->rx_sge_prod);
end = RX_SGE(fp->last_max_sge);
for (j = start; j != end; j = RX_SGE(j + 1)) {
u32 *rx_sge = (u32 *)&fp->rx_sge_ring[j];
struct sw_rx_page *sw_page = &fp->rx_page_ring[j];
BNX2X_ERR("fp%d: rx_sge[%x]=[%x:%x] sw_page=[%p]\n",
i, j, rx_sge[1], rx_sge[0], sw_page->page);
}
start = RCQ_BD(fp->rx_comp_cons - 10);
end = RCQ_BD(fp->rx_comp_cons + 503);
for (j = start; j != end; j = RCQ_BD(j + 1)) {
u32 *cqe = (u32 *)&fp->rx_comp_ring[j];
BNX2X_ERR("fp%d: cqe[%x]=[%x:%x:%x:%x]\n",
i, j, cqe[0], cqe[1], cqe[2], cqe[3]);
}
}
/* Tx */
for_each_queue(bp, i) {
struct bnx2x_fastpath *fp = &bp->fp[i];
start = TX_BD(le16_to_cpu(*fp->tx_cons_sb) - 10);
end = TX_BD(le16_to_cpu(*fp->tx_cons_sb) + 245);
for (j = start; j != end; j = TX_BD(j + 1)) {
struct sw_tx_bd *sw_bd = &fp->tx_buf_ring[j];
BNX2X_ERR("fp%d: packet[%x]=[%p,%x]\n",
i, j, sw_bd->skb, sw_bd->first_bd);
}
start = TX_BD(fp->tx_bd_cons - 10);
end = TX_BD(fp->tx_bd_cons + 254);
for (j = start; j != end; j = TX_BD(j + 1)) {
u32 *tx_bd = (u32 *)&fp->tx_desc_ring[j];
BNX2X_ERR("fp%d: tx_bd[%x]=[%x:%x:%x:%x]\n",
i, j, tx_bd[0], tx_bd[1], tx_bd[2], tx_bd[3]);
}
}
bnx2x_fw_dump(bp);
bnx2x_mc_assert(bp);
BNX2X_ERR("end crash dump -----------------\n");
}
static void bnx2x_int_enable(struct bnx2x *bp)
{
int port = BP_PORT(bp);
u32 addr = port ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
u32 val = REG_RD(bp, addr);
int msix = (bp->flags & USING_MSIX_FLAG) ? 1 : 0;
int msi = (bp->flags & USING_MSI_FLAG) ? 1 : 0;
if (msix) {
val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
HC_CONFIG_0_REG_INT_LINE_EN_0);
val |= (HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
HC_CONFIG_0_REG_ATTN_BIT_EN_0);
} else if (msi) {
val &= ~HC_CONFIG_0_REG_INT_LINE_EN_0;
val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
HC_CONFIG_0_REG_ATTN_BIT_EN_0);
} else {
val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
HC_CONFIG_0_REG_INT_LINE_EN_0 |
HC_CONFIG_0_REG_ATTN_BIT_EN_0);
DP(NETIF_MSG_INTR, "write %x to HC %d (addr 0x%x)\n",
val, port, addr);
REG_WR(bp, addr, val);
val &= ~HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0;
}
DP(NETIF_MSG_INTR, "write %x to HC %d (addr 0x%x) mode %s\n",
val, port, addr, (msix ? "MSI-X" : (msi ? "MSI" : "INTx")));
REG_WR(bp, addr, val);
/*
* Ensure that HC_CONFIG is written before leading/trailing edge config
*/
mmiowb();
barrier();
if (CHIP_IS_E1H(bp)) {
/* init leading/trailing edge */
if (IS_E1HMF(bp)) {
val = (0xee0f | (1 << (BP_E1HVN(bp) + 4)));
if (bp->port.pmf)
/* enable nig and gpio3 attention */
val |= 0x1100;
} else
val = 0xffff;
REG_WR(bp, HC_REG_TRAILING_EDGE_0 + port*8, val);
REG_WR(bp, HC_REG_LEADING_EDGE_0 + port*8, val);
}
/* Make sure that interrupts are indeed enabled from here on */
mmiowb();
}
static void bnx2x_int_disable(struct bnx2x *bp)
{
int port = BP_PORT(bp);
u32 addr = port ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
u32 val = REG_RD(bp, addr);
val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
HC_CONFIG_0_REG_INT_LINE_EN_0 |
HC_CONFIG_0_REG_ATTN_BIT_EN_0);
DP(NETIF_MSG_INTR, "write %x to HC %d (addr 0x%x)\n",
val, port, addr);
/* flush all outstanding writes */
mmiowb();
REG_WR(bp, addr, val);
if (REG_RD(bp, addr) != val)
BNX2X_ERR("BUG! proper val not read from IGU!\n");
}
static void bnx2x_int_disable_sync(struct bnx2x *bp, int disable_hw)
{
int msix = (bp->flags & USING_MSIX_FLAG) ? 1 : 0;
int i, offset;
/* disable interrupt handling */
atomic_inc(&bp->intr_sem);
smp_wmb(); /* Ensure that bp->intr_sem update is SMP-safe */
if (disable_hw)
/* prevent the HW from sending interrupts */
bnx2x_int_disable(bp);
/* make sure all ISRs are done */
if (msix) {
synchronize_irq(bp->msix_table[0].vector);
offset = 1;
#ifdef BCM_CNIC
offset++;
#endif
for_each_queue(bp, i)
synchronize_irq(bp->msix_table[i + offset].vector);
} else
synchronize_irq(bp->pdev->irq);
/* make sure sp_task is not running */
cancel_delayed_work(&bp->sp_task);
flush_workqueue(bnx2x_wq);
}
/* fast path */
/*
* General service functions
*/
/* Return true if succeeded to acquire the lock */
static bool bnx2x_trylock_hw_lock(struct bnx2x *bp, u32 resource)
{
u32 lock_status;
u32 resource_bit = (1 << resource);
int func = BP_FUNC(bp);
u32 hw_lock_control_reg;
DP(NETIF_MSG_HW, "Trying to take a lock on resource %d\n", resource);
/* Validating that the resource is within range */
if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
DP(NETIF_MSG_HW,
"resource(0x%x) > HW_LOCK_MAX_RESOURCE_VALUE(0x%x)\n",
resource, HW_LOCK_MAX_RESOURCE_VALUE);
return -EINVAL;
}
if (func <= 5)
hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + func*8);
else
hw_lock_control_reg =
(MISC_REG_DRIVER_CONTROL_7 + (func - 6)*8);
/* Try to acquire the lock */
REG_WR(bp, hw_lock_control_reg + 4, resource_bit);
lock_status = REG_RD(bp, hw_lock_control_reg);
if (lock_status & resource_bit)
return true;
DP(NETIF_MSG_HW, "Failed to get a lock on resource %d\n", resource);
return false;
}
static inline void bnx2x_ack_sb(struct bnx2x *bp, u8 sb_id,
u8 storm, u16 index, u8 op, u8 update)
{
u32 hc_addr = (HC_REG_COMMAND_REG + BP_PORT(bp)*32 +
COMMAND_REG_INT_ACK);
struct igu_ack_register igu_ack;
igu_ack.status_block_index = index;
igu_ack.sb_id_and_flags =
((sb_id << IGU_ACK_REGISTER_STATUS_BLOCK_ID_SHIFT) |
(storm << IGU_ACK_REGISTER_STORM_ID_SHIFT) |
(update << IGU_ACK_REGISTER_UPDATE_INDEX_SHIFT) |
(op << IGU_ACK_REGISTER_INTERRUPT_MODE_SHIFT));
DP(BNX2X_MSG_OFF, "write 0x%08x to HC addr 0x%x\n",
(*(u32 *)&igu_ack), hc_addr);
REG_WR(bp, hc_addr, (*(u32 *)&igu_ack));
/* Make sure that ACK is written */
mmiowb();
barrier();
}
static inline void bnx2x_update_fpsb_idx(struct bnx2x_fastpath *fp)
{
struct host_status_block *fpsb = fp->status_blk;
barrier(); /* status block is written to by the chip */
fp->fp_c_idx = fpsb->c_status_block.status_block_index;
fp->fp_u_idx = fpsb->u_status_block.status_block_index;
}
static u16 bnx2x_ack_int(struct bnx2x *bp)
{
u32 hc_addr = (HC_REG_COMMAND_REG + BP_PORT(bp)*32 +
COMMAND_REG_SIMD_MASK);
u32 result = REG_RD(bp, hc_addr);
DP(BNX2X_MSG_OFF, "read 0x%08x from HC addr 0x%x\n",
result, hc_addr);
return result;
}
/*
* fast path service functions
*/
static inline int bnx2x_has_tx_work_unload(struct bnx2x_fastpath *fp)
{
/* Tell compiler that consumer and producer can change */
barrier();
return (fp->tx_pkt_prod != fp->tx_pkt_cons);
}
/* free skb in the packet ring at pos idx
* return idx of last bd freed
*/
static u16 bnx2x_free_tx_pkt(struct bnx2x *bp, struct bnx2x_fastpath *fp,
u16 idx)
{
struct sw_tx_bd *tx_buf = &fp->tx_buf_ring[idx];
struct eth_tx_start_bd *tx_start_bd;
struct eth_tx_bd *tx_data_bd;
struct sk_buff *skb = tx_buf->skb;
u16 bd_idx = TX_BD(tx_buf->first_bd), new_cons;
int nbd;
/* prefetch skb end pointer to speedup dev_kfree_skb() */
prefetch(&skb->end);
DP(BNX2X_MSG_OFF, "pkt_idx %d buff @(%p)->skb %p\n",
idx, tx_buf, skb);
/* unmap first bd */
DP(BNX2X_MSG_OFF, "free bd_idx %d\n", bd_idx);
tx_start_bd = &fp->tx_desc_ring[bd_idx].start_bd;
dma_unmap_single(&bp->pdev->dev, BD_UNMAP_ADDR(tx_start_bd),
BD_UNMAP_LEN(tx_start_bd), PCI_DMA_TODEVICE);
nbd = le16_to_cpu(tx_start_bd->nbd) - 1;
#ifdef BNX2X_STOP_ON_ERROR
if ((nbd - 1) > (MAX_SKB_FRAGS + 2)) {
BNX2X_ERR("BAD nbd!\n");
bnx2x_panic();
}
#endif
new_cons = nbd + tx_buf->first_bd;
/* Get the next bd */
bd_idx = TX_BD(NEXT_TX_IDX(bd_idx));
/* Skip a parse bd... */
--nbd;
bd_idx = TX_BD(NEXT_TX_IDX(bd_idx));
/* ...and the TSO split header bd since they have no mapping */
if (tx_buf->flags & BNX2X_TSO_SPLIT_BD) {
--nbd;
bd_idx = TX_BD(NEXT_TX_IDX(bd_idx));
}
/* now free frags */
while (nbd > 0) {
DP(BNX2X_MSG_OFF, "free frag bd_idx %d\n", bd_idx);
tx_data_bd = &fp->tx_desc_ring[bd_idx].reg_bd;
dma_unmap_page(&bp->pdev->dev, BD_UNMAP_ADDR(tx_data_bd),
BD_UNMAP_LEN(tx_data_bd), DMA_TO_DEVICE);
if (--nbd)
bd_idx = TX_BD(NEXT_TX_IDX(bd_idx));
}
/* release skb */
WARN_ON(!skb);
dev_kfree_skb(skb);
tx_buf->first_bd = 0;
tx_buf->skb = NULL;
return new_cons;
}
static inline u16 bnx2x_tx_avail(struct bnx2x_fastpath *fp)
{
s16 used;
u16 prod;
u16 cons;
prod = fp->tx_bd_prod;
cons = fp->tx_bd_cons;
/* NUM_TX_RINGS = number of "next-page" entries
It will be used as a threshold */
used = SUB_S16(prod, cons) + (s16)NUM_TX_RINGS;
#ifdef BNX2X_STOP_ON_ERROR
WARN_ON(used < 0);
WARN_ON(used > fp->bp->tx_ring_size);
WARN_ON((fp->bp->tx_ring_size - used) > MAX_TX_AVAIL);
#endif
return (s16)(fp->bp->tx_ring_size) - used;
}
static inline int bnx2x_has_tx_work(struct bnx2x_fastpath *fp)
{
u16 hw_cons;
/* Tell compiler that status block fields can change */
barrier();
hw_cons = le16_to_cpu(*fp->tx_cons_sb);
return hw_cons != fp->tx_pkt_cons;
}
static int bnx2x_tx_int(struct bnx2x_fastpath *fp)
{
struct bnx2x *bp = fp->bp;
struct netdev_queue *txq;
u16 hw_cons, sw_cons, bd_cons = fp->tx_bd_cons;
#ifdef BNX2X_STOP_ON_ERROR
if (unlikely(bp->panic))
return -1;
#endif
txq = netdev_get_tx_queue(bp->dev, fp->index);
hw_cons = le16_to_cpu(*fp->tx_cons_sb);
sw_cons = fp->tx_pkt_cons;
while (sw_cons != hw_cons) {
u16 pkt_cons;
pkt_cons = TX_BD(sw_cons);
/* prefetch(bp->tx_buf_ring[pkt_cons].skb); */
DP(NETIF_MSG_TX_DONE, "hw_cons %u sw_cons %u pkt_cons %u\n",
hw_cons, sw_cons, pkt_cons);
/* if (NEXT_TX_IDX(sw_cons) != hw_cons) {
rmb();
prefetch(fp->tx_buf_ring[NEXT_TX_IDX(sw_cons)].skb);
}
*/
bd_cons = bnx2x_free_tx_pkt(bp, fp, pkt_cons);
sw_cons++;
}
fp->tx_pkt_cons = sw_cons;
fp->tx_bd_cons = bd_cons;
/* Need to make the tx_bd_cons update visible to start_xmit()
* before checking for netif_tx_queue_stopped(). Without the
* memory barrier, there is a small possibility that
* start_xmit() will miss it and cause the queue to be stopped
* forever.
*/
smp_mb();
/* TBD need a thresh? */
if (unlikely(netif_tx_queue_stopped(txq))) {
/* Taking tx_lock() is needed to prevent reenabling the queue
* while it's empty. This could have happen if rx_action() gets
* suspended in bnx2x_tx_int() after the condition before
* netif_tx_wake_queue(), while tx_action (bnx2x_start_xmit()):
*
* stops the queue->sees fresh tx_bd_cons->releases the queue->
* sends some packets consuming the whole queue again->
* stops the queue
*/
__netif_tx_lock(txq, smp_processor_id());
if ((netif_tx_queue_stopped(txq)) &&
(bp->state == BNX2X_STATE_OPEN) &&
(bnx2x_tx_avail(fp) >= MAX_SKB_FRAGS + 3))
netif_tx_wake_queue(txq);
__netif_tx_unlock(txq);
}
return 0;
}
#ifdef BCM_CNIC
static void bnx2x_cnic_cfc_comp(struct bnx2x *bp, int cid);
#endif
static void bnx2x_sp_event(struct bnx2x_fastpath *fp,
union eth_rx_cqe *rr_cqe)
{
struct bnx2x *bp = fp->bp;
int cid = SW_CID(rr_cqe->ramrod_cqe.conn_and_cmd_data);
int command = CQE_CMD(rr_cqe->ramrod_cqe.conn_and_cmd_data);
DP(BNX2X_MSG_SP,
"fp %d cid %d got ramrod #%d state is %x type is %d\n",
fp->index, cid, command, bp->state,
rr_cqe->ramrod_cqe.ramrod_type);
bp->spq_left++;
if (fp->index) {
switch (command | fp->state) {
case (RAMROD_CMD_ID_ETH_CLIENT_SETUP |
BNX2X_FP_STATE_OPENING):
DP(NETIF_MSG_IFUP, "got MULTI[%d] setup ramrod\n",
cid);
fp->state = BNX2X_FP_STATE_OPEN;
break;
case (RAMROD_CMD_ID_ETH_HALT | BNX2X_FP_STATE_HALTING):
DP(NETIF_MSG_IFDOWN, "got MULTI[%d] halt ramrod\n",
cid);
fp->state = BNX2X_FP_STATE_HALTED;
break;
default:
BNX2X_ERR("unexpected MC reply (%d) "
"fp[%d] state is %x\n",
command, fp->index, fp->state);
break;
}
mb(); /* force bnx2x_wait_ramrod() to see the change */
return;
}
switch (command | bp->state) {
case (RAMROD_CMD_ID_ETH_PORT_SETUP | BNX2X_STATE_OPENING_WAIT4_PORT):
DP(NETIF_MSG_IFUP, "got setup ramrod\n");
bp->state = BNX2X_STATE_OPEN;
break;
case (RAMROD_CMD_ID_ETH_HALT | BNX2X_STATE_CLOSING_WAIT4_HALT):
DP(NETIF_MSG_IFDOWN, "got halt ramrod\n");
bp->state = BNX2X_STATE_CLOSING_WAIT4_DELETE;
fp->state = BNX2X_FP_STATE_HALTED;
break;
case (RAMROD_CMD_ID_ETH_CFC_DEL | BNX2X_STATE_CLOSING_WAIT4_HALT):
DP(NETIF_MSG_IFDOWN, "got delete ramrod for MULTI[%d]\n", cid);
bnx2x_fp(bp, cid, state) = BNX2X_FP_STATE_CLOSED;
break;
#ifdef BCM_CNIC
case (RAMROD_CMD_ID_ETH_CFC_DEL | BNX2X_STATE_OPEN):
DP(NETIF_MSG_IFDOWN, "got delete ramrod for CID %d\n", cid);
bnx2x_cnic_cfc_comp(bp, cid);
break;
#endif
case (RAMROD_CMD_ID_ETH_SET_MAC | BNX2X_STATE_OPEN):
case (RAMROD_CMD_ID_ETH_SET_MAC | BNX2X_STATE_DIAG):
DP(NETIF_MSG_IFUP, "got set mac ramrod\n");
bp->set_mac_pending--;
smp_wmb();
break;
case (RAMROD_CMD_ID_ETH_SET_MAC | BNX2X_STATE_CLOSING_WAIT4_HALT):
DP(NETIF_MSG_IFDOWN, "got (un)set mac ramrod\n");
bp->set_mac_pending--;
smp_wmb();
break;
default:
BNX2X_ERR("unexpected MC reply (%d) bp->state is %x\n",
command, bp->state);
break;
}
mb(); /* force bnx2x_wait_ramrod() to see the change */
}
static inline void bnx2x_free_rx_sge(struct bnx2x *bp,
struct bnx2x_fastpath *fp, u16 index)
{
struct sw_rx_page *sw_buf = &fp->rx_page_ring[index];
struct page *page = sw_buf->page;
struct eth_rx_sge *sge = &fp->rx_sge_ring[index];
/* Skip "next page" elements */
if (!page)
return;
dma_unmap_page(&bp->pdev->dev, dma_unmap_addr(sw_buf, mapping),
SGE_PAGE_SIZE*PAGES_PER_SGE, PCI_DMA_FROMDEVICE);
__free_pages(page, PAGES_PER_SGE_SHIFT);
sw_buf->page = NULL;
sge->addr_hi = 0;
sge->addr_lo = 0;
}
static inline void bnx2x_free_rx_sge_range(struct bnx2x *bp,
struct bnx2x_fastpath *fp, int last)
{
int i;
for (i = 0; i < last; i++)
bnx2x_free_rx_sge(bp, fp, i);
}
static inline int bnx2x_alloc_rx_sge(struct bnx2x *bp,
struct bnx2x_fastpath *fp, u16 index)
{
struct page *page = alloc_pages(GFP_ATOMIC, PAGES_PER_SGE_SHIFT);
struct sw_rx_page *sw_buf = &fp->rx_page_ring[index];
struct eth_rx_sge *sge = &fp->rx_sge_ring[index];
dma_addr_t mapping;
if (unlikely(page == NULL))
return -ENOMEM;
mapping = dma_map_page(&bp->pdev->dev, page, 0,
SGE_PAGE_SIZE*PAGES_PER_SGE, DMA_FROM_DEVICE);
if (unlikely(dma_mapping_error(&bp->pdev->dev, mapping))) {
__free_pages(page, PAGES_PER_SGE_SHIFT);
return -ENOMEM;
}
sw_buf->page = page;
dma_unmap_addr_set(sw_buf, mapping, mapping);
sge->addr_hi = cpu_to_le32(U64_HI(mapping));
sge->addr_lo = cpu_to_le32(U64_LO(mapping));
return 0;
}
static inline int bnx2x_alloc_rx_skb(struct bnx2x *bp,
struct bnx2x_fastpath *fp, u16 index)
{
struct sk_buff *skb;
struct sw_rx_bd *rx_buf = &fp->rx_buf_ring[index];
struct eth_rx_bd *rx_bd = &fp->rx_desc_ring[index];
dma_addr_t mapping;
skb = netdev_alloc_skb(bp->dev, bp->rx_buf_size);
if (unlikely(skb == NULL))
return -ENOMEM;
mapping = dma_map_single(&bp->pdev->dev, skb->data, bp->rx_buf_size,
DMA_FROM_DEVICE);
if (unlikely(dma_mapping_error(&bp->pdev->dev, mapping))) {
dev_kfree_skb(skb);
return -ENOMEM;
}
rx_buf->skb = skb;
dma_unmap_addr_set(rx_buf, mapping, mapping);
rx_bd->addr_hi = cpu_to_le32(U64_HI(mapping));
rx_bd->addr_lo = cpu_to_le32(U64_LO(mapping));
return 0;
}
/* note that we are not allocating a new skb,
* we are just moving one from cons to prod
* we are not creating a new mapping,
* so there is no need to check for dma_mapping_error().
*/
static void bnx2x_reuse_rx_skb(struct bnx2x_fastpath *fp,
struct sk_buff *skb, u16 cons, u16 prod)
{
struct bnx2x *bp = fp->bp;
struct sw_rx_bd *cons_rx_buf = &fp->rx_buf_ring[cons];
struct sw_rx_bd *prod_rx_buf = &fp->rx_buf_ring[prod];
struct eth_rx_bd *cons_bd = &fp->rx_desc_ring[cons];
struct eth_rx_bd *prod_bd = &fp->rx_desc_ring[prod];
dma_sync_single_for_device(&bp->pdev->dev,
dma_unmap_addr(cons_rx_buf, mapping),
RX_COPY_THRESH, DMA_FROM_DEVICE);
prod_rx_buf->skb = cons_rx_buf->skb;
dma_unmap_addr_set(prod_rx_buf, mapping,
dma_unmap_addr(cons_rx_buf, mapping));
*prod_bd = *cons_bd;
}
static inline void bnx2x_update_last_max_sge(struct bnx2x_fastpath *fp,
u16 idx)
{
u16 last_max = fp->last_max_sge;
if (SUB_S16(idx, last_max) > 0)
fp->last_max_sge = idx;
}
static void bnx2x_clear_sge_mask_next_elems(struct bnx2x_fastpath *fp)
{
int i, j;
for (i = 1; i <= NUM_RX_SGE_PAGES; i++) {
int idx = RX_SGE_CNT * i - 1;
for (j = 0; j < 2; j++) {
SGE_MASK_CLEAR_BIT(fp, idx);
idx--;
}
}
}
static void bnx2x_update_sge_prod(struct bnx2x_fastpath *fp,
struct eth_fast_path_rx_cqe *fp_cqe)
{
struct bnx2x *bp = fp->bp;
u16 sge_len = SGE_PAGE_ALIGN(le16_to_cpu(fp_cqe->pkt_len) -
le16_to_cpu(fp_cqe->len_on_bd)) >>
SGE_PAGE_SHIFT;
u16 last_max, last_elem, first_elem;
u16 delta = 0;
u16 i;
if (!sge_len)
return;
/* First mark all used pages */
for (i = 0; i < sge_len; i++)
SGE_MASK_CLEAR_BIT(fp, RX_SGE(le16_to_cpu(fp_cqe->sgl[i])));
DP(NETIF_MSG_RX_STATUS, "fp_cqe->sgl[%d] = %d\n",
sge_len - 1, le16_to_cpu(fp_cqe->sgl[sge_len - 1]));
/* Here we assume that the last SGE index is the biggest */
prefetch((void *)(fp->sge_mask));
bnx2x_update_last_max_sge(fp, le16_to_cpu(fp_cqe->sgl[sge_len - 1]));
last_max = RX_SGE(fp->last_max_sge);
last_elem = last_max >> RX_SGE_MASK_ELEM_SHIFT;
first_elem = RX_SGE(fp->rx_sge_prod) >> RX_SGE_MASK_ELEM_SHIFT;
/* If ring is not full */
if (last_elem + 1 != first_elem)
last_elem++;
/* Now update the prod */
for (i = first_elem; i != last_elem; i = NEXT_SGE_MASK_ELEM(i)) {
if (likely(fp->sge_mask[i]))
break;
fp->sge_mask[i] = RX_SGE_MASK_ELEM_ONE_MASK;
delta += RX_SGE_MASK_ELEM_SZ;
}
if (delta > 0) {
fp->rx_sge_prod += delta;
/* clear page-end entries */
bnx2x_clear_sge_mask_next_elems(fp);
}
DP(NETIF_MSG_RX_STATUS,
"fp->last_max_sge = %d fp->rx_sge_prod = %d\n",
fp->last_max_sge, fp->rx_sge_prod);
}
static inline void bnx2x_init_sge_ring_bit_mask(struct bnx2x_fastpath *fp)
{
/* Set the mask to all 1-s: it's faster to compare to 0 than to 0xf-s */
memset(fp->sge_mask, 0xff,
(NUM_RX_SGE >> RX_SGE_MASK_ELEM_SHIFT)*sizeof(u64));
/* Clear the two last indices in the page to 1:
these are the indices that correspond to the "next" element,
hence will never be indicated and should be removed from
the calculations. */
bnx2x_clear_sge_mask_next_elems(fp);
}
static void bnx2x_tpa_start(struct bnx2x_fastpath *fp, u16 queue,
struct sk_buff *skb, u16 cons, u16 prod)
{
struct bnx2x *bp = fp->bp;
struct sw_rx_bd *cons_rx_buf = &fp->rx_buf_ring[cons];
struct sw_rx_bd *prod_rx_buf = &fp->rx_buf_ring[prod];
struct eth_rx_bd *prod_bd = &fp->rx_desc_ring[prod];
dma_addr_t mapping;
/* move empty skb from pool to prod and map it */
prod_rx_buf->skb = fp->tpa_pool[queue].skb;
mapping = dma_map_single(&bp->pdev->dev, fp->tpa_pool[queue].skb->data,
bp->rx_buf_size, DMA_FROM_DEVICE);
dma_unmap_addr_set(prod_rx_buf, mapping, mapping);
/* move partial skb from cons to pool (don't unmap yet) */
fp->tpa_pool[queue] = *cons_rx_buf;
/* mark bin state as start - print error if current state != stop */
if (fp->tpa_state[queue] != BNX2X_TPA_STOP)
BNX2X_ERR("start of bin not in stop [%d]\n", queue);
fp->tpa_state[queue] = BNX2X_TPA_START;
/* point prod_bd to new skb */
prod_bd->addr_hi = cpu_to_le32(U64_HI(mapping));
prod_bd->addr_lo = cpu_to_le32(U64_LO(mapping));
#ifdef BNX2X_STOP_ON_ERROR
fp->tpa_queue_used |= (1 << queue);
#ifdef _ASM_GENERIC_INT_L64_H
DP(NETIF_MSG_RX_STATUS, "fp->tpa_queue_used = 0x%lx\n",
#else
DP(NETIF_MSG_RX_STATUS, "fp->tpa_queue_used = 0x%llx\n",
#endif
fp->tpa_queue_used);
#endif
}
static int bnx2x_fill_frag_skb(struct bnx2x *bp, struct bnx2x_fastpath *fp,
struct sk_buff *skb,
struct eth_fast_path_rx_cqe *fp_cqe,
u16 cqe_idx)
{
struct sw_rx_page *rx_pg, old_rx_pg;
u16 len_on_bd = le16_to_cpu(fp_cqe->len_on_bd);
u32 i, frag_len, frag_size, pages;
int err;
int j;
frag_size = le16_to_cpu(fp_cqe->pkt_len) - len_on_bd;
pages = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
/* This is needed in order to enable forwarding support */
if (frag_size)
skb_shinfo(skb)->gso_size = min((u32)SGE_PAGE_SIZE,
max(frag_size, (u32)len_on_bd));
#ifdef BNX2X_STOP_ON_ERROR
if (pages > min_t(u32, 8, MAX_SKB_FRAGS)*SGE_PAGE_SIZE*PAGES_PER_SGE) {
BNX2X_ERR("SGL length is too long: %d. CQE index is %d\n",
pages, cqe_idx);
BNX2X_ERR("fp_cqe->pkt_len = %d fp_cqe->len_on_bd = %d\n",
fp_cqe->pkt_len, len_on_bd);
bnx2x_panic();
return -EINVAL;
}
#endif
/* Run through the SGL and compose the fragmented skb */
for (i = 0, j = 0; i < pages; i += PAGES_PER_SGE, j++) {
u16 sge_idx = RX_SGE(le16_to_cpu(fp_cqe->sgl[j]));
/* FW gives the indices of the SGE as if the ring is an array
(meaning that "next" element will consume 2 indices) */
frag_len = min(frag_size, (u32)(SGE_PAGE_SIZE*PAGES_PER_SGE));
rx_pg = &fp->rx_page_ring[sge_idx];
old_rx_pg = *rx_pg;
/* If we fail to allocate a substitute page, we simply stop
where we are and drop the whole packet */
err = bnx2x_alloc_rx_sge(bp, fp, sge_idx);
if (unlikely(err)) {
fp->eth_q_stats.rx_skb_alloc_failed++;
return err;
}
/* Unmap the page as we r going to pass it to the stack */
dma_unmap_page(&bp->pdev->dev,
dma_unmap_addr(&old_rx_pg, mapping),
SGE_PAGE_SIZE*PAGES_PER_SGE, DMA_FROM_DEVICE);
/* Add one frag and update the appropriate fields in the skb */
skb_fill_page_desc(skb, j, old_rx_pg.page, 0, frag_len);
skb->data_len += frag_len;
skb->truesize += frag_len;
skb->len += frag_len;
frag_size -= frag_len;
}
return 0;
}
static void bnx2x_tpa_stop(struct bnx2x *bp, struct bnx2x_fastpath *fp,
u16 queue, int pad, int len, union eth_rx_cqe *cqe,
u16 cqe_idx)
{
struct sw_rx_bd *rx_buf = &fp->tpa_pool[queue];
struct sk_buff *skb = rx_buf->skb;
/* alloc new skb */
struct sk_buff *new_skb = netdev_alloc_skb(bp->dev, bp->rx_buf_size);
/* Unmap skb in the pool anyway, as we are going to change
pool entry status to BNX2X_TPA_STOP even if new skb allocation
fails. */
dma_unmap_single(&bp->pdev->dev, dma_unmap_addr(rx_buf, mapping),
bp->rx_buf_size, DMA_FROM_DEVICE);
if (likely(new_skb)) {
/* fix ip xsum and give it to the stack */
/* (no need to map the new skb) */
#ifdef BCM_VLAN
int is_vlan_cqe =
(le16_to_cpu(cqe->fast_path_cqe.pars_flags.flags) &
PARSING_FLAGS_VLAN);
int is_not_hwaccel_vlan_cqe =
(is_vlan_cqe && (!(bp->flags & HW_VLAN_RX_FLAG)));
#endif
prefetch(skb);
prefetch(((char *)(skb)) + 128);
#ifdef BNX2X_STOP_ON_ERROR
if (pad + len > bp->rx_buf_size) {
BNX2X_ERR("skb_put is about to fail... "
"pad %d len %d rx_buf_size %d\n",
pad, len, bp->rx_buf_size);
bnx2x_panic();
return;
}
#endif
skb_reserve(skb, pad);
skb_put(skb, len);
skb->protocol = eth_type_trans(skb, bp->dev);
skb->ip_summed = CHECKSUM_UNNECESSARY;
{
struct iphdr *iph;
iph = (struct iphdr *)skb->data;
#ifdef BCM_VLAN
/* If there is no Rx VLAN offloading -
take VLAN tag into an account */
if (unlikely(is_not_hwaccel_vlan_cqe))
iph = (struct iphdr *)((u8 *)iph + VLAN_HLEN);
#endif
iph->check = 0;
iph->check = ip_fast_csum((u8 *)iph, iph->ihl);
}
if (!bnx2x_fill_frag_skb(bp, fp, skb,
&cqe->fast_path_cqe, cqe_idx)) {
#ifdef BCM_VLAN
if ((bp->vlgrp != NULL) && is_vlan_cqe &&
(!is_not_hwaccel_vlan_cqe))
vlan_gro_receive(&fp->napi, bp->vlgrp,
le16_to_cpu(cqe->fast_path_cqe.
vlan_tag), skb);
else
#endif
napi_gro_receive(&fp->napi, skb);
} else {
DP(NETIF_MSG_RX_STATUS, "Failed to allocate new pages"
" - dropping packet!\n");
dev_kfree_skb(skb);
}
/* put new skb in bin */
fp->tpa_pool[queue].skb = new_skb;
} else {
/* else drop the packet and keep the buffer in the bin */
DP(NETIF_MSG_RX_STATUS,
"Failed to allocate new skb - dropping packet!\n");
fp->eth_q_stats.rx_skb_alloc_failed++;
}
fp->tpa_state[queue] = BNX2X_TPA_STOP;
}
static inline void bnx2x_update_rx_prod(struct bnx2x *bp,
struct bnx2x_fastpath *fp,
u16 bd_prod, u16 rx_comp_prod,
u16 rx_sge_prod)
{
struct ustorm_eth_rx_producers rx_prods = {0};
int i;
/* Update producers */
rx_prods.bd_prod = bd_prod;
rx_prods.cqe_prod = rx_comp_prod;
rx_prods.sge_prod = rx_sge_prod;
/*
* Make sure that the BD and SGE data is updated before updating the
* producers since FW might read the BD/SGE right after the producer
* is updated.
* This is only applicable for weak-ordered memory model archs such
* as IA-64. The following barrier is also mandatory since FW will
* assumes BDs must have buffers.
*/
wmb();
for (i = 0; i < sizeof(struct ustorm_eth_rx_producers)/4; i++)
REG_WR(bp, BAR_USTRORM_INTMEM +
USTORM_RX_PRODS_OFFSET(BP_PORT(bp), fp->cl_id) + i*4,
((u32 *)&rx_prods)[i]);
mmiowb(); /* keep prod updates ordered */
DP(NETIF_MSG_RX_STATUS,
"queue[%d]: wrote bd_prod %u cqe_prod %u sge_prod %u\n",
fp->index, bd_prod, rx_comp_prod, rx_sge_prod);
}
static int bnx2x_rx_int(struct bnx2x_fastpath *fp, int budget)
{
struct bnx2x *bp = fp->bp;
u16 bd_cons, bd_prod, bd_prod_fw, comp_ring_cons;
u16 hw_comp_cons, sw_comp_cons, sw_comp_prod;
int rx_pkt = 0;
#ifdef BNX2X_STOP_ON_ERROR
if (unlikely(bp->panic))
return 0;
#endif
/* CQ "next element" is of the size of the regular element,
that's why it's ok here */
hw_comp_cons = le16_to_cpu(*fp->rx_cons_sb);
if ((hw_comp_cons & MAX_RCQ_DESC_CNT) == MAX_RCQ_DESC_CNT)
hw_comp_cons++;
bd_cons = fp->rx_bd_cons;
bd_prod = fp->rx_bd_prod;
bd_prod_fw = bd_prod;
sw_comp_cons = fp->rx_comp_cons;
sw_comp_prod = fp->rx_comp_prod;
/* Memory barrier necessary as speculative reads of the rx
* buffer can be ahead of the index in the status block
*/
rmb();
DP(NETIF_MSG_RX_STATUS,
"queue[%d]: hw_comp_cons %u sw_comp_cons %u\n",
fp->index, hw_comp_cons, sw_comp_cons);
while (sw_comp_cons != hw_comp_cons) {
struct sw_rx_bd *rx_buf = NULL;
struct sk_buff *skb;
union eth_rx_cqe *cqe;
u8 cqe_fp_flags, cqe_fp_status_flags;
u16 len, pad;
comp_ring_cons = RCQ_BD(sw_comp_cons);
bd_prod = RX_BD(bd_prod);
bd_cons = RX_BD(bd_cons);
/* Prefetch the page containing the BD descriptor
at producer's index. It will be needed when new skb is
allocated */
prefetch((void *)(PAGE_ALIGN((unsigned long)
(&fp->rx_desc_ring[bd_prod])) -
PAGE_SIZE + 1));
cqe = &fp->rx_comp_ring[comp_ring_cons];
cqe_fp_flags = cqe->fast_path_cqe.type_error_flags;
cqe_fp_status_flags = cqe->fast_path_cqe.status_flags;
DP(NETIF_MSG_RX_STATUS, "CQE type %x err %x status %x"
" queue %x vlan %x len %u\n", CQE_TYPE(cqe_fp_flags),
cqe_fp_flags, cqe->fast_path_cqe.status_flags,
le32_to_cpu(cqe->fast_path_cqe.rss_hash_result),
le16_to_cpu(cqe->fast_path_cqe.vlan_tag),
le16_to_cpu(cqe->fast_path_cqe.pkt_len));
/* is this a slowpath msg? */
if (unlikely(CQE_TYPE(cqe_fp_flags))) {
bnx2x_sp_event(fp, cqe);
goto next_cqe;
/* this is an rx packet */
} else {
rx_buf = &fp->rx_buf_ring[bd_cons];
skb = rx_buf->skb;
prefetch(skb);
len = le16_to_cpu(cqe->fast_path_cqe.pkt_len);
pad = cqe->fast_path_cqe.placement_offset;
/* If CQE is marked both TPA_START and TPA_END
it is a non-TPA CQE */
if ((!fp->disable_tpa) &&
(TPA_TYPE(cqe_fp_flags) !=
(TPA_TYPE_START | TPA_TYPE_END))) {
u16 queue = cqe->fast_path_cqe.queue_index;
if (TPA_TYPE(cqe_fp_flags) == TPA_TYPE_START) {
DP(NETIF_MSG_RX_STATUS,
"calling tpa_start on queue %d\n",
queue);
bnx2x_tpa_start(fp, queue, skb,
bd_cons, bd_prod);
goto next_rx;
}
if (TPA_TYPE(cqe_fp_flags) == TPA_TYPE_END) {
DP(NETIF_MSG_RX_STATUS,
"calling tpa_stop on queue %d\n",
queue);
if (!BNX2X_RX_SUM_FIX(cqe))
BNX2X_ERR("STOP on none TCP "
"data\n");
/* This is a size of the linear data
on this skb */
len = le16_to_cpu(cqe->fast_path_cqe.
len_on_bd);
bnx2x_tpa_stop(bp, fp, queue, pad,
len, cqe, comp_ring_cons);
#ifdef BNX2X_STOP_ON_ERROR
if (bp->panic)
return 0;
#endif
bnx2x_update_sge_prod(fp,
&cqe->fast_path_cqe);
goto next_cqe;
}
}
dma_sync_single_for_device(&bp->pdev->dev,
dma_unmap_addr(rx_buf, mapping),
pad + RX_COPY_THRESH,
DMA_FROM_DEVICE);
prefetch(((char *)(skb)) + 128);
/* is this an error packet? */
if (unlikely(cqe_fp_flags & ETH_RX_ERROR_FALGS)) {
DP(NETIF_MSG_RX_ERR,
"ERROR flags %x rx packet %u\n",
cqe_fp_flags, sw_comp_cons);
fp->eth_q_stats.rx_err_discard_pkt++;
goto reuse_rx;
}
/* Since we don't have a jumbo ring
* copy small packets if mtu > 1500
*/
if ((bp->dev->mtu > ETH_MAX_PACKET_SIZE) &&
(len <= RX_COPY_THRESH)) {
struct sk_buff *new_skb;
new_skb = netdev_alloc_skb(bp->dev,
len + pad);
if (new_skb == NULL) {
DP(NETIF_MSG_RX_ERR,
"ERROR packet dropped "
"because of alloc failure\n");
fp->eth_q_stats.rx_skb_alloc_failed++;
goto reuse_rx;
}
/* aligned copy */
skb_copy_from_linear_data_offset(skb, pad,
new_skb->data + pad, len);
skb_reserve(new_skb, pad);
skb_put(new_skb, len);
bnx2x_reuse_rx_skb(fp, skb, bd_cons, bd_prod);
skb = new_skb;
} else
if (likely(bnx2x_alloc_rx_skb(bp, fp, bd_prod) == 0)) {
dma_unmap_single(&bp->pdev->dev,
dma_unmap_addr(rx_buf, mapping),
bp->rx_buf_size,
DMA_FROM_DEVICE);
skb_reserve(skb, pad);
skb_put(skb, len);
} else {
DP(NETIF_MSG_RX_ERR,
"ERROR packet dropped because "
"of alloc failure\n");
fp->eth_q_stats.rx_skb_alloc_failed++;
reuse_rx:
bnx2x_reuse_rx_skb(fp, skb, bd_cons, bd_prod);
goto next_rx;
}
skb->protocol = eth_type_trans(skb, bp->dev);
if ((bp->dev->features & NETIF_F_RXHASH) &&
(cqe_fp_status_flags &
ETH_FAST_PATH_RX_CQE_RSS_HASH_FLG))
skb->rxhash = le32_to_cpu(
cqe->fast_path_cqe.rss_hash_result);
skb->ip_summed = CHECKSUM_NONE;
if (bp->rx_csum) {
if (likely(BNX2X_RX_CSUM_OK(cqe)))
skb->ip_summed = CHECKSUM_UNNECESSARY;
else
fp->eth_q_stats.hw_csum_err++;
}
}
skb_record_rx_queue(skb, fp->index);
#ifdef BCM_VLAN
if ((bp->vlgrp != NULL) && (bp->flags & HW_VLAN_RX_FLAG) &&
(le16_to_cpu(cqe->fast_path_cqe.pars_flags.flags) &
PARSING_FLAGS_VLAN))
vlan_gro_receive(&fp->napi, bp->vlgrp,
le16_to_cpu(cqe->fast_path_cqe.vlan_tag), skb);
else
#endif
napi_gro_receive(&fp->napi, skb);
next_rx:
rx_buf->skb = NULL;
bd_cons = NEXT_RX_IDX(bd_cons);
bd_prod = NEXT_RX_IDX(bd_prod);
bd_prod_fw = NEXT_RX_IDX(bd_prod_fw);
rx_pkt++;
next_cqe:
sw_comp_prod = NEXT_RCQ_IDX(sw_comp_prod);
sw_comp_cons = NEXT_RCQ_IDX(sw_comp_cons);
if (rx_pkt == budget)
break;
} /* while */
fp->rx_bd_cons = bd_cons;
fp->rx_bd_prod = bd_prod_fw;
fp->rx_comp_cons = sw_comp_cons;
fp->rx_comp_prod = sw_comp_prod;
/* Update producers */
bnx2x_update_rx_prod(bp, fp, bd_prod_fw, sw_comp_prod,
fp->rx_sge_prod);
fp->rx_pkt += rx_pkt;
fp->rx_calls++;
return rx_pkt;
}
static irqreturn_t bnx2x_msix_fp_int(int irq, void *fp_cookie)
{
struct bnx2x_fastpath *fp = fp_cookie;
struct bnx2x *bp = fp->bp;
/* Return here if interrupt is disabled */
if (unlikely(atomic_read(&bp->intr_sem) != 0)) {
DP(NETIF_MSG_INTR, "called but intr_sem not 0, returning\n");
return IRQ_HANDLED;
}
DP(BNX2X_MSG_FP, "got an MSI-X interrupt on IDX:SB [%d:%d]\n",
fp->index, fp->sb_id);
bnx2x_ack_sb(bp, fp->sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
#ifdef BNX2X_STOP_ON_ERROR
if (unlikely(bp->panic))
return IRQ_HANDLED;
#endif
/* Handle Rx and Tx according to MSI-X vector */
prefetch(fp->rx_cons_sb);
prefetch(fp->tx_cons_sb);
prefetch(&fp->status_blk->u_status_block.status_block_index);
prefetch(&fp->status_blk->c_status_block.status_block_index);
napi_schedule(&bnx2x_fp(bp, fp->index, napi));
return IRQ_HANDLED;
}
static irqreturn_t bnx2x_interrupt(int irq, void *dev_instance)
{
struct bnx2x *bp = netdev_priv(dev_instance);
u16 status = bnx2x_ack_int(bp);
u16 mask;
int i;
/* Return here if interrupt is shared and it's not for us */
if (unlikely(status == 0)) {
DP(NETIF_MSG_INTR, "not our interrupt!\n");
return IRQ_NONE;
}
DP(NETIF_MSG_INTR, "got an interrupt status 0x%x\n", status);
/* Return here if interrupt is disabled */
if (unlikely(atomic_read(&bp->intr_sem) != 0)) {
DP(NETIF_MSG_INTR, "called but intr_sem not 0, returning\n");
return IRQ_HANDLED;
}
#ifdef BNX2X_STOP_ON_ERROR
if (unlikely(bp->panic))
return IRQ_HANDLED;
#endif
for (i = 0; i < BNX2X_NUM_QUEUES(bp); i++) {
struct bnx2x_fastpath *fp = &bp->fp[i];
mask = 0x2 << fp->sb_id;
if (status & mask) {
/* Handle Rx and Tx according to SB id */
prefetch(fp->rx_cons_sb);
prefetch(&fp->status_blk->u_status_block.
status_block_index);
prefetch(fp->tx_cons_sb);
prefetch(&fp->status_blk->c_status_block.
status_block_index);
napi_schedule(&bnx2x_fp(bp, fp->index, napi));
status &= ~mask;
}
}
#ifdef BCM_CNIC
mask = 0x2 << CNIC_SB_ID(bp);
if (status & (mask | 0x1)) {
struct cnic_ops *c_ops = NULL;
rcu_read_lock();
c_ops = rcu_dereference(bp->cnic_ops);
if (c_ops)
c_ops->cnic_handler(bp->cnic_data, NULL);
rcu_read_unlock();
status &= ~mask;
}
#endif
if (unlikely(status & 0x1)) {
queue_delayed_work(bnx2x_wq, &bp->sp_task, 0);
status &= ~0x1;
if (!status)
return IRQ_HANDLED;
}
if (unlikely(status))
DP(NETIF_MSG_INTR, "got an unknown interrupt! (status 0x%x)\n",
status);
return IRQ_HANDLED;
}
/* end of fast path */
static void bnx2x_stats_handle(struct bnx2x *bp, enum bnx2x_stats_event event);
/* Link */
/*
* General service functions
*/
static int bnx2x_acquire_hw_lock(struct bnx2x *bp, u32 resource)
{
u32 lock_status;
u32 resource_bit = (1 << resource);
int func = BP_FUNC(bp);
u32 hw_lock_control_reg;
int cnt;
/* Validating that the resource is within range */
if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
DP(NETIF_MSG_HW,
"resource(0x%x) > HW_LOCK_MAX_RESOURCE_VALUE(0x%x)\n",
resource, HW_LOCK_MAX_RESOURCE_VALUE);
return -EINVAL;
}
if (func <= 5) {
hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + func*8);
} else {
hw_lock_control_reg =
(MISC_REG_DRIVER_CONTROL_7 + (func - 6)*8);
}
/* Validating that the resource is not already taken */
lock_status = REG_RD(bp, hw_lock_control_reg);
if (lock_status & resource_bit) {
DP(NETIF_MSG_HW, "lock_status 0x%x resource_bit 0x%x\n",
lock_status, resource_bit);
return -EEXIST;
}
/* Try for 5 second every 5ms */
for (cnt = 0; cnt < 1000; cnt++) {
/* Try to acquire the lock */
REG_WR(bp, hw_lock_control_reg + 4, resource_bit);
lock_status = REG_RD(bp, hw_lock_control_reg);
if (lock_status & resource_bit)
return 0;
msleep(5);
}
DP(NETIF_MSG_HW, "Timeout\n");
return -EAGAIN;
}
static int bnx2x_release_hw_lock(struct bnx2x *bp, u32 resource)
{
u32 lock_status;
u32 resource_bit = (1 << resource);
int func = BP_FUNC(bp);
u32 hw_lock_control_reg;
DP(NETIF_MSG_HW, "Releasing a lock on resource %d\n", resource);
/* Validating that the resource is within range */
if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
DP(NETIF_MSG_HW,
"resource(0x%x) > HW_LOCK_MAX_RESOURCE_VALUE(0x%x)\n",
resource, HW_LOCK_MAX_RESOURCE_VALUE);
return -EINVAL;
}
if (func <= 5) {
hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + func*8);
} else {
hw_lock_control_reg =
(MISC_REG_DRIVER_CONTROL_7 + (func - 6)*8);
}
/* Validating that the resource is currently taken */
lock_status = REG_RD(bp, hw_lock_control_reg);
if (!(lock_status & resource_bit)) {
DP(NETIF_MSG_HW, "lock_status 0x%x resource_bit 0x%x\n",
lock_status, resource_bit);
return -EFAULT;
}
REG_WR(bp, hw_lock_control_reg, resource_bit);
return 0;
}
/* HW Lock for shared dual port PHYs */
static void bnx2x_acquire_phy_lock(struct bnx2x *bp)
{
mutex_lock(&bp->port.phy_mutex);
if (bp->port.need_hw_lock)
bnx2x_acquire_hw_lock(bp, HW_LOCK_RESOURCE_MDIO);
}
static void bnx2x_release_phy_lock(struct bnx2x *bp)
{
if (bp->port.need_hw_lock)
bnx2x_release_hw_lock(bp, HW_LOCK_RESOURCE_MDIO);
mutex_unlock(&bp->port.phy_mutex);
}
int bnx2x_get_gpio(struct bnx2x *bp, int gpio_num, u8 port)
{
/* The GPIO should be swapped if swap register is set and active */
int gpio_port = (REG_RD(bp, NIG_REG_PORT_SWAP) &&
REG_RD(bp, NIG_REG_STRAP_OVERRIDE)) ^ port;
int gpio_shift = gpio_num +
(gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0);
u32 gpio_mask = (1 << gpio_shift);
u32 gpio_reg;
int value;
if (gpio_num > MISC_REGISTERS_GPIO_3) {
BNX2X_ERR("Invalid GPIO %d\n", gpio_num);
return -EINVAL;
}
/* read GPIO value */
gpio_reg = REG_RD(bp, MISC_REG_GPIO);
/* get the requested pin value */
if ((gpio_reg & gpio_mask) == gpio_mask)
value = 1;
else
value = 0;
DP(NETIF_MSG_LINK, "pin %d value 0x%x\n", gpio_num, value);
return value;
}
int bnx2x_set_gpio(struct bnx2x *bp, int gpio_num, u32 mode, u8 port)
{
/* The GPIO should be swapped if swap register is set and active */
int gpio_port = (REG_RD(bp, NIG_REG_PORT_SWAP) &&
REG_RD(bp, NIG_REG_STRAP_OVERRIDE)) ^ port;
int gpio_shift = gpio_num +
(gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0);
u32 gpio_mask = (1 << gpio_shift);
u32 gpio_reg;
if (gpio_num > MISC_REGISTERS_GPIO_3) {
BNX2X_ERR("Invalid GPIO %d\n", gpio_num);
return -EINVAL;
}
bnx2x_acquire_hw_lock(bp, HW_LOCK_RESOURCE_GPIO);
/* read GPIO and mask except the float bits */
gpio_reg = (REG_RD(bp, MISC_REG_GPIO) & MISC_REGISTERS_GPIO_FLOAT);
switch (mode) {
case MISC_REGISTERS_GPIO_OUTPUT_LOW:
DP(NETIF_MSG_LINK, "Set GPIO %d (shift %d) -> output low\n",
gpio_num, gpio_shift);
/* clear FLOAT and set CLR */
gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
gpio_reg |= (gpio_mask << MISC_REGISTERS_GPIO_CLR_POS);
break;
case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
DP(NETIF_MSG_LINK, "Set GPIO %d (shift %d) -> output high\n",
gpio_num, gpio_shift);
/* clear FLOAT and set SET */
gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
gpio_reg |= (gpio_mask << MISC_REGISTERS_GPIO_SET_POS);
break;
case MISC_REGISTERS_GPIO_INPUT_HI_Z:
DP(NETIF_MSG_LINK, "Set GPIO %d (shift %d) -> input\n",
gpio_num, gpio_shift);
/* set FLOAT */
gpio_reg |= (gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
break;
default:
break;
}
REG_WR(bp, MISC_REG_GPIO, gpio_reg);
bnx2x_release_hw_lock(bp, HW_LOCK_RESOURCE_GPIO);
return 0;
}
int bnx2x_set_gpio_int(struct bnx2x *bp, int gpio_num, u32 mode, u8 port)
{
/* The GPIO should be swapped if swap register is set and active */
int gpio_port = (REG_RD(bp, NIG_REG_PORT_SWAP) &&
REG_RD(bp, NIG_REG_STRAP_OVERRIDE)) ^ port;
int gpio_shift = gpio_num +
(gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0);
u32 gpio_mask = (1 << gpio_shift);
u32 gpio_reg;
if (gpio_num > MISC_REGISTERS_GPIO_3) {
BNX2X_ERR("Invalid GPIO %d\n", gpio_num);
return -EINVAL;
}
bnx2x_acquire_hw_lock(bp, HW_LOCK_RESOURCE_GPIO);
/* read GPIO int */
gpio_reg = REG_RD(bp, MISC_REG_GPIO_INT);
switch (mode) {
case MISC_REGISTERS_GPIO_INT_OUTPUT_CLR:
DP(NETIF_MSG_LINK, "Clear GPIO INT %d (shift %d) -> "
"output low\n", gpio_num, gpio_shift);
/* clear SET and set CLR */
gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
gpio_reg |= (gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
break;
case MISC_REGISTERS_GPIO_INT_OUTPUT_SET:
DP(NETIF_MSG_LINK, "Set GPIO INT %d (shift %d) -> "
"output high\n", gpio_num, gpio_shift);
/* clear CLR and set SET */
gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
gpio_reg |= (gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
break;
default:
break;
}
REG_WR(bp, MISC_REG_GPIO_INT, gpio_reg);
bnx2x_release_hw_lock(bp, HW_LOCK_RESOURCE_GPIO);
return 0;
}
static int bnx2x_set_spio(struct bnx2x *bp, int spio_num, u32 mode)
{
u32 spio_mask = (1 << spio_num);
u32 spio_reg;
if ((spio_num < MISC_REGISTERS_SPIO_4) ||
(spio_num > MISC_REGISTERS_SPIO_7)) {
BNX2X_ERR("Invalid SPIO %d\n", spio_num);
return -EINVAL;
}
bnx2x_acquire_hw_lock(bp, HW_LOCK_RESOURCE_SPIO);
/* read SPIO and mask except the float bits */
spio_reg = (REG_RD(bp, MISC_REG_SPIO) & MISC_REGISTERS_SPIO_FLOAT);
switch (mode) {
case MISC_REGISTERS_SPIO_OUTPUT_LOW:
DP(NETIF_MSG_LINK, "Set SPIO %d -> output low\n", spio_num);
/* clear FLOAT and set CLR */
spio_reg &= ~(spio_mask << MISC_REGISTERS_SPIO_FLOAT_POS);
spio_reg |= (spio_mask << MISC_REGISTERS_SPIO_CLR_POS);
break;
case MISC_REGISTERS_SPIO_OUTPUT_HIGH:
DP(NETIF_MSG_LINK, "Set SPIO %d -> output high\n", spio_num);
/* clear FLOAT and set SET */
spio_reg &= ~(spio_mask << MISC_REGISTERS_SPIO_FLOAT_POS);
spio_reg |= (spio_mask << MISC_REGISTERS_SPIO_SET_POS);
break;
case MISC_REGISTERS_SPIO_INPUT_HI_Z:
DP(NETIF_MSG_LINK, "Set SPIO %d -> input\n", spio_num);
/* set FLOAT */
spio_reg |= (spio_mask << MISC_REGISTERS_SPIO_FLOAT_POS);
break;
default:
break;
}
REG_WR(bp, MISC_REG_SPIO, spio_reg);
bnx2x_release_hw_lock(bp, HW_LOCK_RESOURCE_SPIO);
return 0;
}
static void bnx2x_calc_fc_adv(struct bnx2x *bp)
{
switch (bp->link_vars.ieee_fc &
MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_MASK) {
case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_NONE:
bp->port.advertising &= ~(ADVERTISED_Asym_Pause |
ADVERTISED_Pause);
break;
case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_BOTH:
bp->port.advertising |= (ADVERTISED_Asym_Pause |
ADVERTISED_Pause);
break;
case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_ASYMMETRIC:
bp->port.advertising |= ADVERTISED_Asym_Pause;
break;
default:
bp->port.advertising &= ~(ADVERTISED_Asym_Pause |
ADVERTISED_Pause);
break;
}
}
static void bnx2x_link_report(struct bnx2x *bp)
{
if (bp->flags & MF_FUNC_DIS) {
netif_carrier_off(bp->dev);
netdev_err(bp->dev, "NIC Link is Down\n");
return;
}
if (bp->link_vars.link_up) {
u16 line_speed;
if (bp->state == BNX2X_STATE_OPEN)
netif_carrier_on(bp->dev);
netdev_info(bp->dev, "NIC Link is Up, ");
line_speed = bp->link_vars.line_speed;
if (IS_E1HMF(bp)) {
u16 vn_max_rate;
vn_max_rate =
((bp->mf_config & FUNC_MF_CFG_MAX_BW_MASK) >>
FUNC_MF_CFG_MAX_BW_SHIFT) * 100;
if (vn_max_rate < line_speed)
line_speed = vn_max_rate;
}
pr_cont("%d Mbps ", line_speed);
if (bp->link_vars.duplex == DUPLEX_FULL)
pr_cont("full duplex");
else
pr_cont("half duplex");
if (bp->link_vars.flow_ctrl != BNX2X_FLOW_CTRL_NONE) {
if (bp->link_vars.flow_ctrl & BNX2X_FLOW_CTRL_RX) {
pr_cont(", receive ");
if (bp->link_vars.flow_ctrl &
BNX2X_FLOW_CTRL_TX)
pr_cont("& transmit ");
} else {
pr_cont(", transmit ");
}
pr_cont("flow control ON");
}
pr_cont("\n");
} else { /* link_down */
netif_carrier_off(bp->dev);
netdev_err(bp->dev, "NIC Link is Down\n");
}
}
static u8 bnx2x_initial_phy_init(struct bnx2x *bp, int load_mode)
{
if (!BP_NOMCP(bp)) {
u8 rc;
/* Initialize link parameters structure variables */
/* It is recommended to turn off RX FC for jumbo frames
for better performance */
if (bp->dev->mtu > 5000)
bp->link_params.req_fc_auto_adv = BNX2X_FLOW_CTRL_TX;
else
bp->link_params.req_fc_auto_adv = BNX2X_FLOW_CTRL_BOTH;
bnx2x_acquire_phy_lock(bp);
if (load_mode == LOAD_DIAG)
bp->link_params.loopback_mode = LOOPBACK_XGXS_10;
rc = bnx2x_phy_init(&bp->link_params, &bp->link_vars);
bnx2x_release_phy_lock(bp);
bnx2x_calc_fc_adv(bp);
if (CHIP_REV_IS_SLOW(bp) && bp->link_vars.link_up) {
bnx2x_stats_handle(bp, STATS_EVENT_LINK_UP);
bnx2x_link_report(bp);
}
return rc;
}
BNX2X_ERR("Bootcode is missing - can not initialize link\n");
return -EINVAL;
}
static void bnx2x_link_set(struct bnx2x *bp)
{
if (!BP_NOMCP(bp)) {
bnx2x_acquire_phy_lock(bp);
bnx2x_phy_init(&bp->link_params, &bp->link_vars);
bnx2x_release_phy_lock(bp);
bnx2x_calc_fc_adv(bp);
} else
BNX2X_ERR("Bootcode is missing - can not set link\n");
}
static void bnx2x__link_reset(struct bnx2x *bp)
{
if (!BP_NOMCP(bp)) {
bnx2x_acquire_phy_lock(bp);
bnx2x_link_reset(&bp->link_params, &bp->link_vars, 1);
bnx2x_release_phy_lock(bp);
} else
BNX2X_ERR("Bootcode is missing - can not reset link\n");
}
static u8 bnx2x_link_test(struct bnx2x *bp)
{
u8 rc = 0;
if (!BP_NOMCP(bp)) {
bnx2x_acquire_phy_lock(bp);
rc = bnx2x_test_link(&bp->link_params, &bp->link_vars);
bnx2x_release_phy_lock(bp);
} else
BNX2X_ERR("Bootcode is missing - can not test link\n");
return rc;
}
static void bnx2x_init_port_minmax(struct bnx2x *bp)
{
u32 r_param = bp->link_vars.line_speed / 8;
u32 fair_periodic_timeout_usec;
u32 t_fair;
memset(&(bp->cmng.rs_vars), 0,
sizeof(struct rate_shaping_vars_per_port));
memset(&(bp->cmng.fair_vars), 0, sizeof(struct fairness_vars_per_port));
/* 100 usec in SDM ticks = 25 since each tick is 4 usec */
bp->cmng.rs_vars.rs_periodic_timeout = RS_PERIODIC_TIMEOUT_USEC / 4;
/* this is the threshold below which no timer arming will occur
1.25 coefficient is for the threshold to be a little bigger
than the real time, to compensate for timer in-accuracy */
bp->cmng.rs_vars.rs_threshold =
(RS_PERIODIC_TIMEOUT_USEC * r_param * 5) / 4;
/* resolution of fairness timer */
fair_periodic_timeout_usec = QM_ARB_BYTES / r_param;
/* for 10G it is 1000usec. for 1G it is 10000usec. */
t_fair = T_FAIR_COEF / bp->link_vars.line_speed;
/* this is the threshold below which we won't arm the timer anymore */
bp->cmng.fair_vars.fair_threshold = QM_ARB_BYTES;
/* we multiply by 1e3/8 to get bytes/msec.
We don't want the credits to pass a credit
of the t_fair*FAIR_MEM (algorithm resolution) */
bp->cmng.fair_vars.upper_bound = r_param * t_fair * FAIR_MEM;
/* since each tick is 4 usec */
bp->cmng.fair_vars.fairness_timeout = fair_periodic_timeout_usec / 4;
}
/* Calculates the sum of vn_min_rates.
It's needed for further normalizing of the min_rates.
Returns:
sum of vn_min_rates.
or
0 - if all the min_rates are 0.
In the later case fainess algorithm should be deactivated.
If not all min_rates are zero then those that are zeroes will be set to 1.
*/
static void bnx2x_calc_vn_weight_sum(struct bnx2x *bp)
{
int all_zero = 1;
int port = BP_PORT(bp);
int vn;
bp->vn_weight_sum = 0;
for (vn = VN_0; vn < E1HVN_MAX; vn++) {
int func = 2*vn + port;
u32 vn_cfg = SHMEM_RD(bp, mf_cfg.func_mf_config[func].config);
u32 vn_min_rate = ((vn_cfg & FUNC_MF_CFG_MIN_BW_MASK) >>
FUNC_MF_CFG_MIN_BW_SHIFT) * 100;
/* Skip hidden vns */
if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE)
continue;
/* If min rate is zero - set it to 1 */
if (!vn_min_rate)
vn_min_rate = DEF_MIN_RATE;
else
all_zero = 0;
bp->vn_weight_sum += vn_min_rate;
}
/* ... only if all min rates are zeros - disable fairness */
if (all_zero) {
bp->cmng.flags.cmng_enables &=
~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
DP(NETIF_MSG_IFUP, "All MIN values are zeroes"
" fairness will be disabled\n");
} else
bp->cmng.flags.cmng_enables |=
CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
}
static void bnx2x_init_vn_minmax(struct bnx2x *bp, int func)
{
struct rate_shaping_vars_per_vn m_rs_vn;
struct fairness_vars_per_vn m_fair_vn;
u32 vn_cfg = SHMEM_RD(bp, mf_cfg.func_mf_config[func].config);
u16 vn_min_rate, vn_max_rate;
int i;
/* If function is hidden - set min and max to zeroes */
if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
vn_min_rate = 0;
vn_max_rate = 0;
} else {
vn_min_rate = ((vn_cfg & FUNC_MF_CFG_MIN_BW_MASK) >>
FUNC_MF_CFG_MIN_BW_SHIFT) * 100;
/* If min rate is zero - set it to 1 */
if (!vn_min_rate)
vn_min_rate = DEF_MIN_RATE;
vn_max_rate = ((vn_cfg & FUNC_MF_CFG_MAX_BW_MASK) >>
FUNC_MF_CFG_MAX_BW_SHIFT) * 100;
}
DP(NETIF_MSG_IFUP,
"func %d: vn_min_rate %d vn_max_rate %d vn_weight_sum %d\n",
func, vn_min_rate, vn_max_rate, bp->vn_weight_sum);
memset(&m_rs_vn, 0, sizeof(struct rate_shaping_vars_per_vn));
memset(&m_fair_vn, 0, sizeof(struct fairness_vars_per_vn));
/* global vn counter - maximal Mbps for this vn */
m_rs_vn.vn_counter.rate = vn_max_rate;
/* quota - number of bytes transmitted in this period */
m_rs_vn.vn_counter.quota =
(vn_max_rate * RS_PERIODIC_TIMEOUT_USEC) / 8;
if (bp->vn_weight_sum) {
/* credit for each period of the fairness algorithm:
number of bytes in T_FAIR (the vn share the port rate).
vn_weight_sum should not be larger than 10000, thus
T_FAIR_COEF / (8 * vn_weight_sum) will always be greater
than zero */
m_fair_vn.vn_credit_delta =
max_t(u32, (vn_min_rate * (T_FAIR_COEF /
(8 * bp->vn_weight_sum))),
(bp->cmng.fair_vars.fair_threshold * 2));
DP(NETIF_MSG_IFUP, "m_fair_vn.vn_credit_delta %d\n",
m_fair_vn.vn_credit_delta);
}
/* Store it to internal memory */
for (i = 0; i < sizeof(struct rate_shaping_vars_per_vn)/4; i++)
REG_WR(bp, BAR_XSTRORM_INTMEM +
XSTORM_RATE_SHAPING_PER_VN_VARS_OFFSET(func) + i * 4,
((u32 *)(&m_rs_vn))[i]);
for (i = 0; i < sizeof(struct fairness_vars_per_vn)/4; i++)
REG_WR(bp, BAR_XSTRORM_INTMEM +
XSTORM_FAIRNESS_PER_VN_VARS_OFFSET(func) + i * 4,
((u32 *)(&m_fair_vn))[i]);
}
/* This function is called upon link interrupt */
static void bnx2x_link_attn(struct bnx2x *bp)
{
u32 prev_link_status = bp->link_vars.link_status;
/* Make sure that we are synced with the current statistics */
bnx2x_stats_handle(bp, STATS_EVENT_STOP);
bnx2x_link_update(&bp->link_params, &bp->link_vars);
if (bp->link_vars.link_up) {
/* dropless flow control */
if (CHIP_IS_E1H(bp) && bp->dropless_fc) {
int port = BP_PORT(bp);
u32 pause_enabled = 0;
if (bp->link_vars.flow_ctrl & BNX2X_FLOW_CTRL_TX)
pause_enabled = 1;
REG_WR(bp, BAR_USTRORM_INTMEM +
USTORM_ETH_PAUSE_ENABLED_OFFSET(port),
pause_enabled);
}
if (bp->link_vars.mac_type == MAC_TYPE_BMAC) {
struct host_port_stats *pstats;
pstats = bnx2x_sp(bp, port_stats);
/* reset old bmac stats */
memset(&(pstats->mac_stx[0]), 0,
sizeof(struct mac_stx));
}
if (bp->state == BNX2X_STATE_OPEN)
bnx2x_stats_handle(bp, STATS_EVENT_LINK_UP);
}
/* indicate link status only if link status actually changed */
if (prev_link_status != bp->link_vars.link_status)
bnx2x_link_report(bp);
if (IS_E1HMF(bp)) {
int port = BP_PORT(bp);
int func;
int vn;
/* Set the attention towards other drivers on the same port */
for (vn = VN_0; vn < E1HVN_MAX; vn++) {
if (vn == BP_E1HVN(bp))
continue;
func = ((vn << 1) | port);
REG_WR(bp, MISC_REG_AEU_GENERAL_ATTN_0 +
(LINK_SYNC_ATTENTION_BIT_FUNC_0 + func)*4, 1);
}
if (bp->link_vars.link_up) {
int i;
/* Init rate shaping and fairness contexts */
bnx2x_init_port_minmax(bp);
for (vn = VN_0; vn < E1HVN_MAX; vn++)
bnx2x_init_vn_minmax(bp, 2*vn + port);
/* Store it to internal memory */
for (i = 0;
i < sizeof(struct cmng_struct_per_port) / 4; i++)
REG_WR(bp, BAR_XSTRORM_INTMEM +
XSTORM_CMNG_PER_PORT_VARS_OFFSET(port) + i*4,
((u32 *)(&bp->cmng))[i]);
}
}
}
static void bnx2x__link_status_update(struct bnx2x *bp)
{
if ((bp->state != BNX2X_STATE_OPEN) || (bp->flags & MF_FUNC_DIS))
return;
bnx2x_link_status_update(&bp->link_params, &bp->link_vars);
if (bp->link_vars.link_up)
bnx2x_stats_handle(bp, STATS_EVENT_LINK_UP);
else
bnx2x_stats_handle(bp, STATS_EVENT_STOP);
bnx2x_calc_vn_weight_sum(bp);
/* indicate link status */
bnx2x_link_report(bp);
}
static void bnx2x_pmf_update(struct bnx2x *bp)
{
int port = BP_PORT(bp);
u32 val;
bp->port.pmf = 1;
DP(NETIF_MSG_LINK, "pmf %d\n", bp->port.pmf);
/* enable nig attention */
val = (0xff0f | (1 << (BP_E1HVN(bp) + 4)));
REG_WR(bp, HC_REG_TRAILING_EDGE_0 + port*8, val);
REG_WR(bp, HC_REG_LEADING_EDGE_0 + port*8, val);
bnx2x_stats_handle(bp, STATS_EVENT_PMF);
}
/* end of Link */
/* slow path */
/*
* General service functions
*/
/* send the MCP a request, block until there is a reply */
u32 bnx2x_fw_command(struct bnx2x *bp, u32 command)
{
int func = BP_FUNC(bp);
u32 seq = ++bp->fw_seq;
u32 rc = 0;
u32 cnt = 1;
u8 delay = CHIP_REV_IS_SLOW(bp) ? 100 : 10;
mutex_lock(&bp->fw_mb_mutex);
SHMEM_WR(bp, func_mb[func].drv_mb_header, (command | seq));
DP(BNX2X_MSG_MCP, "wrote command (%x) to FW MB\n", (command | seq));
do {
/* let the FW do it's magic ... */
msleep(delay);
rc = SHMEM_RD(bp, func_mb[func].fw_mb_header);
/* Give the FW up to 5 second (500*10ms) */
} while ((seq != (rc & FW_MSG_SEQ_NUMBER_MASK)) && (cnt++ < 500));
DP(BNX2X_MSG_MCP, "[after %d ms] read (%x) seq is (%x) from FW MB\n",
cnt*delay, rc, seq);
/* is this a reply to our command? */
if (seq == (rc & FW_MSG_SEQ_NUMBER_MASK))
rc &= FW_MSG_CODE_MASK;
else {
/* FW BUG! */
BNX2X_ERR("FW failed to respond!\n");
bnx2x_fw_dump(bp);
rc = 0;
}
mutex_unlock(&bp->fw_mb_mutex);
return rc;
}
static void bnx2x_set_eth_mac_addr_e1h(struct bnx2x *bp, int set);
static void bnx2x_set_rx_mode(struct net_device *dev);
static void bnx2x_e1h_disable(struct bnx2x *bp)
{
int port = BP_PORT(bp);
netif_tx_disable(bp->dev);
REG_WR(bp, NIG_REG_LLH0_FUNC_EN + port*8, 0);
netif_carrier_off(bp->dev);
}
static void bnx2x_e1h_enable(struct bnx2x *bp)
{
int port = BP_PORT(bp);
REG_WR(bp, NIG_REG_LLH0_FUNC_EN + port*8, 1);
/* Tx queue should be only reenabled */
netif_tx_wake_all_queues(bp->dev);
/*
* Should not call netif_carrier_on since it will be called if the link
* is up when checking for link state
*/
}
static void bnx2x_update_min_max(struct bnx2x *bp)
{
int port = BP_PORT(bp);
int vn, i;
/* Init rate shaping and fairness contexts */
bnx2x_init_port_minmax(bp);
bnx2x_calc_vn_weight_sum(bp);
for (vn = VN_0; vn < E1HVN_MAX; vn++)
bnx2x_init_vn_minmax(bp, 2*vn + port);
if (bp->port.pmf) {
int func;
/* Set the attention towards other drivers on the same port */
for (vn = VN_0; vn < E1HVN_MAX; vn++) {
if (vn == BP_E1HVN(bp))
continue;
func = ((vn << 1) | port);
REG_WR(bp, MISC_REG_AEU_GENERAL_ATTN_0 +
(LINK_SYNC_ATTENTION_BIT_FUNC_0 + func)*4, 1);
}
/* Store it to internal memory */
for (i = 0; i < sizeof(struct cmng_struct_per_port) / 4; i++)
REG_WR(bp, BAR_XSTRORM_INTMEM +
XSTORM_CMNG_PER_PORT_VARS_OFFSET(port) + i*4,
((u32 *)(&bp->cmng))[i]);
}
}
static void bnx2x_dcc_event(struct bnx2x *bp, u32 dcc_event)
{
DP(BNX2X_MSG_MCP, "dcc_event 0x%x\n", dcc_event);
if (dcc_event & DRV_STATUS_DCC_DISABLE_ENABLE_PF) {
/*
* This is the only place besides the function initialization
* where the bp->flags can change so it is done without any
* locks
*/
if (bp->mf_config & FUNC_MF_CFG_FUNC_DISABLED) {
DP(NETIF_MSG_IFDOWN, "mf_cfg function disabled\n");
bp->flags |= MF_FUNC_DIS;
bnx2x_e1h_disable(bp);
} else {
DP(NETIF_MSG_IFUP, "mf_cfg function enabled\n");
bp->flags &= ~MF_FUNC_DIS;
bnx2x_e1h_enable(bp);
}
dcc_event &= ~DRV_STATUS_DCC_DISABLE_ENABLE_PF;
}
if (dcc_event & DRV_STATUS_DCC_BANDWIDTH_ALLOCATION) {
bnx2x_update_min_max(bp);
dcc_event &= ~DRV_STATUS_DCC_BANDWIDTH_ALLOCATION;
}
/* Report results to MCP */
if (dcc_event)
bnx2x_fw_command(bp, DRV_MSG_CODE_DCC_FAILURE);
else
bnx2x_fw_command(bp, DRV_MSG_CODE_DCC_OK);
}
/* must be called under the spq lock */
static inline struct eth_spe *bnx2x_sp_get_next(struct bnx2x *bp)
{
struct eth_spe *next_spe = bp->spq_prod_bd;
if (bp->spq_prod_bd == bp->spq_last_bd) {
bp->spq_prod_bd = bp->spq;
bp->spq_prod_idx = 0;
DP(NETIF_MSG_TIMER, "end of spq\n");
} else {
bp->spq_prod_bd++;
bp->spq_prod_idx++;
}
return next_spe;
}
/* must be called under the spq lock */
static inline void bnx2x_sp_prod_update(struct bnx2x *bp)
{
int func = BP_FUNC(bp);
/* Make sure that BD data is updated before writing the producer */
wmb();
REG_WR(bp, BAR_XSTRORM_INTMEM + XSTORM_SPQ_PROD_OFFSET(func),
bp->spq_prod_idx);
mmiowb();
}
/* the slow path queue is odd since completions arrive on the fastpath ring */
static int bnx2x_sp_post(struct bnx2x *bp, int command, int cid,
u32 data_hi, u32 data_lo, int common)
{
struct eth_spe *spe;
#ifdef BNX2X_STOP_ON_ERROR
if (unlikely(bp->panic))
return -EIO;
#endif
spin_lock_bh(&bp->spq_lock);
if (!bp->spq_left) {
BNX2X_ERR("BUG! SPQ ring full!\n");
spin_unlock_bh(&bp->spq_lock);
bnx2x_panic();
return -EBUSY;
}
spe = bnx2x_sp_get_next(bp);
/* CID needs port number to be encoded int it */
spe->hdr.conn_and_cmd_data =
cpu_to_le32((command << SPE_HDR_CMD_ID_SHIFT) |
HW_CID(bp, cid));
spe->hdr.type = cpu_to_le16(ETH_CONNECTION_TYPE);
if (common)
spe->hdr.type |=
cpu_to_le16((1 << SPE_HDR_COMMON_RAMROD_SHIFT));
spe->data.mac_config_addr.hi = cpu_to_le32(data_hi);
spe->data.mac_config_addr.lo = cpu_to_le32(data_lo);
bp->spq_left--;
DP(BNX2X_MSG_SP/*NETIF_MSG_TIMER*/,
"SPQE[%x] (%x:%x) command %d hw_cid %x data (%x:%x) left %x\n",
bp->spq_prod_idx, (u32)U64_HI(bp->spq_mapping),
(u32)(U64_LO(bp->spq_mapping) +
(void *)bp->spq_prod_bd - (void *)bp->spq), command,
HW_CID(bp, cid), data_hi, data_lo, bp->spq_left);
bnx2x_sp_prod_update(bp);
spin_unlock_bh(&bp->spq_lock);
return 0;
}
/* acquire split MCP access lock register */
static int bnx2x_acquire_alr(struct bnx2x *bp)
{
u32 j, val;
int rc = 0;
might_sleep();
for (j = 0; j < 1000; j++) {
val = (1UL << 31);
REG_WR(bp, GRCBASE_MCP + 0x9c, val);
val = REG_RD(bp, GRCBASE_MCP + 0x9c);
if (val & (1L << 31))
break;
msleep(5);
}
if (!(val & (1L << 31))) {
BNX2X_ERR("Cannot acquire MCP access lock register\n");
rc = -EBUSY;
}
return rc;
}
/* release split MCP access lock register */
static void bnx2x_release_alr(struct bnx2x *bp)
{
REG_WR(bp, GRCBASE_MCP + 0x9c, 0);
}
static inline u16 bnx2x_update_dsb_idx(struct bnx2x *bp)
{
struct host_def_status_block *def_sb = bp->def_status_blk;
u16 rc = 0;
barrier(); /* status block is written to by the chip */
if (bp->def_att_idx != def_sb->atten_status_block.attn_bits_index) {
bp->def_att_idx = def_sb->atten_status_block.attn_bits_index;
rc |= 1;
}
if (bp->def_c_idx != def_sb->c_def_status_block.status_block_index) {
bp->def_c_idx = def_sb->c_def_status_block.status_block_index;
rc |= 2;
}
if (bp->def_u_idx != def_sb->u_def_status_block.status_block_index) {
bp->def_u_idx = def_sb->u_def_status_block.status_block_index;
rc |= 4;
}
if (bp->def_x_idx != def_sb->x_def_status_block.status_block_index) {
bp->def_x_idx = def_sb->x_def_status_block.status_block_index;
rc |= 8;
}
if (bp->def_t_idx != def_sb->t_def_status_block.status_block_index) {
bp->def_t_idx = def_sb->t_def_status_block.status_block_index;
rc |= 16;
}
return rc;
}
/*
* slow path service functions
*/
static void bnx2x_attn_int_asserted(struct bnx2x *bp, u32 asserted)
{
int port = BP_PORT(bp);
u32 hc_addr = (HC_REG_COMMAND_REG + port*32 +
COMMAND_REG_ATTN_BITS_SET);
u32 aeu_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
MISC_REG_AEU_MASK_ATTN_FUNC_0;
u32 nig_int_mask_addr = port ? NIG_REG_MASK_INTERRUPT_PORT1 :
NIG_REG_MASK_INTERRUPT_PORT0;
u32 aeu_mask;
u32 nig_mask = 0;
if (bp->attn_state & asserted)
BNX2X_ERR("IGU ERROR\n");
bnx2x_acquire_hw_lock(bp, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
aeu_mask = REG_RD(bp, aeu_addr);
DP(NETIF_MSG_HW, "aeu_mask %x newly asserted %x\n",
aeu_mask, asserted);
aeu_mask &= ~(asserted & 0x3ff);
DP(NETIF_MSG_HW, "new mask %x\n", aeu_mask);
REG_WR(bp, aeu_addr, aeu_mask);
bnx2x_release_hw_lock(bp, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
DP(NETIF_MSG_HW, "attn_state %x\n", bp->attn_state);
bp->attn_state |= asserted;
DP(NETIF_MSG_HW, "new state %x\n", bp->attn_state);
if (asserted & ATTN_HARD_WIRED_MASK) {
if (asserted & ATTN_NIG_FOR_FUNC) {
bnx2x_acquire_phy_lock(bp);
/* save nig interrupt mask */
nig_mask = REG_RD(bp, nig_int_mask_addr);
REG_WR(bp, nig_int_mask_addr, 0);
bnx2x_link_attn(bp);
/* handle unicore attn? */
}
if (asserted & ATTN_SW_TIMER_4_FUNC)
DP(NETIF_MSG_HW, "ATTN_SW_TIMER_4_FUNC!\n");
if (asserted & GPIO_2_FUNC)
DP(NETIF_MSG_HW, "GPIO_2_FUNC!\n");
if (asserted & GPIO_3_FUNC)
DP(NETIF_MSG_HW, "GPIO_3_FUNC!\n");
if (asserted & GPIO_4_FUNC)
DP(NETIF_MSG_HW, "GPIO_4_FUNC!\n");
if (port == 0) {
if (asserted & ATTN_GENERAL_ATTN_1) {
DP(NETIF_MSG_HW, "ATTN_GENERAL_ATTN_1!\n");
REG_WR(bp, MISC_REG_AEU_GENERAL_ATTN_1, 0x0);
}
if (asserted & ATTN_GENERAL_ATTN_2) {
DP(NETIF_MSG_HW, "ATTN_GENERAL_ATTN_2!\n");
REG_WR(bp, MISC_REG_AEU_GENERAL_ATTN_2, 0x0);
}
if (asserted & ATTN_GENERAL_ATTN_3) {
DP(NETIF_MSG_HW, "ATTN_GENERAL_ATTN_3!\n");
REG_WR(bp, MISC_REG_AEU_GENERAL_ATTN_3, 0x0);
}
} else {
if (asserted & ATTN_GENERAL_ATTN_4) {
DP(NETIF_MSG_HW, "ATTN_GENERAL_ATTN_4!\n");
REG_WR(bp, MISC_REG_AEU_GENERAL_ATTN_4, 0x0);
}
if (asserted & ATTN_GENERAL_ATTN_5) {
DP(NETIF_MSG_HW, "ATTN_GENERAL_ATTN_5!\n");
REG_WR(bp, MISC_REG_AEU_GENERAL_ATTN_5, 0x0);
}
if (asserted & ATTN_GENERAL_ATTN_6) {
DP(NETIF_MSG_HW, "ATTN_GENERAL_ATTN_6!\n");
REG_WR(bp, MISC_REG_AEU_GENERAL_ATTN_6, 0x0);
}
}
} /* if hardwired */
DP(NETIF_MSG_HW, "about to mask 0x%08x at HC addr 0x%x\n",
asserted, hc_addr);
REG_WR(bp, hc_addr, asserted);
/* now set back the mask */
if (asserted & ATTN_NIG_FOR_FUNC) {
REG_WR(bp, nig_int_mask_addr, nig_mask);
bnx2x_release_phy_lock(bp);
}
}
static inline void bnx2x_fan_failure(struct bnx2x *bp)
{
int port = BP_PORT(bp);
/* mark the failure */
bp->link_params.ext_phy_config &= ~PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK;
bp->link_params.ext_phy_config |= PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE;
SHMEM_WR(bp, dev_info.port_hw_config[port].external_phy_config,
bp->link_params.ext_phy_config);
/* log the failure */
netdev_err(bp->dev, "Fan Failure on Network Controller has caused"
" the driver to shutdown the card to prevent permanent"
" damage. Please contact OEM Support for assistance\n");
}
static inline void bnx2x_attn_int_deasserted0(struct bnx2x *bp, u32 attn)
{
int port = BP_PORT(bp);
int reg_offset;
u32 val, swap_val, swap_override;
reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0);
if (attn & AEU_INPUTS_ATTN_BITS_SPIO5) {
val = REG_RD(bp, reg_offset);
val &= ~AEU_INPUTS_ATTN_BITS_SPIO5;
REG_WR(bp, reg_offset, val);
BNX2X_ERR("SPIO5 hw attention\n");
/* Fan failure attention */
switch (XGXS_EXT_PHY_TYPE(bp->link_params.ext_phy_config)) {
case PORT_HW_CFG_XGXS_EXT_PHY_TYPE_SFX7101:
/* Low power mode is controlled by GPIO 2 */
bnx2x_set_gpio(bp, MISC_REGISTERS_GPIO_2,
MISC_REGISTERS_GPIO_OUTPUT_LOW, port);
/* The PHY reset is controlled by GPIO 1 */
bnx2x_set_gpio(bp, MISC_REGISTERS_GPIO_1,
MISC_REGISTERS_GPIO_OUTPUT_LOW, port);
break;
case PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM8727:
/* The PHY reset is controlled by GPIO 1 */
/* fake the port number to cancel the swap done in
set_gpio() */
swap_val = REG_RD(bp, NIG_REG_PORT_SWAP);
swap_override = REG_RD(bp, NIG_REG_STRAP_OVERRIDE);
port = (swap_val && swap_override) ^ 1;
bnx2x_set_gpio(bp, MISC_REGISTERS_GPIO_1,
MISC_REGISTERS_GPIO_OUTPUT_LOW, port);
break;
default:
break;
}
bnx2x_fan_failure(bp);
}
if (attn & (AEU_INPUTS_ATTN_BITS_GPIO3_FUNCTION_0 |
AEU_INPUTS_ATTN_BITS_GPIO3_FUNCTION_1)) {
bnx2x_acquire_phy_lock(bp);
bnx2x_handle_module_detect_int(&bp->link_params);
bnx2x_release_phy_lock(bp);
}
if (attn & HW_INTERRUT_ASSERT_SET_0) {
val = REG_RD(bp, reg_offset);
val &= ~(attn & HW_INTERRUT_ASSERT_SET_0);
REG_WR(bp, reg_offset, val);
BNX2X_ERR("FATAL HW block attention set0 0x%x\n",
(u32)(attn & HW_INTERRUT_ASSERT_SET_0));
bnx2x_panic();
}
}
static inline void bnx2x_attn_int_deasserted1(struct bnx2x *bp, u32 attn)
{
u32 val;
if (attn & AEU_INPUTS_ATTN_BITS_DOORBELLQ_HW_INTERRUPT) {
val = REG_RD(bp, DORQ_REG_DORQ_INT_STS_CLR);
BNX2X_ERR("DB hw attention 0x%x\n", val);
/* DORQ discard attention */
if (val & 0x2)
BNX2X_ERR("FATAL error from DORQ\n");
}
if (attn & HW_INTERRUT_ASSERT_SET_1) {
int port = BP_PORT(bp);
int reg_offset;
reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_1 :
MISC_REG_AEU_ENABLE1_FUNC_0_OUT_1);
val = REG_RD(bp, reg_offset);
val &= ~(attn & HW_INTERRUT_ASSERT_SET_1);
REG_WR(bp, reg_offset, val);
BNX2X_ERR("FATAL HW block attention set1 0x%x\n",
(u32)(attn & HW_INTERRUT_ASSERT_SET_1));
bnx2x_panic();
}
}
static inline void bnx2x_attn_int_deasserted2(struct bnx2x *bp, u32 attn)
{
u32 val;
if (attn & AEU_INPUTS_ATTN_BITS_CFC_HW_INTERRUPT) {
val = REG_RD(bp, CFC_REG_CFC_INT_STS_CLR);
BNX2X_ERR("CFC hw attention 0x%x\n", val);
/* CFC error attention */
if (val & 0x2)
BNX2X_ERR("FATAL error from CFC\n");
}
if (attn & AEU_INPUTS_ATTN_BITS_PXP_HW_INTERRUPT) {
val = REG_RD(bp, PXP_REG_PXP_INT_STS_CLR_0);
BNX2X_ERR("PXP hw attention 0x%x\n", val);
/* RQ_USDMDP_FIFO_OVERFLOW */
if (val & 0x18000)
BNX2X_ERR("FATAL error from PXP\n");
}
if (attn & HW_INTERRUT_ASSERT_SET_2) {
int port = BP_PORT(bp);
int reg_offset;
reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_2 :
MISC_REG_AEU_ENABLE1_FUNC_0_OUT_2);
val = REG_RD(bp, reg_offset);
val &= ~(attn & HW_INTERRUT_ASSERT_SET_2);
REG_WR(bp, reg_offset, val);
BNX2X_ERR("FATAL HW block attention set2 0x%x\n",
(u32)(attn & HW_INTERRUT_ASSERT_SET_2));
bnx2x_panic();
}
}
static inline void bnx2x_attn_int_deasserted3(struct bnx2x *bp, u32 attn)
{
u32 val;
if (attn & EVEREST_GEN_ATTN_IN_USE_MASK) {
if (attn & BNX2X_PMF_LINK_ASSERT) {
int func = BP_FUNC(bp);
REG_WR(bp, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
bp->mf_config = SHMEM_RD(bp,
mf_cfg.func_mf_config[func].config);
val = SHMEM_RD(bp, func_mb[func].drv_status);
if (val & DRV_STATUS_DCC_EVENT_MASK)
bnx2x_dcc_event(bp,
(val & DRV_STATUS_DCC_EVENT_MASK));
bnx2x__link_status_update(bp);
if ((bp->port.pmf == 0) && (val & DRV_STATUS_PMF))
bnx2x_pmf_update(bp);
} else if (attn & BNX2X_MC_ASSERT_BITS) {
BNX2X_ERR("MC assert!\n");
REG_WR(bp, MISC_REG_AEU_GENERAL_ATTN_10, 0);
REG_WR(bp, MISC_REG_AEU_GENERAL_ATTN_9, 0);
REG_WR(bp, MISC_REG_AEU_GENERAL_ATTN_8, 0);
REG_WR(bp, MISC_REG_AEU_GENERAL_ATTN_7, 0);
bnx2x_panic();
} else if (attn & BNX2X_MCP_ASSERT) {
BNX2X_ERR("MCP assert!\n");
REG_WR(bp, MISC_REG_AEU_GENERAL_ATTN_11, 0);
bnx2x_fw_dump(bp);
} else
BNX2X_ERR("Unknown HW assert! (attn 0x%x)\n", attn);
}
if (attn & EVEREST_LATCHED_ATTN_IN_USE_MASK) {
BNX2X_ERR("LATCHED attention 0x%08x (masked)\n", attn);
if (attn & BNX2X_GRC_TIMEOUT) {
val = CHIP_IS_E1H(bp) ?
REG_RD(bp, MISC_REG_GRC_TIMEOUT_ATTN) : 0;
BNX2X_ERR("GRC time-out 0x%08x\n", val);
}
if (attn & BNX2X_GRC_RSV) {
val = CHIP_IS_E1H(bp) ?
REG_RD(bp, MISC_REG_GRC_RSV_ATTN) : 0;
BNX2X_ERR("GRC reserved 0x%08x\n", val);
}
REG_WR(bp, MISC_REG_AEU_CLR_LATCH_SIGNAL, 0x7ff);
}
}
static int bnx2x_nic_unload(struct bnx2x *bp, int unload_mode);
static int bnx2x_nic_load(struct bnx2x *bp, int load_mode);
#define BNX2X_MISC_GEN_REG MISC_REG_GENERIC_POR_1
#define LOAD_COUNTER_BITS 16 /* Number of bits for load counter */
#define LOAD_COUNTER_MASK (((u32)0x1 << LOAD_COUNTER_BITS) - 1)
#define RESET_DONE_FLAG_MASK (~LOAD_COUNTER_MASK)
#define RESET_DONE_FLAG_SHIFT LOAD_COUNTER_BITS
#define CHIP_PARITY_SUPPORTED(bp) (CHIP_IS_E1(bp) || CHIP_IS_E1H(bp))
/*
* should be run under rtnl lock
*/
static inline void bnx2x_set_reset_done(struct bnx2x *bp)
{
u32 val = REG_RD(bp, BNX2X_MISC_GEN_REG);
val &= ~(1 << RESET_DONE_FLAG_SHIFT);
REG_WR(bp, BNX2X_MISC_GEN_REG, val);
barrier();
mmiowb();
}
/*
* should be run under rtnl lock
*/
static inline void bnx2x_set_reset_in_progress(struct bnx2x *bp)
{
u32 val = REG_RD(bp, BNX2X_MISC_GEN_REG);
val |= (1 << 16);
REG_WR(bp, BNX2X_MISC_GEN_REG, val);
barrier();
mmiowb();
}
/*
* should be run under rtnl lock
*/
static inline bool bnx2x_reset_is_done(struct bnx2x *bp)
{
u32 val = REG_RD(bp, BNX2X_MISC_GEN_REG);
DP(NETIF_MSG_HW, "GEN_REG_VAL=0x%08x\n", val);
return (val & RESET_DONE_FLAG_MASK) ? false : true;
}
/*
* should be run under rtnl lock
*/
static inline void bnx2x_inc_load_cnt(struct bnx2x *bp)
{
u32 val1, val = REG_RD(bp, BNX2X_MISC_GEN_REG);
DP(NETIF_MSG_HW, "Old GEN_REG_VAL=0x%08x\n", val);
val1 = ((val & LOAD_COUNTER_MASK) + 1) & LOAD_COUNTER_MASK;
REG_WR(bp, BNX2X_MISC_GEN_REG, (val & RESET_DONE_FLAG_MASK) | val1);
barrier();
mmiowb();
}
/*
* should be run under rtnl lock
*/
static inline u32 bnx2x_dec_load_cnt(struct bnx2x *bp)
{
u32 val1, val = REG_RD(bp, BNX2X_MISC_GEN_REG);
DP(NETIF_MSG_HW, "Old GEN_REG_VAL=0x%08x\n", val);
val1 = ((val & LOAD_COUNTER_MASK) - 1) & LOAD_COUNTER_MASK;
REG_WR(bp, BNX2X_MISC_GEN_REG, (val & RESET_DONE_FLAG_MASK) | val1);
barrier();
mmiowb();
return val1;
}
/*
* should be run under rtnl lock
*/
static inline u32 bnx2x_get_load_cnt(struct bnx2x *bp)
{
return REG_RD(bp, BNX2X_MISC_GEN_REG) & LOAD_COUNTER_MASK;
}
static inline void bnx2x_clear_load_cnt(struct bnx2x *bp)
{
u32 val = REG_RD(bp, BNX2X_MISC_GEN_REG);
REG_WR(bp, BNX2X_MISC_GEN_REG, val & (~LOAD_COUNTER_MASK));
}
static inline void _print_next_block(int idx, const char *blk)
{
if (idx)
pr_cont(", ");
pr_cont("%s", blk);
}
static inline int bnx2x_print_blocks_with_parity0(u32 sig, int par_num)
{
int i = 0;
u32 cur_bit = 0;
for (i = 0; sig; i++) {
cur_bit = ((u32)0x1 << i);
if (sig & cur_bit) {
switch (cur_bit) {
case AEU_INPUTS_ATTN_BITS_BRB_PARITY_ERROR:
_print_next_block(par_num++, "BRB");
break;
case AEU_INPUTS_ATTN_BITS_PARSER_PARITY_ERROR:
_print_next_block(par_num++, "PARSER");
break;
case AEU_INPUTS_ATTN_BITS_TSDM_PARITY_ERROR:
_print_next_block(par_num++, "TSDM");
break;
case AEU_INPUTS_ATTN_BITS_SEARCHER_PARITY_ERROR:
_print_next_block(par_num++, "SEARCHER");
break;
case AEU_INPUTS_ATTN_BITS_TSEMI_PARITY_ERROR:
_print_next_block(par_num++, "TSEMI");
break;
}
/* Clear the bit */
sig &= ~cur_bit;
}
}
return par_num;
}
static inline int bnx2x_print_blocks_with_parity1(u32 sig, int par_num)
{
int i = 0;
u32 cur_bit = 0;
for (i = 0; sig; i++) {
cur_bit = ((u32)0x1 << i);
if (sig & cur_bit) {
switch (cur_bit) {
case AEU_INPUTS_ATTN_BITS_PBCLIENT_PARITY_ERROR:
_print_next_block(par_num++, "PBCLIENT");
break;
case AEU_INPUTS_ATTN_BITS_QM_PARITY_ERROR:
_print_next_block(par_num++, "QM");
break;
case AEU_INPUTS_ATTN_BITS_XSDM_PARITY_ERROR:
_print_next_block(par_num++, "XSDM");
break;
case AEU_INPUTS_ATTN_BITS_XSEMI_PARITY_ERROR:
_print_next_block(par_num++, "XSEMI");
break;
case AEU_INPUTS_ATTN_BITS_DOORBELLQ_PARITY_ERROR:
_print_next_block(par_num++, "DOORBELLQ");
break;
case AEU_INPUTS_ATTN_BITS_VAUX_PCI_CORE_PARITY_ERROR:
_print_next_block(par_num++, "VAUX PCI CORE");
break;
case AEU_INPUTS_ATTN_BITS_DEBUG_PARITY_ERROR:
_print_next_block(par_num++, "DEBUG");
break;
case AEU_INPUTS_ATTN_BITS_USDM_PARITY_ERROR:
_print_next_block(par_num++, "USDM");
break;
case AEU_INPUTS_ATTN_BITS_USEMI_PARITY_ERROR:
_print_next_block(par_num++, "USEMI");
break;
case AEU_INPUTS_ATTN_BITS_UPB_PARITY_ERROR:
_print_next_block(par_num++, "UPB");
break;
case AEU_INPUTS_ATTN_BITS_CSDM_PARITY_ERROR:
_print_next_block(par_num++, "CSDM");
break;
}
/* Clear the bit */
sig &= ~cur_bit;
}
}
return par_num;
}
static inline int bnx2x_print_blocks_with_parity2(u32 sig, int par_num)
{
int i = 0;
u32 cur_bit = 0;
for (i = 0; sig; i++) {
cur_bit = ((u32)0x1 << i);
if (sig & cur_bit) {
switch (cur_bit) {
case AEU_INPUTS_ATTN_BITS_CSEMI_PARITY_ERROR:
_print_next_block(par_num++, "CSEMI");
break;
case AEU_INPUTS_ATTN_BITS_PXP_PARITY_ERROR:
_print_next_block(par_num++, "PXP");
break;
case AEU_IN_ATTN_BITS_PXPPCICLOCKCLIENT_PARITY_ERROR:
_print_next_block(par_num++,
"PXPPCICLOCKCLIENT");
break;
case AEU_INPUTS_ATTN_BITS_CFC_PARITY_ERROR:
_print_next_block(par_num++, "CFC");
break;
case AEU_INPUTS_ATTN_BITS_CDU_PARITY_ERROR:
_print_next_block(par_num++, "CDU");
break;
case AEU_INPUTS_ATTN_BITS_IGU_PARITY_ERROR:
_print_next_block(par_num++, "IGU");
break;
case AEU_INPUTS_ATTN_BITS_MISC_PARITY_ERROR:
_print_next_block(par_num++, "MISC");
break;
}
/* Clear the bit */
sig &= ~cur_bit;
}
}
return par_num;
}
static inline int bnx2x_print_blocks_with_parity3(u32 sig, int par_num)
{
int i = 0;
u32 cur_bit = 0;
for (i = 0; sig; i++) {
cur_bit = ((u32)0x1 << i);
if (sig & cur_bit) {
switch (cur_bit) {
case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_ROM_PARITY:
_print_next_block(par_num++, "MCP ROM");
break;
case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_RX_PARITY:
_print_next_block(par_num++, "MCP UMP RX");
break;
case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_TX_PARITY:
_print_next_block(par_num++, "MCP UMP TX");
break;
case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_SCPAD_PARITY:
_print_next_block(par_num++, "MCP SCPAD");
break;
}
/* Clear the bit */
sig &= ~cur_bit;
}
}
return par_num;
}
static inline bool bnx2x_parity_attn(struct bnx2x *bp, u32 sig0, u32 sig1,
u32 sig2, u32 sig3)
{
if ((sig0 & HW_PRTY_ASSERT_SET_0) || (sig1 & HW_PRTY_ASSERT_SET_1) ||
(sig2 & HW_PRTY_ASSERT_SET_2) || (sig3 & HW_PRTY_ASSERT_SET_3)) {
int par_num = 0;
DP(NETIF_MSG_HW, "Was parity error: HW block parity attention: "
"[0]:0x%08x [1]:0x%08x "
"[2]:0x%08x [3]:0x%08x\n",
sig0 & HW_PRTY_ASSERT_SET_0,
sig1 & HW_PRTY_ASSERT_SET_1,
sig2 & HW_PRTY_ASSERT_SET_2,
sig3 & HW_PRTY_ASSERT_SET_3);
printk(KERN_ERR"%s: Parity errors detected in blocks: ",
bp->dev->name);
par_num = bnx2x_print_blocks_with_parity0(
sig0 & HW_PRTY_ASSERT_SET_0, par_num);
par_num = bnx2x_print_blocks_with_parity1(
sig1 & HW_PRTY_ASSERT_SET_1, par_num);
par_num = bnx2x_print_blocks_with_parity2(
sig2 & HW_PRTY_ASSERT_SET_2, par_num);
par_num = bnx2x_print_blocks_with_parity3(
sig3 & HW_PRTY_ASSERT_SET_3, par_num);
printk("\n");
return true;
} else
return false;
}
static bool bnx2x_chk_parity_attn(struct bnx2x *bp)
{
struct attn_route attn;
int port = BP_PORT(bp);
attn.sig[0] = REG_RD(bp,
MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 +
port*4);
attn.sig[1] = REG_RD(bp,
MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 +
port*4);
attn.sig[2] = REG_RD(bp,
MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 +
port*4);
attn.sig[3] = REG_RD(bp,
MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 +
port*4);
return bnx2x_parity_attn(bp, attn.sig[0], attn.sig[1], attn.sig[2],
attn.sig[3]);
}
static void bnx2x_attn_int_deasserted(struct bnx2x *bp, u32 deasserted)
{
struct attn_route attn, *group_mask;
int port = BP_PORT(bp);
int index;
u32 reg_addr;
u32 val;
u32 aeu_mask;
/* need to take HW lock because MCP or other port might also
try to handle this event */
bnx2x_acquire_alr(bp);
if (bnx2x_chk_parity_attn(bp)) {
bp->recovery_state = BNX2X_RECOVERY_INIT;
bnx2x_set_reset_in_progress(bp);
schedule_delayed_work(&bp->reset_task, 0);
/* Disable HW interrupts */
bnx2x_int_disable(bp);
bnx2x_release_alr(bp);
/* In case of parity errors don't handle attentions so that
* other function would "see" parity errors.
*/
return;
}
attn.sig[0] = REG_RD(bp, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
attn.sig[1] = REG_RD(bp, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
attn.sig[2] = REG_RD(bp, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
attn.sig[3] = REG_RD(bp, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
DP(NETIF_MSG_HW, "attn: %08x %08x %08x %08x\n",
attn.sig[0], attn.sig[1], attn.sig[2], attn.sig[3]);
for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
if (deasserted & (1 << index)) {
group_mask = &bp->attn_group[index];
DP(NETIF_MSG_HW, "group[%d]: %08x %08x %08x %08x\n",
index, group_mask->sig[0], group_mask->sig[1],
group_mask->sig[2], group_mask->sig[3]);
bnx2x_attn_int_deasserted3(bp,
attn.sig[3] & group_mask->sig[3]);
bnx2x_attn_int_deasserted1(bp,
attn.sig[1] & group_mask->sig[1]);
bnx2x_attn_int_deasserted2(bp,
attn.sig[2] & group_mask->sig[2]);
bnx2x_attn_int_deasserted0(bp,
attn.sig[0] & group_mask->sig[0]);
}
}
bnx2x_release_alr(bp);
reg_addr = (HC_REG_COMMAND_REG + port*32 + COMMAND_REG_ATTN_BITS_CLR);
val = ~deasserted;
DP(NETIF_MSG_HW, "about to mask 0x%08x at HC addr 0x%x\n",
val, reg_addr);
REG_WR(bp, reg_addr, val);
if (~bp->attn_state & deasserted)
BNX2X_ERR("IGU ERROR\n");
reg_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
MISC_REG_AEU_MASK_ATTN_FUNC_0;
bnx2x_acquire_hw_lock(bp, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
aeu_mask = REG_RD(bp, reg_addr);
DP(NETIF_MSG_HW, "aeu_mask %x newly deasserted %x\n",
aeu_mask, deasserted);
aeu_mask |= (deasserted & 0x3ff);
DP(NETIF_MSG_HW, "new mask %x\n", aeu_mask);
REG_WR(bp, reg_addr, aeu_mask);
bnx2x_release_hw_lock(bp, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
DP(NETIF_MSG_HW, "attn_state %x\n", bp->attn_state);
bp->attn_state &= ~deasserted;
DP(NETIF_MSG_HW, "new state %x\n", bp->attn_state);
}
static void bnx2x_attn_int(struct bnx2x *bp)
{
/* read local copy of bits */
u32 attn_bits = le32_to_cpu(bp->def_status_blk->atten_status_block.
attn_bits);
u32 attn_ack = le32_to_cpu(bp->def_status_blk->atten_status_block.
attn_bits_ack);
u32 attn_state = bp->attn_state;
/* look for changed bits */
u32 asserted = attn_bits & ~attn_ack & ~attn_state;
u32 deasserted = ~attn_bits & attn_ack & attn_state;
DP(NETIF_MSG_HW,
"attn_bits %x attn_ack %x asserted %x deasserted %x\n",
attn_bits, attn_ack, asserted, deasserted);
if (~(attn_bits ^ attn_ack) & (attn_bits ^ attn_state))
BNX2X_ERR("BAD attention state\n");
/* handle bits that were raised */
if (asserted)
bnx2x_attn_int_asserted(bp, asserted);
if (deasserted)
bnx2x_attn_int_deasserted(bp, deasserted);
}
static void bnx2x_sp_task(struct work_struct *work)
{
struct bnx2x *bp = container_of(work, struct bnx2x, sp_task.work);
u16 status;
/* Return here if interrupt is disabled */
if (unlikely(atomic_read(&bp->intr_sem) != 0)) {
DP(NETIF_MSG_INTR, "called but intr_sem not 0, returning\n");
return;
}
status = bnx2x_update_dsb_idx(bp);
/* if (status == 0) */
/* BNX2X_ERR("spurious slowpath interrupt!\n"); */
DP(NETIF_MSG_INTR, "got a slowpath interrupt (status 0x%x)\n", status);
/* HW attentions */
if (status & 0x1) {
bnx2x_attn_int(bp);
status &= ~0x1;
}
/* CStorm events: STAT_QUERY */
if (status & 0x2) {
DP(BNX2X_MSG_SP, "CStorm events: STAT_QUERY\n");
status &= ~0x2;
}
if (unlikely(status))
DP(NETIF_MSG_INTR, "got an unknown interrupt! (status 0x%x)\n",
status);
bnx2x_ack_sb(bp, DEF_SB_ID, ATTENTION_ID, le16_to_cpu(bp->def_att_idx),
IGU_INT_NOP, 1);
bnx2x_ack_sb(bp, DEF_SB_ID, USTORM_ID, le16_to_cpu(bp->def_u_idx),
IGU_INT_NOP, 1);
bnx2x_ack_sb(bp, DEF_SB_ID, CSTORM_ID, le16_to_cpu(bp->def_c_idx),
IGU_INT_NOP, 1);
bnx2x_ack_sb(bp, DEF_SB_ID, XSTORM_ID, le16_to_cpu(bp->def_x_idx),
IGU_INT_NOP, 1);
bnx2x_ack_sb(bp, DEF_SB_ID, TSTORM_ID, le16_to_cpu(bp->def_t_idx),
IGU_INT_ENABLE, 1);
}
static irqreturn_t bnx2x_msix_sp_int(int irq, void *dev_instance)
{
struct net_device *dev = dev_instance;
struct bnx2x *bp = netdev_priv(dev);
/* Return here if interrupt is disabled */
if (unlikely(atomic_read(&bp->intr_sem) != 0)) {
DP(NETIF_MSG_INTR, "called but intr_sem not 0, returning\n");
return IRQ_HANDLED;
}
bnx2x_ack_sb(bp, DEF_SB_ID, TSTORM_ID, 0, IGU_INT_DISABLE, 0);
#ifdef BNX2X_STOP_ON_ERROR
if (unlikely(bp->panic))
return IRQ_HANDLED;
#endif
#ifdef BCM_CNIC
{
struct cnic_ops *c_ops;
rcu_read_lock();
c_ops = rcu_dereference(bp->cnic_ops);
if (c_ops)
c_ops->cnic_handler(bp->cnic_data, NULL);
rcu_read_unlock();
}
#endif
queue_delayed_work(bnx2x_wq, &bp->sp_task, 0);
return IRQ_HANDLED;
}
/* end of slow path */
/* Statistics */
/****************************************************************************
* Macros
****************************************************************************/
/* sum[hi:lo] += add[hi:lo] */
#define ADD_64(s_hi, a_hi, s_lo, a_lo) \
do { \
s_lo += a_lo; \
s_hi += a_hi + ((s_lo < a_lo) ? 1 : 0); \
} while (0)
/* difference = minuend - subtrahend */
#define DIFF_64(d_hi, m_hi, s_hi, d_lo, m_lo, s_lo) \
do { \
if (m_lo < s_lo) { \
/* underflow */ \
d_hi = m_hi - s_hi; \
if (d_hi > 0) { \
/* we can 'loan' 1 */ \
d_hi--; \
d_lo = m_lo + (UINT_MAX - s_lo) + 1; \
} else { \
/* m_hi <= s_hi */ \
d_hi = 0; \
d_lo = 0; \
} \
} else { \
/* m_lo >= s_lo */ \
if (m_hi < s_hi) { \
d_hi = 0; \
d_lo = 0; \
} else { \
/* m_hi >= s_hi */ \
d_hi = m_hi - s_hi; \
d_lo = m_lo - s_lo; \
} \
} \
} while (0)
#define UPDATE_STAT64(s, t) \
do { \
DIFF_64(diff.hi, new->s##_hi, pstats->mac_stx[0].t##_hi, \
diff.lo, new->s##_lo, pstats->mac_stx[0].t##_lo); \
pstats->mac_stx[0].t##_hi = new->s##_hi; \
pstats->mac_stx[0].t##_lo = new->s##_lo; \
ADD_64(pstats->mac_stx[1].t##_hi, diff.hi, \
pstats->mac_stx[1].t##_lo, diff.lo); \
} while (0)
#define UPDATE_STAT64_NIG(s, t) \
do { \
DIFF_64(diff.hi, new->s##_hi, old->s##_hi, \
diff.lo, new->s##_lo, old->s##_lo); \
ADD_64(estats->t##_hi, diff.hi, \
estats->t##_lo, diff.lo); \
} while (0)
/* sum[hi:lo] += add */
#define ADD_EXTEND_64(s_hi, s_lo, a) \
do { \
s_lo += a; \
s_hi += (s_lo < a) ? 1 : 0; \
} while (0)
#define UPDATE_EXTEND_STAT(s) \
do { \
ADD_EXTEND_64(pstats->mac_stx[1].s##_hi, \
pstats->mac_stx[1].s##_lo, \
new->s); \
} while (0)
#define UPDATE_EXTEND_TSTAT(s, t) \
do { \
diff = le32_to_cpu(tclient->s) - le32_to_cpu(old_tclient->s); \
old_tclient->s = tclient->s; \
ADD_EXTEND_64(qstats->t##_hi, qstats->t##_lo, diff); \
} while (0)
#define UPDATE_EXTEND_USTAT(s, t) \
do { \
diff = le32_to_cpu(uclient->s) - le32_to_cpu(old_uclient->s); \
old_uclient->s = uclient->s; \
ADD_EXTEND_64(qstats->t##_hi, qstats->t##_lo, diff); \
} while (0)
#define UPDATE_EXTEND_XSTAT(s, t) \
do { \
diff = le32_to_cpu(xclient->s) - le32_to_cpu(old_xclient->s); \
old_xclient->s = xclient->s; \
ADD_EXTEND_64(qstats->t##_hi, qstats->t##_lo, diff); \
} while (0)
/* minuend -= subtrahend */
#define SUB_64(m_hi, s_hi, m_lo, s_lo) \
do { \
DIFF_64(m_hi, m_hi, s_hi, m_lo, m_lo, s_lo); \
} while (0)
/* minuend[hi:lo] -= subtrahend */
#define SUB_EXTEND_64(m_hi, m_lo, s) \
do { \
SUB_64(m_hi, 0, m_lo, s); \
} while (0)
#define SUB_EXTEND_USTAT(s, t) \
do { \
diff = le32_to_cpu(uclient->s) - le32_to_cpu(old_uclient->s); \
SUB_EXTEND_64(qstats->t##_hi, qstats->t##_lo, diff); \
} while (0)
/*
* General service functions
*/
static inline long bnx2x_hilo(u32 *hiref)
{
u32 lo = *(hiref + 1);
#if (BITS_PER_LONG == 64)
u32 hi = *hiref;
return HILO_U64(hi, lo);
#else
return lo;
#endif
}
/*
* Init service functions
*/
static void bnx2x_storm_stats_post(struct bnx2x *bp)
{
if (!bp->stats_pending) {
struct eth_query_ramrod_data ramrod_data = {0};
int i, rc;
spin_lock_bh(&bp->stats_lock);
ramrod_data.drv_counter = bp->stats_counter++;
ramrod_data.collect_port = bp->port.pmf ? 1 : 0;
for_each_queue(bp, i)
ramrod_data.ctr_id_vector |= (1 << bp->fp[i].cl_id);
rc = bnx2x_sp_post(bp, RAMROD_CMD_ID_ETH_STAT_QUERY, 0,
((u32 *)&ramrod_data)[1],
((u32 *)&ramrod_data)[0], 0);
if (rc == 0) {
/* stats ramrod has it's own slot on the spq */
bp->spq_left++;
bp->stats_pending = 1;
}
spin_unlock_bh(&bp->stats_lock);
}
}
static void bnx2x_hw_stats_post(struct bnx2x *bp)
{
struct dmae_command *dmae = &bp->stats_dmae;
u32 *stats_comp = bnx2x_sp(bp, stats_comp);
*stats_comp = DMAE_COMP_VAL;
if (CHIP_REV_IS_SLOW(bp))
return;
/* loader */
if (bp->executer_idx) {
int loader_idx = PMF_DMAE_C(bp);
memset(dmae, 0, sizeof(struct dmae_command));
dmae->opcode = (DMAE_CMD_SRC_PCI | DMAE_CMD_DST_GRC |
DMAE_CMD_C_DST_GRC | DMAE_CMD_C_ENABLE |
DMAE_CMD_DST_RESET |
#ifdef __BIG_ENDIAN
DMAE_CMD_ENDIANITY_B_DW_SWAP |
#else
DMAE_CMD_ENDIANITY_DW_SWAP |
#endif
(BP_PORT(bp) ? DMAE_CMD_PORT_1 :
DMAE_CMD_PORT_0) |
(BP_E1HVN(bp) << DMAE_CMD_E1HVN_SHIFT));
dmae->src_addr_lo = U64_LO(bnx2x_sp_mapping(bp, dmae[0]));
dmae->src_addr_hi = U64_HI(bnx2x_sp_mapping(bp, dmae[0]));
dmae->dst_addr_lo = (DMAE_REG_CMD_MEM +
sizeof(struct dmae_command) *
(loader_idx + 1)) >> 2;
dmae->dst_addr_hi = 0;
dmae->len = sizeof(struct dmae_command) >> 2;
if (CHIP_IS_E1(bp))
dmae->len--;
dmae->comp_addr_lo = dmae_reg_go_c[loader_idx + 1] >> 2;
dmae->comp_addr_hi = 0;
dmae->comp_val = 1;
*stats_comp = 0;
bnx2x_post_dmae(bp, dmae, loader_idx);
} else if (bp->func_stx) {
*stats_comp = 0;
bnx2x_post_dmae(bp, dmae, INIT_DMAE_C(bp));
}
}
static int bnx2x_stats_comp(struct bnx2x *bp)
{
u32 *stats_comp = bnx2x_sp(bp, stats_comp);
int cnt = 10;
might_sleep();
while (*stats_comp != DMAE_COMP_VAL) {
if (!cnt) {
BNX2X_ERR("timeout waiting for stats finished\n");
break;
}
cnt--;
msleep(1);
}
return 1;
}
/*
* Statistics service functions
*/
static void bnx2x_stats_pmf_update(struct bnx2x *bp)
{
struct dmae_command *dmae;
u32 opcode;
int loader_idx = PMF_DMAE_C(bp);
u32 *stats_comp = bnx2x_sp(bp, stats_comp);
/* sanity */
if (!IS_E1HMF(bp) || !bp->port.pmf || !bp->port.port_stx) {
BNX2X_ERR("BUG!\n");
return;
}
bp->executer_idx = 0;
opcode = (DMAE_CMD_SRC_GRC | DMAE_CMD_DST_PCI |
DMAE_CMD_C_ENABLE |
DMAE_CMD_SRC_RESET | DMAE_CMD_DST_RESET |
#ifdef __BIG_ENDIAN
DMAE_CMD_ENDIANITY_B_DW_SWAP |
#else
DMAE_CMD_ENDIANITY_DW_SWAP |
#endif
(BP_PORT(bp) ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0) |
(BP_E1HVN(bp) << DMAE_CMD_E1HVN_SHIFT));
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
dmae->opcode = (opcode | DMAE_CMD_C_DST_GRC);
dmae->src_addr_lo = bp->port.port_stx >> 2;
dmae->src_addr_hi = 0;
dmae->dst_addr_lo = U64_LO(bnx2x_sp_mapping(bp, port_stats));
dmae->dst_addr_hi = U64_HI(bnx2x_sp_mapping(bp, port_stats));
dmae->len = DMAE_LEN32_RD_MAX;
dmae->comp_addr_lo = dmae_reg_go_c[loader_idx] >> 2;
dmae->comp_addr_hi = 0;
dmae->comp_val = 1;
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
dmae->opcode = (opcode | DMAE_CMD_C_DST_PCI);
dmae->src_addr_lo = (bp->port.port_stx >> 2) + DMAE_LEN32_RD_MAX;
dmae->src_addr_hi = 0;
dmae->dst_addr_lo = U64_LO(bnx2x_sp_mapping(bp, port_stats) +
DMAE_LEN32_RD_MAX * 4);
dmae->dst_addr_hi = U64_HI(bnx2x_sp_mapping(bp, port_stats) +
DMAE_LEN32_RD_MAX * 4);
dmae->len = (sizeof(struct host_port_stats) >> 2) - DMAE_LEN32_RD_MAX;
dmae->comp_addr_lo = U64_LO(bnx2x_sp_mapping(bp, stats_comp));
dmae->comp_addr_hi = U64_HI(bnx2x_sp_mapping(bp, stats_comp));
dmae->comp_val = DMAE_COMP_VAL;
*stats_comp = 0;
bnx2x_hw_stats_post(bp);
bnx2x_stats_comp(bp);
}
static void bnx2x_port_stats_init(struct bnx2x *bp)
{
struct dmae_command *dmae;
int port = BP_PORT(bp);
int vn = BP_E1HVN(bp);
u32 opcode;
int loader_idx = PMF_DMAE_C(bp);
u32 mac_addr;
u32 *stats_comp = bnx2x_sp(bp, stats_comp);
/* sanity */
if (!bp->link_vars.link_up || !bp->port.pmf) {
BNX2X_ERR("BUG!\n");
return;
}
bp->executer_idx = 0;
/* MCP */
opcode = (DMAE_CMD_SRC_PCI | DMAE_CMD_DST_GRC |
DMAE_CMD_C_DST_GRC | DMAE_CMD_C_ENABLE |
DMAE_CMD_SRC_RESET | DMAE_CMD_DST_RESET |
#ifdef __BIG_ENDIAN
DMAE_CMD_ENDIANITY_B_DW_SWAP |
#else
DMAE_CMD_ENDIANITY_DW_SWAP |
#endif
(port ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0) |
(vn << DMAE_CMD_E1HVN_SHIFT));
if (bp->port.port_stx) {
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
dmae->opcode = opcode;
dmae->src_addr_lo = U64_LO(bnx2x_sp_mapping(bp, port_stats));
dmae->src_addr_hi = U64_HI(bnx2x_sp_mapping(bp, port_stats));
dmae->dst_addr_lo = bp->port.port_stx >> 2;
dmae->dst_addr_hi = 0;
dmae->len = sizeof(struct host_port_stats) >> 2;
dmae->comp_addr_lo = dmae_reg_go_c[loader_idx] >> 2;
dmae->comp_addr_hi = 0;
dmae->comp_val = 1;
}
if (bp->func_stx) {
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
dmae->opcode = opcode;
dmae->src_addr_lo = U64_LO(bnx2x_sp_mapping(bp, func_stats));
dmae->src_addr_hi = U64_HI(bnx2x_sp_mapping(bp, func_stats));
dmae->dst_addr_lo = bp->func_stx >> 2;
dmae->dst_addr_hi = 0;
dmae->len = sizeof(struct host_func_stats) >> 2;
dmae->comp_addr_lo = dmae_reg_go_c[loader_idx] >> 2;
dmae->comp_addr_hi = 0;
dmae->comp_val = 1;
}
/* MAC */
opcode = (DMAE_CMD_SRC_GRC | DMAE_CMD_DST_PCI |
DMAE_CMD_C_DST_GRC | DMAE_CMD_C_ENABLE |
DMAE_CMD_SRC_RESET | DMAE_CMD_DST_RESET |
#ifdef __BIG_ENDIAN
DMAE_CMD_ENDIANITY_B_DW_SWAP |
#else
DMAE_CMD_ENDIANITY_DW_SWAP |
#endif
(port ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0) |
(vn << DMAE_CMD_E1HVN_SHIFT));
if (bp->link_vars.mac_type == MAC_TYPE_BMAC) {
mac_addr = (port ? NIG_REG_INGRESS_BMAC1_MEM :
NIG_REG_INGRESS_BMAC0_MEM);
/* BIGMAC_REGISTER_TX_STAT_GTPKT ..
BIGMAC_REGISTER_TX_STAT_GTBYT */
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
dmae->opcode = opcode;
dmae->src_addr_lo = (mac_addr +
BIGMAC_REGISTER_TX_STAT_GTPKT) >> 2;
dmae->src_addr_hi = 0;
dmae->dst_addr_lo = U64_LO(bnx2x_sp_mapping(bp, mac_stats));
dmae->dst_addr_hi = U64_HI(bnx2x_sp_mapping(bp, mac_stats));
dmae->len = (8 + BIGMAC_REGISTER_TX_STAT_GTBYT -
BIGMAC_REGISTER_TX_STAT_GTPKT) >> 2;
dmae->comp_addr_lo = dmae_reg_go_c[loader_idx] >> 2;
dmae->comp_addr_hi = 0;
dmae->comp_val = 1;
/* BIGMAC_REGISTER_RX_STAT_GR64 ..
BIGMAC_REGISTER_RX_STAT_GRIPJ */
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
dmae->opcode = opcode;
dmae->src_addr_lo = (mac_addr +
BIGMAC_REGISTER_RX_STAT_GR64) >> 2;
dmae->src_addr_hi = 0;
dmae->dst_addr_lo = U64_LO(bnx2x_sp_mapping(bp, mac_stats) +
offsetof(struct bmac_stats, rx_stat_gr64_lo));
dmae->dst_addr_hi = U64_HI(bnx2x_sp_mapping(bp, mac_stats) +
offsetof(struct bmac_stats, rx_stat_gr64_lo));
dmae->len = (8 + BIGMAC_REGISTER_RX_STAT_GRIPJ -
BIGMAC_REGISTER_RX_STAT_GR64) >> 2;
dmae->comp_addr_lo = dmae_reg_go_c[loader_idx] >> 2;
dmae->comp_addr_hi = 0;
dmae->comp_val = 1;
} else if (bp->link_vars.mac_type == MAC_TYPE_EMAC) {
mac_addr = (port ? GRCBASE_EMAC1 : GRCBASE_EMAC0);
/* EMAC_REG_EMAC_RX_STAT_AC (EMAC_REG_EMAC_RX_STAT_AC_COUNT)*/
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
dmae->opcode = opcode;
dmae->src_addr_lo = (mac_addr +
EMAC_REG_EMAC_RX_STAT_AC) >> 2;
dmae->src_addr_hi = 0;
dmae->dst_addr_lo = U64_LO(bnx2x_sp_mapping(bp, mac_stats));
dmae->dst_addr_hi = U64_HI(bnx2x_sp_mapping(bp, mac_stats));
dmae->len = EMAC_REG_EMAC_RX_STAT_AC_COUNT;
dmae->comp_addr_lo = dmae_reg_go_c[loader_idx] >> 2;
dmae->comp_addr_hi = 0;
dmae->comp_val = 1;
/* EMAC_REG_EMAC_RX_STAT_AC_28 */
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
dmae->opcode = opcode;
dmae->src_addr_lo = (mac_addr +
EMAC_REG_EMAC_RX_STAT_AC_28) >> 2;
dmae->src_addr_hi = 0;
dmae->dst_addr_lo = U64_LO(bnx2x_sp_mapping(bp, mac_stats) +
offsetof(struct emac_stats, rx_stat_falsecarriererrors));
dmae->dst_addr_hi = U64_HI(bnx2x_sp_mapping(bp, mac_stats) +
offsetof(struct emac_stats, rx_stat_falsecarriererrors));
dmae->len = 1;
dmae->comp_addr_lo = dmae_reg_go_c[loader_idx] >> 2;
dmae->comp_addr_hi = 0;
dmae->comp_val = 1;
/* EMAC_REG_EMAC_TX_STAT_AC (EMAC_REG_EMAC_TX_STAT_AC_COUNT)*/
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
dmae->opcode = opcode;
dmae->src_addr_lo = (mac_addr +
EMAC_REG_EMAC_TX_STAT_AC) >> 2;
dmae->src_addr_hi = 0;
dmae->dst_addr_lo = U64_LO(bnx2x_sp_mapping(bp, mac_stats) +
offsetof(struct emac_stats, tx_stat_ifhcoutoctets));
dmae->dst_addr_hi = U64_HI(bnx2x_sp_mapping(bp, mac_stats) +
offsetof(struct emac_stats, tx_stat_ifhcoutoctets));
dmae->len = EMAC_REG_EMAC_TX_STAT_AC_COUNT;
dmae->comp_addr_lo = dmae_reg_go_c[loader_idx] >> 2;
dmae->comp_addr_hi = 0;
dmae->comp_val = 1;
}
/* NIG */
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
dmae->opcode = opcode;
dmae->src_addr_lo = (port ? NIG_REG_STAT1_BRB_DISCARD :
NIG_REG_STAT0_BRB_DISCARD) >> 2;
dmae->src_addr_hi = 0;
dmae->dst_addr_lo = U64_LO(bnx2x_sp_mapping(bp, nig_stats));
dmae->dst_addr_hi = U64_HI(bnx2x_sp_mapping(bp, nig_stats));
dmae->len = (sizeof(struct nig_stats) - 4*sizeof(u32)) >> 2;
dmae->comp_addr_lo = dmae_reg_go_c[loader_idx] >> 2;
dmae->comp_addr_hi = 0;
dmae->comp_val = 1;
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
dmae->opcode = opcode;
dmae->src_addr_lo = (port ? NIG_REG_STAT1_EGRESS_MAC_PKT0 :
NIG_REG_STAT0_EGRESS_MAC_PKT0) >> 2;
dmae->src_addr_hi = 0;
dmae->dst_addr_lo = U64_LO(bnx2x_sp_mapping(bp, nig_stats) +
offsetof(struct nig_stats, egress_mac_pkt0_lo));
dmae->dst_addr_hi = U64_HI(bnx2x_sp_mapping(bp, nig_stats) +
offsetof(struct nig_stats, egress_mac_pkt0_lo));
dmae->len = (2*sizeof(u32)) >> 2;
dmae->comp_addr_lo = dmae_reg_go_c[loader_idx] >> 2;
dmae->comp_addr_hi = 0;
dmae->comp_val = 1;
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
dmae->opcode = (DMAE_CMD_SRC_GRC | DMAE_CMD_DST_PCI |
DMAE_CMD_C_DST_PCI | DMAE_CMD_C_ENABLE |
DMAE_CMD_SRC_RESET | DMAE_CMD_DST_RESET |
#ifdef __BIG_ENDIAN
DMAE_CMD_ENDIANITY_B_DW_SWAP |
#else
DMAE_CMD_ENDIANITY_DW_SWAP |
#endif
(port ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0) |
(vn << DMAE_CMD_E1HVN_SHIFT));
dmae->src_addr_lo = (port ? NIG_REG_STAT1_EGRESS_MAC_PKT1 :
NIG_REG_STAT0_EGRESS_MAC_PKT1) >> 2;
dmae->src_addr_hi = 0;
dmae->dst_addr_lo = U64_LO(bnx2x_sp_mapping(bp, nig_stats) +
offsetof(struct nig_stats, egress_mac_pkt1_lo));
dmae->dst_addr_hi = U64_HI(bnx2x_sp_mapping(bp, nig_stats) +
offsetof(struct nig_stats, egress_mac_pkt1_lo));
dmae->len = (2*sizeof(u32)) >> 2;
dmae->comp_addr_lo = U64_LO(bnx2x_sp_mapping(bp, stats_comp));
dmae->comp_addr_hi = U64_HI(bnx2x_sp_mapping(bp, stats_comp));
dmae->comp_val = DMAE_COMP_VAL;
*stats_comp = 0;
}
static void bnx2x_func_stats_init(struct bnx2x *bp)
{
struct dmae_command *dmae = &bp->stats_dmae;
u32 *stats_comp = bnx2x_sp(bp, stats_comp);
/* sanity */
if (!bp->func_stx) {
BNX2X_ERR("BUG!\n");
return;
}
bp->executer_idx = 0;
memset(dmae, 0, sizeof(struct dmae_command));
dmae->opcode = (DMAE_CMD_SRC_PCI | DMAE_CMD_DST_GRC |
DMAE_CMD_C_DST_PCI | DMAE_CMD_C_ENABLE |
DMAE_CMD_SRC_RESET | DMAE_CMD_DST_RESET |
#ifdef __BIG_ENDIAN
DMAE_CMD_ENDIANITY_B_DW_SWAP |
#else
DMAE_CMD_ENDIANITY_DW_SWAP |
#endif
(BP_PORT(bp) ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0) |
(BP_E1HVN(bp) << DMAE_CMD_E1HVN_SHIFT));
dmae->src_addr_lo = U64_LO(bnx2x_sp_mapping(bp, func_stats));
dmae->src_addr_hi = U64_HI(bnx2x_sp_mapping(bp, func_stats));
dmae->dst_addr_lo = bp->func_stx >> 2;
dmae->dst_addr_hi = 0;
dmae->len = sizeof(struct host_func_stats) >> 2;
dmae->comp_addr_lo = U64_LO(bnx2x_sp_mapping(bp, stats_comp));
dmae->comp_addr_hi = U64_HI(bnx2x_sp_mapping(bp, stats_comp));
dmae->comp_val = DMAE_COMP_VAL;
*stats_comp = 0;
}
static void bnx2x_stats_start(struct bnx2x *bp)
{
if (bp->port.pmf)
bnx2x_port_stats_init(bp);
else if (bp->func_stx)
bnx2x_func_stats_init(bp);
bnx2x_hw_stats_post(bp);
bnx2x_storm_stats_post(bp);
}
static void bnx2x_stats_pmf_start(struct bnx2x *bp)
{
bnx2x_stats_comp(bp);
bnx2x_stats_pmf_update(bp);
bnx2x_stats_start(bp);
}
static void bnx2x_stats_restart(struct bnx2x *bp)
{
bnx2x_stats_comp(bp);
bnx2x_stats_start(bp);
}
static void bnx2x_bmac_stats_update(struct bnx2x *bp)
{
struct bmac_stats *new = bnx2x_sp(bp, mac_stats.bmac_stats);
struct host_port_stats *pstats = bnx2x_sp(bp, port_stats);
struct bnx2x_eth_stats *estats = &bp->eth_stats;
struct {
u32 lo;
u32 hi;
} diff;
UPDATE_STAT64(rx_stat_grerb, rx_stat_ifhcinbadoctets);
UPDATE_STAT64(rx_stat_grfcs, rx_stat_dot3statsfcserrors);
UPDATE_STAT64(rx_stat_grund, rx_stat_etherstatsundersizepkts);
UPDATE_STAT64(rx_stat_grovr, rx_stat_dot3statsframestoolong);
UPDATE_STAT64(rx_stat_grfrg, rx_stat_etherstatsfragments);
UPDATE_STAT64(rx_stat_grjbr, rx_stat_etherstatsjabbers);
UPDATE_STAT64(rx_stat_grxcf, rx_stat_maccontrolframesreceived);
UPDATE_STAT64(rx_stat_grxpf, rx_stat_xoffstateentered);
UPDATE_STAT64(rx_stat_grxpf, rx_stat_bmac_xpf);
UPDATE_STAT64(tx_stat_gtxpf, tx_stat_outxoffsent);
UPDATE_STAT64(tx_stat_gtxpf, tx_stat_flowcontroldone);
UPDATE_STAT64(tx_stat_gt64, tx_stat_etherstatspkts64octets);
UPDATE_STAT64(tx_stat_gt127,
tx_stat_etherstatspkts65octetsto127octets);
UPDATE_STAT64(tx_stat_gt255,
tx_stat_etherstatspkts128octetsto255octets);
UPDATE_STAT64(tx_stat_gt511,
tx_stat_etherstatspkts256octetsto511octets);
UPDATE_STAT64(tx_stat_gt1023,
tx_stat_etherstatspkts512octetsto1023octets);
UPDATE_STAT64(tx_stat_gt1518,
tx_stat_etherstatspkts1024octetsto1522octets);
UPDATE_STAT64(tx_stat_gt2047, tx_stat_bmac_2047);
UPDATE_STAT64(tx_stat_gt4095, tx_stat_bmac_4095);
UPDATE_STAT64(tx_stat_gt9216, tx_stat_bmac_9216);
UPDATE_STAT64(tx_stat_gt16383, tx_stat_bmac_16383);
UPDATE_STAT64(tx_stat_gterr,
tx_stat_dot3statsinternalmactransmiterrors);
UPDATE_STAT64(tx_stat_gtufl, tx_stat_bmac_ufl);
estats->pause_frames_received_hi =
pstats->mac_stx[1].rx_stat_bmac_xpf_hi;
estats->pause_frames_received_lo =
pstats->mac_stx[1].rx_stat_bmac_xpf_lo;
estats->pause_frames_sent_hi =
pstats->mac_stx[1].tx_stat_outxoffsent_hi;
estats->pause_frames_sent_lo =
pstats->mac_stx[1].tx_stat_outxoffsent_lo;
}
static void bnx2x_emac_stats_update(struct bnx2x *bp)
{
struct emac_stats *new = bnx2x_sp(bp, mac_stats.emac_stats);
struct host_port_stats *pstats = bnx2x_sp(bp, port_stats);
struct bnx2x_eth_stats *estats = &bp->eth_stats;
UPDATE_EXTEND_STAT(rx_stat_ifhcinbadoctets);
UPDATE_EXTEND_STAT(tx_stat_ifhcoutbadoctets);
UPDATE_EXTEND_STAT(rx_stat_dot3statsfcserrors);
UPDATE_EXTEND_STAT(rx_stat_dot3statsalignmenterrors);
UPDATE_EXTEND_STAT(rx_stat_dot3statscarriersenseerrors);
UPDATE_EXTEND_STAT(rx_stat_falsecarriererrors);
UPDATE_EXTEND_STAT(rx_stat_etherstatsundersizepkts);
UPDATE_EXTEND_STAT(rx_stat_dot3statsframestoolong);
UPDATE_EXTEND_STAT(rx_stat_etherstatsfragments);
UPDATE_EXTEND_STAT(rx_stat_etherstatsjabbers);
UPDATE_EXTEND_STAT(rx_stat_maccontrolframesreceived);
UPDATE_EXTEND_STAT(rx_stat_xoffstateentered);
UPDATE_EXTEND_STAT(rx_stat_xonpauseframesreceived);
UPDATE_EXTEND_STAT(rx_stat_xoffpauseframesreceived);
UPDATE_EXTEND_STAT(tx_stat_outxonsent);
UPDATE_EXTEND_STAT(tx_stat_outxoffsent);
UPDATE_EXTEND_STAT(tx_stat_flowcontroldone);
UPDATE_EXTEND_STAT(tx_stat_etherstatscollisions);
UPDATE_EXTEND_STAT(tx_stat_dot3statssinglecollisionframes);
UPDATE_EXTEND_STAT(tx_stat_dot3statsmultiplecollisionframes);
UPDATE_EXTEND_STAT(tx_stat_dot3statsdeferredtransmissions);
UPDATE_EXTEND_STAT(tx_stat_dot3statsexcessivecollisions);
UPDATE_EXTEND_STAT(tx_stat_dot3statslatecollisions);
UPDATE_EXTEND_STAT(tx_stat_etherstatspkts64octets);
UPDATE_EXTEND_STAT(tx_stat_etherstatspkts65octetsto127octets);
UPDATE_EXTEND_STAT(tx_stat_etherstatspkts128octetsto255octets);
UPDATE_EXTEND_STAT(tx_stat_etherstatspkts256octetsto511octets);
UPDATE_EXTEND_STAT(tx_stat_etherstatspkts512octetsto1023octets);
UPDATE_EXTEND_STAT(tx_stat_etherstatspkts1024octetsto1522octets);
UPDATE_EXTEND_STAT(tx_stat_etherstatspktsover1522octets);
UPDATE_EXTEND_STAT(tx_stat_dot3statsinternalmactransmiterrors);
estats->pause_frames_received_hi =
pstats->mac_stx[1].rx_stat_xonpauseframesreceived_hi;
estats->pause_frames_received_lo =
pstats->mac_stx[1].rx_stat_xonpauseframesreceived_lo;
ADD_64(estats->pause_frames_received_hi,
pstats->mac_stx[1].rx_stat_xoffpauseframesreceived_hi,
estats->pause_frames_received_lo,
pstats->mac_stx[1].rx_stat_xoffpauseframesreceived_lo);
estats->pause_frames_sent_hi =
pstats->mac_stx[1].tx_stat_outxonsent_hi;
estats->pause_frames_sent_lo =
pstats->mac_stx[1].tx_stat_outxonsent_lo;
ADD_64(estats->pause_frames_sent_hi,
pstats->mac_stx[1].tx_stat_outxoffsent_hi,
estats->pause_frames_sent_lo,
pstats->mac_stx[1].tx_stat_outxoffsent_lo);
}
static int bnx2x_hw_stats_update(struct bnx2x *bp)
{
struct nig_stats *new = bnx2x_sp(bp, nig_stats);
struct nig_stats *old = &(bp->port.old_nig_stats);
struct host_port_stats *pstats = bnx2x_sp(bp, port_stats);
struct bnx2x_eth_stats *estats = &bp->eth_stats;
struct {
u32 lo;
u32 hi;
} diff;
if (bp->link_vars.mac_type == MAC_TYPE_BMAC)
bnx2x_bmac_stats_update(bp);
else if (bp->link_vars.mac_type == MAC_TYPE_EMAC)
bnx2x_emac_stats_update(bp);
else { /* unreached */
BNX2X_ERR("stats updated by DMAE but no MAC active\n");
return -1;
}
ADD_EXTEND_64(pstats->brb_drop_hi, pstats->brb_drop_lo,
new->brb_discard - old->brb_discard);
ADD_EXTEND_64(estats->brb_truncate_hi, estats->brb_truncate_lo,
new->brb_truncate - old->brb_truncate);
UPDATE_STAT64_NIG(egress_mac_pkt0,
etherstatspkts1024octetsto1522octets);
UPDATE_STAT64_NIG(egress_mac_pkt1, etherstatspktsover1522octets);
memcpy(old, new, sizeof(struct nig_stats));
memcpy(&(estats->rx_stat_ifhcinbadoctets_hi), &(pstats->mac_stx[1]),
sizeof(struct mac_stx));
estats->brb_drop_hi = pstats->brb_drop_hi;
estats->brb_drop_lo = pstats->brb_drop_lo;
pstats->host_port_stats_start = ++pstats->host_port_stats_end;
if (!BP_NOMCP(bp)) {
u32 nig_timer_max =
SHMEM_RD(bp, port_mb[BP_PORT(bp)].stat_nig_timer);
if (nig_timer_max != estats->nig_timer_max) {
estats->nig_timer_max = nig_timer_max;
BNX2X_ERR("NIG timer max (%u)\n",
estats->nig_timer_max);
}
}
return 0;
}
static int bnx2x_storm_stats_update(struct bnx2x *bp)
{
struct eth_stats_query *stats = bnx2x_sp(bp, fw_stats);
struct tstorm_per_port_stats *tport =
&stats->tstorm_common.port_statistics;
struct host_func_stats *fstats = bnx2x_sp(bp, func_stats);
struct bnx2x_eth_stats *estats = &bp->eth_stats;
int i;
u16 cur_stats_counter;
/* Make sure we use the value of the counter
* used for sending the last stats ramrod.
*/
spin_lock_bh(&bp->stats_lock);
cur_stats_counter = bp->stats_counter - 1;
spin_unlock_bh(&bp->stats_lock);
memcpy(&(fstats->total_bytes_received_hi),
&(bnx2x_sp(bp, func_stats_base)->total_bytes_received_hi),
sizeof(struct host_func_stats) - 2*sizeof(u32));
estats->error_bytes_received_hi = 0;
estats->error_bytes_received_lo = 0;
estats->etherstatsoverrsizepkts_hi = 0;
estats->etherstatsoverrsizepkts_lo = 0;
estats->no_buff_discard_hi = 0;
estats->no_buff_discard_lo = 0;
for_each_queue(bp, i) {
struct bnx2x_fastpath *fp = &bp->fp[i];
int cl_id = fp->cl_id;
struct tstorm_per_client_stats *tclient =
&stats->tstorm_common.client_statistics[cl_id];
struct tstorm_per_client_stats *old_tclient = &fp->old_tclient;
struct ustorm_per_client_stats *uclient =
&stats->ustorm_common.client_statistics[cl_id];
struct ustorm_per_client_stats *old_uclient = &fp->old_uclient;
struct xstorm_per_client_stats *xclient =
&stats->xstorm_common.client_statistics[cl_id];
struct xstorm_per_client_stats *old_xclient = &fp->old_xclient;
struct bnx2x_eth_q_stats *qstats = &fp->eth_q_stats;
u32 diff;
/* are storm stats valid? */
if (le16_to_cpu(xclient->stats_counter) != cur_stats_counter) {
DP(BNX2X_MSG_STATS, "[%d] stats not updated by xstorm"
" xstorm counter (0x%x) != stats_counter (0x%x)\n",
i, xclient->stats_counter, cur_stats_counter + 1);
return -1;
}
if (le16_to_cpu(tclient->stats_counter) != cur_stats_counter) {
DP(BNX2X_MSG_STATS, "[%d] stats not updated by tstorm"
" tstorm counter (0x%x) != stats_counter (0x%x)\n",
i, tclient->stats_counter, cur_stats_counter + 1);
return -2;
}
if (le16_to_cpu(uclient->stats_counter) != cur_stats_counter) {
DP(BNX2X_MSG_STATS, "[%d] stats not updated by ustorm"
" ustorm counter (0x%x) != stats_counter (0x%x)\n",
i, uclient->stats_counter, cur_stats_counter + 1);
return -4;
}
qstats->total_bytes_received_hi =
le32_to_cpu(tclient->rcv_broadcast_bytes.hi);
qstats->total_bytes_received_lo =
le32_to_cpu(tclient->rcv_broadcast_bytes.lo);
ADD_64(qstats->total_bytes_received_hi,
le32_to_cpu(tclient->rcv_multicast_bytes.hi),
qstats->total_bytes_received_lo,
le32_to_cpu(tclient->rcv_multicast_bytes.lo));
ADD_64(qstats->total_bytes_received_hi,
le32_to_cpu(tclient->rcv_unicast_bytes.hi),
qstats->total_bytes_received_lo,
le32_to_cpu(tclient->rcv_unicast_bytes.lo));
SUB_64(qstats->total_bytes_received_hi,
le32_to_cpu(uclient->bcast_no_buff_bytes.hi),
qstats->total_bytes_received_lo,
le32_to_cpu(uclient->bcast_no_buff_bytes.lo));
SUB_64(qstats->total_bytes_received_hi,
le32_to_cpu(uclient->mcast_no_buff_bytes.hi),
qstats->total_bytes_received_lo,
le32_to_cpu(uclient->mcast_no_buff_bytes.lo));
SUB_64(qstats->total_bytes_received_hi,
le32_to_cpu(uclient->ucast_no_buff_bytes.hi),
qstats->total_bytes_received_lo,
le32_to_cpu(uclient->ucast_no_buff_bytes.lo));
qstats->valid_bytes_received_hi =
qstats->total_bytes_received_hi;
qstats->valid_bytes_received_lo =
qstats->total_bytes_received_lo;
qstats->error_bytes_received_hi =
le32_to_cpu(tclient->rcv_error_bytes.hi);
qstats->error_bytes_received_lo =
le32_to_cpu(tclient->rcv_error_bytes.lo);
ADD_64(qstats->total_bytes_received_hi,
qstats->error_bytes_received_hi,
qstats->total_bytes_received_lo,
qstats->error_bytes_received_lo);
UPDATE_EXTEND_TSTAT(rcv_unicast_pkts,
total_unicast_packets_received);
UPDATE_EXTEND_TSTAT(rcv_multicast_pkts,
total_multicast_packets_received);
UPDATE_EXTEND_TSTAT(rcv_broadcast_pkts,
total_broadcast_packets_received);
UPDATE_EXTEND_TSTAT(packets_too_big_discard,
etherstatsoverrsizepkts);
UPDATE_EXTEND_TSTAT(no_buff_discard, no_buff_discard);
SUB_EXTEND_USTAT(ucast_no_buff_pkts,
total_unicast_packets_received);
SUB_EXTEND_USTAT(mcast_no_buff_pkts,
total_multicast_packets_received);
SUB_EXTEND_USTAT(bcast_no_buff_pkts,
total_broadcast_packets_received);
UPDATE_EXTEND_USTAT(ucast_no_buff_pkts, no_buff_discard);
UPDATE_EXTEND_USTAT(mcast_no_buff_pkts, no_buff_discard);
UPDATE_EXTEND_USTAT(bcast_no_buff_pkts, no_buff_discard);
qstats->total_bytes_transmitted_hi =
le32_to_cpu(xclient->unicast_bytes_sent.hi);
qstats->total_bytes_transmitted_lo =
le32_to_cpu(xclient->unicast_bytes_sent.lo);
ADD_64(qstats->total_bytes_transmitted_hi,
le32_to_cpu(xclient->multicast_bytes_sent.hi),
qstats->total_bytes_transmitted_lo,
le32_to_cpu(xclient->multicast_bytes_sent.lo));
ADD_64(qstats->total_bytes_transmitted_hi,
le32_to_cpu(xclient->broadcast_bytes_sent.hi),
qstats->total_bytes_transmitted_lo,
le32_to_cpu(xclient->broadcast_bytes_sent.lo));
UPDATE_EXTEND_XSTAT(unicast_pkts_sent,
total_unicast_packets_transmitted);
UPDATE_EXTEND_XSTAT(multicast_pkts_sent,
total_multicast_packets_transmitted);
UPDATE_EXTEND_XSTAT(broadcast_pkts_sent,
total_broadcast_packets_transmitted);
old_tclient->checksum_discard = tclient->checksum_discard;
old_tclient->ttl0_discard = tclient->ttl0_discard;
ADD_64(fstats->total_bytes_received_hi,
qstats->total_bytes_received_hi,
fstats->total_bytes_received_lo,
qstats->total_bytes_received_lo);
ADD_64(fstats->total_bytes_transmitted_hi,
qstats->total_bytes_transmitted_hi,
fstats->total_bytes_transmitted_lo,
qstats->total_bytes_transmitted_lo);
ADD_64(fstats->total_unicast_packets_received_hi,
qstats->total_unicast_packets_received_hi,
fstats->total_unicast_packets_received_lo,
qstats->total_unicast_packets_received_lo);
ADD_64(fstats->total_multicast_packets_received_hi,
qstats->total_multicast_packets_received_hi,
fstats->total_multicast_packets_received_lo,
qstats->total_multicast_packets_received_lo);
ADD_64(fstats->total_broadcast_packets_received_hi,
qstats->total_broadcast_packets_received_hi,
fstats->total_broadcast_packets_received_lo,
qstats->total_broadcast_packets_received_lo);
ADD_64(fstats->total_unicast_packets_transmitted_hi,
qstats->total_unicast_packets_transmitted_hi,
fstats->total_unicast_packets_transmitted_lo,
qstats->total_unicast_packets_transmitted_lo);
ADD_64(fstats->total_multicast_packets_transmitted_hi,
qstats->total_multicast_packets_transmitted_hi,
fstats->total_multicast_packets_transmitted_lo,
qstats->total_multicast_packets_transmitted_lo);
ADD_64(fstats->total_broadcast_packets_transmitted_hi,
qstats->total_broadcast_packets_transmitted_hi,
fstats->total_broadcast_packets_transmitted_lo,
qstats->total_broadcast_packets_transmitted_lo);
ADD_64(fstats->valid_bytes_received_hi,
qstats->valid_bytes_received_hi,
fstats->valid_bytes_received_lo,
qstats->valid_bytes_received_lo);
ADD_64(estats->error_bytes_received_hi,
qstats->error_bytes_received_hi,
estats->error_bytes_received_lo,
qstats->error_bytes_received_lo);
ADD_64(estats->etherstatsoverrsizepkts_hi,
qstats->etherstatsoverrsizepkts_hi,
estats->etherstatsoverrsizepkts_lo,
qstats->etherstatsoverrsizepkts_lo);
ADD_64(estats->no_buff_discard_hi, qstats->no_buff_discard_hi,
estats->no_buff_discard_lo, qstats->no_buff_discard_lo);
}
ADD_64(fstats->total_bytes_received_hi,
estats->rx_stat_ifhcinbadoctets_hi,
fstats->total_bytes_received_lo,
estats->rx_stat_ifhcinbadoctets_lo);
memcpy(estats, &(fstats->total_bytes_received_hi),
sizeof(struct host_func_stats) - 2*sizeof(u32));
ADD_64(estats->etherstatsoverrsizepkts_hi,
estats->rx_stat_dot3statsframestoolong_hi,
estats->etherstatsoverrsizepkts_lo,
estats->rx_stat_dot3statsframestoolong_lo);
ADD_64(estats->error_bytes_received_hi,
estats->rx_stat_ifhcinbadoctets_hi,
estats->error_bytes_received_lo,
estats->rx_stat_ifhcinbadoctets_lo);
if (bp->port.pmf) {
estats->mac_filter_discard =
le32_to_cpu(tport->mac_filter_discard);
estats->xxoverflow_discard =
le32_to_cpu(tport->xxoverflow_discard);
estats->brb_truncate_discard =
le32_to_cpu(tport->brb_truncate_discard);
estats->mac_discard = le32_to_cpu(tport->mac_discard);
}
fstats->host_func_stats_start = ++fstats->host_func_stats_end;
bp->stats_pending = 0;
return 0;
}
static void bnx2x_net_stats_update(struct bnx2x *bp)
{
struct bnx2x_eth_stats *estats = &bp->eth_stats;
struct net_device_stats *nstats = &bp->dev->stats;
int i;
nstats->rx_packets =
bnx2x_hilo(&estats->total_unicast_packets_received_hi) +
bnx2x_hilo(&estats->total_multicast_packets_received_hi) +
bnx2x_hilo(&estats->total_broadcast_packets_received_hi);
nstats->tx_packets =
bnx2x_hilo(&estats->total_unicast_packets_transmitted_hi) +
bnx2x_hilo(&estats->total_multicast_packets_transmitted_hi) +
bnx2x_hilo(&estats->total_broadcast_packets_transmitted_hi);
nstats->rx_bytes = bnx2x_hilo(&estats->total_bytes_received_hi);
nstats->tx_bytes = bnx2x_hilo(&estats->total_bytes_transmitted_hi);
nstats->rx_dropped = estats->mac_discard;
for_each_queue(bp, i)
nstats->rx_dropped +=
le32_to_cpu(bp->fp[i].old_tclient.checksum_discard);
nstats->tx_dropped = 0;
nstats->multicast =
bnx2x_hilo(&estats->total_multicast_packets_received_hi);
nstats->collisions =
bnx2x_hilo(&estats->tx_stat_etherstatscollisions_hi);
nstats->rx_length_errors =
bnx2x_hilo(&estats->rx_stat_etherstatsundersizepkts_hi) +
bnx2x_hilo(&estats->etherstatsoverrsizepkts_hi);
nstats->rx_over_errors = bnx2x_hilo(&estats->brb_drop_hi) +
bnx2x_hilo(&estats->brb_truncate_hi);
nstats->rx_crc_errors =
bnx2x_hilo(&estats->rx_stat_dot3statsfcserrors_hi);
nstats->rx_frame_errors =
bnx2x_hilo(&estats->rx_stat_dot3statsalignmenterrors_hi);
nstats->rx_fifo_errors = bnx2x_hilo(&estats->no_buff_discard_hi);
nstats->rx_missed_errors = estats->xxoverflow_discard;
nstats->rx_errors = nstats->rx_length_errors +
nstats->rx_over_errors +
nstats->rx_crc_errors +
nstats->rx_frame_errors +
nstats->rx_fifo_errors +
nstats->rx_missed_errors;
nstats->tx_aborted_errors =
bnx2x_hilo(&estats->tx_stat_dot3statslatecollisions_hi) +
bnx2x_hilo(&estats->tx_stat_dot3statsexcessivecollisions_hi);
nstats->tx_carrier_errors =
bnx2x_hilo(&estats->rx_stat_dot3statscarriersenseerrors_hi);
nstats->tx_fifo_errors = 0;
nstats->tx_heartbeat_errors = 0;
nstats->tx_window_errors = 0;
nstats->tx_errors = nstats->tx_aborted_errors +
nstats->tx_carrier_errors +
bnx2x_hilo(&estats->tx_stat_dot3statsinternalmactransmiterrors_hi);
}
static void bnx2x_drv_stats_update(struct bnx2x *bp)
{
struct bnx2x_eth_stats *estats = &bp->eth_stats;
int i;
estats->driver_xoff = 0;
estats->rx_err_discard_pkt = 0;
estats->rx_skb_alloc_failed = 0;
estats->hw_csum_err = 0;
for_each_queue(bp, i) {
struct bnx2x_eth_q_stats *qstats = &bp->fp[i].eth_q_stats;
estats->driver_xoff += qstats->driver_xoff;
estats->rx_err_discard_pkt += qstats->rx_err_discard_pkt;
estats->rx_skb_alloc_failed += qstats->rx_skb_alloc_failed;
estats->hw_csum_err += qstats->hw_csum_err;
}
}
static void bnx2x_stats_update(struct bnx2x *bp)
{
u32 *stats_comp = bnx2x_sp(bp, stats_comp);
if (*stats_comp != DMAE_COMP_VAL)
return;
if (bp->port.pmf)
bnx2x_hw_stats_update(bp);
if (bnx2x_storm_stats_update(bp) && (bp->stats_pending++ == 3)) {
BNX2X_ERR("storm stats were not updated for 3 times\n");
bnx2x_panic();
return;
}
bnx2x_net_stats_update(bp);
bnx2x_drv_stats_update(bp);
if (netif_msg_timer(bp)) {
struct bnx2x_eth_stats *estats = &bp->eth_stats;
int i;
printk(KERN_DEBUG "%s: brb drops %u brb truncate %u\n",
bp->dev->name,
estats->brb_drop_lo, estats->brb_truncate_lo);
for_each_queue(bp, i) {
struct bnx2x_fastpath *fp = &bp->fp[i];
struct bnx2x_eth_q_stats *qstats = &fp->eth_q_stats;
printk(KERN_DEBUG "%s: rx usage(%4u) *rx_cons_sb(%u)"
" rx pkt(%lu) rx calls(%lu %lu)\n",
fp->name, (le16_to_cpu(*fp->rx_cons_sb) -
fp->rx_comp_cons),
le16_to_cpu(*fp->rx_cons_sb),
bnx2x_hilo(&qstats->
total_unicast_packets_received_hi),
fp->rx_calls, fp->rx_pkt);
}
for_each_queue(bp, i) {
struct bnx2x_fastpath *fp = &bp->fp[i];
struct bnx2x_eth_q_stats *qstats = &fp->eth_q_stats;
struct netdev_queue *txq =
netdev_get_tx_queue(bp->dev, i);
printk(KERN_DEBUG "%s: tx avail(%4u) *tx_cons_sb(%u)"
" tx pkt(%lu) tx calls (%lu)"
" %s (Xoff events %u)\n",
fp->name, bnx2x_tx_avail(fp),
le16_to_cpu(*fp->tx_cons_sb),
bnx2x_hilo(&qstats->
total_unicast_packets_transmitted_hi),
fp->tx_pkt,
(netif_tx_queue_stopped(txq) ? "Xoff" : "Xon"),
qstats->driver_xoff);
}
}
bnx2x_hw_stats_post(bp);
bnx2x_storm_stats_post(bp);
}
static void bnx2x_port_stats_stop(struct bnx2x *bp)
{
struct dmae_command *dmae;
u32 opcode;
int loader_idx = PMF_DMAE_C(bp);
u32 *stats_comp = bnx2x_sp(bp, stats_comp);
bp->executer_idx = 0;
opcode = (DMAE_CMD_SRC_PCI | DMAE_CMD_DST_GRC |
DMAE_CMD_C_ENABLE |
DMAE_CMD_SRC_RESET | DMAE_CMD_DST_RESET |
#ifdef __BIG_ENDIAN
DMAE_CMD_ENDIANITY_B_DW_SWAP |
#else
DMAE_CMD_ENDIANITY_DW_SWAP |
#endif
(BP_PORT(bp) ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0) |
(BP_E1HVN(bp) << DMAE_CMD_E1HVN_SHIFT));
if (bp->port.port_stx) {
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
if (bp->func_stx)
dmae->opcode = (opcode | DMAE_CMD_C_DST_GRC);
else
dmae->opcode = (opcode | DMAE_CMD_C_DST_PCI);
dmae->src_addr_lo = U64_LO(bnx2x_sp_mapping(bp, port_stats));
dmae->src_addr_hi = U64_HI(bnx2x_sp_mapping(bp, port_stats));
dmae->dst_addr_lo = bp->port.port_stx >> 2;
dmae->dst_addr_hi = 0;
dmae->len = sizeof(struct host_port_stats) >> 2;
if (bp->func_stx) {
dmae->comp_addr_lo = dmae_reg_go_c[loader_idx] >> 2;
dmae->comp_addr_hi = 0;
dmae->comp_val = 1;
} else {
dmae->comp_addr_lo =
U64_LO(bnx2x_sp_mapping(bp, stats_comp));
dmae->comp_addr_hi =
U64_HI(bnx2x_sp_mapping(bp, stats_comp));
dmae->comp_val = DMAE_COMP_VAL;
*stats_comp = 0;
}
}
if (bp->func_stx) {
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
dmae->opcode = (opcode | DMAE_CMD_C_DST_PCI);
dmae->src_addr_lo = U64_LO(bnx2x_sp_mapping(bp, func_stats));
dmae->src_addr_hi = U64_HI(bnx2x_sp_mapping(bp, func_stats));
dmae->dst_addr_lo = bp->func_stx >> 2;
dmae->dst_addr_hi = 0;
dmae->len = sizeof(struct host_func_stats) >> 2;
dmae->comp_addr_lo = U64_LO(bnx2x_sp_mapping(bp, stats_comp));
dmae->comp_addr_hi = U64_HI(bnx2x_sp_mapping(bp, stats_comp));
dmae->comp_val = DMAE_COMP_VAL;
*stats_comp = 0;
}
}
static void bnx2x_stats_stop(struct bnx2x *bp)
{
int update = 0;
bnx2x_stats_comp(bp);
if (bp->port.pmf)
update = (bnx2x_hw_stats_update(bp) == 0);
update |= (bnx2x_storm_stats_update(bp) == 0);
if (update) {
bnx2x_net_stats_update(bp);
if (bp->port.pmf)
bnx2x_port_stats_stop(bp);
bnx2x_hw_stats_post(bp);
bnx2x_stats_comp(bp);
}
}
static void bnx2x_stats_do_nothing(struct bnx2x *bp)
{
}
static const struct {
void (*action)(struct bnx2x *bp);
enum bnx2x_stats_state next_state;
} bnx2x_stats_stm[STATS_STATE_MAX][STATS_EVENT_MAX] = {
/* state event */
{
/* DISABLED PMF */ {bnx2x_stats_pmf_update, STATS_STATE_DISABLED},
/* LINK_UP */ {bnx2x_stats_start, STATS_STATE_ENABLED},
/* UPDATE */ {bnx2x_stats_do_nothing, STATS_STATE_DISABLED},
/* STOP */ {bnx2x_stats_do_nothing, STATS_STATE_DISABLED}
},
{
/* ENABLED PMF */ {bnx2x_stats_pmf_start, STATS_STATE_ENABLED},
/* LINK_UP */ {bnx2x_stats_restart, STATS_STATE_ENABLED},
/* UPDATE */ {bnx2x_stats_update, STATS_STATE_ENABLED},
/* STOP */ {bnx2x_stats_stop, STATS_STATE_DISABLED}
}
};
static void bnx2x_stats_handle(struct bnx2x *bp, enum bnx2x_stats_event event)
{
enum bnx2x_stats_state state;
if (unlikely(bp->panic))
return;
/* Protect a state change flow */
spin_lock_bh(&bp->stats_lock);
state = bp->stats_state;
bp->stats_state = bnx2x_stats_stm[state][event].next_state;
spin_unlock_bh(&bp->stats_lock);
bnx2x_stats_stm[state][event].action(bp);
if ((event != STATS_EVENT_UPDATE) || netif_msg_timer(bp))
DP(BNX2X_MSG_STATS, "state %d -> event %d -> state %d\n",
state, event, bp->stats_state);
}
static void bnx2x_port_stats_base_init(struct bnx2x *bp)
{
struct dmae_command *dmae;
u32 *stats_comp = bnx2x_sp(bp, stats_comp);
/* sanity */
if (!bp->port.pmf || !bp->port.port_stx) {
BNX2X_ERR("BUG!\n");
return;
}
bp->executer_idx = 0;
dmae = bnx2x_sp(bp, dmae[bp->executer_idx++]);
dmae->opcode = (DMAE_CMD_SRC_PCI | DMAE_CMD_DST_GRC |
DMAE_CMD_C_DST_PCI | DMAE_CMD_C_ENABLE |
DMAE_CMD_SRC_RESET | DMAE_CMD_DST_RESET |
#ifdef __BIG_ENDIAN
DMAE_CMD_ENDIANITY_B_DW_SWAP |
#else
DMAE_CMD_ENDIANITY_DW_SWAP |
#endif
(BP_PORT(bp) ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0) |
(BP_E1HVN(bp) << DMAE_CMD_E1HVN_SHIFT));
dmae->src_addr_lo = U64_LO(bnx2x_sp_mapping(bp, port_stats));
dmae->src_addr_hi = U64_HI(bnx2x_sp_mapping(bp, port_stats));
dmae->dst_addr_lo = bp->port.port_stx >> 2;
dmae->dst_addr_hi = 0;
dmae->len = sizeof(struct host_port_stats) >> 2;
dmae->comp_addr_lo = U64_LO(bnx2x_sp_mapping(bp, stats_comp));
dmae->comp_addr_hi = U64_HI(bnx2x_sp_mapping(bp, stats_comp));
dmae->comp_val = DMAE_COMP_VAL;
*stats_comp = 0;
bnx2x_hw_stats_post(bp);
bnx2x_stats_comp(bp);
}
static void bnx2x_func_stats_base_init(struct bnx2x *bp)
{
int vn, vn_max = IS_E1HMF(bp) ? E1HVN_MAX : E1VN_MAX;
int port = BP_PORT(bp);
int func;
u32 func_stx;
/* sanity */
if (!bp->port.pmf || !bp->func_stx) {
BNX2X_ERR("BUG!\n");
return;
}
/* save our func_stx */
func_stx = bp->func_stx;
for (vn = VN_0; vn < vn_max; vn++) {
func = 2*vn + port;
bp->func_stx = SHMEM_RD(bp, func_mb[func].fw_mb_param);
bnx2x_func_stats_init(bp);
bnx2x_hw_stats_post(bp);
bnx2x_stats_comp(bp);
}
/* restore our func_stx */
bp->func_stx = func_stx;
}
static void bnx2x_func_stats_base_update(struct bnx2x *bp)
{
struct dmae_command *dmae = &bp->stats_dmae;
u32 *stats_comp = bnx2x_sp(bp, stats_comp);
/* sanity */
if (!bp->func_stx) {
BNX2X_ERR("BUG!\n");
return;
}
bp->executer_idx = 0;
memset(dmae, 0, sizeof(struct dmae_command));
dmae->opcode = (DMAE_CMD_SRC_GRC | DMAE_CMD_DST_PCI |
DMAE_CMD_C_DST_PCI | DMAE_CMD_C_ENABLE |
DMAE_CMD_SRC_RESET | DMAE_CMD_DST_RESET |
#ifdef __BIG_ENDIAN
DMAE_CMD_ENDIANITY_B_DW_SWAP |
#else
DMAE_CMD_ENDIANITY_DW_SWAP |
#endif
(BP_PORT(bp) ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0) |
(BP_E1HVN(bp) << DMAE_CMD_E1HVN_SHIFT));
dmae->src_addr_lo = bp->func_stx >> 2;
dmae->src_addr_hi = 0;
dmae->dst_addr_lo = U64_LO(bnx2x_sp_mapping(bp, func_stats_base));
dmae->dst_addr_hi = U64_HI(bnx2x_sp_mapping(bp, func_stats_base));
dmae->len = sizeof(struct host_func_stats) >> 2;
dmae->comp_addr_lo = U64_LO(bnx2x_sp_mapping(bp, stats_comp));
dmae->comp_addr_hi = U64_HI(bnx2x_sp_mapping(bp, stats_comp));
dmae->comp_val = DMAE_COMP_VAL;
*stats_comp = 0;
bnx2x_hw_stats_post(bp);
bnx2x_stats_comp(bp);
}
static void bnx2x_stats_init(struct bnx2x *bp)
{
int port = BP_PORT(bp);
int func = BP_FUNC(bp);
int i;
bp->stats_pending = 0;
bp->executer_idx = 0;
bp->stats_counter = 0;
/* port and func stats for management */
if (!BP_NOMCP(bp)) {
bp->port.port_stx = SHMEM_RD(bp, port_mb[port].port_stx);
bp->func_stx = SHMEM_RD(bp, func_mb[func].fw_mb_param);
} else {
bp->port.port_stx = 0;
bp->func_stx = 0;
}
DP(BNX2X_MSG_STATS, "port_stx 0x%x func_stx 0x%x\n",
bp->port.port_stx, bp->func_stx);
/* port stats */
memset(&(bp->port.old_nig_stats), 0, sizeof(struct nig_stats));
bp->port.old_nig_stats.brb_discard =
REG_RD(bp, NIG_REG_STAT0_BRB_DISCARD + port*0x38);
bp->port.old_nig_stats.brb_truncate =
REG_RD(bp, NIG_REG_STAT0_BRB_TRUNCATE + port*0x38);
REG_RD_DMAE(bp, NIG_REG_STAT0_EGRESS_MAC_PKT0 + port*0x50,
&(bp->port.old_nig_stats.egress_mac_pkt0_lo), 2);
REG_RD_DMAE(bp, NIG_REG_STAT0_EGRESS_MAC_PKT1 + port*0x50,
&(bp->port.old_nig_stats.egress_mac_pkt1_lo), 2);
/* function stats */
for_each_queue(bp, i) {
struct bnx2x_fastpath *fp = &bp->fp[i];
memset(&fp->old_tclient, 0,
sizeof(struct tstorm_per_client_stats));
memset(&fp->old_uclient, 0,
sizeof(struct ustorm_per_client_stats));
memset(&fp->old_xclient, 0,
sizeof(struct xstorm_per_client_stats));
memset(&fp->eth_q_stats, 0, sizeof(struct bnx2x_eth_q_stats));
}
memset(&bp->dev->stats, 0, sizeof(struct net_device_stats));
memset(&bp->eth_stats, 0, sizeof(struct bnx2x_eth_stats));
bp->stats_state = STATS_STATE_DISABLED;
if (bp->port.pmf) {
if (bp->port.port_stx)
bnx2x_port_stats_base_init(bp);
if (bp->func_stx)
bnx2x_func_stats_base_init(bp);
} else if (bp->func_stx)
bnx2x_func_stats_base_update(bp);
}
static void bnx2x_timer(unsigned long data)
{
struct bnx2x *bp = (struct bnx2x *) data;
if (!netif_running(bp->dev))
return;
if (atomic_read(&bp->intr_sem) != 0)
goto timer_restart;
if (poll) {
struct bnx2x_fastpath *fp = &bp->fp[0];
int rc;
bnx2x_tx_int(fp);
rc = bnx2x_rx_int(fp, 1000);
}
if (!BP_NOMCP(bp)) {
int func = BP_FUNC(bp);
u32 drv_pulse;
u32 mcp_pulse;
++bp->fw_drv_pulse_wr_seq;
bp->fw_drv_pulse_wr_seq &= DRV_PULSE_SEQ_MASK;
/* TBD - add SYSTEM_TIME */
drv_pulse = bp->fw_drv_pulse_wr_seq;
SHMEM_WR(bp, func_mb[func].drv_pulse_mb, drv_pulse);
mcp_pulse = (SHMEM_RD(bp, func_mb[func].mcp_pulse_mb) &
MCP_PULSE_SEQ_MASK);
/* The delta between driver pulse and mcp response
* should be 1 (before mcp response) or 0 (after mcp response)
*/
if ((drv_pulse != mcp_pulse) &&
(drv_pulse != ((mcp_pulse + 1) & MCP_PULSE_SEQ_MASK))) {
/* someone lost a heartbeat... */
BNX2X_ERR("drv_pulse (0x%x) != mcp_pulse (0x%x)\n",
drv_pulse, mcp_pulse);
}
}
if (bp->state == BNX2X_STATE_OPEN)
bnx2x_stats_handle(bp, STATS_EVENT_UPDATE);
timer_restart:
mod_timer(&bp->timer, jiffies + bp->current_interval);
}
/* end of Statistics */
/* nic init */
/*
* nic init service functions
*/
static void bnx2x_zero_sb(struct bnx2x *bp, int sb_id)
{
int port = BP_PORT(bp);
/* "CSTORM" */
bnx2x_init_fill(bp, CSEM_REG_FAST_MEMORY +
CSTORM_SB_HOST_STATUS_BLOCK_U_OFFSET(port, sb_id), 0,
CSTORM_SB_STATUS_BLOCK_U_SIZE / 4);
bnx2x_init_fill(bp, CSEM_REG_FAST_MEMORY +
CSTORM_SB_HOST_STATUS_BLOCK_C_OFFSET(port, sb_id), 0,
CSTORM_SB_STATUS_BLOCK_C_SIZE / 4);
}
static void bnx2x_init_sb(struct bnx2x *bp, struct host_status_block *sb,
dma_addr_t mapping, int sb_id)
{
int port = BP_PORT(bp);
int func = BP_FUNC(bp);
int index;
u64 section;
/* USTORM */
section = ((u64)mapping) + offsetof(struct host_status_block,
u_status_block);
sb->u_status_block.status_block_id = sb_id;
REG_WR(bp, BAR_CSTRORM_INTMEM +
CSTORM_SB_HOST_SB_ADDR_U_OFFSET(port, sb_id), U64_LO(section));
REG_WR(bp, BAR_CSTRORM_INTMEM +
((CSTORM_SB_HOST_SB_ADDR_U_OFFSET(port, sb_id)) + 4),
U64_HI(section));
REG_WR8(bp, BAR_CSTRORM_INTMEM + FP_USB_FUNC_OFF +
CSTORM_SB_HOST_STATUS_BLOCK_U_OFFSET(port, sb_id), func);
for (index = 0; index < HC_USTORM_SB_NUM_INDICES; index++)
REG_WR16(bp, BAR_CSTRORM_INTMEM +
CSTORM_SB_HC_DISABLE_U_OFFSET(port, sb_id, index), 1);
/* CSTORM */
section = ((u64)mapping) + offsetof(struct host_status_block,
c_status_block);
sb->c_status_block.status_block_id = sb_id;
REG_WR(bp, BAR_CSTRORM_INTMEM +
CSTORM_SB_HOST_SB_ADDR_C_OFFSET(port, sb_id), U64_LO(section));
REG_WR(bp, BAR_CSTRORM_INTMEM +
((CSTORM_SB_HOST_SB_ADDR_C_OFFSET(port, sb_id)) + 4),
U64_HI(section));
REG_WR8(bp, BAR_CSTRORM_INTMEM + FP_CSB_FUNC_OFF +
CSTORM_SB_HOST_STATUS_BLOCK_C_OFFSET(port, sb_id), func);
for (index = 0; index < HC_CSTORM_SB_NUM_INDICES; index++)
REG_WR16(bp, BAR_CSTRORM_INTMEM +
CSTORM_SB_HC_DISABLE_C_OFFSET(port, sb_id, index), 1);
bnx2x_ack_sb(bp, sb_id, CSTORM_ID, 0, IGU_INT_ENABLE, 0);
}
static void bnx2x_zero_def_sb(struct bnx2x *bp)
{
int func = BP_FUNC(bp);
bnx2x_init_fill(bp, TSEM_REG_FAST_MEMORY +
TSTORM_DEF_SB_HOST_STATUS_BLOCK_OFFSET(func), 0,
sizeof(struct tstorm_def_status_block)/4);
bnx2x_init_fill(bp, CSEM_REG_FAST_MEMORY +
CSTORM_DEF_SB_HOST_STATUS_BLOCK_U_OFFSET(func), 0,
sizeof(struct cstorm_def_status_block_u)/4);
bnx2x_init_fill(bp, CSEM_REG_FAST_MEMORY +
CSTORM_DEF_SB_HOST_STATUS_BLOCK_C_OFFSET(func), 0,
sizeof(struct cstorm_def_status_block_c)/4);
bnx2x_init_fill(bp, XSEM_REG_FAST_MEMORY +
XSTORM_DEF_SB_HOST_STATUS_BLOCK_OFFSET(func), 0,
sizeof(struct xstorm_def_status_block)/4);
}
static void bnx2x_init_def_sb(struct bnx2x *bp,
struct host_def_status_block *def_sb,
dma_addr_t mapping, int sb_id)
{
int port = BP_PORT(bp);
int func = BP_FUNC(bp);
int index, val, reg_offset;
u64 section;
/* ATTN */
section = ((u64)mapping) + offsetof(struct host_def_status_block,
atten_status_block);
def_sb->atten_status_block.status_block_id = sb_id;
bp->attn_state = 0;
reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0);
for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
bp->attn_group[index].sig[0] = REG_RD(bp,
reg_offset + 0x10*index);
bp->attn_group[index].sig[1] = REG_RD(bp,
reg_offset + 0x4 + 0x10*index);
bp->attn_group[index].sig[2] = REG_RD(bp,
reg_offset + 0x8 + 0x10*index);
bp->attn_group[index].sig[3] = REG_RD(bp,
reg_offset + 0xc + 0x10*index);
}
reg_offset = (port ? HC_REG_ATTN_MSG1_ADDR_L :
HC_REG_ATTN_MSG0_ADDR_L);
REG_WR(bp, reg_offset, U64_LO(section));
REG_WR(bp, reg_offset + 4, U64_HI(section));
reg_offset = (port ? HC_REG_ATTN_NUM_P1 : HC_REG_ATTN_NUM_P0);
val = REG_RD(bp, reg_offset);
val |= sb_id;
REG_WR(bp, reg_offset, val);
/* USTORM */
section = ((u64)mapping) + offsetof(struct host_def_status_block,
u_def_status_block);
def_sb->u_def_status_block.status_block_id = sb_id;
REG_WR(bp, BAR_CSTRORM_INTMEM +
CSTORM_DEF_SB_HOST_SB_ADDR_U_OFFSET(func), U64_LO(section));
REG_WR(bp, BAR_CSTRORM_INTMEM +
((CSTORM_DEF_SB_HOST_SB_ADDR_U_OFFSET(func)) + 4),
U64_HI(section));
REG_WR8(bp, BAR_CSTRORM_INTMEM + DEF_USB_FUNC_OFF +
CSTORM_DEF_SB_HOST_STATUS_BLOCK_U_OFFSET(func), func);
for (index = 0; index < HC_USTORM_DEF_SB_NUM_INDICES; index++)
REG_WR16(bp, BAR_CSTRORM_INTMEM +
CSTORM_DEF_SB_HC_DISABLE_U_OFFSET(func, index), 1);
/* CSTORM */
section = ((u64)mapping) + offsetof(struct host_def_status_block,
c_def_status_block);
def_sb->c_def_status_block.status_block_id = sb_id;
REG_WR(bp, BAR_CSTRORM_INTMEM +
CSTORM_DEF_SB_HOST_SB_ADDR_C_OFFSET(func), U64_LO(section));
REG_WR(bp, BAR_CSTRORM_INTMEM +
((CSTORM_DEF_SB_HOST_SB_ADDR_C_OFFSET(func)) + 4),
U64_HI(section));
REG_WR8(bp, BAR_CSTRORM_INTMEM + DEF_CSB_FUNC_OFF +
CSTORM_DEF_SB_HOST_STATUS_BLOCK_C_OFFSET(func), func);
for (index = 0; index < HC_CSTORM_DEF_SB_NUM_INDICES; index++)
REG_WR16(bp, BAR_CSTRORM_INTMEM +
CSTORM_DEF_SB_HC_DISABLE_C_OFFSET(func, index), 1);
/* TSTORM */
section = ((u64)mapping) + offsetof(struct host_def_status_block,
t_def_status_block);
def_sb->t_def_status_block.status_block_id = sb_id;
REG_WR(bp, BAR_TSTRORM_INTMEM +
TSTORM_DEF_SB_HOST_SB_ADDR_OFFSET(func), U64_LO(section));
REG_WR(bp, BAR_TSTRORM_INTMEM +
((TSTORM_DEF_SB_HOST_SB_ADDR_OFFSET(func)) + 4),
U64_HI(section));
REG_WR8(bp, BAR_TSTRORM_INTMEM + DEF_TSB_FUNC_OFF +
TSTORM_DEF_SB_HOST_STATUS_BLOCK_OFFSET(func), func);
for (index = 0; index < HC_TSTORM_DEF_SB_NUM_INDICES; index++)
REG_WR16(bp, BAR_TSTRORM_INTMEM +
TSTORM_DEF_SB_HC_DISABLE_OFFSET(func, index), 1);
/* XSTORM */
section = ((u64)mapping) + offsetof(struct host_def_status_block,
x_def_status_block);
def_sb->x_def_status_block.status_block_id = sb_id;
REG_WR(bp, BAR_XSTRORM_INTMEM +
XSTORM_DEF_SB_HOST_SB_ADDR_OFFSET(func), U64_LO(section));
REG_WR(bp, BAR_XSTRORM_INTMEM +
((XSTORM_DEF_SB_HOST_SB_ADDR_OFFSET(func)) + 4),
U64_HI(section));
REG_WR8(bp, BAR_XSTRORM_INTMEM + DEF_XSB_FUNC_OFF +
XSTORM_DEF_SB_HOST_STATUS_BLOCK_OFFSET(func), func);
for (index = 0; index < HC_XSTORM_DEF_SB_NUM_INDICES; index++)
REG_WR16(bp, BAR_XSTRORM_INTMEM +
XSTORM_DEF_SB_HC_DISABLE_OFFSET(func, index), 1);
bp->stats_pending = 0;
bp->set_mac_pending = 0;
bnx2x_ack_sb(bp, sb_id, CSTORM_ID, 0, IGU_INT_ENABLE, 0);
}
static void bnx2x_update_coalesce(struct bnx2x *bp)
{
int port = BP_PORT(bp);
int i;
for_each_queue(bp, i) {
int sb_id = bp->fp[i].sb_id;
/* HC_INDEX_U_ETH_RX_CQ_CONS */
REG_WR8(bp, BAR_CSTRORM_INTMEM +
CSTORM_SB_HC_TIMEOUT_U_OFFSET(port, sb_id,
U_SB_ETH_RX_CQ_INDEX),
bp->rx_ticks/(4 * BNX2X_BTR));
REG_WR16(bp, BAR_CSTRORM_INTMEM +
CSTORM_SB_HC_DISABLE_U_OFFSET(port, sb_id,
U_SB_ETH_RX_CQ_INDEX),
(bp->rx_ticks/(4 * BNX2X_BTR)) ? 0 : 1);
/* HC_INDEX_C_ETH_TX_CQ_CONS */
REG_WR8(bp, BAR_CSTRORM_INTMEM +
CSTORM_SB_HC_TIMEOUT_C_OFFSET(port, sb_id,
C_SB_ETH_TX_CQ_INDEX),
bp->tx_ticks/(4 * BNX2X_BTR));
REG_WR16(bp, BAR_CSTRORM_INTMEM +
CSTORM_SB_HC_DISABLE_C_OFFSET(port, sb_id,
C_SB_ETH_TX_CQ_INDEX),
(bp->tx_ticks/(4 * BNX2X_BTR)) ? 0 : 1);
}
}
static inline void bnx2x_free_tpa_pool(struct bnx2x *bp,
struct bnx2x_fastpath *fp, int last)
{
int i;
for (i = 0; i < last; i++) {
struct sw_rx_bd *rx_buf = &(fp->tpa_pool[i]);
struct sk_buff *skb = rx_buf->skb;
if (skb == NULL) {
DP(NETIF_MSG_IFDOWN, "tpa bin %d empty on free\n", i);
continue;
}
if (fp->tpa_state[i] == BNX2X_TPA_START)
dma_unmap_single(&bp->pdev->dev,
dma_unmap_addr(rx_buf, mapping),
bp->rx_buf_size, DMA_FROM_DEVICE);
dev_kfree_skb(skb);
rx_buf->skb = NULL;
}
}
static void bnx2x_init_rx_rings(struct bnx2x *bp)
{
int func = BP_FUNC(bp);
int max_agg_queues = CHIP_IS_E1(bp) ? ETH_MAX_AGGREGATION_QUEUES_E1 :
ETH_MAX_AGGREGATION_QUEUES_E1H;
u16 ring_prod, cqe_ring_prod;
int i, j;
bp->rx_buf_size = bp->dev->mtu + ETH_OVREHEAD + BNX2X_RX_ALIGN;
DP(NETIF_MSG_IFUP,
"mtu %d rx_buf_size %d\n", bp->dev->mtu, bp->rx_buf_size);
if (bp->flags & TPA_ENABLE_FLAG) {
for_each_queue(bp, j) {
struct bnx2x_fastpath *fp = &bp->fp[j];
for (i = 0; i < max_agg_queues; i++) {
fp->tpa_pool[i].skb =
netdev_alloc_skb(bp->dev, bp->rx_buf_size);
if (!fp->tpa_pool[i].skb) {
BNX2X_ERR("Failed to allocate TPA "
"skb pool for queue[%d] - "
"disabling TPA on this "
"queue!\n", j);
bnx2x_free_tpa_pool(bp, fp, i);
fp->disable_tpa = 1;
break;
}
dma_unmap_addr_set((struct sw_rx_bd *)
&bp->fp->tpa_pool[i],
mapping, 0);
fp->tpa_state[i] = BNX2X_TPA_STOP;
}
}
}
for_each_queue(bp, j) {
struct bnx2x_fastpath *fp = &bp->fp[j];
fp->rx_bd_cons = 0;
fp->rx_cons_sb = BNX2X_RX_SB_INDEX;
fp->rx_bd_cons_sb = BNX2X_RX_SB_BD_INDEX;
/* "next page" elements initialization */
/* SGE ring */
for (i = 1; i <= NUM_RX_SGE_PAGES; i++) {
struct eth_rx_sge *sge;
sge = &fp->rx_sge_ring[RX_SGE_CNT * i - 2];
sge->addr_hi =
cpu_to_le32(U64_HI(fp->rx_sge_mapping +
BCM_PAGE_SIZE*(i % NUM_RX_SGE_PAGES)));
sge->addr_lo =
cpu_to_le32(U64_LO(fp->rx_sge_mapping +
BCM_PAGE_SIZE*(i % NUM_RX_SGE_PAGES)));
}
bnx2x_init_sge_ring_bit_mask(fp);
/* RX BD ring */
for (i = 1; i <= NUM_RX_RINGS; i++) {
struct eth_rx_bd *rx_bd;
rx_bd = &fp->rx_desc_ring[RX_DESC_CNT * i - 2];
rx_bd->addr_hi =
cpu_to_le32(U64_HI(fp->rx_desc_mapping +
BCM_PAGE_SIZE*(i % NUM_RX_RINGS)));
rx_bd->addr_lo =
cpu_to_le32(U64_LO(fp->rx_desc_mapping +
BCM_PAGE_SIZE*(i % NUM_RX_RINGS)));
}
/* CQ ring */
for (i = 1; i <= NUM_RCQ_RINGS; i++) {
struct eth_rx_cqe_next_page *nextpg;
nextpg = (struct eth_rx_cqe_next_page *)
&fp->rx_comp_ring[RCQ_DESC_CNT * i - 1];
nextpg->addr_hi =
cpu_to_le32(U64_HI(fp->rx_comp_mapping +
BCM_PAGE_SIZE*(i % NUM_RCQ_RINGS)));
nextpg->addr_lo =
cpu_to_le32(U64_LO(fp->rx_comp_mapping +
BCM_PAGE_SIZE*(i % NUM_RCQ_RINGS)));
}
/* Allocate SGEs and initialize the ring elements */
for (i = 0, ring_prod = 0;
i < MAX_RX_SGE_CNT*NUM_RX_SGE_PAGES; i++) {
if (bnx2x_alloc_rx_sge(bp, fp, ring_prod) < 0) {
BNX2X_ERR("was only able to allocate "
"%d rx sges\n", i);
BNX2X_ERR("disabling TPA for queue[%d]\n", j);
/* Cleanup already allocated elements */
bnx2x_free_rx_sge_range(bp, fp, ring_prod);
bnx2x_free_tpa_pool(bp, fp, max_agg_queues);
fp->disable_tpa = 1;
ring_prod = 0;
break;
}
ring_prod = NEXT_SGE_IDX(ring_prod);
}
fp->rx_sge_prod = ring_prod;
/* Allocate BDs and initialize BD ring */
fp->rx_comp_cons = 0;
cqe_ring_prod = ring_prod = 0;
for (i = 0; i < bp->rx_ring_size; i++) {
if (bnx2x_alloc_rx_skb(bp, fp, ring_prod) < 0) {
BNX2X_ERR("was only able to allocate "
"%d rx skbs on queue[%d]\n", i, j);
fp->eth_q_stats.rx_skb_alloc_failed++;
break;
}
ring_prod = NEXT_RX_IDX(ring_prod);
cqe_ring_prod = NEXT_RCQ_IDX(cqe_ring_prod);
WARN_ON(ring_prod <= i);
}
fp->rx_bd_prod = ring_prod;
/* must not have more available CQEs than BDs */
fp->rx_comp_prod = min_t(u16, NUM_RCQ_RINGS*RCQ_DESC_CNT,
cqe_ring_prod);
fp->rx_pkt = fp->rx_calls = 0;
/* Warning!
* this will generate an interrupt (to the TSTORM)
* must only be done after chip is initialized
*/
bnx2x_update_rx_prod(bp, fp, ring_prod, fp->rx_comp_prod,
fp->rx_sge_prod);
if (j != 0)
continue;
REG_WR(bp, BAR_USTRORM_INTMEM +
USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(func),
U64_LO(fp->rx_comp_mapping));
REG_WR(bp, BAR_USTRORM_INTMEM +
USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(func) + 4,
U64_HI(fp->rx_comp_mapping));
}
}
static void bnx2x_init_tx_ring(struct bnx2x *bp)
{
int i, j;
for_each_queue(bp, j) {
struct bnx2x_fastpath *fp = &bp->fp[j];
for (i = 1; i <= NUM_TX_RINGS; i++) {
struct eth_tx_next_bd *tx_next_bd =
&fp->tx_desc_ring[TX_DESC_CNT * i - 1].next_bd;
tx_next_bd->addr_hi =
cpu_to_le32(U64_HI(fp->tx_desc_mapping +
BCM_PAGE_SIZE*(i % NUM_TX_RINGS)));
tx_next_bd->addr_lo =
cpu_to_le32(U64_LO(fp->tx_desc_mapping +
BCM_PAGE_SIZE*(i % NUM_TX_RINGS)));
}
fp->tx_db.data.header.header = DOORBELL_HDR_DB_TYPE;
fp->tx_db.data.zero_fill1 = 0;
fp->tx_db.data.prod = 0;
fp->tx_pkt_prod = 0;
fp->tx_pkt_cons = 0;
fp->tx_bd_prod = 0;
fp->tx_bd_cons = 0;
fp->tx_cons_sb = BNX2X_TX_SB_INDEX;
fp->tx_pkt = 0;
}
}
static void bnx2x_init_sp_ring(struct bnx2x *bp)
{
int func = BP_FUNC(bp);
spin_lock_init(&bp->spq_lock);
bp->spq_left = MAX_SPQ_PENDING;
bp->spq_prod_idx = 0;
bp->dsb_sp_prod = BNX2X_SP_DSB_INDEX;
bp->spq_prod_bd = bp->spq;
bp->spq_last_bd = bp->spq_prod_bd + MAX_SP_DESC_CNT;
REG_WR(bp, XSEM_REG_FAST_MEMORY + XSTORM_SPQ_PAGE_BASE_OFFSET(func),
U64_LO(bp->spq_mapping));
REG_WR(bp,
XSEM_REG_FAST_MEMORY + XSTORM_SPQ_PAGE_BASE_OFFSET(func) + 4,
U64_HI(bp->spq_mapping));
REG_WR(bp, XSEM_REG_FAST_MEMORY + XSTORM_SPQ_PROD_OFFSET(func),
bp->spq_prod_idx);
}
static void bnx2x_init_context(struct bnx2x *bp)
{
int i;
/* Rx */
for_each_queue(bp, i) {
struct eth_context *context = bnx2x_sp(bp, context[i].eth);
struct bnx2x_fastpath *fp = &bp->fp[i];
u8 cl_id = fp->cl_id;
context->ustorm_st_context.common.sb_index_numbers =
BNX2X_RX_SB_INDEX_NUM;
context->ustorm_st_context.common.clientId = cl_id;
context->ustorm_st_context.common.status_block_id = fp->sb_id;
context->ustorm_st_context.common.flags =
(USTORM_ETH_ST_CONTEXT_CONFIG_ENABLE_MC_ALIGNMENT |
USTORM_ETH_ST_CONTEXT_CONFIG_ENABLE_STATISTICS);
context->ustorm_st_context.common.statistics_counter_id =
cl_id;
context->ustorm_st_context.common.mc_alignment_log_size =
BNX2X_RX_ALIGN_SHIFT;
context->ustorm_st_context.common.bd_buff_size =
bp->rx_buf_size;
context->ustorm_st_context.common.bd_page_base_hi =
U64_HI(fp->rx_desc_mapping);
context->ustorm_st_context.common.bd_page_base_lo =
U64_LO(fp->rx_desc_mapping);
if (!fp->disable_tpa) {
context->ustorm_st_context.common.flags |=
USTORM_ETH_ST_CONTEXT_CONFIG_ENABLE_TPA;
context->ustorm_st_context.common.sge_buff_size =
(u16)min_t(u32, SGE_PAGE_SIZE*PAGES_PER_SGE,
0xffff);
context->ustorm_st_context.common.sge_page_base_hi =
U64_HI(fp->rx_sge_mapping);
context->ustorm_st_context.common.sge_page_base_lo =
U64_LO(fp->rx_sge_mapping);
context->ustorm_st_context.common.max_sges_for_packet =
SGE_PAGE_ALIGN(bp->dev->mtu) >> SGE_PAGE_SHIFT;
context->ustorm_st_context.common.max_sges_for_packet =
((context->ustorm_st_context.common.
max_sges_for_packet + PAGES_PER_SGE - 1) &
(~(PAGES_PER_SGE - 1))) >> PAGES_PER_SGE_SHIFT;
}
context->ustorm_ag_context.cdu_usage =
CDU_RSRVD_VALUE_TYPE_A(HW_CID(bp, i),
CDU_REGION_NUMBER_UCM_AG,
ETH_CONNECTION_TYPE);
context->xstorm_ag_context.cdu_reserved =
CDU_RSRVD_VALUE_TYPE_A(HW_CID(bp, i),
CDU_REGION_NUMBER_XCM_AG,
ETH_CONNECTION_TYPE);
}
/* Tx */
for_each_queue(bp, i) {
struct bnx2x_fastpath *fp = &bp->fp[i];
struct eth_context *context =
bnx2x_sp(bp, context[i].eth);
context->cstorm_st_context.sb_index_number =
C_SB_ETH_TX_CQ_INDEX;
context->cstorm_st_context.status_block_id = fp->sb_id;
context->xstorm_st_context.tx_bd_page_base_hi =
U64_HI(fp->tx_desc_mapping);
context->xstorm_st_context.tx_bd_page_base_lo =
U64_LO(fp->tx_desc_mapping);
context->xstorm_st_context.statistics_data = (fp->cl_id |
XSTORM_ETH_ST_CONTEXT_STATISTICS_ENABLE);
}
}
static void bnx2x_init_ind_table(struct bnx2x *bp)
{
int func = BP_FUNC(bp);
int i;
if (bp->multi_mode == ETH_RSS_MODE_DISABLED)
return;
DP(NETIF_MSG_IFUP,
"Initializing indirection table multi_mode %d\n", bp->multi_mode);
for (i = 0; i < TSTORM_INDIRECTION_TABLE_SIZE; i++)
REG_WR8(bp, BAR_TSTRORM_INTMEM +
TSTORM_INDIRECTION_TABLE_OFFSET(func) + i,
bp->fp->cl_id + (i % bp->num_queues));
}
static void bnx2x_set_client_config(struct bnx2x *bp)
{
struct tstorm_eth_client_config tstorm_client = {0};
int port = BP_PORT(bp);
int i;
tstorm_client.mtu = bp->dev->mtu;
tstorm_client.config_flags =
(TSTORM_ETH_CLIENT_CONFIG_STATSITICS_ENABLE |
TSTORM_ETH_CLIENT_CONFIG_E1HOV_REM_ENABLE);
#ifdef BCM_VLAN
if (bp->rx_mode && bp->vlgrp && (bp->flags & HW_VLAN_RX_FLAG)) {
tstorm_client.config_flags |=
TSTORM_ETH_CLIENT_CONFIG_VLAN_REM_ENABLE;
DP(NETIF_MSG_IFUP, "vlan removal enabled\n");
}
#endif
for_each_queue(bp, i) {
tstorm_client.statistics_counter_id = bp->fp[i].cl_id;
REG_WR(bp, BAR_TSTRORM_INTMEM +
TSTORM_CLIENT_CONFIG_OFFSET(port, bp->fp[i].cl_id),
((u32 *)&tstorm_client)[0]);
REG_WR(bp, BAR_TSTRORM_INTMEM +
TSTORM_CLIENT_CONFIG_OFFSET(port, bp->fp[i].cl_id) + 4,
((u32 *)&tstorm_client)[1]);
}
DP(BNX2X_MSG_OFF, "tstorm_client: 0x%08x 0x%08x\n",
((u32 *)&tstorm_client)[0], ((u32 *)&tstorm_client)[1]);
}
static void bnx2x_set_storm_rx_mode(struct bnx2x *bp)
{
struct tstorm_eth_mac_filter_config tstorm_mac_filter = {0};
int mode = bp->rx_mode;
int mask = bp->rx_mode_cl_mask;
int func = BP_FUNC(bp);
int port = BP_PORT(bp);
int i;
/* All but management unicast packets should pass to the host as well */
u32 llh_mask =
NIG_LLH0_BRB1_DRV_MASK_REG_LLH0_BRB1_DRV_MASK_BRCST |
NIG_LLH0_BRB1_DRV_MASK_REG_LLH0_BRB1_DRV_MASK_MLCST |
NIG_LLH0_BRB1_DRV_MASK_REG_LLH0_BRB1_DRV_MASK_VLAN |
NIG_LLH0_BRB1_DRV_MASK_REG_LLH0_BRB1_DRV_MASK_NO_VLAN;
DP(NETIF_MSG_IFUP, "rx mode %d mask 0x%x\n", mode, mask);
switch (mode) {
case BNX2X_RX_MODE_NONE: /* no Rx */
tstorm_mac_filter.ucast_drop_all = mask;
tstorm_mac_filter.mcast_drop_all = mask;
tstorm_mac_filter.bcast_drop_all = mask;
break;
case BNX2X_RX_MODE_NORMAL:
tstorm_mac_filter.bcast_accept_all = mask;
break;
case BNX2X_RX_MODE_ALLMULTI:
tstorm_mac_filter.mcast_accept_all = mask;
tstorm_mac_filter.bcast_accept_all = mask;
break;
case BNX2X_RX_MODE_PROMISC:
tstorm_mac_filter.ucast_accept_all = mask;
tstorm_mac_filter.mcast_accept_all = mask;
tstorm_mac_filter.bcast_accept_all = mask;
/* pass management unicast packets as well */
llh_mask |= NIG_LLH0_BRB1_DRV_MASK_REG_LLH0_BRB1_DRV_MASK_UNCST;
break;
default:
BNX2X_ERR("BAD rx mode (%d)\n", mode);
break;
}
REG_WR(bp,
(port ? NIG_REG_LLH1_BRB1_DRV_MASK : NIG_REG_LLH0_BRB1_DRV_MASK),
llh_mask);
for (i = 0; i < sizeof(struct tstorm_eth_mac_filter_config)/4; i++) {
REG_WR(bp, BAR_TSTRORM_INTMEM +
TSTORM_MAC_FILTER_CONFIG_OFFSET(func) + i * 4,
((u32 *)&tstorm_mac_filter)[i]);
/* DP(NETIF_MSG_IFUP, "tstorm_mac_filter[%d]: 0x%08x\n", i,
((u32 *)&tstorm_mac_filter)[i]); */
}
if (mode != BNX2X_RX_MODE_NONE)
bnx2x_set_client_config(bp);
}
static void bnx2x_init_internal_common(struct bnx2x *bp)
{
int i;
/* Zero this manually as its initialization is
currently missing in the initTool */
for (i = 0; i < (USTORM_AGG_DATA_SIZE >> 2); i++)
REG_WR(bp, BAR_USTRORM_INTMEM +
USTORM_AGG_DATA_OFFSET + i * 4, 0);
}
static void bnx2x_init_internal_port(struct bnx2x *bp)
{
int port = BP_PORT(bp);
REG_WR(bp,
BAR_CSTRORM_INTMEM + CSTORM_HC_BTR_U_OFFSET(port), BNX2X_BTR);
REG_WR(bp,
BAR_CSTRORM_INTMEM + CSTORM_HC_BTR_C_OFFSET(port), BNX2X_BTR);
REG_WR(bp, BAR_TSTRORM_INTMEM + TSTORM_HC_BTR_OFFSET(port), BNX2X_BTR);
REG_WR(bp, BAR_XSTRORM_INTMEM + XSTORM_HC_BTR_OFFSET(port), BNX2X_BTR);
}
static void bnx2x_init_internal_func(struct bnx2x *bp)
{
struct tstorm_eth_function_common_config tstorm_config = {0};
struct stats_indication_flags stats_flags = {0};
int port = BP_PORT(bp);
int func = BP_FUNC(bp);
int i, j;
u32 offset;
u16 max_agg_size;
tstorm_config.config_flags = RSS_FLAGS(bp);
if (is_multi(bp))
tstorm_config.rss_result_mask = MULTI_MASK;
/* Enable TPA if needed */
if (bp->flags & TPA_ENABLE_FLAG)
tstorm_config.config_flags |=
TSTORM_ETH_FUNCTION_COMMON_CONFIG_ENABLE_TPA;
if (IS_E1HMF(bp))
tstorm_config.config_flags |=
TSTORM_ETH_FUNCTION_COMMON_CONFIG_E1HOV_IN_CAM;
tstorm_config.leading_client_id = BP_L_ID(bp);
REG_WR(bp, BAR_TSTRORM_INTMEM +
TSTORM_FUNCTION_COMMON_CONFIG_OFFSET(func),
(*(u32 *)&tstorm_config));
bp->rx_mode = BNX2X_RX_MODE_NONE; /* no rx until link is up */
bp->rx_mode_cl_mask = (1 << BP_L_ID(bp));
bnx2x_set_storm_rx_mode(bp);
for_each_queue(bp, i) {
u8 cl_id = bp->fp[i].cl_id;
/* reset xstorm per client statistics */
offset = BAR_XSTRORM_INTMEM +
XSTORM_PER_COUNTER_ID_STATS_OFFSET(port, cl_id);
for (j = 0;
j < sizeof(struct xstorm_per_client_stats) / 4; j++)
REG_WR(bp, offset + j*4, 0);
/* reset tstorm per client statistics */
offset = BAR_TSTRORM_INTMEM +
TSTORM_PER_COUNTER_ID_STATS_OFFSET(port, cl_id);
for (j = 0;
j < sizeof(struct tstorm_per_client_stats) / 4; j++)
REG_WR(bp, offset + j*4, 0);
/* reset ustorm per client statistics */
offset = BAR_USTRORM_INTMEM +
USTORM_PER_COUNTER_ID_STATS_OFFSET(port, cl_id);
for (j = 0;
j < sizeof(struct ustorm_per_client_stats) / 4; j++)
REG_WR(bp, offset + j*4, 0);
}
/* Init statistics related context */
stats_flags.collect_eth = 1;
REG_WR(bp, BAR_XSTRORM_INTMEM + XSTORM_STATS_FLAGS_OFFSET(func),
((u32 *)&stats_flags)[0]);
REG_WR(bp, BAR_XSTRORM_INTMEM + XSTORM_STATS_FLAGS_OFFSET(func) + 4,
((u32 *)&stats_flags)[1]);
REG_WR(bp, BAR_TSTRORM_INTMEM + TSTORM_STATS_FLAGS_OFFSET(func),
((u32 *)&stats_flags)[0]);
REG_WR(bp, BAR_TSTRORM_INTMEM + TSTORM_STATS_FLAGS_OFFSET(func) + 4,
((u32 *)&stats_flags)[1]);
REG_WR(bp, BAR_USTRORM_INTMEM + USTORM_STATS_FLAGS_OFFSET(func),
((u32 *)&stats_flags)[0]);
REG_WR(bp, BAR_USTRORM_INTMEM + USTORM_STATS_FLAGS_OFFSET(func) + 4,
((u32 *)&stats_flags)[1]);
REG_WR(bp, BAR_CSTRORM_INTMEM + CSTORM_STATS_FLAGS_OFFSET(func),
((u32 *)&stats_flags)[0]);
REG_WR(bp, BAR_CSTRORM_INTMEM + CSTORM_STATS_FLAGS_OFFSET(func) + 4,
((u32 *)&stats_flags)[1]);
REG_WR(bp, BAR_XSTRORM_INTMEM +
XSTORM_ETH_STATS_QUERY_ADDR_OFFSET(func),
U64_LO(bnx2x_sp_mapping(bp, fw_stats)));
REG_WR(bp, BAR_XSTRORM_INTMEM +
XSTORM_ETH_STATS_QUERY_ADDR_OFFSET(func) + 4,
U64_HI(bnx2x_sp_mapping(bp, fw_stats)));
REG_WR(bp, BAR_TSTRORM_INTMEM +
TSTORM_ETH_STATS_QUERY_ADDR_OFFSET(func),
U64_LO(bnx2x_sp_mapping(bp, fw_stats)));
REG_WR(bp, BAR_TSTRORM_INTMEM +
TSTORM_ETH_STATS_QUERY_ADDR_OFFSET(func) + 4,
U64_HI(bnx2x_sp_mapping(bp, fw_stats)));
REG_WR(bp, BAR_USTRORM_INTMEM +
USTORM_ETH_STATS_QUERY_ADDR_OFFSET(func),
U64_LO(bnx2x_sp_mapping(bp, fw_stats)));
REG_WR(bp, BAR_USTRORM_INTMEM +
USTORM_ETH_STATS_QUERY_ADDR_OFFSET(func) + 4,
U64_HI(bnx2x_sp_mapping(bp, fw_stats)));
if (CHIP_IS_E1H(bp)) {
REG_WR8(bp, BAR_XSTRORM_INTMEM + XSTORM_FUNCTION_MODE_OFFSET,
IS_E1HMF(bp));
REG_WR8(bp, BAR_TSTRORM_INTMEM + TSTORM_FUNCTION_MODE_OFFSET,
IS_E1HMF(bp));
REG_WR8(bp, BAR_CSTRORM_INTMEM + CSTORM_FUNCTION_MODE_OFFSET,
IS_E1HMF(bp));
REG_WR8(bp, BAR_USTRORM_INTMEM + USTORM_FUNCTION_MODE_OFFSET,
IS_E1HMF(bp));
REG_WR16(bp, BAR_XSTRORM_INTMEM + XSTORM_E1HOV_OFFSET(func),
bp->e1hov);
}
/* Init CQ ring mapping and aggregation size, the FW limit is 8 frags */
max_agg_size = min_t(u32, (min_t(u32, 8, MAX_SKB_FRAGS) *
SGE_PAGE_SIZE * PAGES_PER_SGE), 0xffff);
for_each_queue(bp, i) {
struct bnx2x_fastpath *fp = &bp->fp[i];
REG_WR(bp, BAR_USTRORM_INTMEM +
USTORM_CQE_PAGE_BASE_OFFSET(port, fp->cl_id),
U64_LO(fp->rx_comp_mapping));
REG_WR(bp, BAR_USTRORM_INTMEM +
USTORM_CQE_PAGE_BASE_OFFSET(port, fp->cl_id) + 4,
U64_HI(fp->rx_comp_mapping));
/* Next page */
REG_WR(bp, BAR_USTRORM_INTMEM +
USTORM_CQE_PAGE_NEXT_OFFSET(port, fp->cl_id),
U64_LO(fp->rx_comp_mapping + BCM_PAGE_SIZE));
REG_WR(bp, BAR_USTRORM_INTMEM +
USTORM_CQE_PAGE_NEXT_OFFSET(port, fp->cl_id) + 4,
U64_HI(fp->rx_comp_mapping + BCM_PAGE_SIZE));
REG_WR16(bp, BAR_USTRORM_INTMEM +
USTORM_MAX_AGG_SIZE_OFFSET(port, fp->cl_id),
max_agg_size);
}
/* dropless flow control */
if (CHIP_IS_E1H(bp)) {
struct ustorm_eth_rx_pause_data_e1h rx_pause = {0};
rx_pause.bd_thr_low = 250;
rx_pause.cqe_thr_low = 250;
rx_pause.cos = 1;
rx_pause.sge_thr_low = 0;
rx_pause.bd_thr_high = 350;
rx_pause.cqe_thr_high = 350;
rx_pause.sge_thr_high = 0;
for_each_queue(bp, i) {
struct bnx2x_fastpath *fp = &bp->fp[i];
if (!fp->disable_tpa) {
rx_pause.sge_thr_low = 150;
rx_pause.sge_thr_high = 250;
}
offset = BAR_USTRORM_INTMEM +
USTORM_ETH_RING_PAUSE_DATA_OFFSET(port,
fp->cl_id);
for (j = 0;
j < sizeof(struct ustorm_eth_rx_pause_data_e1h)/4;
j++)
REG_WR(bp, offset + j*4,
((u32 *)&rx_pause)[j]);
}
}
memset(&(bp->cmng), 0, sizeof(struct cmng_struct_per_port));
/* Init rate shaping and fairness contexts */
if (IS_E1HMF(bp)) {
int vn;
/* During init there is no active link
Until link is up, set link rate to 10Gbps */
bp->link_vars.line_speed = SPEED_10000;
bnx2x_init_port_minmax(bp);
if (!BP_NOMCP(bp))
bp->mf_config =
SHMEM_RD(bp, mf_cfg.func_mf_config[func].config);
bnx2x_calc_vn_weight_sum(bp);
for (vn = VN_0; vn < E1HVN_MAX; vn++)
bnx2x_init_vn_minmax(bp, 2*vn + port);
/* Enable rate shaping and fairness */
bp->cmng.flags.cmng_enables |=
CMNG_FLAGS_PER_PORT_RATE_SHAPING_VN;
} else {
/* rate shaping and fairness are disabled */
DP(NETIF_MSG_IFUP,
"single function mode minmax will be disabled\n");
}
/* Store cmng structures to internal memory */
if (bp->port.pmf)
for (i = 0; i < sizeof(struct cmng_struct_per_port) / 4; i++)
REG_WR(bp, BAR_XSTRORM_INTMEM +
XSTORM_CMNG_PER_PORT_VARS_OFFSET(port) + i * 4,
((u32 *)(&bp->cmng))[i]);
}
static void bnx2x_init_internal(struct bnx2x *bp, u32 load_code)
{
switch (load_code) {
case FW_MSG_CODE_DRV_LOAD_COMMON:
bnx2x_init_internal_common(bp);
/* no break */
case FW_MSG_CODE_DRV_LOAD_PORT:
bnx2x_init_internal_port(bp);
/* no break */
case FW_MSG_CODE_DRV_LOAD_FUNCTION:
bnx2x_init_internal_func(bp);
break;
default:
BNX2X_ERR("Unknown load_code (0x%x) from MCP\n", load_code);
break;
}
}
static void bnx2x_nic_init(struct bnx2x *bp, u32 load_code)
{
int i;
for_each_queue(bp, i) {
struct bnx2x_fastpath *fp = &bp->fp[i];
fp->bp = bp;
fp->state = BNX2X_FP_STATE_CLOSED;
fp->index = i;
fp->cl_id = BP_L_ID(bp) + i;
#ifdef BCM_CNIC
fp->sb_id = fp->cl_id + 1;
#else
fp->sb_id = fp->cl_id;
#endif
DP(NETIF_MSG_IFUP,
"queue[%d]: bnx2x_init_sb(%p,%p) cl_id %d sb %d\n",
i, bp, fp->status_blk, fp->cl_id, fp->sb_id);
bnx2x_init_sb(bp, fp->status_blk, fp->status_blk_mapping,
fp->sb_id);
bnx2x_update_fpsb_idx(fp);
}
/* ensure status block indices were read */
rmb();
bnx2x_init_def_sb(bp, bp->def_status_blk, bp->def_status_blk_mapping,
DEF_SB_ID);
bnx2x_update_dsb_idx(bp);
bnx2x_update_coalesce(bp);
bnx2x_init_rx_rings(bp);
bnx2x_init_tx_ring(bp);
bnx2x_init_sp_ring(bp);
bnx2x_init_context(bp);
bnx2x_init_internal(bp, load_code);
bnx2x_init_ind_table(bp);
bnx2x_stats_init(bp);
/* At this point, we are ready for interrupts */
atomic_set(&bp->intr_sem, 0);
/* flush all before enabling interrupts */
mb();
mmiowb();
bnx2x_int_enable(bp);
/* Check for SPIO5 */
bnx2x_attn_int_deasserted0(bp,
REG_RD(bp, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + BP_PORT(bp)*4) &
AEU_INPUTS_ATTN_BITS_SPIO5);
}
/* end of nic init */
/*
* gzip service functions
*/
static int bnx2x_gunzip_init(struct bnx2x *bp)
{
bp->gunzip_buf = dma_alloc_coherent(&bp->pdev->dev, FW_BUF_SIZE,
&bp->gunzip_mapping, GFP_KERNEL);
if (bp->gunzip_buf == NULL)
goto gunzip_nomem1;
bp->strm = kmalloc(sizeof(*bp->strm), GFP_KERNEL);
if (bp->strm == NULL)
goto gunzip_nomem2;
bp->strm->workspace = kmalloc(zlib_inflate_workspacesize(),
GFP_KERNEL);
if (bp->strm->workspace == NULL)
goto gunzip_nomem3;
return 0;
gunzip_nomem3:
kfree(bp->strm);
bp->strm = NULL;
gunzip_nomem2:
dma_free_coherent(&bp->pdev->dev, FW_BUF_SIZE, bp->gunzip_buf,
bp->gunzip_mapping);
bp->gunzip_buf = NULL;
gunzip_nomem1:
netdev_err(bp->dev, "Cannot allocate firmware buffer for"
" un-compression\n");
return -ENOMEM;
}
static void bnx2x_gunzip_end(struct bnx2x *bp)
{
kfree(bp->strm->workspace);
kfree(bp->strm);
bp->strm = NULL;
if (bp->gunzip_buf) {
dma_free_coherent(&bp->pdev->dev, FW_BUF_SIZE, bp->gunzip_buf,
bp->gunzip_mapping);
bp->gunzip_buf = NULL;
}
}
static int bnx2x_gunzip(struct bnx2x *bp, const u8 *zbuf, int len)
{
int n, rc;
/* check gzip header */
if ((zbuf[0] != 0x1f) || (zbuf[1] != 0x8b) || (zbuf[2] != Z_DEFLATED)) {
BNX2X_ERR("Bad gzip header\n");
return -EINVAL;
}
n = 10;
#define FNAME 0x8
if (zbuf[3] & FNAME)
while ((zbuf[n++] != 0) && (n < len));
bp->strm->next_in = (typeof(bp->strm->next_in))zbuf + n;
bp->strm->avail_in = len - n;
bp->strm->next_out = bp->gunzip_buf;
bp->strm->avail_out = FW_BUF_SIZE;
rc = zlib_inflateInit2(bp->strm, -MAX_WBITS);
if (rc != Z_OK)
return rc;
rc = zlib_inflate(bp->strm, Z_FINISH);
if ((rc != Z_OK) && (rc != Z_STREAM_END))
netdev_err(bp->dev, "Firmware decompression error: %s\n",
bp->strm->msg);
bp->gunzip_outlen = (FW_BUF_SIZE - bp->strm->avail_out);
if (bp->gunzip_outlen & 0x3)
netdev_err(bp->dev, "Firmware decompression error:"
" gunzip_outlen (%d) not aligned\n",
bp->gunzip_outlen);
bp->gunzip_outlen >>= 2;
zlib_inflateEnd(bp->strm);
if (rc == Z_STREAM_END)
return 0;
return rc;
}
/* nic load/unload */
/*
* General service functions
*/
/* send a NIG loopback debug packet */
static void bnx2x_lb_pckt(struct bnx2x *bp)
{
u32 wb_write[3];
/* Ethernet source and destination addresses */
wb_write[0] = 0x55555555;
wb_write[1] = 0x55555555;
wb_write[2] = 0x20; /* SOP */
REG_WR_DMAE(bp, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
/* NON-IP protocol */
wb_write[0] = 0x09000000;
wb_write[1] = 0x55555555;
wb_write[2] = 0x10; /* EOP, eop_bvalid = 0 */
REG_WR_DMAE(bp, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
}
/* some of the internal memories
* are not directly readable from the driver
* to test them we send debug packets
*/
static int bnx2x_int_mem_test(struct bnx2x *bp)
{
int factor;
int count, i;
u32 val = 0;
if (CHIP_REV_IS_FPGA(bp))
factor = 120;
else if (CHIP_REV_IS_EMUL(bp))
factor = 200;
else
factor = 1;
DP(NETIF_MSG_HW, "start part1\n");
/* Disable inputs of parser neighbor blocks */
REG_WR(bp, TSDM_REG_ENABLE_IN1, 0x0);
REG_WR(bp, TCM_REG_PRS_IFEN, 0x0);
REG_WR(bp, CFC_REG_DEBUG0, 0x1);
REG_WR(bp, NIG_REG_PRS_REQ_IN_EN, 0x0);
/* Write 0 to parser credits for CFC search request */
REG_WR(bp, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
/* send Ethernet packet */
bnx2x_lb_pckt(bp);
/* TODO do i reset NIG statistic? */
/* Wait until NIG register shows 1 packet of size 0x10 */
count = 1000 * factor;
while (count) {
bnx2x_read_dmae(bp, NIG_REG_STAT2_BRB_OCTET, 2);
val = *bnx2x_sp(bp, wb_data[0]);
if (val == 0x10)
break;
msleep(10);
count--;
}
if (val != 0x10) {
BNX2X_ERR("NIG timeout val = 0x%x\n", val);
return -1;
}
/* Wait until PRS register shows 1 packet */
count = 1000 * factor;
while (count) {
val = REG_RD(bp, PRS_REG_NUM_OF_PACKETS);
if (val == 1)
break;
msleep(10);
count--;
}
if (val != 0x1) {
BNX2X_ERR("PRS timeout val = 0x%x\n", val);
return -2;
}
/* Reset and init BRB, PRS */
REG_WR(bp, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
msleep(50);
REG_WR(bp, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
msleep(50);
bnx2x_init_block(bp, BRB1_BLOCK, COMMON_STAGE);
bnx2x_init_block(bp, PRS_BLOCK, COMMON_STAGE);
DP(NETIF_MSG_HW, "part2\n");
/* Disable inputs of parser neighbor blocks */
REG_WR(bp, TSDM_REG_ENABLE_IN1, 0x0);
REG_WR(bp, TCM_REG_PRS_IFEN, 0x0);
REG_WR(bp, CFC_REG_DEBUG0, 0x1);
REG_WR(bp, NIG_REG_PRS_REQ_IN_EN, 0x0);
/* Write 0 to parser credits for CFC search request */
REG_WR(bp, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
/* send 10 Ethernet packets */
for (i = 0; i < 10; i++)
bnx2x_lb_pckt(bp);
/* Wait until NIG register shows 10 + 1
packets of size 11*0x10 = 0xb0 */
count = 1000 * factor;
while (count) {
bnx2x_read_dmae(bp, NIG_REG_STAT2_BRB_OCTET, 2);
val = *bnx2x_sp(bp, wb_data[0]);
if (val == 0xb0)
break;
msleep(10);
count--;
}
if (val != 0xb0) {
BNX2X_ERR("NIG timeout val = 0x%x\n", val);
return -3;
}
/* Wait until PRS register shows 2 packets */
val = REG_RD(bp, PRS_REG_NUM_OF_PACKETS);
if (val != 2)
BNX2X_ERR("PRS timeout val = 0x%x\n", val);
/* Write 1 to parser credits for CFC search request */
REG_WR(bp, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x1);
/* Wait until PRS register shows 3 packets */
msleep(10 * factor);
/* Wait until NIG register shows 1 packet of size 0x10 */
val = REG_RD(bp, PRS_REG_NUM_OF_PACKETS);
if (val != 3)
BNX2X_ERR("PRS timeout val = 0x%x\n", val);
/* clear NIG EOP FIFO */
for (i = 0; i < 11; i++)
REG_RD(bp, NIG_REG_INGRESS_EOP_LB_FIFO);
val = REG_RD(bp, NIG_REG_INGRESS_EOP_LB_EMPTY);
if (val != 1) {
BNX2X_ERR("clear of NIG failed\n");
return -4;
}
/* Reset and init BRB, PRS, NIG */
REG_WR(bp, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
msleep(50);
REG_WR(bp, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
msleep(50);
bnx2x_init_block(bp, BRB1_BLOCK, COMMON_STAGE);
bnx2x_init_block(bp, PRS_BLOCK, COMMON_STAGE);
#ifndef BCM_CNIC
/* set NIC mode */
REG_WR(bp, PRS_REG_NIC_MODE, 1);
#endif
/* Enable inputs of parser neighbor blocks */
REG_WR(bp, TSDM_REG_ENABLE_IN1, 0x7fffffff);
REG_WR(bp, TCM_REG_PRS_IFEN, 0x1);
REG_WR(bp, CFC_REG_DEBUG0, 0x0);
REG_WR(bp, NIG_REG_PRS_REQ_IN_EN, 0x1);
DP(NETIF_MSG_HW, "done\n");
return 0; /* OK */
}
static void enable_blocks_attention(struct bnx2x *bp)
{
REG_WR(bp, PXP_REG_PXP_INT_MASK_0, 0);
REG_WR(bp, PXP_REG_PXP_INT_MASK_1, 0);
REG_WR(bp, DORQ_REG_DORQ_INT_MASK, 0);
REG_WR(bp, CFC_REG_CFC_INT_MASK, 0);
REG_WR(bp, QM_REG_QM_INT_MASK, 0);
REG_WR(bp, TM_REG_TM_INT_MASK, 0);
REG_WR(bp, XSDM_REG_XSDM_INT_MASK_0, 0);
REG_WR(bp, XSDM_REG_XSDM_INT_MASK_1, 0);
REG_WR(bp, XCM_REG_XCM_INT_MASK, 0);
/* REG_WR(bp, XSEM_REG_XSEM_INT_MASK_0, 0); */
/* REG_WR(bp, XSEM_REG_XSEM_INT_MASK_1, 0); */
REG_WR(bp, USDM_REG_USDM_INT_MASK_0, 0);
REG_WR(bp, USDM_REG_USDM_INT_MASK_1, 0);
REG_WR(bp, UCM_REG_UCM_INT_MASK, 0);
/* REG_WR(bp, USEM_REG_USEM_INT_MASK_0, 0); */
/* REG_WR(bp, USEM_REG_USEM_INT_MASK_1, 0); */
REG_WR(bp, GRCBASE_UPB + PB_REG_PB_INT_MASK, 0);
REG_WR(bp, CSDM_REG_CSDM_INT_MASK_0, 0);
REG_WR(bp, CSDM_REG_CSDM_INT_MASK_1, 0);
REG_WR(bp, CCM_REG_CCM_INT_MASK, 0);
/* REG_WR(bp, CSEM_REG_CSEM_INT_MASK_0, 0); */
/* REG_WR(bp, CSEM_REG_CSEM_INT_MASK_1, 0); */
if (CHIP_REV_IS_FPGA(bp))
REG_WR(bp, PXP2_REG_PXP2_INT_MASK_0, 0x580000);
else
REG_WR(bp, PXP2_REG_PXP2_INT_MASK_0, 0x480000);
REG_WR(bp, TSDM_REG_TSDM_INT_MASK_0, 0);
REG_WR(bp, TSDM_REG_TSDM_INT_MASK_1, 0);
REG_WR(bp, TCM_REG_TCM_INT_MASK, 0);
/* REG_WR(bp, TSEM_REG_TSEM_INT_MASK_0, 0); */
/* REG_WR(bp, TSEM_REG_TSEM_INT_MASK_1, 0); */
REG_WR(bp, CDU_REG_CDU_INT_MASK, 0);
REG_WR(bp, DMAE_REG_DMAE_INT_MASK, 0);
/* REG_WR(bp, MISC_REG_MISC_INT_MASK, 0); */
REG_WR(bp, PBF_REG_PBF_INT_MASK, 0X18); /* bit 3,4 masked */
}
static const struct {
u32 addr;
u32 mask;
} bnx2x_parity_mask[] = {
{PXP_REG_PXP_PRTY_MASK, 0xffffffff},
{PXP2_REG_PXP2_PRTY_MASK_0, 0xffffffff},
{PXP2_REG_PXP2_PRTY_MASK_1, 0xffffffff},
{HC_REG_HC_PRTY_MASK, 0xffffffff},
{MISC_REG_MISC_PRTY_MASK, 0xffffffff},
{QM_REG_QM_PRTY_MASK, 0x0},
{DORQ_REG_DORQ_PRTY_MASK, 0x0},
{GRCBASE_UPB + PB_REG_PB_PRTY_MASK, 0x0},
{GRCBASE_XPB + PB_REG_PB_PRTY_MASK, 0x0},
{SRC_REG_SRC_PRTY_MASK, 0x4}, /* bit 2 */
{CDU_REG_CDU_PRTY_MASK, 0x0},
{CFC_REG_CFC_PRTY_MASK, 0x0},
{DBG_REG_DBG_PRTY_MASK, 0x0},
{DMAE_REG_DMAE_PRTY_MASK, 0x0},
{BRB1_REG_BRB1_PRTY_MASK, 0x0},
{PRS_REG_PRS_PRTY_MASK, (1<<6)},/* bit 6 */
{TSDM_REG_TSDM_PRTY_MASK, 0x18},/* bit 3,4 */
{CSDM_REG_CSDM_PRTY_MASK, 0x8}, /* bit 3 */
{USDM_REG_USDM_PRTY_MASK, 0x38},/* bit 3,4,5 */
{XSDM_REG_XSDM_PRTY_MASK, 0x8}, /* bit 3 */
{TSEM_REG_TSEM_PRTY_MASK_0, 0x0},
{TSEM_REG_TSEM_PRTY_MASK_1, 0x0},
{USEM_REG_USEM_PRTY_MASK_0, 0x0},
{USEM_REG_USEM_PRTY_MASK_1, 0x0},
{CSEM_REG_CSEM_PRTY_MASK_0, 0x0},
{CSEM_REG_CSEM_PRTY_MASK_1, 0x0},
{XSEM_REG_XSEM_PRTY_MASK_0, 0x0},
{XSEM_REG_XSEM_PRTY_MASK_1, 0x0}
};
static void enable_blocks_parity(struct bnx2x *bp)
{
int i, mask_arr_len =
sizeof(bnx2x_parity_mask)/(sizeof(bnx2x_parity_mask[0]));
for (i = 0; i < mask_arr_len; i++)
REG_WR(bp, bnx2x_parity_mask[i].addr,
bnx2x_parity_mask[i].mask);
}
static void bnx2x_reset_common(struct bnx2x *bp)
{
/* reset_common */
REG_WR(bp, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
0xd3ffff7f);
REG_WR(bp, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR, 0x1403);
}
static void bnx2x_init_pxp(struct bnx2x *bp)
{
u16 devctl;
int r_order, w_order;
pci_read_config_word(bp->pdev,
bp->pcie_cap + PCI_EXP_DEVCTL, &devctl);
DP(NETIF_MSG_HW, "read 0x%x from devctl\n", devctl);
w_order = ((devctl & PCI_EXP_DEVCTL_PAYLOAD) >> 5);
if (bp->mrrs == -1)
r_order = ((devctl & PCI_EXP_DEVCTL_READRQ) >> 12);
else {
DP(NETIF_MSG_HW, "force read order to %d\n", bp->mrrs);
r_order = bp->mrrs;
}
bnx2x_init_pxp_arb(bp, r_order, w_order);
}
static void bnx2x_setup_fan_failure_detection(struct bnx2x *bp)
{
int is_required;
u32 val;
int port;
if (BP_NOMCP(bp))
return;
is_required = 0;
val = SHMEM_RD(bp, dev_info.shared_hw_config.config2) &
SHARED_HW_CFG_FAN_FAILURE_MASK;
if (val == SHARED_HW_CFG_FAN_FAILURE_ENABLED)
is_required = 1;
/*
* The fan failure mechanism is usually related to the PHY type since
* the power consumption of the board is affected by the PHY. Currently,
* fan is required for most designs with SFX7101, BCM8727 and BCM8481.
*/
else if (val == SHARED_HW_CFG_FAN_FAILURE_PHY_TYPE)
for (port = PORT_0; port < PORT_MAX; port++) {
u32 phy_type =
SHMEM_RD(bp, dev_info.port_hw_config[port].
external_phy_config) &
PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK;
is_required |=
((phy_type ==
PORT_HW_CFG_XGXS_EXT_PHY_TYPE_SFX7101) ||
(phy_type ==
PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM8727) ||
(phy_type ==
PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM8481));
}
DP(NETIF_MSG_HW, "fan detection setting: %d\n", is_required);
if (is_required == 0)
return;
/* Fan failure is indicated by SPIO 5 */
bnx2x_set_spio(bp, MISC_REGISTERS_SPIO_5,
MISC_REGISTERS_SPIO_INPUT_HI_Z);
/* set to active low mode */
val = REG_RD(bp, MISC_REG_SPIO_INT);
val |= ((1 << MISC_REGISTERS_SPIO_5) <<
MISC_REGISTERS_SPIO_INT_OLD_SET_POS);
REG_WR(bp, MISC_REG_SPIO_INT, val);
/* enable interrupt to signal the IGU */
val = REG_RD(bp, MISC_REG_SPIO_EVENT_EN);
val |= (1 << MISC_REGISTERS_SPIO_5);
REG_WR(bp, MISC_REG_SPIO_EVENT_EN, val);
}
static int bnx2x_init_common(struct bnx2x *bp)
{
u32 val, i;
#ifdef BCM_CNIC
u32 wb_write[2];
#endif
DP(BNX2X_MSG_MCP, "starting common init func %d\n", BP_FUNC(bp));
bnx2x_reset_common(bp);
REG_WR(bp, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0xffffffff);
REG_WR(bp, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET, 0xfffc);
bnx2x_init_block(bp, MISC_BLOCK, COMMON_STAGE);
if (CHIP_IS_E1H(bp))
REG_WR(bp, MISC_REG_E1HMF_MODE, IS_E1HMF(bp));
REG_WR(bp, MISC_REG_LCPLL_CTRL_REG_2, 0x100);
msleep(30);
REG_WR(bp, MISC_REG_LCPLL_CTRL_REG_2, 0x0);
bnx2x_init_block(bp, PXP_BLOCK, COMMON_STAGE);
if (CHIP_IS_E1(bp)) {
/* enable HW interrupt from PXP on USDM overflow
bit 16 on INT_MASK_0 */
REG_WR(bp, PXP_REG_PXP_INT_MASK_0, 0);
}
bnx2x_init_block(bp, PXP2_BLOCK, COMMON_STAGE);
bnx2x_init_pxp(bp);
#ifdef __BIG_ENDIAN
REG_WR(bp, PXP2_REG_RQ_QM_ENDIAN_M, 1);
REG_WR(bp, PXP2_REG_RQ_TM_ENDIAN_M, 1);
REG_WR(bp, PXP2_REG_RQ_SRC_ENDIAN_M, 1);
REG_WR(bp, PXP2_REG_RQ_CDU_ENDIAN_M, 1);
REG_WR(bp, PXP2_REG_RQ_DBG_ENDIAN_M, 1);
/* make sure this value is 0 */
REG_WR(bp, PXP2_REG_RQ_HC_ENDIAN_M, 0);
/* REG_WR(bp, PXP2_REG_RD_PBF_SWAP_MODE, 1); */
REG_WR(bp, PXP2_REG_RD_QM_SWAP_MODE, 1);
REG_WR(bp, PXP2_REG_RD_TM_SWAP_MODE, 1);
REG_WR(bp, PXP2_REG_RD_SRC_SWAP_MODE, 1);
REG_WR(bp, PXP2_REG_RD_CDURD_SWAP_MODE, 1);
#endif
REG_WR(bp, PXP2_REG_RQ_CDU_P_SIZE, 2);
#ifdef BCM_CNIC
REG_WR(bp, PXP2_REG_RQ_TM_P_SIZE, 5);
REG_WR(bp, PXP2_REG_RQ_QM_P_SIZE, 5);
REG_WR(bp, PXP2_REG_RQ_SRC_P_SIZE, 5);
#endif
if (CHIP_REV_IS_FPGA(bp) && CHIP_IS_E1H(bp))
REG_WR(bp, PXP2_REG_PGL_TAGS_LIMIT, 0x1);
/* let the HW do it's magic ... */
msleep(100);
/* finish PXP init */
val = REG_RD(bp, PXP2_REG_RQ_CFG_DONE);
if (val != 1) {
BNX2X_ERR("PXP2 CFG failed\n");
return -EBUSY;
}
val = REG_RD(bp, PXP2_REG_RD_INIT_DONE);
if (val != 1) {
BNX2X_ERR("PXP2 RD_INIT failed\n");
return -EBUSY;
}
REG_WR(bp, PXP2_REG_RQ_DISABLE_INPUTS, 0);
REG_WR(bp, PXP2_REG_RD_DISABLE_INPUTS, 0);
bnx2x_init_block(bp, DMAE_BLOCK, COMMON_STAGE);
/* clean the DMAE memory */
bp->dmae_ready = 1;
bnx2x_init_fill(bp, TSEM_REG_PRAM, 0, 8);
bnx2x_init_block(bp, TCM_BLOCK, COMMON_STAGE);
bnx2x_init_block(bp, UCM_BLOCK, COMMON_STAGE);
bnx2x_init_block(bp, CCM_BLOCK, COMMON_STAGE);
bnx2x_init_block(bp, XCM_BLOCK, COMMON_STAGE);
bnx2x_read_dmae(bp, XSEM_REG_PASSIVE_BUFFER, 3);
bnx2x_read_dmae(bp, CSEM_REG_PASSIVE_BUFFER, 3);
bnx2x_read_dmae(bp, TSEM_REG_PASSIVE_BUFFER, 3);
bnx2x_read_dmae(bp, USEM_REG_PASSIVE_BUFFER, 3);
bnx2x_init_block(bp, QM_BLOCK, COMMON_STAGE);
#ifdef BCM_CNIC
wb_write[0] = 0;
wb_write[1] = 0;
for (i = 0; i < 64; i++) {
REG_WR(bp, QM_REG_BASEADDR + i*4, 1024 * 4 * (i%16));
bnx2x_init_ind_wr(bp, QM_REG_PTRTBL + i*8, wb_write, 2);
if (CHIP_IS_E1H(bp)) {
REG_WR(bp, QM_REG_BASEADDR_EXT_A + i*4, 1024*4*(i%16));
bnx2x_init_ind_wr(bp, QM_REG_PTRTBL_EXT_A + i*8,
wb_write, 2);
}
}
#endif
/* soft reset pulse */
REG_WR(bp, QM_REG_SOFT_RESET, 1);
REG_WR(bp, QM_REG_SOFT_RESET, 0);
#ifdef BCM_CNIC
bnx2x_init_block(bp, TIMERS_BLOCK, COMMON_STAGE);
#endif
bnx2x_init_block(bp, DQ_BLOCK, COMMON_STAGE);
REG_WR(bp, DORQ_REG_DPM_CID_OFST, BCM_PAGE_SHIFT);
if (!CHIP_REV_IS_SLOW(bp)) {
/* enable hw interrupt from doorbell Q */
REG_WR(bp, DORQ_REG_DORQ_INT_MASK, 0);
}
bnx2x_init_block(bp, BRB1_BLOCK, COMMON_STAGE);
bnx2x_init_block(bp, PRS_BLOCK, COMMON_STAGE);
REG_WR(bp, PRS_REG_A_PRSU_20, 0xf);
#ifndef BCM_CNIC
/* set NIC mode */
REG_WR(bp, PRS_REG_NIC_MODE, 1);
#endif
if (CHIP_IS_E1H(bp))
REG_WR(bp, PRS_REG_E1HOV_MODE, IS_E1HMF(bp));
bnx2x_init_block(bp, TSDM_BLOCK, COMMON_STAGE);
bnx2x_init_block(bp, CSDM_BLOCK, COMMON_STAGE);
bnx2x_init_block(bp, USDM_BLOCK, COMMON_STAGE);
bnx2x_init_block(bp, XSDM_BLOCK, COMMON_STAGE);
bnx2x_init_fill(bp, TSEM_REG_FAST_MEMORY, 0, STORM_INTMEM_SIZE(bp));
bnx2x_init_fill(bp, USEM_REG_FAST_MEMORY, 0, STORM_INTMEM_SIZE(bp));
bnx2x_init_fill(bp, CSEM_REG_FAST_MEMORY, 0, STORM_INTMEM_SIZE(bp));
bnx2x_init_fill(bp, XSEM_REG_FAST_MEMORY, 0, STORM_INTMEM_SIZE(bp));
bnx2x_init_block(bp, TSEM_BLOCK, COMMON_STAGE);
bnx2x_init_block(bp, USEM_BLOCK, COMMON_STAGE);
bnx2x_init_block(bp, CSEM_BLOCK, COMMON_STAGE);
bnx2x_init_block(bp, XSEM_BLOCK, COMMON_STAGE);
/* sync semi rtc */
REG_WR(bp, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
0x80000000);
REG_WR(bp, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET,
0x80000000);
bnx2x_init_block(bp, UPB_BLOCK, COMMON_STAGE);
bnx2x_init_block(bp, XPB_BLOCK, COMMON_STAGE);
bnx2x_init_block(bp, PBF_BLOCK, COMMON_STAGE);
REG_WR(bp, SRC_REG_SOFT_RST, 1);
for (i = SRC_REG_KEYRSS0_0; i <= SRC_REG_KEYRSS1_9; i += 4)
REG_WR(bp, i, random32());
bnx2x_init_block(bp, SRCH_BLOCK, COMMON_STAGE);
#ifdef BCM_CNIC
REG_WR(bp, SRC_REG_KEYSEARCH_0, 0x63285672);
REG_WR(bp, SRC_REG_KEYSEARCH_1, 0x24b8f2cc);
REG_WR(bp, SRC_REG_KEYSEARCH_2, 0x223aef9b);
REG_WR(bp, SRC_REG_KEYSEARCH_3, 0x26001e3a);
REG_WR(bp, SRC_REG_KEYSEARCH_4, 0x7ae91116);
REG_WR(bp, SRC_REG_KEYSEARCH_5, 0x5ce5230b);
REG_WR(bp, SRC_REG_KEYSEARCH_6, 0x298d8adf);
REG_WR(bp, SRC_REG_KEYSEARCH_7, 0x6eb0ff09);
REG_WR(bp, SRC_REG_KEYSEARCH_8, 0x1830f82f);
REG_WR(bp, SRC_REG_KEYSEARCH_9, 0x01e46be7);
#endif
REG_WR(bp, SRC_REG_SOFT_RST, 0);
if (sizeof(union cdu_context) != 1024)
/* we currently assume that a context is 1024 bytes */
dev_alert(&bp->pdev->dev, "please adjust the size "
"of cdu_context(%ld)\n",
(long)sizeof(union cdu_context));
bnx2x_init_block(bp, CDU_BLOCK, COMMON_STAGE);
val = (4 << 24) + (0 << 12) + 1024;
REG_WR(bp, CDU_REG_CDU_GLOBAL_PARAMS, val);
bnx2x_init_block(bp, CFC_BLOCK, COMMON_STAGE);
REG_WR(bp, CFC_REG_INIT_REG, 0x7FF);
/* enable context validation interrupt from CFC */
REG_WR(bp, CFC_REG_CFC_INT_MASK, 0);
/* set the thresholds to prevent CFC/CDU race */
REG_WR(bp, CFC_REG_DEBUG0, 0x20020000);
bnx2x_init_block(bp, HC_BLOCK, COMMON_STAGE);
bnx2x_init_block(bp, MISC_AEU_BLOCK, COMMON_STAGE);
bnx2x_init_block(bp, PXPCS_BLOCK, COMMON_STAGE);
/* Reset PCIE errors for debug */
REG_WR(bp, 0x2814, 0xffffffff);
REG_WR(bp, 0x3820, 0xffffffff);
bnx2x_init_block(bp, EMAC0_BLOCK, COMMON_STAGE);
bnx2x_init_block(bp, EMAC1_BLOCK, COMMON_STAGE);
bnx2x_init_block(bp, DBU_BLOCK, COMMON_STAGE);
bnx2x_init_block(bp, DBG_BLOCK, COMMON_STAGE);
bnx2x_init_block(bp, NIG_BLOCK, COMMON_STAGE);
if (CHIP_IS_E1H(bp)) {
REG_WR(bp, NIG_REG_LLH_MF_MODE, IS_E1HMF(bp));
REG_WR(bp, NIG_REG_LLH_E1HOV_MODE, IS_E1HMF(bp));
}
if (CHIP_REV_IS_SLOW(bp))
msleep(200);
/* finish CFC init */
val = reg_poll(bp, CFC_REG_LL_INIT_DONE, 1, 100, 10);
if (val != 1) {
BNX2X_ERR("CFC LL_INIT failed\n");
return -EBUSY;
}
val = reg_poll(bp, CFC_REG_AC_INIT_DONE, 1, 100, 10);
if (val != 1) {
BNX2X_ERR("CFC AC_INIT failed\n");
return -EBUSY;
}
val = reg_poll(bp, CFC_REG_CAM_INIT_DONE, 1, 100, 10);
if (val != 1) {
BNX2X_ERR("CFC CAM_INIT failed\n");
return -EBUSY;
}
REG_WR(bp, CFC_REG_DEBUG0, 0);
/* read NIG statistic
to see if this is our first up since powerup */
bnx2x_read_dmae(bp, NIG_REG_STAT2_BRB_OCTET, 2);
val = *bnx2x_sp(bp, wb_data[0]);
/* do internal memory self test */
if ((CHIP_IS_E1(bp)) && (val == 0) && bnx2x_int_mem_test(bp)) {
BNX2X_ERR("internal mem self test failed\n");
return -EBUSY;
}
switch (XGXS_EXT_PHY_TYPE(bp->link_params.ext_phy_config)) {
case PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM8072:
case PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM8073:
case PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM8726:
case PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM8727:
bp->port.need_hw_lock = 1;
break;
default:
break;
}
bnx2x_setup_fan_failure_detection(bp);
/* clear PXP2 attentions */
REG_RD(bp, PXP2_REG_PXP2_INT_STS_CLR_0);
enable_blocks_attention(bp);
if (CHIP_PARITY_SUPPORTED(bp))
enable_blocks_parity(bp);
if (!BP_NOMCP(bp)) {
bnx2x_acquire_phy_lock(bp);
bnx2x_common_init_phy(bp, bp->common.shmem_base);
bnx2x_release_phy_lock(bp);
} else
BNX2X_ERR("Bootcode is missing - can not initialize link\n");
return 0;
}
static int bnx2x_init_port(struct bnx2x *bp)
{
int port = BP_PORT(bp);
int init_stage = port ? PORT1_STAGE : PORT0_STAGE;
u32 low, high;
u32 val;
DP(BNX2X_MSG_MCP, "starting port init port %d\n", port);
REG_WR(bp, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
bnx2x_init_block(bp, PXP_BLOCK, init_stage);
bnx2x_init_block(bp, PXP2_BLOCK, init_stage);
bnx2x_init_block(bp, TCM_BLOCK, init_stage);
bnx2x_init_block(bp, UCM_BLOCK, init_stage);
bnx2x_init_block(bp, CCM_BLOCK, init_stage);
bnx2x_init_block(bp, XCM_BLOCK, init_stage);
#ifdef BCM_CNIC
REG_WR(bp, QM_REG_CONNNUM_0 + port*4, 1024/16 - 1);
bnx2x_init_block(bp, TIMERS_BLOCK, init_stage);
REG_WR(bp, TM_REG_LIN0_SCAN_TIME + port*4, 20);
REG_WR(bp, TM_REG_LIN0_MAX_ACTIVE_CID + port*4, 31);
#endif
bnx2x_init_block(bp, DQ_BLOCK, init_stage);
bnx2x_init_block(bp, BRB1_BLOCK, init_stage);
if (CHIP_REV_IS_SLOW(bp) && !CHIP_IS_E1H(bp)) {
/* no pause for emulation and FPGA */
low = 0;
high = 513;
} else {
if (IS_E1HMF(bp))
low = ((bp->flags & ONE_PORT_FLAG) ? 160 : 246);
else if (bp->dev->mtu > 4096) {
if (bp->flags & ONE_PORT_FLAG)
low = 160;
else {
val = bp->dev->mtu;
/* (24*1024 + val*4)/256 */
low = 96 + (val/64) + ((val % 64) ? 1 : 0);
}
} else
low = ((bp->flags & ONE_PORT_FLAG) ? 80 : 160);
high = low + 56; /* 14*1024/256 */
}
REG_WR(bp, BRB1_REG_PAUSE_LOW_THRESHOLD_0 + port*4, low);
REG_WR(bp, BRB1_REG_PAUSE_HIGH_THRESHOLD_0 + port*4, high);
bnx2x_init_block(bp, PRS_BLOCK, init_stage);
bnx2x_init_block(bp, TSDM_BLOCK, init_stage);
bnx2x_init_block(bp, CSDM_BLOCK, init_stage);
bnx2x_init_block(bp, USDM_BLOCK, init_stage);
bnx2x_init_block(bp, XSDM_BLOCK, init_stage);
bnx2x_init_block(bp, TSEM_BLOCK, init_stage);
bnx2x_init_block(bp, USEM_BLOCK, init_stage);
bnx2x_init_block(bp, CSEM_BLOCK, init_stage);
bnx2x_init_block(bp, XSEM_BLOCK, init_stage);
bnx2x_init_block(bp, UPB_BLOCK, init_stage);
bnx2x_init_block(bp, XPB_BLOCK, init_stage);
bnx2x_init_block(bp, PBF_BLOCK, init_stage);
/* configure PBF to work without PAUSE mtu 9000 */
REG_WR(bp, PBF_REG_P0_PAUSE_ENABLE + port*4, 0);
/* update threshold */
REG_WR(bp, PBF_REG_P0_ARB_THRSH + port*4, (9040/16));
/* update init credit */
REG_WR(bp, PBF_REG_P0_INIT_CRD + port*4, (9040/16) + 553 - 22);
/* probe changes */
REG_WR(bp, PBF_REG_INIT_P0 + port*4, 1);
msleep(5);
REG_WR(bp, PBF_REG_INIT_P0 + port*4, 0);
#ifdef BCM_CNIC
bnx2x_init_block(bp, SRCH_BLOCK, init_stage);
#endif
bnx2x_init_block(bp, CDU_BLOCK, init_stage);
bnx2x_init_block(bp, CFC_BLOCK, init_stage);
if (CHIP_IS_E1(bp)) {
REG_WR(bp, HC_REG_LEADING_EDGE_0 + port*8, 0);
REG_WR(bp, HC_REG_TRAILING_EDGE_0 + port*8, 0);
}
bnx2x_init_block(bp, HC_BLOCK, init_stage);
bnx2x_init_block(bp, MISC_AEU_BLOCK, init_stage);
/* init aeu_mask_attn_func_0/1:
* - SF mode: bits 3-7 are masked. only bits 0-2 are in use
* - MF mode: bit 3 is masked. bits 0-2 are in use as in SF
* bits 4-7 are used for "per vn group attention" */
REG_WR(bp, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4,
(IS_E1HMF(bp) ? 0xF7 : 0x7));
bnx2x_init_block(bp, PXPCS_BLOCK, init_stage);
bnx2x_init_block(bp, EMAC0_BLOCK, init_stage);
bnx2x_init_block(bp, EMAC1_BLOCK, init_stage);
bnx2x_init_block(bp, DBU_BLOCK, init_stage);
bnx2x_init_block(bp, DBG_BLOCK, init_stage);
bnx2x_init_block(bp, NIG_BLOCK, init_stage);
REG_WR(bp, NIG_REG_XGXS_SERDES0_MODE_SEL + port*4, 1);
if (CHIP_IS_E1H(bp)) {
/* 0x2 disable e1hov, 0x1 enable */
REG_WR(bp, NIG_REG_LLH0_BRB1_DRV_MASK_MF + port*4,
(IS_E1HMF(bp) ? 0x1 : 0x2));
{
REG_WR(bp, NIG_REG_LLFC_ENABLE_0 + port*4, 0);
REG_WR(bp, NIG_REG_LLFC_OUT_EN_0 + port*4, 0);
REG_WR(bp, NIG_REG_PAUSE_ENABLE_0 + port*4, 1);
}
}
bnx2x_init_block(bp, MCP_BLOCK, init_stage);
bnx2x_init_block(bp, DMAE_BLOCK, init_stage);
switch (XGXS_EXT_PHY_TYPE(bp->link_params.ext_phy_config)) {
case PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM8726:
{
u32 swap_val, swap_override, aeu_gpio_mask, offset;
bnx2x_set_gpio(bp, MISC_REGISTERS_GPIO_3,
MISC_REGISTERS_GPIO_INPUT_HI_Z, port);
/* The GPIO should be swapped if the swap register is
set and active */
swap_val = REG_RD(bp, NIG_REG_PORT_SWAP);
swap_override = REG_RD(bp, NIG_REG_STRAP_OVERRIDE);
/* Select function upon port-swap configuration */
if (port == 0) {
offset = MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
aeu_gpio_mask = (swap_val && swap_override) ?
AEU_INPUTS_ATTN_BITS_GPIO3_FUNCTION_1 :
AEU_INPUTS_ATTN_BITS_GPIO3_FUNCTION_0;
} else {
offset = MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0;
aeu_gpio_mask = (swap_val && swap_override) ?
AEU_INPUTS_ATTN_BITS_GPIO3_FUNCTION_0 :
AEU_INPUTS_ATTN_BITS_GPIO3_FUNCTION_1;
}
val = REG_RD(bp, offset);
/* add GPIO3 to group */
val |= aeu_gpio_mask;
REG_WR(bp, offset, val);
}
break;
case PORT_HW_CFG_XGXS_EXT_PHY_TYPE_SFX7101:
case PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM8727:
/* add SPIO 5 to group 0 */
{
u32 reg_addr = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0);
val = REG_RD(bp, reg_addr);
val |= AEU_INPUTS_ATTN_BITS_SPIO5;
REG_WR(bp, reg_addr, val);
}
break;
default:
break;
}
bnx2x__link_reset(bp);
return 0;
}
#define ILT_PER_FUNC (768/2)
#define FUNC_ILT_BASE(func) (func * ILT_PER_FUNC)
/* the phys address is shifted right 12 bits and has an added
1=valid bit added to the 53rd bit
then since this is a wide register(TM)
we split it into two 32 bit writes
*/
#define ONCHIP_ADDR1(x) ((u32)(((u64)x >> 12) & 0xFFFFFFFF))
#define ONCHIP_ADDR2(x) ((u32)((1 << 20) | ((u64)x >> 44)))
#define PXP_ONE_ILT(x) (((x) << 10) | x)
#define PXP_ILT_RANGE(f, l) (((l) << 10) | f)
#ifdef BCM_CNIC
#define CNIC_ILT_LINES 127
#define CNIC_CTX_PER_ILT 16
#else
#define CNIC_ILT_LINES 0
#endif
static void bnx2x_ilt_wr(struct bnx2x *bp, u32 index, dma_addr_t addr)
{
int reg;
if (CHIP_IS_E1H(bp))
reg = PXP2_REG_RQ_ONCHIP_AT_B0 + index*8;
else /* E1 */
reg = PXP2_REG_RQ_ONCHIP_AT + index*8;
bnx2x_wb_wr(bp, reg, ONCHIP_ADDR1(addr), ONCHIP_ADDR2(addr));
}
static int bnx2x_init_func(struct bnx2x *bp)
{
int port = BP_PORT(bp);
int func = BP_FUNC(bp);
u32 addr, val;
int i;
DP(BNX2X_MSG_MCP, "starting func init func %d\n", func);
/* set MSI reconfigure capability */
addr = (port ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0);
val = REG_RD(bp, addr);
val |= HC_CONFIG_0_REG_MSI_ATTN_EN_0;
REG_WR(bp, addr, val);
i = FUNC_ILT_BASE(func);
bnx2x_ilt_wr(bp, i, bnx2x_sp_mapping(bp, context));
if (CHIP_IS_E1H(bp)) {
REG_WR(bp, PXP2_REG_RQ_CDU_FIRST_ILT, i);
REG_WR(bp, PXP2_REG_RQ_CDU_LAST_ILT, i + CNIC_ILT_LINES);
} else /* E1 */
REG_WR(bp, PXP2_REG_PSWRQ_CDU0_L2P + func*4,
PXP_ILT_RANGE(i, i + CNIC_ILT_LINES));
#ifdef BCM_CNIC
i += 1 + CNIC_ILT_LINES;
bnx2x_ilt_wr(bp, i, bp->timers_mapping);
if (CHIP_IS_E1(bp))
REG_WR(bp, PXP2_REG_PSWRQ_TM0_L2P + func*4, PXP_ONE_ILT(i));
else {
REG_WR(bp, PXP2_REG_RQ_TM_FIRST_ILT, i);
REG_WR(bp, PXP2_REG_RQ_TM_LAST_ILT, i);
}
i++;
bnx2x_ilt_wr(bp, i, bp->qm_mapping);
if (CHIP_IS_E1(bp))
REG_WR(bp, PXP2_REG_PSWRQ_QM0_L2P + func*4, PXP_ONE_ILT(i));
else {
REG_WR(bp, PXP2_REG_RQ_QM_FIRST_ILT, i);
REG_WR(bp, PXP2_REG_RQ_QM_LAST_ILT, i);
}
i++;
bnx2x_ilt_wr(bp, i, bp->t1_mapping);
if (CHIP_IS_E1(bp))
REG_WR(bp, PXP2_REG_PSWRQ_SRC0_L2P + func*4, PXP_ONE_ILT(i));
else {
REG_WR(bp, PXP2_REG_RQ_SRC_FIRST_ILT, i);
REG_WR(bp, PXP2_REG_RQ_SRC_LAST_ILT, i);
}
/* tell the searcher where the T2 table is */
REG_WR(bp, SRC_REG_COUNTFREE0 + port*4, 16*1024/64);
bnx2x_wb_wr(bp, SRC_REG_FIRSTFREE0 + port*16,
U64_LO(bp->t2_mapping), U64_HI(bp->t2_mapping));
bnx2x_wb_wr(bp, SRC_REG_LASTFREE0 + port*16,
U64_LO((u64)bp->t2_mapping + 16*1024 - 64),
U64_HI((u64)bp->t2_mapping + 16*1024 - 64));
REG_WR(bp, SRC_REG_NUMBER_HASH_BITS0 + port*4, 10);
#endif
if (CHIP_IS_E1H(bp)) {
bnx2x_init_block(bp, MISC_BLOCK, FUNC0_STAGE + func);
bnx2x_init_block(bp, TCM_BLOCK, FUNC0_STAGE + func);
bnx2x_init_block(bp, UCM_BLOCK, FUNC0_STAGE + func);
bnx2x_init_block(bp, CCM_BLOCK, FUNC0_STAGE + func);
bnx2x_init_block(bp, XCM_BLOCK, FUNC0_STAGE + func);
bnx2x_init_block(bp, TSEM_BLOCK, FUNC0_STAGE + func);
bnx2x_init_block(bp, USEM_BLOCK, FUNC0_STAGE + func);
bnx2x_init_block(bp, CSEM_BLOCK, FUNC0_STAGE + func);
bnx2x_init_block(bp, XSEM_BLOCK, FUNC0_STAGE + func);
REG_WR(bp, NIG_REG_LLH0_FUNC_EN + port*8, 1);
REG_WR(bp, NIG_REG_LLH0_FUNC_VLAN_ID + port*8, bp->e1hov);
}
/* HC init per function */
if (CHIP_IS_E1H(bp)) {
REG_WR(bp, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
REG_WR(bp, HC_REG_LEADING_EDGE_0 + port*8, 0);
REG_WR(bp, HC_REG_TRAILING_EDGE_0 + port*8, 0);
}
bnx2x_init_block(bp, HC_BLOCK, FUNC0_STAGE + func);
/* Reset PCIE errors for debug */
REG_WR(bp, 0x2114, 0xffffffff);
REG_WR(bp, 0x2120, 0xffffffff);
return 0;
}
static int bnx2x_init_hw(struct bnx2x *bp, u32 load_code)
{
int i, rc = 0;
DP(BNX2X_MSG_MCP, "function %d load_code %x\n",
BP_FUNC(bp), load_code);
bp->dmae_ready = 0;
mutex_init(&bp->dmae_mutex);
rc = bnx2x_gunzip_init(bp);
if (rc)
return rc;
switch (load_code) {
case FW_MSG_CODE_DRV_LOAD_COMMON:
rc = bnx2x_init_common(bp);
if (rc)
goto init_hw_err;
/* no break */
case FW_MSG_CODE_DRV_LOAD_PORT:
bp->dmae_ready = 1;
rc = bnx2x_init_port(bp);
if (rc)
goto init_hw_err;
/* no break */
case FW_MSG_CODE_DRV_LOAD_FUNCTION:
bp->dmae_ready = 1;
rc = bnx2x_init_func(bp);
if (rc)
goto init_hw_err;
break;
default:
BNX2X_ERR("Unknown load_code (0x%x) from MCP\n", load_code);
break;
}
if (!BP_NOMCP(bp)) {
int func = BP_FUNC(bp);
bp->fw_drv_pulse_wr_seq =
(SHMEM_RD(bp, func_mb[func].drv_pulse_mb) &
DRV_PULSE_SEQ_MASK);
DP(BNX2X_MSG_MCP, "drv_pulse 0x%x\n", bp->fw_drv_pulse_wr_seq);
}
/* this needs to be done before gunzip end */
bnx2x_zero_def_sb(bp);
for_each_queue(bp, i)
bnx2x_zero_sb(bp, BP_L_ID(bp) + i);
#ifdef BCM_CNIC
bnx2x_zero_sb(bp, BP_L_ID(bp) + i);
#endif
init_hw_err:
bnx2x_gunzip_end(bp);
return rc;
}
static void bnx2x_free_mem(struct bnx2x *bp)
{
#define BNX2X_PCI_FREE(x, y, size) \
do { \
if (x) { \
dma_free_coherent(&bp->pdev->dev, size, x, y); \
x = NULL; \
y = 0; \
} \
} while (0)
#define BNX2X_FREE(x) \
do { \
if (x) { \
vfree(x); \
x = NULL; \
} \
} while (0)
int i;
/* fastpath */
/* Common */
for_each_queue(bp, i) {
/* status blocks */
BNX2X_PCI_FREE(bnx2x_fp(bp, i, status_blk),
bnx2x_fp(bp, i, status_blk_mapping),
sizeof(struct host_status_block));
}
/* Rx */
for_each_queue(bp, i) {
/* fastpath rx rings: rx_buf rx_desc rx_comp */
BNX2X_FREE(bnx2x_fp(bp, i, rx_buf_ring));
BNX2X_PCI_FREE(bnx2x_fp(bp, i, rx_desc_ring),
bnx2x_fp(bp, i, rx_desc_mapping),
sizeof(struct eth_rx_bd) * NUM_RX_BD);
BNX2X_PCI_FREE(bnx2x_fp(bp, i, rx_comp_ring),
bnx2x_fp(bp, i, rx_comp_mapping),
sizeof(struct eth_fast_path_rx_cqe) *
NUM_RCQ_BD);
/* SGE ring */
BNX2X_FREE(bnx2x_fp(bp, i, rx_page_ring));
BNX2X_PCI_FREE(bnx2x_fp(bp, i, rx_sge_ring),
bnx2x_fp(bp, i, rx_sge_mapping),
BCM_PAGE_SIZE * NUM_RX_SGE_PAGES);
}
/* Tx */
for_each_queue(bp, i) {
/* fastpath tx rings: tx_buf tx_desc */
BNX2X_FREE(bnx2x_fp(bp, i, tx_buf_ring));
BNX2X_PCI_FREE(bnx2x_fp(bp, i, tx_desc_ring),
bnx2x_fp(bp, i, tx_desc_mapping),
sizeof(union eth_tx_bd_types) * NUM_TX_BD);
}
/* end of fastpath */
BNX2X_PCI_FREE(bp->def_status_blk, bp->def_status_blk_mapping,
sizeof(struct host_def_status_block));
BNX2X_PCI_FREE(bp->slowpath, bp->slowpath_mapping,
sizeof(struct bnx2x_slowpath));
#ifdef BCM_CNIC
BNX2X_PCI_FREE(bp->t1, bp->t1_mapping, 64*1024);
BNX2X_PCI_FREE(bp->t2, bp->t2_mapping, 16*1024);
BNX2X_PCI_FREE(bp->timers, bp->timers_mapping, 8*1024);
BNX2X_PCI_FREE(bp->qm, bp->qm_mapping, 128*1024);
BNX2X_PCI_FREE(bp->cnic_sb, bp->cnic_sb_mapping,
sizeof(struct host_status_block));
#endif
BNX2X_PCI_FREE(bp->spq, bp->spq_mapping, BCM_PAGE_SIZE);
#undef BNX2X_PCI_FREE
#undef BNX2X_KFREE
}
static int bnx2x_alloc_mem(struct bnx2x *bp)
{
#define BNX2X_PCI_ALLOC(x, y, size) \
do { \
x = dma_alloc_coherent(&bp->pdev->dev, size, y, GFP_KERNEL); \
if (x == NULL) \
goto alloc_mem_err; \
memset(x, 0, size); \
} while (0)
#define BNX2X_ALLOC(x, size) \
do { \
x = vmalloc(size); \
if (x == NULL) \
goto alloc_mem_err; \
memset(x, 0, size); \
} while (0)
int i;
/* fastpath */
/* Common */
for_each_queue(bp, i) {
bnx2x_fp(bp, i, bp) = bp;
/* status blocks */
BNX2X_PCI_ALLOC(bnx2x_fp(bp, i, status_blk),
&bnx2x_fp(bp, i, status_blk_mapping),
sizeof(struct host_status_block));
}
/* Rx */
for_each_queue(bp, i) {
/* fastpath rx rings: rx_buf rx_desc rx_comp */
BNX2X_ALLOC(bnx2x_fp(bp, i, rx_buf_ring),
sizeof(struct sw_rx_bd) * NUM_RX_BD);
BNX2X_PCI_ALLOC(bnx2x_fp(bp, i, rx_desc_ring),
&bnx2x_fp(bp, i, rx_desc_mapping),
sizeof(struct eth_rx_bd) * NUM_RX_BD);
BNX2X_PCI_ALLOC(bnx2x_fp(bp, i, rx_comp_ring),
&bnx2x_fp(bp, i, rx_comp_mapping),
sizeof(struct eth_fast_path_rx_cqe) *
NUM_RCQ_BD);
/* SGE ring */
BNX2X_ALLOC(bnx2x_fp(bp, i, rx_page_ring),
sizeof(struct sw_rx_page) * NUM_RX_SGE);
BNX2X_PCI_ALLOC(bnx2x_fp(bp, i, rx_sge_ring),
&bnx2x_fp(bp, i, rx_sge_mapping),
BCM_PAGE_SIZE * NUM_RX_SGE_PAGES);
}
/* Tx */
for_each_queue(bp, i) {
/* fastpath tx rings: tx_buf tx_desc */
BNX2X_ALLOC(bnx2x_fp(bp, i, tx_buf_ring),
sizeof(struct sw_tx_bd) * NUM_TX_BD);
BNX2X_PCI_ALLOC(bnx2x_fp(bp, i, tx_desc_ring),
&bnx2x_fp(bp, i, tx_desc_mapping),
sizeof(union eth_tx_bd_types) * NUM_TX_BD);
}
/* end of fastpath */
BNX2X_PCI_ALLOC(bp->def_status_blk, &bp->def_status_blk_mapping,
sizeof(struct host_def_status_block));
BNX2X_PCI_ALLOC(bp->slowpath, &bp->slowpath_mapping,
sizeof(struct bnx2x_slowpath));
#ifdef BCM_CNIC
BNX2X_PCI_ALLOC(bp->t1, &bp->t1_mapping, 64*1024);
/* allocate searcher T2 table
we allocate 1/4 of alloc num for T2
(which is not entered into the ILT) */
BNX2X_PCI_ALLOC(bp->t2, &bp->t2_mapping, 16*1024);
/* Initialize T2 (for 1024 connections) */
for (i = 0; i < 16*1024; i += 64)
*(u64 *)((char *)bp->t2 + i + 56) = bp->t2_mapping + i + 64;
/* Timer block array (8*MAX_CONN) phys uncached for now 1024 conns */
BNX2X_PCI_ALLOC(bp->timers, &bp->timers_mapping, 8*1024);
/* QM queues (128*MAX_CONN) */
BNX2X_PCI_ALLOC(bp->qm, &bp->qm_mapping, 128*1024);
BNX2X_PCI_ALLOC(bp->cnic_sb, &bp->cnic_sb_mapping,
sizeof(struct host_status_block));
#endif
/* Slow path ring */
BNX2X_PCI_ALLOC(bp->spq, &bp->spq_mapping, BCM_PAGE_SIZE);
return 0;
alloc_mem_err:
bnx2x_free_mem(bp);
return -ENOMEM;
#undef BNX2X_PCI_ALLOC
#undef BNX2X_ALLOC
}
static void bnx2x_free_tx_skbs(struct bnx2x *bp)
{
int i;
for_each_queue(bp, i) {
struct bnx2x_fastpath *fp = &bp->fp[i];
u16 bd_cons = fp->tx_bd_cons;
u16 sw_prod = fp->tx_pkt_prod;
u16 sw_cons = fp->tx_pkt_cons;
while (sw_cons != sw_prod) {
bd_cons = bnx2x_free_tx_pkt(bp, fp, TX_BD(sw_cons));
sw_cons++;
}
}
}
static void bnx2x_free_rx_skbs(struct bnx2x *bp)
{
int i, j;
for_each_queue(bp, j) {
struct bnx2x_fastpath *fp = &bp->fp[j];
for (i = 0; i < NUM_RX_BD; i++) {
struct sw_rx_bd *rx_buf = &fp->rx_buf_ring[i];
struct sk_buff *skb = rx_buf->skb;
if (skb == NULL)
continue;
dma_unmap_single(&bp->pdev->dev,
dma_unmap_addr(rx_buf, mapping),
bp->rx_buf_size, DMA_FROM_DEVICE);
rx_buf->skb = NULL;
dev_kfree_skb(skb);
}
if (!fp->disable_tpa)
bnx2x_free_tpa_pool(bp, fp, CHIP_IS_E1(bp) ?
ETH_MAX_AGGREGATION_QUEUES_E1 :
ETH_MAX_AGGREGATION_QUEUES_E1H);
}
}
static void bnx2x_free_skbs(struct bnx2x *bp)
{
bnx2x_free_tx_skbs(bp);
bnx2x_free_rx_skbs(bp);
}
static void bnx2x_free_msix_irqs(struct bnx2x *bp)
{
int i, offset = 1;
free_irq(bp->msix_table[0].vector, bp->dev);
DP(NETIF_MSG_IFDOWN, "released sp irq (%d)\n",
bp->msix_table[0].vector);
#ifdef BCM_CNIC
offset++;
#endif
for_each_queue(bp, i) {
DP(NETIF_MSG_IFDOWN, "about to release fp #%d->%d irq "
"state %x\n", i, bp->msix_table[i + offset].vector,
bnx2x_fp(bp, i, state));
free_irq(bp->msix_table[i + offset].vector, &bp->fp[i]);
}
}
static void bnx2x_free_irq(struct bnx2x *bp, bool disable_only)
{
if (bp->flags & USING_MSIX_FLAG) {
if (!disable_only)
bnx2x_free_msix_irqs(bp);
pci_disable_msix(bp->pdev);
bp->flags &= ~USING_MSIX_FLAG;
} else if (bp->flags & USING_MSI_FLAG) {
if (!disable_only)
free_irq(bp->pdev->irq, bp->dev);
pci_disable_msi(bp->pdev);
bp->flags &= ~USING_MSI_FLAG;
} else if (!disable_only)
free_irq(bp->pdev->irq, bp->dev);
}
static int bnx2x_enable_msix(struct bnx2x *bp)
{
int i, rc, offset = 1;
int igu_vec = 0;
bp->msix_table[0].entry = igu_vec;
DP(NETIF_MSG_IFUP, "msix_table[0].entry = %d (slowpath)\n", igu_vec);
#ifdef BCM_CNIC
igu_vec = BP_L_ID(bp) + offset;
bp->msix_table[1].entry = igu_vec;
DP(NETIF_MSG_IFUP, "msix_table[1].entry = %d (CNIC)\n", igu_vec);
offset++;
#endif
for_each_queue(bp, i) {
igu_vec = BP_L_ID(bp) + offset + i;
bp->msix_table[i + offset].entry = igu_vec;
DP(NETIF_MSG_IFUP, "msix_table[%d].entry = %d "
"(fastpath #%u)\n", i + offset, igu_vec, i);
}
rc = pci_enable_msix(bp->pdev, &bp->msix_table[0],
BNX2X_NUM_QUEUES(bp) + offset);
/*
* reconfigure number of tx/rx queues according to available
* MSI-X vectors
*/
if (rc >= BNX2X_MIN_MSIX_VEC_CNT) {
/* vectors available for FP */
int fp_vec = rc - BNX2X_MSIX_VEC_FP_START;
DP(NETIF_MSG_IFUP,
"Trying to use less MSI-X vectors: %d\n", rc);
rc = pci_enable_msix(bp->pdev, &bp->msix_table[0], rc);
if (rc) {
DP(NETIF_MSG_IFUP,
"MSI-X is not attainable rc %d\n", rc);
return rc;
}
bp->num_queues = min(bp->num_queues, fp_vec);
DP(NETIF_MSG_IFUP, "New queue configuration set: %d\n",
bp->num_queues);
} else if (rc) {
DP(NETIF_MSG_IFUP, "MSI-X is not attainable rc %d\n", rc);
return rc;
}
bp->flags |= USING_MSIX_FLAG;
return 0;
}
static int bnx2x_req_msix_irqs(struct bnx2x *bp)
{
int i, rc, offset = 1;
rc = request_irq(bp->msix_table[0].vector, bnx2x_msix_sp_int, 0,
bp->dev->name, bp->dev);
if (rc) {
BNX2X_ERR("request sp irq failed\n");
return -EBUSY;
}
#ifdef BCM_CNIC
offset++;
#endif
for_each_queue(bp, i) {
struct bnx2x_fastpath *fp = &bp->fp[i];
snprintf(fp->name, sizeof(fp->name), "%s-fp-%d",
bp->dev->name, i);
rc = request_irq(bp->msix_table[i + offset].vector,
bnx2x_msix_fp_int, 0, fp->name, fp);
if (rc) {
BNX2X_ERR("request fp #%d irq failed rc %d\n", i, rc);
bnx2x_free_msix_irqs(bp);
return -EBUSY;
}
fp->state = BNX2X_FP_STATE_IRQ;
}
i = BNX2X_NUM_QUEUES(bp);
netdev_info(bp->dev, "using MSI-X IRQs: sp %d fp[%d] %d"
" ... fp[%d] %d\n",
bp->msix_table[0].vector,
0, bp->msix_table[offset].vector,
i - 1, bp->msix_table[offset + i - 1].vector);
return 0;
}
static int bnx2x_enable_msi(struct bnx2x *bp)
{
int rc;
rc = pci_enable_msi(bp->pdev);
if (rc) {
DP(NETIF_MSG_IFUP, "MSI is not attainable\n");
return -1;
}
bp->flags |= USING_MSI_FLAG;
return 0;
}
static int bnx2x_req_irq(struct bnx2x *bp)
{
unsigned long flags;
int rc;
if (bp->flags & USING_MSI_FLAG)
flags = 0;
else
flags = IRQF_SHARED;
rc = request_irq(bp->pdev->irq, bnx2x_interrupt, flags,
bp->dev->name, bp->dev);
if (!rc)
bnx2x_fp(bp, 0, state) = BNX2X_FP_STATE_IRQ;
return rc;
}
static void bnx2x_napi_enable(struct bnx2x *bp)
{
int i;
for_each_queue(bp, i)
napi_enable(&bnx2x_fp(bp, i, napi));
}
static void bnx2x_napi_disable(struct bnx2x *bp)
{
int i;
for_each_queue(bp, i)
napi_disable(&bnx2x_fp(bp, i, napi));
}
static void bnx2x_netif_start(struct bnx2x *bp)
{
int intr_sem;
intr_sem = atomic_dec_and_test(&bp->intr_sem);
smp_wmb(); /* Ensure that bp->intr_sem update is SMP-safe */
if (intr_sem) {
if (netif_running(bp->dev)) {
bnx2x_napi_enable(bp);
bnx2x_int_enable(bp);
if (bp->state == BNX2X_STATE_OPEN)
netif_tx_wake_all_queues(bp->dev);
}
}
}
static void bnx2x_netif_stop(struct bnx2x *bp, int disable_hw)
{
bnx2x_int_disable_sync(bp, disable_hw);
bnx2x_napi_disable(bp);
netif_tx_disable(bp->dev);
}
/*
* Init service functions
*/
/**
* Sets a MAC in a CAM for a few L2 Clients for E1 chip
*
* @param bp driver descriptor
* @param set set or clear an entry (1 or 0)
* @param mac pointer to a buffer containing a MAC
* @param cl_bit_vec bit vector of clients to register a MAC for
* @param cam_offset offset in a CAM to use
* @param with_bcast set broadcast MAC as well
*/
static void bnx2x_set_mac_addr_e1_gen(struct bnx2x *bp, int set, u8 *mac,
u32 cl_bit_vec, u8 cam_offset,
u8 with_bcast)
{
struct mac_configuration_cmd *config = bnx2x_sp(bp, mac_config);
int port = BP_PORT(bp);
/* CAM allocation
* unicasts 0-31:port0 32-63:port1
* multicast 64-127:port0 128-191:port1
*/
config->hdr.length = 1 + (with_bcast ? 1 : 0);
config->hdr.offset = cam_offset;
config->hdr.client_id = 0xff;
config->hdr.reserved1 = 0;
/* primary MAC */
config->config_table[0].cam_entry.msb_mac_addr =
swab16(*(u16 *)&mac[0]);
config->config_table[0].cam_entry.middle_mac_addr =
swab16(*(u16 *)&mac[2]);
config->config_table[0].cam_entry.lsb_mac_addr =
swab16(*(u16 *)&mac[4]);
config->config_table[0].cam_entry.flags = cpu_to_le16(port);
if (set)
config->config_table[0].target_table_entry.flags = 0;
else
CAM_INVALIDATE(config->config_table[0]);
config->config_table[0].target_table_entry.clients_bit_vector =
cpu_to_le32(cl_bit_vec);
config->config_table[0].target_table_entry.vlan_id = 0;
DP(NETIF_MSG_IFUP, "%s MAC (%04x:%04x:%04x)\n",
(set ? "setting" : "clearing"),
config->config_table[0].cam_entry.msb_mac_addr,
config->config_table[0].cam_entry.middle_mac_addr,
config->config_table[0].cam_entry.lsb_mac_addr);
/* broadcast */
if (with_bcast) {
config->config_table[1].cam_entry.msb_mac_addr =
cpu_to_le16(0xffff);
config->config_table[1].cam_entry.middle_mac_addr =
cpu_to_le16(0xffff);
config->config_table[1].cam_entry.lsb_mac_addr =
cpu_to_le16(0xffff);
config->config_table[1].cam_entry.flags = cpu_to_le16(port);
if (set)
config->config_table[1].target_table_entry.flags =
TSTORM_CAM_TARGET_TABLE_ENTRY_BROADCAST;
else
CAM_INVALIDATE(config->config_table[1]);
config->config_table[1].target_table_entry.clients_bit_vector =
cpu_to_le32(cl_bit_vec);
config->config_table[1].target_table_entry.vlan_id = 0;
}
bnx2x_sp_post(bp, RAMROD_CMD_ID_ETH_SET_MAC, 0,
U64_HI(bnx2x_sp_mapping(bp, mac_config)),
U64_LO(bnx2x_sp_mapping(bp, mac_config)), 0);
}
/**
* Sets a MAC in a CAM for a few L2 Clients for E1H chip
*
* @param bp driver descriptor
* @param set set or clear an entry (1 or 0)
* @param mac pointer to a buffer containing a MAC
* @param cl_bit_vec bit vector of clients to register a MAC for
* @param cam_offset offset in a CAM to use
*/
static void bnx2x_set_mac_addr_e1h_gen(struct bnx2x *bp, int set, u8 *mac,
u32 cl_bit_vec, u8 cam_offset)
{
struct mac_configuration_cmd_e1h *config =
(struct mac_configuration_cmd_e1h *)bnx2x_sp(bp, mac_config);
config->hdr.length = 1;
config->hdr.offset = cam_offset;
config->hdr.client_id = 0xff;
config->hdr.reserved1 = 0;
/* primary MAC */
config->config_table[0].msb_mac_addr =
swab16(*(u16 *)&mac[0]);
config->config_table[0].middle_mac_addr =
swab16(*(u16 *)&mac[2]);
config->config_table[0].lsb_mac_addr =
swab16(*(u16 *)&mac[4]);
config->config_table[0].clients_bit_vector =
cpu_to_le32(cl_bit_vec);
config->config_table[0].vlan_id = 0;
config->config_table[0].e1hov_id = cpu_to_le16(bp->e1hov);
if (set)
config->config_table[0].flags = BP_PORT(bp);
else
config->config_table[0].flags =
MAC_CONFIGURATION_ENTRY_E1H_ACTION_TYPE;
DP(NETIF_MSG_IFUP, "%s MAC (%04x:%04x:%04x) E1HOV %d CLID mask %d\n",
(set ? "setting" : "clearing"),
config->config_table[0].msb_mac_addr,
config->config_table[0].middle_mac_addr,
config->config_table[0].lsb_mac_addr, bp->e1hov, cl_bit_vec);
bnx2x_sp_post(bp, RAMROD_CMD_ID_ETH_SET_MAC, 0,
U64_HI(bnx2x_sp_mapping(bp, mac_config)),
U64_LO(bnx2x_sp_mapping(bp, mac_config)), 0);
}
static int bnx2x_wait_ramrod(struct bnx2x *bp, int state, int idx,
int *state_p, int poll)
{
/* can take a while if any port is running */
int cnt = 5000;
DP(NETIF_MSG_IFUP, "%s for state to become %x on IDX [%d]\n",
poll ? "polling" : "waiting", state, idx);
might_sleep();
while (cnt--) {
if (poll) {
bnx2x_rx_int(bp->fp, 10);
/* if index is different from 0
* the reply for some commands will
* be on the non default queue
*/
if (idx)
bnx2x_rx_int(&bp->fp[idx], 10);
}
mb(); /* state is changed by bnx2x_sp_event() */
if (*state_p == state) {
#ifdef BNX2X_STOP_ON_ERROR
DP(NETIF_MSG_IFUP, "exit (cnt %d)\n", 5000 - cnt);
#endif
return 0;
}
msleep(1);
if (bp->panic)
return -EIO;
}
/* timeout! */
BNX2X_ERR("timeout %s for state %x on IDX [%d]\n",
poll ? "polling" : "waiting", state, idx);
#ifdef BNX2X_STOP_ON_ERROR
bnx2x_panic();
#endif
return -EBUSY;
}
static void bnx2x_set_eth_mac_addr_e1h(struct bnx2x *bp, int set)
{
bp->set_mac_pending++;
smp_wmb();
bnx2x_set_mac_addr_e1h_gen(bp, set, bp->dev->dev_addr,
(1 << bp->fp->cl_id), BP_FUNC(bp));
/* Wait for a completion */
bnx2x_wait_ramrod(bp, 0, 0, &bp->set_mac_pending, set ? 0 : 1);
}
static void bnx2x_set_eth_mac_addr_e1(struct bnx2x *bp, int set)
{
bp->set_mac_pending++;
smp_wmb();
bnx2x_set_mac_addr_e1_gen(bp, set, bp->dev->dev_addr,
(1 << bp->fp->cl_id), (BP_PORT(bp) ? 32 : 0),
1);
/* Wait for a completion */
bnx2x_wait_ramrod(bp, 0, 0, &bp->set_mac_pending, set ? 0 : 1);
}
#ifdef BCM_CNIC
/**
* Set iSCSI MAC(s) at the next enties in the CAM after the ETH
* MAC(s). This function will wait until the ramdord completion
* returns.
*
* @param bp driver handle
* @param set set or clear the CAM entry
*
* @return 0 if cussess, -ENODEV if ramrod doesn't return.
*/
static int bnx2x_set_iscsi_eth_mac_addr(struct bnx2x *bp, int set)
{
u32 cl_bit_vec = (1 << BCM_ISCSI_ETH_CL_ID);
bp->set_mac_pending++;
smp_wmb();
/* Send a SET_MAC ramrod */
if (CHIP_IS_E1(bp))
bnx2x_set_mac_addr_e1_gen(bp, set, bp->iscsi_mac,
cl_bit_vec, (BP_PORT(bp) ? 32 : 0) + 2,
1);
else
/* CAM allocation for E1H
* unicasts: by func number
* multicast: 20+FUNC*20, 20 each
*/
bnx2x_set_mac_addr_e1h_gen(bp, set, bp->iscsi_mac,
cl_bit_vec, E1H_FUNC_MAX + BP_FUNC(bp));
/* Wait for a completion when setting */
bnx2x_wait_ramrod(bp, 0, 0, &bp->set_mac_pending, set ? 0 : 1);
return 0;
}
#endif
static int bnx2x_setup_leading(struct bnx2x *bp)
{
int rc;
/* reset IGU state */
bnx2x_ack_sb(bp, bp->fp[0].sb_id, CSTORM_ID, 0, IGU_INT_ENABLE, 0);
/* SETUP ramrod */
bnx2x_sp_post(bp, RAMROD_CMD_ID_ETH_PORT_SETUP, 0, 0, 0, 0);
/* Wait for completion */
rc = bnx2x_wait_ramrod(bp, BNX2X_STATE_OPEN, 0, &(bp->state), 0);
return rc;
}
static int bnx2x_setup_multi(struct bnx2x *bp, int index)
{
struct bnx2x_fastpath *fp = &bp->fp[index];
/* reset IGU state */
bnx2x_ack_sb(bp, fp->sb_id, CSTORM_ID, 0, IGU_INT_ENABLE, 0);
/* SETUP ramrod */
fp->state = BNX2X_FP_STATE_OPENING;
bnx2x_sp_post(bp, RAMROD_CMD_ID_ETH_CLIENT_SETUP, index, 0,
fp->cl_id, 0);
/* Wait for completion */
return bnx2x_wait_ramrod(bp, BNX2X_FP_STATE_OPEN, index,
&(fp->state), 0);
}
static int bnx2x_poll(struct napi_struct *napi, int budget);
static void bnx2x_set_num_queues_msix(struct bnx2x *bp)
{
switch (bp->multi_mode) {
case ETH_RSS_MODE_DISABLED:
bp->num_queues = 1;
break;
case ETH_RSS_MODE_REGULAR:
if (num_queues)
bp->num_queues = min_t(u32, num_queues,
BNX2X_MAX_QUEUES(bp));
else
bp->num_queues = min_t(u32, num_online_cpus(),
BNX2X_MAX_QUEUES(bp));
break;
default:
bp->num_queues = 1;
break;
}
}
static int bnx2x_set_num_queues(struct bnx2x *bp)
{
int rc = 0;
switch (int_mode) {
case INT_MODE_INTx:
case INT_MODE_MSI:
bp->num_queues = 1;
DP(NETIF_MSG_IFUP, "set number of queues to 1\n");
break;
default:
/* Set number of queues according to bp->multi_mode value */
bnx2x_set_num_queues_msix(bp);
DP(NETIF_MSG_IFUP, "set number of queues to %d\n",
bp->num_queues);
/* if we can't use MSI-X we only need one fp,
* so try to enable MSI-X with the requested number of fp's
* and fallback to MSI or legacy INTx with one fp
*/
rc = bnx2x_enable_msix(bp);
if (rc)
/* failed to enable MSI-X */
bp->num_queues = 1;
break;
}
bp->dev->real_num_tx_queues = bp->num_queues;
return rc;
}
#ifdef BCM_CNIC
static int bnx2x_cnic_notify(struct bnx2x *bp, int cmd);
static void bnx2x_setup_cnic_irq_info(struct bnx2x *bp);
#endif
/* must be called with rtnl_lock */
static int bnx2x_nic_load(struct bnx2x *bp, int load_mode)
{
u32 load_code;
int i, rc;
#ifdef BNX2X_STOP_ON_ERROR
if (unlikely(bp->panic))
return -EPERM;
#endif
bp->state = BNX2X_STATE_OPENING_WAIT4_LOAD;
rc = bnx2x_set_num_queues(bp);
if (bnx2x_alloc_mem(bp)) {
bnx2x_free_irq(bp, true);
return -ENOMEM;
}
for_each_queue(bp, i)
bnx2x_fp(bp, i, disable_tpa) =
((bp->flags & TPA_ENABLE_FLAG) == 0);
for_each_queue(bp, i)
netif_napi_add(bp->dev, &bnx2x_fp(bp, i, napi),
bnx2x_poll, 128);
bnx2x_napi_enable(bp);
if (bp->flags & USING_MSIX_FLAG) {
rc = bnx2x_req_msix_irqs(bp);
if (rc) {
bnx2x_free_irq(bp, true);
goto load_error1;
}
} else {
/* Fall to INTx if failed to enable MSI-X due to lack of
memory (in bnx2x_set_num_queues()) */
if ((rc != -ENOMEM) && (int_mode != INT_MODE_INTx))
bnx2x_enable_msi(bp);
bnx2x_ack_int(bp);
rc = bnx2x_req_irq(bp);
if (rc) {
BNX2X_ERR("IRQ request failed rc %d, aborting\n", rc);
bnx2x_free_irq(bp, true);
goto load_error1;
}
if (bp->flags & USING_MSI_FLAG) {
bp->dev->irq = bp->pdev->irq;
netdev_info(bp->dev, "using MSI IRQ %d\n",
bp->pdev->irq);
}
}
/* Send LOAD_REQUEST command to MCP
Returns the type of LOAD command:
if it is the first port to be initialized
common blocks should be initialized, otherwise - not
*/
if (!BP_NOMCP(bp)) {
load_code = bnx2x_fw_command(bp, DRV_MSG_CODE_LOAD_REQ);
if (!load_code) {
BNX2X_ERR("MCP response failure, aborting\n");
rc = -EBUSY;
goto load_error2;
}
if (load_code == FW_MSG_CODE_DRV_LOAD_REFUSED) {
rc = -EBUSY; /* other port in diagnostic mode */
goto load_error2;
}
} else {
int port = BP_PORT(bp);
DP(NETIF_MSG_IFUP, "NO MCP - load counts %d, %d, %d\n",
load_count[0], load_count[1], load_count[2]);
load_count[0]++;
load_count[1 + port]++;
DP(NETIF_MSG_IFUP, "NO MCP - new load counts %d, %d, %d\n",
load_count[0], load_count[1], load_count[2]);
if (load_count[0] == 1)
load_code = FW_MSG_CODE_DRV_LOAD_COMMON;
else if (load_count[1 + port] == 1)
load_code = FW_MSG_CODE_DRV_LOAD_PORT;
else
load_code = FW_MSG_CODE_DRV_LOAD_FUNCTION;
}
if ((load_code == FW_MSG_CODE_DRV_LOAD_COMMON) ||
(load_code == FW_MSG_CODE_DRV_LOAD_PORT))
bp->port.pmf = 1;
else
bp->port.pmf = 0;
DP(NETIF_MSG_LINK, "pmf %d\n", bp->port.pmf);
/* Initialize HW */
rc = bnx2x_init_hw(bp, load_code);
if (rc) {
BNX2X_ERR("HW init failed, aborting\n");
bnx2x_fw_command(bp, DRV_MSG_CODE_LOAD_DONE);
bnx2x_fw_command(bp, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP);
bnx2x_fw_command(bp, DRV_MSG_CODE_UNLOAD_DONE);
goto load_error2;
}
/* Setup NIC internals and enable interrupts */
bnx2x_nic_init(bp, load_code);
if ((load_code == FW_MSG_CODE_DRV_LOAD_COMMON) &&
(bp->common.shmem2_base))
SHMEM2_WR(bp, dcc_support,
(SHMEM_DCC_SUPPORT_DISABLE_ENABLE_PF_TLV |
SHMEM_DCC_SUPPORT_BANDWIDTH_ALLOCATION_TLV));
/* Send LOAD_DONE command to MCP */
if (!BP_NOMCP(bp)) {
load_code = bnx2x_fw_command(bp, DRV_MSG_CODE_LOAD_DONE);
if (!load_code) {
BNX2X_ERR("MCP response failure, aborting\n");
rc = -EBUSY;
goto load_error3;
}
}
bp->state = BNX2X_STATE_OPENING_WAIT4_PORT;
rc = bnx2x_setup_leading(bp);
if (rc) {
BNX2X_ERR("Setup leading failed!\n");
#ifndef BNX2X_STOP_ON_ERROR
goto load_error3;
#else
bp->panic = 1;
return -EBUSY;
#endif
}
if (CHIP_IS_E1H(bp))
if (bp->mf_config & FUNC_MF_CFG_FUNC_DISABLED) {
DP(NETIF_MSG_IFUP, "mf_cfg function disabled\n");
bp->flags |= MF_FUNC_DIS;
}
if (bp->state == BNX2X_STATE_OPEN) {
#ifdef BCM_CNIC
/* Enable Timer scan */
REG_WR(bp, TM_REG_EN_LINEAR0_TIMER + BP_PORT(bp)*4, 1);
#endif
for_each_nondefault_queue(bp, i) {
rc = bnx2x_setup_multi(bp, i);
if (rc)
#ifdef BCM_CNIC
goto load_error4;
#else
goto load_error3;
#endif
}
if (CHIP_IS_E1(bp))
bnx2x_set_eth_mac_addr_e1(bp, 1);
else
bnx2x_set_eth_mac_addr_e1h(bp, 1);
#ifdef BCM_CNIC
/* Set iSCSI L2 MAC */
mutex_lock(&bp->cnic_mutex);
if (bp->cnic_eth_dev.drv_state & CNIC_DRV_STATE_REGD) {
bnx2x_set_iscsi_eth_mac_addr(bp, 1);
bp->cnic_flags |= BNX2X_CNIC_FLAG_MAC_SET;
bnx2x_init_sb(bp, bp->cnic_sb, bp->cnic_sb_mapping,
CNIC_SB_ID(bp));
}
mutex_unlock(&bp->cnic_mutex);
#endif
}
if (bp->port.pmf)
bnx2x_initial_phy_init(bp, load_mode);
/* Start fast path */
switch (load_mode) {
case LOAD_NORMAL:
if (bp->state == BNX2X_STATE_OPEN) {
/* Tx queue should be only reenabled */
netif_tx_wake_all_queues(bp->dev);
}
/* Initialize the receive filter. */
bnx2x_set_rx_mode(bp->dev);
break;
case LOAD_OPEN:
netif_tx_start_all_queues(bp->dev);
if (bp->state != BNX2X_STATE_OPEN)
netif_tx_disable(bp->dev);
/* Initialize the receive filter. */
bnx2x_set_rx_mode(bp->dev);
break;
case LOAD_DIAG:
/* Initialize the receive filter. */
bnx2x_set_rx_mode(bp->dev);
bp->state = BNX2X_STATE_DIAG;
break;
default:
break;
}
if (!bp->port.pmf)
bnx2x__link_status_update(bp);
/* start the timer */
mod_timer(&bp->timer, jiffies + bp->current_interval);
#ifdef BCM_CNIC
bnx2x_setup_cnic_irq_info(bp);
if (bp->state == BNX2X_STATE_OPEN)
bnx2x_cnic_notify(bp, CNIC_CTL_START_CMD);
#endif
bnx2x_inc_load_cnt(bp);
return 0;
#ifdef BCM_CNIC
load_error4:
/* Disable Timer scan */
REG_WR(bp, TM_REG_EN_LINEAR0_TIMER + BP_PORT(bp)*4, 0);
#endif
load_error3:
bnx2x_int_disable_sync(bp, 1);
if (!BP_NOMCP(bp)) {
bnx2x_fw_command(bp, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP);
bnx2x_fw_command(bp, DRV_MSG_CODE_UNLOAD_DONE);
}
bp->port.pmf = 0;
/* Free SKBs, SGEs, TPA pool and driver internals */
bnx2x_free_skbs(bp);
for_each_queue(bp, i)
bnx2x_free_rx_sge_range(bp, bp->fp + i, NUM_RX_SGE);
load_error2:
/* Release IRQs */
bnx2x_free_irq(bp, false);
load_error1:
bnx2x_napi_disable(bp);
for_each_queue(bp, i)
netif_napi_del(&bnx2x_fp(bp, i, napi));
bnx2x_free_mem(bp);
return rc;
}
static int bnx2x_stop_multi(struct bnx2x *bp, int index)
{
struct bnx2x_fastpath *fp = &bp->fp[index];
int rc;
/* halt the connection */
fp->state = BNX2X_FP_STATE_HALTING;
bnx2x_sp_post(bp, RAMROD_CMD_ID_ETH_HALT, index, 0, fp->cl_id, 0);
/* Wait for completion */
rc = bnx2x_wait_ramrod(bp, BNX2X_FP_STATE_HALTED, index,
&(fp->state), 1);
if (rc) /* timeout */
return rc;
/* delete cfc entry */
bnx2x_sp_post(bp, RAMROD_CMD_ID_ETH_CFC_DEL, index, 0, 0, 1);
/* Wait for completion */
rc = bnx2x_wait_ramrod(bp, BNX2X_FP_STATE_CLOSED, index,
&(fp->state), 1);
return rc;
}
static int bnx2x_stop_leading(struct bnx2x *bp)
{
__le16 dsb_sp_prod_idx;
/* if the other port is handling traffic,
this can take a lot of time */
int cnt = 500;
int rc;
might_sleep();
/* Send HALT ramrod */
bp->fp[0].state = BNX2X_FP_STATE_HALTING;
bnx2x_sp_post(bp, RAMROD_CMD_ID_ETH_HALT, 0, 0, bp->fp->cl_id, 0);
/* Wait for completion */
rc = bnx2x_wait_ramrod(bp, BNX2X_FP_STATE_HALTED, 0,
&(bp->fp[0].state), 1);
if (rc) /* timeout */
return rc;
dsb_sp_prod_idx = *bp->dsb_sp_prod;
/* Send PORT_DELETE ramrod */
bnx2x_sp_post(bp, RAMROD_CMD_ID_ETH_PORT_DEL, 0, 0, 0, 1);
/* Wait for completion to arrive on default status block
we are going to reset the chip anyway
so there is not much to do if this times out
*/
while (dsb_sp_prod_idx == *bp->dsb_sp_prod) {
if (!cnt) {
DP(NETIF_MSG_IFDOWN, "timeout waiting for port del "
"dsb_sp_prod 0x%x != dsb_sp_prod_idx 0x%x\n",
*bp->dsb_sp_prod, dsb_sp_prod_idx);
#ifdef BNX2X_STOP_ON_ERROR
bnx2x_panic();
#endif
rc = -EBUSY;
break;
}
cnt--;
msleep(1);
rmb(); /* Refresh the dsb_sp_prod */
}
bp->state = BNX2X_STATE_CLOSING_WAIT4_UNLOAD;
bp->fp[0].state = BNX2X_FP_STATE_CLOSED;
return rc;
}
static void bnx2x_reset_func(struct bnx2x *bp)
{
int port = BP_PORT(bp);
int func = BP_FUNC(bp);
int base, i;
/* Configure IGU */
REG_WR(bp, HC_REG_LEADING_EDGE_0 + port*8, 0);
REG_WR(bp, HC_REG_TRAILING_EDGE_0 + port*8, 0);
#ifdef BCM_CNIC
/* Disable Timer scan */
REG_WR(bp, TM_REG_EN_LINEAR0_TIMER + port*4, 0);
/*
* Wait for at least 10ms and up to 2 second for the timers scan to
* complete
*/
for (i = 0; i < 200; i++) {
msleep(10);
if (!REG_RD(bp, TM_REG_LIN0_SCAN_ON + port*4))
break;
}
#endif
/* Clear ILT */
base = FUNC_ILT_BASE(func);
for (i = base; i < base + ILT_PER_FUNC; i++)
bnx2x_ilt_wr(bp, i, 0);
}
static void bnx2x_reset_port(struct bnx2x *bp)
{
int port = BP_PORT(bp);
u32 val;
REG_WR(bp, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
/* Do not rcv packets to BRB */
REG_WR(bp, NIG_REG_LLH0_BRB1_DRV_MASK + port*4, 0x0);
/* Do not direct rcv packets that are not for MCP to the BRB */
REG_WR(bp, (port ? NIG_REG_LLH1_BRB1_NOT_MCP :
NIG_REG_LLH0_BRB1_NOT_MCP), 0x0);
/* Configure AEU */
REG_WR(bp, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, 0);
msleep(100);
/* Check for BRB port occupancy */
val = REG_RD(bp, BRB1_REG_PORT_NUM_OCC_BLOCKS_0 + port*4);
if (val)
DP(NETIF_MSG_IFDOWN,
"BRB1 is not empty %d blocks are occupied\n", val);
/* TODO: Close Doorbell port? */
}
static void bnx2x_reset_chip(struct bnx2x *bp, u32 reset_code)
{
DP(BNX2X_MSG_MCP, "function %d reset_code %x\n",
BP_FUNC(bp), reset_code);
switch (reset_code) {
case FW_MSG_CODE_DRV_UNLOAD_COMMON:
bnx2x_reset_port(bp);
bnx2x_reset_func(bp);
bnx2x_reset_common(bp);
break;
case FW_MSG_CODE_DRV_UNLOAD_PORT:
bnx2x_reset_port(bp);
bnx2x_reset_func(bp);
break;
case FW_MSG_CODE_DRV_UNLOAD_FUNCTION:
bnx2x_reset_func(bp);
break;
default:
BNX2X_ERR("Unknown reset_code (0x%x) from MCP\n", reset_code);
break;
}
}
static void bnx2x_chip_cleanup(struct bnx2x *bp, int unload_mode)
{
int port = BP_PORT(bp);
u32 reset_code = 0;
int i, cnt, rc;
/* Wait until tx fastpath tasks complete */
for_each_queue(bp, i) {
struct bnx2x_fastpath *fp = &bp->fp[i];
cnt = 1000;
while (bnx2x_has_tx_work_unload(fp)) {
bnx2x_tx_int(fp);
if (!cnt) {
BNX2X_ERR("timeout waiting for queue[%d]\n",
i);
#ifdef BNX2X_STOP_ON_ERROR
bnx2x_panic();
return -EBUSY;
#else
break;
#endif
}
cnt--;
msleep(1);
}
}
/* Give HW time to discard old tx messages */
msleep(1);
if (CHIP_IS_E1(bp)) {
struct mac_configuration_cmd *config =
bnx2x_sp(bp, mcast_config);
bnx2x_set_eth_mac_addr_e1(bp, 0);
for (i = 0; i < config->hdr.length; i++)
CAM_INVALIDATE(config->config_table[i]);
config->hdr.length = i;
if (CHIP_REV_IS_SLOW(bp))
config->hdr.offset = BNX2X_MAX_EMUL_MULTI*(1 + port);
else
config->hdr.offset = BNX2X_MAX_MULTICAST*(1 + port);
config->hdr.client_id = bp->fp->cl_id;
config->hdr.reserved1 = 0;
bp->set_mac_pending++;
smp_wmb();
bnx2x_sp_post(bp, RAMROD_CMD_ID_ETH_SET_MAC, 0,
U64_HI(bnx2x_sp_mapping(bp, mcast_config)),
U64_LO(bnx2x_sp_mapping(bp, mcast_config)), 0);
} else { /* E1H */
REG_WR(bp, NIG_REG_LLH0_FUNC_EN + port*8, 0);
bnx2x_set_eth_mac_addr_e1h(bp, 0);
for (i = 0; i < MC_HASH_SIZE; i++)
REG_WR(bp, MC_HASH_OFFSET(bp, i), 0);
REG_WR(bp, MISC_REG_E1HMF_MODE, 0);
}
#ifdef BCM_CNIC
/* Clear iSCSI L2 MAC */
mutex_lock(&bp->cnic_mutex);
if (bp->cnic_flags & BNX2X_CNIC_FLAG_MAC_SET) {
bnx2x_set_iscsi_eth_mac_addr(bp, 0);
bp->cnic_flags &= ~BNX2X_CNIC_FLAG_MAC_SET;
}
mutex_unlock(&bp->cnic_mutex);
#endif
if (unload_mode == UNLOAD_NORMAL)
reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
else if (bp->flags & NO_WOL_FLAG)
reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP;
else if (bp->wol) {
u32 emac_base = port ? GRCBASE_EMAC1 : GRCBASE_EMAC0;
u8 *mac_addr = bp->dev->dev_addr;
u32 val;
/* The mac address is written to entries 1-4 to
preserve entry 0 which is used by the PMF */
u8 entry = (BP_E1HVN(bp) + 1)*8;
val = (mac_addr[0] << 8) | mac_addr[1];
EMAC_WR(bp, EMAC_REG_EMAC_MAC_MATCH + entry, val);
val = (mac_addr[2] << 24) | (mac_addr[3] << 16) |
(mac_addr[4] << 8) | mac_addr[5];
EMAC_WR(bp, EMAC_REG_EMAC_MAC_MATCH + entry + 4, val);
reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_EN;
} else
reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
/* Close multi and leading connections
Completions for ramrods are collected in a synchronous way */
for_each_nondefault_queue(bp, i)
if (bnx2x_stop_multi(bp, i))
goto unload_error;
rc = bnx2x_stop_leading(bp);
if (rc) {
BNX2X_ERR("Stop leading failed!\n");
#ifdef BNX2X_STOP_ON_ERROR
return -EBUSY;
#else
goto unload_error;
#endif
}
unload_error:
if (!BP_NOMCP(bp))
reset_code = bnx2x_fw_command(bp, reset_code);
else {
DP(NETIF_MSG_IFDOWN, "NO MCP - load counts %d, %d, %d\n",
load_count[0], load_count[1], load_count[2]);
load_count[0]--;
load_count[1 + port]--;
DP(NETIF_MSG_IFDOWN, "NO MCP - new load counts %d, %d, %d\n",
load_count[0], load_count[1], load_count[2]);
if (load_count[0] == 0)
reset_code = FW_MSG_CODE_DRV_UNLOAD_COMMON;
else if (load_count[1 + port] == 0)
reset_code = FW_MSG_CODE_DRV_UNLOAD_PORT;
else
reset_code = FW_MSG_CODE_DRV_UNLOAD_FUNCTION;
}
if ((reset_code == FW_MSG_CODE_DRV_UNLOAD_COMMON) ||
(reset_code == FW_MSG_CODE_DRV_UNLOAD_PORT))
bnx2x__link_reset(bp);
/* Reset the chip */
bnx2x_reset_chip(bp, reset_code);
/* Report UNLOAD_DONE to MCP */
if (!BP_NOMCP(bp))
bnx2x_fw_command(bp, DRV_MSG_CODE_UNLOAD_DONE);
}
static inline void bnx2x_disable_close_the_gate(struct bnx2x *bp)
{
u32 val;
DP(NETIF_MSG_HW, "Disabling \"close the gates\"\n");
if (CHIP_IS_E1(bp)) {
int port = BP_PORT(bp);
u32 addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
MISC_REG_AEU_MASK_ATTN_FUNC_0;
val = REG_RD(bp, addr);
val &= ~(0x300);
REG_WR(bp, addr, val);
} else if (CHIP_IS_E1H(bp)) {
val = REG_RD(bp, MISC_REG_AEU_GENERAL_MASK);
val &= ~(MISC_AEU_GENERAL_MASK_REG_AEU_PXP_CLOSE_MASK |
MISC_AEU_GENERAL_MASK_REG_AEU_NIG_CLOSE_MASK);
REG_WR(bp, MISC_REG_AEU_GENERAL_MASK, val);
}
}
/* must be called with rtnl_lock */
static int bnx2x_nic_unload(struct bnx2x *bp, int unload_mode)
{
int i;
if (bp->state == BNX2X_STATE_CLOSED) {
/* Interface has been removed - nothing to recover */
bp->recovery_state = BNX2X_RECOVERY_DONE;
bp->is_leader = 0;
bnx2x_release_hw_lock(bp, HW_LOCK_RESOURCE_RESERVED_08);
smp_wmb();
return -EINVAL;
}
#ifdef BCM_CNIC
bnx2x_cnic_notify(bp, CNIC_CTL_STOP_CMD);
#endif
bp->state = BNX2X_STATE_CLOSING_WAIT4_HALT;
/* Set "drop all" */
bp->rx_mode = BNX2X_RX_MODE_NONE;
bnx2x_set_storm_rx_mode(bp);
/* Disable HW interrupts, NAPI and Tx */
bnx2x_netif_stop(bp, 1);
netif_carrier_off(bp->dev);
del_timer_sync(&bp->timer);
SHMEM_WR(bp, func_mb[BP_FUNC(bp)].drv_pulse_mb,
(DRV_PULSE_ALWAYS_ALIVE | bp->fw_drv_pulse_wr_seq));
bnx2x_stats_handle(bp, STATS_EVENT_STOP);
/* Release IRQs */
bnx2x_free_irq(bp, false);
/* Cleanup the chip if needed */
if (unload_mode != UNLOAD_RECOVERY)
bnx2x_chip_cleanup(bp, unload_mode);
bp->port.pmf = 0;
/* Free SKBs, SGEs, TPA pool and driver internals */
bnx2x_free_skbs(bp);
for_each_queue(bp, i)
bnx2x_free_rx_sge_range(bp, bp->fp + i, NUM_RX_SGE);
for_each_queue(bp, i)
netif_napi_del(&bnx2x_fp(bp, i, napi));
bnx2x_free_mem(bp);
bp->state = BNX2X_STATE_CLOSED;
/* The last driver must disable a "close the gate" if there is no
* parity attention or "process kill" pending.
*/
if ((!bnx2x_dec_load_cnt(bp)) && (!bnx2x_chk_parity_attn(bp)) &&
bnx2x_reset_is_done(bp))
bnx2x_disable_close_the_gate(bp);
/* Reset MCP mail box sequence if there is on going recovery */
if (unload_mode == UNLOAD_RECOVERY)
bp->fw_seq = 0;
return 0;
}
/* Close gates #2, #3 and #4: */
static void bnx2x_set_234_gates(struct bnx2x *bp, bool close)
{
u32 val, addr;
/* Gates #2 and #4a are closed/opened for "not E1" only */
if (!CHIP_IS_E1(bp)) {
/* #4 */
val = REG_RD(bp, PXP_REG_HST_DISCARD_DOORBELLS);
REG_WR(bp, PXP_REG_HST_DISCARD_DOORBELLS,
close ? (val | 0x1) : (val & (~(u32)1)));
/* #2 */
val = REG_RD(bp, PXP_REG_HST_DISCARD_INTERNAL_WRITES);
REG_WR(bp, PXP_REG_HST_DISCARD_INTERNAL_WRITES,
close ? (val | 0x1) : (val & (~(u32)1)));
}
/* #3 */
addr = BP_PORT(bp) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
val = REG_RD(bp, addr);
REG_WR(bp, addr, (!close) ? (val | 0x1) : (val & (~(u32)1)));
DP(NETIF_MSG_HW, "%s gates #2, #3 and #4\n",
close ? "closing" : "opening");
mmiowb();
}
#define SHARED_MF_CLP_MAGIC 0x80000000 /* `magic' bit */
static void bnx2x_clp_reset_prep(struct bnx2x *bp, u32 *magic_val)
{
/* Do some magic... */
u32 val = MF_CFG_RD(bp, shared_mf_config.clp_mb);
*magic_val = val & SHARED_MF_CLP_MAGIC;
MF_CFG_WR(bp, shared_mf_config.clp_mb, val | SHARED_MF_CLP_MAGIC);
}
/* Restore the value of the `magic' bit.
*
* @param pdev Device handle.
* @param magic_val Old value of the `magic' bit.
*/
static void bnx2x_clp_reset_done(struct bnx2x *bp, u32 magic_val)
{
/* Restore the `magic' bit value... */
/* u32 val = SHMEM_RD(bp, mf_cfg.shared_mf_config.clp_mb);
SHMEM_WR(bp, mf_cfg.shared_mf_config.clp_mb,
(val & (~SHARED_MF_CLP_MAGIC)) | magic_val); */
u32 val = MF_CFG_RD(bp, shared_mf_config.clp_mb);
MF_CFG_WR(bp, shared_mf_config.clp_mb,
(val & (~SHARED_MF_CLP_MAGIC)) | magic_val);
}
/* Prepares for MCP reset: takes care of CLP configurations.
*
* @param bp
* @param magic_val Old value of 'magic' bit.
*/
static void bnx2x_reset_mcp_prep(struct bnx2x *bp, u32 *magic_val)
{
u32 shmem;
u32 validity_offset;
DP(NETIF_MSG_HW, "Starting\n");
/* Set `magic' bit in order to save MF config */
if (!CHIP_IS_E1(bp))
bnx2x_clp_reset_prep(bp, magic_val);
/* Get shmem offset */
shmem = REG_RD(bp, MISC_REG_SHARED_MEM_ADDR);
validity_offset = offsetof(struct shmem_region, validity_map[0]);
/* Clear validity map flags */
if (shmem > 0)
REG_WR(bp, shmem + validity_offset, 0);
}
#define MCP_TIMEOUT 5000 /* 5 seconds (in ms) */
#define MCP_ONE_TIMEOUT 100 /* 100 ms */
/* Waits for MCP_ONE_TIMEOUT or MCP_ONE_TIMEOUT*10,
* depending on the HW type.
*
* @param bp
*/
static inline void bnx2x_mcp_wait_one(struct bnx2x *bp)
{
/* special handling for emulation and FPGA,
wait 10 times longer */
if (CHIP_REV_IS_SLOW(bp))
msleep(MCP_ONE_TIMEOUT*10);
else
msleep(MCP_ONE_TIMEOUT);
}
static int bnx2x_reset_mcp_comp(struct bnx2x *bp, u32 magic_val)
{
u32 shmem, cnt, validity_offset, val;
int rc = 0;
msleep(100);
/* Get shmem offset */
shmem = REG_RD(bp, MISC_REG_SHARED_MEM_ADDR);
if (shmem == 0) {
BNX2X_ERR("Shmem 0 return failure\n");
rc = -ENOTTY;
goto exit_lbl;
}
validity_offset = offsetof(struct shmem_region, validity_map[0]);
/* Wait for MCP to come up */
for (cnt = 0; cnt < (MCP_TIMEOUT / MCP_ONE_TIMEOUT); cnt++) {
/* TBD: its best to check validity map of last port.
* currently checks on port 0.
*/
val = REG_RD(bp, shmem + validity_offset);
DP(NETIF_MSG_HW, "shmem 0x%x validity map(0x%x)=0x%x\n", shmem,
shmem + validity_offset, val);
/* check that shared memory is valid. */
if ((val & (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB))
== (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB))
break;
bnx2x_mcp_wait_one(bp);
}
DP(NETIF_MSG_HW, "Cnt=%d Shmem validity map 0x%x\n", cnt, val);
/* Check that shared memory is valid. This indicates that MCP is up. */
if ((val & (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) !=
(SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) {
BNX2X_ERR("Shmem signature not present. MCP is not up !!\n");
rc = -ENOTTY;
goto exit_lbl;
}
exit_lbl:
/* Restore the `magic' bit value */
if (!CHIP_IS_E1(bp))
bnx2x_clp_reset_done(bp, magic_val);
return rc;
}
static void bnx2x_pxp_prep(struct bnx2x *bp)
{
if (!CHIP_IS_E1(bp)) {
REG_WR(bp, PXP2_REG_RD_START_INIT, 0);
REG_WR(bp, PXP2_REG_RQ_RBC_DONE, 0);
REG_WR(bp, PXP2_REG_RQ_CFG_DONE, 0);
mmiowb();
}
}
/*
* Reset the whole chip except for:
* - PCIE core
* - PCI Glue, PSWHST, PXP/PXP2 RF (all controlled by
* one reset bit)
* - IGU
* - MISC (including AEU)
* - GRC
* - RBCN, RBCP
*/
static void bnx2x_process_kill_chip_reset(struct bnx2x *bp)
{
u32 not_reset_mask1, reset_mask1, not_reset_mask2, reset_mask2;
not_reset_mask1 =
MISC_REGISTERS_RESET_REG_1_RST_HC |
MISC_REGISTERS_RESET_REG_1_RST_PXPV |
MISC_REGISTERS_RESET_REG_1_RST_PXP;
not_reset_mask2 =
MISC_REGISTERS_RESET_REG_2_RST_MDIO |
MISC_REGISTERS_RESET_REG_2_RST_EMAC0_HARD_CORE |
MISC_REGISTERS_RESET_REG_2_RST_EMAC1_HARD_CORE |
MISC_REGISTERS_RESET_REG_2_RST_MISC_CORE |
MISC_REGISTERS_RESET_REG_2_RST_RBCN |
MISC_REGISTERS_RESET_REG_2_RST_GRC |
MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_REG_HARD_CORE |
MISC_REGISTERS_RESET_REG_2_RST_MCP_N_HARD_CORE_RST_B;
reset_mask1 = 0xffffffff;
if (CHIP_IS_E1(bp))
reset_mask2 = 0xffff;
else
reset_mask2 = 0x1ffff;
REG_WR(bp, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
reset_mask1 & (~not_reset_mask1));
REG_WR(bp, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR,
reset_mask2 & (~not_reset_mask2));
barrier();
mmiowb();
REG_WR(bp, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, reset_mask1);
REG_WR(bp, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET, reset_mask2);
mmiowb();
}
static int bnx2x_process_kill(struct bnx2x *bp)
{
int cnt = 1000;
u32 val = 0;
u32 sr_cnt, blk_cnt, port_is_idle_0, port_is_idle_1, pgl_exp_rom2;
/* Empty the Tetris buffer, wait for 1s */
do {
sr_cnt = REG_RD(bp, PXP2_REG_RD_SR_CNT);
blk_cnt = REG_RD(bp, PXP2_REG_RD_BLK_CNT);
port_is_idle_0 = REG_RD(bp, PXP2_REG_RD_PORT_IS_IDLE_0);
port_is_idle_1 = REG_RD(bp, PXP2_REG_RD_PORT_IS_IDLE_1);
pgl_exp_rom2 = REG_RD(bp, PXP2_REG_PGL_EXP_ROM2);
if ((sr_cnt == 0x7e) && (blk_cnt == 0xa0) &&
((port_is_idle_0 & 0x1) == 0x1) &&
((port_is_idle_1 & 0x1) == 0x1) &&
(pgl_exp_rom2 == 0xffffffff))
break;
msleep(1);
} while (cnt-- > 0);
if (cnt <= 0) {
DP(NETIF_MSG_HW, "Tetris buffer didn't get empty or there"
" are still"
" outstanding read requests after 1s!\n");
DP(NETIF_MSG_HW, "sr_cnt=0x%08x, blk_cnt=0x%08x,"
" port_is_idle_0=0x%08x,"
" port_is_idle_1=0x%08x, pgl_exp_rom2=0x%08x\n",
sr_cnt, blk_cnt, port_is_idle_0, port_is_idle_1,
pgl_exp_rom2);
return -EAGAIN;
}
barrier();
/* Close gates #2, #3 and #4 */
bnx2x_set_234_gates(bp, true);
/* TBD: Indicate that "process kill" is in progress to MCP */
/* Clear "unprepared" bit */
REG_WR(bp, MISC_REG_UNPREPARED, 0);
barrier();
/* Make sure all is written to the chip before the reset */
mmiowb();
/* Wait for 1ms to empty GLUE and PCI-E core queues,
* PSWHST, GRC and PSWRD Tetris buffer.
*/
msleep(1);
/* Prepare to chip reset: */
/* MCP */
bnx2x_reset_mcp_prep(bp, &val);
/* PXP */
bnx2x_pxp_prep(bp);
barrier();
/* reset the chip */
bnx2x_process_kill_chip_reset(bp);
barrier();
/* Recover after reset: */
/* MCP */
if (bnx2x_reset_mcp_comp(bp, val))
return -EAGAIN;
/* PXP */
bnx2x_pxp_prep(bp);
/* Open the gates #2, #3 and #4 */
bnx2x_set_234_gates(bp, false);
/* TBD: IGU/AEU preparation bring back the AEU/IGU to a
* reset state, re-enable attentions. */
return 0;
}
static int bnx2x_leader_reset(struct bnx2x *bp)
{
int rc = 0;
/* Try to recover after the failure */
if (bnx2x_process_kill(bp)) {
printk(KERN_ERR "%s: Something bad had happen! Aii!\n",
bp->dev->name);
rc = -EAGAIN;
goto exit_leader_reset;
}
/* Clear "reset is in progress" bit and update the driver state */
bnx2x_set_reset_done(bp);
bp->recovery_state = BNX2X_RECOVERY_DONE;
exit_leader_reset:
bp->is_leader = 0;
bnx2x_release_hw_lock(bp, HW_LOCK_RESOURCE_RESERVED_08);
smp_wmb();
return rc;
}
static int bnx2x_set_power_state(struct bnx2x *bp, pci_power_t state);
/* Assumption: runs under rtnl lock. This together with the fact
* that it's called only from bnx2x_reset_task() ensure that it
* will never be called when netif_running(bp->dev) is false.
*/
static void bnx2x_parity_recover(struct bnx2x *bp)
{
DP(NETIF_MSG_HW, "Handling parity\n");
while (1) {
switch (bp->recovery_state) {
case BNX2X_RECOVERY_INIT:
DP(NETIF_MSG_HW, "State is BNX2X_RECOVERY_INIT\n");
/* Try to get a LEADER_LOCK HW lock */
if (bnx2x_trylock_hw_lock(bp,
HW_LOCK_RESOURCE_RESERVED_08))
bp->is_leader = 1;
/* Stop the driver */
/* If interface has been removed - break */
if (bnx2x_nic_unload(bp, UNLOAD_RECOVERY))
return;
bp->recovery_state = BNX2X_RECOVERY_WAIT;
/* Ensure "is_leader" and "recovery_state"
* update values are seen on other CPUs
*/
smp_wmb();
break;
case BNX2X_RECOVERY_WAIT:
DP(NETIF_MSG_HW, "State is BNX2X_RECOVERY_WAIT\n");
if (bp->is_leader) {
u32 load_counter = bnx2x_get_load_cnt(bp);
if (load_counter) {
/* Wait until all other functions get
* down.
*/
schedule_delayed_work(&bp->reset_task,
HZ/10);
return;
} else {
/* If all other functions got down -
* try to bring the chip back to
* normal. In any case it's an exit
* point for a leader.
*/
if (bnx2x_leader_reset(bp) ||
bnx2x_nic_load(bp, LOAD_NORMAL)) {
printk(KERN_ERR"%s: Recovery "
"has failed. Power cycle is "
"needed.\n", bp->dev->name);
/* Disconnect this device */
netif_device_detach(bp->dev);
/* Block ifup for all function
* of this ASIC until
* "process kill" or power
* cycle.
*/
bnx2x_set_reset_in_progress(bp);
/* Shut down the power */
bnx2x_set_power_state(bp,
PCI_D3hot);
return;
}
return;
}
} else { /* non-leader */
if (!bnx2x_reset_is_done(bp)) {
/* Try to get a LEADER_LOCK HW lock as
* long as a former leader may have
* been unloaded by the user or
* released a leadership by another
* reason.
*/
if (bnx2x_trylock_hw_lock(bp,
HW_LOCK_RESOURCE_RESERVED_08)) {
/* I'm a leader now! Restart a
* switch case.
*/
bp->is_leader = 1;
break;
}
schedule_delayed_work(&bp->reset_task,
HZ/10);
return;
} else { /* A leader has completed
* the "process kill". It's an exit
* point for a non-leader.
*/
bnx2x_nic_load(bp, LOAD_NORMAL);
bp->recovery_state =
BNX2X_RECOVERY_DONE;
smp_wmb();
return;
}
}
default:
return;
}
}
}
/* bnx2x_nic_unload() flushes the bnx2x_wq, thus reset task is
* scheduled on a general queue in order to prevent a dead lock.
*/
static void bnx2x_reset_task(struct work_struct *work)
{
struct bnx2x *bp = container_of(work, struct bnx2x, reset_task.work);
#ifdef BNX2X_STOP_ON_ERROR
BNX2X_ERR("reset task called but STOP_ON_ERROR defined"
" so reset not done to allow debug dump,\n"
KERN_ERR " you will need to reboot when done\n");
return;
#endif
rtnl_lock();
if (!netif_running(bp->dev))
goto reset_task_exit;
if (unlikely(bp->recovery_state != BNX2X_RECOVERY_DONE))
bnx2x_parity_recover(bp);
else {
bnx2x_nic_unload(bp, UNLOAD_NORMAL);
bnx2x_nic_load(bp, LOAD_NORMAL);
}
reset_task_exit:
rtnl_unlock();
}
/* end of nic load/unload */
/* ethtool_ops */
/*
* Init service functions
*/
static inline u32 bnx2x_get_pretend_reg(struct bnx2x *bp, int func)
{
switch (func) {
case 0: return PXP2_REG_PGL_PRETEND_FUNC_F0;
case 1: return PXP2_REG_PGL_PRETEND_FUNC_F1;
case 2: return PXP2_REG_PGL_PRETEND_FUNC_F2;
case 3: return PXP2_REG_PGL_PRETEND_FUNC_F3;
case 4: return PXP2_REG_PGL_PRETEND_FUNC_F4;
case 5: return PXP2_REG_PGL_PRETEND_FUNC_F5;
case 6: return PXP2_REG_PGL_PRETEND_FUNC_F6;
case 7: return PXP2_REG_PGL_PRETEND_FUNC_F7;
default:
BNX2X_ERR("Unsupported function index: %d\n", func);
return (u32)(-1);
}
}
static void bnx2x_undi_int_disable_e1h(struct bnx2x *bp, int orig_func)
{
u32 reg = bnx2x_get_pretend_reg(bp, orig_func), new_val;
/* Flush all outstanding writes */
mmiowb();
/* Pretend to be function 0 */
REG_WR(bp, reg, 0);
/* Flush the GRC transaction (in the chip) */
new_val = REG_RD(bp, reg);
if (new_val != 0) {
BNX2X_ERR("Hmmm... Pretend register wasn't updated: (0,%d)!\n",
new_val);
BUG();
}
/* From now we are in the "like-E1" mode */
bnx2x_int_disable(bp);
/* Flush all outstanding writes */
mmiowb();
/* Restore the original funtion settings */
REG_WR(bp, reg, orig_func);
new_val = REG_RD(bp, reg);
if (new_val != orig_func) {
BNX2X_ERR("Hmmm... Pretend register wasn't updated: (%d,%d)!\n",
orig_func, new_val);
BUG();
}
}
static inline void bnx2x_undi_int_disable(struct bnx2x *bp, int func)
{
if (CHIP_IS_E1H(bp))
bnx2x_undi_int_disable_e1h(bp, func);
else
bnx2x_int_disable(bp);
}
static void __devinit bnx2x_undi_unload(struct bnx2x *bp)
{
u32 val;
/* Check if there is any driver already loaded */
val = REG_RD(bp, MISC_REG_UNPREPARED);
if (val == 0x1) {
/* Check if it is the UNDI driver
* UNDI driver initializes CID offset for normal bell to 0x7
*/
bnx2x_acquire_hw_lock(bp, HW_LOCK_RESOURCE_UNDI);
val = REG_RD(bp, DORQ_REG_NORM_CID_OFST);
if (val == 0x7) {
u32 reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
/* save our func */
int func = BP_FUNC(bp);
u32 swap_en;
u32 swap_val;
/* clear the UNDI indication */
REG_WR(bp, DORQ_REG_NORM_CID_OFST, 0);
BNX2X_DEV_INFO("UNDI is active! reset device\n");
/* try unload UNDI on port 0 */
bp->func = 0;
bp->fw_seq =
(SHMEM_RD(bp, func_mb[bp->func].drv_mb_header) &
DRV_MSG_SEQ_NUMBER_MASK);
reset_code = bnx2x_fw_command(bp, reset_code);
/* if UNDI is loaded on the other port */
if (reset_code != FW_MSG_CODE_DRV_UNLOAD_COMMON) {
/* send "DONE" for previous unload */
bnx2x_fw_command(bp, DRV_MSG_CODE_UNLOAD_DONE);
/* unload UNDI on port 1 */
bp->func = 1;
bp->fw_seq =
(SHMEM_RD(bp, func_mb[bp->func].drv_mb_header) &
DRV_MSG_SEQ_NUMBER_MASK);
reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
bnx2x_fw_command(bp, reset_code);
}
/* now it's safe to release the lock */
bnx2x_release_hw_lock(bp, HW_LOCK_RESOURCE_UNDI);
bnx2x_undi_int_disable(bp, func);
/* close input traffic and wait for it */
/* Do not rcv packets to BRB */
REG_WR(bp,
(BP_PORT(bp) ? NIG_REG_LLH1_BRB1_DRV_MASK :
NIG_REG_LLH0_BRB1_DRV_MASK), 0x0);
/* Do not direct rcv packets that are not for MCP to
* the BRB */
REG_WR(bp,
(BP_PORT(bp) ? NIG_REG_LLH1_BRB1_NOT_MCP :
NIG_REG_LLH0_BRB1_NOT_MCP), 0x0);
/* clear AEU */
REG_WR(bp,
(BP_PORT(bp) ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
MISC_REG_AEU_MASK_ATTN_FUNC_0), 0);
msleep(10);
/* save NIG port swap info */
swap_val = REG_RD(bp, NIG_REG_PORT_SWAP);
swap_en = REG_RD(bp, NIG_REG_STRAP_OVERRIDE);
/* reset device */
REG_WR(bp,
GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
0xd3ffffff);
REG_WR(bp,
GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR,
0x1403);
/* take the NIG out of reset and restore swap values */
REG_WR(bp,
GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET,
MISC_REGISTERS_RESET_REG_1_RST_NIG);
REG_WR(bp, NIG_REG_PORT_SWAP, swap_val);
REG_WR(bp, NIG_REG_STRAP_OVERRIDE, swap_en);
/* send unload done to the MCP */
bnx2x_fw_command(bp, DRV_MSG_CODE_UNLOAD_DONE);
/* restore our func and fw_seq */
bp->func = func;
bp->fw_seq =
(SHMEM_RD(bp, func_mb[bp->func].drv_mb_header) &
DRV_MSG_SEQ_NUMBER_MASK);
} else
bnx2x_release_hw_lock(bp, HW_LOCK_RESOURCE_UNDI);
}
}
static void __devinit bnx2x_get_common_hwinfo(struct bnx2x *bp)
{
u32 val, val2, val3, val4, id;
u16 pmc;
/* Get the chip revision id and number. */
/* chip num:16-31, rev:12-15, metal:4-11, bond_id:0-3 */
val = REG_RD(bp, MISC_REG_CHIP_NUM);
id = ((val & 0xffff) << 16);
val = REG_RD(bp, MISC_REG_CHIP_REV);
id |= ((val & 0xf) << 12);
val = REG_RD(bp, MISC_REG_CHIP_METAL);
id |= ((val & 0xff) << 4);
val = REG_RD(bp, MISC_REG_BOND_ID);
id |= (val & 0xf);
bp->common.chip_id = id;
bp->link_params.chip_id = bp->common.chip_id;
BNX2X_DEV_INFO("chip ID is 0x%x\n", id);
val = (REG_RD(bp, 0x2874) & 0x55);
if ((bp->common.chip_id & 0x1) ||
(CHIP_IS_E1(bp) && val) || (CHIP_IS_E1H(bp) && (val == 0x55))) {
bp->flags |= ONE_PORT_FLAG;
BNX2X_DEV_INFO("single port device\n");
}
val = REG_RD(bp, MCP_REG_MCPR_NVM_CFG4);
bp->common.flash_size = (NVRAM_1MB_SIZE <<
(val & MCPR_NVM_CFG4_FLASH_SIZE));
BNX2X_DEV_INFO("flash_size 0x%x (%d)\n",
bp->common.flash_size, bp->common.flash_size);
bp->common.shmem_base = REG_RD(bp, MISC_REG_SHARED_MEM_ADDR);
bp->common.shmem2_base = REG_RD(bp, MISC_REG_GENERIC_CR_0);
bp->link_params.shmem_base = bp->common.shmem_base;
BNX2X_DEV_INFO("shmem offset 0x%x shmem2 offset 0x%x\n",
bp->common.shmem_base, bp->common.shmem2_base);
if (!bp->common.shmem_base ||
(bp->common.shmem_base < 0xA0000) ||
(bp->common.shmem_base >= 0xC0000)) {
BNX2X_DEV_INFO("MCP not active\n");
bp->flags |= NO_MCP_FLAG;
return;
}
val = SHMEM_RD(bp, validity_map[BP_PORT(bp)]);
if ((val & (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB))
!= (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB))
BNX2X_ERROR("BAD MCP validity signature\n");
bp->common.hw_config = SHMEM_RD(bp, dev_info.shared_hw_config.config);
BNX2X_DEV_INFO("hw_config 0x%08x\n", bp->common.hw_config);
bp->link_params.hw_led_mode = ((bp->common.hw_config &
SHARED_HW_CFG_LED_MODE_MASK) >>
SHARED_HW_CFG_LED_MODE_SHIFT);
bp->link_params.feature_config_flags = 0;
val = SHMEM_RD(bp, dev_info.shared_feature_config.config);
if (val & SHARED_FEAT_CFG_OVERRIDE_PREEMPHASIS_CFG_ENABLED)
bp->link_params.feature_config_flags |=
FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
else
bp->link_params.feature_config_flags &=
~FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
val = SHMEM_RD(bp, dev_info.bc_rev) >> 8;
bp->common.bc_ver = val;
BNX2X_DEV_INFO("bc_ver %X\n", val);
if (val < BNX2X_BC_VER) {
/* for now only warn
* later we might need to enforce this */
BNX2X_ERROR("This driver needs bc_ver %X but found %X, "
"please upgrade BC\n", BNX2X_BC_VER, val);
}
bp->link_params.feature_config_flags |=
(val >= REQ_BC_VER_4_VRFY_OPT_MDL) ?
FEATURE_CONFIG_BC_SUPPORTS_OPT_MDL_VRFY : 0;
if (BP_E1HVN(bp) == 0) {
pci_read_config_word(bp->pdev, bp->pm_cap + PCI_PM_PMC, &pmc);
bp->flags |= (pmc & PCI_PM_CAP_PME_D3cold) ? 0 : NO_WOL_FLAG;
} else {
/* no WOL capability for E1HVN != 0 */
bp->flags |= NO_WOL_FLAG;
}
BNX2X_DEV_INFO("%sWoL capable\n",
(bp->flags & NO_WOL_FLAG) ? "not " : "");
val = SHMEM_RD(bp, dev_info.shared_hw_config.part_num);
val2 = SHMEM_RD(bp, dev_info.shared_hw_config.part_num[4]);
val3 = SHMEM_RD(bp, dev_info.shared_hw_config.part_num[8]);
val4 = SHMEM_RD(bp, dev_info.shared_hw_config.part_num[12]);
dev_info(&bp->pdev->dev, "part number %X-%X-%X-%X\n",
val, val2, val3, val4);
}
static void __devinit bnx2x_link_settings_supported(struct bnx2x *bp,
u32 switch_cfg)
{
int port = BP_PORT(bp);
u32 ext_phy_type;
switch (switch_cfg) {
case SWITCH_CFG_1G:
BNX2X_DEV_INFO("switch_cfg 0x%x (1G)\n", switch_cfg);
ext_phy_type =
SERDES_EXT_PHY_TYPE(bp->link_params.ext_phy_config);
switch (ext_phy_type) {
case PORT_HW_CFG_SERDES_EXT_PHY_TYPE_DIRECT:
BNX2X_DEV_INFO("ext_phy_type 0x%x (Direct)\n",
ext_phy_type);
bp->port.supported |= (SUPPORTED_10baseT_Half |
SUPPORTED_10baseT_Full |
SUPPORTED_100baseT_Half |
SUPPORTED_100baseT_Full |
SUPPORTED_1000baseT_Full |
SUPPORTED_2500baseX_Full |
SUPPORTED_TP |
SUPPORTED_FIBRE |
SUPPORTED_Autoneg |
SUPPORTED_Pause |
SUPPORTED_Asym_Pause);
break;
case PORT_HW_CFG_SERDES_EXT_PHY_TYPE_BCM5482:
BNX2X_DEV_INFO("ext_phy_type 0x%x (5482)\n",
ext_phy_type);
bp->port.supported |= (SUPPORTED_10baseT_Half |
SUPPORTED_10baseT_Full |
SUPPORTED_100baseT_Half |
SUPPORTED_100baseT_Full |
SUPPORTED_1000baseT_Full |
SUPPORTED_TP |
SUPPORTED_FIBRE |
SUPPORTED_Autoneg |
SUPPORTED_Pause |
SUPPORTED_Asym_Pause);
break;
default:
BNX2X_ERR("NVRAM config error. "
"BAD SerDes ext_phy_config 0x%x\n",
bp->link_params.ext_phy_config);
return;
}
bp->port.phy_addr = REG_RD(bp, NIG_REG_SERDES0_CTRL_PHY_ADDR +
port*0x10);
BNX2X_DEV_INFO("phy_addr 0x%x\n", bp->port.phy_addr);
break;
case SWITCH_CFG_10G:
BNX2X_DEV_INFO("switch_cfg 0x%x (10G)\n", switch_cfg);
ext_phy_type =
XGXS_EXT_PHY_TYPE(bp->link_params.ext_phy_config);
switch (ext_phy_type) {
case PORT_HW_CFG_XGXS_EXT_PHY_TYPE_DIRECT:
BNX2X_DEV_INFO("ext_phy_type 0x%x (Direct)\n",
ext_phy_type);
bp->port.supported |= (SUPPORTED_10baseT_Half |
SUPPORTED_10baseT_Full |
SUPPORTED_100baseT_Half |
SUPPORTED_100baseT_Full |
SUPPORTED_1000baseT_Full |
SUPPORTED_2500baseX_Full |
SUPPORTED_10000baseT_Full |
SUPPORTED_TP |
SUPPORTED_FIBRE |
SUPPORTED_Autoneg |
SUPPORTED_Pause |
SUPPORTED_Asym_Pause);
break;
case PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM8072:
BNX2X_DEV_INFO("ext_phy_type 0x%x (8072)\n",
ext_phy_type);
bp->port.supported |= (SUPPORTED_10000baseT_Full |
SUPPORTED_1000baseT_Full |
SUPPORTED_FIBRE |
SUPPORTED_Autoneg |
SUPPORTED_Pause |
SUPPORTED_Asym_Pause);
break;
case PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM8073:
BNX2X_DEV_INFO("ext_phy_type 0x%x (8073)\n",
ext_phy_type);
bp->port.supported |= (SUPPORTED_10000baseT_Full |
SUPPORTED_2500baseX_Full |
SUPPORTED_1000baseT_Full |
SUPPORTED_FIBRE |
SUPPORTED_Autoneg |
SUPPORTED_Pause |
SUPPORTED_Asym_Pause);
break;
case PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM8705:
BNX2X_DEV_INFO("ext_phy_type 0x%x (8705)\n",
ext_phy_type);
bp->port.supported |= (SUPPORTED_10000baseT_Full |
SUPPORTED_FIBRE |
SUPPORTED_Pause |
SUPPORTED_Asym_Pause);
break;
case PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM8706:
BNX2X_DEV_INFO("ext_phy_type 0x%x (8706)\n",
ext_phy_type);
bp->port.supported |= (SUPPORTED_10000baseT_Full |
SUPPORTED_1000baseT_Full |
SUPPORTED_FIBRE |
SUPPORTED_Pause |
SUPPORTED_Asym_Pause);
break;
case PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM8726:
BNX2X_DEV_INFO("ext_phy_type 0x%x (8726)\n",
ext_phy_type);
bp->port.supported |= (SUPPORTED_10000baseT_Full |
SUPPORTED_1000baseT_Full |
SUPPORTED_Autoneg |
SUPPORTED_FIBRE |
SUPPORTED_Pause |
SUPPORTED_Asym_Pause);
break;
case PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM8727:
BNX2X_DEV_INFO("ext_phy_type 0x%x (8727)\n",
ext_phy_type);
bp->port.supported |= (SUPPORTED_10000baseT_Full |
SUPPORTED_1000baseT_Full |
SUPPORTED_Autoneg |
SUPPORTED_FIBRE |
SUPPORTED_Pause |
SUPPORTED_Asym_Pause);
break;
case PORT_HW_CFG_XGXS_EXT_PHY_TYPE_SFX7101:
BNX2X_DEV_INFO("ext_phy_type 0x%x (SFX7101)\n",
ext_phy_type);
bp->port.supported |= (SUPPORTED_10000baseT_Full |
SUPPORTED_TP |
SUPPORTED_Autoneg |
SUPPORTED_Pause |
SUPPORTED_Asym_Pause);
break;
case PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM8481:
BNX2X_DEV_INFO("ext_phy_type 0x%x (BCM8481)\n",
ext_phy_type);
bp->port.supported |= (SUPPORTED_10baseT_Half |
SUPPORTED_10baseT_Full |
SUPPORTED_100baseT_Half |
SUPPORTED_100baseT_Full |
SUPPORTED_1000baseT_Full |
SUPPORTED_10000baseT_Full |
SUPPORTED_TP |
SUPPORTED_Autoneg |
SUPPORTED_Pause |
SUPPORTED_Asym_Pause);
break;
case PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE:
BNX2X_ERR("XGXS PHY Failure detected 0x%x\n",
bp->link_params.ext_phy_config);
break;
default:
BNX2X_ERR("NVRAM config error. "
"BAD XGXS ext_phy_config 0x%x\n",
bp->link_params.ext_phy_config);
return;
}
bp->port.phy_addr = REG_RD(bp, NIG_REG_XGXS0_CTRL_PHY_ADDR +
port*0x18);
BNX2X_DEV_INFO("phy_addr 0x%x\n", bp->port.phy_addr);
break;
default:
BNX2X_ERR("BAD switch_cfg link_config 0x%x\n",
bp->port.link_config);
return;
}
bp->link_params.phy_addr = bp->port.phy_addr;
/* mask what we support according to speed_cap_mask */
if (!(bp->link_params.speed_cap_mask &
PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_HALF))
bp->port.supported &= ~SUPPORTED_10baseT_Half;
if (!(bp->link_params.speed_cap_mask &
PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_FULL))
bp->port.supported &= ~SUPPORTED_10baseT_Full;
if (!(bp->link_params.speed_cap_mask &
PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_HALF))
bp->port.supported &= ~SUPPORTED_100baseT_Half;
if (!(bp->link_params.speed_cap_mask &
PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_FULL))
bp->port.supported &= ~SUPPORTED_100baseT_Full;
if (!(bp->link_params.speed_cap_mask &
PORT_HW_CFG_SPEED_CAPABILITY_D0_1G))
bp->port.supported &= ~(SUPPORTED_1000baseT_Half |
SUPPORTED_1000baseT_Full);
if (!(bp->link_params.speed_cap_mask &
PORT_HW_CFG_SPEED_CAPABILITY_D0_2_5G))
bp->port.supported &= ~SUPPORTED_2500baseX_Full;
if (!(bp->link_params.speed_cap_mask &
PORT_HW_CFG_SPEED_CAPABILITY_D0_10G))
bp->port.supported &= ~SUPPORTED_10000baseT_Full;
BNX2X_DEV_INFO("supported 0x%x\n", bp->port.supported);
}
static void __devinit bnx2x_link_settings_requested(struct bnx2x *bp)
{
bp->link_params.req_duplex = DUPLEX_FULL;
switch (bp->port.link_config & PORT_FEATURE_LINK_SPEED_MASK) {
case PORT_FEATURE_LINK_SPEED_AUTO:
if (bp->port.supported & SUPPORTED_Autoneg) {
bp->link_params.req_line_speed = SPEED_AUTO_NEG;
bp->port.advertising = bp->port.supported;
} else {
u32 ext_phy_type =
XGXS_EXT_PHY_TYPE(bp->link_params.ext_phy_config);
if ((ext_phy_type ==
PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM8705) ||
(ext_phy_type ==
PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM8706)) {
/* force 10G, no AN */
bp->link_params.req_line_speed = SPEED_10000;
bp->port.advertising =
(ADVERTISED_10000baseT_Full |
ADVERTISED_FIBRE);
break;
}
BNX2X_ERR("NVRAM config error. "
"Invalid link_config 0x%x"
" Autoneg not supported\n",
bp->port.link_config);
return;
}
break;
case PORT_FEATURE_LINK_SPEED_10M_FULL:
if (bp->port.supported & SUPPORTED_10baseT_Full) {
bp->link_params.req_line_speed = SPEED_10;
bp->port.advertising = (ADVERTISED_10baseT_Full |
ADVERTISED_TP);
} else {
BNX2X_ERROR("NVRAM config error. "
"Invalid link_config 0x%x"
" speed_cap_mask 0x%x\n",
bp->port.link_config,
bp->link_params.speed_cap_mask);
return;
}
break;
case PORT_FEATURE_LINK_SPEED_10M_HALF:
if (bp->port.supported & SUPPORTED_10baseT_Half) {
bp->link_params.req_line_speed = SPEED_10;
bp->link_params.req_duplex = DUPLEX_HALF;
bp->port.advertising = (ADVERTISED_10baseT_Half |
ADVERTISED_TP);
} else {
BNX2X_ERROR("NVRAM config error. "
"Invalid link_config 0x%x"
" speed_cap_mask 0x%x\n",
bp->port.link_config,
bp->link_params.speed_cap_mask);
return;
}
break;
case PORT_FEATURE_LINK_SPEED_100M_FULL:
if (bp->port.supported & SUPPORTED_100baseT_Full) {
bp->link_params.req_line_speed = SPEED_100;
bp->port.advertising = (ADVERTISED_100baseT_Full |
ADVERTISED_TP);
} else {
BNX2X_ERROR("NVRAM config error. "
"Invalid link_config 0x%x"
" speed_cap_mask 0x%x\n",
bp->port.link_config,
bp->link_params.speed_cap_mask);
return;
}
break;
case PORT_FEATURE_LINK_SPEED_100M_HALF:
if (bp->port.supported & SUPPORTED_100baseT_Half) {
bp->link_params.req_line_speed = SPEED_100;
bp->link_params.req_duplex = DUPLEX_HALF;
bp->port.advertising = (ADVERTISED_100baseT_Half |
ADVERTISED_TP);
} else {
BNX2X_ERROR("NVRAM config error. "
"Invalid link_config 0x%x"
" speed_cap_mask 0x%x\n",
bp->port.link_config,
bp->link_params.speed_cap_mask);
return;
}
break;
case PORT_FEATURE_LINK_SPEED_1G:
if (bp->port.supported & SUPPORTED_1000baseT_Full) {
bp->link_params.req_line_speed = SPEED_1000;
bp->port.advertising = (ADVERTISED_1000baseT_Full |
ADVERTISED_TP);
} else {
BNX2X_ERROR("NVRAM config error. "
"Invalid link_config 0x%x"
" speed_cap_mask 0x%x\n",
bp->port.link_config,
bp->link_params.speed_cap_mask);
return;
}
break;
case PORT_FEATURE_LINK_SPEED_2_5G:
if (bp->port.supported & SUPPORTED_2500baseX_Full) {
bp->link_params.req_line_speed = SPEED_2500;
bp->port.advertising = (ADVERTISED_2500baseX_Full |
ADVERTISED_TP);
} else {
BNX2X_ERROR("NVRAM config error. "
"Invalid link_config 0x%x"
" speed_cap_mask 0x%x\n",
bp->port.link_config,
bp->link_params.speed_cap_mask);
return;
}
break;
case PORT_FEATURE_LINK_SPEED_10G_CX4:
case PORT_FEATURE_LINK_SPEED_10G_KX4:
case PORT_FEATURE_LINK_SPEED_10G_KR:
if (bp->port.supported & SUPPORTED_10000baseT_Full) {
bp->link_params.req_line_speed = SPEED_10000;
bp->port.advertising = (ADVERTISED_10000baseT_Full |
ADVERTISED_FIBRE);
} else {
BNX2X_ERROR("NVRAM config error. "
"Invalid link_config 0x%x"
" speed_cap_mask 0x%x\n",
bp->port.link_config,
bp->link_params.speed_cap_mask);
return;
}
break;
default:
BNX2X_ERROR("NVRAM config error. "
"BAD link speed link_config 0x%x\n",
bp->port.link_config);
bp->link_params.req_line_speed = SPEED_AUTO_NEG;
bp->port.advertising = bp->port.supported;
break;
}
bp->link_params.req_flow_ctrl = (bp->port.link_config &
PORT_FEATURE_FLOW_CONTROL_MASK);
if ((bp->link_params.req_flow_ctrl == BNX2X_FLOW_CTRL_AUTO) &&
!(bp->port.supported & SUPPORTED_Autoneg))
bp->link_params.req_flow_ctrl = BNX2X_FLOW_CTRL_NONE;
BNX2X_DEV_INFO("req_line_speed %d req_duplex %d req_flow_ctrl 0x%x"
" advertising 0x%x\n",
bp->link_params.req_line_speed,
bp->link_params.req_duplex,
bp->link_params.req_flow_ctrl, bp->port.advertising);
}
static void __devinit bnx2x_set_mac_buf(u8 *mac_buf, u32 mac_lo, u16 mac_hi)
{
mac_hi = cpu_to_be16(mac_hi);
mac_lo = cpu_to_be32(mac_lo);
memcpy(mac_buf, &mac_hi, sizeof(mac_hi));
memcpy(mac_buf + sizeof(mac_hi), &mac_lo, sizeof(mac_lo));
}
static void __devinit bnx2x_get_port_hwinfo(struct bnx2x *bp)
{
int port = BP_PORT(bp);
u32 val, val2;
u32 config;
u16 i;
u32 ext_phy_type;
bp->link_params.bp = bp;
bp->link_params.port = port;
bp->link_params.lane_config =
SHMEM_RD(bp, dev_info.port_hw_config[port].lane_config);
bp->link_params.ext_phy_config =
SHMEM_RD(bp,
dev_info.port_hw_config[port].external_phy_config);
/* BCM8727_NOC => BCM8727 no over current */
if (XGXS_EXT_PHY_TYPE(bp->link_params.ext_phy_config) ==
PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM8727_NOC) {
bp->link_params.ext_phy_config &=
~PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK;
bp->link_params.ext_phy_config |=
PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM8727;
bp->link_params.feature_config_flags |=
FEATURE_CONFIG_BCM8727_NOC;
}
bp->link_params.speed_cap_mask =
SHMEM_RD(bp,
dev_info.port_hw_config[port].speed_capability_mask);
bp->port.link_config =
SHMEM_RD(bp, dev_info.port_feature_config[port].link_config);
/* Get the 4 lanes xgxs config rx and tx */
for (i = 0; i < 2; i++) {
val = SHMEM_RD(bp,
dev_info.port_hw_config[port].xgxs_config_rx[i<<1]);
bp->link_params.xgxs_config_rx[i << 1] = ((val>>16) & 0xffff);
bp->link_params.xgxs_config_rx[(i << 1) + 1] = (val & 0xffff);
val = SHMEM_RD(bp,
dev_info.port_hw_config[port].xgxs_config_tx[i<<1]);
bp->link_params.xgxs_config_tx[i << 1] = ((val>>16) & 0xffff);
bp->link_params.xgxs_config_tx[(i << 1) + 1] = (val & 0xffff);
}
/* If the device is capable of WoL, set the default state according
* to the HW
*/
config = SHMEM_RD(bp, dev_info.port_feature_config[port].config);
bp->wol = (!(bp->flags & NO_WOL_FLAG) &&
(config & PORT_FEATURE_WOL_ENABLED));
BNX2X_DEV_INFO("lane_config 0x%08x ext_phy_config 0x%08x"
" speed_cap_mask 0x%08x link_config 0x%08x\n",
bp->link_params.lane_config,
bp->link_params.ext_phy_config,
bp->link_params.speed_cap_mask, bp->port.link_config);
bp->link_params.switch_cfg |= (bp->port.link_config &
PORT_FEATURE_CONNECTED_SWITCH_MASK);
bnx2x_link_settings_supported(bp, bp->link_params.switch_cfg);
bnx2x_link_settings_requested(bp);
/*
* If connected directly, work with the internal PHY, otherwise, work
* with the external PHY
*/
ext_phy_type = XGXS_EXT_PHY_TYPE(bp->link_params.ext_phy_config);
if (ext_phy_type == PORT_HW_CFG_XGXS_EXT_PHY_TYPE_DIRECT)
bp->mdio.prtad = bp->link_params.phy_addr;
else if ((ext_phy_type != PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE) &&
(ext_phy_type != PORT_HW_CFG_XGXS_EXT_PHY_TYPE_NOT_CONN))
bp->mdio.prtad =
XGXS_EXT_PHY_ADDR(bp->link_params.ext_phy_config);
val2 = SHMEM_RD(bp, dev_info.port_hw_config[port].mac_upper);
val = SHMEM_RD(bp, dev_info.port_hw_config[port].mac_lower);
bnx2x_set_mac_buf(bp->dev->dev_addr, val, val2);
memcpy(bp->link_params.mac_addr, bp->dev->dev_addr, ETH_ALEN);
memcpy(bp->dev->perm_addr, bp->dev->dev_addr, ETH_ALEN);
#ifdef BCM_CNIC
val2 = SHMEM_RD(bp, dev_info.port_hw_config[port].iscsi_mac_upper);
val = SHMEM_RD(bp, dev_info.port_hw_config[port].iscsi_mac_lower);
bnx2x_set_mac_buf(bp->iscsi_mac, val, val2);
#endif
}
static int __devinit bnx2x_get_hwinfo(struct bnx2x *bp)
{
int func = BP_FUNC(bp);
u32 val, val2;
int rc = 0;
bnx2x_get_common_hwinfo(bp);
bp->e1hov = 0;
bp->e1hmf = 0;
if (CHIP_IS_E1H(bp) && !BP_NOMCP(bp)) {
bp->mf_config =
SHMEM_RD(bp, mf_cfg.func_mf_config[func].config);
val = (SHMEM_RD(bp, mf_cfg.func_mf_config[FUNC_0].e1hov_tag) &
FUNC_MF_CFG_E1HOV_TAG_MASK);
if (val != FUNC_MF_CFG_E1HOV_TAG_DEFAULT)
bp->e1hmf = 1;
BNX2X_DEV_INFO("%s function mode\n",
IS_E1HMF(bp) ? "multi" : "single");
if (IS_E1HMF(bp)) {
val = (SHMEM_RD(bp, mf_cfg.func_mf_config[func].
e1hov_tag) &
FUNC_MF_CFG_E1HOV_TAG_MASK);
if (val != FUNC_MF_CFG_E1HOV_TAG_DEFAULT) {
bp->e1hov = val;
BNX2X_DEV_INFO("E1HOV for func %d is %d "
"(0x%04x)\n",
func, bp->e1hov, bp->e1hov);
} else {
BNX2X_ERROR("No valid E1HOV for func %d,"
" aborting\n", func);
rc = -EPERM;
}
} else {
if (BP_E1HVN(bp)) {
BNX2X_ERROR("VN %d in single function mode,"
" aborting\n", BP_E1HVN(bp));
rc = -EPERM;
}
}
}
if (!BP_NOMCP(bp)) {
bnx2x_get_port_hwinfo(bp);
bp->fw_seq = (SHMEM_RD(bp, func_mb[func].drv_mb_header) &
DRV_MSG_SEQ_NUMBER_MASK);
BNX2X_DEV_INFO("fw_seq 0x%08x\n", bp->fw_seq);
}
if (IS_E1HMF(bp)) {
val2 = SHMEM_RD(bp, mf_cfg.func_mf_config[func].mac_upper);
val = SHMEM_RD(bp, mf_cfg.func_mf_config[func].mac_lower);
if ((val2 != FUNC_MF_CFG_UPPERMAC_DEFAULT) &&
(val != FUNC_MF_CFG_LOWERMAC_DEFAULT)) {
bp->dev->dev_addr[0] = (u8)(val2 >> 8 & 0xff);
bp->dev->dev_addr[1] = (u8)(val2 & 0xff);
bp->dev->dev_addr[2] = (u8)(val >> 24 & 0xff);
bp->dev->dev_addr[3] = (u8)(val >> 16 & 0xff);
bp->dev->dev_addr[4] = (u8)(val >> 8 & 0xff);
bp->dev->dev_addr[5] = (u8)(val & 0xff);
memcpy(bp->link_params.mac_addr, bp->dev->dev_addr,
ETH_ALEN);
memcpy(bp->dev->perm_addr, bp->dev->dev_addr,
ETH_ALEN);
}
return rc;
}
if (BP_NOMCP(bp)) {
/* only supposed to happen on emulation/FPGA */
BNX2X_ERROR("warning: random MAC workaround active\n");
random_ether_addr(bp->dev->dev_addr);
memcpy(bp->dev->perm_addr, bp->dev->dev_addr, ETH_ALEN);
}
return rc;
}
static void __devinit bnx2x_read_fwinfo(struct bnx2x *bp)
{
int cnt, i, block_end, rodi;
char vpd_data[BNX2X_VPD_LEN+1];
char str_id_reg[VENDOR_ID_LEN+1];
char str_id_cap[VENDOR_ID_LEN+1];
u8 len;
cnt = pci_read_vpd(bp->pdev, 0, BNX2X_VPD_LEN, vpd_data);
memset(bp->fw_ver, 0, sizeof(bp->fw_ver));
if (cnt < BNX2X_VPD_LEN)
goto out_not_found;
i = pci_vpd_find_tag(vpd_data, 0, BNX2X_VPD_LEN,
PCI_VPD_LRDT_RO_DATA);
if (i < 0)
goto out_not_found;
block_end = i + PCI_VPD_LRDT_TAG_SIZE +
pci_vpd_lrdt_size(&vpd_data[i]);
i += PCI_VPD_LRDT_TAG_SIZE;
if (block_end > BNX2X_VPD_LEN)
goto out_not_found;
rodi = pci_vpd_find_info_keyword(vpd_data, i, block_end,
PCI_VPD_RO_KEYWORD_MFR_ID);
if (rodi < 0)
goto out_not_found;
len = pci_vpd_info_field_size(&vpd_data[rodi]);
if (len != VENDOR_ID_LEN)
goto out_not_found;
rodi += PCI_VPD_INFO_FLD_HDR_SIZE;
/* vendor specific info */
snprintf(str_id_reg, VENDOR_ID_LEN + 1, "%04x", PCI_VENDOR_ID_DELL);
snprintf(str_id_cap, VENDOR_ID_LEN + 1, "%04X", PCI_VENDOR_ID_DELL);
if (!strncmp(str_id_reg, &vpd_data[rodi], VENDOR_ID_LEN) ||
!strncmp(str_id_cap, &vpd_data[rodi], VENDOR_ID_LEN)) {
rodi = pci_vpd_find_info_keyword(vpd_data, i, block_end,
PCI_VPD_RO_KEYWORD_VENDOR0);
if (rodi >= 0) {
len = pci_vpd_info_field_size(&vpd_data[rodi]);
rodi += PCI_VPD_INFO_FLD_HDR_SIZE;
if (len < 32 && (len + rodi) <= BNX2X_VPD_LEN) {
memcpy(bp->fw_ver, &vpd_data[rodi], len);
bp->fw_ver[len] = ' ';
}
}
return;
}
out_not_found:
return;
}
static int __devinit bnx2x_init_bp(struct bnx2x *bp)
{
int func = BP_FUNC(bp);
int timer_interval;
int rc;
/* Disable interrupt handling until HW is initialized */
atomic_set(&bp->intr_sem, 1);
smp_wmb(); /* Ensure that bp->intr_sem update is SMP-safe */
mutex_init(&bp->port.phy_mutex);
mutex_init(&bp->fw_mb_mutex);
spin_lock_init(&bp->stats_lock);
#ifdef BCM_CNIC
mutex_init(&bp->cnic_mutex);
#endif
INIT_DELAYED_WORK(&bp->sp_task, bnx2x_sp_task);
INIT_DELAYED_WORK(&bp->reset_task, bnx2x_reset_task);
rc = bnx2x_get_hwinfo(bp);
bnx2x_read_fwinfo(bp);
/* need to reset chip if undi was active */
if (!BP_NOMCP(bp))
bnx2x_undi_unload(bp);
if (CHIP_REV_IS_FPGA(bp))
dev_err(&bp->pdev->dev, "FPGA detected\n");
if (BP_NOMCP(bp) && (func == 0))
dev_err(&bp->pdev->dev, "MCP disabled, "
"must load devices in order!\n");
/* Set multi queue mode */
if ((multi_mode != ETH_RSS_MODE_DISABLED) &&
((int_mode == INT_MODE_INTx) || (int_mode == INT_MODE_MSI))) {
dev_err(&bp->pdev->dev, "Multi disabled since int_mode "
"requested is not MSI-X\n");
multi_mode = ETH_RSS_MODE_DISABLED;
}
bp->multi_mode = multi_mode;
bp->dev->features |= NETIF_F_GRO;
/* Set TPA flags */
if (disable_tpa) {
bp->flags &= ~TPA_ENABLE_FLAG;
bp->dev->features &= ~NETIF_F_LRO;
} else {
bp->flags |= TPA_ENABLE_FLAG;
bp->dev->features |= NETIF_F_LRO;
}
if (CHIP_IS_E1(bp))
bp->dropless_fc = 0;
else
bp->dropless_fc = dropless_fc;
bp->mrrs = mrrs;
bp->tx_ring_size = MAX_TX_AVAIL;
bp->rx_ring_size = MAX_RX_AVAIL;
bp->rx_csum = 1;
/* make sure that the numbers are in the right granularity */
bp->tx_ticks = (50 / (4 * BNX2X_BTR)) * (4 * BNX2X_BTR);
bp->rx_ticks = (25 / (4 * BNX2X_BTR)) * (4 * BNX2X_BTR);
timer_interval = (CHIP_REV_IS_SLOW(bp) ? 5*HZ : HZ);
bp->current_interval = (poll ? poll : timer_interval);
init_timer(&bp->timer);
bp->timer.expires = jiffies + bp->current_interval;
bp->timer.data = (unsigned long) bp;
bp->timer.function = bnx2x_timer;
return rc;
}
/*
* ethtool service functions
*/
/* All ethtool functions called with rtnl_lock */
static int bnx2x_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct bnx2x *bp = netdev_priv(dev);
cmd->supported = bp->port.supported;
cmd->advertising = bp->port.advertising;
if ((bp->state == BNX2X_STATE_OPEN) &&
!(bp->flags & MF_FUNC_DIS) &&
(bp->link_vars.link_up)) {
cmd->speed = bp->link_vars.line_speed;
cmd->duplex = bp->link_vars.duplex;
if (IS_E1HMF(bp)) {
u16 vn_max_rate;
vn_max_rate =
((bp->mf_config & FUNC_MF_CFG_MAX_BW_MASK) >>
FUNC_MF_CFG_MAX_BW_SHIFT) * 100;
if (vn_max_rate < cmd->speed)
cmd->speed = vn_max_rate;
}
} else {
cmd->speed = -1;
cmd->duplex = -1;
}
if (bp->link_params.switch_cfg == SWITCH_CFG_10G) {
u32 ext_phy_type =
XGXS_EXT_PHY_TYPE(bp->link_params.ext_phy_config);
switch (ext_phy_type) {
case PORT_HW_CFG_XGXS_EXT_PHY_TYPE_DIRECT:
case PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM8072:
case PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM8073:
case PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM8705:
case PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM8706:
case PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM8726:
case PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM8727:
cmd->port = PORT_FIBRE;
break;
case PORT_HW_CFG_XGXS_EXT_PHY_TYPE_SFX7101:
case PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM8481:
cmd->port = PORT_TP;
break;
case PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE:
BNX2X_ERR("XGXS PHY Failure detected 0x%x\n",
bp->link_params.ext_phy_config);
break;
default:
DP(NETIF_MSG_LINK, "BAD XGXS ext_phy_config 0x%x\n",
bp->link_params.ext_phy_config);
break;
}
} else
cmd->port = PORT_TP;
cmd->phy_address = bp->mdio.prtad;
cmd->transceiver = XCVR_INTERNAL;
if (bp->link_params.req_line_speed == SPEED_AUTO_NEG)
cmd->autoneg = AUTONEG_ENABLE;
else
cmd->autoneg = AUTONEG_DISABLE;
cmd->maxtxpkt = 0;
cmd->maxrxpkt = 0;
DP(NETIF_MSG_LINK, "ethtool_cmd: cmd %d\n"
DP_LEVEL " supported 0x%x advertising 0x%x speed %d\n"
DP_LEVEL " duplex %d port %d phy_address %d transceiver %d\n"
DP_LEVEL " autoneg %d maxtxpkt %d maxrxpkt %d\n",
cmd->cmd, cmd->supported, cmd->advertising, cmd->speed,
cmd->duplex, cmd->port, cmd->phy_address, cmd->transceiver,
cmd->autoneg, cmd->maxtxpkt, cmd->maxrxpkt);
return 0;
}
static int bnx2x_set_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct bnx2x *bp = netdev_priv(dev);
u32 advertising;
if (IS_E1HMF(bp))
return 0;
DP(NETIF_MSG_LINK, "ethtool_cmd: cmd %d\n"
DP_LEVEL " supported 0x%x advertising 0x%x speed %d\n"
DP_LEVEL " duplex %d port %d phy_address %d transceiver %d\n"
DP_LEVEL " autoneg %d maxtxpkt %d maxrxpkt %d\n",
cmd->cmd, cmd->supported, cmd->advertising, cmd->speed,
cmd->duplex, cmd->port, cmd->phy_address, cmd->transceiver,
cmd->autoneg, cmd->maxtxpkt, cmd->maxrxpkt);
if (cmd->autoneg == AUTONEG_ENABLE) {
if (!(bp->port.supported & SUPPORTED_Autoneg)) {
DP(NETIF_MSG_LINK, "Autoneg not supported\n");
return -EINVAL;
}
/* advertise the requested speed and duplex if supported */
cmd->advertising &= bp->port.supported;
bp->link_params.req_line_speed = SPEED_AUTO_NEG;
bp->link_params.req_duplex = DUPLEX_FULL;
bp->port.advertising |= (ADVERTISED_Autoneg |
cmd->advertising);
} else { /* forced speed */
/* advertise the requested speed and duplex if supported */
switch (cmd->speed) {
case SPEED_10:
if (cmd->duplex == DUPLEX_FULL) {
if (!(bp->port.supported &
SUPPORTED_10baseT_Full)) {
DP(NETIF_MSG_LINK,
"10M full not supported\n");
return -EINVAL;
}
advertising = (ADVERTISED_10baseT_Full |
ADVERTISED_TP);
} else {
if (!(bp->port.supported &
SUPPORTED_10baseT_Half)) {
DP(NETIF_MSG_LINK,
"10M half not supported\n");
return -EINVAL;
}
advertising = (ADVERTISED_10baseT_Half |
ADVERTISED_TP);
}
break;
case SPEED_100:
if (cmd->duplex == DUPLEX_FULL) {
if (!(bp->port.supported &
SUPPORTED_100baseT_Full)) {
DP(NETIF_MSG_LINK,
"100M full not supported\n");
return -EINVAL;
}
advertising = (ADVERTISED_100baseT_Full |
ADVERTISED_TP);
} else {
if (!(bp->port.supported &
SUPPORTED_100baseT_Half)) {
DP(NETIF_MSG_LINK,
"100M half not supported\n");
return -EINVAL;
}
advertising = (ADVERTISED_100baseT_Half |
ADVERTISED_TP);
}
break;
case SPEED_1000:
if (cmd->duplex != DUPLEX_FULL) {
DP(NETIF_MSG_LINK, "1G half not supported\n");
return -EINVAL;
}
if (!(bp->port.supported & SUPPORTED_1000baseT_Full)) {
DP(NETIF_MSG_LINK, "1G full not supported\n");
return -EINVAL;
}
advertising = (ADVERTISED_1000baseT_Full |
ADVERTISED_TP);
break;
case SPEED_2500:
if (cmd->duplex != DUPLEX_FULL) {
DP(NETIF_MSG_LINK,
"2.5G half not supported\n");
return -EINVAL;
}
if (!(bp->port.supported & SUPPORTED_2500baseX_Full)) {
DP(NETIF_MSG_LINK,
"2.5G full not supported\n");
return -EINVAL;
}
advertising = (ADVERTISED_2500baseX_Full |
ADVERTISED_TP);
break;
case SPEED_10000:
if (cmd->duplex != DUPLEX_FULL) {
DP(NETIF_MSG_LINK, "10G half not supported\n");
return -EINVAL;
}
if (!(bp->port.supported & SUPPORTED_10000baseT_Full)) {
DP(NETIF_MSG_LINK, "10G full not supported\n");
return -EINVAL;
}
advertising = (ADVERTISED_10000baseT_Full |
ADVERTISED_FIBRE);
break;
default:
DP(NETIF_MSG_LINK, "Unsupported speed\n");
return -EINVAL;
}
bp->link_params.req_line_speed = cmd->speed;
bp->link_params.req_duplex = cmd->duplex;
bp->port.advertising = advertising;
}
DP(NETIF_MSG_LINK, "req_line_speed %d\n"
DP_LEVEL " req_duplex %d advertising 0x%x\n",
bp->link_params.req_line_speed, bp->link_params.req_duplex,
bp->port.advertising);
if (netif_running(dev)) {
bnx2x_stats_handle(bp, STATS_EVENT_STOP);
bnx2x_link_set(bp);
}
return 0;
}
#define IS_E1_ONLINE(info) (((info) & RI_E1_ONLINE) == RI_E1_ONLINE)
#define IS_E1H_ONLINE(info) (((info) & RI_E1H_ONLINE) == RI_E1H_ONLINE)
static int bnx2x_get_regs_len(struct net_device *dev)
{
struct bnx2x *bp = netdev_priv(dev);
int regdump_len = 0;
int i;
if (CHIP_IS_E1(bp)) {
for (i = 0; i < REGS_COUNT; i++)
if (IS_E1_ONLINE(reg_addrs[i].info))
regdump_len += reg_addrs[i].size;
for (i = 0; i < WREGS_COUNT_E1; i++)
if (IS_E1_ONLINE(wreg_addrs_e1[i].info))
regdump_len += wreg_addrs_e1[i].size *
(1 + wreg_addrs_e1[i].read_regs_count);
} else { /* E1H */
for (i = 0; i < REGS_COUNT; i++)
if (IS_E1H_ONLINE(reg_addrs[i].info))
regdump_len += reg_addrs[i].size;
for (i = 0; i < WREGS_COUNT_E1H; i++)
if (IS_E1H_ONLINE(wreg_addrs_e1h[i].info))
regdump_len += wreg_addrs_e1h[i].size *
(1 + wreg_addrs_e1h[i].read_regs_count);
}
regdump_len *= 4;
regdump_len += sizeof(struct dump_hdr);
return regdump_len;
}
static void bnx2x_get_regs(struct net_device *dev,
struct ethtool_regs *regs, void *_p)
{
u32 *p = _p, i, j;
struct bnx2x *bp = netdev_priv(dev);
struct dump_hdr dump_hdr = {0};
regs->version = 0;
memset(p, 0, regs->len);
if (!netif_running(bp->dev))
return;
dump_hdr.hdr_size = (sizeof(struct dump_hdr) / 4) - 1;
dump_hdr.dump_sign = dump_sign_all;
dump_hdr.xstorm_waitp = REG_RD(bp, XSTORM_WAITP_ADDR);
dump_hdr.tstorm_waitp = REG_RD(bp, TSTORM_WAITP_ADDR);
dump_hdr.ustorm_waitp = REG_RD(bp, USTORM_WAITP_ADDR);
dump_hdr.cstorm_waitp = REG_RD(bp, CSTORM_WAITP_ADDR);
dump_hdr.info = CHIP_IS_E1(bp) ? RI_E1_ONLINE : RI_E1H_ONLINE;
memcpy(p, &dump_hdr, sizeof(struct dump_hdr));
p += dump_hdr.hdr_size + 1;
if (CHIP_IS_E1(bp)) {
for (i = 0; i < REGS_COUNT; i++)
if (IS_E1_ONLINE(reg_addrs[i].info))
for (j = 0; j < reg_addrs[i].size; j++)
*p++ = REG_RD(bp,
reg_addrs[i].addr + j*4);
} else { /* E1H */
for (i = 0; i < REGS_COUNT; i++)
if (IS_E1H_ONLINE(reg_addrs[i].info))
for (j = 0; j < reg_addrs[i].size; j++)
*p++ = REG_RD(bp,
reg_addrs[i].addr + j*4);
}
}
#define PHY_FW_VER_LEN 10
static void bnx2x_get_drvinfo(struct net_device *dev,
struct ethtool_drvinfo *info)
{
struct bnx2x *bp = netdev_priv(dev);
u8 phy_fw_ver[PHY_FW_VER_LEN];
strcpy(info->driver, DRV_MODULE_NAME);
strcpy(info->version, DRV_MODULE_VERSION);
phy_fw_ver[0] = '\0';
if (bp->port.pmf) {
bnx2x_acquire_phy_lock(bp);
bnx2x_get_ext_phy_fw_version(&bp->link_params,
(bp->state != BNX2X_STATE_CLOSED),
phy_fw_ver, PHY_FW_VER_LEN);
bnx2x_release_phy_lock(bp);
}
strncpy(info->fw_version, bp->fw_ver, 32);
snprintf(info->fw_version + strlen(bp->fw_ver), 32 - strlen(bp->fw_ver),
"bc %d.%d.%d%s%s",
(bp->common.bc_ver & 0xff0000) >> 16,
(bp->common.bc_ver & 0xff00) >> 8,
(bp->common.bc_ver & 0xff),
((phy_fw_ver[0] != '\0') ? " phy " : ""), phy_fw_ver);
strcpy(info->bus_info, pci_name(bp->pdev));
info->n_stats = BNX2X_NUM_STATS;
info->testinfo_len = BNX2X_NUM_TESTS;
info->eedump_len = bp->common.flash_size;
info->regdump_len = bnx2x_get_regs_len(dev);
}
static void bnx2x_get_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
struct bnx2x *bp = netdev_priv(dev);
if (bp->flags & NO_WOL_FLAG) {
wol->supported = 0;
wol->wolopts = 0;
} else {
wol->supported = WAKE_MAGIC;
if (bp->wol)
wol->wolopts = WAKE_MAGIC;
else
wol->wolopts = 0;
}
memset(&wol->sopass, 0, sizeof(wol->sopass));
}
static int bnx2x_set_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
struct bnx2x *bp = netdev_priv(dev);
if (wol->wolopts & ~WAKE_MAGIC)
return -EINVAL;
if (wol->wolopts & WAKE_MAGIC) {
if (bp->flags & NO_WOL_FLAG)
return -EINVAL;
bp->wol = 1;
} else
bp->wol = 0;
return 0;
}
static u32 bnx2x_get_msglevel(struct net_device *dev)
{
struct bnx2x *bp = netdev_priv(dev);
return bp->msg_enable;
}
static void bnx2x_set_msglevel(struct net_device *dev, u32 level)
{
struct bnx2x *bp = netdev_priv(dev);
if (capable(CAP_NET_ADMIN))
bp->msg_enable = level;
}
static int bnx2x_nway_reset(struct net_device *dev)
{
struct bnx2x *bp = netdev_priv(dev);
if (!bp->port.pmf)
return 0;
if (netif_running(dev)) {
bnx2x_stats_handle(bp, STATS_EVENT_STOP);
bnx2x_link_set(bp);
}
return 0;
}
static u32 bnx2x_get_link(struct net_device *dev)
{
struct bnx2x *bp = netdev_priv(dev);
if (bp->flags & MF_FUNC_DIS)
return 0;
return bp->link_vars.link_up;
}
static int bnx2x_get_eeprom_len(struct net_device *dev)
{
struct bnx2x *bp = netdev_priv(dev);
return bp->common.flash_size;
}
static int bnx2x_acquire_nvram_lock(struct bnx2x *bp)
{
int port = BP_PORT(bp);
int count, i;
u32 val = 0;
/* adjust timeout for emulation/FPGA */
count = NVRAM_TIMEOUT_COUNT;
if (CHIP_REV_IS_SLOW(bp))
count *= 100;
/* request access to nvram interface */
REG_WR(bp, MCP_REG_MCPR_NVM_SW_ARB,
(MCPR_NVM_SW_ARB_ARB_REQ_SET1 << port));
for (i = 0; i < count*10; i++) {
val = REG_RD(bp, MCP_REG_MCPR_NVM_SW_ARB);
if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))
break;
udelay(5);
}
if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
DP(BNX2X_MSG_NVM, "cannot get access to nvram interface\n");
return -EBUSY;
}
return 0;
}
static int bnx2x_release_nvram_lock(struct bnx2x *bp)
{
int port = BP_PORT(bp);
int count, i;
u32 val = 0;
/* adjust timeout for emulation/FPGA */
count = NVRAM_TIMEOUT_COUNT;
if (CHIP_REV_IS_SLOW(bp))
count *= 100;
/* relinquish nvram interface */
REG_WR(bp, MCP_REG_MCPR_NVM_SW_ARB,
(MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << port));
for (i = 0; i < count*10; i++) {
val = REG_RD(bp, MCP_REG_MCPR_NVM_SW_ARB);
if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)))
break;
udelay(5);
}
if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
DP(BNX2X_MSG_NVM, "cannot free access to nvram interface\n");
return -EBUSY;
}
return 0;
}
static void bnx2x_enable_nvram_access(struct bnx2x *bp)
{
u32 val;
val = REG_RD(bp, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
/* enable both bits, even on read */
REG_WR(bp, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
(val | MCPR_NVM_ACCESS_ENABLE_EN |
MCPR_NVM_ACCESS_ENABLE_WR_EN));
}
static void bnx2x_disable_nvram_access(struct bnx2x *bp)
{
u32 val;
val = REG_RD(bp, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
/* disable both bits, even after read */
REG_WR(bp, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
(val & ~(MCPR_NVM_ACCESS_ENABLE_EN |
MCPR_NVM_ACCESS_ENABLE_WR_EN)));
}
static int bnx2x_nvram_read_dword(struct bnx2x *bp, u32 offset, __be32 *ret_val,
u32 cmd_flags)
{
int count, i, rc;
u32 val;
/* build the command word */
cmd_flags |= MCPR_NVM_COMMAND_DOIT;
/* need to clear DONE bit separately */
REG_WR(bp, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
/* address of the NVRAM to read from */
REG_WR(bp, MCP_REG_MCPR_NVM_ADDR,
(offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
/* issue a read command */
REG_WR(bp, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
/* adjust timeout for emulation/FPGA */
count = NVRAM_TIMEOUT_COUNT;
if (CHIP_REV_IS_SLOW(bp))
count *= 100;
/* wait for completion */
*ret_val = 0;
rc = -EBUSY;
for (i = 0; i < count; i++) {
udelay(5);
val = REG_RD(bp, MCP_REG_MCPR_NVM_COMMAND);
if (val & MCPR_NVM_COMMAND_DONE) {
val = REG_RD(bp, MCP_REG_MCPR_NVM_READ);
/* we read nvram data in cpu order
* but ethtool sees it as an array of bytes
* converting to big-endian will do the work */
*ret_val = cpu_to_be32(val);
rc = 0;
break;
}
}
return rc;
}
static int bnx2x_nvram_read(struct bnx2x *bp, u32 offset, u8 *ret_buf,
int buf_size)
{
int rc;
u32 cmd_flags;
__be32 val;
if ((offset & 0x03) || (buf_size & 0x03) || (buf_size == 0)) {
DP(BNX2X_MSG_NVM,
"Invalid parameter: offset 0x%x buf_size 0x%x\n",
offset, buf_size);
return -EINVAL;
}
if (offset + buf_size > bp->common.flash_size) {
DP(BNX2X_MSG_NVM, "Invalid parameter: offset (0x%x) +"
" buf_size (0x%x) > flash_size (0x%x)\n",
offset, buf_size, bp->common.flash_size);
return -EINVAL;
}
/* request access to nvram interface */
rc = bnx2x_acquire_nvram_lock(bp);
if (rc)
return rc;
/* enable access to nvram interface */
bnx2x_enable_nvram_access(bp);
/* read the first word(s) */
cmd_flags = MCPR_NVM_COMMAND_FIRST;
while ((buf_size > sizeof(u32)) && (rc == 0)) {
rc = bnx2x_nvram_read_dword(bp, offset, &val, cmd_flags);
memcpy(ret_buf, &val, 4);
/* advance to the next dword */
offset += sizeof(u32);
ret_buf += sizeof(u32);
buf_size -= sizeof(u32);
cmd_flags = 0;
}
if (rc == 0) {
cmd_flags |= MCPR_NVM_COMMAND_LAST;
rc = bnx2x_nvram_read_dword(bp, offset, &val, cmd_flags);
memcpy(ret_buf, &val, 4);
}
/* disable access to nvram interface */
bnx2x_disable_nvram_access(bp);
bnx2x_release_nvram_lock(bp);
return rc;
}
static int bnx2x_get_eeprom(struct net_device *dev,
struct ethtool_eeprom *eeprom, u8 *eebuf)
{
struct bnx2x *bp = netdev_priv(dev);
int rc;
if (!netif_running(dev))
return -EAGAIN;
DP(BNX2X_MSG_NVM, "ethtool_eeprom: cmd %d\n"
DP_LEVEL " magic 0x%x offset 0x%x (%d) len 0x%x (%d)\n",
eeprom->cmd, eeprom->magic, eeprom->offset, eeprom->offset,
eeprom->len, eeprom->len);
/* parameters already validated in ethtool_get_eeprom */
rc = bnx2x_nvram_read(bp, eeprom->offset, eebuf, eeprom->len);
return rc;
}
static int bnx2x_nvram_write_dword(struct bnx2x *bp, u32 offset, u32 val,
u32 cmd_flags)
{
int count, i, rc;
/* build the command word */
cmd_flags |= MCPR_NVM_COMMAND_DOIT | MCPR_NVM_COMMAND_WR;
/* need to clear DONE bit separately */
REG_WR(bp, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
/* write the data */
REG_WR(bp, MCP_REG_MCPR_NVM_WRITE, val);
/* address of the NVRAM to write to */
REG_WR(bp, MCP_REG_MCPR_NVM_ADDR,
(offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
/* issue the write command */
REG_WR(bp, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
/* adjust timeout for emulation/FPGA */
count = NVRAM_TIMEOUT_COUNT;
if (CHIP_REV_IS_SLOW(bp))
count *= 100;
/* wait for completion */
rc = -EBUSY;
for (i = 0; i < count; i++) {
udelay(5);
val = REG_RD(bp, MCP_REG_MCPR_NVM_COMMAND);
if (val & MCPR_NVM_COMMAND_DONE) {
rc = 0;
break;
}
}
return rc;
}
#define BYTE_OFFSET(offset) (8 * (offset & 0x03))
static int bnx2x_nvram_write1(struct bnx2x *bp, u32 offset, u8 *data_buf,
int buf_size)
{
int rc;
u32 cmd_flags;
u32 align_offset;
__be32 val;
if (offset + buf_size > bp->common.flash_size) {
DP(BNX2X_MSG_NVM, "Invalid parameter: offset (0x%x) +"
" buf_size (0x%x) > flash_size (0x%x)\n",
offset, buf_size, bp->common.flash_size);
return -EINVAL;
}
/* request access to nvram interface */
rc = bnx2x_acquire_nvram_lock(bp);
if (rc)
return rc;
/* enable access to nvram interface */
bnx2x_enable_nvram_access(bp);
cmd_flags = (MCPR_NVM_COMMAND_FIRST | MCPR_NVM_COMMAND_LAST);
align_offset = (offset & ~0x03);
rc = bnx2x_nvram_read_dword(bp, align_offset, &val, cmd_flags);
if (rc == 0) {
val &= ~(0xff << BYTE_OFFSET(offset));
val |= (*data_buf << BYTE_OFFSET(offset));
/* nvram data is returned as an array of bytes
* convert it back to cpu order */
val = be32_to_cpu(val);
rc = bnx2x_nvram_write_dword(bp, align_offset, val,
cmd_flags);
}
/* disable access to nvram interface */
bnx2x_disable_nvram_access(bp);
bnx2x_release_nvram_lock(bp);
return rc;
}
static int bnx2x_nvram_write(struct bnx2x *bp, u32 offset, u8 *data_buf,
int buf_size)
{
int rc;
u32 cmd_flags;
u32 val;
u32 written_so_far;
if (buf_size == 1) /* ethtool */
return bnx2x_nvram_write1(bp, offset, data_buf, buf_size);
if ((offset & 0x03) || (buf_size & 0x03) || (buf_size == 0)) {
DP(BNX2X_MSG_NVM,
"Invalid parameter: offset 0x%x buf_size 0x%x\n",
offset, buf_size);
return -EINVAL;
}
if (offset + buf_size > bp->common.flash_size) {
DP(BNX2X_MSG_NVM, "Invalid parameter: offset (0x%x) +"
" buf_size (0x%x) > flash_size (0x%x)\n",
offset, buf_size, bp->common.flash_size);
return -EINVAL;
}
/* request access to nvram interface */
rc = bnx2x_acquire_nvram_lock(bp);
if (rc)
return rc;
/* enable access to nvram interface */
bnx2x_enable_nvram_access(bp);
written_so_far = 0;
cmd_flags = MCPR_NVM_COMMAND_FIRST;
while ((written_so_far < buf_size) && (rc == 0)) {
if (written_so_far == (buf_size - sizeof(u32)))
cmd_flags |= MCPR_NVM_COMMAND_LAST;
else if (((offset + 4) % NVRAM_PAGE_SIZE) == 0)
cmd_flags |= MCPR_NVM_COMMAND_LAST;
else if ((offset % NVRAM_PAGE_SIZE) == 0)
cmd_flags |= MCPR_NVM_COMMAND_FIRST;
memcpy(&val, data_buf, 4);
rc = bnx2x_nvram_write_dword(bp, offset, val, cmd_flags);
/* advance to the next dword */
offset += sizeof(u32);
data_buf += sizeof(u32);
written_so_far += sizeof(u32);
cmd_flags = 0;
}
/* disable access to nvram interface */
bnx2x_disable_nvram_access(bp);
bnx2x_release_nvram_lock(bp);
return rc;
}
static int bnx2x_set_eeprom(struct net_device *dev,
struct ethtool_eeprom *eeprom, u8 *eebuf)
{
struct bnx2x *bp = netdev_priv(dev);
int port = BP_PORT(bp);
int rc = 0;
if (!netif_running(dev))
return -EAGAIN;
DP(BNX2X_MSG_NVM, "ethtool_eeprom: cmd %d\n"
DP_LEVEL " magic 0x%x offset 0x%x (%d) len 0x%x (%d)\n",
eeprom->cmd, eeprom->magic, eeprom->offset, eeprom->offset,
eeprom->len, eeprom->len);
/* parameters already validated in ethtool_set_eeprom */
/* PHY eeprom can be accessed only by the PMF */
if ((eeprom->magic >= 0x50485900) && (eeprom->magic <= 0x504859FF) &&
!bp->port.pmf)
return -EINVAL;
if (eeprom->magic == 0x50485950) {
/* 'PHYP' (0x50485950): prepare phy for FW upgrade */
bnx2x_stats_handle(bp, STATS_EVENT_STOP);
bnx2x_acquire_phy_lock(bp);
rc |= bnx2x_link_reset(&bp->link_params,
&bp->link_vars, 0);
if (XGXS_EXT_PHY_TYPE(bp->link_params.ext_phy_config) ==
PORT_HW_CFG_XGXS_EXT_PHY_TYPE_SFX7101)
bnx2x_set_gpio(bp, MISC_REGISTERS_GPIO_0,
MISC_REGISTERS_GPIO_HIGH, port);
bnx2x_release_phy_lock(bp);
bnx2x_link_report(bp);
} else if (eeprom->magic == 0x50485952) {
/* 'PHYR' (0x50485952): re-init link after FW upgrade */
if (bp->state == BNX2X_STATE_OPEN) {
bnx2x_acquire_phy_lock(bp);
rc |= bnx2x_link_reset(&bp->link_params,
&bp->link_vars, 1);
rc |= bnx2x_phy_init(&bp->link_params,
&bp->link_vars);
bnx2x_release_phy_lock(bp);
bnx2x_calc_fc_adv(bp);
}
} else if (eeprom->magic == 0x53985943) {
/* 'PHYC' (0x53985943): PHY FW upgrade completed */
if (XGXS_EXT_PHY_TYPE(bp->link_params.ext_phy_config) ==
PORT_HW_CFG_XGXS_EXT_PHY_TYPE_SFX7101) {
u8 ext_phy_addr =
XGXS_EXT_PHY_ADDR(bp->link_params.ext_phy_config);
/* DSP Remove Download Mode */
bnx2x_set_gpio(bp, MISC_REGISTERS_GPIO_0,
MISC_REGISTERS_GPIO_LOW, port);
bnx2x_acquire_phy_lock(bp);
bnx2x_sfx7101_sp_sw_reset(bp, port, ext_phy_addr);
/* wait 0.5 sec to allow it to run */
msleep(500);
bnx2x_ext_phy_hw_reset(bp, port);
msleep(500);
bnx2x_release_phy_lock(bp);
}
} else
rc = bnx2x_nvram_write(bp, eeprom->offset, eebuf, eeprom->len);
return rc;
}
static int bnx2x_get_coalesce(struct net_device *dev,
struct ethtool_coalesce *coal)
{
struct bnx2x *bp = netdev_priv(dev);
memset(coal, 0, sizeof(struct ethtool_coalesce));
coal->rx_coalesce_usecs = bp->rx_ticks;
coal->tx_coalesce_usecs = bp->tx_ticks;
return 0;
}
static int bnx2x_set_coalesce(struct net_device *dev,
struct ethtool_coalesce *coal)
{
struct bnx2x *bp = netdev_priv(dev);
bp->rx_ticks = (u16)coal->rx_coalesce_usecs;
if (bp->rx_ticks > BNX2X_MAX_COALESCE_TOUT)
bp->rx_ticks = BNX2X_MAX_COALESCE_TOUT;
bp->tx_ticks = (u16)coal->tx_coalesce_usecs;
if (bp->tx_ticks > BNX2X_MAX_COALESCE_TOUT)
bp->tx_ticks = BNX2X_MAX_COALESCE_TOUT;
if (netif_running(dev))
bnx2x_update_coalesce(bp);
return 0;
}
static void bnx2x_get_ringparam(struct net_device *dev,
struct ethtool_ringparam *ering)
{
struct bnx2x *bp = netdev_priv(dev);
ering->rx_max_pending = MAX_RX_AVAIL;
ering->rx_mini_max_pending = 0;
ering->rx_jumbo_max_pending = 0;
ering->rx_pending = bp->rx_ring_size;
ering->rx_mini_pending = 0;
ering->rx_jumbo_pending = 0;
ering->tx_max_pending = MAX_TX_AVAIL;
ering->tx_pending = bp->tx_ring_size;
}
static int bnx2x_set_ringparam(struct net_device *dev,
struct ethtool_ringparam *ering)
{
struct bnx2x *bp = netdev_priv(dev);
int rc = 0;
if (bp->recovery_state != BNX2X_RECOVERY_DONE) {
printk(KERN_ERR "Handling parity error recovery. Try again later\n");
return -EAGAIN;
}
if ((ering->rx_pending > MAX_RX_AVAIL) ||
(ering->tx_pending > MAX_TX_AVAIL) ||
(ering->tx_pending <= MAX_SKB_FRAGS + 4))
return -EINVAL;
bp->rx_ring_size = ering->rx_pending;
bp->tx_ring_size = ering->tx_pending;
if (netif_running(dev)) {
bnx2x_nic_unload(bp, UNLOAD_NORMAL);
rc = bnx2x_nic_load(bp, LOAD_NORMAL);
}
return rc;
}
static void bnx2x_get_pauseparam(struct net_device *dev,
struct ethtool_pauseparam *epause)
{
struct bnx2x *bp = netdev_priv(dev);
epause->autoneg = (bp->link_params.req_flow_ctrl ==
BNX2X_FLOW_CTRL_AUTO) &&
(bp->link_params.req_line_speed == SPEED_AUTO_NEG);
epause->rx_pause = ((bp->link_vars.flow_ctrl & BNX2X_FLOW_CTRL_RX) ==
BNX2X_FLOW_CTRL_RX);
epause->tx_pause = ((bp->link_vars.flow_ctrl & BNX2X_FLOW_CTRL_TX) ==
BNX2X_FLOW_CTRL_TX);
DP(NETIF_MSG_LINK, "ethtool_pauseparam: cmd %d\n"
DP_LEVEL " autoneg %d rx_pause %d tx_pause %d\n",
epause->cmd, epause->autoneg, epause->rx_pause, epause->tx_pause);
}
static int bnx2x_set_pauseparam(struct net_device *dev,
struct ethtool_pauseparam *epause)
{
struct bnx2x *bp = netdev_priv(dev);
if (IS_E1HMF(bp))
return 0;
DP(NETIF_MSG_LINK, "ethtool_pauseparam: cmd %d\n"
DP_LEVEL " autoneg %d rx_pause %d tx_pause %d\n",
epause->cmd, epause->autoneg, epause->rx_pause, epause->tx_pause);
bp->link_params.req_flow_ctrl = BNX2X_FLOW_CTRL_AUTO;
if (epause->rx_pause)
bp->link_params.req_flow_ctrl |= BNX2X_FLOW_CTRL_RX;
if (epause->tx_pause)
bp->link_params.req_flow_ctrl |= BNX2X_FLOW_CTRL_TX;
if (bp->link_params.req_flow_ctrl == BNX2X_FLOW_CTRL_AUTO)
bp->link_params.req_flow_ctrl = BNX2X_FLOW_CTRL_NONE;
if (epause->autoneg) {
if (!(bp->port.supported & SUPPORTED_Autoneg)) {
DP(NETIF_MSG_LINK, "autoneg not supported\n");
return -EINVAL;
}
if (bp->link_params.req_line_speed == SPEED_AUTO_NEG)
bp->link_params.req_flow_ctrl = BNX2X_FLOW_CTRL_AUTO;
}
DP(NETIF_MSG_LINK,
"req_flow_ctrl 0x%x\n", bp->link_params.req_flow_ctrl);
if (netif_running(dev)) {
bnx2x_stats_handle(bp, STATS_EVENT_STOP);
bnx2x_link_set(bp);
}
return 0;
}
static int bnx2x_set_flags(struct net_device *dev, u32 data)
{
struct bnx2x *bp = netdev_priv(dev);
int changed = 0;
int rc = 0;
if (bp->recovery_state != BNX2X_RECOVERY_DONE) {
printk(KERN_ERR "Handling parity error recovery. Try again later\n");
return -EAGAIN;
}
/* TPA requires Rx CSUM offloading */
if ((data & ETH_FLAG_LRO) && bp->rx_csum) {
if (!disable_tpa) {
if (!(dev->features & NETIF_F_LRO)) {
dev->features |= NETIF_F_LRO;
bp->flags |= TPA_ENABLE_FLAG;
changed = 1;
}
} else
rc = -EINVAL;
} else if (dev->features & NETIF_F_LRO) {
dev->features &= ~NETIF_F_LRO;
bp->flags &= ~TPA_ENABLE_FLAG;
changed = 1;
}
if (data & ETH_FLAG_RXHASH)
dev->features |= NETIF_F_RXHASH;
else
dev->features &= ~NETIF_F_RXHASH;
if (changed && netif_running(dev)) {
bnx2x_nic_unload(bp, UNLOAD_NORMAL);
rc = bnx2x_nic_load(bp, LOAD_NORMAL);
}
return rc;
}
static u32 bnx2x_get_rx_csum(struct net_device *dev)
{
struct bnx2x *bp = netdev_priv(dev);
return bp->rx_csum;
}
static int bnx2x_set_rx_csum(struct net_device *dev, u32 data)
{
struct bnx2x *bp = netdev_priv(dev);
int rc = 0;
if (bp->recovery_state != BNX2X_RECOVERY_DONE) {
printk(KERN_ERR "Handling parity error recovery. Try again later\n");
return -EAGAIN;
}
bp->rx_csum = data;
/* Disable TPA, when Rx CSUM is disabled. Otherwise all
TPA'ed packets will be discarded due to wrong TCP CSUM */
if (!data) {
u32 flags = ethtool_op_get_flags(dev);
rc = bnx2x_set_flags(dev, (flags & ~ETH_FLAG_LRO));
}
return rc;
}
static int bnx2x_set_tso(struct net_device *dev, u32 data)
{
if (data) {
dev->features |= (NETIF_F_TSO | NETIF_F_TSO_ECN);
dev->features |= NETIF_F_TSO6;
} else {
dev->features &= ~(NETIF_F_TSO | NETIF_F_TSO_ECN);
dev->features &= ~NETIF_F_TSO6;
}
return 0;
}
static const struct {
char string[ETH_GSTRING_LEN];
} bnx2x_tests_str_arr[BNX2X_NUM_TESTS] = {
{ "register_test (offline)" },
{ "memory_test (offline)" },
{ "loopback_test (offline)" },
{ "nvram_test (online)" },
{ "interrupt_test (online)" },
{ "link_test (online)" },
{ "idle check (online)" }
};
static int bnx2x_test_registers(struct bnx2x *bp)
{
int idx, i, rc = -ENODEV;
u32 wr_val = 0;
int port = BP_PORT(bp);
static const struct {
u32 offset0;
u32 offset1;
u32 mask;
} reg_tbl[] = {
/* 0 */ { BRB1_REG_PAUSE_LOW_THRESHOLD_0, 4, 0x000003ff },
{ DORQ_REG_DB_ADDR0, 4, 0xffffffff },
{ HC_REG_AGG_INT_0, 4, 0x000003ff },
{ PBF_REG_MAC_IF0_ENABLE, 4, 0x00000001 },
{ PBF_REG_P0_INIT_CRD, 4, 0x000007ff },
{ PRS_REG_CID_PORT_0, 4, 0x00ffffff },
{ PXP2_REG_PSWRQ_CDU0_L2P, 4, 0x000fffff },
{ PXP2_REG_RQ_CDU0_EFIRST_MEM_ADDR, 8, 0x0003ffff },
{ PXP2_REG_PSWRQ_TM0_L2P, 4, 0x000fffff },
{ PXP2_REG_RQ_USDM0_EFIRST_MEM_ADDR, 8, 0x0003ffff },
/* 10 */ { PXP2_REG_PSWRQ_TSDM0_L2P, 4, 0x000fffff },
{ QM_REG_CONNNUM_0, 4, 0x000fffff },
{ TM_REG_LIN0_MAX_ACTIVE_CID, 4, 0x0003ffff },
{ SRC_REG_KEYRSS0_0, 40, 0xffffffff },
{ SRC_REG_KEYRSS0_7, 40, 0xffffffff },
{ XCM_REG_WU_DA_SET_TMR_CNT_FLG_CMD00, 4, 0x00000001 },
{ XCM_REG_WU_DA_CNT_CMD00, 4, 0x00000003 },
{ XCM_REG_GLB_DEL_ACK_MAX_CNT_0, 4, 0x000000ff },
{ NIG_REG_LLH0_T_BIT, 4, 0x00000001 },
{ NIG_REG_EMAC0_IN_EN, 4, 0x00000001 },
/* 20 */ { NIG_REG_BMAC0_IN_EN, 4, 0x00000001 },
{ NIG_REG_XCM0_OUT_EN, 4, 0x00000001 },
{ NIG_REG_BRB0_OUT_EN, 4, 0x00000001 },
{ NIG_REG_LLH0_XCM_MASK, 4, 0x00000007 },
{ NIG_REG_LLH0_ACPI_PAT_6_LEN, 68, 0x000000ff },
{ NIG_REG_LLH0_ACPI_PAT_0_CRC, 68, 0xffffffff },
{ NIG_REG_LLH0_DEST_MAC_0_0, 160, 0xffffffff },
{ NIG_REG_LLH0_DEST_IP_0_1, 160, 0xffffffff },
{ NIG_REG_LLH0_IPV4_IPV6_0, 160, 0x00000001 },
{ NIG_REG_LLH0_DEST_UDP_0, 160, 0x0000ffff },
/* 30 */ { NIG_REG_LLH0_DEST_TCP_0, 160, 0x0000ffff },
{ NIG_REG_LLH0_VLAN_ID_0, 160, 0x00000fff },
{ NIG_REG_XGXS_SERDES0_MODE_SEL, 4, 0x00000001 },
{ NIG_REG_LED_CONTROL_OVERRIDE_TRAFFIC_P0, 4, 0x00000001 },
{ NIG_REG_STATUS_INTERRUPT_PORT0, 4, 0x07ffffff },
{ NIG_REG_XGXS0_CTRL_EXTREMOTEMDIOST, 24, 0x00000001 },
{ NIG_REG_SERDES0_CTRL_PHY_ADDR, 16, 0x0000001f },
{ 0xffffffff, 0, 0x00000000 }
};
if (!netif_running(bp->dev))
return rc;
/* Repeat the test twice:
First by writing 0x00000000, second by writing 0xffffffff */
for (idx = 0; idx < 2; idx++) {
switch (idx) {
case 0:
wr_val = 0;
break;
case 1:
wr_val = 0xffffffff;
break;
}
for (i = 0; reg_tbl[i].offset0 != 0xffffffff; i++) {
u32 offset, mask, save_val, val;
offset = reg_tbl[i].offset0 + port*reg_tbl[i].offset1;
mask = reg_tbl[i].mask;
save_val = REG_RD(bp, offset);
REG_WR(bp, offset, (wr_val & mask));
val = REG_RD(bp, offset);
/* Restore the original register's value */
REG_WR(bp, offset, save_val);
/* verify value is as expected */
if ((val & mask) != (wr_val & mask)) {
DP(NETIF_MSG_PROBE,
"offset 0x%x: val 0x%x != 0x%x mask 0x%x\n",
offset, val, wr_val, mask);
goto test_reg_exit;
}
}
}
rc = 0;
test_reg_exit:
return rc;
}
static int bnx2x_test_memory(struct bnx2x *bp)
{
int i, j, rc = -ENODEV;
u32 val;
static const struct {
u32 offset;
int size;
} mem_tbl[] = {
{ CCM_REG_XX_DESCR_TABLE, CCM_REG_XX_DESCR_TABLE_SIZE },
{ CFC_REG_ACTIVITY_COUNTER, CFC_REG_ACTIVITY_COUNTER_SIZE },
{ CFC_REG_LINK_LIST, CFC_REG_LINK_LIST_SIZE },
{ DMAE_REG_CMD_MEM, DMAE_REG_CMD_MEM_SIZE },
{ TCM_REG_XX_DESCR_TABLE, TCM_REG_XX_DESCR_TABLE_SIZE },
{ UCM_REG_XX_DESCR_TABLE, UCM_REG_XX_DESCR_TABLE_SIZE },
{ XCM_REG_XX_DESCR_TABLE, XCM_REG_XX_DESCR_TABLE_SIZE },
{ 0xffffffff, 0 }
};
static const struct {
char *name;
u32 offset;
u32 e1_mask;
u32 e1h_mask;
} prty_tbl[] = {
{ "CCM_PRTY_STS", CCM_REG_CCM_PRTY_STS, 0x3ffc0, 0 },
{ "CFC_PRTY_STS", CFC_REG_CFC_PRTY_STS, 0x2, 0x2 },
{ "DMAE_PRTY_STS", DMAE_REG_DMAE_PRTY_STS, 0, 0 },
{ "TCM_PRTY_STS", TCM_REG_TCM_PRTY_STS, 0x3ffc0, 0 },
{ "UCM_PRTY_STS", UCM_REG_UCM_PRTY_STS, 0x3ffc0, 0 },
{ "XCM_PRTY_STS", XCM_REG_XCM_PRTY_STS, 0x3ffc1, 0 },
{ NULL, 0xffffffff, 0, 0 }
};
if (!netif_running(bp->dev))
return rc;
/* Go through all the memories */
for (i = 0; mem_tbl[i].offset != 0xffffffff; i++)
for (j = 0; j < mem_tbl[i].size; j++)
REG_RD(bp, mem_tbl[i].offset + j*4);
/* Check the parity status */
for (i = 0; prty_tbl[i].offset != 0xffffffff; i++) {
val = REG_RD(bp, prty_tbl[i].offset);
if ((CHIP_IS_E1(bp) && (val & ~(prty_tbl[i].e1_mask))) ||
(CHIP_IS_E1H(bp) && (val & ~(prty_tbl[i].e1h_mask)))) {
DP(NETIF_MSG_HW,
"%s is 0x%x\n", prty_tbl[i].name, val);
goto test_mem_exit;
}
}
rc = 0;
test_mem_exit:
return rc;
}
static void bnx2x_wait_for_link(struct bnx2x *bp, u8 link_up)
{
int cnt = 1000;
if (link_up)
while (bnx2x_link_test(bp) && cnt--)
msleep(10);
}
static int bnx2x_run_loopback(struct bnx2x *bp, int loopback_mode, u8 link_up)
{
unsigned int pkt_size, num_pkts, i;
struct sk_buff *skb;
unsigned char *packet;
struct bnx2x_fastpath *fp_rx = &bp->fp[0];
struct bnx2x_fastpath *fp_tx = &bp->fp[0];
u16 tx_start_idx, tx_idx;
u16 rx_start_idx, rx_idx;
u16 pkt_prod, bd_prod;
struct sw_tx_bd *tx_buf;
struct eth_tx_start_bd *tx_start_bd;
struct eth_tx_parse_bd *pbd = NULL;
dma_addr_t mapping;
union eth_rx_cqe *cqe;
u8 cqe_fp_flags;
struct sw_rx_bd *rx_buf;
u16 len;
int rc = -ENODEV;
/* check the loopback mode */
switch (loopback_mode) {
case BNX2X_PHY_LOOPBACK:
if (bp->link_params.loopback_mode != LOOPBACK_XGXS_10)
return -EINVAL;
break;
case BNX2X_MAC_LOOPBACK:
bp->link_params.loopback_mode = LOOPBACK_BMAC;
bnx2x_phy_init(&bp->link_params, &bp->link_vars);
break;
default:
return -EINVAL;
}
/* prepare the loopback packet */
pkt_size = (((bp->dev->mtu < ETH_MAX_PACKET_SIZE) ?
bp->dev->mtu : ETH_MAX_PACKET_SIZE) + ETH_HLEN);
skb = netdev_alloc_skb(bp->dev, bp->rx_buf_size);
if (!skb) {
rc = -ENOMEM;
goto test_loopback_exit;
}
packet = skb_put(skb, pkt_size);
memcpy(packet, bp->dev->dev_addr, ETH_ALEN);
memset(packet + ETH_ALEN, 0, ETH_ALEN);
memset(packet + 2*ETH_ALEN, 0x77, (ETH_HLEN - 2*ETH_ALEN));
for (i = ETH_HLEN; i < pkt_size; i++)
packet[i] = (unsigned char) (i & 0xff);
/* send the loopback packet */
num_pkts = 0;
tx_start_idx = le16_to_cpu(*fp_tx->tx_cons_sb);
rx_start_idx = le16_to_cpu(*fp_rx->rx_cons_sb);
pkt_prod = fp_tx->tx_pkt_prod++;
tx_buf = &fp_tx->tx_buf_ring[TX_BD(pkt_prod)];
tx_buf->first_bd = fp_tx->tx_bd_prod;
tx_buf->skb = skb;
tx_buf->flags = 0;
bd_prod = TX_BD(fp_tx->tx_bd_prod);
tx_start_bd = &fp_tx->tx_desc_ring[bd_prod].start_bd;
mapping = dma_map_single(&bp->pdev->dev, skb->data,
skb_headlen(skb), DMA_TO_DEVICE);
tx_start_bd->addr_hi = cpu_to_le32(U64_HI(mapping));
tx_start_bd->addr_lo = cpu_to_le32(U64_LO(mapping));
tx_start_bd->nbd = cpu_to_le16(2); /* start + pbd */
tx_start_bd->nbytes = cpu_to_le16(skb_headlen(skb));
tx_start_bd->vlan = cpu_to_le16(pkt_prod);
tx_start_bd->bd_flags.as_bitfield = ETH_TX_BD_FLAGS_START_BD;
tx_start_bd->general_data = ((UNICAST_ADDRESS <<
ETH_TX_START_BD_ETH_ADDR_TYPE_SHIFT) | 1);
/* turn on parsing and get a BD */
bd_prod = TX_BD(NEXT_TX_IDX(bd_prod));
pbd = &fp_tx->tx_desc_ring[bd_prod].parse_bd;
memset(pbd, 0, sizeof(struct eth_tx_parse_bd));
wmb();
fp_tx->tx_db.data.prod += 2;
barrier();
DOORBELL(bp, fp_tx->index, fp_tx->tx_db.raw);
mmiowb();
num_pkts++;
fp_tx->tx_bd_prod += 2; /* start + pbd */
udelay(100);
tx_idx = le16_to_cpu(*fp_tx->tx_cons_sb);
if (tx_idx != tx_start_idx + num_pkts)
goto test_loopback_exit;
rx_idx = le16_to_cpu(*fp_rx->rx_cons_sb);
if (rx_idx != rx_start_idx + num_pkts)
goto test_loopback_exit;
cqe = &fp_rx->rx_comp_ring[RCQ_BD(fp_rx->rx_comp_cons)];
cqe_fp_flags = cqe->fast_path_cqe.type_error_flags;
if (CQE_TYPE(cqe_fp_flags) || (cqe_fp_flags & ETH_RX_ERROR_FALGS))
goto test_loopback_rx_exit;
len = le16_to_cpu(cqe->fast_path_cqe.pkt_len);
if (len != pkt_size)
goto test_loopback_rx_exit;
rx_buf = &fp_rx->rx_buf_ring[RX_BD(fp_rx->rx_bd_cons)];
skb = rx_buf->skb;
skb_reserve(skb, cqe->fast_path_cqe.placement_offset);
for (i = ETH_HLEN; i < pkt_size; i++)
if (*(skb->data + i) != (unsigned char) (i & 0xff))
goto test_loopback_rx_exit;
rc = 0;
test_loopback_rx_exit:
fp_rx->rx_bd_cons = NEXT_RX_IDX(fp_rx->rx_bd_cons);
fp_rx->rx_bd_prod = NEXT_RX_IDX(fp_rx->rx_bd_prod);
fp_rx->rx_comp_cons = NEXT_RCQ_IDX(fp_rx->rx_comp_cons);
fp_rx->rx_comp_prod = NEXT_RCQ_IDX(fp_rx->rx_comp_prod);
/* Update producers */
bnx2x_update_rx_prod(bp, fp_rx, fp_rx->rx_bd_prod, fp_rx->rx_comp_prod,
fp_rx->rx_sge_prod);
test_loopback_exit:
bp->link_params.loopback_mode = LOOPBACK_NONE;
return rc;
}
static int bnx2x_test_loopback(struct bnx2x *bp, u8 link_up)
{
int rc = 0, res;
if (BP_NOMCP(bp))
return rc;
if (!netif_running(bp->dev))
return BNX2X_LOOPBACK_FAILED;
bnx2x_netif_stop(bp, 1);
bnx2x_acquire_phy_lock(bp);
res = bnx2x_run_loopback(bp, BNX2X_PHY_LOOPBACK, link_up);
if (res) {
DP(NETIF_MSG_PROBE, " PHY loopback failed (res %d)\n", res);
rc |= BNX2X_PHY_LOOPBACK_FAILED;
}
res = bnx2x_run_loopback(bp, BNX2X_MAC_LOOPBACK, link_up);
if (res) {
DP(NETIF_MSG_PROBE, " MAC loopback failed (res %d)\n", res);
rc |= BNX2X_MAC_LOOPBACK_FAILED;
}
bnx2x_release_phy_lock(bp);
bnx2x_netif_start(bp);
return rc;
}
#define CRC32_RESIDUAL 0xdebb20e3
static int bnx2x_test_nvram(struct bnx2x *bp)
{
static const struct {
int offset;
int size;
} nvram_tbl[] = {
{ 0, 0x14 }, /* bootstrap */
{ 0x14, 0xec }, /* dir */
{ 0x100, 0x350 }, /* manuf_info */
{ 0x450, 0xf0 }, /* feature_info */
{ 0x640, 0x64 }, /* upgrade_key_info */
{ 0x6a4, 0x64 },
{ 0x708, 0x70 }, /* manuf_key_info */
{ 0x778, 0x70 },
{ 0, 0 }
};
__be32 buf[0x350 / 4];
u8 *data = (u8 *)buf;
int i, rc;
u32 magic, crc;
if (BP_NOMCP(bp))
return 0;
rc = bnx2x_nvram_read(bp, 0, data, 4);
if (rc) {
DP(NETIF_MSG_PROBE, "magic value read (rc %d)\n", rc);
goto test_nvram_exit;
}
magic = be32_to_cpu(buf[0]);
if (magic != 0x669955aa) {
DP(NETIF_MSG_PROBE, "magic value (0x%08x)\n", magic);
rc = -ENODEV;
goto test_nvram_exit;
}
for (i = 0; nvram_tbl[i].size; i++) {
rc = bnx2x_nvram_read(bp, nvram_tbl[i].offset, data,
nvram_tbl[i].size);
if (rc) {
DP(NETIF_MSG_PROBE,
"nvram_tbl[%d] read data (rc %d)\n", i, rc);
goto test_nvram_exit;
}
crc = ether_crc_le(nvram_tbl[i].size, data);
if (crc != CRC32_RESIDUAL) {
DP(NETIF_MSG_PROBE,
"nvram_tbl[%d] crc value (0x%08x)\n", i, crc);
rc = -ENODEV;
goto test_nvram_exit;
}
}
test_nvram_exit:
return rc;
}
static int bnx2x_test_intr(struct bnx2x *bp)
{
struct mac_configuration_cmd *config = bnx2x_sp(bp, mac_config);
int i, rc;
if (!netif_running(bp->dev))
return -ENODEV;
config->hdr.length = 0;
if (CHIP_IS_E1(bp))
/* use last unicast entries */
config->hdr.offset = (BP_PORT(bp) ? 63 : 31);
else
config->hdr.offset = BP_FUNC(bp);
config->hdr.client_id = bp->fp->cl_id;
config->hdr.reserved1 = 0;
bp->set_mac_pending++;
smp_wmb();
rc = bnx2x_sp_post(bp, RAMROD_CMD_ID_ETH_SET_MAC, 0,
U64_HI(bnx2x_sp_mapping(bp, mac_config)),
U64_LO(bnx2x_sp_mapping(bp, mac_config)), 0);
if (rc == 0) {
for (i = 0; i < 10; i++) {
if (!bp->set_mac_pending)
break;
smp_rmb();
msleep_interruptible(10);
}
if (i == 10)
rc = -ENODEV;
}
return rc;
}
static void bnx2x_self_test(struct net_device *dev,
struct ethtool_test *etest, u64 *buf)
{
struct bnx2x *bp = netdev_priv(dev);
if (bp->recovery_state != BNX2X_RECOVERY_DONE) {
printk(KERN_ERR "Handling parity error recovery. Try again later\n");
etest->flags |= ETH_TEST_FL_FAILED;
return;
}
memset(buf, 0, sizeof(u64) * BNX2X_NUM_TESTS);
if (!netif_running(dev))
return;
/* offline tests are not supported in MF mode */
if (IS_E1HMF(bp))
etest->flags &= ~ETH_TEST_FL_OFFLINE;
if (etest->flags & ETH_TEST_FL_OFFLINE) {
int port = BP_PORT(bp);
u32 val;
u8 link_up;
/* save current value of input enable for TX port IF */
val = REG_RD(bp, NIG_REG_EGRESS_UMP0_IN_EN + port*4);
/* disable input for TX port IF */
REG_WR(bp, NIG_REG_EGRESS_UMP0_IN_EN + port*4, 0);
link_up = (bnx2x_link_test(bp) == 0);
bnx2x_nic_unload(bp, UNLOAD_NORMAL);
bnx2x_nic_load(bp, LOAD_DIAG);
/* wait until link state is restored */
bnx2x_wait_for_link(bp, link_up);
if (bnx2x_test_registers(bp) != 0) {
buf[0] = 1;
etest->flags |= ETH_TEST_FL_FAILED;
}
if (bnx2x_test_memory(bp) != 0) {
buf[1] = 1;
etest->flags |= ETH_TEST_FL_FAILED;
}
buf[2] = bnx2x_test_loopback(bp, link_up);
if (buf[2] != 0)
etest->flags |= ETH_TEST_FL_FAILED;
bnx2x_nic_unload(bp, UNLOAD_NORMAL);
/* restore input for TX port IF */
REG_WR(bp, NIG_REG_EGRESS_UMP0_IN_EN + port*4, val);
bnx2x_nic_load(bp, LOAD_NORMAL);
/* wait until link state is restored */
bnx2x_wait_for_link(bp, link_up);
}
if (bnx2x_test_nvram(bp) != 0) {
buf[3] = 1;
etest->flags |= ETH_TEST_FL_FAILED;
}
if (bnx2x_test_intr(bp) != 0) {
buf[4] = 1;
etest->flags |= ETH_TEST_FL_FAILED;
}
if (bp->port.pmf)
if (bnx2x_link_test(bp) != 0) {
buf[5] = 1;
etest->flags |= ETH_TEST_FL_FAILED;
}
#ifdef BNX2X_EXTRA_DEBUG
bnx2x_panic_dump(bp);
#endif
}
static const struct {
long offset;
int size;
u8 string[ETH_GSTRING_LEN];
} bnx2x_q_stats_arr[BNX2X_NUM_Q_STATS] = {
/* 1 */ { Q_STATS_OFFSET32(total_bytes_received_hi), 8, "[%d]: rx_bytes" },
{ Q_STATS_OFFSET32(error_bytes_received_hi),
8, "[%d]: rx_error_bytes" },
{ Q_STATS_OFFSET32(total_unicast_packets_received_hi),
8, "[%d]: rx_ucast_packets" },
{ Q_STATS_OFFSET32(total_multicast_packets_received_hi),
8, "[%d]: rx_mcast_packets" },
{ Q_STATS_OFFSET32(total_broadcast_packets_received_hi),
8, "[%d]: rx_bcast_packets" },
{ Q_STATS_OFFSET32(no_buff_discard_hi), 8, "[%d]: rx_discards" },
{ Q_STATS_OFFSET32(rx_err_discard_pkt),
4, "[%d]: rx_phy_ip_err_discards"},
{ Q_STATS_OFFSET32(rx_skb_alloc_failed),
4, "[%d]: rx_skb_alloc_discard" },
{ Q_STATS_OFFSET32(hw_csum_err), 4, "[%d]: rx_csum_offload_errors" },
/* 10 */{ Q_STATS_OFFSET32(total_bytes_transmitted_hi), 8, "[%d]: tx_bytes" },
{ Q_STATS_OFFSET32(total_unicast_packets_transmitted_hi),
8, "[%d]: tx_ucast_packets" },
{ Q_STATS_OFFSET32(total_multicast_packets_transmitted_hi),
8, "[%d]: tx_mcast_packets" },
{ Q_STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
8, "[%d]: tx_bcast_packets" }
};
static const struct {
long offset;
int size;
u32 flags;
#define STATS_FLAGS_PORT 1
#define STATS_FLAGS_FUNC 2
#define STATS_FLAGS_BOTH (STATS_FLAGS_FUNC | STATS_FLAGS_PORT)
u8 string[ETH_GSTRING_LEN];
} bnx2x_stats_arr[BNX2X_NUM_STATS] = {
/* 1 */ { STATS_OFFSET32(total_bytes_received_hi),
8, STATS_FLAGS_BOTH, "rx_bytes" },
{ STATS_OFFSET32(error_bytes_received_hi),
8, STATS_FLAGS_BOTH, "rx_error_bytes" },
{ STATS_OFFSET32(total_unicast_packets_received_hi),
8, STATS_FLAGS_BOTH, "rx_ucast_packets" },
{ STATS_OFFSET32(total_multicast_packets_received_hi),
8, STATS_FLAGS_BOTH, "rx_mcast_packets" },
{ STATS_OFFSET32(total_broadcast_packets_received_hi),
8, STATS_FLAGS_BOTH, "rx_bcast_packets" },
{ STATS_OFFSET32(rx_stat_dot3statsfcserrors_hi),
8, STATS_FLAGS_PORT, "rx_crc_errors" },
{ STATS_OFFSET32(rx_stat_dot3statsalignmenterrors_hi),
8, STATS_FLAGS_PORT, "rx_align_errors" },
{ STATS_OFFSET32(rx_stat_etherstatsundersizepkts_hi),
8, STATS_FLAGS_PORT, "rx_undersize_packets" },
{ STATS_OFFSET32(etherstatsoverrsizepkts_hi),
8, STATS_FLAGS_PORT, "rx_oversize_packets" },
/* 10 */{ STATS_OFFSET32(rx_stat_etherstatsfragments_hi),
8, STATS_FLAGS_PORT, "rx_fragments" },
{ STATS_OFFSET32(rx_stat_etherstatsjabbers_hi),
8, STATS_FLAGS_PORT, "rx_jabbers" },
{ STATS_OFFSET32(no_buff_discard_hi),
8, STATS_FLAGS_BOTH, "rx_discards" },
{ STATS_OFFSET32(mac_filter_discard),
4, STATS_FLAGS_PORT, "rx_filtered_packets" },
{ STATS_OFFSET32(xxoverflow_discard),
4, STATS_FLAGS_PORT, "rx_fw_discards" },
{ STATS_OFFSET32(brb_drop_hi),
8, STATS_FLAGS_PORT, "rx_brb_discard" },
{ STATS_OFFSET32(brb_truncate_hi),
8, STATS_FLAGS_PORT, "rx_brb_truncate" },
{ STATS_OFFSET32(pause_frames_received_hi),
8, STATS_FLAGS_PORT, "rx_pause_frames" },
{ STATS_OFFSET32(rx_stat_maccontrolframesreceived_hi),
8, STATS_FLAGS_PORT, "rx_mac_ctrl_frames" },
{ STATS_OFFSET32(nig_timer_max),
4, STATS_FLAGS_PORT, "rx_constant_pause_events" },
/* 20 */{ STATS_OFFSET32(rx_err_discard_pkt),
4, STATS_FLAGS_BOTH, "rx_phy_ip_err_discards"},
{ STATS_OFFSET32(rx_skb_alloc_failed),
4, STATS_FLAGS_BOTH, "rx_skb_alloc_discard" },
{ STATS_OFFSET32(hw_csum_err),
4, STATS_FLAGS_BOTH, "rx_csum_offload_errors" },
{ STATS_OFFSET32(total_bytes_transmitted_hi),
8, STATS_FLAGS_BOTH, "tx_bytes" },
{ STATS_OFFSET32(tx_stat_ifhcoutbadoctets_hi),
8, STATS_FLAGS_PORT, "tx_error_bytes" },
{ STATS_OFFSET32(total_unicast_packets_transmitted_hi),
8, STATS_FLAGS_BOTH, "tx_ucast_packets" },
{ STATS_OFFSET32(total_multicast_packets_transmitted_hi),
8, STATS_FLAGS_BOTH, "tx_mcast_packets" },
{ STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
8, STATS_FLAGS_BOTH, "tx_bcast_packets" },
{ STATS_OFFSET32(tx_stat_dot3statsinternalmactransmiterrors_hi),
8, STATS_FLAGS_PORT, "tx_mac_errors" },
{ STATS_OFFSET32(rx_stat_dot3statscarriersenseerrors_hi),
8, STATS_FLAGS_PORT, "tx_carrier_errors" },
/* 30 */{ STATS_OFFSET32(tx_stat_dot3statssinglecollisionframes_hi),
8, STATS_FLAGS_PORT, "tx_single_collisions" },
{ STATS_OFFSET32(tx_stat_dot3statsmultiplecollisionframes_hi),
8, STATS_FLAGS_PORT, "tx_multi_collisions" },
{ STATS_OFFSET32(tx_stat_dot3statsdeferredtransmissions_hi),
8, STATS_FLAGS_PORT, "tx_deferred" },
{ STATS_OFFSET32(tx_stat_dot3statsexcessivecollisions_hi),
8, STATS_FLAGS_PORT, "tx_excess_collisions" },
{ STATS_OFFSET32(tx_stat_dot3statslatecollisions_hi),
8, STATS_FLAGS_PORT, "tx_late_collisions" },
{ STATS_OFFSET32(tx_stat_etherstatscollisions_hi),
8, STATS_FLAGS_PORT, "tx_total_collisions" },
{ STATS_OFFSET32(tx_stat_etherstatspkts64octets_hi),
8, STATS_FLAGS_PORT, "tx_64_byte_packets" },
{ STATS_OFFSET32(tx_stat_etherstatspkts65octetsto127octets_hi),
8, STATS_FLAGS_PORT, "tx_65_to_127_byte_packets" },
{ STATS_OFFSET32(tx_stat_etherstatspkts128octetsto255octets_hi),
8, STATS_FLAGS_PORT, "tx_128_to_255_byte_packets" },
{ STATS_OFFSET32(tx_stat_etherstatspkts256octetsto511octets_hi),
8, STATS_FLAGS_PORT, "tx_256_to_511_byte_packets" },
/* 40 */{ STATS_OFFSET32(tx_stat_etherstatspkts512octetsto1023octets_hi),
8, STATS_FLAGS_PORT, "tx_512_to_1023_byte_packets" },
{ STATS_OFFSET32(etherstatspkts1024octetsto1522octets_hi),
8, STATS_FLAGS_PORT, "tx_1024_to_1522_byte_packets" },
{ STATS_OFFSET32(etherstatspktsover1522octets_hi),
8, STATS_FLAGS_PORT, "tx_1523_to_9022_byte_packets" },
{ STATS_OFFSET32(pause_frames_sent_hi),
8, STATS_FLAGS_PORT, "tx_pause_frames" }
};
#define IS_PORT_STAT(i) \
((bnx2x_stats_arr[i].flags & STATS_FLAGS_BOTH) == STATS_FLAGS_PORT)
#define IS_FUNC_STAT(i) (bnx2x_stats_arr[i].flags & STATS_FLAGS_FUNC)
#define IS_E1HMF_MODE_STAT(bp) \
(IS_E1HMF(bp) && !(bp->msg_enable & BNX2X_MSG_STATS))
static int bnx2x_get_sset_count(struct net_device *dev, int stringset)
{
struct bnx2x *bp = netdev_priv(dev);
int i, num_stats;
switch (stringset) {
case ETH_SS_STATS:
if (is_multi(bp)) {
num_stats = BNX2X_NUM_Q_STATS * bp->num_queues;
if (!IS_E1HMF_MODE_STAT(bp))
num_stats += BNX2X_NUM_STATS;
} else {
if (IS_E1HMF_MODE_STAT(bp)) {
num_stats = 0;
for (i = 0; i < BNX2X_NUM_STATS; i++)
if (IS_FUNC_STAT(i))
num_stats++;
} else
num_stats = BNX2X_NUM_STATS;
}
return num_stats;
case ETH_SS_TEST:
return BNX2X_NUM_TESTS;
default:
return -EINVAL;
}
}
static void bnx2x_get_strings(struct net_device *dev, u32 stringset, u8 *buf)
{
struct bnx2x *bp = netdev_priv(dev);
int i, j, k;
switch (stringset) {
case ETH_SS_STATS:
if (is_multi(bp)) {
k = 0;
for_each_queue(bp, i) {
for (j = 0; j < BNX2X_NUM_Q_STATS; j++)
sprintf(buf + (k + j)*ETH_GSTRING_LEN,
bnx2x_q_stats_arr[j].string, i);
k += BNX2X_NUM_Q_STATS;
}
if (IS_E1HMF_MODE_STAT(bp))
break;
for (j = 0; j < BNX2X_NUM_STATS; j++)
strcpy(buf + (k + j)*ETH_GSTRING_LEN,
bnx2x_stats_arr[j].string);
} else {
for (i = 0, j = 0; i < BNX2X_NUM_STATS; i++) {
if (IS_E1HMF_MODE_STAT(bp) && IS_PORT_STAT(i))
continue;
strcpy(buf + j*ETH_GSTRING_LEN,
bnx2x_stats_arr[i].string);
j++;
}
}
break;
case ETH_SS_TEST:
memcpy(buf, bnx2x_tests_str_arr, sizeof(bnx2x_tests_str_arr));
break;
}
}
static void bnx2x_get_ethtool_stats(struct net_device *dev,
struct ethtool_stats *stats, u64 *buf)
{
struct bnx2x *bp = netdev_priv(dev);
u32 *hw_stats, *offset;
int i, j, k;
if (is_multi(bp)) {
k = 0;
for_each_queue(bp, i) {
hw_stats = (u32 *)&bp->fp[i].eth_q_stats;
for (j = 0; j < BNX2X_NUM_Q_STATS; j++) {
if (bnx2x_q_stats_arr[j].size == 0) {
/* skip this counter */
buf[k + j] = 0;
continue;
}
offset = (hw_stats +
bnx2x_q_stats_arr[j].offset);
if (bnx2x_q_stats_arr[j].size == 4) {
/* 4-byte counter */
buf[k + j] = (u64) *offset;
continue;
}
/* 8-byte counter */
buf[k + j] = HILO_U64(*offset, *(offset + 1));
}
k += BNX2X_NUM_Q_STATS;
}
if (IS_E1HMF_MODE_STAT(bp))
return;
hw_stats = (u32 *)&bp->eth_stats;
for (j = 0; j < BNX2X_NUM_STATS; j++) {
if (bnx2x_stats_arr[j].size == 0) {
/* skip this counter */
buf[k + j] = 0;
continue;
}
offset = (hw_stats + bnx2x_stats_arr[j].offset);
if (bnx2x_stats_arr[j].size == 4) {
/* 4-byte counter */
buf[k + j] = (u64) *offset;
continue;
}
/* 8-byte counter */
buf[k + j] = HILO_U64(*offset, *(offset + 1));
}
} else {
hw_stats = (u32 *)&bp->eth_stats;
for (i = 0, j = 0; i < BNX2X_NUM_STATS; i++) {
if (IS_E1HMF_MODE_STAT(bp) && IS_PORT_STAT(i))
continue;
if (bnx2x_stats_arr[i].size == 0) {
/* skip this counter */
buf[j] = 0;
j++;
continue;
}
offset = (hw_stats + bnx2x_stats_arr[i].offset);
if (bnx2x_stats_arr[i].size == 4) {
/* 4-byte counter */
buf[j] = (u64) *offset;
j++;
continue;
}
/* 8-byte counter */
buf[j] = HILO_U64(*offset, *(offset + 1));
j++;
}
}
}
static int bnx2x_phys_id(struct net_device *dev, u32 data)
{
struct bnx2x *bp = netdev_priv(dev);
int i;
if (!netif_running(dev))
return 0;
if (!bp->port.pmf)
return 0;
if (data == 0)
data = 2;
for (i = 0; i < (data * 2); i++) {
if ((i % 2) == 0)
bnx2x_set_led(&bp->link_params, LED_MODE_OPER,
SPEED_1000);
else
bnx2x_set_led(&bp->link_params, LED_MODE_OFF, 0);
msleep_interruptible(500);
if (signal_pending(current))
break;
}
if (bp->link_vars.link_up)
bnx2x_set_led(&bp->link_params, LED_MODE_OPER,
bp->link_vars.line_speed);
return 0;
}
static const struct ethtool_ops bnx2x_ethtool_ops = {
.get_settings = bnx2x_get_settings,
.set_settings = bnx2x_set_settings,
.get_drvinfo = bnx2x_get_drvinfo,
.get_regs_len = bnx2x_get_regs_len,
.get_regs = bnx2x_get_regs,
.get_wol = bnx2x_get_wol,
.set_wol = bnx2x_set_wol,
.get_msglevel = bnx2x_get_msglevel,
.set_msglevel = bnx2x_set_msglevel,
.nway_reset = bnx2x_nway_reset,
.get_link = bnx2x_get_link,
.get_eeprom_len = bnx2x_get_eeprom_len,
.get_eeprom = bnx2x_get_eeprom,
.set_eeprom = bnx2x_set_eeprom,
.get_coalesce = bnx2x_get_coalesce,
.set_coalesce = bnx2x_set_coalesce,
.get_ringparam = bnx2x_get_ringparam,
.set_ringparam = bnx2x_set_ringparam,
.get_pauseparam = bnx2x_get_pauseparam,
.set_pauseparam = bnx2x_set_pauseparam,
.get_rx_csum = bnx2x_get_rx_csum,
.set_rx_csum = bnx2x_set_rx_csum,
.get_tx_csum = ethtool_op_get_tx_csum,
.set_tx_csum = ethtool_op_set_tx_hw_csum,
.set_flags = bnx2x_set_flags,
.get_flags = ethtool_op_get_flags,
.get_sg = ethtool_op_get_sg,
.set_sg = ethtool_op_set_sg,
.get_tso = ethtool_op_get_tso,
.set_tso = bnx2x_set_tso,
.self_test = bnx2x_self_test,
.get_sset_count = bnx2x_get_sset_count,
.get_strings = bnx2x_get_strings,
.phys_id = bnx2x_phys_id,
.get_ethtool_stats = bnx2x_get_ethtool_stats,
};
/* end of ethtool_ops */
/****************************************************************************
* General service functions
****************************************************************************/
static int bnx2x_set_power_state(struct bnx2x *bp, pci_power_t state)
{
u16 pmcsr;
pci_read_config_word(bp->pdev, bp->pm_cap + PCI_PM_CTRL, &pmcsr);
switch (state) {
case PCI_D0:
pci_write_config_word(bp->pdev, bp->pm_cap + PCI_PM_CTRL,
((pmcsr & ~PCI_PM_CTRL_STATE_MASK) |
PCI_PM_CTRL_PME_STATUS));
if (pmcsr & PCI_PM_CTRL_STATE_MASK)
/* delay required during transition out of D3hot */
msleep(20);
break;
case PCI_D3hot:
/* If there are other clients above don't
shut down the power */
if (atomic_read(&bp->pdev->enable_cnt) != 1)
return 0;
/* Don't shut down the power for emulation and FPGA */
if (CHIP_REV_IS_SLOW(bp))
return 0;
pmcsr &= ~PCI_PM_CTRL_STATE_MASK;
pmcsr |= 3;
if (bp->wol)
pmcsr |= PCI_PM_CTRL_PME_ENABLE;
pci_write_config_word(bp->pdev, bp->pm_cap + PCI_PM_CTRL,
pmcsr);
/* No more memory access after this point until
* device is brought back to D0.
*/
break;
default:
return -EINVAL;
}
return 0;
}
static inline int bnx2x_has_rx_work(struct bnx2x_fastpath *fp)
{
u16 rx_cons_sb;
/* Tell compiler that status block fields can change */
barrier();
rx_cons_sb = le16_to_cpu(*fp->rx_cons_sb);
if ((rx_cons_sb & MAX_RCQ_DESC_CNT) == MAX_RCQ_DESC_CNT)
rx_cons_sb++;
return (fp->rx_comp_cons != rx_cons_sb);
}
/*
* net_device service functions
*/
static int bnx2x_poll(struct napi_struct *napi, int budget)
{
int work_done = 0;
struct bnx2x_fastpath *fp = container_of(napi, struct bnx2x_fastpath,
napi);
struct bnx2x *bp = fp->bp;
while (1) {
#ifdef BNX2X_STOP_ON_ERROR
if (unlikely(bp->panic)) {
napi_complete(napi);
return 0;
}
#endif
if (bnx2x_has_tx_work(fp))
bnx2x_tx_int(fp);
if (bnx2x_has_rx_work(fp)) {
work_done += bnx2x_rx_int(fp, budget - work_done);
/* must not complete if we consumed full budget */
if (work_done >= budget)
break;
}
/* Fall out from the NAPI loop if needed */
if (!(bnx2x_has_rx_work(fp) || bnx2x_has_tx_work(fp))) {
bnx2x_update_fpsb_idx(fp);
/* bnx2x_has_rx_work() reads the status block, thus we need
* to ensure that status block indices have been actually read
* (bnx2x_update_fpsb_idx) prior to this check
* (bnx2x_has_rx_work) so that we won't write the "newer"
* value of the status block to IGU (if there was a DMA right
* after bnx2x_has_rx_work and if there is no rmb, the memory
* reading (bnx2x_update_fpsb_idx) may be postponed to right
* before bnx2x_ack_sb). In this case there will never be
* another interrupt until there is another update of the
* status block, while there is still unhandled work.
*/
rmb();
if (!(bnx2x_has_rx_work(fp) || bnx2x_has_tx_work(fp))) {
napi_complete(napi);
/* Re-enable interrupts */
bnx2x_ack_sb(bp, fp->sb_id, CSTORM_ID,
le16_to_cpu(fp->fp_c_idx),
IGU_INT_NOP, 1);
bnx2x_ack_sb(bp, fp->sb_id, USTORM_ID,
le16_to_cpu(fp->fp_u_idx),
IGU_INT_ENABLE, 1);
break;
}
}
}
return work_done;
}
/* we split the first BD into headers and data BDs
* to ease the pain of our fellow microcode engineers
* we use one mapping for both BDs
* So far this has only been observed to happen
* in Other Operating Systems(TM)
*/
static noinline u16 bnx2x_tx_split(struct bnx2x *bp,
struct bnx2x_fastpath *fp,
struct sw_tx_bd *tx_buf,
struct eth_tx_start_bd **tx_bd, u16 hlen,
u16 bd_prod, int nbd)
{
struct eth_tx_start_bd *h_tx_bd = *tx_bd;
struct eth_tx_bd *d_tx_bd;
dma_addr_t mapping;
int old_len = le16_to_cpu(h_tx_bd->nbytes);
/* first fix first BD */
h_tx_bd->nbd = cpu_to_le16(nbd);
h_tx_bd->nbytes = cpu_to_le16(hlen);
DP(NETIF_MSG_TX_QUEUED, "TSO split header size is %d "
"(%x:%x) nbd %d\n", h_tx_bd->nbytes, h_tx_bd->addr_hi,
h_tx_bd->addr_lo, h_tx_bd->nbd);
/* now get a new data BD
* (after the pbd) and fill it */
bd_prod = TX_BD(NEXT_TX_IDX(bd_prod));
d_tx_bd = &fp->tx_desc_ring[bd_prod].reg_bd;
mapping = HILO_U64(le32_to_cpu(h_tx_bd->addr_hi),
le32_to_cpu(h_tx_bd->addr_lo)) + hlen;
d_tx_bd->addr_hi = cpu_to_le32(U64_HI(mapping));
d_tx_bd->addr_lo = cpu_to_le32(U64_LO(mapping));
d_tx_bd->nbytes = cpu_to_le16(old_len - hlen);
/* this marks the BD as one that has no individual mapping */
tx_buf->flags |= BNX2X_TSO_SPLIT_BD;
DP(NETIF_MSG_TX_QUEUED,
"TSO split data size is %d (%x:%x)\n",
d_tx_bd->nbytes, d_tx_bd->addr_hi, d_tx_bd->addr_lo);
/* update tx_bd */
*tx_bd = (struct eth_tx_start_bd *)d_tx_bd;
return bd_prod;
}
static inline u16 bnx2x_csum_fix(unsigned char *t_header, u16 csum, s8 fix)
{
if (fix > 0)
csum = (u16) ~csum_fold(csum_sub(csum,
csum_partial(t_header - fix, fix, 0)));
else if (fix < 0)
csum = (u16) ~csum_fold(csum_add(csum,
csum_partial(t_header, -fix, 0)));
return swab16(csum);
}
static inline u32 bnx2x_xmit_type(struct bnx2x *bp, struct sk_buff *skb)
{
u32 rc;
if (skb->ip_summed != CHECKSUM_PARTIAL)
rc = XMIT_PLAIN;
else {
if (skb->protocol == htons(ETH_P_IPV6)) {
rc = XMIT_CSUM_V6;
if (ipv6_hdr(skb)->nexthdr == IPPROTO_TCP)
rc |= XMIT_CSUM_TCP;
} else {
rc = XMIT_CSUM_V4;
if (ip_hdr(skb)->protocol == IPPROTO_TCP)
rc |= XMIT_CSUM_TCP;
}
}
if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4)
rc |= (XMIT_GSO_V4 | XMIT_CSUM_V4 | XMIT_CSUM_TCP);
else if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV6)
rc |= (XMIT_GSO_V6 | XMIT_CSUM_TCP | XMIT_CSUM_V6);
return rc;
}
#if (MAX_SKB_FRAGS >= MAX_FETCH_BD - 3)
/* check if packet requires linearization (packet is too fragmented)
no need to check fragmentation if page size > 8K (there will be no
violation to FW restrictions) */
static int bnx2x_pkt_req_lin(struct bnx2x *bp, struct sk_buff *skb,
u32 xmit_type)
{
int to_copy = 0;
int hlen = 0;
int first_bd_sz = 0;
/* 3 = 1 (for linear data BD) + 2 (for PBD and last BD) */
if (skb_shinfo(skb)->nr_frags >= (MAX_FETCH_BD - 3)) {
if (xmit_type & XMIT_GSO) {
unsigned short lso_mss = skb_shinfo(skb)->gso_size;
/* Check if LSO packet needs to be copied:
3 = 1 (for headers BD) + 2 (for PBD and last BD) */
int wnd_size = MAX_FETCH_BD - 3;
/* Number of windows to check */
int num_wnds = skb_shinfo(skb)->nr_frags - wnd_size;
int wnd_idx = 0;
int frag_idx = 0;
u32 wnd_sum = 0;
/* Headers length */
hlen = (int)(skb_transport_header(skb) - skb->data) +
tcp_hdrlen(skb);
/* Amount of data (w/o headers) on linear part of SKB*/
first_bd_sz = skb_headlen(skb) - hlen;
wnd_sum = first_bd_sz;
/* Calculate the first sum - it's special */
for (frag_idx = 0; frag_idx < wnd_size - 1; frag_idx++)
wnd_sum +=
skb_shinfo(skb)->frags[frag_idx].size;
/* If there was data on linear skb data - check it */
if (first_bd_sz > 0) {
if (unlikely(wnd_sum < lso_mss)) {
to_copy = 1;
goto exit_lbl;
}
wnd_sum -= first_bd_sz;
}
/* Others are easier: run through the frag list and
check all windows */
for (wnd_idx = 0; wnd_idx <= num_wnds; wnd_idx++) {
wnd_sum +=
skb_shinfo(skb)->frags[wnd_idx + wnd_size - 1].size;
if (unlikely(wnd_sum < lso_mss)) {
to_copy = 1;
break;
}
wnd_sum -=
skb_shinfo(skb)->frags[wnd_idx].size;
}
} else {
/* in non-LSO too fragmented packet should always
be linearized */
to_copy = 1;
}
}
exit_lbl:
if (unlikely(to_copy))
DP(NETIF_MSG_TX_QUEUED,
"Linearization IS REQUIRED for %s packet. "
"num_frags %d hlen %d first_bd_sz %d\n",
(xmit_type & XMIT_GSO) ? "LSO" : "non-LSO",
skb_shinfo(skb)->nr_frags, hlen, first_bd_sz);
return to_copy;
}
#endif
/* called with netif_tx_lock
* bnx2x_tx_int() runs without netif_tx_lock unless it needs to call
* netif_wake_queue()
*/
static netdev_tx_t bnx2x_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct bnx2x *bp = netdev_priv(dev);
struct bnx2x_fastpath *fp;
struct netdev_queue *txq;
struct sw_tx_bd *tx_buf;
struct eth_tx_start_bd *tx_start_bd;
struct eth_tx_bd *tx_data_bd, *total_pkt_bd = NULL;
struct eth_tx_parse_bd *pbd = NULL;
u16 pkt_prod, bd_prod;
int nbd, fp_index;
dma_addr_t mapping;
u32 xmit_type = bnx2x_xmit_type(bp, skb);
int i;
u8 hlen = 0;
__le16 pkt_size = 0;
struct ethhdr *eth;
u8 mac_type = UNICAST_ADDRESS;
#ifdef BNX2X_STOP_ON_ERROR
if (unlikely(bp->panic))
return NETDEV_TX_BUSY;
#endif
fp_index = skb_get_queue_mapping(skb);
txq = netdev_get_tx_queue(dev, fp_index);
fp = &bp->fp[fp_index];
if (unlikely(bnx2x_tx_avail(fp) < (skb_shinfo(skb)->nr_frags + 3))) {
fp->eth_q_stats.driver_xoff++;
netif_tx_stop_queue(txq);
BNX2X_ERR("BUG! Tx ring full when queue awake!\n");
return NETDEV_TX_BUSY;
}
DP(NETIF_MSG_TX_QUEUED, "SKB: summed %x protocol %x protocol(%x,%x)"
" gso type %x xmit_type %x\n",
skb->ip_summed, skb->protocol, ipv6_hdr(skb)->nexthdr,
ip_hdr(skb)->protocol, skb_shinfo(skb)->gso_type, xmit_type);
eth = (struct ethhdr *)skb->data;
/* set flag according to packet type (UNICAST_ADDRESS is default)*/
if (unlikely(is_multicast_ether_addr(eth->h_dest))) {
if (is_broadcast_ether_addr(eth->h_dest))
mac_type = BROADCAST_ADDRESS;
else
mac_type = MULTICAST_ADDRESS;
}
#if (MAX_SKB_FRAGS >= MAX_FETCH_BD - 3)
/* First, check if we need to linearize the skb (due to FW
restrictions). No need to check fragmentation if page size > 8K
(there will be no violation to FW restrictions) */
if (bnx2x_pkt_req_lin(bp, skb, xmit_type)) {
/* Statistics of linearization */
bp->lin_cnt++;
if (skb_linearize(skb) != 0) {
DP(NETIF_MSG_TX_QUEUED, "SKB linearization failed - "
"silently dropping this SKB\n");
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
}
#endif
/*
Please read carefully. First we use one BD which we mark as start,
then we have a parsing info BD (used for TSO or xsum),
and only then we have the rest of the TSO BDs.
(don't forget to mark the last one as last,
and to unmap only AFTER you write to the BD ...)
And above all, all pdb sizes are in words - NOT DWORDS!
*/
pkt_prod = fp->tx_pkt_prod++;
bd_prod = TX_BD(fp->tx_bd_prod);
/* get a tx_buf and first BD */
tx_buf = &fp->tx_buf_ring[TX_BD(pkt_prod)];
tx_start_bd = &fp->tx_desc_ring[bd_prod].start_bd;
tx_start_bd->bd_flags.as_bitfield = ETH_TX_BD_FLAGS_START_BD;
tx_start_bd->general_data = (mac_type <<
ETH_TX_START_BD_ETH_ADDR_TYPE_SHIFT);
/* header nbd */
tx_start_bd->general_data |= (1 << ETH_TX_START_BD_HDR_NBDS_SHIFT);
/* remember the first BD of the packet */
tx_buf->first_bd = fp->tx_bd_prod;
tx_buf->skb = skb;
tx_buf->flags = 0;
DP(NETIF_MSG_TX_QUEUED,
"sending pkt %u @%p next_idx %u bd %u @%p\n",
pkt_prod, tx_buf, fp->tx_pkt_prod, bd_prod, tx_start_bd);
#ifdef BCM_VLAN
if ((bp->vlgrp != NULL) && vlan_tx_tag_present(skb) &&
(bp->flags & HW_VLAN_TX_FLAG)) {
tx_start_bd->vlan = cpu_to_le16(vlan_tx_tag_get(skb));
tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_VLAN_TAG;
} else
#endif
tx_start_bd->vlan = cpu_to_le16(pkt_prod);
/* turn on parsing and get a BD */
bd_prod = TX_BD(NEXT_TX_IDX(bd_prod));
pbd = &fp->tx_desc_ring[bd_prod].parse_bd;
memset(pbd, 0, sizeof(struct eth_tx_parse_bd));
if (xmit_type & XMIT_CSUM) {
hlen = (skb_network_header(skb) - skb->data) / 2;
/* for now NS flag is not used in Linux */
pbd->global_data =
(hlen | ((skb->protocol == cpu_to_be16(ETH_P_8021Q)) <<
ETH_TX_PARSE_BD_LLC_SNAP_EN_SHIFT));
pbd->ip_hlen = (skb_transport_header(skb) -
skb_network_header(skb)) / 2;
hlen += pbd->ip_hlen + tcp_hdrlen(skb) / 2;
pbd->total_hlen = cpu_to_le16(hlen);
hlen = hlen*2;
tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_L4_CSUM;
if (xmit_type & XMIT_CSUM_V4)
tx_start_bd->bd_flags.as_bitfield |=
ETH_TX_BD_FLAGS_IP_CSUM;
else
tx_start_bd->bd_flags.as_bitfield |=
ETH_TX_BD_FLAGS_IPV6;
if (xmit_type & XMIT_CSUM_TCP) {
pbd->tcp_pseudo_csum = swab16(tcp_hdr(skb)->check);
} else {
s8 fix = SKB_CS_OFF(skb); /* signed! */
pbd->global_data |= ETH_TX_PARSE_BD_UDP_CS_FLG;
DP(NETIF_MSG_TX_QUEUED,
"hlen %d fix %d csum before fix %x\n",
le16_to_cpu(pbd->total_hlen), fix, SKB_CS(skb));
/* HW bug: fixup the CSUM */
pbd->tcp_pseudo_csum =
bnx2x_csum_fix(skb_transport_header(skb),
SKB_CS(skb), fix);
DP(NETIF_MSG_TX_QUEUED, "csum after fix %x\n",
pbd->tcp_pseudo_csum);
}
}
mapping = dma_map_single(&bp->pdev->dev, skb->data,
skb_headlen(skb), DMA_TO_DEVICE);
tx_start_bd->addr_hi = cpu_to_le32(U64_HI(mapping));
tx_start_bd->addr_lo = cpu_to_le32(U64_LO(mapping));
nbd = skb_shinfo(skb)->nr_frags + 2; /* start_bd + pbd + frags */
tx_start_bd->nbd = cpu_to_le16(nbd);
tx_start_bd->nbytes = cpu_to_le16(skb_headlen(skb));
pkt_size = tx_start_bd->nbytes;
DP(NETIF_MSG_TX_QUEUED, "first bd @%p addr (%x:%x) nbd %d"
" nbytes %d flags %x vlan %x\n",
tx_start_bd, tx_start_bd->addr_hi, tx_start_bd->addr_lo,
le16_to_cpu(tx_start_bd->nbd), le16_to_cpu(tx_start_bd->nbytes),
tx_start_bd->bd_flags.as_bitfield, le16_to_cpu(tx_start_bd->vlan));
if (xmit_type & XMIT_GSO) {
DP(NETIF_MSG_TX_QUEUED,
"TSO packet len %d hlen %d total len %d tso size %d\n",
skb->len, hlen, skb_headlen(skb),
skb_shinfo(skb)->gso_size);
tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_SW_LSO;
if (unlikely(skb_headlen(skb) > hlen))
bd_prod = bnx2x_tx_split(bp, fp, tx_buf, &tx_start_bd,
hlen, bd_prod, ++nbd);
pbd->lso_mss = cpu_to_le16(skb_shinfo(skb)->gso_size);
pbd->tcp_send_seq = swab32(tcp_hdr(skb)->seq);
pbd->tcp_flags = pbd_tcp_flags(skb);
if (xmit_type & XMIT_GSO_V4) {
pbd->ip_id = swab16(ip_hdr(skb)->id);
pbd->tcp_pseudo_csum =
swab16(~csum_tcpudp_magic(ip_hdr(skb)->saddr,
ip_hdr(skb)->daddr,
0, IPPROTO_TCP, 0));
} else
pbd->tcp_pseudo_csum =
swab16(~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
&ipv6_hdr(skb)->daddr,
0, IPPROTO_TCP, 0));
pbd->global_data |= ETH_TX_PARSE_BD_PSEUDO_CS_WITHOUT_LEN;
}
tx_data_bd = (struct eth_tx_bd *)tx_start_bd;
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
bd_prod = TX_BD(NEXT_TX_IDX(bd_prod));
tx_data_bd = &fp->tx_desc_ring[bd_prod].reg_bd;
if (total_pkt_bd == NULL)
total_pkt_bd = &fp->tx_desc_ring[bd_prod].reg_bd;
mapping = dma_map_page(&bp->pdev->dev, frag->page,
frag->page_offset,
frag->size, DMA_TO_DEVICE);
tx_data_bd->addr_hi = cpu_to_le32(U64_HI(mapping));
tx_data_bd->addr_lo = cpu_to_le32(U64_LO(mapping));
tx_data_bd->nbytes = cpu_to_le16(frag->size);
le16_add_cpu(&pkt_size, frag->size);
DP(NETIF_MSG_TX_QUEUED,
"frag %d bd @%p addr (%x:%x) nbytes %d\n",
i, tx_data_bd, tx_data_bd->addr_hi, tx_data_bd->addr_lo,
le16_to_cpu(tx_data_bd->nbytes));
}
DP(NETIF_MSG_TX_QUEUED, "last bd @%p\n", tx_data_bd);
bd_prod = TX_BD(NEXT_TX_IDX(bd_prod));
/* now send a tx doorbell, counting the next BD
* if the packet contains or ends with it
*/
if (TX_BD_POFF(bd_prod) < nbd)
nbd++;
if (total_pkt_bd != NULL)
total_pkt_bd->total_pkt_bytes = pkt_size;
if (pbd)
DP(NETIF_MSG_TX_QUEUED,
"PBD @%p ip_data %x ip_hlen %u ip_id %u lso_mss %u"
" tcp_flags %x xsum %x seq %u hlen %u\n",
pbd, pbd->global_data, pbd->ip_hlen, pbd->ip_id,
pbd->lso_mss, pbd->tcp_flags, pbd->tcp_pseudo_csum,
pbd->tcp_send_seq, le16_to_cpu(pbd->total_hlen));
DP(NETIF_MSG_TX_QUEUED, "doorbell: nbd %d bd %u\n", nbd, bd_prod);
/*
* Make sure that the BD data is updated before updating the producer
* since FW might read the BD right after the producer is updated.
* This is only applicable for weak-ordered memory model archs such
* as IA-64. The following barrier is also mandatory since FW will
* assumes packets must have BDs.
*/
wmb();
fp->tx_db.data.prod += nbd;
barrier();
DOORBELL(bp, fp->index, fp->tx_db.raw);
mmiowb();
fp->tx_bd_prod += nbd;
if (unlikely(bnx2x_tx_avail(fp) < MAX_SKB_FRAGS + 3)) {
netif_tx_stop_queue(txq);
/* paired memory barrier is in bnx2x_tx_int(), we have to keep
* ordering of set_bit() in netif_tx_stop_queue() and read of
* fp->bd_tx_cons */
smp_mb();
fp->eth_q_stats.driver_xoff++;
if (bnx2x_tx_avail(fp) >= MAX_SKB_FRAGS + 3)
netif_tx_wake_queue(txq);
}
fp->tx_pkt++;
return NETDEV_TX_OK;
}
/* called with rtnl_lock */
static int bnx2x_open(struct net_device *dev)
{
struct bnx2x *bp = netdev_priv(dev);
netif_carrier_off(dev);
bnx2x_set_power_state(bp, PCI_D0);
if (!bnx2x_reset_is_done(bp)) {
do {
/* Reset MCP mail box sequence if there is on going
* recovery
*/
bp->fw_seq = 0;
/* If it's the first function to load and reset done
* is still not cleared it may mean that. We don't
* check the attention state here because it may have
* already been cleared by a "common" reset but we
* shell proceed with "process kill" anyway.
*/
if ((bnx2x_get_load_cnt(bp) == 0) &&
bnx2x_trylock_hw_lock(bp,
HW_LOCK_RESOURCE_RESERVED_08) &&
(!bnx2x_leader_reset(bp))) {
DP(NETIF_MSG_HW, "Recovered in open\n");
break;
}
bnx2x_set_power_state(bp, PCI_D3hot);
printk(KERN_ERR"%s: Recovery flow hasn't been properly"
" completed yet. Try again later. If u still see this"
" message after a few retries then power cycle is"
" required.\n", bp->dev->name);
return -EAGAIN;
} while (0);
}
bp->recovery_state = BNX2X_RECOVERY_DONE;
return bnx2x_nic_load(bp, LOAD_OPEN);
}
/* called with rtnl_lock */
static int bnx2x_close(struct net_device *dev)
{
struct bnx2x *bp = netdev_priv(dev);
/* Unload the driver, release IRQs */
bnx2x_nic_unload(bp, UNLOAD_CLOSE);
bnx2x_set_power_state(bp, PCI_D3hot);
return 0;
}
/* called with netif_tx_lock from dev_mcast.c */
static void bnx2x_set_rx_mode(struct net_device *dev)
{
struct bnx2x *bp = netdev_priv(dev);
u32 rx_mode = BNX2X_RX_MODE_NORMAL;
int port = BP_PORT(bp);
if (bp->state != BNX2X_STATE_OPEN) {
DP(NETIF_MSG_IFUP, "state is %x, returning\n", bp->state);
return;
}
DP(NETIF_MSG_IFUP, "dev->flags = %x\n", dev->flags);
if (dev->flags & IFF_PROMISC)
rx_mode = BNX2X_RX_MODE_PROMISC;
else if ((dev->flags & IFF_ALLMULTI) ||
((netdev_mc_count(dev) > BNX2X_MAX_MULTICAST) &&
CHIP_IS_E1(bp)))
rx_mode = BNX2X_RX_MODE_ALLMULTI;
else { /* some multicasts */
if (CHIP_IS_E1(bp)) {
int i, old, offset;
struct netdev_hw_addr *ha;
struct mac_configuration_cmd *config =
bnx2x_sp(bp, mcast_config);
i = 0;
netdev_for_each_mc_addr(ha, dev) {
config->config_table[i].
cam_entry.msb_mac_addr =
swab16(*(u16 *)&ha->addr[0]);
config->config_table[i].
cam_entry.middle_mac_addr =
swab16(*(u16 *)&ha->addr[2]);
config->config_table[i].
cam_entry.lsb_mac_addr =
swab16(*(u16 *)&ha->addr[4]);
config->config_table[i].cam_entry.flags =
cpu_to_le16(port);
config->config_table[i].
target_table_entry.flags = 0;
config->config_table[i].target_table_entry.
clients_bit_vector =
cpu_to_le32(1 << BP_L_ID(bp));
config->config_table[i].
target_table_entry.vlan_id = 0;
DP(NETIF_MSG_IFUP,
"setting MCAST[%d] (%04x:%04x:%04x)\n", i,
config->config_table[i].
cam_entry.msb_mac_addr,
config->config_table[i].
cam_entry.middle_mac_addr,
config->config_table[i].
cam_entry.lsb_mac_addr);
i++;
}
old = config->hdr.length;
if (old > i) {
for (; i < old; i++) {
if (CAM_IS_INVALID(config->
config_table[i])) {
/* already invalidated */
break;
}
/* invalidate */
CAM_INVALIDATE(config->
config_table[i]);
}
}
if (CHIP_REV_IS_SLOW(bp))
offset = BNX2X_MAX_EMUL_MULTI*(1 + port);
else
offset = BNX2X_MAX_MULTICAST*(1 + port);
config->hdr.length = i;
config->hdr.offset = offset;
config->hdr.client_id = bp->fp->cl_id;
config->hdr.reserved1 = 0;
bp->set_mac_pending++;
smp_wmb();
bnx2x_sp_post(bp, RAMROD_CMD_ID_ETH_SET_MAC, 0,
U64_HI(bnx2x_sp_mapping(bp, mcast_config)),
U64_LO(bnx2x_sp_mapping(bp, mcast_config)),
0);
} else { /* E1H */
/* Accept one or more multicasts */
struct netdev_hw_addr *ha;
u32 mc_filter[MC_HASH_SIZE];
u32 crc, bit, regidx;
int i;
memset(mc_filter, 0, 4 * MC_HASH_SIZE);
netdev_for_each_mc_addr(ha, dev) {
DP(NETIF_MSG_IFUP, "Adding mcast MAC: %pM\n",
ha->addr);
crc = crc32c_le(0, ha->addr, ETH_ALEN);
bit = (crc >> 24) & 0xff;
regidx = bit >> 5;
bit &= 0x1f;
mc_filter[regidx] |= (1 << bit);
}
for (i = 0; i < MC_HASH_SIZE; i++)
REG_WR(bp, MC_HASH_OFFSET(bp, i),
mc_filter[i]);
}
}
bp->rx_mode = rx_mode;
bnx2x_set_storm_rx_mode(bp);
}
/* called with rtnl_lock */
static int bnx2x_change_mac_addr(struct net_device *dev, void *p)
{
struct sockaddr *addr = p;
struct bnx2x *bp = netdev_priv(dev);
if (!is_valid_ether_addr((u8 *)(addr->sa_data)))
return -EINVAL;
memcpy(dev->dev_addr, addr->sa_data, dev->addr_len);
if (netif_running(dev)) {
if (CHIP_IS_E1(bp))
bnx2x_set_eth_mac_addr_e1(bp, 1);
else
bnx2x_set_eth_mac_addr_e1h(bp, 1);
}
return 0;
}
/* called with rtnl_lock */
static int bnx2x_mdio_read(struct net_device *netdev, int prtad,
int devad, u16 addr)
{
struct bnx2x *bp = netdev_priv(netdev);
u16 value;
int rc;
u32 phy_type = XGXS_EXT_PHY_TYPE(bp->link_params.ext_phy_config);
DP(NETIF_MSG_LINK, "mdio_read: prtad 0x%x, devad 0x%x, addr 0x%x\n",
prtad, devad, addr);
if (prtad != bp->mdio.prtad) {
DP(NETIF_MSG_LINK, "prtad missmatch (cmd:0x%x != bp:0x%x)\n",
prtad, bp->mdio.prtad);
return -EINVAL;
}
/* The HW expects different devad if CL22 is used */
devad = (devad == MDIO_DEVAD_NONE) ? DEFAULT_PHY_DEV_ADDR : devad;
bnx2x_acquire_phy_lock(bp);
rc = bnx2x_cl45_read(bp, BP_PORT(bp), phy_type, prtad,
devad, addr, &value);
bnx2x_release_phy_lock(bp);
DP(NETIF_MSG_LINK, "mdio_read_val 0x%x rc = 0x%x\n", value, rc);
if (!rc)
rc = value;
return rc;
}
/* called with rtnl_lock */
static int bnx2x_mdio_write(struct net_device *netdev, int prtad, int devad,
u16 addr, u16 value)
{
struct bnx2x *bp = netdev_priv(netdev);
u32 ext_phy_type = XGXS_EXT_PHY_TYPE(bp->link_params.ext_phy_config);
int rc;
DP(NETIF_MSG_LINK, "mdio_write: prtad 0x%x, devad 0x%x, addr 0x%x,"
" value 0x%x\n", prtad, devad, addr, value);
if (prtad != bp->mdio.prtad) {
DP(NETIF_MSG_LINK, "prtad missmatch (cmd:0x%x != bp:0x%x)\n",
prtad, bp->mdio.prtad);
return -EINVAL;
}
/* The HW expects different devad if CL22 is used */
devad = (devad == MDIO_DEVAD_NONE) ? DEFAULT_PHY_DEV_ADDR : devad;
bnx2x_acquire_phy_lock(bp);
rc = bnx2x_cl45_write(bp, BP_PORT(bp), ext_phy_type, prtad,
devad, addr, value);
bnx2x_release_phy_lock(bp);
return rc;
}
/* called with rtnl_lock */
static int bnx2x_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
struct bnx2x *bp = netdev_priv(dev);
struct mii_ioctl_data *mdio = if_mii(ifr);
DP(NETIF_MSG_LINK, "ioctl: phy id 0x%x, reg 0x%x, val_in 0x%x\n",
mdio->phy_id, mdio->reg_num, mdio->val_in);
if (!netif_running(dev))
return -EAGAIN;
return mdio_mii_ioctl(&bp->mdio, mdio, cmd);
}
/* called with rtnl_lock */
static int bnx2x_change_mtu(struct net_device *dev, int new_mtu)
{
struct bnx2x *bp = netdev_priv(dev);
int rc = 0;
if (bp->recovery_state != BNX2X_RECOVERY_DONE) {
printk(KERN_ERR "Handling parity error recovery. Try again later\n");
return -EAGAIN;
}
if ((new_mtu > ETH_MAX_JUMBO_PACKET_SIZE) ||
((new_mtu + ETH_HLEN) < ETH_MIN_PACKET_SIZE))
return -EINVAL;
/* This does not race with packet allocation
* because the actual alloc size is
* only updated as part of load
*/
dev->mtu = new_mtu;
if (netif_running(dev)) {
bnx2x_nic_unload(bp, UNLOAD_NORMAL);
rc = bnx2x_nic_load(bp, LOAD_NORMAL);
}
return rc;
}
static void bnx2x_tx_timeout(struct net_device *dev)
{
struct bnx2x *bp = netdev_priv(dev);
#ifdef BNX2X_STOP_ON_ERROR
if (!bp->panic)
bnx2x_panic();
#endif
/* This allows the netif to be shutdown gracefully before resetting */
schedule_delayed_work(&bp->reset_task, 0);
}
#ifdef BCM_VLAN
/* called with rtnl_lock */
static void bnx2x_vlan_rx_register(struct net_device *dev,
struct vlan_group *vlgrp)
{
struct bnx2x *bp = netdev_priv(dev);
bp->vlgrp = vlgrp;
/* Set flags according to the required capabilities */
bp->flags &= ~(HW_VLAN_RX_FLAG | HW_VLAN_TX_FLAG);
if (dev->features & NETIF_F_HW_VLAN_TX)
bp->flags |= HW_VLAN_TX_FLAG;
if (dev->features & NETIF_F_HW_VLAN_RX)
bp->flags |= HW_VLAN_RX_FLAG;
if (netif_running(dev))
bnx2x_set_client_config(bp);
}
#endif
#ifdef CONFIG_NET_POLL_CONTROLLER
static void poll_bnx2x(struct net_device *dev)
{
struct bnx2x *bp = netdev_priv(dev);
disable_irq(bp->pdev->irq);
bnx2x_interrupt(bp->pdev->irq, dev);
enable_irq(bp->pdev->irq);
}
#endif
static const struct net_device_ops bnx2x_netdev_ops = {
.ndo_open = bnx2x_open,
.ndo_stop = bnx2x_close,
.ndo_start_xmit = bnx2x_start_xmit,
.ndo_set_multicast_list = bnx2x_set_rx_mode,
.ndo_set_mac_address = bnx2x_change_mac_addr,
.ndo_validate_addr = eth_validate_addr,
.ndo_do_ioctl = bnx2x_ioctl,
.ndo_change_mtu = bnx2x_change_mtu,
.ndo_tx_timeout = bnx2x_tx_timeout,
#ifdef BCM_VLAN
.ndo_vlan_rx_register = bnx2x_vlan_rx_register,
#endif
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = poll_bnx2x,
#endif
};
static int __devinit bnx2x_init_dev(struct pci_dev *pdev,
struct net_device *dev)
{
struct bnx2x *bp;
int rc;
SET_NETDEV_DEV(dev, &pdev->dev);
bp = netdev_priv(dev);
bp->dev = dev;
bp->pdev = pdev;
bp->flags = 0;
bp->func = PCI_FUNC(pdev->devfn);
rc = pci_enable_device(pdev);
if (rc) {
dev_err(&bp->pdev->dev,
"Cannot enable PCI device, aborting\n");
goto err_out;
}
if (!(pci_resource_flags(pdev, 0) & IORESOURCE_MEM)) {
dev_err(&bp->pdev->dev,
"Cannot find PCI device base address, aborting\n");
rc = -ENODEV;
goto err_out_disable;
}
if (!(pci_resource_flags(pdev, 2) & IORESOURCE_MEM)) {
dev_err(&bp->pdev->dev, "Cannot find second PCI device"
" base address, aborting\n");
rc = -ENODEV;
goto err_out_disable;
}
if (atomic_read(&pdev->enable_cnt) == 1) {
rc = pci_request_regions(pdev, DRV_MODULE_NAME);
if (rc) {
dev_err(&bp->pdev->dev,
"Cannot obtain PCI resources, aborting\n");
goto err_out_disable;
}
pci_set_master(pdev);
pci_save_state(pdev);
}
bp->pm_cap = pci_find_capability(pdev, PCI_CAP_ID_PM);
if (bp->pm_cap == 0) {
dev_err(&bp->pdev->dev,
"Cannot find power management capability, aborting\n");
rc = -EIO;
goto err_out_release;
}
bp->pcie_cap = pci_find_capability(pdev, PCI_CAP_ID_EXP);
if (bp->pcie_cap == 0) {
dev_err(&bp->pdev->dev,
"Cannot find PCI Express capability, aborting\n");
rc = -EIO;
goto err_out_release;
}
if (dma_set_mask(&pdev->dev, DMA_BIT_MASK(64)) == 0) {
bp->flags |= USING_DAC_FLAG;
if (dma_set_coherent_mask(&pdev->dev, DMA_BIT_MASK(64)) != 0) {
dev_err(&bp->pdev->dev, "dma_set_coherent_mask"
" failed, aborting\n");
rc = -EIO;
goto err_out_release;
}
} else if (dma_set_mask(&pdev->dev, DMA_BIT_MASK(32)) != 0) {
dev_err(&bp->pdev->dev,
"System does not support DMA, aborting\n");
rc = -EIO;
goto err_out_release;
}
dev->mem_start = pci_resource_start(pdev, 0);
dev->base_addr = dev->mem_start;
dev->mem_end = pci_resource_end(pdev, 0);
dev->irq = pdev->irq;
bp->regview = pci_ioremap_bar(pdev, 0);
if (!bp->regview) {
dev_err(&bp->pdev->dev,
"Cannot map register space, aborting\n");
rc = -ENOMEM;
goto err_out_release;
}
bp->doorbells = ioremap_nocache(pci_resource_start(pdev, 2),
min_t(u64, BNX2X_DB_SIZE,
pci_resource_len(pdev, 2)));
if (!bp->doorbells) {
dev_err(&bp->pdev->dev,
"Cannot map doorbell space, aborting\n");
rc = -ENOMEM;
goto err_out_unmap;
}
bnx2x_set_power_state(bp, PCI_D0);
/* clean indirect addresses */
pci_write_config_dword(bp->pdev, PCICFG_GRC_ADDRESS,
PCICFG_VENDOR_ID_OFFSET);
REG_WR(bp, PXP2_REG_PGL_ADDR_88_F0 + BP_PORT(bp)*16, 0);
REG_WR(bp, PXP2_REG_PGL_ADDR_8C_F0 + BP_PORT(bp)*16, 0);
REG_WR(bp, PXP2_REG_PGL_ADDR_90_F0 + BP_PORT(bp)*16, 0);
REG_WR(bp, PXP2_REG_PGL_ADDR_94_F0 + BP_PORT(bp)*16, 0);
/* Reset the load counter */
bnx2x_clear_load_cnt(bp);
dev->watchdog_timeo = TX_TIMEOUT;
dev->netdev_ops = &bnx2x_netdev_ops;
dev->ethtool_ops = &bnx2x_ethtool_ops;
dev->features |= NETIF_F_SG;
dev->features |= NETIF_F_HW_CSUM;
if (bp->flags & USING_DAC_FLAG)
dev->features |= NETIF_F_HIGHDMA;
dev->features |= (NETIF_F_TSO | NETIF_F_TSO_ECN);
dev->features |= NETIF_F_TSO6;
#ifdef BCM_VLAN
dev->features |= (NETIF_F_HW_VLAN_TX | NETIF_F_HW_VLAN_RX);
bp->flags |= (HW_VLAN_RX_FLAG | HW_VLAN_TX_FLAG);
dev->vlan_features |= NETIF_F_SG;
dev->vlan_features |= NETIF_F_HW_CSUM;
if (bp->flags & USING_DAC_FLAG)
dev->vlan_features |= NETIF_F_HIGHDMA;
dev->vlan_features |= (NETIF_F_TSO | NETIF_F_TSO_ECN);
dev->vlan_features |= NETIF_F_TSO6;
#endif
/* get_port_hwinfo() will set prtad and mmds properly */
bp->mdio.prtad = MDIO_PRTAD_NONE;
bp->mdio.mmds = 0;
bp->mdio.mode_support = MDIO_SUPPORTS_C45 | MDIO_EMULATE_C22;
bp->mdio.dev = dev;
bp->mdio.mdio_read = bnx2x_mdio_read;
bp->mdio.mdio_write = bnx2x_mdio_write;
return 0;
err_out_unmap:
if (bp->regview) {
iounmap(bp->regview);
bp->regview = NULL;
}
if (bp->doorbells) {
iounmap(bp->doorbells);
bp->doorbells = NULL;
}
err_out_release:
if (atomic_read(&pdev->enable_cnt) == 1)
pci_release_regions(pdev);
err_out_disable:
pci_disable_device(pdev);
pci_set_drvdata(pdev, NULL);
err_out:
return rc;
}
static void __devinit bnx2x_get_pcie_width_speed(struct bnx2x *bp,
int *width, int *speed)
{
u32 val = REG_RD(bp, PCICFG_OFFSET + PCICFG_LINK_CONTROL);
*width = (val & PCICFG_LINK_WIDTH) >> PCICFG_LINK_WIDTH_SHIFT;
/* return value of 1=2.5GHz 2=5GHz */
*speed = (val & PCICFG_LINK_SPEED) >> PCICFG_LINK_SPEED_SHIFT;
}
static int __devinit bnx2x_check_firmware(struct bnx2x *bp)
{
const struct firmware *firmware = bp->firmware;
struct bnx2x_fw_file_hdr *fw_hdr;
struct bnx2x_fw_file_section *sections;
u32 offset, len, num_ops;
u16 *ops_offsets;
int i;
const u8 *fw_ver;
if (firmware->size < sizeof(struct bnx2x_fw_file_hdr))
return -EINVAL;
fw_hdr = (struct bnx2x_fw_file_hdr *)firmware->data;
sections = (struct bnx2x_fw_file_section *)fw_hdr;
/* Make sure none of the offsets and sizes make us read beyond
* the end of the firmware data */
for (i = 0; i < sizeof(*fw_hdr) / sizeof(*sections); i++) {
offset = be32_to_cpu(sections[i].offset);
len = be32_to_cpu(sections[i].len);
if (offset + len > firmware->size) {
dev_err(&bp->pdev->dev,
"Section %d length is out of bounds\n", i);
return -EINVAL;
}
}
/* Likewise for the init_ops offsets */
offset = be32_to_cpu(fw_hdr->init_ops_offsets.offset);
ops_offsets = (u16 *)(firmware->data + offset);
num_ops = be32_to_cpu(fw_hdr->init_ops.len) / sizeof(struct raw_op);
for (i = 0; i < be32_to_cpu(fw_hdr->init_ops_offsets.len) / 2; i++) {
if (be16_to_cpu(ops_offsets[i]) > num_ops) {
dev_err(&bp->pdev->dev,
"Section offset %d is out of bounds\n", i);
return -EINVAL;
}
}
/* Check FW version */
offset = be32_to_cpu(fw_hdr->fw_version.offset);
fw_ver = firmware->data + offset;
if ((fw_ver[0] != BCM_5710_FW_MAJOR_VERSION) ||
(fw_ver[1] != BCM_5710_FW_MINOR_VERSION) ||
(fw_ver[2] != BCM_5710_FW_REVISION_VERSION) ||
(fw_ver[3] != BCM_5710_FW_ENGINEERING_VERSION)) {
dev_err(&bp->pdev->dev,
"Bad FW version:%d.%d.%d.%d. Should be %d.%d.%d.%d\n",
fw_ver[0], fw_ver[1], fw_ver[2],
fw_ver[3], BCM_5710_FW_MAJOR_VERSION,
BCM_5710_FW_MINOR_VERSION,
BCM_5710_FW_REVISION_VERSION,
BCM_5710_FW_ENGINEERING_VERSION);
return -EINVAL;
}
return 0;
}
static inline void be32_to_cpu_n(const u8 *_source, u8 *_target, u32 n)
{
const __be32 *source = (const __be32 *)_source;
u32 *target = (u32 *)_target;
u32 i;
for (i = 0; i < n/4; i++)
target[i] = be32_to_cpu(source[i]);
}
/*
Ops array is stored in the following format:
{op(8bit), offset(24bit, big endian), data(32bit, big endian)}
*/
static inline void bnx2x_prep_ops(const u8 *_source, u8 *_target, u32 n)
{
const __be32 *source = (const __be32 *)_source;
struct raw_op *target = (struct raw_op *)_target;
u32 i, j, tmp;
for (i = 0, j = 0; i < n/8; i++, j += 2) {
tmp = be32_to_cpu(source[j]);
target[i].op = (tmp >> 24) & 0xff;
target[i].offset = tmp & 0xffffff;
target[i].raw_data = be32_to_cpu(source[j + 1]);
}
}
static inline void be16_to_cpu_n(const u8 *_source, u8 *_target, u32 n)
{
const __be16 *source = (const __be16 *)_source;
u16 *target = (u16 *)_target;
u32 i;
for (i = 0; i < n/2; i++)
target[i] = be16_to_cpu(source[i]);
}
#define BNX2X_ALLOC_AND_SET(arr, lbl, func) \
do { \
u32 len = be32_to_cpu(fw_hdr->arr.len); \
bp->arr = kmalloc(len, GFP_KERNEL); \
if (!bp->arr) { \
pr_err("Failed to allocate %d bytes for "#arr"\n", len); \
goto lbl; \
} \
func(bp->firmware->data + be32_to_cpu(fw_hdr->arr.offset), \
(u8 *)bp->arr, len); \
} while (0)
static int __devinit bnx2x_init_firmware(struct bnx2x *bp, struct device *dev)
{
const char *fw_file_name;
struct bnx2x_fw_file_hdr *fw_hdr;
int rc;
if (CHIP_IS_E1(bp))
fw_file_name = FW_FILE_NAME_E1;
else if (CHIP_IS_E1H(bp))
fw_file_name = FW_FILE_NAME_E1H;
else {
dev_err(dev, "Unsupported chip revision\n");
return -EINVAL;
}
dev_info(dev, "Loading %s\n", fw_file_name);
rc = request_firmware(&bp->firmware, fw_file_name, dev);
if (rc) {
dev_err(dev, "Can't load firmware file %s\n", fw_file_name);
goto request_firmware_exit;
}
rc = bnx2x_check_firmware(bp);
if (rc) {
dev_err(dev, "Corrupt firmware file %s\n", fw_file_name);
goto request_firmware_exit;
}
fw_hdr = (struct bnx2x_fw_file_hdr *)bp->firmware->data;
/* Initialize the pointers to the init arrays */
/* Blob */
BNX2X_ALLOC_AND_SET(init_data, request_firmware_exit, be32_to_cpu_n);
/* Opcodes */
BNX2X_ALLOC_AND_SET(init_ops, init_ops_alloc_err, bnx2x_prep_ops);
/* Offsets */
BNX2X_ALLOC_AND_SET(init_ops_offsets, init_offsets_alloc_err,
be16_to_cpu_n);
/* STORMs firmware */
INIT_TSEM_INT_TABLE_DATA(bp) = bp->firmware->data +
be32_to_cpu(fw_hdr->tsem_int_table_data.offset);
INIT_TSEM_PRAM_DATA(bp) = bp->firmware->data +
be32_to_cpu(fw_hdr->tsem_pram_data.offset);
INIT_USEM_INT_TABLE_DATA(bp) = bp->firmware->data +
be32_to_cpu(fw_hdr->usem_int_table_data.offset);
INIT_USEM_PRAM_DATA(bp) = bp->firmware->data +
be32_to_cpu(fw_hdr->usem_pram_data.offset);
INIT_XSEM_INT_TABLE_DATA(bp) = bp->firmware->data +
be32_to_cpu(fw_hdr->xsem_int_table_data.offset);
INIT_XSEM_PRAM_DATA(bp) = bp->firmware->data +
be32_to_cpu(fw_hdr->xsem_pram_data.offset);
INIT_CSEM_INT_TABLE_DATA(bp) = bp->firmware->data +
be32_to_cpu(fw_hdr->csem_int_table_data.offset);
INIT_CSEM_PRAM_DATA(bp) = bp->firmware->data +
be32_to_cpu(fw_hdr->csem_pram_data.offset);
return 0;
init_offsets_alloc_err:
kfree(bp->init_ops);
init_ops_alloc_err:
kfree(bp->init_data);
request_firmware_exit:
release_firmware(bp->firmware);
return rc;
}
static int __devinit bnx2x_init_one(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct net_device *dev = NULL;
struct bnx2x *bp;
int pcie_width, pcie_speed;
int rc;
/* dev zeroed in init_etherdev */
dev = alloc_etherdev_mq(sizeof(*bp), MAX_CONTEXT);
if (!dev) {
dev_err(&pdev->dev, "Cannot allocate net device\n");
return -ENOMEM;
}
bp = netdev_priv(dev);
bp->msg_enable = debug;
pci_set_drvdata(pdev, dev);
rc = bnx2x_init_dev(pdev, dev);
if (rc < 0) {
free_netdev(dev);
return rc;
}
rc = bnx2x_init_bp(bp);
if (rc)
goto init_one_exit;
/* Set init arrays */
rc = bnx2x_init_firmware(bp, &pdev->dev);
if (rc) {
dev_err(&pdev->dev, "Error loading firmware\n");
goto init_one_exit;
}
rc = register_netdev(dev);
if (rc) {
dev_err(&pdev->dev, "Cannot register net device\n");
goto init_one_exit;
}
bnx2x_get_pcie_width_speed(bp, &pcie_width, &pcie_speed);
netdev_info(dev, "%s (%c%d) PCI-E x%d %s found at mem %lx,"
" IRQ %d, ", board_info[ent->driver_data].name,
(CHIP_REV(bp) >> 12) + 'A', (CHIP_METAL(bp) >> 4),
pcie_width, (pcie_speed == 2) ? "5GHz (Gen2)" : "2.5GHz",
dev->base_addr, bp->pdev->irq);
pr_cont("node addr %pM\n", dev->dev_addr);
return 0;
init_one_exit:
if (bp->regview)
iounmap(bp->regview);
if (bp->doorbells)
iounmap(bp->doorbells);
free_netdev(dev);
if (atomic_read(&pdev->enable_cnt) == 1)
pci_release_regions(pdev);
pci_disable_device(pdev);
pci_set_drvdata(pdev, NULL);
return rc;
}
static void __devexit bnx2x_remove_one(struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev);
struct bnx2x *bp;
if (!dev) {
dev_err(&pdev->dev, "BAD net device from bnx2x_init_one\n");
return;
}
bp = netdev_priv(dev);
unregister_netdev(dev);
/* Make sure RESET task is not scheduled before continuing */
cancel_delayed_work_sync(&bp->reset_task);
kfree(bp->init_ops_offsets);
kfree(bp->init_ops);
kfree(bp->init_data);
release_firmware(bp->firmware);
if (bp->regview)
iounmap(bp->regview);
if (bp->doorbells)
iounmap(bp->doorbells);
free_netdev(dev);
if (atomic_read(&pdev->enable_cnt) == 1)
pci_release_regions(pdev);
pci_disable_device(pdev);
pci_set_drvdata(pdev, NULL);
}
static int bnx2x_suspend(struct pci_dev *pdev, pm_message_t state)
{
struct net_device *dev = pci_get_drvdata(pdev);
struct bnx2x *bp;
if (!dev) {
dev_err(&pdev->dev, "BAD net device from bnx2x_init_one\n");
return -ENODEV;
}
bp = netdev_priv(dev);
rtnl_lock();
pci_save_state(pdev);
if (!netif_running(dev)) {
rtnl_unlock();
return 0;
}
netif_device_detach(dev);
bnx2x_nic_unload(bp, UNLOAD_CLOSE);
bnx2x_set_power_state(bp, pci_choose_state(pdev, state));
rtnl_unlock();
return 0;
}
static int bnx2x_resume(struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev);
struct bnx2x *bp;
int rc;
if (!dev) {
dev_err(&pdev->dev, "BAD net device from bnx2x_init_one\n");
return -ENODEV;
}
bp = netdev_priv(dev);
if (bp->recovery_state != BNX2X_RECOVERY_DONE) {
printk(KERN_ERR "Handling parity error recovery. Try again later\n");
return -EAGAIN;
}
rtnl_lock();
pci_restore_state(pdev);
if (!netif_running(dev)) {
rtnl_unlock();
return 0;
}
bnx2x_set_power_state(bp, PCI_D0);
netif_device_attach(dev);
rc = bnx2x_nic_load(bp, LOAD_OPEN);
rtnl_unlock();
return rc;
}
static int bnx2x_eeh_nic_unload(struct bnx2x *bp)
{
int i;
bp->state = BNX2X_STATE_ERROR;
bp->rx_mode = BNX2X_RX_MODE_NONE;
bnx2x_netif_stop(bp, 0);
netif_carrier_off(bp->dev);
del_timer_sync(&bp->timer);
bp->stats_state = STATS_STATE_DISABLED;
DP(BNX2X_MSG_STATS, "stats_state - DISABLED\n");
/* Release IRQs */
bnx2x_free_irq(bp, false);
if (CHIP_IS_E1(bp)) {
struct mac_configuration_cmd *config =
bnx2x_sp(bp, mcast_config);
for (i = 0; i < config->hdr.length; i++)
CAM_INVALIDATE(config->config_table[i]);
}
/* Free SKBs, SGEs, TPA pool and driver internals */
bnx2x_free_skbs(bp);
for_each_queue(bp, i)
bnx2x_free_rx_sge_range(bp, bp->fp + i, NUM_RX_SGE);
for_each_queue(bp, i)
netif_napi_del(&bnx2x_fp(bp, i, napi));
bnx2x_free_mem(bp);
bp->state = BNX2X_STATE_CLOSED;
return 0;
}
static void bnx2x_eeh_recover(struct bnx2x *bp)
{
u32 val;
mutex_init(&bp->port.phy_mutex);
bp->common.shmem_base = REG_RD(bp, MISC_REG_SHARED_MEM_ADDR);
bp->link_params.shmem_base = bp->common.shmem_base;
BNX2X_DEV_INFO("shmem offset is 0x%x\n", bp->common.shmem_base);
if (!bp->common.shmem_base ||
(bp->common.shmem_base < 0xA0000) ||
(bp->common.shmem_base >= 0xC0000)) {
BNX2X_DEV_INFO("MCP not active\n");
bp->flags |= NO_MCP_FLAG;
return;
}
val = SHMEM_RD(bp, validity_map[BP_PORT(bp)]);
if ((val & (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB))
!= (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB))
BNX2X_ERR("BAD MCP validity signature\n");
if (!BP_NOMCP(bp)) {
bp->fw_seq = (SHMEM_RD(bp, func_mb[BP_FUNC(bp)].drv_mb_header)
& DRV_MSG_SEQ_NUMBER_MASK);
BNX2X_DEV_INFO("fw_seq 0x%08x\n", bp->fw_seq);
}
}
/**
* bnx2x_io_error_detected - called when PCI error is detected
* @pdev: Pointer to PCI device
* @state: The current pci connection state
*
* This function is called after a PCI bus error affecting
* this device has been detected.
*/
static pci_ers_result_t bnx2x_io_error_detected(struct pci_dev *pdev,
pci_channel_state_t state)
{
struct net_device *dev = pci_get_drvdata(pdev);
struct bnx2x *bp = netdev_priv(dev);
rtnl_lock();
netif_device_detach(dev);
if (state == pci_channel_io_perm_failure) {
rtnl_unlock();
return PCI_ERS_RESULT_DISCONNECT;
}
if (netif_running(dev))
bnx2x_eeh_nic_unload(bp);
pci_disable_device(pdev);
rtnl_unlock();
/* Request a slot reset */
return PCI_ERS_RESULT_NEED_RESET;
}
/**
* bnx2x_io_slot_reset - called after the PCI bus has been reset
* @pdev: Pointer to PCI device
*
* Restart the card from scratch, as if from a cold-boot.
*/
static pci_ers_result_t bnx2x_io_slot_reset(struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev);
struct bnx2x *bp = netdev_priv(dev);
rtnl_lock();
if (pci_enable_device(pdev)) {
dev_err(&pdev->dev,
"Cannot re-enable PCI device after reset\n");
rtnl_unlock();
return PCI_ERS_RESULT_DISCONNECT;
}
pci_set_master(pdev);
pci_restore_state(pdev);
if (netif_running(dev))
bnx2x_set_power_state(bp, PCI_D0);
rtnl_unlock();
return PCI_ERS_RESULT_RECOVERED;
}
/**
* bnx2x_io_resume - called when traffic can start flowing again
* @pdev: Pointer to PCI device
*
* This callback is called when the error recovery driver tells us that
* its OK to resume normal operation.
*/
static void bnx2x_io_resume(struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev);
struct bnx2x *bp = netdev_priv(dev);
if (bp->recovery_state != BNX2X_RECOVERY_DONE) {
printk(KERN_ERR "Handling parity error recovery. Try again later\n");
return;
}
rtnl_lock();
bnx2x_eeh_recover(bp);
if (netif_running(dev))
bnx2x_nic_load(bp, LOAD_NORMAL);
netif_device_attach(dev);
rtnl_unlock();
}
static struct pci_error_handlers bnx2x_err_handler = {
.error_detected = bnx2x_io_error_detected,
.slot_reset = bnx2x_io_slot_reset,
.resume = bnx2x_io_resume,
};
static struct pci_driver bnx2x_pci_driver = {
.name = DRV_MODULE_NAME,
.id_table = bnx2x_pci_tbl,
.probe = bnx2x_init_one,
.remove = __devexit_p(bnx2x_remove_one),
.suspend = bnx2x_suspend,
.resume = bnx2x_resume,
.err_handler = &bnx2x_err_handler,
};
static int __init bnx2x_init(void)
{
int ret;
pr_info("%s", version);
bnx2x_wq = create_singlethread_workqueue("bnx2x");
if (bnx2x_wq == NULL) {
pr_err("Cannot create workqueue\n");
return -ENOMEM;
}
ret = pci_register_driver(&bnx2x_pci_driver);
if (ret) {
pr_err("Cannot register driver\n");
destroy_workqueue(bnx2x_wq);
}
return ret;
}
static void __exit bnx2x_cleanup(void)
{
pci_unregister_driver(&bnx2x_pci_driver);
destroy_workqueue(bnx2x_wq);
}
module_init(bnx2x_init);
module_exit(bnx2x_cleanup);
#ifdef BCM_CNIC
/* count denotes the number of new completions we have seen */
static void bnx2x_cnic_sp_post(struct bnx2x *bp, int count)
{
struct eth_spe *spe;
#ifdef BNX2X_STOP_ON_ERROR
if (unlikely(bp->panic))
return;
#endif
spin_lock_bh(&bp->spq_lock);
bp->cnic_spq_pending -= count;
for (; bp->cnic_spq_pending < bp->cnic_eth_dev.max_kwqe_pending;
bp->cnic_spq_pending++) {
if (!bp->cnic_kwq_pending)
break;
spe = bnx2x_sp_get_next(bp);
*spe = *bp->cnic_kwq_cons;
bp->cnic_kwq_pending--;
DP(NETIF_MSG_TIMER, "pending on SPQ %d, on KWQ %d count %d\n",
bp->cnic_spq_pending, bp->cnic_kwq_pending, count);
if (bp->cnic_kwq_cons == bp->cnic_kwq_last)
bp->cnic_kwq_cons = bp->cnic_kwq;
else
bp->cnic_kwq_cons++;
}
bnx2x_sp_prod_update(bp);
spin_unlock_bh(&bp->spq_lock);
}
static int bnx2x_cnic_sp_queue(struct net_device *dev,
struct kwqe_16 *kwqes[], u32 count)
{
struct bnx2x *bp = netdev_priv(dev);
int i;
#ifdef BNX2X_STOP_ON_ERROR
if (unlikely(bp->panic))
return -EIO;
#endif
spin_lock_bh(&bp->spq_lock);
for (i = 0; i < count; i++) {
struct eth_spe *spe = (struct eth_spe *)kwqes[i];
if (bp->cnic_kwq_pending == MAX_SP_DESC_CNT)
break;
*bp->cnic_kwq_prod = *spe;
bp->cnic_kwq_pending++;
DP(NETIF_MSG_TIMER, "L5 SPQE %x %x %x:%x pos %d\n",
spe->hdr.conn_and_cmd_data, spe->hdr.type,
spe->data.mac_config_addr.hi,
spe->data.mac_config_addr.lo,
bp->cnic_kwq_pending);
if (bp->cnic_kwq_prod == bp->cnic_kwq_last)
bp->cnic_kwq_prod = bp->cnic_kwq;
else
bp->cnic_kwq_prod++;
}
spin_unlock_bh(&bp->spq_lock);
if (bp->cnic_spq_pending < bp->cnic_eth_dev.max_kwqe_pending)
bnx2x_cnic_sp_post(bp, 0);
return i;
}
static int bnx2x_cnic_ctl_send(struct bnx2x *bp, struct cnic_ctl_info *ctl)
{
struct cnic_ops *c_ops;
int rc = 0;
mutex_lock(&bp->cnic_mutex);
c_ops = bp->cnic_ops;
if (c_ops)
rc = c_ops->cnic_ctl(bp->cnic_data, ctl);
mutex_unlock(&bp->cnic_mutex);
return rc;
}
static int bnx2x_cnic_ctl_send_bh(struct bnx2x *bp, struct cnic_ctl_info *ctl)
{
struct cnic_ops *c_ops;
int rc = 0;
rcu_read_lock();
c_ops = rcu_dereference(bp->cnic_ops);
if (c_ops)
rc = c_ops->cnic_ctl(bp->cnic_data, ctl);
rcu_read_unlock();
return rc;
}
/*
* for commands that have no data
*/
static int bnx2x_cnic_notify(struct bnx2x *bp, int cmd)
{
struct cnic_ctl_info ctl = {0};
ctl.cmd = cmd;
return bnx2x_cnic_ctl_send(bp, &ctl);
}
static void bnx2x_cnic_cfc_comp(struct bnx2x *bp, int cid)
{
struct cnic_ctl_info ctl;
/* first we tell CNIC and only then we count this as a completion */
ctl.cmd = CNIC_CTL_COMPLETION_CMD;
ctl.data.comp.cid = cid;
bnx2x_cnic_ctl_send_bh(bp, &ctl);
bnx2x_cnic_sp_post(bp, 1);
}
static int bnx2x_drv_ctl(struct net_device *dev, struct drv_ctl_info *ctl)
{
struct bnx2x *bp = netdev_priv(dev);
int rc = 0;
switch (ctl->cmd) {
case DRV_CTL_CTXTBL_WR_CMD: {
u32 index = ctl->data.io.offset;
dma_addr_t addr = ctl->data.io.dma_addr;
bnx2x_ilt_wr(bp, index, addr);
break;
}
case DRV_CTL_COMPLETION_CMD: {
int count = ctl->data.comp.comp_count;
bnx2x_cnic_sp_post(bp, count);
break;
}
/* rtnl_lock is held. */
case DRV_CTL_START_L2_CMD: {
u32 cli = ctl->data.ring.client_id;
bp->rx_mode_cl_mask |= (1 << cli);
bnx2x_set_storm_rx_mode(bp);
break;
}
/* rtnl_lock is held. */
case DRV_CTL_STOP_L2_CMD: {
u32 cli = ctl->data.ring.client_id;
bp->rx_mode_cl_mask &= ~(1 << cli);
bnx2x_set_storm_rx_mode(bp);
break;
}
default:
BNX2X_ERR("unknown command %x\n", ctl->cmd);
rc = -EINVAL;
}
return rc;
}
static void bnx2x_setup_cnic_irq_info(struct bnx2x *bp)
{
struct cnic_eth_dev *cp = &bp->cnic_eth_dev;
if (bp->flags & USING_MSIX_FLAG) {
cp->drv_state |= CNIC_DRV_STATE_USING_MSIX;
cp->irq_arr[0].irq_flags |= CNIC_IRQ_FL_MSIX;
cp->irq_arr[0].vector = bp->msix_table[1].vector;
} else {
cp->drv_state &= ~CNIC_DRV_STATE_USING_MSIX;
cp->irq_arr[0].irq_flags &= ~CNIC_IRQ_FL_MSIX;
}
cp->irq_arr[0].status_blk = bp->cnic_sb;
cp->irq_arr[0].status_blk_num = CNIC_SB_ID(bp);
cp->irq_arr[1].status_blk = bp->def_status_blk;
cp->irq_arr[1].status_blk_num = DEF_SB_ID;
cp->num_irq = 2;
}
static int bnx2x_register_cnic(struct net_device *dev, struct cnic_ops *ops,
void *data)
{
struct bnx2x *bp = netdev_priv(dev);
struct cnic_eth_dev *cp = &bp->cnic_eth_dev;
if (ops == NULL)
return -EINVAL;
if (atomic_read(&bp->intr_sem) != 0)
return -EBUSY;
bp->cnic_kwq = kzalloc(PAGE_SIZE, GFP_KERNEL);
if (!bp->cnic_kwq)
return -ENOMEM;
bp->cnic_kwq_cons = bp->cnic_kwq;
bp->cnic_kwq_prod = bp->cnic_kwq;
bp->cnic_kwq_last = bp->cnic_kwq + MAX_SP_DESC_CNT;
bp->cnic_spq_pending = 0;
bp->cnic_kwq_pending = 0;
bp->cnic_data = data;
cp->num_irq = 0;
cp->drv_state = CNIC_DRV_STATE_REGD;
bnx2x_init_sb(bp, bp->cnic_sb, bp->cnic_sb_mapping, CNIC_SB_ID(bp));
bnx2x_setup_cnic_irq_info(bp);
bnx2x_set_iscsi_eth_mac_addr(bp, 1);
bp->cnic_flags |= BNX2X_CNIC_FLAG_MAC_SET;
rcu_assign_pointer(bp->cnic_ops, ops);
return 0;
}
static int bnx2x_unregister_cnic(struct net_device *dev)
{
struct bnx2x *bp = netdev_priv(dev);
struct cnic_eth_dev *cp = &bp->cnic_eth_dev;
mutex_lock(&bp->cnic_mutex);
if (bp->cnic_flags & BNX2X_CNIC_FLAG_MAC_SET) {
bp->cnic_flags &= ~BNX2X_CNIC_FLAG_MAC_SET;
bnx2x_set_iscsi_eth_mac_addr(bp, 0);
}
cp->drv_state = 0;
rcu_assign_pointer(bp->cnic_ops, NULL);
mutex_unlock(&bp->cnic_mutex);
synchronize_rcu();
kfree(bp->cnic_kwq);
bp->cnic_kwq = NULL;
return 0;
}
struct cnic_eth_dev *bnx2x_cnic_probe(struct net_device *dev)
{
struct bnx2x *bp = netdev_priv(dev);
struct cnic_eth_dev *cp = &bp->cnic_eth_dev;
cp->drv_owner = THIS_MODULE;
cp->chip_id = CHIP_ID(bp);
cp->pdev = bp->pdev;
cp->io_base = bp->regview;
cp->io_base2 = bp->doorbells;
cp->max_kwqe_pending = 8;
cp->ctx_blk_size = CNIC_CTX_PER_ILT * sizeof(union cdu_context);
cp->ctx_tbl_offset = FUNC_ILT_BASE(BP_FUNC(bp)) + 1;
cp->ctx_tbl_len = CNIC_ILT_LINES;
cp->starting_cid = BCM_CNIC_CID_START;
cp->drv_submit_kwqes_16 = bnx2x_cnic_sp_queue;
cp->drv_ctl = bnx2x_drv_ctl;
cp->drv_register_cnic = bnx2x_register_cnic;
cp->drv_unregister_cnic = bnx2x_unregister_cnic;
return cp;
}
EXPORT_SYMBOL(bnx2x_cnic_probe);
#endif /* BCM_CNIC */
| gpl-2.0 |
sbryan12144/BLACKOUT_GB_MSM7x30 | drivers/infiniband/hw/qib/qib_fs.c | 760 | 14658 | /*
* Copyright (c) 2006, 2007, 2008, 2009 QLogic Corporation. All rights reserved.
* Copyright (c) 2006 PathScale, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/mount.h>
#include <linux/pagemap.h>
#include <linux/init.h>
#include <linux/namei.h>
#include "qib.h"
#define QIBFS_MAGIC 0x726a77
static struct super_block *qib_super;
#define private2dd(file) ((file)->f_dentry->d_inode->i_private)
static int qibfs_mknod(struct inode *dir, struct dentry *dentry,
int mode, const struct file_operations *fops,
void *data)
{
int error;
struct inode *inode = new_inode(dir->i_sb);
if (!inode) {
error = -EPERM;
goto bail;
}
inode->i_mode = mode;
inode->i_uid = 0;
inode->i_gid = 0;
inode->i_blocks = 0;
inode->i_atime = CURRENT_TIME;
inode->i_mtime = inode->i_atime;
inode->i_ctime = inode->i_atime;
inode->i_private = data;
if ((mode & S_IFMT) == S_IFDIR) {
inode->i_op = &simple_dir_inode_operations;
inc_nlink(inode);
inc_nlink(dir);
}
inode->i_fop = fops;
d_instantiate(dentry, inode);
error = 0;
bail:
return error;
}
static int create_file(const char *name, mode_t mode,
struct dentry *parent, struct dentry **dentry,
const struct file_operations *fops, void *data)
{
int error;
*dentry = NULL;
mutex_lock(&parent->d_inode->i_mutex);
*dentry = lookup_one_len(name, parent, strlen(name));
if (!IS_ERR(*dentry))
error = qibfs_mknod(parent->d_inode, *dentry,
mode, fops, data);
else
error = PTR_ERR(*dentry);
mutex_unlock(&parent->d_inode->i_mutex);
return error;
}
static ssize_t driver_stats_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
return simple_read_from_buffer(buf, count, ppos, &qib_stats,
sizeof qib_stats);
}
/*
* driver stats field names, one line per stat, single string. Used by
* programs like ipathstats to print the stats in a way which works for
* different versions of drivers, without changing program source.
* if qlogic_ib_stats changes, this needs to change. Names need to be
* 12 chars or less (w/o newline), for proper display by ipathstats utility.
*/
static const char qib_statnames[] =
"KernIntr\n"
"ErrorIntr\n"
"Tx_Errs\n"
"Rcv_Errs\n"
"H/W_Errs\n"
"NoPIOBufs\n"
"CtxtsOpen\n"
"RcvLen_Errs\n"
"EgrBufFull\n"
"EgrHdrFull\n"
;
static ssize_t driver_names_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
return simple_read_from_buffer(buf, count, ppos, qib_statnames,
sizeof qib_statnames - 1); /* no null */
}
static const struct file_operations driver_ops[] = {
{ .read = driver_stats_read, },
{ .read = driver_names_read, },
};
/* read the per-device counters */
static ssize_t dev_counters_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
u64 *counters;
size_t avail;
struct qib_devdata *dd = private2dd(file);
avail = dd->f_read_cntrs(dd, *ppos, NULL, &counters);
return simple_read_from_buffer(buf, count, ppos, counters, avail);
}
/* read the per-device counters */
static ssize_t dev_names_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
char *names;
size_t avail;
struct qib_devdata *dd = private2dd(file);
avail = dd->f_read_cntrs(dd, *ppos, &names, NULL);
return simple_read_from_buffer(buf, count, ppos, names, avail);
}
static const struct file_operations cntr_ops[] = {
{ .read = dev_counters_read, },
{ .read = dev_names_read, },
};
/*
* Could use file->f_dentry->d_inode->i_ino to figure out which file,
* instead of separate routine for each, but for now, this works...
*/
/* read the per-port names (same for each port) */
static ssize_t portnames_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
char *names;
size_t avail;
struct qib_devdata *dd = private2dd(file);
avail = dd->f_read_portcntrs(dd, *ppos, 0, &names, NULL);
return simple_read_from_buffer(buf, count, ppos, names, avail);
}
/* read the per-port counters for port 1 (pidx 0) */
static ssize_t portcntrs_1_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
u64 *counters;
size_t avail;
struct qib_devdata *dd = private2dd(file);
avail = dd->f_read_portcntrs(dd, *ppos, 0, NULL, &counters);
return simple_read_from_buffer(buf, count, ppos, counters, avail);
}
/* read the per-port counters for port 2 (pidx 1) */
static ssize_t portcntrs_2_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
u64 *counters;
size_t avail;
struct qib_devdata *dd = private2dd(file);
avail = dd->f_read_portcntrs(dd, *ppos, 1, NULL, &counters);
return simple_read_from_buffer(buf, count, ppos, counters, avail);
}
static const struct file_operations portcntr_ops[] = {
{ .read = portnames_read, },
{ .read = portcntrs_1_read, },
{ .read = portcntrs_2_read, },
};
/*
* read the per-port QSFP data for port 1 (pidx 0)
*/
static ssize_t qsfp_1_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct qib_devdata *dd = private2dd(file);
char *tmp;
int ret;
tmp = kmalloc(PAGE_SIZE, GFP_KERNEL);
if (!tmp)
return -ENOMEM;
ret = qib_qsfp_dump(dd->pport, tmp, PAGE_SIZE);
if (ret > 0)
ret = simple_read_from_buffer(buf, count, ppos, tmp, ret);
kfree(tmp);
return ret;
}
/*
* read the per-port QSFP data for port 2 (pidx 1)
*/
static ssize_t qsfp_2_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct qib_devdata *dd = private2dd(file);
char *tmp;
int ret;
if (dd->num_pports < 2)
return -ENODEV;
tmp = kmalloc(PAGE_SIZE, GFP_KERNEL);
if (!tmp)
return -ENOMEM;
ret = qib_qsfp_dump(dd->pport + 1, tmp, PAGE_SIZE);
if (ret > 0)
ret = simple_read_from_buffer(buf, count, ppos, tmp, ret);
kfree(tmp);
return ret;
}
static const struct file_operations qsfp_ops[] = {
{ .read = qsfp_1_read, },
{ .read = qsfp_2_read, },
};
static ssize_t flash_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct qib_devdata *dd;
ssize_t ret;
loff_t pos;
char *tmp;
pos = *ppos;
if (pos < 0) {
ret = -EINVAL;
goto bail;
}
if (pos >= sizeof(struct qib_flash)) {
ret = 0;
goto bail;
}
if (count > sizeof(struct qib_flash) - pos)
count = sizeof(struct qib_flash) - pos;
tmp = kmalloc(count, GFP_KERNEL);
if (!tmp) {
ret = -ENOMEM;
goto bail;
}
dd = private2dd(file);
if (qib_eeprom_read(dd, pos, tmp, count)) {
qib_dev_err(dd, "failed to read from flash\n");
ret = -ENXIO;
goto bail_tmp;
}
if (copy_to_user(buf, tmp, count)) {
ret = -EFAULT;
goto bail_tmp;
}
*ppos = pos + count;
ret = count;
bail_tmp:
kfree(tmp);
bail:
return ret;
}
static ssize_t flash_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
struct qib_devdata *dd;
ssize_t ret;
loff_t pos;
char *tmp;
pos = *ppos;
if (pos != 0) {
ret = -EINVAL;
goto bail;
}
if (count != sizeof(struct qib_flash)) {
ret = -EINVAL;
goto bail;
}
tmp = kmalloc(count, GFP_KERNEL);
if (!tmp) {
ret = -ENOMEM;
goto bail;
}
if (copy_from_user(tmp, buf, count)) {
ret = -EFAULT;
goto bail_tmp;
}
dd = private2dd(file);
if (qib_eeprom_write(dd, pos, tmp, count)) {
ret = -ENXIO;
qib_dev_err(dd, "failed to write to flash\n");
goto bail_tmp;
}
*ppos = pos + count;
ret = count;
bail_tmp:
kfree(tmp);
bail:
return ret;
}
static const struct file_operations flash_ops = {
.read = flash_read,
.write = flash_write,
};
static int add_cntr_files(struct super_block *sb, struct qib_devdata *dd)
{
struct dentry *dir, *tmp;
char unit[10];
int ret, i;
/* create the per-unit directory */
snprintf(unit, sizeof unit, "%u", dd->unit);
ret = create_file(unit, S_IFDIR|S_IRUGO|S_IXUGO, sb->s_root, &dir,
&simple_dir_operations, dd);
if (ret) {
printk(KERN_ERR "create_file(%s) failed: %d\n", unit, ret);
goto bail;
}
/* create the files in the new directory */
ret = create_file("counters", S_IFREG|S_IRUGO, dir, &tmp,
&cntr_ops[0], dd);
if (ret) {
printk(KERN_ERR "create_file(%s/counters) failed: %d\n",
unit, ret);
goto bail;
}
ret = create_file("counter_names", S_IFREG|S_IRUGO, dir, &tmp,
&cntr_ops[1], dd);
if (ret) {
printk(KERN_ERR "create_file(%s/counter_names) failed: %d\n",
unit, ret);
goto bail;
}
ret = create_file("portcounter_names", S_IFREG|S_IRUGO, dir, &tmp,
&portcntr_ops[0], dd);
if (ret) {
printk(KERN_ERR "create_file(%s/%s) failed: %d\n",
unit, "portcounter_names", ret);
goto bail;
}
for (i = 1; i <= dd->num_pports; i++) {
char fname[24];
sprintf(fname, "port%dcounters", i);
/* create the files in the new directory */
ret = create_file(fname, S_IFREG|S_IRUGO, dir, &tmp,
&portcntr_ops[i], dd);
if (ret) {
printk(KERN_ERR "create_file(%s/%s) failed: %d\n",
unit, fname, ret);
goto bail;
}
if (!(dd->flags & QIB_HAS_QSFP))
continue;
sprintf(fname, "qsfp%d", i);
ret = create_file(fname, S_IFREG|S_IRUGO, dir, &tmp,
&qsfp_ops[i - 1], dd);
if (ret) {
printk(KERN_ERR "create_file(%s/%s) failed: %d\n",
unit, fname, ret);
goto bail;
}
}
ret = create_file("flash", S_IFREG|S_IWUSR|S_IRUGO, dir, &tmp,
&flash_ops, dd);
if (ret)
printk(KERN_ERR "create_file(%s/flash) failed: %d\n",
unit, ret);
bail:
return ret;
}
static int remove_file(struct dentry *parent, char *name)
{
struct dentry *tmp;
int ret;
tmp = lookup_one_len(name, parent, strlen(name));
if (IS_ERR(tmp)) {
ret = PTR_ERR(tmp);
goto bail;
}
spin_lock(&dcache_lock);
spin_lock(&tmp->d_lock);
if (!(d_unhashed(tmp) && tmp->d_inode)) {
dget_locked(tmp);
__d_drop(tmp);
spin_unlock(&tmp->d_lock);
spin_unlock(&dcache_lock);
simple_unlink(parent->d_inode, tmp);
} else {
spin_unlock(&tmp->d_lock);
spin_unlock(&dcache_lock);
}
ret = 0;
bail:
/*
* We don't expect clients to care about the return value, but
* it's there if they need it.
*/
return ret;
}
static int remove_device_files(struct super_block *sb,
struct qib_devdata *dd)
{
struct dentry *dir, *root;
char unit[10];
int ret, i;
root = dget(sb->s_root);
mutex_lock(&root->d_inode->i_mutex);
snprintf(unit, sizeof unit, "%u", dd->unit);
dir = lookup_one_len(unit, root, strlen(unit));
if (IS_ERR(dir)) {
ret = PTR_ERR(dir);
printk(KERN_ERR "Lookup of %s failed\n", unit);
goto bail;
}
remove_file(dir, "counters");
remove_file(dir, "counter_names");
remove_file(dir, "portcounter_names");
for (i = 0; i < dd->num_pports; i++) {
char fname[24];
sprintf(fname, "port%dcounters", i + 1);
remove_file(dir, fname);
if (dd->flags & QIB_HAS_QSFP) {
sprintf(fname, "qsfp%d", i + 1);
remove_file(dir, fname);
}
}
remove_file(dir, "flash");
d_delete(dir);
ret = simple_rmdir(root->d_inode, dir);
bail:
mutex_unlock(&root->d_inode->i_mutex);
dput(root);
return ret;
}
/*
* This fills everything in when the fs is mounted, to handle umount/mount
* after device init. The direct add_cntr_files() call handles adding
* them from the init code, when the fs is already mounted.
*/
static int qibfs_fill_super(struct super_block *sb, void *data, int silent)
{
struct qib_devdata *dd, *tmp;
unsigned long flags;
int ret;
static struct tree_descr files[] = {
[2] = {"driver_stats", &driver_ops[0], S_IRUGO},
[3] = {"driver_stats_names", &driver_ops[1], S_IRUGO},
{""},
};
ret = simple_fill_super(sb, QIBFS_MAGIC, files);
if (ret) {
printk(KERN_ERR "simple_fill_super failed: %d\n", ret);
goto bail;
}
spin_lock_irqsave(&qib_devs_lock, flags);
list_for_each_entry_safe(dd, tmp, &qib_dev_list, list) {
spin_unlock_irqrestore(&qib_devs_lock, flags);
ret = add_cntr_files(sb, dd);
if (ret)
goto bail;
spin_lock_irqsave(&qib_devs_lock, flags);
}
spin_unlock_irqrestore(&qib_devs_lock, flags);
bail:
return ret;
}
static int qibfs_get_sb(struct file_system_type *fs_type, int flags,
const char *dev_name, void *data, struct vfsmount *mnt)
{
int ret = get_sb_single(fs_type, flags, data,
qibfs_fill_super, mnt);
if (ret >= 0)
qib_super = mnt->mnt_sb;
return ret;
}
static void qibfs_kill_super(struct super_block *s)
{
kill_litter_super(s);
qib_super = NULL;
}
int qibfs_add(struct qib_devdata *dd)
{
int ret;
/*
* On first unit initialized, qib_super will not yet exist
* because nobody has yet tried to mount the filesystem, so
* we can't consider that to be an error; if an error occurs
* during the mount, that will get a complaint, so this is OK.
* add_cntr_files() for all units is done at mount from
* qibfs_fill_super(), so one way or another, everything works.
*/
if (qib_super == NULL)
ret = 0;
else
ret = add_cntr_files(qib_super, dd);
return ret;
}
int qibfs_remove(struct qib_devdata *dd)
{
int ret = 0;
if (qib_super)
ret = remove_device_files(qib_super, dd);
return ret;
}
static struct file_system_type qibfs_fs_type = {
.owner = THIS_MODULE,
.name = "ipathfs",
.get_sb = qibfs_get_sb,
.kill_sb = qibfs_kill_super,
};
int __init qib_init_qibfs(void)
{
return register_filesystem(&qibfs_fs_type);
}
int __exit qib_exit_qibfs(void)
{
return unregister_filesystem(&qibfs_fs_type);
}
| gpl-2.0 |
mdmower/android_kernel_htc_m7 | drivers/video/msm/mdss/mdss_mdp_intf_video.c | 1272 | 8405 | /* Copyright (c) 2012, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#define pr_fmt(fmt) "%s: " fmt, __func__
#include "mdss_fb.h"
#include "mdss_mdp.h"
/* intf timing settings */
struct intf_timing_params {
u32 width;
u32 height;
u32 xres;
u32 yres;
u32 h_back_porch;
u32 h_front_porch;
u32 v_back_porch;
u32 v_front_porch;
u32 hsync_pulse_width;
u32 vsync_pulse_width;
u32 border_clr;
u32 underflow_clr;
u32 hsync_skew;
};
#define MAX_SESSIONS 3
struct mdss_mdp_video_ctx {
u32 ctl_num;
u32 pp_num;
u8 ref_cnt;
u8 timegen_en;
struct completion pp_comp;
struct completion vsync_comp;
};
struct mdss_mdp_video_ctx mdss_mdp_video_ctx_list[MAX_SESSIONS];
static int mdss_mdp_video_timegen_setup(struct mdss_mdp_ctl *ctl,
struct intf_timing_params *p)
{
u32 hsync_period, vsync_period;
u32 hsync_start_x, hsync_end_x, display_v_start, display_v_end;
u32 active_h_start, active_h_end, active_v_start, active_v_end;
u32 display_hctl, active_hctl, hsync_ctl, polarity_ctl;
int off;
off = MDSS_MDP_REG_INTF_OFFSET(ctl->intf_num);
hsync_period = p->hsync_pulse_width + p->h_back_porch +
p->width + p->h_front_porch;
vsync_period = p->vsync_pulse_width + p->v_back_porch +
p->height + p->v_front_porch;
display_v_start = ((p->vsync_pulse_width + p->v_back_porch) *
hsync_period) + p->hsync_skew;
display_v_end = ((vsync_period - p->v_front_porch) * hsync_period) +
p->hsync_skew - 1;
if (ctl->intf_type == MDSS_INTF_EDP) {
display_v_start += p->hsync_pulse_width + p->h_back_porch;
display_v_end -= p->h_front_porch;
}
hsync_start_x = p->h_back_porch + p->hsync_pulse_width;
hsync_end_x = hsync_period - p->h_front_porch - 1;
if (p->width != p->xres) {
active_h_start = hsync_start_x;
active_h_end = active_h_start + p->xres - 1;
} else {
active_h_start = 0;
active_h_end = 0;
}
if (p->height != p->yres) {
active_v_start = display_v_start;
active_v_end = active_v_start + (p->yres * hsync_period) - 1;
} else {
active_v_start = 0;
active_v_end = 0;
}
if (active_h_end) {
active_hctl = (active_h_end << 16) | active_h_start;
active_hctl |= BIT(31); /* ACTIVE_H_ENABLE */
} else {
active_hctl = 0;
}
if (active_v_end)
active_v_start |= BIT(31); /* ACTIVE_V_ENABLE */
hsync_ctl = (hsync_period << 16) | p->hsync_pulse_width;
display_hctl = (hsync_end_x << 16) | hsync_start_x;
polarity_ctl = (0 << 2) | /* DEN Polarity */
(0 << 1) | /* VSYNC Polarity */
(0); /* HSYNC Polarity */
MDSS_MDP_REG_WRITE(off + MDSS_MDP_REG_INTF_HSYNC_CTL, hsync_ctl);
MDSS_MDP_REG_WRITE(off + MDSS_MDP_REG_INTF_VSYNC_PERIOD_F0,
vsync_period * hsync_period);
MDSS_MDP_REG_WRITE(off + MDSS_MDP_REG_INTF_VSYNC_PULSE_WIDTH_F0,
p->vsync_pulse_width * hsync_period);
MDSS_MDP_REG_WRITE(off + MDSS_MDP_REG_INTF_DISPLAY_HCTL,
display_hctl);
MDSS_MDP_REG_WRITE(off + MDSS_MDP_REG_INTF_DISPLAY_V_START_F0,
display_v_start);
MDSS_MDP_REG_WRITE(off + MDSS_MDP_REG_INTF_DISPLAY_V_END_F0,
display_v_end);
MDSS_MDP_REG_WRITE(off + MDSS_MDP_REG_INTF_ACTIVE_HCTL, active_hctl);
MDSS_MDP_REG_WRITE(off + MDSS_MDP_REG_INTF_ACTIVE_V_START_F0,
active_v_start);
MDSS_MDP_REG_WRITE(off + MDSS_MDP_REG_INTF_ACTIVE_V_END_F0,
active_v_end);
MDSS_MDP_REG_WRITE(off + MDSS_MDP_REG_INTF_BORDER_COLOR,
p->border_clr);
MDSS_MDP_REG_WRITE(off + MDSS_MDP_REG_INTF_UNDERFLOW_COLOR,
p->underflow_clr);
MDSS_MDP_REG_WRITE(off + MDSS_MDP_REG_INTF_HSYNC_SKEW,
p->hsync_skew);
MDSS_MDP_REG_WRITE(off + MDSS_MDP_REG_INTF_POLARITY_CTL,
polarity_ctl);
MDSS_MDP_REG_WRITE(off + MDSS_MDP_REG_INTF_PANEL_FORMAT,
MDSS_MDP_PANEL_FORMAT_RGB888);
return 0;
}
static int mdss_mdp_video_stop(struct mdss_mdp_ctl *ctl)
{
struct mdss_mdp_video_ctx *ctx;
int off;
pr_debug("stop ctl=%d\n", ctl->num);
ctx = (struct mdss_mdp_video_ctx *) ctl->priv_data;
if (!ctx) {
pr_err("invalid ctx for ctl=%d\n", ctl->num);
return -ENODEV;
}
if (ctx->timegen_en) {
off = MDSS_MDP_REG_INTF_OFFSET(ctl->intf_num);
MDSS_MDP_REG_WRITE(off + MDSS_MDP_REG_INTF_TIMING_ENGINE_EN, 0);
mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_OFF, false);
ctx->timegen_en = false;
}
memset(ctx, 0, sizeof(*ctx));
return 0;
}
static void mdss_mdp_video_pp_intr_done(void *arg)
{
struct mdss_mdp_video_ctx *ctx;
ctx = (struct mdss_mdp_video_ctx *) arg;
if (!ctx) {
pr_err("invalid ctx\n");
return;
}
pr_debug("intr mixer=%d\n", ctx->pp_num);
complete(&ctx->pp_comp);
}
static void mdss_mdp_video_vsync_intr_done(void *arg)
{
struct mdss_mdp_video_ctx *ctx;
ctx = (struct mdss_mdp_video_ctx *) arg;
if (!ctx) {
pr_err("invalid ctx\n");
return;
}
pr_debug("intr ctl=%d\n", ctx->ctl_num);
complete(&ctx->vsync_comp);
}
static int mdss_mdp_video_prepare(struct mdss_mdp_ctl *ctl, void *arg)
{
struct mdss_mdp_video_ctx *ctx;
ctx = (struct mdss_mdp_video_ctx *) ctl->priv_data;
if (!ctx) {
pr_err("invalid ctx\n");
return -ENODEV;
}
if (ctx->timegen_en) {
u32 intr_type = MDSS_MDP_IRQ_PING_PONG_COMP;
pr_debug("waiting for ping pong %d done\n", ctx->pp_num);
mdss_mdp_set_intr_callback(intr_type, ctx->pp_num,
mdss_mdp_video_pp_intr_done, ctx);
mdss_mdp_irq_enable(intr_type, ctx->pp_num);
wait_for_completion_interruptible(&ctx->pp_comp);
mdss_mdp_irq_disable(intr_type, ctx->pp_num);
}
return 0;
}
static int mdss_mdp_video_display(struct mdss_mdp_ctl *ctl, void *arg)
{
struct mdss_mdp_video_ctx *ctx;
u32 intr_type = MDSS_MDP_IRQ_INTF_VSYNC;
pr_debug("kickoff ctl=%d\n", ctl->num);
ctx = (struct mdss_mdp_video_ctx *) ctl->priv_data;
if (!ctx) {
pr_err("invalid ctx\n");
return -ENODEV;
}
mdss_mdp_set_intr_callback(intr_type, ctl->intf_num,
mdss_mdp_video_vsync_intr_done, ctx);
mdss_mdp_irq_enable(intr_type, ctl->intf_num);
if (!ctx->timegen_en) {
int off = MDSS_MDP_REG_INTF_OFFSET(ctl->intf_num);
pr_debug("enabling timing gen for intf=%d\n", ctl->intf_num);
mdss_mdp_clk_ctrl(MDP_BLOCK_POWER_ON, false);
MDSS_MDP_REG_WRITE(off + MDSS_MDP_REG_INTF_TIMING_ENGINE_EN, 1);
ctx->timegen_en = true;
wmb();
}
wait_for_completion_interruptible(&ctx->vsync_comp);
mdss_mdp_irq_disable(intr_type, ctl->intf_num);
return 0;
}
int mdss_mdp_video_start(struct mdss_mdp_ctl *ctl)
{
struct msm_fb_data_type *mfd;
struct mdss_panel_info *pinfo;
struct mdss_mdp_video_ctx *ctx;
struct mdss_mdp_mixer *mixer;
struct intf_timing_params itp = {0};
struct fb_info *fbi;
int i;
mfd = ctl->mfd;
fbi = mfd->fbi;
pinfo = &mfd->panel_info;
mixer = mdss_mdp_mixer_get(ctl, MDSS_MDP_MIXER_MUX_LEFT);
if (!mixer) {
pr_err("mixer not setup correctly\n");
return -ENODEV;
}
pr_debug("start ctl=%u\n", ctl->num);
for (i = 0; i < MAX_SESSIONS; i++) {
ctx = &mdss_mdp_video_ctx_list[i];
if (ctx->ref_cnt == 0) {
ctx->ref_cnt++;
break;
}
}
if (i == MAX_SESSIONS) {
pr_err("too many sessions\n");
return -ENOMEM;
}
ctl->priv_data = ctx;
ctx->ctl_num = ctl->num;
ctx->pp_num = mixer->num;
init_completion(&ctx->pp_comp);
init_completion(&ctx->vsync_comp);
itp.width = pinfo->xres + pinfo->lcdc.xres_pad;
itp.height = pinfo->yres + pinfo->lcdc.yres_pad;
itp.border_clr = pinfo->lcdc.border_clr;
itp.underflow_clr = pinfo->lcdc.underflow_clr;
itp.hsync_skew = pinfo->lcdc.hsync_skew;
itp.xres = pinfo->xres;
itp.yres = pinfo->yres;
itp.h_back_porch = pinfo->lcdc.h_back_porch;
itp.h_front_porch = pinfo->lcdc.h_front_porch;
itp.v_back_porch = pinfo->lcdc.v_back_porch;
itp.v_front_porch = pinfo->lcdc.v_front_porch;
itp.hsync_pulse_width = pinfo->lcdc.h_pulse_width;
itp.vsync_pulse_width = pinfo->lcdc.v_pulse_width;
if (mdss_mdp_video_timegen_setup(ctl, &itp)) {
pr_err("unable to get timing parameters\n");
return -EINVAL;
}
ctl->stop_fnc = mdss_mdp_video_stop;
ctl->prepare_fnc = mdss_mdp_video_prepare;
ctl->display_fnc = mdss_mdp_video_display;
return 0;
}
| gpl-2.0 |
caplio/android_kernel_samsung_hltedcm | arch/arm/mach-msm/perf_event_msm_l2.c | 1784 | 26515 | /*
* Copyright (c) 2011-2013 The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/irq.h>
#include <asm/pmu.h>
#include <linux/platform_device.h>
#include <linux/spinlock.h>
#define MAX_SCORPION_L2_CTRS 10
#define SCORPION_L2CYCLE_CTR_BIT 31
#define SCORPION_L2CYCLE_CTR_RAW_CODE 0xfe
#define SCORPIONL2_PMNC_E (1 << 0) /* Enable all counters */
#define SCORPION_L2_EVT_PREFIX 3
#define SCORPION_MAX_L2_REG 4
#define L2_EVT_MASK 0xfffff
#define L2_EVT_PREFIX_MASK 0xf0000
#define L2_EVT_PREFIX_SHIFT 16
#define L2_SLAVE_EVT_PREFIX 4
#define PMCR_NUM_EV_SHIFT 11
#define PMCR_NUM_EV_MASK 0x1f
/*
* The L2 PMU is shared between all CPU's, so protect
* its bitmap access.
*/
struct pmu_constraints {
u64 pmu_bitmap;
u8 codes[64];
raw_spinlock_t lock;
} l2_pmu_constraints = {
.pmu_bitmap = 0,
.codes = {-1},
.lock = __RAW_SPIN_LOCK_UNLOCKED(l2_pmu_constraints.lock),
};
/* NRCCG format for perf RAW codes. */
PMU_FORMAT_ATTR(l2_prefix, "config:16-19");
PMU_FORMAT_ATTR(l2_reg, "config:12-15");
PMU_FORMAT_ATTR(l2_code, "config:4-11");
PMU_FORMAT_ATTR(l2_grp, "config:0-3");
static struct attribute *msm_l2_ev_formats[] = {
&format_attr_l2_prefix.attr,
&format_attr_l2_reg.attr,
&format_attr_l2_code.attr,
&format_attr_l2_grp.attr,
NULL,
};
/*
* Format group is essential to access PMU's from userspace
* via their .name field.
*/
static struct attribute_group msm_l2_pmu_format_group = {
.name = "format",
.attrs = msm_l2_ev_formats,
};
static const struct attribute_group *msm_l2_pmu_attr_grps[] = {
&msm_l2_pmu_format_group,
NULL,
};
static u32 total_l2_ctrs;
static u32 l2_cycle_ctr_idx;
static u32 pmu_type;
static struct arm_pmu scorpion_l2_pmu;
static u32 l2_orig_filter_prefix = 0x000f0030;
/* L2 slave port traffic filtering */
static u32 l2_slv_filter_prefix = 0x000f0010;
static struct perf_event *l2_events[MAX_SCORPION_L2_CTRS];
static unsigned long l2_used_mask[BITS_TO_LONGS(MAX_SCORPION_L2_CTRS)];
static struct pmu_hw_events scorpion_l2_pmu_hw_events = {
.events = l2_events,
.used_mask = l2_used_mask,
.pmu_lock =
__RAW_SPIN_LOCK_UNLOCKED(scorpion_l2_pmu_hw_events.pmu_lock),
};
struct scorpion_l2_scorp_evt {
u32 evt_type;
u32 val;
u8 grp;
u32 evt_type_act;
};
enum scorpion_perf_types {
SCORPIONL2_TOTAL_BANK_REQ = 0x90,
SCORPIONL2_DSIDE_READ = 0x91,
SCORPIONL2_DSIDE_WRITE = 0x92,
SCORPIONL2_ISIDE_READ = 0x93,
SCORPIONL2_L2CACHE_ISIDE_READ = 0x94,
SCORPIONL2_L2CACHE_BANK_REQ = 0x95,
SCORPIONL2_L2CACHE_DSIDE_READ = 0x96,
SCORPIONL2_L2CACHE_DSIDE_WRITE = 0x97,
SCORPIONL2_L2NOCACHE_DSIDE_WRITE = 0x98,
SCORPIONL2_L2NOCACHE_ISIDE_READ = 0x99,
SCORPIONL2_L2NOCACHE_TOTAL_REQ = 0x9a,
SCORPIONL2_L2NOCACHE_DSIDE_READ = 0x9b,
SCORPIONL2_DSIDE_READ_NOL1 = 0x9c,
SCORPIONL2_L2CACHE_WRITETHROUGH = 0x9d,
SCORPIONL2_BARRIERS = 0x9e,
SCORPIONL2_HARDWARE_TABLE_WALKS = 0x9f,
SCORPIONL2_MVA_POC = 0xa0,
SCORPIONL2_L2CACHE_HW_TABLE_WALKS = 0xa1,
SCORPIONL2_SETWAY_CACHE_OPS = 0xa2,
SCORPIONL2_DSIDE_WRITE_HITS = 0xa3,
SCORPIONL2_ISIDE_READ_HITS = 0xa4,
SCORPIONL2_CACHE_DSIDE_READ_NOL1 = 0xa5,
SCORPIONL2_TOTAL_CACHE_HITS = 0xa6,
SCORPIONL2_CACHE_MATCH_MISS = 0xa7,
SCORPIONL2_DREAD_HIT_L1_DATA = 0xa8,
SCORPIONL2_L2LINE_LOCKED = 0xa9,
SCORPIONL2_HW_TABLE_WALK_HIT = 0xaa,
SCORPIONL2_CACHE_MVA_POC = 0xab,
SCORPIONL2_L2ALLOC_DWRITE_MISS = 0xac,
SCORPIONL2_CORRECTED_TAG_ARRAY = 0xad,
SCORPIONL2_CORRECTED_DATA_ARRAY = 0xae,
SCORPIONL2_CORRECTED_REPLACEMENT_ARRAY = 0xaf,
SCORPIONL2_PMBUS_MPAAF = 0xb0,
SCORPIONL2_PMBUS_MPWDAF = 0xb1,
SCORPIONL2_PMBUS_MPBRT = 0xb2,
SCORPIONL2_CPU0_GRANT = 0xb3,
SCORPIONL2_CPU1_GRANT = 0xb4,
SCORPIONL2_CPU0_NOGRANT = 0xb5,
SCORPIONL2_CPU1_NOGRANT = 0xb6,
SCORPIONL2_CPU0_LOSING_ARB = 0xb7,
SCORPIONL2_CPU1_LOSING_ARB = 0xb8,
SCORPIONL2_SLAVEPORT_NOGRANT = 0xb9,
SCORPIONL2_SLAVEPORT_BPQ_FULL = 0xba,
SCORPIONL2_SLAVEPORT_LOSING_ARB = 0xbb,
SCORPIONL2_SLAVEPORT_GRANT = 0xbc,
SCORPIONL2_SLAVEPORT_GRANTLOCK = 0xbd,
SCORPIONL2_L2EM_STREX_PASS = 0xbe,
SCORPIONL2_L2EM_STREX_FAIL = 0xbf,
SCORPIONL2_LDREX_RESERVE_L2EM = 0xc0,
SCORPIONL2_SLAVEPORT_LDREX = 0xc1,
SCORPIONL2_CPU0_L2EM_CLEARED = 0xc2,
SCORPIONL2_CPU1_L2EM_CLEARED = 0xc3,
SCORPIONL2_SLAVEPORT_L2EM_CLEARED = 0xc4,
SCORPIONL2_CPU0_CLAMPED = 0xc5,
SCORPIONL2_CPU1_CLAMPED = 0xc6,
SCORPIONL2_CPU0_WAIT = 0xc7,
SCORPIONL2_CPU1_WAIT = 0xc8,
SCORPIONL2_CPU0_NONAMBAS_WAIT = 0xc9,
SCORPIONL2_CPU1_NONAMBAS_WAIT = 0xca,
SCORPIONL2_CPU0_DSB_WAIT = 0xcb,
SCORPIONL2_CPU1_DSB_WAIT = 0xcc,
SCORPIONL2_AXI_READ = 0xcd,
SCORPIONL2_AXI_WRITE = 0xce,
SCORPIONL2_1BEAT_WRITE = 0xcf,
SCORPIONL2_2BEAT_WRITE = 0xd0,
SCORPIONL2_4BEAT_WRITE = 0xd1,
SCORPIONL2_8BEAT_WRITE = 0xd2,
SCORPIONL2_12BEAT_WRITE = 0xd3,
SCORPIONL2_16BEAT_WRITE = 0xd4,
SCORPIONL2_1BEAT_DSIDE_READ = 0xd5,
SCORPIONL2_2BEAT_DSIDE_READ = 0xd6,
SCORPIONL2_4BEAT_DSIDE_READ = 0xd7,
SCORPIONL2_8BEAT_DSIDE_READ = 0xd8,
SCORPIONL2_CSYS_READ_1BEAT = 0xd9,
SCORPIONL2_CSYS_READ_2BEAT = 0xda,
SCORPIONL2_CSYS_READ_4BEAT = 0xdb,
SCORPIONL2_CSYS_READ_8BEAT = 0xdc,
SCORPIONL2_4BEAT_IFETCH_READ = 0xdd,
SCORPIONL2_8BEAT_IFETCH_READ = 0xde,
SCORPIONL2_CSYS_WRITE_1BEAT = 0xdf,
SCORPIONL2_CSYS_WRITE_2BEAT = 0xe0,
SCORPIONL2_AXI_READ_DATA_BEAT = 0xe1,
SCORPIONL2_AXI_WRITE_EVT1 = 0xe2,
SCORPIONL2_AXI_WRITE_EVT2 = 0xe3,
SCORPIONL2_LDREX_REQ = 0xe4,
SCORPIONL2_STREX_PASS = 0xe5,
SCORPIONL2_STREX_FAIL = 0xe6,
SCORPIONL2_CPREAD = 0xe7,
SCORPIONL2_CPWRITE = 0xe8,
SCORPIONL2_BARRIER_REQ = 0xe9,
SCORPIONL2_AXI_READ_SLVPORT = 0xea,
SCORPIONL2_AXI_WRITE_SLVPORT = 0xeb,
SCORPIONL2_AXI_READ_SLVPORT_DATABEAT = 0xec,
SCORPIONL2_AXI_WRITE_SLVPORT_DATABEAT = 0xed,
SCORPIONL2_SNOOPKILL_PREFILTER = 0xee,
SCORPIONL2_SNOOPKILL_FILTEROUT = 0xef,
SCORPIONL2_SNOOPED_IC = 0xf0,
SCORPIONL2_SNOOPED_BP = 0xf1,
SCORPIONL2_SNOOPED_BARRIERS = 0xf2,
SCORPIONL2_SNOOPED_TLB = 0xf3,
SCORPION_L2_MAX_EVT,
};
static const struct scorpion_l2_scorp_evt sc_evt[] = {
{SCORPIONL2_TOTAL_BANK_REQ, 0x80000001, 0, 0x00},
{SCORPIONL2_DSIDE_READ, 0x80000100, 0, 0x01},
{SCORPIONL2_DSIDE_WRITE, 0x80010000, 0, 0x02},
{SCORPIONL2_ISIDE_READ, 0x81000000, 0, 0x03},
{SCORPIONL2_L2CACHE_ISIDE_READ, 0x80000002, 0, 0x00},
{SCORPIONL2_L2CACHE_BANK_REQ, 0x80000200, 0, 0x01},
{SCORPIONL2_L2CACHE_DSIDE_READ, 0x80020000, 0, 0x02},
{SCORPIONL2_L2CACHE_DSIDE_WRITE, 0x82000000, 0, 0x03},
{SCORPIONL2_L2NOCACHE_DSIDE_WRITE, 0x80000003, 0, 0x00},
{SCORPIONL2_L2NOCACHE_ISIDE_READ, 0x80000300, 0, 0x01},
{SCORPIONL2_L2NOCACHE_TOTAL_REQ, 0x80030000, 0, 0x02},
{SCORPIONL2_L2NOCACHE_DSIDE_READ, 0x83000000, 0, 0x03},
{SCORPIONL2_DSIDE_READ_NOL1, 0x80000004, 0, 0x00},
{SCORPIONL2_L2CACHE_WRITETHROUGH, 0x80000400, 0, 0x01},
{SCORPIONL2_BARRIERS, 0x84000000, 0, 0x03},
{SCORPIONL2_HARDWARE_TABLE_WALKS, 0x80000005, 0, 0x00},
{SCORPIONL2_MVA_POC, 0x80000500, 0, 0x01},
{SCORPIONL2_L2CACHE_HW_TABLE_WALKS, 0x80050000, 0, 0x02},
{SCORPIONL2_SETWAY_CACHE_OPS, 0x85000000, 0, 0x03},
{SCORPIONL2_DSIDE_WRITE_HITS, 0x80000006, 0, 0x00},
{SCORPIONL2_ISIDE_READ_HITS, 0x80000600, 0, 0x01},
{SCORPIONL2_CACHE_DSIDE_READ_NOL1, 0x80060000, 0, 0x02},
{SCORPIONL2_TOTAL_CACHE_HITS, 0x86000000, 0, 0x03},
{SCORPIONL2_CACHE_MATCH_MISS, 0x80000007, 0, 0x00},
{SCORPIONL2_DREAD_HIT_L1_DATA, 0x87000000, 0, 0x03},
{SCORPIONL2_L2LINE_LOCKED, 0x80000008, 0, 0x00},
{SCORPIONL2_HW_TABLE_WALK_HIT, 0x80000800, 0, 0x01},
{SCORPIONL2_CACHE_MVA_POC, 0x80080000, 0, 0x02},
{SCORPIONL2_L2ALLOC_DWRITE_MISS, 0x88000000, 0, 0x03},
{SCORPIONL2_CORRECTED_TAG_ARRAY, 0x80001A00, 0, 0x01},
{SCORPIONL2_CORRECTED_DATA_ARRAY, 0x801A0000, 0, 0x02},
{SCORPIONL2_CORRECTED_REPLACEMENT_ARRAY, 0x9A000000, 0, 0x03},
{SCORPIONL2_PMBUS_MPAAF, 0x80001C00, 0, 0x01},
{SCORPIONL2_PMBUS_MPWDAF, 0x801C0000, 0, 0x02},
{SCORPIONL2_PMBUS_MPBRT, 0x9C000000, 0, 0x03},
{SCORPIONL2_CPU0_GRANT, 0x80000001, 1, 0x04},
{SCORPIONL2_CPU1_GRANT, 0x80000100, 1, 0x05},
{SCORPIONL2_CPU0_NOGRANT, 0x80020000, 1, 0x06},
{SCORPIONL2_CPU1_NOGRANT, 0x82000000, 1, 0x07},
{SCORPIONL2_CPU0_LOSING_ARB, 0x80040000, 1, 0x06},
{SCORPIONL2_CPU1_LOSING_ARB, 0x84000000, 1, 0x07},
{SCORPIONL2_SLAVEPORT_NOGRANT, 0x80000007, 1, 0x04},
{SCORPIONL2_SLAVEPORT_BPQ_FULL, 0x80000700, 1, 0x05},
{SCORPIONL2_SLAVEPORT_LOSING_ARB, 0x80070000, 1, 0x06},
{SCORPIONL2_SLAVEPORT_GRANT, 0x87000000, 1, 0x07},
{SCORPIONL2_SLAVEPORT_GRANTLOCK, 0x80000008, 1, 0x04},
{SCORPIONL2_L2EM_STREX_PASS, 0x80000009, 1, 0x04},
{SCORPIONL2_L2EM_STREX_FAIL, 0x80000900, 1, 0x05},
{SCORPIONL2_LDREX_RESERVE_L2EM, 0x80090000, 1, 0x06},
{SCORPIONL2_SLAVEPORT_LDREX, 0x89000000, 1, 0x07},
{SCORPIONL2_CPU0_L2EM_CLEARED, 0x800A0000, 1, 0x06},
{SCORPIONL2_CPU1_L2EM_CLEARED, 0x8A000000, 1, 0x07},
{SCORPIONL2_SLAVEPORT_L2EM_CLEARED, 0x80000B00, 1, 0x05},
{SCORPIONL2_CPU0_CLAMPED, 0x8000000E, 1, 0x04},
{SCORPIONL2_CPU1_CLAMPED, 0x80000E00, 1, 0x05},
{SCORPIONL2_CPU0_WAIT, 0x800F0000, 1, 0x06},
{SCORPIONL2_CPU1_WAIT, 0x8F000000, 1, 0x07},
{SCORPIONL2_CPU0_NONAMBAS_WAIT, 0x80000010, 1, 0x04},
{SCORPIONL2_CPU1_NONAMBAS_WAIT, 0x80001000, 1, 0x05},
{SCORPIONL2_CPU0_DSB_WAIT, 0x80000014, 1, 0x04},
{SCORPIONL2_CPU1_DSB_WAIT, 0x80001400, 1, 0x05},
{SCORPIONL2_AXI_READ, 0x80000001, 2, 0x08},
{SCORPIONL2_AXI_WRITE, 0x80000100, 2, 0x09},
{SCORPIONL2_1BEAT_WRITE, 0x80010000, 2, 0x0a},
{SCORPIONL2_2BEAT_WRITE, 0x80010000, 2, 0x0b},
{SCORPIONL2_4BEAT_WRITE, 0x80000002, 2, 0x08},
{SCORPIONL2_8BEAT_WRITE, 0x80000200, 2, 0x09},
{SCORPIONL2_12BEAT_WRITE, 0x80020000, 2, 0x0a},
{SCORPIONL2_16BEAT_WRITE, 0x82000000, 2, 0x0b},
{SCORPIONL2_1BEAT_DSIDE_READ, 0x80000003, 2, 0x08},
{SCORPIONL2_2BEAT_DSIDE_READ, 0x80000300, 2, 0x09},
{SCORPIONL2_4BEAT_DSIDE_READ, 0x80030000, 2, 0x0a},
{SCORPIONL2_8BEAT_DSIDE_READ, 0x83000000, 2, 0x0b},
{SCORPIONL2_CSYS_READ_1BEAT, 0x80000004, 2, 0x08},
{SCORPIONL2_CSYS_READ_2BEAT, 0x80000400, 2, 0x09},
{SCORPIONL2_CSYS_READ_4BEAT, 0x80040000, 2, 0x0a},
{SCORPIONL2_CSYS_READ_8BEAT, 0x84000000, 2, 0x0b},
{SCORPIONL2_4BEAT_IFETCH_READ, 0x80000005, 2, 0x08},
{SCORPIONL2_8BEAT_IFETCH_READ, 0x80000500, 2, 0x09},
{SCORPIONL2_CSYS_WRITE_1BEAT, 0x80050000, 2, 0x0a},
{SCORPIONL2_CSYS_WRITE_2BEAT, 0x85000000, 2, 0x0b},
{SCORPIONL2_AXI_READ_DATA_BEAT, 0x80000600, 2, 0x09},
{SCORPIONL2_AXI_WRITE_EVT1, 0x80060000, 2, 0x0a},
{SCORPIONL2_AXI_WRITE_EVT2, 0x86000000, 2, 0x0b},
{SCORPIONL2_LDREX_REQ, 0x80000007, 2, 0x08},
{SCORPIONL2_STREX_PASS, 0x80000700, 2, 0x09},
{SCORPIONL2_STREX_FAIL, 0x80070000, 2, 0x0a},
{SCORPIONL2_CPREAD, 0x80000008, 2, 0x08},
{SCORPIONL2_CPWRITE, 0x80000800, 2, 0x09},
{SCORPIONL2_BARRIER_REQ, 0x88000000, 2, 0x0b},
{SCORPIONL2_AXI_READ_SLVPORT, 0x80000001, 3, 0x0c},
{SCORPIONL2_AXI_WRITE_SLVPORT, 0x80000100, 3, 0x0d},
{SCORPIONL2_AXI_READ_SLVPORT_DATABEAT, 0x80010000, 3, 0x0e},
{SCORPIONL2_AXI_WRITE_SLVPORT_DATABEAT, 0x81000000, 3, 0x0f},
{SCORPIONL2_SNOOPKILL_PREFILTER, 0x80000001, 4, 0x10},
{SCORPIONL2_SNOOPKILL_FILTEROUT, 0x80000100, 4, 0x11},
{SCORPIONL2_SNOOPED_IC, 0x80000002, 4, 0x10},
{SCORPIONL2_SNOOPED_BP, 0x80000200, 4, 0x11},
{SCORPIONL2_SNOOPED_BARRIERS, 0x80020000, 4, 0x12},
{SCORPIONL2_SNOOPED_TLB, 0x82000000, 4, 0x13},
};
static struct pmu_hw_events *scorpion_l2_get_hw_events(void)
{
return &scorpion_l2_pmu_hw_events;
}
static u32 scorpion_l2_read_l2pm0(void)
{
u32 val;
asm volatile ("mrc p15, 3, %0, c15, c7, 0" : "=r" (val));
return val;
}
static void scorpion_l2_write_l2pm0(u32 val)
{
asm volatile ("mcr p15, 3, %0, c15, c7, 0" : : "r" (val));
}
static u32 scorpion_l2_read_l2pm1(void)
{
u32 val;
asm volatile ("mrc p15, 3, %0, c15, c7, 1" : "=r" (val));
return val;
}
static void scorpion_l2_write_l2pm1(u32 val)
{
asm volatile ("mcr p15, 3, %0, c15, c7, 1" : : "r" (val));
}
static u32 scorpion_l2_read_l2pm2(void)
{
u32 val;
asm volatile ("mrc p15, 3, %0, c15, c7, 2" : "=r" (val));
return val;
}
static void scorpion_l2_write_l2pm2(u32 val)
{
asm volatile ("mcr p15, 3, %0, c15, c7, 2" : : "r" (val));
}
static u32 scorpion_l2_read_l2pm3(void)
{
u32 val;
asm volatile ("mrc p15, 3, %0, c15, c7, 3" : "=r" (val));
return val;
}
static void scorpion_l2_write_l2pm3(u32 val)
{
asm volatile ("mcr p15, 3, %0, c15, c7, 3" : : "r" (val));
}
static u32 scorpion_l2_read_l2pm4(void)
{
u32 val;
asm volatile ("mrc p15, 3, %0, c15, c7, 4" : "=r" (val));
return val;
}
static void scorpion_l2_write_l2pm4(u32 val)
{
asm volatile ("mcr p15, 3, %0, c15, c7, 4" : : "r" (val));
}
struct scorpion_scorpion_access_funcs {
u32(*read) (void);
void (*write) (u32);
void (*pre) (void);
void (*post) (void);
};
struct scorpion_scorpion_access_funcs scorpion_l2_func[] = {
{scorpion_l2_read_l2pm0, scorpion_l2_write_l2pm0, NULL, NULL},
{scorpion_l2_read_l2pm1, scorpion_l2_write_l2pm1, NULL, NULL},
{scorpion_l2_read_l2pm2, scorpion_l2_write_l2pm2, NULL, NULL},
{scorpion_l2_read_l2pm3, scorpion_l2_write_l2pm3, NULL, NULL},
{scorpion_l2_read_l2pm4, scorpion_l2_write_l2pm4, NULL, NULL},
};
#define COLMN0MASK 0x000000ff
#define COLMN1MASK 0x0000ff00
#define COLMN2MASK 0x00ff0000
static u32 scorpion_l2_get_columnmask(u32 setval)
{
if (setval & COLMN0MASK)
return 0xffffff00;
else if (setval & COLMN1MASK)
return 0xffff00ff;
else if (setval & COLMN2MASK)
return 0xff00ffff;
else
return 0x80ffffff;
}
static void scorpion_l2_evt_setup(u32 gr, u32 setval)
{
u32 val;
if (scorpion_l2_func[gr].pre)
scorpion_l2_func[gr].pre();
val = scorpion_l2_get_columnmask(setval) & scorpion_l2_func[gr].read();
val = val | setval;
scorpion_l2_func[gr].write(val);
if (scorpion_l2_func[gr].post)
scorpion_l2_func[gr].post();
}
#define SCORPION_L2_EVT_START_IDX 0x90
#define SCORPION_L2_INV_EVTYPE 0
static unsigned int get_scorpion_l2_evtinfo(unsigned int evt_type,
struct scorpion_l2_scorp_evt *evtinfo)
{
u32 idx;
u8 prefix;
u8 reg;
u8 code;
u8 group;
prefix = (evt_type & 0xF0000) >> 16;
if (prefix == SCORPION_L2_EVT_PREFIX ||
prefix == L2_SLAVE_EVT_PREFIX) {
reg = (evt_type & 0x0F000) >> 12;
code = (evt_type & 0x00FF0) >> 4;
group = evt_type & 0x0000F;
if ((group > 3) || (reg > SCORPION_MAX_L2_REG))
return SCORPION_L2_INV_EVTYPE;
evtinfo->val = 0x80000000 | (code << (group * 8));
evtinfo->grp = reg;
evtinfo->evt_type_act = group | (reg << 2);
return evtinfo->evt_type_act;
}
if (evt_type < SCORPION_L2_EVT_START_IDX
|| evt_type >= SCORPION_L2_MAX_EVT)
return SCORPION_L2_INV_EVTYPE;
idx = evt_type - SCORPION_L2_EVT_START_IDX;
if (sc_evt[idx].evt_type == evt_type) {
evtinfo->val = sc_evt[idx].val;
evtinfo->grp = sc_evt[idx].grp;
evtinfo->evt_type_act = sc_evt[idx].evt_type_act;
return sc_evt[idx].evt_type_act;
}
return SCORPION_L2_INV_EVTYPE;
}
static inline void scorpion_l2_pmnc_write(unsigned long val)
{
val &= 0xff;
asm volatile ("mcr p15, 3, %0, c15, c4, 0" : : "r" (val));
}
static inline unsigned long scorpion_l2_pmnc_read(void)
{
u32 val;
asm volatile ("mrc p15, 3, %0, c15, c4, 0" : "=r" (val));
return val;
}
static void scorpion_l2_set_evcntcr(void)
{
u32 val = 0x0;
asm volatile ("mcr p15, 3, %0, c15, c6, 4" : : "r" (val));
}
static inline void scorpion_l2_set_evtyper(int ctr, int val)
{
/* select ctr */
asm volatile ("mcr p15, 3, %0, c15, c6, 0" : : "r" (ctr));
/* write into EVTYPER */
asm volatile ("mcr p15, 3, %0, c15, c6, 7" : : "r" (val));
}
static void scorpion_l2_set_evfilter_task_mode(unsigned int is_slv)
{
u32 filter_val = l2_orig_filter_prefix | 1 << smp_processor_id();
if (is_slv)
filter_val = l2_slv_filter_prefix;
asm volatile ("mcr p15, 3, %0, c15, c6, 3" : : "r" (filter_val));
}
static void scorpion_l2_set_evfilter_sys_mode(unsigned int is_slv)
{
u32 filter_val = l2_orig_filter_prefix | 0xf;
if (is_slv)
filter_val = l2_slv_filter_prefix;
asm volatile ("mcr p15, 3, %0, c15, c6, 3" : : "r" (filter_val));
}
static void scorpion_l2_enable_intenset(u32 idx)
{
if (idx == l2_cycle_ctr_idx) {
asm volatile ("mcr p15, 3, %0, c15, c5, 1" : : "r"
(1 << SCORPION_L2CYCLE_CTR_BIT));
} else {
asm volatile ("mcr p15, 3, %0, c15, c5, 1" : : "r" (1 << idx));
}
}
static void scorpion_l2_disable_intenclr(u32 idx)
{
if (idx == l2_cycle_ctr_idx) {
asm volatile ("mcr p15, 3, %0, c15, c5, 0" : : "r"
(1 << SCORPION_L2CYCLE_CTR_BIT));
} else {
asm volatile ("mcr p15, 3, %0, c15, c5, 0" : : "r" (1 << idx));
}
}
static void scorpion_l2_enable_counter(u32 idx)
{
if (idx == l2_cycle_ctr_idx) {
asm volatile ("mcr p15, 3, %0, c15, c4, 3" : : "r"
(1 << SCORPION_L2CYCLE_CTR_BIT));
} else {
asm volatile ("mcr p15, 3, %0, c15, c4, 3" : : "r" (1 << idx));
}
}
static void scorpion_l2_disable_counter(u32 idx)
{
if (idx == l2_cycle_ctr_idx) {
asm volatile ("mcr p15, 3, %0, c15, c4, 2" : : "r"
(1 << SCORPION_L2CYCLE_CTR_BIT));
} else {
asm volatile ("mcr p15, 3, %0, c15, c4, 2" : : "r" (1 << idx));
}
}
static u32 scorpion_l2_read_counter(int idx)
{
u32 val;
unsigned long iflags;
if (idx == l2_cycle_ctr_idx) {
asm volatile ("mrc p15, 3, %0, c15, c4, 5" : "=r" (val));
} else {
raw_spin_lock_irqsave(&scorpion_l2_pmu_hw_events.pmu_lock,
iflags);
asm volatile ("mcr p15, 3, %0, c15, c6, 0" : : "r" (idx));
/* read val from counter */
asm volatile ("mrc p15, 3, %0, c15, c6, 5" : "=r" (val));
raw_spin_unlock_irqrestore(&scorpion_l2_pmu_hw_events.pmu_lock,
iflags);
}
return val;
}
static void scorpion_l2_write_counter(int idx, u32 val)
{
unsigned long iflags;
if (idx == l2_cycle_ctr_idx) {
asm volatile ("mcr p15, 3, %0, c15, c4, 5" : : "r" (val));
} else {
raw_spin_lock_irqsave(&scorpion_l2_pmu_hw_events.pmu_lock,
iflags);
/* select counter */
asm volatile ("mcr p15, 3, %0, c15, c6, 0" : : "r" (idx));
/* write val into counter */
asm volatile ("mcr p15, 3, %0, c15, c6, 5" : : "r" (val));
raw_spin_unlock_irqrestore(&scorpion_l2_pmu_hw_events.pmu_lock,
iflags);
}
}
static void scorpion_l2_stop_counter(struct hw_perf_event *hwc, int idx)
{
scorpion_l2_disable_intenclr(idx);
scorpion_l2_disable_counter(idx);
pr_debug("%s: event: %ld ctr: %d stopped\n", __func__,
hwc->config_base, idx);
}
static void scorpion_l2_enable(struct hw_perf_event *hwc, int idx, int cpu)
{
struct scorpion_l2_scorp_evt evtinfo;
int evtype = hwc->config_base;
int ev_typer;
unsigned long iflags;
unsigned int is_slv = 0;
unsigned int evt_prefix;
raw_spin_lock_irqsave(&scorpion_l2_pmu_hw_events.pmu_lock, iflags);
if (hwc->config_base == SCORPION_L2CYCLE_CTR_RAW_CODE)
goto out;
/* Check if user requested any special origin filtering. */
evt_prefix = (hwc->config_base &
L2_EVT_PREFIX_MASK) >> L2_EVT_PREFIX_SHIFT;
if (evt_prefix == L2_SLAVE_EVT_PREFIX)
is_slv = 1;
memset(&evtinfo, 0, sizeof(evtinfo));
ev_typer = get_scorpion_l2_evtinfo(evtype, &evtinfo);
scorpion_l2_set_evtyper(idx, ev_typer);
scorpion_l2_set_evcntcr();
if (cpu < 0)
scorpion_l2_set_evfilter_task_mode(is_slv);
else
scorpion_l2_set_evfilter_sys_mode(is_slv);
scorpion_l2_evt_setup(evtinfo.grp, evtinfo.val);
out:
scorpion_l2_enable_intenset(idx);
scorpion_l2_enable_counter(idx);
raw_spin_unlock_irqrestore(&scorpion_l2_pmu_hw_events.pmu_lock, iflags);
pr_debug("%s: ctr: %d group: %ld group_code: %lld started from cpu:%d\n",
__func__, idx, hwc->config_base, hwc->config, smp_processor_id());
}
static void scorpion_l2_disable(struct hw_perf_event *hwc, int idx)
{
unsigned long iflags;
raw_spin_lock_irqsave(&scorpion_l2_pmu_hw_events.pmu_lock, iflags);
scorpion_l2_stop_counter(hwc, idx);
raw_spin_unlock_irqrestore(&scorpion_l2_pmu_hw_events.pmu_lock, iflags);
pr_debug("%s: event: %ld deleted\n", __func__, hwc->config_base);
}
static int scorpion_l2_get_event_idx(struct pmu_hw_events *cpuc,
struct hw_perf_event *hwc)
{
int ctr = 0;
if (hwc->config_base == SCORPION_L2CYCLE_CTR_RAW_CODE) {
if (test_and_set_bit(l2_cycle_ctr_idx,
cpuc->used_mask))
return -EAGAIN;
return l2_cycle_ctr_idx;
}
for (ctr = 0; ctr < total_l2_ctrs - 1; ctr++) {
if (!test_and_set_bit(ctr, cpuc->used_mask))
return ctr;
}
return -EAGAIN;
}
static void scorpion_l2_start(void)
{
isb();
/* Enable all counters */
scorpion_l2_pmnc_write(scorpion_l2_pmnc_read() | SCORPIONL2_PMNC_E);
}
static void scorpion_l2_stop(void)
{
/* Disable all counters */
scorpion_l2_pmnc_write(scorpion_l2_pmnc_read() & ~SCORPIONL2_PMNC_E);
isb();
}
static inline u32 scorpion_l2_get_reset_pmovsr(void)
{
u32 val;
/* Read */
asm volatile ("mrc p15, 3, %0, c15, c4, 1" : "=r" (val));
/* Write to clear flags */
val &= 0xffffffff;
asm volatile ("mcr p15, 3, %0, c15, c4, 1" : : "r" (val));
return val;
}
static irqreturn_t scorpion_l2_handle_irq(int irq_num, void *dev)
{
unsigned long pmovsr;
struct perf_sample_data data;
struct pt_regs *regs;
struct perf_event *event;
struct hw_perf_event *hwc;
int bitp;
int idx = 0;
pmovsr = scorpion_l2_get_reset_pmovsr();
if (!(pmovsr & 0xffffffff))
return IRQ_NONE;
regs = get_irq_regs();
perf_sample_data_init(&data, 0);
while (pmovsr) {
bitp = __ffs(pmovsr);
if (bitp == SCORPION_L2CYCLE_CTR_BIT)
idx = l2_cycle_ctr_idx;
else
idx = bitp;
event = scorpion_l2_pmu_hw_events.events[idx];
if (!event)
goto next;
if (!test_bit(idx, scorpion_l2_pmu_hw_events.used_mask))
goto next;
hwc = &event->hw;
armpmu_event_update(event, hwc, idx);
data.period = event->hw.last_period;
if (!armpmu_event_set_period(event, hwc, idx))
goto next;
if (perf_event_overflow(event, &data, regs))
scorpion_l2_disable_counter(hwc->idx);
next:
pmovsr &= (pmovsr - 1);
}
irq_work_run();
return IRQ_HANDLED;
}
static int scorpion_l2_map_event(struct perf_event *event)
{
if (pmu_type > 0 && pmu_type == event->attr.type)
return event->attr.config & L2_EVT_MASK;
else
return -ENOENT;
}
static int
scorpion_l2_pmu_generic_request_irq(int irq, irq_handler_t *handle_irq)
{
return request_irq(irq, *handle_irq,
IRQF_DISABLED | IRQF_NOBALANCING,
"scorpion-l2-armpmu", NULL);
}
static void
scorpion_l2_pmu_generic_free_irq(int irq)
{
if (irq >= 0)
free_irq(irq, NULL);
}
static int msm_l2_test_set_ev_constraint(struct perf_event *event)
{
u32 evt_type = event->attr.config & L2_EVT_MASK;
u8 prefix = (evt_type & 0xF0000) >> 16;
u8 reg = (evt_type & 0x0F000) >> 12;
u8 group = evt_type & 0x0000F;
u8 code = (evt_type & 0x00FF0) >> 4;
unsigned long flags;
u32 err = 0;
u64 bitmap_t;
u32 shift_idx;
if (!prefix)
return 0;
/*
* Cycle counter collision is detected in
* get_event_idx().
*/
if (evt_type == SCORPION_L2CYCLE_CTR_RAW_CODE)
return err;
raw_spin_lock_irqsave(&l2_pmu_constraints.lock, flags);
shift_idx = ((reg * 4) + group);
bitmap_t = 1 << shift_idx;
if (!(l2_pmu_constraints.pmu_bitmap & bitmap_t)) {
l2_pmu_constraints.pmu_bitmap |= bitmap_t;
l2_pmu_constraints.codes[shift_idx] = code;
goto out;
} else {
/*
* If NRCCG's are identical,
* its not column exclusion.
*/
if (l2_pmu_constraints.codes[shift_idx] != code)
err = -EPERM;
else
/*
* If the event is counted in syswide mode
* then we want to count only on one CPU
* and set its filter to count from all.
* This sets the event OFF on all but one
* CPU.
*/
if (!(event->cpu < 0))
event->state = PERF_EVENT_STATE_OFF;
}
out:
raw_spin_unlock_irqrestore(&l2_pmu_constraints.lock, flags);
return err;
}
static int msm_l2_clear_ev_constraint(struct perf_event *event)
{
u32 evt_type = event->attr.config & L2_EVT_MASK;
u8 prefix = (evt_type & 0xF0000) >> 16;
u8 reg = (evt_type & 0x0F000) >> 12;
u8 group = evt_type & 0x0000F;
unsigned long flags;
u64 bitmap_t;
u32 shift_idx;
if (!prefix)
return 0;
raw_spin_lock_irqsave(&l2_pmu_constraints.lock, flags);
shift_idx = ((reg * 4) + group);
bitmap_t = 1 << shift_idx;
/* Clear constraint bit. */
l2_pmu_constraints.pmu_bitmap &= ~bitmap_t;
raw_spin_unlock_irqrestore(&l2_pmu_constraints.lock, flags);
return 1;
}
static int get_num_events(void)
{
int val;
val = scorpion_l2_pmnc_read();
/*
* Read bits 15:11 of the L2PMCR and add 1
* for the cycle counter.
*/
return ((val >> PMCR_NUM_EV_SHIFT) & PMCR_NUM_EV_MASK) + 1;
}
static struct arm_pmu scorpion_l2_pmu = {
.id = ARM_PERF_PMU_ID_SCORPIONMP_L2,
.type = ARM_PMU_DEVICE_L2CC,
.name = "Scorpion L2CC PMU",
.start = scorpion_l2_start,
.stop = scorpion_l2_stop,
.handle_irq = scorpion_l2_handle_irq,
.request_pmu_irq = scorpion_l2_pmu_generic_request_irq,
.free_pmu_irq = scorpion_l2_pmu_generic_free_irq,
.enable = scorpion_l2_enable,
.disable = scorpion_l2_disable,
.read_counter = scorpion_l2_read_counter,
.get_event_idx = scorpion_l2_get_event_idx,
.write_counter = scorpion_l2_write_counter,
.map_event = scorpion_l2_map_event,
.max_period = (1LLU << 32) - 1,
.get_hw_events = scorpion_l2_get_hw_events,
.test_set_event_constraints = msm_l2_test_set_ev_constraint,
.clear_event_constraints = msm_l2_clear_ev_constraint,
.pmu.attr_groups = msm_l2_pmu_attr_grps,
};
static int __devinit scorpion_l2_pmu_device_probe(struct platform_device *pdev)
{
scorpion_l2_pmu.plat_device = pdev;
if (!armpmu_register(&scorpion_l2_pmu, "msm-l2", -1))
pmu_type = scorpion_l2_pmu.pmu.type;
return 0;
}
static struct platform_driver scorpion_l2_pmu_driver = {
.driver = {
.name = "l2-pmu",
},
.probe = scorpion_l2_pmu_device_probe,
};
static int __init register_scorpion_l2_pmu_driver(void)
{
/* Avoid spurious interrupt if any */
scorpion_l2_get_reset_pmovsr();
total_l2_ctrs = get_num_events();
scorpion_l2_pmu.num_events = total_l2_ctrs;
pr_info("Detected %d counters on the L2CC PMU.\n",
total_l2_ctrs);
/*
* The L2 cycle counter index in the used_mask
* bit stream is always after the other counters.
* Counter indexes begin from 0 to keep it consistent
* with the h/w.
*/
l2_cycle_ctr_idx = total_l2_ctrs - 1;
return platform_driver_register(&scorpion_l2_pmu_driver);
}
device_initcall(register_scorpion_l2_pmu_driver);
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.