diff options
211 files changed, 152422 insertions, 1 deletions
diff --git a/Documentation/sysctl/kernel.txt b/Documentation/sysctl/kernel.txt index e1ff0d920a5c..bde799e06598 100644 --- a/Documentation/sysctl/kernel.txt +++ b/Documentation/sysctl/kernel.txt @@ -369,4 +369,5 @@ can be ORed together: 2 - A module was force loaded by insmod -f. Set by modutils >= 2.4.9 and module-init-tools. 4 - Unsafe SMP processors: SMP with CPUs not designed for SMP. + 64 - A module from drivers/staging was loaded. diff --git a/MAINTAINERS b/MAINTAINERS index 52702b057c02..355c192d6997 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -3937,7 +3937,7 @@ M: jbglaw@lug-owl.de L: linux-kernel@vger.kernel.org S: Maintained -STABLE BRANCH: +STABLE BRANCH P: Greg Kroah-Hartman M: greg@kroah.com P: Chris Wright @@ -3945,6 +3945,13 @@ M: chrisw@sous-sol.org L: stable@kernel.org S: Maintained +STAGING SUBSYSTEM +P: Greg Kroah-Hartman +M: gregkh@suse.de +L: linux-kernel@vger.kernel.org +T: quilt kernel.org/pub/linux/kernel/people/gregkh/gregkh-2.6/ +S: Maintained + STARFIRE/DURALAN NETWORK DRIVER P: Ion Badulescu M: ionut@cs.columbia.edu diff --git a/drivers/Kconfig b/drivers/Kconfig index 59f33fa6af3e..d19b6f5a1106 100644 --- a/drivers/Kconfig +++ b/drivers/Kconfig @@ -101,4 +101,6 @@ source "drivers/auxdisplay/Kconfig" source "drivers/uio/Kconfig" source "drivers/xen/Kconfig" + +source "drivers/staging/Kconfig" endmenu diff --git a/drivers/Makefile b/drivers/Makefile index 2735bde73475..46c8681a07f4 100644 --- a/drivers/Makefile +++ b/drivers/Makefile @@ -99,3 +99,4 @@ obj-$(CONFIG_OF) += of/ obj-$(CONFIG_SSB) += ssb/ obj-$(CONFIG_VIRTIO) += virtio/ obj-$(CONFIG_REGULATOR) += regulator/ +obj-$(CONFIG_STAGING) += staging/ diff --git a/drivers/staging/Kconfig b/drivers/staging/Kconfig new file mode 100644 index 000000000000..2a79decd7dfc --- /dev/null +++ b/drivers/staging/Kconfig @@ -0,0 +1,46 @@ +menuconfig STAGING + bool "Staging drivers" + default n + ---help--- + This option allows you to select a number of drivers that are + not of the "normal" Linux kernel quality level. These drivers + are placed here in order to get a wider audience for use of + them. Please note that these drivers are under heavy + development, may or may not work, and may contain userspace + interfaces that most likely will be changed in the near + future. + + Using any of these drivers will taint your kernel which might + affect support options from both the community, and various + commercial support orginizations. + + If you wish to work on these drivers, to help improve them, or + to report problems you have with them, please see the + driver_name.README file in the drivers/staging/ directory to + see what needs to be worked on, and who to contact. + + If in doubt, say N here. + +if STAGING + +source "drivers/staging/et131x/Kconfig" + +source "drivers/staging/slicoss/Kconfig" + +source "drivers/staging/sxg/Kconfig" + +source "drivers/staging/me4000/Kconfig" + +source "drivers/staging/go7007/Kconfig" + +source "drivers/staging/usbip/Kconfig" + +source "drivers/staging/winbond/Kconfig" + +source "drivers/staging/wlan-ng/Kconfig" + +source "drivers/staging/echo/Kconfig" + +source "drivers/staging/at76_usb/Kconfig" + +endif # STAGING diff --git a/drivers/staging/Makefile b/drivers/staging/Makefile new file mode 100644 index 000000000000..325bca4f71c0 --- /dev/null +++ b/drivers/staging/Makefile @@ -0,0 +1,15 @@ +# Makefile for staging directory + +# fix for build system bug... +obj-$(CONFIG_STAGING) += staging.o + +obj-$(CONFIG_ET131X) += et131x/ +obj-$(CONFIG_SLICOSS) += slicoss/ +obj-$(CONFIG_SXG) += sxg/ +obj-$(CONFIG_ME4000) += me4000/ +obj-$(CONFIG_VIDEO_GO7007) += go7007/ +obj-$(CONFIG_USB_IP_COMMON) += usbip/ +obj-$(CONFIG_W35UND) += winbond/ +obj-$(CONFIG_PRISM2_USB) += wlan-ng/ +obj-$(CONFIG_ECHO) += echo/ +obj-$(CONFIG_USB_ATMEL) += at76_usb/ diff --git a/drivers/staging/at76_usb/Kconfig b/drivers/staging/at76_usb/Kconfig new file mode 100644 index 000000000000..8606f9621624 --- /dev/null +++ b/drivers/staging/at76_usb/Kconfig @@ -0,0 +1,8 @@ +config USB_ATMEL + tristate "Atmel at76c503/at76c505/at76c505a USB cards" + depends on WLAN_80211 && USB + default N + select FW_LOADER + ---help--- + Enable support for USB Wireless devices using Atmel at76c503, + at76c505 or at76c505a chips. diff --git a/drivers/staging/at76_usb/Makefile b/drivers/staging/at76_usb/Makefile new file mode 100644 index 000000000000..6a47e8872309 --- /dev/null +++ b/drivers/staging/at76_usb/Makefile @@ -0,0 +1 @@ +obj-$(CONFIG_USB_ATMEL) += at76_usb.o diff --git a/drivers/staging/at76_usb/TODO b/drivers/staging/at76_usb/TODO new file mode 100644 index 000000000000..6911ca71a41a --- /dev/null +++ b/drivers/staging/at76_usb/TODO @@ -0,0 +1,2 @@ +rewrite the driver to use the proper in-kernel wireless stack +instead of using its own. diff --git a/drivers/staging/at76_usb/at76_usb.c b/drivers/staging/at76_usb/at76_usb.c new file mode 100644 index 000000000000..52df0c665183 --- /dev/null +++ b/drivers/staging/at76_usb/at76_usb.c @@ -0,0 +1,5559 @@ +/* + * at76c503/at76c505 USB driver + * + * Copyright (c) 2002 - 2003 Oliver Kurth + * Copyright (c) 2004 Joerg Albert <joerg.albert@gmx.de> + * Copyright (c) 2004 Nick Jones + * Copyright (c) 2004 Balint Seeber <n0_5p4m_p13453@hotmail.com> + * Copyright (c) 2007 Guido Guenther <agx@sigxcpu.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 file is part of the Berlios driver for WLAN USB devices based on the + * Atmel AT76C503A/505/505A. + * + * Some iw_handler code was taken from airo.c, (C) 1999 Benjamin Reed + */ + +#include <linux/init.h> +#include <linux/kernel.h> +#include <linux/sched.h> +#include <linux/errno.h> +#include <linux/slab.h> +#include <linux/module.h> +#include <linux/spinlock.h> +#include <linux/list.h> +#include <linux/usb.h> +#include <linux/netdevice.h> +#include <linux/if_arp.h> +#include <linux/etherdevice.h> +#include <linux/ethtool.h> +#include <linux/wireless.h> +#include <net/iw_handler.h> +#include <net/ieee80211_radiotap.h> +#include <linux/firmware.h> +#include <linux/leds.h> +#include <net/ieee80211.h> + +#include "at76_usb.h" + +/* Version information */ +#define DRIVER_NAME "at76_usb" +#define DRIVER_VERSION "0.17" +#define DRIVER_DESC "Atmel at76x USB Wireless LAN Driver" + +/* at76_debug bits */ +#define DBG_PROGRESS 0x00000001 /* authentication/accociation */ +#define DBG_BSS_TABLE 0x00000002 /* show BSS table after scans */ +#define DBG_IOCTL 0x00000004 /* ioctl calls / settings */ +#define DBG_MAC_STATE 0x00000008 /* MAC state transitions */ +#define DBG_TX_DATA 0x00000010 /* tx header */ +#define DBG_TX_DATA_CONTENT 0x00000020 /* tx content */ +#define DBG_TX_MGMT 0x00000040 /* tx management */ +#define DBG_RX_DATA 0x00000080 /* rx data header */ +#define DBG_RX_DATA_CONTENT 0x00000100 /* rx data content */ +#define DBG_RX_MGMT 0x00000200 /* rx mgmt frame headers */ +#define DBG_RX_BEACON 0x00000400 /* rx beacon */ +#define DBG_RX_CTRL 0x00000800 /* rx control */ +#define DBG_RX_MGMT_CONTENT 0x00001000 /* rx mgmt content */ +#define DBG_RX_FRAGS 0x00002000 /* rx data fragment handling */ +#define DBG_DEVSTART 0x00004000 /* fw download, device start */ +#define DBG_URB 0x00008000 /* rx urb status, ... */ +#define DBG_RX_ATMEL_HDR 0x00010000 /* Atmel-specific Rx headers */ +#define DBG_PROC_ENTRY 0x00020000 /* procedure entries/exits */ +#define DBG_PM 0x00040000 /* power management settings */ +#define DBG_BSS_MATCH 0x00080000 /* BSS match failures */ +#define DBG_PARAMS 0x00100000 /* show configured parameters */ +#define DBG_WAIT_COMPLETE 0x00200000 /* command completion */ +#define DBG_RX_FRAGS_SKB 0x00400000 /* skb header of Rx fragments */ +#define DBG_BSS_TABLE_RM 0x00800000 /* purging bss table entries */ +#define DBG_MONITOR_MODE 0x01000000 /* monitor mode */ +#define DBG_MIB 0x02000000 /* dump all MIBs on startup */ +#define DBG_MGMT_TIMER 0x04000000 /* dump mgmt_timer ops */ +#define DBG_WE_EVENTS 0x08000000 /* dump wireless events */ +#define DBG_FW 0x10000000 /* firmware download */ +#define DBG_DFU 0x20000000 /* device firmware upgrade */ + +#define DBG_DEFAULTS 0 + +/* Use our own dbg macro */ +#define at76_dbg(bits, format, arg...) \ + do { \ + if (at76_debug & (bits)) \ + printk(KERN_DEBUG DRIVER_NAME ": " format "\n" , ## arg); \ + } while (0) + +static int at76_debug = DBG_DEFAULTS; + +/* Protect against concurrent firmware loading and parsing */ +static struct mutex fw_mutex; + +static struct fwentry firmwares[] = { + [0] = {""}, + [BOARD_503_ISL3861] = {"atmel_at76c503-i3861.bin"}, + [BOARD_503_ISL3863] = {"atmel_at76c503-i3863.bin"}, + [BOARD_503] = {"atmel_at76c503-rfmd.bin"}, + [BOARD_503_ACC] = {"atmel_at76c503-rfmd-acc.bin"}, + [BOARD_505] = {"atmel_at76c505-rfmd.bin"}, + [BOARD_505_2958] = {"atmel_at76c505-rfmd2958.bin"}, + [BOARD_505A] = {"atmel_at76c505a-rfmd2958.bin"}, + [BOARD_505AMX] = {"atmel_at76c505amx-rfmd.bin"}, +}; + +#define USB_DEVICE_DATA(__ops) .driver_info = (kernel_ulong_t)(__ops) + +static struct usb_device_id dev_table[] = { + /* + * at76c503-i3861 + */ + /* Generic AT76C503/3861 device */ + {USB_DEVICE(0x03eb, 0x7603), USB_DEVICE_DATA(BOARD_503_ISL3861)}, + /* Linksys WUSB11 v2.1/v2.6 */ + {USB_DEVICE(0x066b, 0x2211), USB_DEVICE_DATA(BOARD_503_ISL3861)}, + /* Netgear MA101 rev. A */ + {USB_DEVICE(0x0864, 0x4100), USB_DEVICE_DATA(BOARD_503_ISL3861)}, + /* Tekram U300C / Allnet ALL0193 */ + {USB_DEVICE(0x0b3b, 0x1612), USB_DEVICE_DATA(BOARD_503_ISL3861)}, + /* HP HN210W J7801A */ + {USB_DEVICE(0x03f0, 0x011c), USB_DEVICE_DATA(BOARD_503_ISL3861)}, + /* Sitecom/Z-Com/Zyxel M4Y-750 */ + {USB_DEVICE(0x0cde, 0x0001), USB_DEVICE_DATA(BOARD_503_ISL3861)}, + /* Dynalink/Askey WLL013 (intersil) */ + {USB_DEVICE(0x069a, 0x0320), USB_DEVICE_DATA(BOARD_503_ISL3861)}, + /* EZ connect 11Mpbs Wireless USB Adapter SMC2662W v1 */ + {USB_DEVICE(0x0d5c, 0xa001), USB_DEVICE_DATA(BOARD_503_ISL3861)}, + /* BenQ AWL300 */ + {USB_DEVICE(0x04a5, 0x9000), USB_DEVICE_DATA(BOARD_503_ISL3861)}, + /* Addtron AWU-120, Compex WLU11 */ + {USB_DEVICE(0x05dd, 0xff31), USB_DEVICE_DATA(BOARD_503_ISL3861)}, + /* Intel AP310 AnyPoint II USB */ + {USB_DEVICE(0x8086, 0x0200), USB_DEVICE_DATA(BOARD_503_ISL3861)}, + /* Dynalink L11U */ + {USB_DEVICE(0x0d8e, 0x7100), USB_DEVICE_DATA(BOARD_503_ISL3861)}, + /* Arescom WL-210, FCC id 07J-GL2411USB */ + {USB_DEVICE(0x0d8e, 0x7110), USB_DEVICE_DATA(BOARD_503_ISL3861)}, + /* I-O DATA WN-B11/USB */ + {USB_DEVICE(0x04bb, 0x0919), USB_DEVICE_DATA(BOARD_503_ISL3861)}, + /* BT Voyager 1010 */ + {USB_DEVICE(0x069a, 0x0821), USB_DEVICE_DATA(BOARD_503_ISL3861)}, + /* + * at76c503-i3863 + */ + /* Generic AT76C503/3863 device */ + {USB_DEVICE(0x03eb, 0x7604), USB_DEVICE_DATA(BOARD_503_ISL3863)}, + /* Samsung SWL-2100U */ + {USB_DEVICE(0x055d, 0xa000), USB_DEVICE_DATA(BOARD_503_ISL3863)}, + /* + * at76c503-rfmd + */ + /* Generic AT76C503/RFMD device */ + {USB_DEVICE(0x03eb, 0x7605), USB_DEVICE_DATA(BOARD_503)}, + /* Dynalink/Askey WLL013 (rfmd) */ + {USB_DEVICE(0x069a, 0x0321), USB_DEVICE_DATA(BOARD_503)}, + /* Linksys WUSB11 v2.6 */ + {USB_DEVICE(0x077b, 0x2219), USB_DEVICE_DATA(BOARD_503)}, + /* Network Everywhere NWU11B */ + {USB_DEVICE(0x077b, 0x2227), USB_DEVICE_DATA(BOARD_503)}, + /* Netgear MA101 rev. B */ + {USB_DEVICE(0x0864, 0x4102), USB_DEVICE_DATA(BOARD_503)}, + /* D-Link DWL-120 rev. E */ + {USB_DEVICE(0x2001, 0x3200), USB_DEVICE_DATA(BOARD_503)}, + /* Actiontec 802UAT1, HWU01150-01UK */ + {USB_DEVICE(0x1668, 0x7605), USB_DEVICE_DATA(BOARD_503)}, + /* AirVast W-Buddie WN210 */ + {USB_DEVICE(0x03eb, 0x4102), USB_DEVICE_DATA(BOARD_503)}, + /* Dick Smith Electronics XH1153 802.11b USB adapter */ + {USB_DEVICE(0x1371, 0x5743), USB_DEVICE_DATA(BOARD_503)}, + /* CNet CNUSB611 */ + {USB_DEVICE(0x1371, 0x0001), USB_DEVICE_DATA(BOARD_503)}, + /* FiberLine FL-WL200U */ + {USB_DEVICE(0x1371, 0x0002), USB_DEVICE_DATA(BOARD_503)}, + /* BenQ AWL400 USB stick */ + {USB_DEVICE(0x04a5, 0x9001), USB_DEVICE_DATA(BOARD_503)}, + /* 3Com 3CRSHEW696 */ + {USB_DEVICE(0x0506, 0x0a01), USB_DEVICE_DATA(BOARD_503)}, + /* Siemens Santis ADSL WLAN USB adapter WLL 013 */ + {USB_DEVICE(0x0681, 0x001b), USB_DEVICE_DATA(BOARD_503)}, + /* Belkin F5D6050, version 2 */ + {USB_DEVICE(0x050d, 0x0050), USB_DEVICE_DATA(BOARD_503)}, + /* iBlitzz, BWU613 (not *B or *SB) */ + {USB_DEVICE(0x07b8, 0xb000), USB_DEVICE_DATA(BOARD_503)}, + /* Gigabyte GN-WLBM101 */ + {USB_DEVICE(0x1044, 0x8003), USB_DEVICE_DATA(BOARD_503)}, + /* Planex GW-US11S */ + {USB_DEVICE(0x2019, 0x3220), USB_DEVICE_DATA(BOARD_503)}, + /* Internal WLAN adapter in h5[4,5]xx series iPAQs */ + {USB_DEVICE(0x049f, 0x0032), USB_DEVICE_DATA(BOARD_503)}, + /* Corega Wireless LAN USB-11 mini */ + {USB_DEVICE(0x07aa, 0x0011), USB_DEVICE_DATA(BOARD_503)}, + /* Corega Wireless LAN USB-11 mini2 */ + {USB_DEVICE(0x07aa, 0x0018), USB_DEVICE_DATA(BOARD_503)}, + /* Uniden PCW100 */ + {USB_DEVICE(0x05dd, 0xff35), USB_DEVICE_DATA(BOARD_503)}, + /* + * at76c503-rfmd-acc + */ + /* SMC2664W */ + {USB_DEVICE(0x083a, 0x3501), USB_DEVICE_DATA(BOARD_503_ACC)}, + /* Belkin F5D6050, SMC2662W v2, SMC2662W-AR */ + {USB_DEVICE(0x0d5c, 0xa002), USB_DEVICE_DATA(BOARD_503_ACC)}, + /* + * at76c505-rfmd + */ + /* Generic AT76C505/RFMD */ + {USB_DEVICE(0x03eb, 0x7606), USB_DEVICE_DATA(BOARD_505)}, + /* + * at76c505-rfmd2958 + */ + /* Generic AT76C505/RFMD, OvisLink WL-1130USB */ + {USB_DEVICE(0x03eb, 0x7613), USB_DEVICE_DATA(BOARD_505_2958)}, + /* Fiberline FL-WL240U */ + {USB_DEVICE(0x1371, 0x0014), USB_DEVICE_DATA(BOARD_505_2958)}, + /* CNet CNUSB-611G */ + {USB_DEVICE(0x1371, 0x0013), USB_DEVICE_DATA(BOARD_505_2958)}, + /* Linksys WUSB11 v2.8 */ + {USB_DEVICE(0x1915, 0x2233), USB_DEVICE_DATA(BOARD_505_2958)}, + /* Xterasys XN-2122B, IBlitzz BWU613B/BWU613SB */ + {USB_DEVICE(0x12fd, 0x1001), USB_DEVICE_DATA(BOARD_505_2958)}, + /* Corega WLAN USB Stick 11 */ + {USB_DEVICE(0x07aa, 0x7613), USB_DEVICE_DATA(BOARD_505_2958)}, + /* Microstar MSI Box MS6978 */ + {USB_DEVICE(0x0db0, 0x1020), USB_DEVICE_DATA(BOARD_505_2958)}, + /* + * at76c505a-rfmd2958 + */ + /* Generic AT76C505A device */ + {USB_DEVICE(0x03eb, 0x7614), USB_DEVICE_DATA(BOARD_505A)}, + /* Generic AT76C505AS device */ + {USB_DEVICE(0x03eb, 0x7617), USB_DEVICE_DATA(BOARD_505A)}, + /* Siemens Gigaset USB WLAN Adapter 11 */ + {USB_DEVICE(0x1690, 0x0701), USB_DEVICE_DATA(BOARD_505A)}, + /* + * at76c505amx-rfmd + */ + /* Generic AT76C505AMX device */ + {USB_DEVICE(0x03eb, 0x7615), USB_DEVICE_DATA(BOARD_505AMX)}, + {} +}; + +MODULE_DEVICE_TABLE(usb, dev_table); + +/* Supported rates of this hardware, bit 7 marks basic rates */ +static const u8 hw_rates[] = { 0x82, 0x84, 0x0b, 0x16 }; + +/* Frequency of each channel in MHz */ +static const long channel_frequency[] = { + 2412, 2417, 2422, 2427, 2432, 2437, 2442, + 2447, 2452, 2457, 2462, 2467, 2472, 2484 +}; + +#define NUM_CHANNELS ARRAY_SIZE(channel_frequency) + +static const char *const preambles[] = { "long", "short", "auto" }; + +static const char *const mac_states[] = { + [MAC_INIT] = "INIT", + [MAC_SCANNING] = "SCANNING", + [MAC_AUTH] = "AUTH", + [MAC_ASSOC] = "ASSOC", + [MAC_JOINING] = "JOINING", + [MAC_CONNECTED] = "CONNECTED", + [MAC_OWN_IBSS] = "OWN_IBSS" +}; + +/* Firmware download */ +/* DFU states */ +#define STATE_IDLE 0x00 +#define STATE_DETACH 0x01 +#define STATE_DFU_IDLE 0x02 +#define STATE_DFU_DOWNLOAD_SYNC 0x03 +#define STATE_DFU_DOWNLOAD_BUSY 0x04 +#define STATE_DFU_DOWNLOAD_IDLE 0x05 +#define STATE_DFU_MANIFEST_SYNC 0x06 +#define STATE_DFU_MANIFEST 0x07 +#define STATE_DFU_MANIFEST_WAIT_RESET 0x08 +#define STATE_DFU_UPLOAD_IDLE 0x09 +#define STATE_DFU_ERROR 0x0a + +/* DFU commands */ +#define DFU_DETACH 0 +#define DFU_DNLOAD 1 +#define DFU_UPLOAD 2 +#define DFU_GETSTATUS 3 +#define DFU_CLRSTATUS 4 +#define DFU_GETSTATE 5 +#define DFU_ABORT 6 + +#define FW_BLOCK_SIZE 1024 + +struct dfu_status { + unsigned char status; + unsigned char poll_timeout[3]; + unsigned char state; + unsigned char string; +} __attribute__((packed)); + +static inline int at76_is_intersil(enum board_type board) +{ + return (board == BOARD_503_ISL3861 || board == BOARD_503_ISL3863); +} + +static inline int at76_is_503rfmd(enum board_type board) +{ + return (board == BOARD_503 || board == BOARD_503_ACC); +} + +static inline int at76_is_505a(enum board_type board) +{ + return (board == BOARD_505A || board == BOARD_505AMX); +} + +/* Load a block of the first (internal) part of the firmware */ +static int at76_load_int_fw_block(struct usb_device *udev, int blockno, + void *block, int size) +{ + return usb_control_msg(udev, usb_sndctrlpipe(udev, 0), DFU_DNLOAD, + USB_TYPE_CLASS | USB_DIR_OUT | + USB_RECIP_INTERFACE, blockno, 0, block, size, + USB_CTRL_GET_TIMEOUT); +} + +static int at76_dfu_get_status(struct usb_device *udev, + struct dfu_status *status) +{ + int ret; + + ret = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), DFU_GETSTATUS, + USB_TYPE_CLASS | USB_DIR_IN | USB_RECIP_INTERFACE, + 0, 0, status, sizeof(struct dfu_status), + USB_CTRL_GET_TIMEOUT); + return ret; +} + +static u8 at76_dfu_get_state(struct usb_device *udev, u8 *state) +{ + int ret; + + ret = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), DFU_GETSTATE, + USB_TYPE_CLASS | USB_DIR_IN | USB_RECIP_INTERFACE, + 0, 0, state, 1, USB_CTRL_GET_TIMEOUT); + return ret; +} + +/* Convert timeout from the DFU status to jiffies */ +static inline unsigned long at76_get_timeout(struct dfu_status *s) +{ + return msecs_to_jiffies((s->poll_timeout[2] << 16) + | (s->poll_timeout[1] << 8) + | (s->poll_timeout[0])); +} + +/* Load internal firmware from the buffer. If manifest_sync_timeout > 0, use + * its value in jiffies in the MANIFEST_SYNC state. */ +static int at76_usbdfu_download(struct usb_device *udev, u8 *buf, u32 size, + int manifest_sync_timeout) +{ + u8 *block; + struct dfu_status dfu_stat_buf; + int ret = 0; + int need_dfu_state = 1; + int is_done = 0; + u8 dfu_state = 0; + u32 dfu_timeout = 0; + int bsize = 0; + int blockno = 0; + + at76_dbg(DBG_DFU, "%s( %p, %u, %d)", __func__, buf, size, + manifest_sync_timeout); + + if (!size) { + dev_printk(KERN_ERR, &udev->dev, "FW buffer length invalid!\n"); + return -EINVAL; + } + + block = kmalloc(FW_BLOCK_SIZE, GFP_KERNEL); + if (!block) + return -ENOMEM; + + do { + if (need_dfu_state) { + ret = at76_dfu_get_state(udev, &dfu_state); + if (ret < 0) { + dev_printk(KERN_ERR, &udev->dev, + "cannot get DFU state: %d\n", ret); + goto exit; + } + need_dfu_state = 0; + } + + switch (dfu_state) { + case STATE_DFU_DOWNLOAD_SYNC: + at76_dbg(DBG_DFU, "STATE_DFU_DOWNLOAD_SYNC"); + ret = at76_dfu_get_status(udev, &dfu_stat_buf); + if (ret >= 0) { + dfu_state = dfu_stat_buf.state; + dfu_timeout = at76_get_timeout(&dfu_stat_buf); + need_dfu_state = 0; + } else + dev_printk(KERN_ERR, &udev->dev, + "at76_dfu_get_status returned %d\n", + ret); + break; + + case STATE_DFU_DOWNLOAD_BUSY: + at76_dbg(DBG_DFU, "STATE_DFU_DOWNLOAD_BUSY"); + need_dfu_state = 1; + + at76_dbg(DBG_DFU, "DFU: Resetting device"); + schedule_timeout_interruptible(dfu_timeout); + break; + + case STATE_DFU_DOWNLOAD_IDLE: + at76_dbg(DBG_DFU, "DOWNLOAD..."); + /* fall through */ + case STATE_DFU_IDLE: + at76_dbg(DBG_DFU, "DFU IDLE"); + + bsize = min_t(int, size, FW_BLOCK_SIZE); + memcpy(block, buf, bsize); + at76_dbg(DBG_DFU, "int fw, size left = %5d, " + "bsize = %4d, blockno = %2d", size, bsize, + blockno); + ret = + at76_load_int_fw_block(udev, blockno, block, bsize); + buf += bsize; + size -= bsize; + blockno++; + + if (ret != bsize) + dev_printk(KERN_ERR, &udev->dev, + "at76_load_int_fw_block " + "returned %d\n", ret); + need_dfu_state = 1; + break; + + case STATE_DFU_MANIFEST_SYNC: + at76_dbg(DBG_DFU, "STATE_DFU_MANIFEST_SYNC"); + + ret = at76_dfu_get_status(udev, &dfu_stat_buf); + if (ret < 0) + break; + + dfu_state = dfu_stat_buf.state; + dfu_timeout = at76_get_timeout(&dfu_stat_buf); + need_dfu_state = 0; + + /* override the timeout from the status response, + needed for AT76C505A */ + if (manifest_sync_timeout > 0) + dfu_timeout = manifest_sync_timeout; + + at76_dbg(DBG_DFU, "DFU: Waiting for manifest phase"); + schedule_timeout_interruptible(dfu_timeout); + break; + + case STATE_DFU_MANIFEST: + at76_dbg(DBG_DFU, "STATE_DFU_MANIFEST"); + is_done = 1; + break; + + case STATE_DFU_MANIFEST_WAIT_RESET: + at76_dbg(DBG_DFU, "STATE_DFU_MANIFEST_WAIT_RESET"); + is_done = 1; + break; + + case STATE_DFU_UPLOAD_IDLE: + at76_dbg(DBG_DFU, "STATE_DFU_UPLOAD_IDLE"); + break; + + case STATE_DFU_ERROR: + at76_dbg(DBG_DFU, "STATE_DFU_ERROR"); + ret = -EPIPE; + break; + + default: + at76_dbg(DBG_DFU, "DFU UNKNOWN STATE (%d)", dfu_state); + ret = -EINVAL; + break; + } + } while (!is_done && (ret >= 0)); + +exit: + kfree(block); + if (ret >= 0) + ret = 0; + + return ret; +} + +/* Report that the scan results are ready */ +static inline void at76_iwevent_scan_complete(struct net_device *netdev) +{ + union iwreq_data wrqu; + wrqu.data.length = 0; + wrqu.data.flags = 0; + wireless_send_event(netdev, SIOCGIWSCAN, &wrqu, NULL); + at76_dbg(DBG_WE_EVENTS, "%s: SIOCGIWSCAN sent", netdev->name); +} + +static inline void at76_iwevent_bss_connect(struct net_device *netdev, + u8 *bssid) +{ + union iwreq_data wrqu; + wrqu.data.length = 0; + wrqu.data.flags = 0; + memcpy(wrqu.ap_addr.sa_data, bssid, ETH_ALEN); + wrqu.ap_addr.sa_family = ARPHRD_ETHER; + wireless_send_event(netdev, SIOCGIWAP, &wrqu, NULL); + at76_dbg(DBG_WE_EVENTS, "%s: %s: SIOCGIWAP sent", netdev->name, + __func__); +} + +static inline void at76_iwevent_bss_disconnect(struct net_device *netdev) +{ + union iwreq_data wrqu; + wrqu.data.length = 0; + wrqu.data.flags = 0; + memset(wrqu.ap_addr.sa_data, 0, ETH_ALEN); + wrqu.ap_addr.sa_family = ARPHRD_ETHER; + wireless_send_event(netdev, SIOCGIWAP, &wrqu, NULL); + at76_dbg(DBG_WE_EVENTS, "%s: %s: SIOCGIWAP sent", netdev->name, + __func__); +} + +#define HEX2STR_BUFFERS 4 +#define HEX2STR_MAX_LEN 64 +#define BIN2HEX(x) ((x) < 10 ? '0' + (x) : (x) + 'A' - 10) + +/* Convert binary data into hex string */ +static char *hex2str(void *buf, int len) +{ + static atomic_t a = ATOMIC_INIT(0); + static char bufs[HEX2STR_BUFFERS][3 * HEX2STR_MAX_LEN + 1]; + char *ret = bufs[atomic_inc_return(&a) & (HEX2STR_BUFFERS - 1)]; + char *obuf = ret; + u8 *ibuf = buf; + + if (len > HEX2STR_MAX_LEN) + len = HEX2STR_MAX_LEN; + + if (len <= 0) { + ret[0] = '\0'; + return ret; + } + + while (len--) { + *obuf++ = BIN2HEX(*ibuf >> 4); + *obuf++ = BIN2HEX(*ibuf & 0xf); + *obuf++ = '-'; + ibuf++; + } + *(--obuf) = '\0'; + + return ret; +} + +#define MAC2STR_BUFFERS 4 + +static inline char *mac2str(u8 *mac) +{ + static atomic_t a = ATOMIC_INIT(0); + static char bufs[MAC2STR_BUFFERS][6 * 3]; + char *str; + + str = bufs[atomic_inc_return(&a) & (MAC2STR_BUFFERS - 1)]; + sprintf(str, "%02x:%02x:%02x:%02x:%02x:%02x", + mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); + return str; +} + +/* LED trigger */ +static int tx_activity; +static void at76_ledtrig_tx_timerfunc(unsigned long data); +static DEFINE_TIMER(ledtrig_tx_timer, at76_ledtrig_tx_timerfunc, 0, 0); +DEFINE_LED_TRIGGER(ledtrig_tx); + +static void at76_ledtrig_tx_timerfunc(unsigned long data) +{ + static int tx_lastactivity; + + if (tx_lastactivity != tx_activity) { + tx_lastactivity = tx_activity; + led_trigger_event(ledtrig_tx, LED_FULL); + mod_timer(&ledtrig_tx_timer, jiffies + HZ / 4); + } else + led_trigger_event(ledtrig_tx, LED_OFF); +} + +static void at76_ledtrig_tx_activity(void) +{ + tx_activity++; + if (!timer_pending(&ledtrig_tx_timer)) + mod_timer(&ledtrig_tx_timer, jiffies + HZ / 4); +} + +/* Check if the given ssid is hidden */ +static inline int at76_is_hidden_ssid(u8 *ssid, int length) +{ + static const u8 zeros[32]; + + if (length == 0) + return 1; + + if (length == 1 && ssid[0] == ' ') + return 1; + + return (memcmp(ssid, zeros, length) == 0); +} + +static inline void at76_free_bss_list(struct at76_priv *priv) +{ + struct list_head *next, *ptr; + unsigned long flags; + + spin_lock_irqsave(&priv->bss_list_spinlock, flags); + + priv->curr_bss = NULL; + + list_for_each_safe(ptr, next, &priv->bss_list) { + list_del(ptr); + kfree(list_entry(ptr, struct bss_info, list)); + } + + spin_unlock_irqrestore(&priv->bss_list_spinlock, flags); +} + +static int at76_remap(struct usb_device *udev) +{ + int ret; + ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x0a, + USB_TYPE_VENDOR | USB_DIR_OUT | + USB_RECIP_INTERFACE, 0, 0, NULL, 0, + USB_CTRL_GET_TIMEOUT); + if (ret < 0) + return ret; + return 0; +} + +static int at76_get_op_mode(struct usb_device *udev) +{ + int ret; + u8 op_mode; + + ret = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x33, + USB_TYPE_VENDOR | USB_DIR_IN | + USB_RECIP_INTERFACE, 0x01, 0, &op_mode, 1, + USB_CTRL_GET_TIMEOUT); + if (ret < 0) + return ret; + else if (ret < 1) + return -EIO; + else + return op_mode; +} + +/* Load a block of the second ("external") part of the firmware */ +static inline int at76_load_ext_fw_block(struct usb_device *udev, int blockno, + void *block, int size) +{ + return usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x0e, + USB_TYPE_VENDOR | USB_DIR_OUT | USB_RECIP_DEVICE, + 0x0802, blockno, block, size, + USB_CTRL_GET_TIMEOUT); +} + +static inline int at76_get_hw_cfg(struct usb_device *udev, + union at76_hwcfg *buf, int buf_size) +{ + return usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x33, + USB_TYPE_VENDOR | USB_DIR_IN | + USB_RECIP_INTERFACE, 0x0a02, 0, + buf, buf_size, USB_CTRL_GET_TIMEOUT); +} + +/* Intersil boards use a different "value" for GetHWConfig requests */ +static inline int at76_get_hw_cfg_intersil(struct usb_device *udev, + union at76_hwcfg *buf, int buf_size) +{ + return usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x33, + USB_TYPE_VENDOR | USB_DIR_IN | + USB_RECIP_INTERFACE, 0x0902, 0, + buf, buf_size, USB_CTRL_GET_TIMEOUT); +} + +/* Get the hardware configuration for the adapter and put it to the appropriate + * fields of 'priv' (the GetHWConfig request and interpretation of the result + * depends on the board type) */ +static int at76_get_hw_config(struct at76_priv *priv) +{ + int ret; + union at76_hwcfg *hwcfg = kmalloc(sizeof(*hwcfg), GFP_KERNEL); + + if (!hwcfg) + return -ENOMEM; + + if (at76_is_intersil(priv->board_type)) { + ret = at76_get_hw_cfg_intersil(priv->udev, hwcfg, + sizeof(hwcfg->i)); + if (ret < 0) + goto exit; + memcpy(priv->mac_addr, hwcfg->i.mac_addr, ETH_ALEN); + priv->regulatory_domain = hwcfg->i.regulatory_domain; + } else if (at76_is_503rfmd(priv->board_type)) { + ret = at76_get_hw_cfg(priv->udev, hwcfg, sizeof(hwcfg->r3)); + if (ret < 0) + goto exit; + memcpy(priv->mac_addr, hwcfg->r3.mac_addr, ETH_ALEN); + priv->regulatory_domain = hwcfg->r3.regulatory_domain; + } else { + ret = at76_get_hw_cfg(priv->udev, hwcfg, sizeof(hwcfg->r5)); + if (ret < 0) + goto exit; + memcpy(priv->mac_addr, hwcfg->r5.mac_addr, ETH_ALEN); + priv->regulatory_domain = hwcfg->r5.regulatory_domain; + } + +exit: + kfree(hwcfg); + if (ret < 0) + printk(KERN_ERR "%s: cannot get HW Config (error %d)\n", + priv->netdev->name, ret); + + return ret; +} + +static struct reg_domain const *at76_get_reg_domain(u16 code) +{ + int i; + static struct reg_domain const fd_tab[] = { + {0x10, "FCC (USA)", 0x7ff}, /* ch 1-11 */ + {0x20, "IC (Canada)", 0x7ff}, /* ch 1-11 */ + {0x30, "ETSI (most of Europe)", 0x1fff}, /* ch 1-13 */ + {0x31, "Spain", 0x600}, /* ch 10-11 */ + {0x32, "France", 0x1e00}, /* ch 10-13 */ + {0x40, "MKK (Japan)", 0x2000}, /* ch 14 */ + {0x41, "MKK1 (Japan)", 0x3fff}, /* ch 1-14 */ + {0x50, "Israel", 0x3fc}, /* ch 3-9 */ + {0x00, "<unknown>", 0xffffffff} /* ch 1-32 */ + }; + + /* Last entry is fallback for unknown domain code */ + for (i = 0; i < ARRAY_SIZE(fd_tab) - 1; i++) + if (code == fd_tab[i].code) + break; + + return &fd_tab[i]; +} + +static inline int at76_get_mib(struct usb_device *udev, u16 mib, void *buf, + int buf_size) +{ + int ret; + + ret = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x33, + USB_TYPE_VENDOR | USB_DIR_IN | + USB_RECIP_INTERFACE, mib << 8, 0, buf, buf_size, + USB_CTRL_GET_TIMEOUT); + if (ret >= 0 && ret != buf_size) + return -EIO; + return ret; +} + +/* Return positive number for status, negative for an error */ +static inline int at76_get_cmd_status(struct usb_device *udev, u8 cmd) +{ + u8 stat_buf[40]; + int ret; + + ret = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x22, + USB_TYPE_VENDOR | USB_DIR_IN | + USB_RECIP_INTERFACE, cmd, 0, stat_buf, + sizeof(stat_buf), USB_CTRL_GET_TIMEOUT); + if (ret < 0) + return ret; + + return stat_buf[5]; +} + +static int at76_set_card_command(struct usb_device *udev, int cmd, void *buf, + int buf_size) +{ + int ret; + struct at76_command *cmd_buf = kmalloc(sizeof(struct at76_command) + + buf_size, GFP_KERNEL); + + if (!cmd_buf) + return -ENOMEM; + + cmd_buf->cmd = cmd; + cmd_buf->reserved = 0; + cmd_buf->size = cpu_to_le16(buf_size); + memcpy(cmd_buf->data, buf, buf_size); + + ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x0e, + USB_TYPE_VENDOR | USB_DIR_OUT | USB_RECIP_DEVICE, + 0, 0, cmd_buf, + sizeof(struct at76_command) + buf_size, + USB_CTRL_GET_TIMEOUT); + kfree(cmd_buf); + return ret; +} + +#define MAKE_CMD_STATUS_CASE(c) case (c): return #c +static const char *at76_get_cmd_status_string(u8 cmd_status) +{ + switch (cmd_status) { + MAKE_CMD_STATUS_CASE(CMD_STATUS_IDLE); + MAKE_CMD_STATUS_CASE(CMD_STATUS_COMPLETE); + MAKE_CMD_STATUS_CASE(CMD_STATUS_UNKNOWN); + MAKE_CMD_STATUS_CASE(CMD_STATUS_INVALID_PARAMETER); + MAKE_CMD_STATUS_CASE(CMD_STATUS_FUNCTION_NOT_SUPPORTED); + MAKE_CMD_STATUS_CASE(CMD_STATUS_TIME_OUT); + MAKE_CMD_STATUS_CASE(CMD_STATUS_IN_PROGRESS); + MAKE_CMD_STATUS_CASE(CMD_STATUS_HOST_FAILURE); + MAKE_CMD_STATUS_CASE(CMD_STATUS_SCAN_FAILED); + } + + return "UNKNOWN"; +} + +/* Wait until the command is completed */ +static int at76_wait_completion(struct at76_priv *priv, int cmd) +{ + int status = 0; + unsigned long timeout = jiffies + CMD_COMPLETION_TIMEOUT; + + do { + status = at76_get_cmd_status(priv->udev, cmd); + if (status < 0) { + printk(KERN_ERR "%s: at76_get_cmd_status failed: %d\n", + priv->netdev->name, status); + break; + } + + at76_dbg(DBG_WAIT_COMPLETE, + "%s: Waiting on cmd %d, status = %d (%s)", + priv->netdev->name, cmd, status, + at76_get_cmd_status_string(status)); + + if (status != CMD_STATUS_IN_PROGRESS + && status != CMD_STATUS_IDLE) + break; + + schedule_timeout_interruptible(HZ / 10); /* 100 ms */ + if (time_after(jiffies, timeout)) { + printk(KERN_ERR + "%s: completion timeout for command %d\n", + priv->netdev->name, cmd); + status = -ETIMEDOUT; + break; + } + } while (1); + + return status; +} + +static int at76_set_mib(struct at76_priv *priv, struct set_mib_buffer *buf) +{ + int ret; + + ret = at76_set_card_command(priv->udev, CMD_SET_MIB, buf, + offsetof(struct set_mib_buffer, + data) + buf->size); + if (ret < 0) + return ret; + + ret = at76_wait_completion(priv, CMD_SET_MIB); + if (ret != CMD_STATUS_COMPLETE) { + printk(KERN_INFO + "%s: set_mib: at76_wait_completion failed " + "with %d\n", priv->netdev->name, ret); + ret = -EIO; + } + + return ret; +} + +/* Return < 0 on error, == 0 if no command sent, == 1 if cmd sent */ +static int at76_set_radio(struct at76_priv *priv, int enable) +{ + int ret; + int cmd; + + if (priv->radio_on == enable) + return 0; + + cmd = enable ? CMD_RADIO_ON : CMD_RADIO_OFF; + + ret = at76_set_card_command(priv->udev, cmd, NULL, 0); + if (ret < 0) + printk(KERN_ERR "%s: at76_set_card_command(%d) failed: %d\n", + priv->netdev->name, cmd, ret); + else + ret = 1; + + priv->radio_on = enable; + return ret; +} + +/* Set current power save mode (AT76_PM_OFF/AT76_PM_ON/AT76_PM_SMART) */ +static int at76_set_pm_mode(struct at76_priv *priv) +{ + int ret = 0; + + priv->mib_buf.type = MIB_MAC_MGMT; + priv->mib_buf.size = 1; + priv->mib_buf.index = offsetof(struct mib_mac_mgmt, power_mgmt_mode); + priv->mib_buf.data.byte = priv->pm_mode; + + ret = at76_set_mib(priv, &priv->mib_buf); + if (ret < 0) + printk(KERN_ERR "%s: set_mib (pm_mode) failed: %d\n", + priv->netdev->name, ret); + + return ret; +} + +/* Set the association id for power save mode */ +static int at76_set_associd(struct at76_priv *priv, u16 id) +{ + int ret = 0; + + priv->mib_buf.type = MIB_MAC_MGMT; + priv->mib_buf.size = 2; + priv->mib_buf.index = offsetof(struct mib_mac_mgmt, station_id); + priv->mib_buf.data.word = cpu_to_le16(id); + + ret = at76_set_mib(priv, &priv->mib_buf); + if (ret < 0) + printk(KERN_ERR "%s: set_mib (associd) failed: %d\n", + priv->netdev->name, ret); + + return ret; +} + +/* Set the listen interval for power save mode */ +static int at76_set_listen_interval(struct at76_priv *priv, u16 interval) +{ + int ret = 0; + + priv->mib_buf.type = MIB_MAC; + priv->mib_buf.size = 2; + priv->mib_buf.index = offsetof(struct mib_mac, listen_interval); + priv->mib_buf.data.word = cpu_to_le16(interval); + + ret = at76_set_mib(priv, &priv->mib_buf); + if (ret < 0) + printk(KERN_ERR + "%s: set_mib (listen_interval) failed: %d\n", + priv->netdev->name, ret); + + return ret; +} + +static int at76_set_preamble(struct at76_priv *priv, u8 type) +{ + int ret = 0; + + priv->mib_buf.type = MIB_LOCAL; + priv->mib_buf.size = 1; + priv->mib_buf.index = offsetof(struct mib_local, preamble_type); + priv->mib_buf.data.byte = type; + + ret = at76_set_mib(priv, &priv->mib_buf); + if (ret < 0) + printk(KERN_ERR "%s: set_mib (preamble) failed: %d\n", + priv->netdev->name, ret); + + return ret; +} + +static int at76_set_frag(struct at76_priv *priv, u16 size) +{ + int ret = 0; + + priv->mib_buf.type = MIB_MAC; + priv->mib_buf.size = 2; + priv->mib_buf.index = offsetof(struct mib_mac, frag_threshold); + priv->mib_buf.data.word = cpu_to_le16(size); + + ret = at76_set_mib(priv, &priv->mib_buf); + if (ret < 0) + printk(KERN_ERR "%s: set_mib (frag threshold) failed: %d\n", + priv->netdev->name, ret); + + return ret; +} + +static int at76_set_rts(struct at76_priv *priv, u16 size) +{ + int ret = 0; + + priv->mib_buf.type = MIB_MAC; + priv->mib_buf.size = 2; + priv->mib_buf.index = offsetof(struct mib_mac, rts_threshold); + priv->mib_buf.data.word = cpu_to_le16(size); + + ret = at76_set_mib(priv, &priv->mib_buf); + if (ret < 0) + printk(KERN_ERR "%s: set_mib (rts) failed: %d\n", + priv->netdev->name, ret); + + return ret; +} + +static int at76_set_autorate_fallback(struct at76_priv *priv, int onoff) +{ + int ret = 0; + + priv->mib_buf.type = MIB_LOCAL; + priv->mib_buf.size = 1; + priv->mib_buf.index = offsetof(struct mib_local, txautorate_fallback); + priv->mib_buf.data.byte = onoff; + + ret = at76_set_mib(priv, &priv->mib_buf); + if (ret < 0) + printk(KERN_ERR "%s: set_mib (autorate fallback) failed: %d\n", + priv->netdev->name, ret); + + return ret; +} + +static int at76_add_mac_address(struct at76_priv *priv, void *addr) +{ + int ret = 0; + + priv->mib_buf.type = MIB_MAC_ADDR; + priv->mib_buf.size = ETH_ALEN; + priv->mib_buf.index = offsetof(struct mib_mac_addr, mac_addr); + memcpy(priv->mib_buf.data.addr, addr, ETH_ALEN); + + ret = at76_set_mib(priv, &priv->mib_buf); + if (ret < 0) + printk(KERN_ERR "%s: set_mib (MAC_ADDR, mac_addr) failed: %d\n", + priv->netdev->name, ret); + + return ret; +} + +static void at76_dump_mib_mac_addr(struct at76_priv *priv) +{ + int i; + int ret; + struct mib_mac_addr *m = kmalloc(sizeof(struct mib_mac_addr), + GFP_KERNEL); + + if (!m) + return; + + ret = at76_get_mib(priv->udev, MIB_MAC_ADDR, m, + sizeof(struct mib_mac_addr)); + if (ret < 0) { + printk(KERN_ERR "%s: at76_get_mib (MAC_ADDR) failed: %d\n", + priv->netdev->name, ret); + goto exit; + } + + at76_dbg(DBG_MIB, "%s: MIB MAC_ADDR: mac_addr %s res 0x%x 0x%x", + priv->netdev->name, + mac2str(m->mac_addr), m->res[0], m->res[1]); + for (i = 0; i < ARRAY_SIZE(m->group_addr); i++) + at76_dbg(DBG_MIB, "%s: MIB MAC_ADDR: group addr %d: %s, " + "status %d", priv->netdev->name, i, + mac2str(m->group_addr[i]), m->group_addr_status[i]); +exit: + kfree(m); +} + +static void at76_dump_mib_mac_wep(struct at76_priv *priv) +{ + int i; + int ret; + int key_len; + struct mib_mac_wep *m = kmalloc(sizeof(struct mib_mac_wep), GFP_KERNEL); + + if (!m) + return; + + ret = at76_get_mib(priv->udev, MIB_MAC_WEP, m, + sizeof(struct mib_mac_wep)); + if (ret < 0) { + printk(KERN_ERR "%s: at76_get_mib (MAC_WEP) failed: %d\n", + priv->netdev->name, ret); + goto exit; + } + + at76_dbg(DBG_MIB, "%s: MIB MAC_WEP: priv_invoked %u def_key_id %u " + "key_len %u excl_unencr %u wep_icv_err %u wep_excluded %u " + "encr_level %u key %d", priv->netdev->name, + m->privacy_invoked, m->wep_default_key_id, + m->wep_key_mapping_len, m->exclude_unencrypted, + le32_to_cpu(m->wep_icv_error_count), + le32_to_cpu(m->wep_excluded_count), m->encryption_level, + m->wep_default_key_id); + + key_len = (m->encryption_level == 1) ? + WEP_SMALL_KEY_LEN : WEP_LARGE_KEY_LEN; + + for (i = 0; i < WEP_KEYS; i++) + at76_dbg(DBG_MIB, "%s: MIB MAC_WEP: key %d: %s", + priv->netdev->name, i, + hex2str(m->wep_default_keyvalue[i], key_len)); +exit: + kfree(m); +} + +static void at76_dump_mib_mac_mgmt(struct at76_priv *priv) +{ + int ret; + struct mib_mac_mgmt *m = kmalloc(sizeof(struct mib_mac_mgmt), + GFP_KERNEL); + + if (!m) + return; + + ret = at76_get_mib(priv->udev, MIB_MAC_MGMT, m, + sizeof(struct mib_mac_mgmt)); + if (ret < 0) { + printk(KERN_ERR "%s: at76_get_mib (MAC_MGMT) failed: %d\n", + priv->netdev->name, ret); + goto exit; + } + + at76_dbg(DBG_MIB, "%s: MIB MAC_MGMT: beacon_period %d CFP_max_duration " + "%d medium_occupancy_limit %d station_id 0x%x ATIM_window %d " + "CFP_mode %d privacy_opt_impl %d DTIM_period %d CFP_period %d " + "current_bssid %s current_essid %s current_bss_type %d " + "pm_mode %d ibss_change %d res %d " + "multi_domain_capability_implemented %d " + "international_roaming %d country_string %.3s", + priv->netdev->name, le16_to_cpu(m->beacon_period), + le16_to_cpu(m->CFP_max_duration), + le16_to_cpu(m->medium_occupancy_limit), + le16_to_cpu(m->station_id), le16_to_cpu(m->ATIM_window), + m->CFP_mode, m->privacy_option_implemented, m->DTIM_period, + m->CFP_period, mac2str(m->current_bssid), + hex2str(m->current_essid, IW_ESSID_MAX_SIZE), + m->current_bss_type, m->power_mgmt_mode, m->ibss_change, + m->res, m->multi_domain_capability_implemented, + m->multi_domain_capability_enabled, m->country_string); +exit: + kfree(m); +} + +static void at76_dump_mib_mac(struct at76_priv *priv) +{ + int ret; + struct mib_mac *m = kmalloc(sizeof(struct mib_mac), GFP_KERNEL); + + if (!m) + return; + + ret = at76_get_mib(priv->udev, MIB_MAC, m, sizeof(struct mib_mac)); + if (ret < 0) { + printk(KERN_ERR "%s: at76_get_mib (MAC) failed: %d\n", + priv->netdev->name, ret); + goto exit; + } + + at76_dbg(DBG_MIB, "%s: MIB MAC: max_tx_msdu_lifetime %d " + "max_rx_lifetime %d frag_threshold %d rts_threshold %d " + "cwmin %d cwmax %d short_retry_time %d long_retry_time %d " + "scan_type %d scan_channel %d probe_delay %u " + "min_channel_time %d max_channel_time %d listen_int %d " + "desired_ssid %s desired_bssid %s desired_bsstype %d", + priv->netdev->name, le32_to_cpu(m->max_tx_msdu_lifetime), + le32_to_cpu(m->max_rx_lifetime), + le16_to_cpu(m->frag_threshold), le16_to_cpu(m->rts_threshold), + le16_to_cpu(m->cwmin), le16_to_cpu(m->cwmax), + m->short_retry_time, m->long_retry_time, m->scan_type, + m->scan_channel, le16_to_cpu(m->probe_delay), + le16_to_cpu(m->min_channel_time), + le16_to_cpu(m->max_channel_time), + le16_to_cpu(m->listen_interval), + hex2str(m->desired_ssid, IW_ESSID_MAX_SIZE), + mac2str(m->desired_bssid), m->desired_bsstype); +exit: + kfree(m); +} + +static void at76_dump_mib_phy(struct at76_priv *priv) +{ + int ret; + struct mib_phy *m = kmalloc(sizeof(struct mib_phy), GFP_KERNEL); + + if (!m) + return; + + ret = at76_get_mib(priv->udev, MIB_PHY, m, sizeof(struct mib_phy)); + if (ret < 0) { + printk(KERN_ERR "%s: at76_get_mib (PHY) failed: %d\n", + priv->netdev->name, ret); + goto exit; + } + + at76_dbg(DBG_MIB, "%s: MIB PHY: ed_threshold %d slot_time %d " + "sifs_time %d preamble_length %d plcp_header_length %d " + "mpdu_max_length %d cca_mode_supported %d operation_rate_set " + "0x%x 0x%x 0x%x 0x%x channel_id %d current_cca_mode %d " + "phy_type %d current_reg_domain %d", + priv->netdev->name, le32_to_cpu(m->ed_threshold), + le16_to_cpu(m->slot_time), le16_to_cpu(m->sifs_time), + le16_to_cpu(m->preamble_length), + le16_to_cpu(m->plcp_header_length), + le16_to_cpu(m->mpdu_max_length), + le16_to_cpu(m->cca_mode_supported), m->operation_rate_set[0], + m->operation_rate_set[1], m->operation_rate_set[2], + m->operation_rate_set[3], m->channel_id, m->current_cca_mode, + m->phy_type, m->current_reg_domain); +exit: + kfree(m); +} + +static void at76_dump_mib_local(struct at76_priv *priv) +{ + int ret; + struct mib_local *m = kmalloc(sizeof(struct mib_phy), GFP_KERNEL); + + if (!m) + return; + + ret = at76_get_mib(priv->udev, MIB_LOCAL, m, sizeof(struct mib_local)); + if (ret < 0) { + printk(KERN_ERR "%s: at76_get_mib (LOCAL) failed: %d\n", + priv->netdev->name, ret); + goto exit; + } + + at76_dbg(DBG_MIB, "%s: MIB LOCAL: beacon_enable %d " + "txautorate_fallback %d ssid_size %d promiscuous_mode %d " + "preamble_type %d", priv->netdev->name, m->beacon_enable, + m->txautorate_fallback, m->ssid_size, m->promiscuous_mode, + m->preamble_type); +exit: + kfree(m); +} + +static void at76_dump_mib_mdomain(struct at76_priv *priv) +{ + int ret; + struct mib_mdomain *m = kmalloc(sizeof(struct mib_mdomain), GFP_KERNEL); + + if (!m) + return; + + ret = at76_get_mib(priv->udev, MIB_MDOMAIN, m, + sizeof(struct mib_mdomain)); + if (ret < 0) { + printk(KERN_ERR "%s: at76_get_mib (MDOMAIN) failed: %d\n", + priv->netdev->name, ret); + goto exit; + } + + at76_dbg(DBG_MIB, "%s: MIB MDOMAIN: channel_list %s", + priv->netdev->name, + hex2str(m->channel_list, sizeof(m->channel_list))); + + at76_dbg(DBG_MIB, "%s: MIB MDOMAIN: tx_powerlevel %s", + priv->netdev->name, + hex2str(m->tx_powerlevel, sizeof(m->tx_powerlevel))); +exit: + kfree(m); +} + +static int at76_get_current_bssid(struct at76_priv *priv) +{ + int ret = 0; + struct mib_mac_mgmt *mac_mgmt = + kmalloc(sizeof(struct mib_mac_mgmt), GFP_KERNEL); + + if (!mac_mgmt) { + ret = -ENOMEM; + goto exit; + } + + ret = at76_get_mib(priv->udev, MIB_MAC_MGMT, mac_mgmt, + sizeof(struct mib_mac_mgmt)); + if (ret < 0) { + printk(KERN_ERR "%s: at76_get_mib failed: %d\n", + priv->netdev->name, ret); + goto error; + } + memcpy(priv->bssid, mac_mgmt->current_bssid, ETH_ALEN); + printk(KERN_INFO "%s: using BSSID %s\n", priv->netdev->name, + mac2str(priv->bssid)); +error: + kfree(mac_mgmt); +exit: + return ret; +} + +static int at76_get_current_channel(struct at76_priv *priv) +{ + int ret = 0; + struct mib_phy *phy = kmalloc(sizeof(struct mib_phy), GFP_KERNEL); + + if (!phy) { + ret = -ENOMEM; + goto exit; + } + ret = at76_get_mib(priv->udev, MIB_PHY, phy, sizeof(struct mib_phy)); + if (ret < 0) { + printk(KERN_ERR "%s: at76_get_mib(MIB_PHY) failed: %d\n", + priv->netdev->name, ret); + goto error; + } + priv->channel = phy->channel_id; +error: + kfree(phy); +exit: + return ret; +} + +/** + * at76_start_scan - start a scan + * + * @use_essid - use the configured ESSID in non passive mode + */ +static int at76_start_scan(struct at76_priv *priv, int use_essid) +{ + struct at76_req_scan scan; + + memset(&scan, 0, sizeof(struct at76_req_scan)); + memset(scan.bssid, 0xff, ETH_ALEN); + + if (use_essid) { + memcpy(scan.essid, priv->essid, IW_ESSID_MAX_SIZE); + scan.essid_size = priv->essid_size; + } else + scan.essid_size = 0; + + /* jal: why should we start at a certain channel? we do scan the whole + range allowed by reg domain. */ + scan.channel = priv->channel; + + /* atmelwlandriver differs between scan type 0 and 1 (active/passive) + For ad-hoc mode, it uses type 0 only. */ + scan.scan_type = priv->scan_mode; + + /* INFO: For probe_delay, not multiplying by 1024 as this will be + slightly less than min_channel_time + (per spec: probe delay < min. channel time) */ + scan.min_channel_time = cpu_to_le16(priv->scan_min_time); + scan.max_channel_time = cpu_to_le16(priv->scan_max_time); + scan.probe_delay = cpu_to_le16(priv->scan_min_time * 1000); + scan.international_scan = 0; + + /* other values are set to 0 for type 0 */ + + at76_dbg(DBG_PROGRESS, "%s: start_scan (use_essid = %d, intl = %d, " + "channel = %d, probe_delay = %d, scan_min_time = %d, " + "scan_max_time = %d)", + priv->netdev->name, use_essid, + scan.international_scan, scan.channel, + le16_to_cpu(scan.probe_delay), + le16_to_cpu(scan.min_channel_time), + le16_to_cpu(scan.max_channel_time)); + + return at76_set_card_command(priv->udev, CMD_SCAN, &scan, sizeof(scan)); +} + +/* Enable monitor mode */ +static int at76_start_monitor(struct at76_priv *priv) +{ + struct at76_req_scan scan; + int ret; + + memset(&scan, 0, sizeof(struct at76_req_scan)); + memset(scan.bssid, 0xff, ETH_ALEN); + + scan.channel = priv->channel; + scan.scan_type = SCAN_TYPE_PASSIVE; + scan.international_scan = 0; + + ret = at76_set_card_command(priv->udev, CMD_SCAN, &scan, sizeof(scan)); + if (ret >= 0) + ret = at76_get_cmd_status(priv->udev, CMD_SCAN); + + return ret; +} + +static int at76_start_ibss(struct at76_priv *priv) +{ + struct at76_req_ibss bss; + int ret; + + WARN_ON(priv->mac_state != MAC_OWN_IBSS); + if (priv->mac_state != MAC_OWN_IBSS) + return -EBUSY; + + memset(&bss, 0, sizeof(struct at76_req_ibss)); + memset(bss.bssid, 0xff, ETH_ALEN); + memcpy(bss.essid, priv->essid, IW_ESSID_MAX_SIZE); + bss.essid_size = priv->essid_size; + bss.bss_type = ADHOC_MODE; + bss.channel = priv->channel; + + ret = at76_set_card_command(priv->udev, CMD_START_IBSS, &bss, + sizeof(struct at76_req_ibss)); + if (ret < 0) { + printk(KERN_ERR "%s: start_ibss failed: %d\n", + priv->netdev->name, ret); + return ret; + } + + ret = at76_wait_completion(priv, CMD_START_IBSS); + if (ret != CMD_STATUS_COMPLETE) { + printk(KERN_ERR "%s: start_ibss failed to complete, %d\n", + priv->netdev->name, ret); + return ret; + } + + ret = at76_get_current_bssid(priv); + if (ret < 0) + return ret; + + ret = at76_get_current_channel(priv); + if (ret < 0) + return ret; + + /* not sure what this is good for ??? */ + priv->mib_buf.type = MIB_MAC_MGMT; + priv->mib_buf.size = 1; + priv->mib_buf.index = offsetof(struct mib_mac_mgmt, ibss_change); + priv->mib_buf.data.byte = 0; + + ret = at76_set_mib(priv, &priv->mib_buf); + if (ret < 0) { + printk(KERN_ERR "%s: set_mib (ibss change ok) failed: %d\n", + priv->netdev->name, ret); + return ret; + } + + netif_carrier_on(priv->netdev); + netif_start_queue(priv->netdev); + return 0; +} + +/* Request card to join BSS in managed or ad-hoc mode */ +static int at76_join_bss(struct at76_priv *priv, struct bss_info *ptr) +{ + struct at76_req_join join; + + BUG_ON(!ptr); + + memset(&join, 0, sizeof(struct at76_req_join)); + memcpy(join.bssid, ptr->bssid, ETH_ALEN); + memcpy(join.essid, ptr->ssid, ptr->ssid_len); + join.essid_size = ptr->ssid_len; + join.bss_type = (priv->iw_mode == IW_MODE_ADHOC ? 1 : 2); + join.channel = ptr->channel; + join.timeout = cpu_to_le16(2000); + + at76_dbg(DBG_PROGRESS, + "%s join addr %s ssid %s type %d ch %d timeout %d", + priv->netdev->name, mac2str(join.bssid), join.essid, + join.bss_type, join.channel, le16_to_cpu(join.timeout)); + return at76_set_card_command(priv->udev, CMD_JOIN, &join, + sizeof(struct at76_req_join)); +} + +/* Calculate padding from txbuf->wlength (which excludes the USB TX header), + likely to compensate a flaw in the AT76C503A USB part ... */ +static inline int at76_calc_padding(int wlen) +{ + /* add the USB TX header */ + wlen += AT76_TX_HDRLEN; + + wlen = wlen % 64; + + if (wlen < 50) + return 50 - wlen; + + if (wlen >= 61) + return 64 + 50 - wlen; + + return 0; +} + +/* We are doing a lot of things here in an interrupt. Need + a bh handler (Watching TV with a TV card is probably + a good test: if you see flickers, we are doing too much. + Currently I do see flickers... even with our tasklet :-( ) + Maybe because the bttv driver and usb-uhci use the same interrupt +*/ +/* Or maybe because our BH handler is preempting bttv's BH handler.. BHs don't + * solve everything.. (alex) */ +static void at76_rx_callback(struct urb *urb) +{ + struct at76_priv *priv = urb->context; + + priv->rx_tasklet.data = (unsigned long)urb; + tasklet_schedule(&priv->rx_tasklet); + return; +} + +static void at76_tx_callback(struct urb *urb) +{ + struct at76_priv *priv = urb->context; + struct net_device_stats *stats = &priv->stats; + unsigned long flags; + struct at76_tx_buffer *mgmt_buf; + int ret; + + switch (urb->status) { + case 0: + stats->tx_packets++; + break; + case -ENOENT: + case -ECONNRESET: + /* urb has been unlinked */ + return; + default: + at76_dbg(DBG_URB, "%s - nonzero tx status received: %d", + __func__, urb->status); + stats->tx_errors++; + break; + } + + spin_lock_irqsave(&priv->mgmt_spinlock, flags); + mgmt_buf = priv->next_mgmt_bulk; + priv->next_mgmt_bulk = NULL; + spin_unlock_irqrestore(&priv->mgmt_spinlock, flags); + + if (!mgmt_buf) { + netif_wake_queue(priv->netdev); + return; + } + + /* we don't copy the padding bytes, but add them + to the length */ + memcpy(priv->bulk_out_buffer, mgmt_buf, + le16_to_cpu(mgmt_buf->wlength) + AT76_TX_HDRLEN); + usb_fill_bulk_urb(priv->tx_urb, priv->udev, priv->tx_pipe, + priv->bulk_out_buffer, + le16_to_cpu(mgmt_buf->wlength) + mgmt_buf->padding + + AT76_TX_HDRLEN, at76_tx_callback, priv); + ret = usb_submit_urb(priv->tx_urb, GFP_ATOMIC); + if (ret) + printk(KERN_ERR "%s: error in tx submit urb: %d\n", + priv->netdev->name, ret); + + kfree(mgmt_buf); +} + +/* Send a management frame on bulk-out. txbuf->wlength must be set */ +static int at76_tx_mgmt(struct at76_priv *priv, struct at76_tx_buffer *txbuf) +{ + unsigned long flags; + int ret; + int urb_status; + void *oldbuf = NULL; + + netif_carrier_off(priv->netdev); /* stop netdev watchdog */ + netif_stop_queue(priv->netdev); /* stop tx data packets */ + + spin_lock_irqsave(&priv->mgmt_spinlock, flags); + + urb_status = priv->tx_urb->status; + if (urb_status == -EINPROGRESS) { + /* cannot transmit now, put in the queue */ + oldbuf = priv->next_mgmt_bulk; + priv->next_mgmt_bulk = txbuf; + } + spin_unlock_irqrestore(&priv->mgmt_spinlock, flags); + + if (oldbuf) { + /* a data/mgmt tx is already pending in the URB - + if this is no error in some situations we must + implement a queue or silently modify the old msg */ + printk(KERN_ERR "%s: removed pending mgmt buffer %s\n", + priv->netdev->name, hex2str(oldbuf, 64)); + kfree(oldbuf); + return 0; + } + + txbuf->tx_rate = TX_RATE_1MBIT; + txbuf->padding = at76_calc_padding(le16_to_cpu(txbuf->wlength)); + memset(txbuf->reserved, 0, sizeof(txbuf->reserved)); + + if (priv->next_mgmt_bulk) + printk(KERN_ERR "%s: URB status %d, but mgmt is pending\n", + priv->netdev->name, urb_status); + + at76_dbg(DBG_TX_MGMT, + "%s: tx mgmt: wlen %d tx_rate %d pad %d %s", + priv->netdev->name, le16_to_cpu(txbuf->wlength), + txbuf->tx_rate, txbuf->padding, + hex2str(txbuf->packet, le16_to_cpu(txbuf->wlength))); + + /* txbuf was not consumed above -> send mgmt msg immediately */ + memcpy(priv->bulk_out_buffer, txbuf, + le16_to_cpu(txbuf->wlength) + AT76_TX_HDRLEN); + usb_fill_bulk_urb(priv->tx_urb, priv->udev, priv->tx_pipe, + priv->bulk_out_buffer, + le16_to_cpu(txbuf->wlength) + txbuf->padding + + AT76_TX_HDRLEN, at76_tx_callback, priv); + ret = usb_submit_urb(priv->tx_urb, GFP_ATOMIC); + if (ret) + printk(KERN_ERR "%s: error in tx submit urb: %d\n", + priv->netdev->name, ret); + + kfree(txbuf); + + return ret; +} + +/* Go to the next information element */ +static inline void next_ie(struct ieee80211_info_element **ie) +{ + *ie = (struct ieee80211_info_element *)(&(*ie)->data[(*ie)->len]); +} + +/* Challenge is the challenge string (in TLV format) + we got with seq_nr 2 for shared secret authentication only and + send in seq_nr 3 WEP encrypted to prove we have the correct WEP key; + otherwise it is NULL */ +static int at76_auth_req(struct at76_priv *priv, struct bss_info *bss, + int seq_nr, struct ieee80211_info_element *challenge) +{ + struct at76_tx_buffer *tx_buffer; + struct ieee80211_hdr_3addr *mgmt; + struct ieee80211_auth *req; + int buf_len = (seq_nr != 3 ? AUTH_FRAME_SIZE : + AUTH_FRAME_SIZE + 1 + 1 + challenge->len); + + BUG_ON(!bss); + BUG_ON(seq_nr == 3 && !challenge); + tx_buffer = kmalloc(buf_len + MAX_PADDING_SIZE, GFP_ATOMIC); + if (!tx_buffer) + return -ENOMEM; + + req = (struct ieee80211_auth *)tx_buffer->packet; + mgmt = &req->header; + + /* make wireless header */ + /* first auth msg is not encrypted, only the second (seq_nr == 3) */ + mgmt->frame_ctl = + cpu_to_le16(IEEE80211_FTYPE_MGMT | IEEE80211_STYPE_AUTH | + (seq_nr == 3 ? IEEE80211_FCTL_PROTECTED : 0)); + + mgmt->duration_id = cpu_to_le16(0x8000); + memcpy(mgmt->addr1, bss->bssid, ETH_ALEN); + memcpy(mgmt->addr2, priv->netdev->dev_addr, ETH_ALEN); + memcpy(mgmt->addr3, bss->bssid, ETH_ALEN); + mgmt->seq_ctl = cpu_to_le16(0); + + req->algorithm = cpu_to_le16(priv->auth_mode); + req->transaction = cpu_to_le16(seq_nr); + req->status = cpu_to_le16(0); + + if (seq_nr == 3) + memcpy(req->info_element, challenge, 1 + 1 + challenge->len); + + /* init. at76_priv tx header */ + tx_buffer->wlength = cpu_to_le16(buf_len - AT76_TX_HDRLEN); + at76_dbg(DBG_TX_MGMT, "%s: AuthReq bssid %s alg %d seq_nr %d", + priv->netdev->name, mac2str(mgmt->addr3), + le16_to_cpu(req->algorithm), le16_to_cpu(req->transaction)); + if (seq_nr == 3) + at76_dbg(DBG_TX_MGMT, "%s: AuthReq challenge: %s ...", + priv->netdev->name, hex2str(req->info_element, 18)); + + /* either send immediately (if no data tx is pending + or put it in pending list */ + return at76_tx_mgmt(priv, tx_buffer); +} + +static int at76_assoc_req(struct at76_priv *priv, struct bss_info *bss) +{ + struct at76_tx_buffer *tx_buffer; + struct ieee80211_hdr_3addr *mgmt; + struct ieee80211_assoc_request *req; + struct ieee80211_info_element *ie; + char *essid; + int essid_len; + u16 capa; + + BUG_ON(!bss); + + tx_buffer = kmalloc(ASSOCREQ_MAX_SIZE + MAX_PADDING_SIZE, GFP_ATOMIC); + if (!tx_buffer) + return -ENOMEM; + + req = (struct ieee80211_assoc_request *)tx_buffer->packet; + mgmt = &req->header; + ie = req->info_element; + + /* make wireless header */ + mgmt->frame_ctl = cpu_to_le16(IEEE80211_FTYPE_MGMT | + IEEE80211_STYPE_ASSOC_REQ); + + mgmt->duration_id = cpu_to_le16(0x8000); + memcpy(mgmt->addr1, bss->bssid, ETH_ALEN); + memcpy(mgmt->addr2, priv->netdev->dev_addr, ETH_ALEN); + memcpy(mgmt->addr3, bss->bssid, ETH_ALEN); + mgmt->seq_ctl = cpu_to_le16(0); + + /* we must set the Privacy bit in the capabilities to assure an + Agere-based AP with optional WEP transmits encrypted frames + to us. AP only set the Privacy bit in their capabilities + if WEP is mandatory in the BSS! */ + capa = bss->capa; + if (priv->wep_enabled) + capa |= WLAN_CAPABILITY_PRIVACY; + if (priv->preamble_type != PREAMBLE_TYPE_LONG) + capa |= WLAN_CAPABILITY_SHORT_PREAMBLE; + req->capability = cpu_to_le16(capa); + + req->listen_interval = cpu_to_le16(2 * bss->beacon_interval); + + /* write TLV data elements */ + + ie->id = MFIE_TYPE_SSID; + ie->len = bss->ssid_len; + memcpy(ie->data, bss->ssid, bss->ssid_len); + next_ie(&ie); + + ie->id = MFIE_TYPE_RATES; + ie->len = sizeof(hw_rates); + memcpy(ie->data, hw_rates, sizeof(hw_rates)); + next_ie(&ie); /* ie points behind the supp_rates field */ + + /* init. at76_priv tx header */ + tx_buffer->wlength = cpu_to_le16((u8 *)ie - (u8 *)mgmt); + + ie = req->info_element; + essid = ie->data; + essid_len = min_t(int, IW_ESSID_MAX_SIZE, ie->len); + + next_ie(&ie); /* points to IE of rates now */ + at76_dbg(DBG_TX_MGMT, + "%s: AssocReq bssid %s capa 0x%04x ssid %.*s rates %s", + priv->netdev->name, mac2str(mgmt->addr3), + le16_to_cpu(req->capability), essid_len, essid, + hex2str(ie->data, ie->len)); + + /* either send immediately (if no data tx is pending + or put it in pending list */ + return at76_tx_mgmt(priv, tx_buffer); +} + +/* We got to check the bss_list for old entries */ +static void at76_bss_list_timeout(unsigned long par) +{ + struct at76_priv *priv = (struct at76_priv *)par; + unsigned long flags; + struct list_head *lptr, *nptr; + struct bss_info *ptr; + + spin_lock_irqsave(&priv->bss_list_spinlock, flags); + + list_for_each_safe(lptr, nptr, &priv->bss_list) { + + ptr = list_entry(lptr, struct bss_info, list); + + if (ptr != priv->curr_bss + && time_after(jiffies, ptr->last_rx + BSS_LIST_TIMEOUT)) { + at76_dbg(DBG_BSS_TABLE_RM, + "%s: bss_list: removing old BSS %s ch %d", + priv->netdev->name, mac2str(ptr->bssid), + ptr->channel); + list_del(&ptr->list); + kfree(ptr); + } + } + spin_unlock_irqrestore(&priv->bss_list_spinlock, flags); + /* restart the timer */ + mod_timer(&priv->bss_list_timer, jiffies + BSS_LIST_TIMEOUT); +} + +static inline void at76_set_mac_state(struct at76_priv *priv, + enum mac_state mac_state) +{ + at76_dbg(DBG_MAC_STATE, "%s state: %s", priv->netdev->name, + mac_states[mac_state]); + priv->mac_state = mac_state; +} + +static void at76_dump_bss_table(struct at76_priv *priv) +{ + struct bss_info *ptr; + unsigned long flags; + struct list_head *lptr; + + spin_lock_irqsave(&priv->bss_list_spinlock, flags); + + at76_dbg(DBG_BSS_TABLE, "%s BSS table (curr=%p):", priv->netdev->name, + priv->curr_bss); + + list_for_each(lptr, &priv->bss_list) { + ptr = list_entry(lptr, struct bss_info, list); + at76_dbg(DBG_BSS_TABLE, "0x%p: bssid %s channel %d ssid %.*s " + "(%s) capa 0x%04x rates %s rssi %d link %d noise %d", + ptr, mac2str(ptr->bssid), ptr->channel, ptr->ssid_len, + ptr->ssid, hex2str(ptr->ssid, ptr->ssid_len), + ptr->capa, hex2str(ptr->rates, ptr->rates_len), + ptr->rssi, ptr->link_qual, ptr->noise_level); + } + spin_unlock_irqrestore(&priv->bss_list_spinlock, flags); +} + +/* Called upon successful association to mark interface as connected */ +static void at76_work_assoc_done(struct work_struct *work) +{ + struct at76_priv *priv = container_of(work, struct at76_priv, + work_assoc_done); + + mutex_lock(&priv->mtx); + + WARN_ON(priv->mac_state != MAC_ASSOC); + WARN_ON(!priv->curr_bss); + if (priv->mac_state != MAC_ASSOC || !priv->curr_bss) + goto exit; + + if (priv->iw_mode == IW_MODE_INFRA) { + if (priv->pm_mode != AT76_PM_OFF) { + /* calculate the listen interval in units of + beacon intervals of the curr_bss */ + u32 pm_period_beacon = (priv->pm_period >> 10) / + priv->curr_bss->beacon_interval; + + pm_period_beacon = max(pm_period_beacon, 2u); + pm_period_beacon = min(pm_period_beacon, 0xffffu); + + at76_dbg(DBG_PM, + "%s: pm_mode %d assoc id 0x%x listen int %d", + priv->netdev->name, priv->pm_mode, + priv->assoc_id, pm_period_beacon); + + at76_set_associd(priv, priv->assoc_id); + at76_set_listen_interval(priv, (u16)pm_period_beacon); + } + schedule_delayed_work(&priv->dwork_beacon, BEACON_TIMEOUT); + } + at76_set_pm_mode(priv); + + netif_carrier_on(priv->netdev); + netif_wake_queue(priv->netdev); + at76_set_mac_state(priv, MAC_CONNECTED); + at76_iwevent_bss_connect(priv->netdev, priv->curr_bss->bssid); + at76_dbg(DBG_PROGRESS, "%s: connected to BSSID %s", + priv->netdev->name, mac2str(priv->curr_bss->bssid)); + +exit: + mutex_unlock(&priv->mtx); +} + +/* We only store the new mac address in netdev struct, + it gets set when the netdev is opened. */ +static int at76_set_mac_address(struct net_device *netdev, void *addr) +{ + struct sockaddr *mac = addr; + memcpy(netdev->dev_addr, mac->sa_data, ETH_ALEN); + return 1; +} + +static struct net_device_stats *at76_get_stats(struct net_device *netdev) +{ + struct at76_priv *priv = netdev_priv(netdev); + return &priv->stats; +} + +static struct iw_statistics *at76_get_wireless_stats(struct net_device *netdev) +{ + struct at76_priv *priv = netdev_priv(netdev); + + at76_dbg(DBG_IOCTL, "RETURN qual %d level %d noise %d updated %d", + priv->wstats.qual.qual, priv->wstats.qual.level, + priv->wstats.qual.noise, priv->wstats.qual.updated); + + return &priv->wstats; +} + +static void at76_set_multicast(struct net_device *netdev) +{ + struct at76_priv *priv = netdev_priv(netdev); + int promisc; + + promisc = ((netdev->flags & IFF_PROMISC) != 0); + if (promisc != priv->promisc) { + /* This gets called in interrupt, must reschedule */ + priv->promisc = promisc; + schedule_work(&priv->work_set_promisc); + } +} + +/* Stop all network activity, flush all pending tasks */ +static void at76_quiesce(struct at76_priv *priv) +{ + unsigned long flags; + + netif_stop_queue(priv->netdev); + netif_carrier_off(priv->netdev); + + at76_set_mac_state(priv, MAC_INIT); + + cancel_delayed_work(&priv->dwork_get_scan); + cancel_delayed_work(&priv->dwork_beacon); + cancel_delayed_work(&priv->dwork_auth); + cancel_delayed_work(&priv->dwork_assoc); + cancel_delayed_work(&priv->dwork_restart); + + spin_lock_irqsave(&priv->mgmt_spinlock, flags); + kfree(priv->next_mgmt_bulk); + priv->next_mgmt_bulk = NULL; + spin_unlock_irqrestore(&priv->mgmt_spinlock, flags); +} + +/******************************************************************************* + * at76_priv implementations of iw_handler functions: + */ +static int at76_iw_handler_commit(struct net_device *netdev, + struct iw_request_info *info, + void *null, char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + + at76_dbg(DBG_IOCTL, "%s %s: restarting the device", netdev->name, + __func__); + + if (priv->mac_state != MAC_INIT) + at76_quiesce(priv); + + /* Wait half second before the restart to process subsequent + * requests from the same iwconfig in a single restart */ + schedule_delayed_work(&priv->dwork_restart, HZ / 2); + + return 0; +} + +static int at76_iw_handler_get_name(struct net_device *netdev, + struct iw_request_info *info, + char *name, char *extra) +{ + strcpy(name, "IEEE 802.11b"); + at76_dbg(DBG_IOCTL, "%s: SIOCGIWNAME - name %s", netdev->name, name); + return 0; +} + +static int at76_iw_handler_set_freq(struct net_device *netdev, + struct iw_request_info *info, + struct iw_freq *freq, char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + int chan = -1; + int ret = -EIWCOMMIT; + at76_dbg(DBG_IOCTL, "%s: SIOCSIWFREQ - freq.m %d freq.e %d", + netdev->name, freq->m, freq->e); + + if ((freq->e == 0) && (freq->m <= 1000)) + /* Setting by channel number */ + chan = freq->m; + else { + /* Setting by frequency - search the table */ + int mult = 1; + int i; + + for (i = 0; i < (6 - freq->e); i++) + mult *= 10; + + for (i = 0; i < NUM_CHANNELS; i++) { + if (freq->m == (channel_frequency[i] * mult)) + chan = i + 1; + } + } + + if (chan < 1 || !priv->domain) + /* non-positive channels are invalid + * we need a domain info to set the channel + * either that or an invalid frequency was + * provided by the user */ + ret = -EINVAL; + else if (!(priv->domain->channel_map & (1 << (chan - 1)))) { + printk(KERN_INFO "%s: channel %d not allowed for domain %s\n", + priv->netdev->name, chan, priv->domain->name); + ret = -EINVAL; + } + + if (ret == -EIWCOMMIT) { + priv->channel = chan; + at76_dbg(DBG_IOCTL, "%s: SIOCSIWFREQ - ch %d", netdev->name, + chan); + } + + return ret; +} + +static int at76_iw_handler_get_freq(struct net_device *netdev, + struct iw_request_info *info, + struct iw_freq *freq, char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + + freq->m = priv->channel; + freq->e = 0; + + if (priv->channel) + at76_dbg(DBG_IOCTL, "%s: SIOCGIWFREQ - freq %ld x 10e%d", + netdev->name, channel_frequency[priv->channel - 1], 6); + + at76_dbg(DBG_IOCTL, "%s: SIOCGIWFREQ - ch %d", netdev->name, + priv->channel); + + return 0; +} + +static int at76_iw_handler_set_mode(struct net_device *netdev, + struct iw_request_info *info, + __u32 *mode, char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + + at76_dbg(DBG_IOCTL, "%s: SIOCSIWMODE - %d", netdev->name, *mode); + + if ((*mode != IW_MODE_ADHOC) && (*mode != IW_MODE_INFRA) && + (*mode != IW_MODE_MONITOR)) + return -EINVAL; + + priv->iw_mode = *mode; + if (priv->iw_mode != IW_MODE_INFRA) + priv->pm_mode = AT76_PM_OFF; + + return -EIWCOMMIT; +} + +static int at76_iw_handler_get_mode(struct net_device *netdev, + struct iw_request_info *info, + __u32 *mode, char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + + *mode = priv->iw_mode; + + at76_dbg(DBG_IOCTL, "%s: SIOCGIWMODE - %d", netdev->name, *mode); + + return 0; +} + +static int at76_iw_handler_get_range(struct net_device *netdev, + struct iw_request_info *info, + struct iw_point *data, char *extra) +{ + /* inspired by atmel.c */ + struct at76_priv *priv = netdev_priv(netdev); + struct iw_range *range = (struct iw_range *)extra; + int i; + + data->length = sizeof(struct iw_range); + memset(range, 0, sizeof(struct iw_range)); + + /* TODO: range->throughput = xxxxxx; */ + + range->min_nwid = 0x0000; + range->max_nwid = 0x0000; + + /* this driver doesn't maintain sensitivity information */ + range->sensitivity = 0; + + range->max_qual.qual = 100; + range->max_qual.level = 100; + range->max_qual.noise = 0; + range->max_qual.updated = IW_QUAL_NOISE_INVALID; + + range->avg_qual.qual = 50; + range->avg_qual.level = 50; + range->avg_qual.noise = 0; + range->avg_qual.updated = IW_QUAL_NOISE_INVALID; + + range->bitrate[0] = 1000000; + range->bitrate[1] = 2000000; + range->bitrate[2] = 5500000; + range->bitrate[3] = 11000000; + range->num_bitrates = 4; + + range->min_rts = 0; + range->max_rts = MAX_RTS_THRESHOLD; + + range->min_frag = MIN_FRAG_THRESHOLD; + range->max_frag = MAX_FRAG_THRESHOLD; + + range->pmp_flags = IW_POWER_PERIOD; + range->pmt_flags = IW_POWER_ON; + range->pm_capa = IW_POWER_PERIOD | IW_POWER_ALL_R; + + range->encoding_size[0] = WEP_SMALL_KEY_LEN; + range->encoding_size[1] = WEP_LARGE_KEY_LEN; + range->num_encoding_sizes = 2; + range->max_encoding_tokens = WEP_KEYS; + + /* both WL-240U and Linksys WUSB11 v2.6 specify 15 dBm as output power + - take this for all (ignore antenna gains) */ + range->txpower[0] = 15; + range->num_txpower = 1; + range->txpower_capa = IW_TXPOW_DBM; + + range->we_version_source = WIRELESS_EXT; + range->we_version_compiled = WIRELESS_EXT; + + /* same as the values used in atmel.c */ + range->retry_capa = IW_RETRY_LIMIT; + range->retry_flags = IW_RETRY_LIMIT; + range->r_time_flags = 0; + range->min_retry = 1; + range->max_retry = 255; + + range->num_channels = NUM_CHANNELS; + range->num_frequency = 0; + + for (i = 0; i < NUM_CHANNELS; i++) { + /* test if channel map bit is raised */ + if (priv->domain->channel_map & (0x1 << i)) { + range->num_frequency += 1; + + range->freq[i].i = i + 1; + range->freq[i].m = channel_frequency[i] * 100000; + range->freq[i].e = 1; /* freq * 10^1 */ + } + } + + at76_dbg(DBG_IOCTL, "%s: SIOCGIWRANGE", netdev->name); + + return 0; +} + +static int at76_iw_handler_set_spy(struct net_device *netdev, + struct iw_request_info *info, + struct iw_point *data, char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + int ret = 0; + + at76_dbg(DBG_IOCTL, "%s: SIOCSIWSPY - number of addresses %d", + netdev->name, data->length); + + spin_lock_bh(&priv->spy_spinlock); + ret = iw_handler_set_spy(priv->netdev, info, (union iwreq_data *)data, + extra); + spin_unlock_bh(&priv->spy_spinlock); + + return ret; +} + +static int at76_iw_handler_get_spy(struct net_device *netdev, + struct iw_request_info *info, + struct iw_point *data, char *extra) +{ + + struct at76_priv *priv = netdev_priv(netdev); + int ret = 0; + + spin_lock_bh(&priv->spy_spinlock); + ret = iw_handler_get_spy(priv->netdev, info, + (union iwreq_data *)data, extra); + spin_unlock_bh(&priv->spy_spinlock); + + at76_dbg(DBG_IOCTL, "%s: SIOCGIWSPY - number of addresses %d", + netdev->name, data->length); + + return ret; +} + +static int at76_iw_handler_set_thrspy(struct net_device *netdev, + struct iw_request_info *info, + struct iw_point *data, char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + int ret; + + at76_dbg(DBG_IOCTL, "%s: SIOCSIWTHRSPY - number of addresses %d)", + netdev->name, data->length); + + spin_lock_bh(&priv->spy_spinlock); + ret = iw_handler_set_thrspy(netdev, info, (union iwreq_data *)data, + extra); + spin_unlock_bh(&priv->spy_spinlock); + + return ret; +} + +static int at76_iw_handler_get_thrspy(struct net_device *netdev, + struct iw_request_info *info, + struct iw_point *data, char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + int ret; + + spin_lock_bh(&priv->spy_spinlock); + ret = iw_handler_get_thrspy(netdev, info, (union iwreq_data *)data, + extra); + spin_unlock_bh(&priv->spy_spinlock); + + at76_dbg(DBG_IOCTL, "%s: SIOCGIWTHRSPY - number of addresses %d)", + netdev->name, data->length); + + return ret; +} + +static int at76_iw_handler_set_wap(struct net_device *netdev, + struct iw_request_info *info, + struct sockaddr *ap_addr, char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + + at76_dbg(DBG_IOCTL, "%s: SIOCSIWAP - wap/bssid %s", netdev->name, + mac2str(ap_addr->sa_data)); + + /* if the incoming address == ff:ff:ff:ff:ff:ff, the user has + chosen any or auto AP preference */ + if (is_broadcast_ether_addr(ap_addr->sa_data) + || is_zero_ether_addr(ap_addr->sa_data)) + priv->wanted_bssid_valid = 0; + else { + /* user wants to set a preferred AP address */ + priv->wanted_bssid_valid = 1; + memcpy(priv->wanted_bssid, ap_addr->sa_data, ETH_ALEN); + } + + return -EIWCOMMIT; +} + +static int at76_iw_handler_get_wap(struct net_device *netdev, + struct iw_request_info *info, + struct sockaddr *ap_addr, char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + + ap_addr->sa_family = ARPHRD_ETHER; + memcpy(ap_addr->sa_data, priv->bssid, ETH_ALEN); + + at76_dbg(DBG_IOCTL, "%s: SIOCGIWAP - wap/bssid %s", netdev->name, + mac2str(ap_addr->sa_data)); + + return 0; +} + +static int at76_iw_handler_set_scan(struct net_device *netdev, + struct iw_request_info *info, + union iwreq_data *wrqu, char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + int ret = 0; + + at76_dbg(DBG_IOCTL, "%s: SIOCSIWSCAN", netdev->name); + + if (mutex_lock_interruptible(&priv->mtx)) + return -EINTR; + + if (!netif_running(netdev)) { + ret = -ENETDOWN; + goto exit; + } + + /* jal: we don't allow "iwlist ethX scan" while we are + in monitor mode */ + if (priv->iw_mode == IW_MODE_MONITOR) { + ret = -EBUSY; + goto exit; + } + + /* Discard old scan results */ + if ((jiffies - priv->last_scan) > (20 * HZ)) + priv->scan_state = SCAN_IDLE; + priv->last_scan = jiffies; + + /* Initiate a scan command */ + if (priv->scan_state == SCAN_IN_PROGRESS) { + ret = -EBUSY; + goto exit; + } + + priv->scan_state = SCAN_IN_PROGRESS; + + at76_quiesce(priv); + + /* Try to do passive or active scan if WE asks as. */ + if (wrqu->data.length + && wrqu->data.length == sizeof(struct iw_scan_req)) { + struct iw_scan_req *req = (struct iw_scan_req *)extra; + + if (req->scan_type == IW_SCAN_TYPE_PASSIVE) + priv->scan_mode = SCAN_TYPE_PASSIVE; + else if (req->scan_type == IW_SCAN_TYPE_ACTIVE) + priv->scan_mode = SCAN_TYPE_ACTIVE; + + /* Sanity check values? */ + if (req->min_channel_time > 0) + priv->scan_min_time = req->min_channel_time; + + if (req->max_channel_time > 0) + priv->scan_max_time = req->max_channel_time; + } + + /* change to scanning state */ + at76_set_mac_state(priv, MAC_SCANNING); + schedule_work(&priv->work_start_scan); + +exit: + mutex_unlock(&priv->mtx); + return ret; +} + +static int at76_iw_handler_get_scan(struct net_device *netdev, + struct iw_request_info *info, + struct iw_point *data, char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + unsigned long flags; + struct list_head *lptr, *nptr; + struct bss_info *curr_bss; + struct iw_event *iwe = kmalloc(sizeof(struct iw_event), GFP_KERNEL); + char *curr_val, *curr_pos = extra; + int i; + + at76_dbg(DBG_IOCTL, "%s: SIOCGIWSCAN", netdev->name); + + if (!iwe) + return -ENOMEM; + + if (priv->scan_state != SCAN_COMPLETED) + /* scan not yet finished */ + return -EAGAIN; + + spin_lock_irqsave(&priv->bss_list_spinlock, flags); + + list_for_each_safe(lptr, nptr, &priv->bss_list) { + curr_bss = list_entry(lptr, struct bss_info, list); + + iwe->cmd = SIOCGIWAP; + iwe->u.ap_addr.sa_family = ARPHRD_ETHER; + memcpy(iwe->u.ap_addr.sa_data, curr_bss->bssid, 6); + curr_pos = iwe_stream_add_event(info, curr_pos, + extra + IW_SCAN_MAX_DATA, iwe, + IW_EV_ADDR_LEN); + + iwe->u.data.length = curr_bss->ssid_len; + iwe->cmd = SIOCGIWESSID; + iwe->u.data.flags = 1; + + curr_pos = iwe_stream_add_point(info, curr_pos, + extra + IW_SCAN_MAX_DATA, iwe, + curr_bss->ssid); + + iwe->cmd = SIOCGIWMODE; + iwe->u.mode = (curr_bss->capa & WLAN_CAPABILITY_IBSS) ? + IW_MODE_ADHOC : + (curr_bss->capa & WLAN_CAPABILITY_ESS) ? + IW_MODE_MASTER : IW_MODE_AUTO; + /* IW_MODE_AUTO = 0 which I thought is + * the most logical value to return in this case */ + curr_pos = iwe_stream_add_event(info, curr_pos, + extra + IW_SCAN_MAX_DATA, iwe, + IW_EV_UINT_LEN); + + iwe->cmd = SIOCGIWFREQ; + iwe->u.freq.m = curr_bss->channel; + iwe->u.freq.e = 0; + curr_pos = iwe_stream_add_event(info, curr_pos, + extra + IW_SCAN_MAX_DATA, iwe, + IW_EV_FREQ_LEN); + + iwe->cmd = SIOCGIWENCODE; + if (curr_bss->capa & WLAN_CAPABILITY_PRIVACY) + iwe->u.data.flags = IW_ENCODE_ENABLED | IW_ENCODE_NOKEY; + else + iwe->u.data.flags = IW_ENCODE_DISABLED; + + iwe->u.data.length = 0; + curr_pos = iwe_stream_add_point(info, curr_pos, + extra + IW_SCAN_MAX_DATA, iwe, + NULL); + + /* Add quality statistics */ + iwe->cmd = IWEVQUAL; + iwe->u.qual.noise = 0; + iwe->u.qual.updated = + IW_QUAL_NOISE_INVALID | IW_QUAL_LEVEL_UPDATED; + iwe->u.qual.level = (curr_bss->rssi * 100 / 42); + if (iwe->u.qual.level > 100) + iwe->u.qual.level = 100; + if (at76_is_intersil(priv->board_type)) + iwe->u.qual.qual = curr_bss->link_qual; + else { + iwe->u.qual.qual = 0; + iwe->u.qual.updated |= IW_QUAL_QUAL_INVALID; + } + /* Add new value to event */ + curr_pos = iwe_stream_add_event(info, curr_pos, + extra + IW_SCAN_MAX_DATA, iwe, + IW_EV_QUAL_LEN); + + /* Rate: stuffing multiple values in a single event requires + * a bit more of magic - Jean II */ + curr_val = curr_pos + IW_EV_LCP_LEN; + + iwe->cmd = SIOCGIWRATE; + /* Those two flags are ignored... */ + iwe->u.bitrate.fixed = 0; + iwe->u.bitrate.disabled = 0; + /* Max 8 values */ + for (i = 0; i < curr_bss->rates_len; i++) { + /* Bit rate given in 500 kb/s units (+ 0x80) */ + iwe->u.bitrate.value = + ((curr_bss->rates[i] & 0x7f) * 500000); + /* Add new value to event */ + curr_val = iwe_stream_add_value(info, curr_pos, + curr_val, + extra + + IW_SCAN_MAX_DATA, iwe, + IW_EV_PARAM_LEN); + } + + /* Check if we added any event */ + if ((curr_val - curr_pos) > IW_EV_LCP_LEN) + curr_pos = curr_val; + + /* more information may be sent back using IWECUSTOM */ + + } + + spin_unlock_irqrestore(&priv->bss_list_spinlock, flags); + + data->length = (curr_pos - extra); + data->flags = 0; + + kfree(iwe); + return 0; +} + +static int at76_iw_handler_set_essid(struct net_device *netdev, + struct iw_request_info *info, + struct iw_point *data, char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + + at76_dbg(DBG_IOCTL, "%s: SIOCSIWESSID - %s", netdev->name, extra); + + if (data->flags) { + memcpy(priv->essid, extra, data->length); + priv->essid_size = data->length; + } else + priv->essid_size = 0; /* Use any SSID */ + + return -EIWCOMMIT; +} + +static int at76_iw_handler_get_essid(struct net_device *netdev, + struct iw_request_info *info, + struct iw_point *data, char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + + if (priv->essid_size) { + /* not the ANY ssid in priv->essid */ + data->flags = 1; + data->length = priv->essid_size; + memcpy(extra, priv->essid, data->length); + } else { + /* the ANY ssid was specified */ + if (priv->mac_state == MAC_CONNECTED && priv->curr_bss) { + /* report the SSID we have found */ + data->flags = 1; + data->length = priv->curr_bss->ssid_len; + memcpy(extra, priv->curr_bss->ssid, data->length); + } else { + /* report ANY back */ + data->flags = 0; + data->length = 0; + } + } + + at76_dbg(DBG_IOCTL, "%s: SIOCGIWESSID - %.*s", netdev->name, + data->length, extra); + + return 0; +} + +static int at76_iw_handler_set_rate(struct net_device *netdev, + struct iw_request_info *info, + struct iw_param *bitrate, char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + int ret = -EIWCOMMIT; + + at76_dbg(DBG_IOCTL, "%s: SIOCSIWRATE - %d", netdev->name, + bitrate->value); + + switch (bitrate->value) { + case -1: + priv->txrate = TX_RATE_AUTO; + break; /* auto rate */ + case 1000000: + priv->txrate = TX_RATE_1MBIT; + break; + case 2000000: + priv->txrate = TX_RATE_2MBIT; + break; + case 5500000: + priv->txrate = TX_RATE_5_5MBIT; + break; + case 11000000: + priv->txrate = TX_RATE_11MBIT; + break; + default: + ret = -EINVAL; + } + + return ret; +} + +static int at76_iw_handler_get_rate(struct net_device *netdev, + struct iw_request_info *info, + struct iw_param *bitrate, char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + int ret = 0; + + switch (priv->txrate) { + /* return max rate if RATE_AUTO */ + case TX_RATE_AUTO: + bitrate->value = 11000000; + break; + case TX_RATE_1MBIT: + bitrate->value = 1000000; + break; + case TX_RATE_2MBIT: + bitrate->value = 2000000; + break; + case TX_RATE_5_5MBIT: + bitrate->value = 5500000; + break; + case TX_RATE_11MBIT: + bitrate->value = 11000000; + break; + default: + ret = -EINVAL; + } + + bitrate->fixed = (priv->txrate != TX_RATE_AUTO); + bitrate->disabled = 0; + + at76_dbg(DBG_IOCTL, "%s: SIOCGIWRATE - %d", netdev->name, + bitrate->value); + + return ret; +} + +static int at76_iw_handler_set_rts(struct net_device *netdev, + struct iw_request_info *info, + struct iw_param *rts, char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + int ret = -EIWCOMMIT; + int rthr = rts->value; + + at76_dbg(DBG_IOCTL, "%s: SIOCSIWRTS - value %d disabled %s", + netdev->name, rts->value, (rts->disabled) ? "true" : "false"); + + if (rts->disabled) + rthr = MAX_RTS_THRESHOLD; + + if ((rthr < 0) || (rthr > MAX_RTS_THRESHOLD)) + ret = -EINVAL; + else + priv->rts_threshold = rthr; + + return ret; +} + +static int at76_iw_handler_get_rts(struct net_device *netdev, + struct iw_request_info *info, + struct iw_param *rts, char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + + rts->value = priv->rts_threshold; + rts->disabled = (rts->value >= MAX_RTS_THRESHOLD); + rts->fixed = 1; + + at76_dbg(DBG_IOCTL, "%s: SIOCGIWRTS - value %d disabled %s", + netdev->name, rts->value, (rts->disabled) ? "true" : "false"); + + return 0; +} + +static int at76_iw_handler_set_frag(struct net_device *netdev, + struct iw_request_info *info, + struct iw_param *frag, char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + int ret = -EIWCOMMIT; + int fthr = frag->value; + + at76_dbg(DBG_IOCTL, "%s: SIOCSIWFRAG - value %d, disabled %s", + netdev->name, frag->value, + (frag->disabled) ? "true" : "false"); + + if (frag->disabled) + fthr = MAX_FRAG_THRESHOLD; + + if ((fthr < MIN_FRAG_THRESHOLD) || (fthr > MAX_FRAG_THRESHOLD)) + ret = -EINVAL; + else + priv->frag_threshold = fthr & ~0x1; /* get an even value */ + + return ret; +} + +static int at76_iw_handler_get_frag(struct net_device *netdev, + struct iw_request_info *info, + struct iw_param *frag, char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + + frag->value = priv->frag_threshold; + frag->disabled = (frag->value >= MAX_FRAG_THRESHOLD); + frag->fixed = 1; + + at76_dbg(DBG_IOCTL, "%s: SIOCGIWFRAG - value %d, disabled %s", + netdev->name, frag->value, + (frag->disabled) ? "true" : "false"); + + return 0; +} + +static int at76_iw_handler_get_txpow(struct net_device *netdev, + struct iw_request_info *info, + struct iw_param *power, char *extra) +{ + power->value = 15; + power->fixed = 1; /* No power control */ + power->disabled = 0; + power->flags = IW_TXPOW_DBM; + + at76_dbg(DBG_IOCTL, "%s: SIOCGIWTXPOW - txpow %d dBm", netdev->name, + power->value); + + return 0; +} + +/* jal: short retry is handled by the firmware (at least 0.90.x), + while long retry is not (?) */ +static int at76_iw_handler_set_retry(struct net_device *netdev, + struct iw_request_info *info, + struct iw_param *retry, char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + int ret = -EIWCOMMIT; + + at76_dbg(DBG_IOCTL, "%s: SIOCSIWRETRY disabled %d flags 0x%x val %d", + netdev->name, retry->disabled, retry->flags, retry->value); + + if (!retry->disabled && (retry->flags & IW_RETRY_LIMIT)) { + if ((retry->flags & IW_RETRY_MIN) || + !(retry->flags & IW_RETRY_MAX)) + priv->short_retry_limit = retry->value; + else + ret = -EINVAL; + } else + ret = -EINVAL; + + return ret; +} + +/* Adapted (ripped) from atmel.c */ +static int at76_iw_handler_get_retry(struct net_device *netdev, + struct iw_request_info *info, + struct iw_param *retry, char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + + at76_dbg(DBG_IOCTL, "%s: SIOCGIWRETRY", netdev->name); + + retry->disabled = 0; /* Can't be disabled */ + retry->flags = IW_RETRY_LIMIT; + retry->value = priv->short_retry_limit; + + return 0; +} + +static int at76_iw_handler_set_encode(struct net_device *netdev, + struct iw_request_info *info, + struct iw_point *encoding, char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + int index = (encoding->flags & IW_ENCODE_INDEX) - 1; + int len = encoding->length; + + at76_dbg(DBG_IOCTL, "%s: SIOCSIWENCODE - enc.flags %08x " + "pointer %p len %d", netdev->name, encoding->flags, + encoding->pointer, encoding->length); + at76_dbg(DBG_IOCTL, + "%s: SIOCSIWENCODE - old wepstate: enabled %s key_id %d " + "auth_mode %s", netdev->name, + (priv->wep_enabled) ? "true" : "false", priv->wep_key_id, + (priv->auth_mode == + WLAN_AUTH_SHARED_KEY) ? "restricted" : "open"); + + /* take the old default key if index is invalid */ + if ((index < 0) || (index >= WEP_KEYS)) + index = priv->wep_key_id; + + if (len > 0) { + if (len > WEP_LARGE_KEY_LEN) + len = WEP_LARGE_KEY_LEN; + + memset(priv->wep_keys[index], 0, WEP_KEY_LEN); + memcpy(priv->wep_keys[index], extra, len); + priv->wep_keys_len[index] = (len <= WEP_SMALL_KEY_LEN) ? + WEP_SMALL_KEY_LEN : WEP_LARGE_KEY_LEN; + priv->wep_enabled = 1; + } + + priv->wep_key_id = index; + priv->wep_enabled = ((encoding->flags & IW_ENCODE_DISABLED) == 0); + + if (encoding->flags & IW_ENCODE_RESTRICTED) + priv->auth_mode = WLAN_AUTH_SHARED_KEY; + if (encoding->flags & IW_ENCODE_OPEN) + priv->auth_mode = WLAN_AUTH_OPEN; + + at76_dbg(DBG_IOCTL, + "%s: SIOCSIWENCODE - new wepstate: enabled %s key_id %d " + "key_len %d auth_mode %s", netdev->name, + (priv->wep_enabled) ? "true" : "false", priv->wep_key_id + 1, + priv->wep_keys_len[priv->wep_key_id], + (priv->auth_mode == + WLAN_AUTH_SHARED_KEY) ? "restricted" : "open"); + + return -EIWCOMMIT; +} + +static int at76_iw_handler_get_encode(struct net_device *netdev, + struct iw_request_info *info, + struct iw_point *encoding, char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + int index = (encoding->flags & IW_ENCODE_INDEX) - 1; + + if ((index < 0) || (index >= WEP_KEYS)) + index = priv->wep_key_id; + + encoding->flags = + (priv->auth_mode == WLAN_AUTH_SHARED_KEY) ? + IW_ENCODE_RESTRICTED : IW_ENCODE_OPEN; + + if (!priv->wep_enabled) + encoding->flags |= IW_ENCODE_DISABLED; + + if (encoding->pointer) { + encoding->length = priv->wep_keys_len[index]; + + memcpy(extra, priv->wep_keys[index], priv->wep_keys_len[index]); + + encoding->flags |= (index + 1); + } + + at76_dbg(DBG_IOCTL, "%s: SIOCGIWENCODE - enc.flags %08x " + "pointer %p len %d", netdev->name, encoding->flags, + encoding->pointer, encoding->length); + at76_dbg(DBG_IOCTL, + "%s: SIOCGIWENCODE - wepstate: enabled %s key_id %d " + "key_len %d auth_mode %s", netdev->name, + (priv->wep_enabled) ? "true" : "false", priv->wep_key_id + 1, + priv->wep_keys_len[priv->wep_key_id], + (priv->auth_mode == + WLAN_AUTH_SHARED_KEY) ? "restricted" : "open"); + + return 0; +} + +static int at76_iw_handler_set_power(struct net_device *netdev, + struct iw_request_info *info, + struct iw_param *prq, char *extra) +{ + int err = -EIWCOMMIT; + struct at76_priv *priv = netdev_priv(netdev); + + at76_dbg(DBG_IOCTL, + "%s: SIOCSIWPOWER - disabled %s flags 0x%x value 0x%x", + netdev->name, (prq->disabled) ? "true" : "false", prq->flags, + prq->value); + + if (prq->disabled) + priv->pm_mode = AT76_PM_OFF; + else { + switch (prq->flags & IW_POWER_MODE) { + case IW_POWER_ALL_R: + case IW_POWER_ON: + break; + default: + err = -EINVAL; + goto exit; + } + if (prq->flags & IW_POWER_PERIOD) + priv->pm_period = prq->value; + + if (prq->flags & IW_POWER_TIMEOUT) { + err = -EINVAL; + goto exit; + } + priv->pm_mode = AT76_PM_ON; + } +exit: + return err; +} + +static int at76_iw_handler_get_power(struct net_device *netdev, + struct iw_request_info *info, + struct iw_param *power, char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + + power->disabled = (priv->pm_mode == AT76_PM_OFF); + if (!power->disabled) { + power->flags = IW_POWER_PERIOD | IW_POWER_ALL_R; + power->value = priv->pm_period; + } + + at76_dbg(DBG_IOCTL, "%s: SIOCGIWPOWER - %s flags 0x%x value 0x%x", + netdev->name, power->disabled ? "disabled" : "enabled", + power->flags, power->value); + + return 0; +} + +/******************************************************************************* + * Private IOCTLS + */ +static int at76_iw_set_short_preamble(struct net_device *netdev, + struct iw_request_info *info, char *name, + char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + int val = *((int *)name); + int ret = -EIWCOMMIT; + + at76_dbg(DBG_IOCTL, "%s: AT76_SET_SHORT_PREAMBLE, %d", + netdev->name, val); + + if (val < PREAMBLE_TYPE_LONG || val > PREAMBLE_TYPE_AUTO) + ret = -EINVAL; + else + priv->preamble_type = val; + + return ret; +} + +static int at76_iw_get_short_preamble(struct net_device *netdev, + struct iw_request_info *info, + union iwreq_data *wrqu, char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + + snprintf(wrqu->name, sizeof(wrqu->name), "%s (%d)", + preambles[priv->preamble_type], priv->preamble_type); + return 0; +} + +static int at76_iw_set_debug(struct net_device *netdev, + struct iw_request_info *info, + struct iw_point *data, char *extra) +{ + char *ptr; + u32 val; + + if (data->length > 0) { + val = simple_strtol(extra, &ptr, 0); + + if (ptr == extra) + val = DBG_DEFAULTS; + + at76_dbg(DBG_IOCTL, "%s: AT76_SET_DEBUG input %d: %s -> 0x%x", + netdev->name, data->length, extra, val); + } else + val = DBG_DEFAULTS; + + at76_dbg(DBG_IOCTL, "%s: AT76_SET_DEBUG, old 0x%x, new 0x%x", + netdev->name, at76_debug, val); + + /* jal: some more output to pin down lockups */ + at76_dbg(DBG_IOCTL, "%s: netif running %d queue_stopped %d " + "carrier_ok %d", netdev->name, netif_running(netdev), + netif_queue_stopped(netdev), netif_carrier_ok(netdev)); + + at76_debug = val; + + return 0; +} + +static int at76_iw_get_debug(struct net_device *netdev, + struct iw_request_info *info, + union iwreq_data *wrqu, char *extra) +{ + snprintf(wrqu->name, sizeof(wrqu->name), "0x%08x", at76_debug); + return 0; +} + +static int at76_iw_set_powersave_mode(struct net_device *netdev, + struct iw_request_info *info, char *name, + char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + int val = *((int *)name); + int ret = -EIWCOMMIT; + + at76_dbg(DBG_IOCTL, "%s: AT76_SET_POWERSAVE_MODE, %d (%s)", + netdev->name, val, + val == AT76_PM_OFF ? "active" : val == AT76_PM_ON ? "save" : + val == AT76_PM_SMART ? "smart save" : "<invalid>"); + if (val < AT76_PM_OFF || val > AT76_PM_SMART) + ret = -EINVAL; + else + priv->pm_mode = val; + + return ret; +} + +static int at76_iw_get_powersave_mode(struct net_device *netdev, + struct iw_request_info *info, + union iwreq_data *wrqu, char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + int *param = (int *)extra; + + param[0] = priv->pm_mode; + return 0; +} + +static int at76_iw_set_scan_times(struct net_device *netdev, + struct iw_request_info *info, char *name, + char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + int mint = *((int *)name); + int maxt = *((int *)name + 1); + int ret = -EIWCOMMIT; + + at76_dbg(DBG_IOCTL, "%s: AT76_SET_SCAN_TIMES - min %d max %d", + netdev->name, mint, maxt); + if (mint <= 0 || maxt <= 0 || mint > maxt) + ret = -EINVAL; + else { + priv->scan_min_time = mint; + priv->scan_max_time = maxt; + } + + return ret; +} + +static int at76_iw_get_scan_times(struct net_device *netdev, + struct iw_request_info *info, + union iwreq_data *wrqu, char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + int *param = (int *)extra; + + param[0] = priv->scan_min_time; + param[1] = priv->scan_max_time; + return 0; +} + +static int at76_iw_set_scan_mode(struct net_device *netdev, + struct iw_request_info *info, char *name, + char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + int val = *((int *)name); + int ret = -EIWCOMMIT; + + at76_dbg(DBG_IOCTL, "%s: AT76_SET_SCAN_MODE - mode %s", + netdev->name, (val = SCAN_TYPE_ACTIVE) ? "active" : + (val = SCAN_TYPE_PASSIVE) ? "passive" : "<invalid>"); + + if (val != SCAN_TYPE_ACTIVE && val != SCAN_TYPE_PASSIVE) + ret = -EINVAL; + else + priv->scan_mode = val; + + return ret; +} + +static int at76_iw_get_scan_mode(struct net_device *netdev, + struct iw_request_info *info, + union iwreq_data *wrqu, char *extra) +{ + struct at76_priv *priv = netdev_priv(netdev); + int *param = (int *)extra; + + param[0] = priv->scan_mode; + return 0; +} + +#define AT76_SET_HANDLER(h, f) [h - SIOCIWFIRST] = (iw_handler) f + +/* Standard wireless handlers */ +static const iw_handler at76_handlers[] = { + AT76_SET_HANDLER(SIOCSIWCOMMIT, at76_iw_handler_commit), + AT76_SET_HANDLER(SIOCGIWNAME, at76_iw_handler_get_name), + AT76_SET_HANDLER(SIOCSIWFREQ, at76_iw_handler_set_freq), + AT76_SET_HANDLER(SIOCGIWFREQ, at76_iw_handler_get_freq), + AT76_SET_HANDLER(SIOCSIWMODE, at76_iw_handler_set_mode), + AT76_SET_HANDLER(SIOCGIWMODE, at76_iw_handler_get_mode), + AT76_SET_HANDLER(SIOCGIWRANGE, at76_iw_handler_get_range), + AT76_SET_HANDLER(SIOCSIWSPY, at76_iw_handler_set_spy), + AT76_SET_HANDLER(SIOCGIWSPY, at76_iw_handler_get_spy), + AT76_SET_HANDLER(SIOCSIWTHRSPY, at76_iw_handler_set_thrspy), + AT76_SET_HANDLER(SIOCGIWTHRSPY, at76_iw_handler_get_thrspy), + AT76_SET_HANDLER(SIOCSIWAP, at76_iw_handler_set_wap), + AT76_SET_HANDLER(SIOCGIWAP, at76_iw_handler_get_wap), + AT76_SET_HANDLER(SIOCSIWSCAN, at76_iw_handler_set_scan), + AT76_SET_HANDLER(SIOCGIWSCAN, at76_iw_handler_get_scan), + AT76_SET_HANDLER(SIOCSIWESSID, at76_iw_handler_set_essid), + AT76_SET_HANDLER(SIOCGIWESSID, at76_iw_handler_get_essid), + AT76_SET_HANDLER(SIOCSIWRATE, at76_iw_handler_set_rate), + AT76_SET_HANDLER(SIOCGIWRATE, at76_iw_handler_get_rate), + AT76_SET_HANDLER(SIOCSIWRTS, at76_iw_handler_set_rts), + AT76_SET_HANDLER(SIOCGIWRTS, at76_iw_handler_get_rts), + AT76_SET_HANDLER(SIOCSIWFRAG, at76_iw_handler_set_frag), + AT76_SET_HANDLER(SIOCGIWFRAG, at76_iw_handler_get_frag), + AT76_SET_HANDLER(SIOCGIWTXPOW, at76_iw_handler_get_txpow), + AT76_SET_HANDLER(SIOCSIWRETRY, at76_iw_handler_set_retry), + AT76_SET_HANDLER(SIOCGIWRETRY, at76_iw_handler_get_retry), + AT76_SET_HANDLER(SIOCSIWENCODE, at76_iw_handler_set_encode), + AT76_SET_HANDLER(SIOCGIWENCODE, at76_iw_handler_get_encode), + AT76_SET_HANDLER(SIOCSIWPOWER, at76_iw_handler_set_power), + AT76_SET_HANDLER(SIOCGIWPOWER, at76_iw_handler_get_power) +}; + +#define AT76_SET_PRIV(h, f) [h - SIOCIWFIRSTPRIV] = (iw_handler) f + +/* Private wireless handlers */ +static const iw_handler at76_priv_handlers[] = { + AT76_SET_PRIV(AT76_SET_SHORT_PREAMBLE, at76_iw_set_short_preamble), + AT76_SET_PRIV(AT76_GET_SHORT_PREAMBLE, at76_iw_get_short_preamble), + AT76_SET_PRIV(AT76_SET_DEBUG, at76_iw_set_debug), + AT76_SET_PRIV(AT76_GET_DEBUG, at76_iw_get_debug), + AT76_SET_PRIV(AT76_SET_POWERSAVE_MODE, at76_iw_set_powersave_mode), + AT76_SET_PRIV(AT76_GET_POWERSAVE_MODE, at76_iw_get_powersave_mode), + AT76_SET_PRIV(AT76_SET_SCAN_TIMES, at76_iw_set_scan_times), + AT76_SET_PRIV(AT76_GET_SCAN_TIMES, at76_iw_get_scan_times), + AT76_SET_PRIV(AT76_SET_SCAN_MODE, at76_iw_set_scan_mode), + AT76_SET_PRIV(AT76_GET_SCAN_MODE, at76_iw_get_scan_mode), +}; + +/* Names and arguments of private wireless handlers */ +static const struct iw_priv_args at76_priv_args[] = { + /* 0 - long, 1 - short */ + {AT76_SET_SHORT_PREAMBLE, + IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "set_preamble"}, + + {AT76_GET_SHORT_PREAMBLE, + 0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_FIXED | 10, "get_preamble"}, + + /* we must pass the new debug mask as a string, because iwpriv cannot + * parse hex numbers starting with 0x :-( */ + {AT76_SET_DEBUG, + IW_PRIV_TYPE_CHAR | 10, 0, "set_debug"}, + + {AT76_GET_DEBUG, + 0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_FIXED | 10, "get_debug"}, + + /* 1 - active, 2 - power save, 3 - smart power save */ + {AT76_SET_POWERSAVE_MODE, + IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "set_powersave"}, + + {AT76_GET_POWERSAVE_MODE, + 0, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, "get_powersave"}, + + /* min_channel_time, max_channel_time */ + {AT76_SET_SCAN_TIMES, + IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 2, 0, "set_scan_times"}, + + {AT76_GET_SCAN_TIMES, + 0, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 2, "get_scan_times"}, + + /* 0 - active, 1 - passive scan */ + {AT76_SET_SCAN_MODE, + IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "set_scan_mode"}, + + {AT76_GET_SCAN_MODE, + 0, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, "get_scan_mode"}, +}; + +static const struct iw_handler_def at76_handler_def = { + .num_standard = ARRAY_SIZE(at76_handlers), + .num_private = ARRAY_SIZE(at76_priv_handlers), + .num_private_args = ARRAY_SIZE(at76_priv_args), + .standard = at76_handlers, + .private = at76_priv_handlers, + .private_args = at76_priv_args, + .get_wireless_stats = at76_get_wireless_stats, +}; + +static const u8 snapsig[] = { 0xaa, 0xaa, 0x03 }; + +/* RFC 1042 encapsulates Ethernet frames in 802.2 SNAP (0xaa, 0xaa, 0x03) with + * a SNAP OID of 0 (0x00, 0x00, 0x00) */ +static const u8 rfc1042sig[] = { 0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00 }; + +static int at76_tx(struct sk_buff *skb, struct net_device *netdev) +{ + struct at76_priv *priv = netdev_priv(netdev); + struct net_device_stats *stats = &priv->stats; + int ret = 0; + int wlen; + int submit_len; + struct at76_tx_buffer *tx_buffer = priv->bulk_out_buffer; + struct ieee80211_hdr_3addr *i802_11_hdr = + (struct ieee80211_hdr_3addr *)tx_buffer->packet; + u8 *payload = i802_11_hdr->payload; + struct ethhdr *eh = (struct ethhdr *)skb->data; + + if (netif_queue_stopped(netdev)) { + printk(KERN_ERR "%s: %s called while netdev is stopped\n", + netdev->name, __func__); + /* skip this packet */ + dev_kfree_skb(skb); + return 0; + } + + if (priv->tx_urb->status == -EINPROGRESS) { + printk(KERN_ERR "%s: %s called while tx urb is pending\n", + netdev->name, __func__); + /* skip this packet */ + dev_kfree_skb(skb); + return 0; + } + + if (skb->len < ETH_HLEN) { + printk(KERN_ERR "%s: %s: skb too short (%d)\n", + netdev->name, __func__, skb->len); + dev_kfree_skb(skb); + return 0; + } + + at76_ledtrig_tx_activity(); /* tell ledtrigger we send a packet */ + + /* we can get rid of memcpy if we set netdev->hard_header_len to + reserve enough space, but we would need to keep the skb around */ + + if (ntohs(eh->h_proto) <= ETH_DATA_LEN) { + /* this is a 802.3 packet */ + if (skb->len >= ETH_HLEN + sizeof(rfc1042sig) + && skb->data[ETH_HLEN] == rfc1042sig[0] + && skb->data[ETH_HLEN + 1] == rfc1042sig[1]) { + /* higher layer delivered SNAP header - keep it */ + memcpy(payload, skb->data + ETH_HLEN, + skb->len - ETH_HLEN); + wlen = IEEE80211_3ADDR_LEN + skb->len - ETH_HLEN; + } else { + printk(KERN_ERR "%s: dropping non-SNAP 802.2 packet " + "(DSAP 0x%02x SSAP 0x%02x cntrl 0x%02x)\n", + priv->netdev->name, skb->data[ETH_HLEN], + skb->data[ETH_HLEN + 1], + skb->data[ETH_HLEN + 2]); + dev_kfree_skb(skb); + return 0; + } + } else { + /* add RFC 1042 header in front */ + memcpy(payload, rfc1042sig, sizeof(rfc1042sig)); + memcpy(payload + sizeof(rfc1042sig), &eh->h_proto, + skb->len - offsetof(struct ethhdr, h_proto)); + wlen = IEEE80211_3ADDR_LEN + sizeof(rfc1042sig) + skb->len - + offsetof(struct ethhdr, h_proto); + } + + /* make wireless header */ + i802_11_hdr->frame_ctl = + cpu_to_le16(IEEE80211_FTYPE_DATA | + (priv->wep_enabled ? IEEE80211_FCTL_PROTECTED : 0) | + (priv->iw_mode == + IW_MODE_INFRA ? IEEE80211_FCTL_TODS : 0)); + + if (priv->iw_mode == IW_MODE_ADHOC) { + memcpy(i802_11_hdr->addr1, eh->h_dest, ETH_ALEN); + memcpy(i802_11_hdr->addr2, eh->h_source, ETH_ALEN); + memcpy(i802_11_hdr->addr3, priv->bssid, ETH_ALEN); + } else if (priv->iw_mode == IW_MODE_INFRA) { + memcpy(i802_11_hdr->addr1, priv->bssid, ETH_ALEN); + memcpy(i802_11_hdr->addr2, eh->h_source, ETH_ALEN); + memcpy(i802_11_hdr->addr3, eh->h_dest, ETH_ALEN); + } + + i802_11_hdr->duration_id = cpu_to_le16(0); + i802_11_hdr->seq_ctl = cpu_to_le16(0); + + /* setup 'Atmel' header */ + tx_buffer->wlength = cpu_to_le16(wlen); + tx_buffer->tx_rate = priv->txrate; + /* for broadcast destination addresses, the firmware 0.100.x + seems to choose the highest rate set with CMD_STARTUP in + basic_rate_set replacing this value */ + + memset(tx_buffer->reserved, 0, sizeof(tx_buffer->reserved)); + + tx_buffer->padding = at76_calc_padding(wlen); + submit_len = wlen + AT76_TX_HDRLEN + tx_buffer->padding; + + at76_dbg(DBG_TX_DATA_CONTENT, "%s skb->data %s", priv->netdev->name, + hex2str(skb->data, 32)); + at76_dbg(DBG_TX_DATA, "%s tx: wlen 0x%x pad 0x%x rate %d hdr %s", + priv->netdev->name, + le16_to_cpu(tx_buffer->wlength), + tx_buffer->padding, tx_buffer->tx_rate, + hex2str(i802_11_hdr, sizeof(*i802_11_hdr))); + at76_dbg(DBG_TX_DATA_CONTENT, "%s payload %s", priv->netdev->name, + hex2str(payload, 48)); + + /* send stuff */ + netif_stop_queue(netdev); + netdev->trans_start = jiffies; + + usb_fill_bulk_urb(priv->tx_urb, priv->udev, priv->tx_pipe, tx_buffer, + submit_len, at76_tx_callback, priv); + ret = usb_submit_urb(priv->tx_urb, GFP_ATOMIC); + if (ret) { + stats->tx_errors++; + printk(KERN_ERR "%s: error in tx submit urb: %d\n", + netdev->name, ret); + if (ret == -EINVAL) + printk(KERN_ERR + "%s: -EINVAL: tx urb %p hcpriv %p complete %p\n", + priv->netdev->name, priv->tx_urb, + priv->tx_urb->hcpriv, priv->tx_urb->complete); + } else { + stats->tx_bytes += skb->len; + dev_kfree_skb(skb); + } + + return ret; +} + +static void at76_tx_timeout(struct net_device *netdev) +{ + struct at76_priv *priv = netdev_priv(netdev); + + if (!priv) + return; + dev_warn(&netdev->dev, "tx timeout."); + + usb_unlink_urb(priv->tx_urb); + priv->stats.tx_errors++; +} + +static int at76_submit_rx_urb(struct at76_priv *priv) +{ + int ret; + int size; + struct sk_buff *skb = priv->rx_skb; + + if (!priv->rx_urb) { + printk(KERN_ERR "%s: %s: priv->rx_urb is NULL\n", + priv->netdev->name, __func__); + return -EFAULT; + } + + if (!skb) { + skb = dev_alloc_skb(sizeof(struct at76_rx_buffer)); + if (!skb) { + printk(KERN_ERR "%s: cannot allocate rx skbuff\n", + priv->netdev->name); + ret = -ENOMEM; + goto exit; + } + priv->rx_skb = skb; + } else { + skb_push(skb, skb_headroom(skb)); + skb_trim(skb, 0); + } + + size = skb_tailroom(skb); + usb_fill_bulk_urb(priv->rx_urb, priv->udev, priv->rx_pipe, + skb_put(skb, size), size, at76_rx_callback, priv); + ret = usb_submit_urb(priv->rx_urb, GFP_ATOMIC); + if (ret < 0) { + if (ret == -ENODEV) + at76_dbg(DBG_DEVSTART, + "usb_submit_urb returned -ENODEV"); + else + printk(KERN_ERR "%s: rx, usb_submit_urb failed: %d\n", + priv->netdev->name, ret); + } + +exit: + if (ret < 0 && ret != -ENODEV) + printk(KERN_ERR "%s: cannot submit rx urb - please unload the " + "driver and/or power cycle the device\n", + priv->netdev->name); + + return ret; +} + +static int at76_open(struct net_device *netdev) +{ + struct at76_priv *priv = netdev_priv(netdev); + int ret = 0; + + at76_dbg(DBG_PROC_ENTRY, "%s(): entry", __func__); + + if (mutex_lock_interruptible(&priv->mtx)) + return -EINTR; + + /* if netdev->dev_addr != priv->mac_addr we must + set the mac address in the device ! */ + if (compare_ether_addr(netdev->dev_addr, priv->mac_addr)) { + if (at76_add_mac_address(priv, netdev->dev_addr) >= 0) + at76_dbg(DBG_PROGRESS, "%s: set new MAC addr %s", + netdev->name, mac2str(netdev->dev_addr)); + } + + priv->scan_state = SCAN_IDLE; + priv->last_scan = jiffies; + + ret = at76_submit_rx_urb(priv); + if (ret < 0) { + printk(KERN_ERR "%s: open: submit_rx_urb failed: %d\n", + netdev->name, ret); + goto error; + } + + schedule_delayed_work(&priv->dwork_restart, 0); + + at76_dbg(DBG_PROC_ENTRY, "%s(): end", __func__); +error: + mutex_unlock(&priv->mtx); + return ret < 0 ? ret : 0; +} + +static int at76_stop(struct net_device *netdev) +{ + struct at76_priv *priv = netdev_priv(netdev); + + at76_dbg(DBG_DEVSTART, "%s: ENTER", __func__); + + if (mutex_lock_interruptible(&priv->mtx)) + return -EINTR; + + at76_quiesce(priv); + + if (!priv->device_unplugged) { + /* We are called by "ifconfig ethX down", not because the + * device is not available anymore. */ + at76_set_radio(priv, 0); + + /* We unlink rx_urb because at76_open() re-submits it. + * If unplugged, at76_delete_device() takes care of it. */ + usb_kill_urb(priv->rx_urb); + } + + /* free the bss_list */ + at76_free_bss_list(priv); + + mutex_unlock(&priv->mtx); + at76_dbg(DBG_DEVSTART, "%s: EXIT", __func__); + + return 0; +} + +static void at76_ethtool_get_drvinfo(struct net_device *netdev, + struct ethtool_drvinfo *info) +{ + struct at76_priv *priv = netdev_priv(netdev); + + strncpy(info->driver, DRIVER_NAME, sizeof(info->driver)); + strncpy(info->version, DRIVER_VERSION, sizeof(info->version)); + + usb_make_path(priv->udev, info->bus_info, sizeof(info->bus_info)); + + snprintf(info->fw_version, sizeof(info->fw_version), "%d.%d.%d-%d", + priv->fw_version.major, priv->fw_version.minor, + priv->fw_version.patch, priv->fw_version.build); +} + +static u32 at76_ethtool_get_link(struct net_device *netdev) +{ + struct at76_priv *priv = netdev_priv(netdev); + return priv->mac_state == MAC_CONNECTED; +} + +static struct ethtool_ops at76_ethtool_ops = { + .get_drvinfo = at76_ethtool_get_drvinfo, + .get_link = at76_ethtool_get_link, +}; + +/* Download external firmware */ +static int at76_load_external_fw(struct usb_device *udev, struct fwentry *fwe) +{ + int ret; + int op_mode; + int blockno = 0; + int bsize; + u8 *block; + u8 *buf = fwe->extfw; + int size = fwe->extfw_size; + + if (!buf || !size) + return -ENOENT; + + op_mode = at76_get_op_mode(udev); + at76_dbg(DBG_DEVSTART, "opmode %d", op_mode); + + if (op_mode != OPMODE_NORMAL_NIC_WITHOUT_FLASH) { + dev_printk(KERN_ERR, &udev->dev, "unexpected opmode %d\n", + op_mode); + return -EINVAL; + } + + block = kmalloc(FW_BLOCK_SIZE, GFP_KERNEL); + if (!block) + return -ENOMEM; + + at76_dbg(DBG_DEVSTART, "downloading external firmware"); + + /* for fw >= 0.100, the device needs an extra empty block */ + do { + bsize = min_t(int, size, FW_BLOCK_SIZE); + memcpy(block, buf, bsize); + at76_dbg(DBG_DEVSTART, + "ext fw, size left = %5d, bsize = %4d, blockno = %2d", + size, bsize, blockno); + ret = at76_load_ext_fw_block(udev, blockno, block, bsize); + if (ret != bsize) { + dev_printk(KERN_ERR, &udev->dev, + "loading %dth firmware block failed: %d\n", + blockno, ret); + goto exit; + } + buf += bsize; + size -= bsize; + blockno++; + } while (bsize > 0); + + if (at76_is_505a(fwe->board_type)) { + at76_dbg(DBG_DEVSTART, "200 ms delay for 505a"); + schedule_timeout_interruptible(HZ / 5 + 1); + } + +exit: + kfree(block); + if (ret < 0) + dev_printk(KERN_ERR, &udev->dev, + "downloading external firmware failed: %d\n", ret); + return ret; +} + +/* Download internal firmware */ +static int at76_load_internal_fw(struct usb_device *udev, struct fwentry *fwe) +{ + int ret; + int need_remap = !at76_is_505a(fwe->board_type); + + ret = at76_usbdfu_download(udev, fwe->intfw, fwe->intfw_size, + need_remap ? 0 : 2 * HZ); + + if (ret < 0) { + dev_printk(KERN_ERR, &udev->dev, + "downloading internal fw failed with %d\n", ret); + goto exit; + } + + at76_dbg(DBG_DEVSTART, "sending REMAP"); + + /* no REMAP for 505A (see SF driver) */ + if (need_remap) { + ret = at76_remap(udev); + if (ret < 0) { + dev_printk(KERN_ERR, &udev->dev, + "sending REMAP failed with %d\n", ret); + goto exit; + } + } + + at76_dbg(DBG_DEVSTART, "sleeping for 2 seconds"); + schedule_timeout_interruptible(2 * HZ + 1); + usb_reset_device(udev); + +exit: + return ret; +} + +static int at76_match_essid(struct at76_priv *priv, struct bss_info *ptr) +{ + /* common criteria for both modi */ + + int ret = (priv->essid_size == 0 /* ANY ssid */ || + (priv->essid_size == ptr->ssid_len && + !memcmp(priv->essid, ptr->ssid, ptr->ssid_len))); + if (!ret) + at76_dbg(DBG_BSS_MATCH, + "%s bss table entry %p: essid didn't match", + priv->netdev->name, ptr); + return ret; +} + +static inline int at76_match_mode(struct at76_priv *priv, struct bss_info *ptr) +{ + int ret; + + if (priv->iw_mode == IW_MODE_ADHOC) + ret = ptr->capa & WLAN_CAPABILITY_IBSS; + else + ret = ptr->capa & WLAN_CAPABILITY_ESS; + if (!ret) + at76_dbg(DBG_BSS_MATCH, + "%s bss table entry %p: mode didn't match", + priv->netdev->name, ptr); + return ret; +} + +static int at76_match_rates(struct at76_priv *priv, struct bss_info *ptr) +{ + int i; + + for (i = 0; i < ptr->rates_len; i++) { + u8 rate = ptr->rates[i]; + + if (!(rate & 0x80)) + continue; + + /* this is a basic rate we have to support + (see IEEE802.11, ch. 7.3.2.2) */ + if (rate != (0x80 | hw_rates[0]) + && rate != (0x80 | hw_rates[1]) + && rate != (0x80 | hw_rates[2]) + && rate != (0x80 | hw_rates[3])) { + at76_dbg(DBG_BSS_MATCH, + "%s: bss table entry %p: basic rate %02x not " + "supported", priv->netdev->name, ptr, rate); + return 0; + } + } + + /* if we use short preamble, the bss must support it */ + if (priv->preamble_type == PREAMBLE_TYPE_SHORT && + !(ptr->capa & WLAN_CAPABILITY_SHORT_PREAMBLE)) { + at76_dbg(DBG_BSS_MATCH, + "%s: %p does not support short preamble", + priv->netdev->name, ptr); + return 0; + } else + return 1; +} + +static inline int at76_match_wep(struct at76_priv *priv, struct bss_info *ptr) +{ + if (!priv->wep_enabled && ptr->capa & WLAN_CAPABILITY_PRIVACY) { + /* we have disabled WEP, but the BSS signals privacy */ + at76_dbg(DBG_BSS_MATCH, + "%s: bss table entry %p: requires encryption", + priv->netdev->name, ptr); + return 0; + } + /* otherwise if the BSS does not signal privacy it may well + accept encrypted packets from us ... */ + return 1; +} + +static inline int at76_match_bssid(struct at76_priv *priv, struct bss_info *ptr) +{ + if (!priv->wanted_bssid_valid || + !compare_ether_addr(ptr->bssid, priv->wanted_bssid)) + return 1; + + at76_dbg(DBG_BSS_MATCH, + "%s: requested bssid - %s does not match", + priv->netdev->name, mac2str(priv->wanted_bssid)); + at76_dbg(DBG_BSS_MATCH, + " AP bssid - %s of bss table entry %p", + mac2str(ptr->bssid), ptr); + return 0; +} + +/** + * at76_match_bss - try to find a matching bss in priv->bss + * + * last - last bss tried + * + * last == NULL signals a new round starting with priv->bss_list.next + * this function must be called inside an acquired priv->bss_list_spinlock + * otherwise the timeout on bss may remove the newly chosen entry + */ +static struct bss_info *at76_match_bss(struct at76_priv *priv, + struct bss_info *last) +{ + struct bss_info *ptr = NULL; + struct list_head *curr; + + curr = last ? last->list.next : priv->bss_list.next; + while (curr != &priv->bss_list) { + ptr = list_entry(curr, struct bss_info, list); + if (at76_match_essid(priv, ptr) && at76_match_mode(priv, ptr) + && at76_match_wep(priv, ptr) && at76_match_rates(priv, ptr) + && at76_match_bssid(priv, ptr)) + break; + curr = curr->next; + } + + if (curr == &priv->bss_list) + ptr = NULL; + /* otherwise ptr points to the struct bss_info we have chosen */ + + at76_dbg(DBG_BSS_TABLE, "%s %s: returned %p", priv->netdev->name, + __func__, ptr); + return ptr; +} + +/* Start joining a matching BSS, or create own IBSS */ +static void at76_work_join(struct work_struct *work) +{ + struct at76_priv *priv = container_of(work, struct at76_priv, + work_join); + int ret; + unsigned long flags; + + mutex_lock(&priv->mtx); + + WARN_ON(priv->mac_state != MAC_JOINING); + if (priv->mac_state != MAC_JOINING) + goto exit; + + /* secure the access to priv->curr_bss ! */ + spin_lock_irqsave(&priv->bss_list_spinlock, flags); + priv->curr_bss = at76_match_bss(priv, priv->curr_bss); + spin_unlock_irqrestore(&priv->bss_list_spinlock, flags); + + if (!priv->curr_bss) { + /* here we haven't found a matching (i)bss ... */ + if (priv->iw_mode == IW_MODE_ADHOC) { + at76_set_mac_state(priv, MAC_OWN_IBSS); + at76_start_ibss(priv); + goto exit; + } + /* haven't found a matching BSS in infra mode - try again */ + at76_set_mac_state(priv, MAC_SCANNING); + schedule_work(&priv->work_start_scan); + goto exit; + } + + ret = at76_join_bss(priv, priv->curr_bss); + if (ret < 0) { + printk(KERN_ERR "%s: join_bss failed with %d\n", + priv->netdev->name, ret); + goto exit; + } + + ret = at76_wait_completion(priv, CMD_JOIN); + if (ret != CMD_STATUS_COMPLETE) { + if (ret != CMD_STATUS_TIME_OUT) + printk(KERN_ERR "%s: join_bss completed with %d\n", + priv->netdev->name, ret); + else + printk(KERN_INFO "%s: join_bss ssid %s timed out\n", + priv->netdev->name, + mac2str(priv->curr_bss->bssid)); + + /* retry next BSS immediately */ + schedule_work(&priv->work_join); + goto exit; + } + + /* here we have joined the (I)BSS */ + if (priv->iw_mode == IW_MODE_ADHOC) { + struct bss_info *bptr = priv->curr_bss; + at76_set_mac_state(priv, MAC_CONNECTED); + /* get ESSID, BSSID and channel for priv->curr_bss */ + priv->essid_size = bptr->ssid_len; + memcpy(priv->essid, bptr->ssid, bptr->ssid_len); + memcpy(priv->bssid, bptr->bssid, ETH_ALEN); + priv->channel = bptr->channel; + at76_iwevent_bss_connect(priv->netdev, bptr->bssid); + netif_carrier_on(priv->netdev); + netif_start_queue(priv->netdev); + /* just to be sure */ + cancel_delayed_work(&priv->dwork_get_scan); + cancel_delayed_work(&priv->dwork_auth); + cancel_delayed_work(&priv->dwork_assoc); + } else { + /* send auth req */ + priv->retries = AUTH_RETRIES; + at76_set_mac_state(priv, MAC_AUTH); + at76_auth_req(priv, priv->curr_bss, 1, NULL); + at76_dbg(DBG_MGMT_TIMER, + "%s:%d: starting mgmt_timer + HZ", __func__, __LINE__); + schedule_delayed_work(&priv->dwork_auth, AUTH_TIMEOUT); + } + +exit: + mutex_unlock(&priv->mtx); +} + +/* Reap scan results */ +static void at76_dwork_get_scan(struct work_struct *work) +{ + int status; + int ret; + struct at76_priv *priv = container_of(work, struct at76_priv, + dwork_get_scan.work); + + mutex_lock(&priv->mtx); + WARN_ON(priv->mac_state != MAC_SCANNING); + if (priv->mac_state != MAC_SCANNING) + goto exit; + + status = at76_get_cmd_status(priv->udev, CMD_SCAN); + if (status < 0) { + printk(KERN_ERR "%s: %s: at76_get_cmd_status failed with %d\n", + priv->netdev->name, __func__, status); + status = CMD_STATUS_IN_PROGRESS; + /* INFO: Hope it was a one off error - if not, scanning + further down the line and stop this cycle */ + } + at76_dbg(DBG_PROGRESS, + "%s %s: got cmd_status %d (state %s, need_any %d)", + priv->netdev->name, __func__, status, + mac_states[priv->mac_state], priv->scan_need_any); + + if (status != CMD_STATUS_COMPLETE) { + if ((status != CMD_STATUS_IN_PROGRESS) && + (status != CMD_STATUS_IDLE)) + printk(KERN_ERR "%s: %s: Bad scan status: %s\n", + priv->netdev->name, __func__, + at76_get_cmd_status_string(status)); + + /* the first cmd status after scan start is always a IDLE -> + start the timer to poll again until COMPLETED */ + at76_dbg(DBG_MGMT_TIMER, + "%s:%d: starting mgmt_timer for %d ticks", + __func__, __LINE__, SCAN_POLL_INTERVAL); + schedule_delayed_work(&priv->dwork_get_scan, + SCAN_POLL_INTERVAL); + goto exit; + } + + if (at76_debug & DBG_BSS_TABLE) + at76_dump_bss_table(priv); + + if (priv->scan_need_any) { + ret = at76_start_scan(priv, 0); + if (ret < 0) + printk(KERN_ERR + "%s: %s: start_scan (ANY) failed with %d\n", + priv->netdev->name, __func__, ret); + at76_dbg(DBG_MGMT_TIMER, + "%s:%d: starting mgmt_timer for %d ticks", __func__, + __LINE__, SCAN_POLL_INTERVAL); + schedule_delayed_work(&priv->dwork_get_scan, + SCAN_POLL_INTERVAL); + priv->scan_need_any = 0; + } else { + priv->scan_state = SCAN_COMPLETED; + /* report the end of scan to user space */ + at76_iwevent_scan_complete(priv->netdev); + at76_set_mac_state(priv, MAC_JOINING); + schedule_work(&priv->work_join); + } + +exit: + mutex_unlock(&priv->mtx); +} + +/* Handle loss of beacons from the AP */ +static void at76_dwork_beacon(struct work_struct *work) +{ + struct at76_priv *priv = container_of(work, struct at76_priv, + dwork_beacon.work); + + mutex_lock(&priv->mtx); + if (priv->mac_state != MAC_CONNECTED || priv->iw_mode != IW_MODE_INFRA) + goto exit; + + /* We haven't received any beacons from out AP for BEACON_TIMEOUT */ + printk(KERN_INFO "%s: lost beacon bssid %s\n", + priv->netdev->name, mac2str(priv->curr_bss->bssid)); + + netif_carrier_off(priv->netdev); + netif_stop_queue(priv->netdev); + at76_iwevent_bss_disconnect(priv->netdev); + at76_set_mac_state(priv, MAC_SCANNING); + schedule_work(&priv->work_start_scan); + +exit: + mutex_unlock(&priv->mtx); +} + +/* Handle authentication response timeout */ +static void at76_dwork_auth(struct work_struct *work) +{ + struct at76_priv *priv = container_of(work, struct at76_priv, + dwork_auth.work); + + mutex_lock(&priv->mtx); + WARN_ON(priv->mac_state != MAC_AUTH); + if (priv->mac_state != MAC_AUTH) + goto exit; + + at76_dbg(DBG_PROGRESS, "%s: authentication response timeout", + priv->netdev->name); + + if (priv->retries-- >= 0) { + at76_auth_req(priv, priv->curr_bss, 1, NULL); + at76_dbg(DBG_MGMT_TIMER, "%s:%d: starting mgmt_timer + HZ", + __func__, __LINE__); + schedule_delayed_work(&priv->dwork_auth, AUTH_TIMEOUT); + } else { + /* try to get next matching BSS */ + at76_set_mac_state(priv, MAC_JOINING); + schedule_work(&priv->work_join); + } + +exit: + mutex_unlock(&priv->mtx); +} + +/* Handle association response timeout */ +static void at76_dwork_assoc(struct work_struct *work) +{ + struct at76_priv *priv = container_of(work, struct at76_priv, + dwork_assoc.work); + + mutex_lock(&priv->mtx); + WARN_ON(priv->mac_state != MAC_ASSOC); + if (priv->mac_state != MAC_ASSOC) + goto exit; + + at76_dbg(DBG_PROGRESS, "%s: association response timeout", + priv->netdev->name); + + if (priv->retries-- >= 0) { + at76_assoc_req(priv, priv->curr_bss); + at76_dbg(DBG_MGMT_TIMER, "%s:%d: starting mgmt_timer + HZ", + __func__, __LINE__); + schedule_delayed_work(&priv->dwork_assoc, ASSOC_TIMEOUT); + } else { + /* try to get next matching BSS */ + at76_set_mac_state(priv, MAC_JOINING); + schedule_work(&priv->work_join); + } + +exit: + mutex_unlock(&priv->mtx); +} + +/* Read new bssid in ad-hoc mode */ +static void at76_work_new_bss(struct work_struct *work) +{ + struct at76_priv *priv = container_of(work, struct at76_priv, + work_new_bss); + int ret; + struct mib_mac_mgmt mac_mgmt; + + mutex_lock(&priv->mtx); + + ret = at76_get_mib(priv->udev, MIB_MAC_MGMT, &mac_mgmt, + sizeof(struct mib_mac_mgmt)); + if (ret < 0) { + printk(KERN_ERR "%s: at76_get_mib failed: %d\n", + priv->netdev->name, ret); + goto exit; + } + + at76_dbg(DBG_PROGRESS, "ibss_change = 0x%2x", mac_mgmt.ibss_change); + memcpy(priv->bssid, mac_mgmt.current_bssid, ETH_ALEN); + at76_dbg(DBG_PROGRESS, "using BSSID %s", mac2str(priv->bssid)); + + at76_iwevent_bss_connect(priv->netdev, priv->bssid); + + priv->mib_buf.type = MIB_MAC_MGMT; + priv->mib_buf.size = 1; + priv->mib_buf.index = offsetof(struct mib_mac_mgmt, ibss_change); + priv->mib_buf.data.byte = 0; + + ret = at76_set_mib(priv, &priv->mib_buf); + if (ret < 0) + printk(KERN_ERR "%s: set_mib (ibss change ok) failed: %d\n", + priv->netdev->name, ret); + +exit: + mutex_unlock(&priv->mtx); +} + +static int at76_startup_device(struct at76_priv *priv) +{ + struct at76_card_config *ccfg = &priv->card_config; + int ret; + + at76_dbg(DBG_PARAMS, + "%s param: ssid %.*s (%s) mode %s ch %d wep %s key %d " + "keylen %d", priv->netdev->name, priv->essid_size, priv->essid, + hex2str(priv->essid, IW_ESSID_MAX_SIZE), + priv->iw_mode == IW_MODE_ADHOC ? "adhoc" : "infra", + priv->channel, priv->wep_enabled ? "enabled" : "disabled", + priv->wep_key_id, priv->wep_keys_len[priv->wep_key_id]); + at76_dbg(DBG_PARAMS, + "%s param: preamble %s rts %d retry %d frag %d " + "txrate %s auth_mode %d", priv->netdev->name, + preambles[priv->preamble_type], priv->rts_threshold, + priv->short_retry_limit, priv->frag_threshold, + priv->txrate == TX_RATE_1MBIT ? "1MBit" : priv->txrate == + TX_RATE_2MBIT ? "2MBit" : priv->txrate == + TX_RATE_5_5MBIT ? "5.5MBit" : priv->txrate == + TX_RATE_11MBIT ? "11MBit" : priv->txrate == + TX_RATE_AUTO ? "auto" : "<invalid>", priv->auth_mode); + at76_dbg(DBG_PARAMS, + "%s param: pm_mode %d pm_period %d auth_mode %s " + "scan_times %d %d scan_mode %s", + priv->netdev->name, priv->pm_mode, priv->pm_period, + priv->auth_mode == WLAN_AUTH_OPEN ? "open" : "shared_secret", + priv->scan_min_time, priv->scan_max_time, + priv->scan_mode == SCAN_TYPE_ACTIVE ? "active" : "passive"); + + memset(ccfg, 0, sizeof(struct at76_card_config)); + ccfg->promiscuous_mode = 0; + ccfg->short_retry_limit = priv->short_retry_limit; + + if (priv->wep_enabled) { + if (priv->wep_keys_len[priv->wep_key_id] > WEP_SMALL_KEY_LEN) + ccfg->encryption_type = 2; + else + ccfg->encryption_type = 1; + + /* jal: always exclude unencrypted if WEP is active */ + ccfg->exclude_unencrypted = 1; + } else { + ccfg->exclude_unencrypted = 0; + ccfg->encryption_type = 0; + } + + ccfg->rts_threshold = cpu_to_le16(priv->rts_threshold); + ccfg->fragmentation_threshold = cpu_to_le16(priv->frag_threshold); + + memcpy(ccfg->basic_rate_set, hw_rates, 4); + /* jal: really needed, we do a set_mib for autorate later ??? */ + ccfg->auto_rate_fallback = (priv->txrate == TX_RATE_AUTO ? 1 : 0); + ccfg->channel = priv->channel; + ccfg->privacy_invoked = priv->wep_enabled; + memcpy(ccfg->current_ssid, priv->essid, IW_ESSID_MAX_SIZE); + ccfg->ssid_len = priv->essid_size; + + ccfg->wep_default_key_id = priv->wep_key_id; + memcpy(ccfg->wep_default_key_value, priv->wep_keys, 4 * WEP_KEY_LEN); + + ccfg->short_preamble = priv->preamble_type; + ccfg->beacon_period = cpu_to_le16(priv->beacon_period); + + ret = at76_set_card_command(priv->udev, CMD_STARTUP, &priv->card_config, + sizeof(struct at76_card_config)); + if (ret < 0) { + printk(KERN_ERR "%s: at76_set_card_command failed: %d\n", + priv->netdev->name, ret); + return ret; + } + + at76_wait_completion(priv, CMD_STARTUP); + + /* remove BSSID from previous run */ + memset(priv->bssid, 0, ETH_ALEN); + + if (at76_set_radio(priv, 1) == 1) + at76_wait_completion(priv, CMD_RADIO_ON); + + ret = at76_set_preamble(priv, priv->preamble_type); + if (ret < 0) + return ret; + + ret = at76_set_frag(priv, priv->frag_threshold); + if (ret < 0) + return ret; + + ret = at76_set_rts(priv, priv->rts_threshold); + if (ret < 0) + return ret; + + ret = at76_set_autorate_fallback(priv, + priv->txrate == TX_RATE_AUTO ? 1 : 0); + if (ret < 0) + return ret; + + ret = at76_set_pm_mode(priv); + if (ret < 0) + return ret; + + if (at76_debug & DBG_MIB) { + at76_dump_mib_mac(priv); + at76_dump_mib_mac_addr(priv); + at76_dump_mib_mac_mgmt(priv); + at76_dump_mib_mac_wep(priv); + at76_dump_mib_mdomain(priv); + at76_dump_mib_phy(priv); + at76_dump_mib_local(priv); + } + + return 0; +} + +/* Restart the interface */ +static void at76_dwork_restart(struct work_struct *work) +{ + struct at76_priv *priv = container_of(work, struct at76_priv, + dwork_restart.work); + + mutex_lock(&priv->mtx); + + netif_carrier_off(priv->netdev); /* stop netdev watchdog */ + netif_stop_queue(priv->netdev); /* stop tx data packets */ + + at76_startup_device(priv); + + if (priv->iw_mode != IW_MODE_MONITOR) { + priv->netdev->type = ARPHRD_ETHER; + at76_set_mac_state(priv, MAC_SCANNING); + schedule_work(&priv->work_start_scan); + } else { + priv->netdev->type = ARPHRD_IEEE80211_RADIOTAP; + at76_start_monitor(priv); + } + + mutex_unlock(&priv->mtx); +} + +/* Initiate scanning */ +static void at76_work_start_scan(struct work_struct *work) +{ + struct at76_priv *priv = container_of(work, struct at76_priv, + work_start_scan); + int ret; + + mutex_lock(&priv->mtx); + + WARN_ON(priv->mac_state != MAC_SCANNING); + if (priv->mac_state != MAC_SCANNING) + goto exit; + + /* only clear the bss list when a scan is actively initiated, + * otherwise simply rely on at76_bss_list_timeout */ + if (priv->scan_state == SCAN_IN_PROGRESS) { + at76_free_bss_list(priv); + priv->scan_need_any = 1; + } else + priv->scan_need_any = 0; + + ret = at76_start_scan(priv, 1); + + if (ret < 0) + printk(KERN_ERR "%s: %s: start_scan failed with %d\n", + priv->netdev->name, __func__, ret); + else { + at76_dbg(DBG_MGMT_TIMER, + "%s:%d: starting mgmt_timer for %d ticks", + __func__, __LINE__, SCAN_POLL_INTERVAL); + schedule_delayed_work(&priv->dwork_get_scan, + SCAN_POLL_INTERVAL); + } + +exit: + mutex_unlock(&priv->mtx); +} + +/* Enable or disable promiscuous mode */ +static void at76_work_set_promisc(struct work_struct *work) +{ + struct at76_priv *priv = container_of(work, struct at76_priv, + work_set_promisc); + int ret = 0; + + mutex_lock(&priv->mtx); + + priv->mib_buf.type = MIB_LOCAL; + priv->mib_buf.size = 1; + priv->mib_buf.index = offsetof(struct mib_local, promiscuous_mode); + priv->mib_buf.data.byte = priv->promisc ? 1 : 0; + + ret = at76_set_mib(priv, &priv->mib_buf); + if (ret < 0) + printk(KERN_ERR "%s: set_mib (promiscuous_mode) failed: %d\n", + priv->netdev->name, ret); + + mutex_unlock(&priv->mtx); +} + +/* Submit Rx urb back to the device */ +static void at76_work_submit_rx(struct work_struct *work) +{ + struct at76_priv *priv = container_of(work, struct at76_priv, + work_submit_rx); + + mutex_lock(&priv->mtx); + at76_submit_rx_urb(priv); + mutex_unlock(&priv->mtx); +} + +/* We got an association response */ +static void at76_rx_mgmt_assoc(struct at76_priv *priv, + struct at76_rx_buffer *buf) +{ + struct ieee80211_assoc_response *resp = + (struct ieee80211_assoc_response *)buf->packet; + u16 assoc_id = le16_to_cpu(resp->aid); + u16 status = le16_to_cpu(resp->status); + + at76_dbg(DBG_RX_MGMT, "%s: rx AssocResp bssid %s capa 0x%04x status " + "0x%04x assoc_id 0x%04x rates %s", priv->netdev->name, + mac2str(resp->header.addr3), le16_to_cpu(resp->capability), + status, assoc_id, hex2str(resp->info_element->data, + resp->info_element->len)); + + if (priv->mac_state != MAC_ASSOC) { + printk(KERN_INFO "%s: AssocResp in state %s ignored\n", + priv->netdev->name, mac_states[priv->mac_state]); + return; + } + + BUG_ON(!priv->curr_bss); + + cancel_delayed_work(&priv->dwork_assoc); + if (status == WLAN_STATUS_SUCCESS) { + struct bss_info *ptr = priv->curr_bss; + priv->assoc_id = assoc_id & 0x3fff; + /* update iwconfig params */ + memcpy(priv->bssid, ptr->bssid, ETH_ALEN); + memcpy(priv->essid, ptr->ssid, ptr->ssid_len); + priv->essid_size = ptr->ssid_len; + priv->channel = ptr->channel; + schedule_work(&priv->work_assoc_done); + } else { + at76_set_mac_state(priv, MAC_JOINING); + schedule_work(&priv->work_join); + } +} + +/* Process disassociation request from the AP */ +static void at76_rx_mgmt_disassoc(struct at76_priv *priv, + struct at76_rx_buffer *buf) +{ + struct ieee80211_disassoc *resp = + (struct ieee80211_disassoc *)buf->packet; + struct ieee80211_hdr_3addr *mgmt = &resp->header; + + at76_dbg(DBG_RX_MGMT, + "%s: rx DisAssoc bssid %s reason 0x%04x destination %s", + priv->netdev->name, mac2str(mgmt->addr3), + le16_to_cpu(resp->reason), mac2str(mgmt->addr1)); + + /* We are not connected, ignore */ + if (priv->mac_state == MAC_SCANNING || priv->mac_state == MAC_INIT + || !priv->curr_bss) + return; + + /* Not our BSSID, ignore */ + if (compare_ether_addr(mgmt->addr3, priv->curr_bss->bssid)) + return; + + /* Not for our STA and not broadcast, ignore */ + if (compare_ether_addr(priv->netdev->dev_addr, mgmt->addr1) + && !is_broadcast_ether_addr(mgmt->addr1)) + return; + + if (priv->mac_state != MAC_ASSOC && priv->mac_state != MAC_CONNECTED + && priv->mac_state != MAC_JOINING) { + printk(KERN_INFO "%s: DisAssoc in state %s ignored\n", + priv->netdev->name, mac_states[priv->mac_state]); + return; + } + + if (priv->mac_state == MAC_CONNECTED) { + netif_carrier_off(priv->netdev); + netif_stop_queue(priv->netdev); + at76_iwevent_bss_disconnect(priv->netdev); + } + cancel_delayed_work(&priv->dwork_get_scan); + cancel_delayed_work(&priv->dwork_beacon); + cancel_delayed_work(&priv->dwork_auth); + cancel_delayed_work(&priv->dwork_assoc); + at76_set_mac_state(priv, MAC_JOINING); + schedule_work(&priv->work_join); +} + +static void at76_rx_mgmt_auth(struct at76_priv *priv, + struct at76_rx_buffer *buf) +{ + struct ieee80211_auth *resp = (struct ieee80211_auth *)buf->packet; + struct ieee80211_hdr_3addr *mgmt = &resp->header; + int seq_nr = le16_to_cpu(resp->transaction); + int alg = le16_to_cpu(resp->algorithm); + int status = le16_to_cpu(resp->status); + + at76_dbg(DBG_RX_MGMT, + "%s: rx AuthFrame bssid %s alg %d seq_nr %d status %d " + "destination %s", priv->netdev->name, mac2str(mgmt->addr3), + alg, seq_nr, status, mac2str(mgmt->addr1)); + + if (alg == WLAN_AUTH_SHARED_KEY && seq_nr == 2) + at76_dbg(DBG_RX_MGMT, "%s: AuthFrame challenge %s ...", + priv->netdev->name, hex2str(resp->info_element, 18)); + + if (priv->mac_state != MAC_AUTH) { + printk(KERN_INFO "%s: ignored AuthFrame in state %s\n", + priv->netdev->name, mac_states[priv->mac_state]); + return; + } + if (priv->auth_mode != alg) { + printk(KERN_INFO "%s: ignored AuthFrame for alg %d\n", + priv->netdev->name, alg); + return; + } + + BUG_ON(!priv->curr_bss); + + /* Not our BSSID or not for our STA, ignore */ + if (compare_ether_addr(mgmt->addr3, priv->curr_bss->bssid) + || compare_ether_addr(priv->netdev->dev_addr, mgmt->addr1)) + return; + + cancel_delayed_work(&priv->dwork_auth); + if (status != WLAN_STATUS_SUCCESS) { + /* try to join next bss */ + at76_set_mac_state(priv, MAC_JOINING); + schedule_work(&priv->work_join); + return; + } + + if (priv->auth_mode == WLAN_AUTH_OPEN || seq_nr == 4) { + priv->retries = ASSOC_RETRIES; + at76_set_mac_state(priv, MAC_ASSOC); + at76_assoc_req(priv, priv->curr_bss); + at76_dbg(DBG_MGMT_TIMER, + "%s:%d: starting mgmt_timer + HZ", __func__, __LINE__); + schedule_delayed_work(&priv->dwork_assoc, ASSOC_TIMEOUT); + return; + } + + WARN_ON(seq_nr != 2); + at76_auth_req(priv, priv->curr_bss, seq_nr + 1, resp->info_element); + at76_dbg(DBG_MGMT_TIMER, "%s:%d: starting mgmt_timer + HZ", __func__, + __LINE__); + schedule_delayed_work(&priv->dwork_auth, AUTH_TIMEOUT); +} + +static void at76_rx_mgmt_deauth(struct at76_priv *priv, + struct at76_rx_buffer *buf) +{ + struct ieee80211_disassoc *resp = + (struct ieee80211_disassoc *)buf->packet; + struct ieee80211_hdr_3addr *mgmt = &resp->header; + + at76_dbg(DBG_RX_MGMT | DBG_PROGRESS, + "%s: rx DeAuth bssid %s reason 0x%04x destination %s", + priv->netdev->name, mac2str(mgmt->addr3), + le16_to_cpu(resp->reason), mac2str(mgmt->addr1)); + + if (priv->mac_state != MAC_AUTH && priv->mac_state != MAC_ASSOC + && priv->mac_state != MAC_CONNECTED) { + printk(KERN_INFO "%s: DeAuth in state %s ignored\n", + priv->netdev->name, mac_states[priv->mac_state]); + return; + } + + BUG_ON(!priv->curr_bss); + + /* Not our BSSID, ignore */ + if (compare_ether_addr(mgmt->addr3, priv->curr_bss->bssid)) + return; + + /* Not for our STA and not broadcast, ignore */ + if (compare_ether_addr(priv->netdev->dev_addr, mgmt->addr1) + && !is_broadcast_ether_addr(mgmt->addr1)) + return; + + if (priv->mac_state == MAC_CONNECTED) + at76_iwevent_bss_disconnect(priv->netdev); + + at76_set_mac_state(priv, MAC_JOINING); + schedule_work(&priv->work_join); + cancel_delayed_work(&priv->dwork_get_scan); + cancel_delayed_work(&priv->dwork_beacon); + cancel_delayed_work(&priv->dwork_auth); + cancel_delayed_work(&priv->dwork_assoc); +} + +static void at76_rx_mgmt_beacon(struct at76_priv *priv, + struct at76_rx_buffer *buf) +{ + int varpar_len; + /* beacon content */ + struct ieee80211_beacon *bdata = (struct ieee80211_beacon *)buf->packet; + struct ieee80211_hdr_3addr *mgmt = &bdata->header; + + struct list_head *lptr; + struct bss_info *match; /* entry matching addr3 with its bssid */ + int new_entry = 0; + int len; + struct ieee80211_info_element *ie; + int have_ssid = 0; + int have_rates = 0; + int have_channel = 0; + int keep_going = 1; + unsigned long flags; + + spin_lock_irqsave(&priv->bss_list_spinlock, flags); + if (priv->mac_state == MAC_CONNECTED) { + /* in state MAC_CONNECTED we use the mgmt_timer to control + the beacon of the BSS */ + BUG_ON(!priv->curr_bss); + + if (!compare_ether_addr(priv->curr_bss->bssid, mgmt->addr3)) { + /* We got our AP's beacon, defer the timeout handler. + Kill pending work first, as schedule_delayed_work() + won't do it. */ + cancel_delayed_work(&priv->dwork_beacon); + schedule_delayed_work(&priv->dwork_beacon, + BEACON_TIMEOUT); + priv->curr_bss->rssi = buf->rssi; + priv->beacons_received++; + goto exit; + } + } + + /* look if we have this BSS already in the list */ + match = NULL; + + if (!list_empty(&priv->bss_list)) { + list_for_each(lptr, &priv->bss_list) { + struct bss_info *bss_ptr = + list_entry(lptr, struct bss_info, list); + if (!compare_ether_addr(bss_ptr->bssid, mgmt->addr3)) { + match = bss_ptr; + break; + } + } + } + + if (!match) { + /* BSS not in the list - append it */ + match = kzalloc(sizeof(struct bss_info), GFP_ATOMIC); + if (!match) { + at76_dbg(DBG_BSS_TABLE, + "%s: cannot kmalloc new bss info (%zd byte)", + priv->netdev->name, sizeof(struct bss_info)); + goto exit; + } + new_entry = 1; + list_add_tail(&match->list, &priv->bss_list); + } + + match->capa = le16_to_cpu(bdata->capability); + match->beacon_interval = le16_to_cpu(bdata->beacon_interval); + match->rssi = buf->rssi; + match->link_qual = buf->link_quality; + match->noise_level = buf->noise_level; + memcpy(match->bssid, mgmt->addr3, ETH_ALEN); + at76_dbg(DBG_RX_BEACON, "%s: bssid %s", priv->netdev->name, + mac2str(match->bssid)); + + ie = bdata->info_element; + + /* length of var length beacon parameters */ + varpar_len = min_t(int, le16_to_cpu(buf->wlength) - + sizeof(struct ieee80211_beacon), + BEACON_MAX_DATA_LENGTH); + + /* This routine steps through the bdata->data array to get + * some useful information about the access point. + * Currently, this implementation supports receipt of: SSID, + * supported transfer rates and channel, in any order, with some + * tolerance for intermittent unknown codes (although this + * functionality may not be necessary as the useful information will + * usually arrive in consecutively, but there have been some + * reports of some of the useful information fields arriving in a + * different order). + * It does not support any more IE types although MFIE_TYPE_TIM may + * be supported (on my AP at least). + * The bdata->data array is about 1500 bytes long but only ~36 of those + * bytes are useful, hence the have_ssid etc optimizations. */ + + while (keep_going && + ((&ie->data[ie->len] - (u8 *)bdata->info_element) <= + varpar_len)) { + + switch (ie->id) { + + case MFIE_TYPE_SSID: + if (have_ssid) + break; + + len = min_t(int, IW_ESSID_MAX_SIZE, ie->len); + + /* we copy only if this is a new entry, + or the incoming SSID is not a hidden SSID. This + will protect us from overwriting a real SSID read + in a ProbeResponse with a hidden one from a + following beacon. */ + if (!new_entry && at76_is_hidden_ssid(ie->data, len)) { + have_ssid = 1; + break; + } + + match->ssid_len = len; + memcpy(match->ssid, ie->data, len); + at76_dbg(DBG_RX_BEACON, "%s: SSID - %.*s", + priv->netdev->name, len, match->ssid); + have_ssid = 1; + break; + + case MFIE_TYPE_RATES: + if (have_rates) + break; + + match->rates_len = + min_t(int, sizeof(match->rates), ie->len); + memcpy(match->rates, ie->data, match->rates_len); + have_rates = 1; + at76_dbg(DBG_RX_BEACON, "%s: SUPPORTED RATES %s", + priv->netdev->name, + hex2str(ie->data, ie->len)); + break; + + case MFIE_TYPE_DS_SET: + if (have_channel) + break; + + match->channel = ie->data[0]; + have_channel = 1; + at76_dbg(DBG_RX_BEACON, "%s: CHANNEL - %d", + priv->netdev->name, match->channel); + break; + + case MFIE_TYPE_CF_SET: + case MFIE_TYPE_TIM: + case MFIE_TYPE_IBSS_SET: + default: + at76_dbg(DBG_RX_BEACON, "%s: beacon IE id %d len %d %s", + priv->netdev->name, ie->id, ie->len, + hex2str(ie->data, ie->len)); + break; + } + + /* advance to the next informational element */ + next_ie(&ie); + + /* Optimization: after all, the bdata->data array is + * varpar_len bytes long, whereas we get all of the useful + * information after only ~36 bytes, this saves us a lot of + * time (and trouble as the remaining portion of the array + * could be full of junk) + * Comment this out if you want to see what other information + * comes from the AP - although little of it may be useful */ + } + + at76_dbg(DBG_RX_BEACON, "%s: Finished processing beacon data", + priv->netdev->name); + + match->last_rx = jiffies; /* record last rx of beacon */ + +exit: + spin_unlock_irqrestore(&priv->bss_list_spinlock, flags); +} + +/* Calculate the link level from a given rx_buffer */ +static void at76_calc_level(struct at76_priv *priv, struct at76_rx_buffer *buf, + struct iw_quality *qual) +{ + /* just a guess for now, might be different for other chips */ + int max_rssi = 42; + + qual->level = (buf->rssi * 100 / max_rssi); + if (qual->level > 100) + qual->level = 100; + qual->updated |= IW_QUAL_LEVEL_UPDATED; +} + +/* Calculate the link quality from a given rx_buffer */ +static void at76_calc_qual(struct at76_priv *priv, struct at76_rx_buffer *buf, + struct iw_quality *qual) +{ + if (at76_is_intersil(priv->board_type)) + qual->qual = buf->link_quality; + else { + unsigned long elapsed; + + /* Update qual at most once a second */ + elapsed = jiffies - priv->beacons_last_qual; + if (elapsed < 1 * HZ) + return; + + qual->qual = qual->level * priv->beacons_received * + msecs_to_jiffies(priv->beacon_period) / elapsed; + + priv->beacons_last_qual = jiffies; + priv->beacons_received = 0; + } + qual->qual = (qual->qual > 100) ? 100 : qual->qual; + qual->updated |= IW_QUAL_QUAL_UPDATED; +} + +/* Calculate the noise quality from a given rx_buffer */ +static void at76_calc_noise(struct at76_priv *priv, struct at76_rx_buffer *buf, + struct iw_quality *qual) +{ + qual->noise = 0; + qual->updated |= IW_QUAL_NOISE_INVALID; +} + +static void at76_update_wstats(struct at76_priv *priv, + struct at76_rx_buffer *buf) +{ + struct iw_quality *qual = &priv->wstats.qual; + + if (buf->rssi && priv->mac_state == MAC_CONNECTED) { + qual->updated = 0; + at76_calc_level(priv, buf, qual); + at76_calc_qual(priv, buf, qual); + at76_calc_noise(priv, buf, qual); + } else { + qual->qual = 0; + qual->level = 0; + qual->noise = 0; + qual->updated = IW_QUAL_ALL_INVALID; + } +} + +static void at76_rx_mgmt(struct at76_priv *priv, struct at76_rx_buffer *buf) +{ + struct ieee80211_hdr_3addr *mgmt = + (struct ieee80211_hdr_3addr *)buf->packet; + u16 framectl = le16_to_cpu(mgmt->frame_ctl); + + /* update wstats */ + if (priv->mac_state != MAC_INIT && priv->mac_state != MAC_SCANNING) { + /* jal: this is a dirty hack needed by Tim in ad-hoc mode */ + /* Data packets always seem to have a 0 link level, so we + only read link quality info from management packets. + Atmel driver actually averages the present, and previous + values, we just present the raw value at the moment - TJS */ + if (priv->iw_mode == IW_MODE_ADHOC + || (priv->curr_bss + && !compare_ether_addr(mgmt->addr3, + priv->curr_bss->bssid))) + at76_update_wstats(priv, buf); + } + + at76_dbg(DBG_RX_MGMT_CONTENT, "%s rx mgmt framectl 0x%x %s", + priv->netdev->name, framectl, + hex2str(mgmt, le16_to_cpu(buf->wlength))); + + switch (framectl & IEEE80211_FCTL_STYPE) { + case IEEE80211_STYPE_BEACON: + case IEEE80211_STYPE_PROBE_RESP: + at76_rx_mgmt_beacon(priv, buf); + break; + + case IEEE80211_STYPE_ASSOC_RESP: + at76_rx_mgmt_assoc(priv, buf); + break; + + case IEEE80211_STYPE_DISASSOC: + at76_rx_mgmt_disassoc(priv, buf); + break; + + case IEEE80211_STYPE_AUTH: + at76_rx_mgmt_auth(priv, buf); + break; + + case IEEE80211_STYPE_DEAUTH: + at76_rx_mgmt_deauth(priv, buf); + break; + + default: + printk(KERN_DEBUG "%s: ignoring frame with framectl 0x%04x\n", + priv->netdev->name, framectl); + } + + return; +} + +/* Convert the 802.11 header into an ethernet-style header, make skb + * ready for consumption by netif_rx() */ +static void at76_ieee80211_to_eth(struct sk_buff *skb, int iw_mode) +{ + struct ieee80211_hdr_3addr *i802_11_hdr; + struct ethhdr *eth_hdr_p; + u8 *src_addr; + u8 *dest_addr; + + i802_11_hdr = (struct ieee80211_hdr_3addr *)skb->data; + + /* That would be the ethernet header if the hardware converted + * the frame for us. Make sure the source and the destination + * match the 802.11 header. Which hardware does it? */ + eth_hdr_p = (struct ethhdr *)skb_pull(skb, IEEE80211_3ADDR_LEN); + + dest_addr = i802_11_hdr->addr1; + if (iw_mode == IW_MODE_ADHOC) + src_addr = i802_11_hdr->addr2; + else + src_addr = i802_11_hdr->addr3; + + if (!compare_ether_addr(eth_hdr_p->h_source, src_addr) && + !compare_ether_addr(eth_hdr_p->h_dest, dest_addr)) + /* Yes, we already have an ethernet header */ + skb_reset_mac_header(skb); + else { + u16 len; + + /* Need to build an ethernet header */ + if (!memcmp(skb->data, snapsig, sizeof(snapsig))) { + /* SNAP frame - decapsulate, keep proto */ + skb_push(skb, offsetof(struct ethhdr, h_proto) - + sizeof(rfc1042sig)); + len = 0; + } else { + /* 802.3 frame, proto is length */ + len = skb->len; + skb_push(skb, ETH_HLEN); + } + + skb_reset_mac_header(skb); + eth_hdr_p = eth_hdr(skb); + /* This needs to be done in this order (eth_hdr_p->h_dest may + * overlap src_addr) */ + memcpy(eth_hdr_p->h_source, src_addr, ETH_ALEN); + memcpy(eth_hdr_p->h_dest, dest_addr, ETH_ALEN); + if (len) + eth_hdr_p->h_proto = htons(len); + } + + skb->protocol = eth_type_trans(skb, skb->dev); +} + +/* Check for fragmented data in priv->rx_skb. If the packet was no fragment + or it was the last of a fragment set a skb containing the whole packet + is returned for further processing. Otherwise we get NULL and are + done and the packet is either stored inside the fragment buffer + or thrown away. Every returned skb starts with the ieee802_11 header + and contains _no_ FCS at the end */ +static struct sk_buff *at76_check_for_rx_frags(struct at76_priv *priv) +{ + struct sk_buff *skb = priv->rx_skb; + struct at76_rx_buffer *buf = (struct at76_rx_buffer *)skb->data; + struct ieee80211_hdr_3addr *i802_11_hdr = + (struct ieee80211_hdr_3addr *)buf->packet; + /* seq_ctrl, fragment_number, sequence number of new packet */ + u16 sctl = le16_to_cpu(i802_11_hdr->seq_ctl); + u16 fragnr = sctl & 0xf; + u16 seqnr = sctl >> 4; + u16 frame_ctl = le16_to_cpu(i802_11_hdr->frame_ctl); + + /* Length including the IEEE802.11 header, but without the trailing + * FCS and without the Atmel Rx header */ + int length = le16_to_cpu(buf->wlength) - IEEE80211_FCS_LEN; + + /* where does the data payload start in skb->data ? */ + u8 *data = i802_11_hdr->payload; + + /* length of payload, excl. the trailing FCS */ + int data_len = length - IEEE80211_3ADDR_LEN; + + int i; + struct rx_data_buf *bptr, *optr; + unsigned long oldest = ~0UL; + + at76_dbg(DBG_RX_FRAGS, + "%s: rx data frame_ctl %04x addr2 %s seq/frag %d/%d " + "length %d data %d: %s ...", priv->netdev->name, frame_ctl, + mac2str(i802_11_hdr->addr2), seqnr, fragnr, length, data_len, + hex2str(data, 32)); + + at76_dbg(DBG_RX_FRAGS_SKB, "%s: incoming skb: head %p data %p " + "tail %p end %p len %d", priv->netdev->name, skb->head, + skb->data, skb_tail_pointer(skb), skb_end_pointer(skb), + skb->len); + + if (data_len < 0) { + /* make sure data starts in the buffer */ + printk(KERN_INFO "%s: data frame too short\n", + priv->netdev->name); + return NULL; + } + + WARN_ON(length <= AT76_RX_HDRLEN); + if (length <= AT76_RX_HDRLEN) + return NULL; + + /* remove the at76_rx_buffer header - we don't need it anymore */ + /* we need the IEEE802.11 header (for the addresses) if this packet + is the first of a chain */ + skb_pull(skb, AT76_RX_HDRLEN); + + /* remove FCS at end */ + skb_trim(skb, length); + + at76_dbg(DBG_RX_FRAGS_SKB, "%s: trimmed skb: head %p data %p tail %p " + "end %p len %d data %p data_len %d", priv->netdev->name, + skb->head, skb->data, skb_tail_pointer(skb), + skb_end_pointer(skb), skb->len, data, data_len); + + if (fragnr == 0 && !(frame_ctl & IEEE80211_FCTL_MOREFRAGS)) { + /* unfragmented packet received */ + /* Use a new skb for the next receive */ + priv->rx_skb = NULL; + at76_dbg(DBG_RX_FRAGS, "%s: unfragmented", priv->netdev->name); + return skb; + } + + /* look if we've got a chain for the sender address. + afterwards optr points to first free or the oldest entry, + or, if i < NR_RX_DATA_BUF, bptr points to the entry for the + sender address */ + /* determining the oldest entry doesn't cope with jiffies wrapping + but I don't care to delete a young entry at these rare moments ... */ + + bptr = priv->rx_data; + optr = NULL; + for (i = 0; i < NR_RX_DATA_BUF; i++, bptr++) { + if (!bptr->skb) { + optr = bptr; + oldest = 0UL; + continue; + } + + if (!compare_ether_addr(i802_11_hdr->addr2, bptr->sender)) + break; + + if (!optr) { + optr = bptr; + oldest = bptr->last_rx; + } else if (bptr->last_rx < oldest) + optr = bptr; + } + + if (i < NR_RX_DATA_BUF) { + + at76_dbg(DBG_RX_FRAGS, "%s: %d. cacheentry (seq/frag = %d/%d) " + "matched sender addr", + priv->netdev->name, i, bptr->seqnr, bptr->fragnr); + + /* bptr points to an entry for the sender address */ + if (bptr->seqnr == seqnr) { + int left; + /* the fragment has the current sequence number */ + if (((bptr->fragnr + 1) & 0xf) != fragnr) { + /* wrong fragment number -> ignore it */ + /* is & 0xf necessary above ??? */ + at76_dbg(DBG_RX_FRAGS, + "%s: frag nr mismatch: %d + 1 != %d", + priv->netdev->name, bptr->fragnr, + fragnr); + return NULL; + } + bptr->last_rx = jiffies; + /* the next following fragment number -> + add the data at the end */ + + /* for test only ??? */ + left = skb_tailroom(bptr->skb); + if (left < data_len) + printk(KERN_INFO + "%s: only %d byte free (need %d)\n", + priv->netdev->name, left, data_len); + else + memcpy(skb_put(bptr->skb, data_len), data, + data_len); + + bptr->fragnr = fragnr; + if (frame_ctl & IEEE80211_FCTL_MOREFRAGS) + return NULL; + + /* this was the last fragment - send it */ + skb = bptr->skb; + bptr->skb = NULL; /* free the entry */ + at76_dbg(DBG_RX_FRAGS, "%s: last frag of seq %d", + priv->netdev->name, seqnr); + return skb; + } + + /* got another sequence number */ + if (fragnr == 0) { + /* it's the start of a new chain - replace the + old one by this */ + /* bptr->sender has the correct value already */ + at76_dbg(DBG_RX_FRAGS, + "%s: start of new seq %d, removing old seq %d", + priv->netdev->name, seqnr, bptr->seqnr); + bptr->seqnr = seqnr; + bptr->fragnr = 0; + bptr->last_rx = jiffies; + /* swap bptr->skb and priv->rx_skb */ + skb = bptr->skb; + bptr->skb = priv->rx_skb; + priv->rx_skb = skb; + } else { + /* it from the middle of a new chain -> + delete the old entry and skip the new one */ + at76_dbg(DBG_RX_FRAGS, + "%s: middle of new seq %d (%d) " + "removing old seq %d", + priv->netdev->name, seqnr, fragnr, + bptr->seqnr); + dev_kfree_skb(bptr->skb); + bptr->skb = NULL; + } + return NULL; + } + + /* if we didn't find a chain for the sender address, optr + points either to the first free or the oldest entry */ + + if (fragnr != 0) { + /* this is not the begin of a fragment chain ... */ + at76_dbg(DBG_RX_FRAGS, + "%s: no chain for non-first fragment (%d)", + priv->netdev->name, fragnr); + return NULL; + } + + BUG_ON(!optr); + if (optr->skb) { + /* swap the skb's */ + skb = optr->skb; + optr->skb = priv->rx_skb; + priv->rx_skb = skb; + + at76_dbg(DBG_RX_FRAGS, + "%s: free old contents: sender %s seq/frag %d/%d", + priv->netdev->name, mac2str(optr->sender), + optr->seqnr, optr->fragnr); + + } else { + /* take the skb from priv->rx_skb */ + optr->skb = priv->rx_skb; + /* let at76_submit_rx_urb() allocate a new skb */ + priv->rx_skb = NULL; + + at76_dbg(DBG_RX_FRAGS, "%s: use a free entry", + priv->netdev->name); + } + memcpy(optr->sender, i802_11_hdr->addr2, ETH_ALEN); + optr->seqnr = seqnr; + optr->fragnr = 0; + optr->last_rx = jiffies; + + return NULL; +} + +/* Rx interrupt: we expect the complete data buffer in priv->rx_skb */ +static void at76_rx_data(struct at76_priv *priv) +{ + struct net_device *netdev = priv->netdev; + struct net_device_stats *stats = &priv->stats; + struct sk_buff *skb = priv->rx_skb; + struct at76_rx_buffer *buf = (struct at76_rx_buffer *)skb->data; + struct ieee80211_hdr_3addr *i802_11_hdr; + int length = le16_to_cpu(buf->wlength); + + at76_dbg(DBG_RX_DATA, "%s received data packet: %s", netdev->name, + hex2str(skb->data, AT76_RX_HDRLEN)); + + at76_dbg(DBG_RX_DATA_CONTENT, "rx packet: %s", + hex2str(skb->data + AT76_RX_HDRLEN, length)); + + skb = at76_check_for_rx_frags(priv); + if (!skb) + return; + + /* Atmel header and the FCS are already removed */ + i802_11_hdr = (struct ieee80211_hdr_3addr *)skb->data; + + skb->dev = netdev; + skb->ip_summed = CHECKSUM_NONE; /* TODO: should check CRC */ + + if (is_broadcast_ether_addr(i802_11_hdr->addr1)) { + if (!compare_ether_addr(i802_11_hdr->addr1, netdev->broadcast)) + skb->pkt_type = PACKET_BROADCAST; + else + skb->pkt_type = PACKET_MULTICAST; + } else if (compare_ether_addr(i802_11_hdr->addr1, netdev->dev_addr)) + skb->pkt_type = PACKET_OTHERHOST; + + at76_ieee80211_to_eth(skb, priv->iw_mode); + + netdev->last_rx = jiffies; + netif_rx(skb); + stats->rx_packets++; + stats->rx_bytes += length; + + return; +} + +static void at76_rx_monitor_mode(struct at76_priv *priv) +{ + struct at76_rx_radiotap *rt; + u8 *payload; + int skblen; + struct net_device *netdev = priv->netdev; + struct at76_rx_buffer *buf = + (struct at76_rx_buffer *)priv->rx_skb->data; + /* length including the IEEE802.11 header and the trailing FCS, + but not at76_rx_buffer */ + int length = le16_to_cpu(buf->wlength); + struct sk_buff *skb = priv->rx_skb; + struct net_device_stats *stats = &priv->stats; + + if (length < IEEE80211_FCS_LEN) { + /* buffer contains no data */ + at76_dbg(DBG_MONITOR_MODE, + "%s: MONITOR MODE: rx skb without data", + priv->netdev->name); + return; + } + + skblen = sizeof(struct at76_rx_radiotap) + length; + + skb = dev_alloc_skb(skblen); + if (!skb) { + printk(KERN_ERR "%s: MONITOR MODE: dev_alloc_skb for radiotap " + "header returned NULL\n", priv->netdev->name); + return; + } + + skb_put(skb, skblen); + + rt = (struct at76_rx_radiotap *)skb->data; + payload = skb->data + sizeof(struct at76_rx_radiotap); + + rt->rt_hdr.it_version = 0; + rt->rt_hdr.it_pad = 0; + rt->rt_hdr.it_len = cpu_to_le16(sizeof(struct at76_rx_radiotap)); + rt->rt_hdr.it_present = cpu_to_le32(AT76_RX_RADIOTAP_PRESENT); + + rt->rt_tsft = cpu_to_le64(le32_to_cpu(buf->rx_time)); + rt->rt_rate = hw_rates[buf->rx_rate] & (~0x80); + rt->rt_signal = buf->rssi; + rt->rt_noise = buf->noise_level; + rt->rt_flags = IEEE80211_RADIOTAP_F_FCS; + if (buf->fragmentation) + rt->rt_flags |= IEEE80211_RADIOTAP_F_FRAG; + + memcpy(payload, buf->packet, length); + skb->dev = netdev; + skb->ip_summed = CHECKSUM_NONE; + skb_reset_mac_header(skb); + skb->pkt_type = PACKET_OTHERHOST; + skb->protocol = htons(ETH_P_802_2); + + netdev->last_rx = jiffies; + netif_rx(skb); + stats->rx_packets++; + stats->rx_bytes += length; +} + +/* Check if we spy on the sender address in buf and update stats */ +static void at76_iwspy_update(struct at76_priv *priv, + struct at76_rx_buffer *buf) +{ + struct ieee80211_hdr_3addr *hdr = + (struct ieee80211_hdr_3addr *)buf->packet; + struct iw_quality qual; + + /* We can only set the level here */ + qual.updated = IW_QUAL_QUAL_INVALID | IW_QUAL_NOISE_INVALID; + qual.level = 0; + qual.noise = 0; + at76_calc_level(priv, buf, &qual); + + spin_lock_bh(&priv->spy_spinlock); + + if (priv->spy_data.spy_number > 0) + wireless_spy_update(priv->netdev, hdr->addr2, &qual); + + spin_unlock_bh(&priv->spy_spinlock); +} + +static void at76_rx_tasklet(unsigned long param) +{ + struct urb *urb = (struct urb *)param; + struct at76_priv *priv = urb->context; + struct net_device *netdev = priv->netdev; + struct at76_rx_buffer *buf; + struct ieee80211_hdr_3addr *i802_11_hdr; + u16 frame_ctl; + + if (priv->device_unplugged) { + at76_dbg(DBG_DEVSTART, "device unplugged"); + if (urb) + at76_dbg(DBG_DEVSTART, "urb status %d", urb->status); + return; + } + + if (!priv->rx_skb || !netdev || !priv->rx_skb->data) + return; + + buf = (struct at76_rx_buffer *)priv->rx_skb->data; + + i802_11_hdr = (struct ieee80211_hdr_3addr *)buf->packet; + + frame_ctl = le16_to_cpu(i802_11_hdr->frame_ctl); + + if (urb->status != 0) { + if (urb->status != -ENOENT && urb->status != -ECONNRESET) + at76_dbg(DBG_URB, + "%s %s: - nonzero Rx bulk status received: %d", + __func__, netdev->name, urb->status); + return; + } + + at76_dbg(DBG_RX_ATMEL_HDR, + "%s: rx frame: rate %d rssi %d noise %d link %d %s", + priv->netdev->name, buf->rx_rate, buf->rssi, buf->noise_level, + buf->link_quality, hex2str(i802_11_hdr, 48)); + if (priv->iw_mode == IW_MODE_MONITOR) { + at76_rx_monitor_mode(priv); + goto exit; + } + + /* there is a new bssid around, accept it: */ + if (buf->newbss && priv->iw_mode == IW_MODE_ADHOC) { + at76_dbg(DBG_PROGRESS, "%s: rx newbss", netdev->name); + schedule_work(&priv->work_new_bss); + } + + switch (frame_ctl & IEEE80211_FCTL_FTYPE) { + case IEEE80211_FTYPE_DATA: + at76_rx_data(priv); + break; + + case IEEE80211_FTYPE_MGMT: + /* jal: TODO: find out if we can update iwspy also on + other frames than management (might depend on the + radio chip / firmware version !) */ + + at76_iwspy_update(priv, buf); + + at76_rx_mgmt(priv, buf); + break; + + case IEEE80211_FTYPE_CTL: + at76_dbg(DBG_RX_CTRL, "%s: ignored ctrl frame: %04x", + priv->netdev->name, frame_ctl); + break; + + default: + printk(KERN_DEBUG "%s: ignoring frame with framectl 0x%04x\n", + priv->netdev->name, frame_ctl); + } +exit: + at76_submit_rx_urb(priv); +} + +/* Load firmware into kernel memory and parse it */ +static struct fwentry *at76_load_firmware(struct usb_device *udev, + enum board_type board_type) +{ + int ret; + char *str; + struct at76_fw_header *fwh; + struct fwentry *fwe = &firmwares[board_type]; + + mutex_lock(&fw_mutex); + + if (fwe->loaded) { + at76_dbg(DBG_FW, "re-using previously loaded fw"); + goto exit; + } + + at76_dbg(DBG_FW, "downloading firmware %s", fwe->fwname); + ret = request_firmware(&fwe->fw, fwe->fwname, &udev->dev); + if (ret < 0) { + dev_printk(KERN_ERR, &udev->dev, "firmware %s not found!\n", + fwe->fwname); + dev_printk(KERN_ERR, &udev->dev, + "you may need to download the firmware from " + "http://developer.berlios.de/projects/at76c503a/"); + goto exit; + } + + at76_dbg(DBG_FW, "got it."); + fwh = (struct at76_fw_header *)(fwe->fw->data); + + if (fwe->fw->size <= sizeof(*fwh)) { + dev_printk(KERN_ERR, &udev->dev, + "firmware is too short (0x%zx)\n", fwe->fw->size); + goto exit; + } + + /* CRC currently not checked */ + fwe->board_type = le32_to_cpu(fwh->board_type); + if (fwe->board_type != board_type) { + dev_printk(KERN_ERR, &udev->dev, + "board type mismatch, requested %u, got %u\n", + board_type, fwe->board_type); + goto exit; + } + + fwe->fw_version.major = fwh->major; + fwe->fw_version.minor = fwh->minor; + fwe->fw_version.patch = fwh->patch; + fwe->fw_version.build = fwh->build; + + str = (char *)fwh + le32_to_cpu(fwh->str_offset); + fwe->intfw = (u8 *)fwh + le32_to_cpu(fwh->int_fw_offset); + fwe->intfw_size = le32_to_cpu(fwh->int_fw_len); + fwe->extfw = (u8 *)fwh + le32_to_cpu(fwh->ext_fw_offset); + fwe->extfw_size = le32_to_cpu(fwh->ext_fw_len); + + fwe->loaded = 1; + + dev_printk(KERN_DEBUG, &udev->dev, + "using firmware %s (version %d.%d.%d-%d)\n", + fwe->fwname, fwh->major, fwh->minor, fwh->patch, fwh->build); + + at76_dbg(DBG_DEVSTART, "board %u, int %d:%d, ext %d:%d", board_type, + le32_to_cpu(fwh->int_fw_offset), le32_to_cpu(fwh->int_fw_len), + le32_to_cpu(fwh->ext_fw_offset), le32_to_cpu(fwh->ext_fw_len)); + at76_dbg(DBG_DEVSTART, "firmware id %s", str); + +exit: + mutex_unlock(&fw_mutex); + + if (fwe->loaded) + return fwe; + else + return NULL; +} + +/* Allocate network device and initialize private data */ +static struct at76_priv *at76_alloc_new_device(struct usb_device *udev) +{ + struct net_device *netdev; + struct at76_priv *priv; + int i; + + /* allocate memory for our device state and initialize it */ + netdev = alloc_etherdev(sizeof(struct at76_priv)); + if (!netdev) { + dev_printk(KERN_ERR, &udev->dev, "out of memory\n"); + return NULL; + } + + priv = netdev_priv(netdev); + + priv->udev = udev; + priv->netdev = netdev; + + mutex_init(&priv->mtx); + INIT_WORK(&priv->work_assoc_done, at76_work_assoc_done); + INIT_WORK(&priv->work_join, at76_work_join); + INIT_WORK(&priv->work_new_bss, at76_work_new_bss); + INIT_WORK(&priv->work_start_scan, at76_work_start_scan); + INIT_WORK(&priv->work_set_promisc, at76_work_set_promisc); + INIT_WORK(&priv->work_submit_rx, at76_work_submit_rx); + INIT_DELAYED_WORK(&priv->dwork_restart, at76_dwork_restart); + INIT_DELAYED_WORK(&priv->dwork_get_scan, at76_dwork_get_scan); + INIT_DELAYED_WORK(&priv->dwork_beacon, at76_dwork_beacon); + INIT_DELAYED_WORK(&priv->dwork_auth, at76_dwork_auth); + INIT_DELAYED_WORK(&priv->dwork_assoc, at76_dwork_assoc); + + spin_lock_init(&priv->mgmt_spinlock); + priv->next_mgmt_bulk = NULL; + priv->mac_state = MAC_INIT; + + /* initialize empty BSS list */ + priv->curr_bss = NULL; + INIT_LIST_HEAD(&priv->bss_list); + spin_lock_init(&priv->bss_list_spinlock); + + init_timer(&priv->bss_list_timer); + priv->bss_list_timer.data = (unsigned long)priv; + priv->bss_list_timer.function = at76_bss_list_timeout; + + spin_lock_init(&priv->spy_spinlock); + + /* mark all rx data entries as unused */ + for (i = 0; i < NR_RX_DATA_BUF; i++) + priv->rx_data[i].skb = NULL; + + priv->rx_tasklet.func = at76_rx_tasklet; + priv->rx_tasklet.data = 0; + + priv->pm_mode = AT76_PM_OFF; + priv->pm_period = 0; + + return priv; +} + +static int at76_alloc_urbs(struct at76_priv *priv, + struct usb_interface *interface) +{ + struct usb_endpoint_descriptor *endpoint, *ep_in, *ep_out; + int i; + int buffer_size; + struct usb_host_interface *iface_desc; + + at76_dbg(DBG_PROC_ENTRY, "%s: ENTER", __func__); + + at76_dbg(DBG_URB, "%s: NumEndpoints %d ", __func__, + interface->altsetting[0].desc.bNumEndpoints); + + ep_in = NULL; + ep_out = NULL; + iface_desc = interface->cur_altsetting; + for (i = 0; i < iface_desc->desc.bNumEndpoints; i++) { + endpoint = &iface_desc->endpoint[i].desc; + + at76_dbg(DBG_URB, "%s: %d. endpoint: addr 0x%x attr 0x%x", + __func__, i, endpoint->bEndpointAddress, + endpoint->bmAttributes); + + if (!ep_in && usb_endpoint_is_bulk_in(endpoint)) + ep_in = endpoint; + + if (!ep_out && usb_endpoint_is_bulk_out(endpoint)) + ep_out = endpoint; + } + + if (!ep_in || !ep_out) { + dev_printk(KERN_ERR, &interface->dev, + "bulk endpoints missing\n"); + return -ENXIO; + } + + priv->rx_pipe = usb_rcvbulkpipe(priv->udev, ep_in->bEndpointAddress); + priv->tx_pipe = usb_sndbulkpipe(priv->udev, ep_out->bEndpointAddress); + + priv->rx_urb = usb_alloc_urb(0, GFP_KERNEL); + priv->tx_urb = usb_alloc_urb(0, GFP_KERNEL); + if (!priv->rx_urb || !priv->tx_urb) { + dev_printk(KERN_ERR, &interface->dev, "cannot allocate URB\n"); + return -ENOMEM; + } + + buffer_size = sizeof(struct at76_tx_buffer) + MAX_PADDING_SIZE; + priv->bulk_out_buffer = kmalloc(buffer_size, GFP_KERNEL); + if (!priv->bulk_out_buffer) { + dev_printk(KERN_ERR, &interface->dev, + "cannot allocate output buffer\n"); + return -ENOMEM; + } + + at76_dbg(DBG_PROC_ENTRY, "%s: EXIT", __func__); + + return 0; +} + +/* Register network device and initialize the hardware */ +static int at76_init_new_device(struct at76_priv *priv, + struct usb_interface *interface) +{ + struct net_device *netdev = priv->netdev; + int ret; + + /* set up the endpoint information */ + /* check out the endpoints */ + + at76_dbg(DBG_DEVSTART, "USB interface: %d endpoints", + interface->cur_altsetting->desc.bNumEndpoints); + + ret = at76_alloc_urbs(priv, interface); + if (ret < 0) + goto exit; + + /* MAC address */ + ret = at76_get_hw_config(priv); + if (ret < 0) { + dev_printk(KERN_ERR, &interface->dev, + "cannot get MAC address\n"); + goto exit; + } + + priv->domain = at76_get_reg_domain(priv->regulatory_domain); + /* init. netdev->dev_addr */ + memcpy(netdev->dev_addr, priv->mac_addr, ETH_ALEN); + + priv->channel = DEF_CHANNEL; + priv->iw_mode = IW_MODE_INFRA; + priv->rts_threshold = DEF_RTS_THRESHOLD; + priv->frag_threshold = DEF_FRAG_THRESHOLD; + priv->short_retry_limit = DEF_SHORT_RETRY_LIMIT; + priv->txrate = TX_RATE_AUTO; + priv->preamble_type = PREAMBLE_TYPE_LONG; + priv->beacon_period = 100; + priv->beacons_last_qual = jiffies; + priv->auth_mode = WLAN_AUTH_OPEN; + priv->scan_min_time = DEF_SCAN_MIN_TIME; + priv->scan_max_time = DEF_SCAN_MAX_TIME; + priv->scan_mode = SCAN_TYPE_ACTIVE; + + netdev->flags &= ~IFF_MULTICAST; /* not yet or never */ + netdev->open = at76_open; + netdev->stop = at76_stop; + netdev->get_stats = at76_get_stats; + netdev->ethtool_ops = &at76_ethtool_ops; + + /* Add pointers to enable iwspy support. */ + priv->wireless_data.spy_data = &priv->spy_data; + netdev->wireless_data = &priv->wireless_data; + + netdev->hard_start_xmit = at76_tx; + netdev->tx_timeout = at76_tx_timeout; + netdev->watchdog_timeo = 2 * HZ; + netdev->wireless_handlers = &at76_handler_def; + netdev->set_multicast_list = at76_set_multicast; + netdev->set_mac_address = at76_set_mac_address; + dev_alloc_name(netdev, "wlan%d"); + + ret = register_netdev(priv->netdev); + if (ret) { + dev_printk(KERN_ERR, &interface->dev, + "cannot register netdevice (status %d)!\n", ret); + goto exit; + } + priv->netdev_registered = 1; + + printk(KERN_INFO "%s: USB %s, MAC %s, firmware %d.%d.%d-%d\n", + netdev->name, interface->dev.bus_id, mac2str(priv->mac_addr), + priv->fw_version.major, priv->fw_version.minor, + priv->fw_version.patch, priv->fw_version.build); + printk(KERN_INFO "%s: regulatory domain 0x%02x: %s\n", netdev->name, + priv->regulatory_domain, priv->domain->name); + + /* we let this timer run the whole time this driver instance lives */ + mod_timer(&priv->bss_list_timer, jiffies + BSS_LIST_TIMEOUT); + +exit: + return ret; +} + +static void at76_delete_device(struct at76_priv *priv) +{ + int i; + + at76_dbg(DBG_PROC_ENTRY, "%s: ENTER", __func__); + + /* The device is gone, don't bother turning it off */ + priv->device_unplugged = 1; + + if (priv->netdev_registered) + unregister_netdev(priv->netdev); + + /* assuming we used keventd, it must quiesce too */ + flush_scheduled_work(); + + kfree(priv->bulk_out_buffer); + + if (priv->tx_urb) { + usb_kill_urb(priv->tx_urb); + usb_free_urb(priv->tx_urb); + } + if (priv->rx_urb) { + usb_kill_urb(priv->rx_urb); + usb_free_urb(priv->rx_urb); + } + + at76_dbg(DBG_PROC_ENTRY, "%s: unlinked urbs", __func__); + + if (priv->rx_skb) + kfree_skb(priv->rx_skb); + + at76_free_bss_list(priv); + del_timer_sync(&priv->bss_list_timer); + cancel_delayed_work(&priv->dwork_get_scan); + cancel_delayed_work(&priv->dwork_beacon); + cancel_delayed_work(&priv->dwork_auth); + cancel_delayed_work(&priv->dwork_assoc); + + if (priv->mac_state == MAC_CONNECTED) + at76_iwevent_bss_disconnect(priv->netdev); + + for (i = 0; i < NR_RX_DATA_BUF; i++) + if (priv->rx_data[i].skb) { + dev_kfree_skb(priv->rx_data[i].skb); + priv->rx_data[i].skb = NULL; + } + usb_put_dev(priv->udev); + + at76_dbg(DBG_PROC_ENTRY, "%s: before freeing priv/netdev", __func__); + free_netdev(priv->netdev); /* priv is in netdev */ + + at76_dbg(DBG_PROC_ENTRY, "%s: EXIT", __func__); +} + +static int at76_probe(struct usb_interface *interface, + const struct usb_device_id *id) +{ + int ret; + struct at76_priv *priv; + struct fwentry *fwe; + struct usb_device *udev; + int op_mode; + int need_ext_fw = 0; + struct mib_fw_version fwv; + int board_type = (int)id->driver_info; + + udev = usb_get_dev(interface_to_usbdev(interface)); + + /* Load firmware into kernel memory */ + fwe = at76_load_firmware(udev, board_type); + if (!fwe) { + ret = -ENOENT; + goto error; + } + + op_mode = at76_get_op_mode(udev); + + at76_dbg(DBG_DEVSTART, "opmode %d", op_mode); + + /* we get OPMODE_NONE with 2.4.23, SMC2662W-AR ??? + we get 204 with 2.4.23, Fiberline FL-WL240u (505A+RFMD2958) ??? */ + + if (op_mode == OPMODE_HW_CONFIG_MODE) { + dev_printk(KERN_ERR, &interface->dev, + "cannot handle a device in HW_CONFIG_MODE\n"); + ret = -EBUSY; + goto error; + } + + if (op_mode != OPMODE_NORMAL_NIC_WITH_FLASH + && op_mode != OPMODE_NORMAL_NIC_WITHOUT_FLASH) { + /* download internal firmware part */ + dev_printk(KERN_DEBUG, &interface->dev, + "downloading internal firmware\n"); + ret = at76_load_internal_fw(udev, fwe); + if (ret < 0) { + dev_printk(KERN_ERR, &interface->dev, + "error %d downloading internal firmware\n", + ret); + goto error; + } + usb_put_dev(udev); + return ret; + } + + /* Internal firmware already inside the device. Get firmware + * version to test if external firmware is loaded. + * This works only for newer firmware, e.g. the Intersil 0.90.x + * says "control timeout on ep0in" and subsequent + * at76_get_op_mode() fail too :-( */ + + /* if version >= 0.100.x.y or device with built-in flash we can + * query the device for the fw version */ + if ((fwe->fw_version.major > 0 || fwe->fw_version.minor >= 100) + || (op_mode == OPMODE_NORMAL_NIC_WITH_FLASH)) { + ret = at76_get_mib(udev, MIB_FW_VERSION, &fwv, sizeof(fwv)); + if (ret < 0 || (fwv.major | fwv.minor) == 0) + need_ext_fw = 1; + } else + /* No way to check firmware version, reload to be sure */ + need_ext_fw = 1; + + if (need_ext_fw) { + dev_printk(KERN_DEBUG, &interface->dev, + "downloading external firmware\n"); + + ret = at76_load_external_fw(udev, fwe); + if (ret) + goto error; + + /* Re-check firmware version */ + ret = at76_get_mib(udev, MIB_FW_VERSION, &fwv, sizeof(fwv)); + if (ret < 0) { + dev_printk(KERN_ERR, &interface->dev, + "error %d getting firmware version\n", ret); + goto error; + } + } + + priv = at76_alloc_new_device(udev); + if (!priv) { + ret = -ENOMEM; + goto error; + } + + SET_NETDEV_DEV(priv->netdev, &interface->dev); + usb_set_intfdata(interface, priv); + + memcpy(&priv->fw_version, &fwv, sizeof(struct mib_fw_version)); + priv->board_type = board_type; + + ret = at76_init_new_device(priv, interface); + if (ret < 0) + at76_delete_device(priv); + + return ret; + +error: + usb_put_dev(udev); + return ret; +} + +static void at76_disconnect(struct usb_interface *interface) +{ + struct at76_priv *priv; + + priv = usb_get_intfdata(interface); + usb_set_intfdata(interface, NULL); + + /* Disconnect after loading internal firmware */ + if (!priv) + return; + + printk(KERN_INFO "%s: disconnecting\n", priv->netdev->name); + at76_delete_device(priv); + dev_printk(KERN_INFO, &interface->dev, "disconnected\n"); +} + +/* Structure for registering this driver with the USB subsystem */ +static struct usb_driver at76_driver = { + .name = DRIVER_NAME, + .probe = at76_probe, + .disconnect = at76_disconnect, + .id_table = dev_table, +}; + +static int __init at76_mod_init(void) +{ + int result; + + printk(KERN_INFO DRIVER_DESC " " DRIVER_VERSION " loading\n"); + + mutex_init(&fw_mutex); + + /* register this driver with the USB subsystem */ + result = usb_register(&at76_driver); + if (result < 0) + printk(KERN_ERR DRIVER_NAME + ": usb_register failed (status %d)\n", result); + + led_trigger_register_simple("at76_usb-tx", &ledtrig_tx); + return result; +} + +static void __exit at76_mod_exit(void) +{ + int i; + + printk(KERN_INFO DRIVER_DESC " " DRIVER_VERSION " unloading\n"); + usb_deregister(&at76_driver); + for (i = 0; i < ARRAY_SIZE(firmwares); i++) { + if (firmwares[i].fw) + release_firmware(firmwares[i].fw); + } + led_trigger_unregister_simple(ledtrig_tx); +} + +module_param_named(debug, at76_debug, int, 0600); +MODULE_PARM_DESC(debug, "Debugging level"); + +module_init(at76_mod_init); +module_exit(at76_mod_exit); + +MODULE_AUTHOR("Oliver Kurth <oku@masqmail.cx>"); +MODULE_AUTHOR("Joerg Albert <joerg.albert@gmx.de>"); +MODULE_AUTHOR("Alex <alex@foogod.com>"); +MODULE_AUTHOR("Nick Jones"); +MODULE_AUTHOR("Balint Seeber <n0_5p4m_p13453@hotmail.com>"); +MODULE_AUTHOR("Pavel Roskin <proski@gnu.org>"); +MODULE_DESCRIPTION(DRIVER_DESC); +MODULE_LICENSE("GPL"); diff --git a/drivers/staging/at76_usb/at76_usb.h b/drivers/staging/at76_usb/at76_usb.h new file mode 100644 index 000000000000..b20be9da1fa1 --- /dev/null +++ b/drivers/staging/at76_usb/at76_usb.h @@ -0,0 +1,619 @@ +/* + * Copyright (c) 2002,2003 Oliver Kurth + * (c) 2003,2004 Joerg Albert <joerg.albert@gmx.de> + * (c) 2007 Guido Guenther <agx@sigxcpu.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 driver was based on information from the Sourceforge driver + * released and maintained by Atmel: + * + * http://sourceforge.net/projects/atmelwlandriver/ + * + * Although the code was completely re-written, + * it would have been impossible without Atmel's decision to + * release an Open Source driver (unfortunately the firmware was + * kept binary only). Thanks for that decision to Atmel! + */ + +#ifndef _AT76_USB_H +#define _AT76_USB_H + +/* Board types */ +enum board_type { + BOARD_503_ISL3861 = 1, + BOARD_503_ISL3863 = 2, + BOARD_503 = 3, + BOARD_503_ACC = 4, + BOARD_505 = 5, + BOARD_505_2958 = 6, + BOARD_505A = 7, + BOARD_505AMX = 8 +}; + +/* our private ioctl's */ +/* preamble length (0 - long, 1 - short, 2 - auto) */ +#define AT76_SET_SHORT_PREAMBLE (SIOCIWFIRSTPRIV + 0) +#define AT76_GET_SHORT_PREAMBLE (SIOCIWFIRSTPRIV + 1) +/* which debug channels are enabled */ +#define AT76_SET_DEBUG (SIOCIWFIRSTPRIV + 2) +#define AT76_GET_DEBUG (SIOCIWFIRSTPRIV + 3) +/* power save mode (incl. the Atmel proprietary smart save mode) */ +#define AT76_SET_POWERSAVE_MODE (SIOCIWFIRSTPRIV + 4) +#define AT76_GET_POWERSAVE_MODE (SIOCIWFIRSTPRIV + 5) +/* min and max channel times for scan */ +#define AT76_SET_SCAN_TIMES (SIOCIWFIRSTPRIV + 6) +#define AT76_GET_SCAN_TIMES (SIOCIWFIRSTPRIV + 7) +/* scan mode (0 - active, 1 - passive) */ +#define AT76_SET_SCAN_MODE (SIOCIWFIRSTPRIV + 8) +#define AT76_GET_SCAN_MODE (SIOCIWFIRSTPRIV + 9) + +#define CMD_STATUS_IDLE 0x00 +#define CMD_STATUS_COMPLETE 0x01 +#define CMD_STATUS_UNKNOWN 0x02 +#define CMD_STATUS_INVALID_PARAMETER 0x03 +#define CMD_STATUS_FUNCTION_NOT_SUPPORTED 0x04 +#define CMD_STATUS_TIME_OUT 0x07 +#define CMD_STATUS_IN_PROGRESS 0x08 +#define CMD_STATUS_HOST_FAILURE 0xff +#define CMD_STATUS_SCAN_FAILED 0xf0 + +/* answers to get op mode */ +#define OPMODE_NONE 0x00 +#define OPMODE_NORMAL_NIC_WITH_FLASH 0x01 +#define OPMODE_HW_CONFIG_MODE 0x02 +#define OPMODE_DFU_MODE_WITH_FLASH 0x03 +#define OPMODE_NORMAL_NIC_WITHOUT_FLASH 0x04 + +#define CMD_SET_MIB 0x01 +#define CMD_GET_MIB 0x02 +#define CMD_SCAN 0x03 +#define CMD_JOIN 0x04 +#define CMD_START_IBSS 0x05 +#define CMD_RADIO_ON 0x06 +#define CMD_RADIO_OFF 0x07 +#define CMD_STARTUP 0x0B + +#define MIB_LOCAL 0x01 +#define MIB_MAC_ADDR 0x02 +#define MIB_MAC 0x03 +#define MIB_MAC_MGMT 0x05 +#define MIB_MAC_WEP 0x06 +#define MIB_PHY 0x07 +#define MIB_FW_VERSION 0x08 +#define MIB_MDOMAIN 0x09 + +#define ADHOC_MODE 1 +#define INFRASTRUCTURE_MODE 2 + +/* values for struct mib_local, field preamble_type */ +#define PREAMBLE_TYPE_LONG 0 +#define PREAMBLE_TYPE_SHORT 1 +#define PREAMBLE_TYPE_AUTO 2 + +/* values for tx_rate */ +#define TX_RATE_1MBIT 0 +#define TX_RATE_2MBIT 1 +#define TX_RATE_5_5MBIT 2 +#define TX_RATE_11MBIT 3 +#define TX_RATE_AUTO 4 + +/* power management modes */ +#define AT76_PM_OFF 1 +#define AT76_PM_ON 2 +#define AT76_PM_SMART 3 + +struct hwcfg_r505 { + u8 cr39_values[14]; + u8 reserved1[14]; + u8 bb_cr[14]; + u8 pidvid[4]; + u8 mac_addr[ETH_ALEN]; + u8 regulatory_domain; + u8 reserved2[14]; + u8 cr15_values[14]; + u8 reserved3[3]; +} __attribute__((packed)); + +struct hwcfg_rfmd { + u8 cr20_values[14]; + u8 cr21_values[14]; + u8 bb_cr[14]; + u8 pidvid[4]; + u8 mac_addr[ETH_ALEN]; + u8 regulatory_domain; + u8 low_power_values[14]; + u8 normal_power_values[14]; + u8 reserved1[3]; +} __attribute__((packed)); + +struct hwcfg_intersil { + u8 mac_addr[ETH_ALEN]; + u8 cr31_values[14]; + u8 cr58_values[14]; + u8 pidvid[4]; + u8 regulatory_domain; + u8 reserved[1]; +} __attribute__((packed)); + +union at76_hwcfg { + struct hwcfg_intersil i; + struct hwcfg_rfmd r3; + struct hwcfg_r505 r5; +}; + +#define WEP_SMALL_KEY_LEN (40 / 8) +#define WEP_LARGE_KEY_LEN (104 / 8) + +struct at76_card_config { + u8 exclude_unencrypted; + u8 promiscuous_mode; + u8 short_retry_limit; + u8 encryption_type; + __le16 rts_threshold; + __le16 fragmentation_threshold; /* 256..2346 */ + u8 basic_rate_set[4]; + u8 auto_rate_fallback; /* 0,1 */ + u8 channel; + u8 privacy_invoked; + u8 wep_default_key_id; /* 0..3 */ + u8 current_ssid[32]; + u8 wep_default_key_value[4][WEP_KEY_LEN]; + u8 ssid_len; + u8 short_preamble; + __le16 beacon_period; +} __attribute__((packed)); + +struct at76_command { + u8 cmd; + u8 reserved; + __le16 size; + u8 data[0]; +} __attribute__((packed)); + +/* Length of Atmel-specific Rx header before 802.11 frame */ +#define AT76_RX_HDRLEN offsetof(struct at76_rx_buffer, packet) + +struct at76_rx_buffer { + __le16 wlength; + u8 rx_rate; + u8 newbss; + u8 fragmentation; + u8 rssi; + u8 link_quality; + u8 noise_level; + __le32 rx_time; + u8 packet[IEEE80211_FRAME_LEN + IEEE80211_FCS_LEN]; +} __attribute__((packed)); + +/* Length of Atmel-specific Tx header before 802.11 frame */ +#define AT76_TX_HDRLEN offsetof(struct at76_tx_buffer, packet) + +struct at76_tx_buffer { + __le16 wlength; + u8 tx_rate; + u8 padding; + u8 reserved[4]; + u8 packet[IEEE80211_FRAME_LEN + IEEE80211_FCS_LEN]; +} __attribute__((packed)); + +/* defines for scan_type below */ +#define SCAN_TYPE_ACTIVE 0 +#define SCAN_TYPE_PASSIVE 1 + +struct at76_req_scan { + u8 bssid[ETH_ALEN]; + u8 essid[32]; + u8 scan_type; + u8 channel; + __le16 probe_delay; + __le16 min_channel_time; + __le16 max_channel_time; + u8 essid_size; + u8 international_scan; +} __attribute__((packed)); + +struct at76_req_ibss { + u8 bssid[ETH_ALEN]; + u8 essid[32]; + u8 bss_type; + u8 channel; + u8 essid_size; + u8 reserved[3]; +} __attribute__((packed)); + +struct at76_req_join { + u8 bssid[ETH_ALEN]; + u8 essid[32]; + u8 bss_type; + u8 channel; + __le16 timeout; + u8 essid_size; + u8 reserved; +} __attribute__((packed)); + +struct set_mib_buffer { + u8 type; + u8 size; + u8 index; + u8 reserved; + union { + u8 byte; + __le16 word; + u8 addr[ETH_ALEN]; + } data; +} __attribute__((packed)); + +struct mib_local { + u16 reserved0; + u8 beacon_enable; + u8 txautorate_fallback; + u8 reserved1; + u8 ssid_size; + u8 promiscuous_mode; + u16 reserved2; + u8 preamble_type; + u16 reserved3; +} __attribute__((packed)); + +struct mib_mac_addr { + u8 mac_addr[ETH_ALEN]; + u8 res[2]; /* ??? */ + u8 group_addr[4][ETH_ALEN]; + u8 group_addr_status[4]; +} __attribute__((packed)); + +struct mib_mac { + __le32 max_tx_msdu_lifetime; + __le32 max_rx_lifetime; + __le16 frag_threshold; + __le16 rts_threshold; + __le16 cwmin; + __le16 cwmax; + u8 short_retry_time; + u8 long_retry_time; + u8 scan_type; /* active or passive */ + u8 scan_channel; + __le16 probe_delay; /* delay before ProbeReq in active scan, RO */ + __le16 min_channel_time; + __le16 max_channel_time; + __le16 listen_interval; + u8 desired_ssid[32]; + u8 desired_bssid[ETH_ALEN]; + u8 desired_bsstype; /* ad-hoc or infrastructure */ + u8 reserved2; +} __attribute__((packed)); + +struct mib_mac_mgmt { + __le16 beacon_period; + __le16 CFP_max_duration; + __le16 medium_occupancy_limit; + __le16 station_id; /* assoc id */ + __le16 ATIM_window; + u8 CFP_mode; + u8 privacy_option_implemented; + u8 DTIM_period; + u8 CFP_period; + u8 current_bssid[ETH_ALEN]; + u8 current_essid[32]; + u8 current_bss_type; + u8 power_mgmt_mode; + /* rfmd and 505 */ + u8 ibss_change; + u8 res; + u8 multi_domain_capability_implemented; + u8 multi_domain_capability_enabled; + u8 country_string[3]; + u8 reserved[3]; +} __attribute__((packed)); + +struct mib_mac_wep { + u8 privacy_invoked; /* 0 disable encr., 1 enable encr */ + u8 wep_default_key_id; + u8 wep_key_mapping_len; + u8 exclude_unencrypted; + __le32 wep_icv_error_count; + __le32 wep_excluded_count; + u8 wep_default_keyvalue[WEP_KEYS][WEP_KEY_LEN]; + u8 encryption_level; /* 1 for 40bit, 2 for 104bit encryption */ +} __attribute__((packed)); + +struct mib_phy { + __le32 ed_threshold; + + __le16 slot_time; + __le16 sifs_time; + __le16 preamble_length; + __le16 plcp_header_length; + __le16 mpdu_max_length; + __le16 cca_mode_supported; + + u8 operation_rate_set[4]; + u8 channel_id; + u8 current_cca_mode; + u8 phy_type; + u8 current_reg_domain; +} __attribute__((packed)); + +struct mib_fw_version { + u8 major; + u8 minor; + u8 patch; + u8 build; +} __attribute__((packed)); + +struct mib_mdomain { + u8 tx_powerlevel[14]; + u8 channel_list[14]; /* 0 for invalid channels */ +} __attribute__((packed)); + +struct at76_fw_header { + __le32 crc; /* CRC32 of the whole image */ + __le32 board_type; /* firmware compatibility code */ + u8 build; /* firmware build number */ + u8 patch; /* firmware patch level */ + u8 minor; /* firmware minor version */ + u8 major; /* firmware major version */ + __le32 str_offset; /* offset of the copyright string */ + __le32 int_fw_offset; /* internal firmware image offset */ + __le32 int_fw_len; /* internal firmware image length */ + __le32 ext_fw_offset; /* external firmware image offset */ + __le32 ext_fw_len; /* external firmware image length */ +} __attribute__((packed)); + +enum mac_state { + MAC_INIT, + MAC_SCANNING, + MAC_AUTH, + MAC_ASSOC, + MAC_JOINING, + MAC_CONNECTED, + MAC_OWN_IBSS +}; + +/* a description of a regulatory domain and the allowed channels */ +struct reg_domain { + u16 code; + char const *name; + u32 channel_map; /* if bit N is set, channel (N+1) is allowed */ +}; + +/* how long do we keep a (I)BSS in the bss_list in jiffies + this should be long enough for the user to retrieve the table + (by iwlist ?) after the device started, because all entries from + other channels than the one the device locks on get removed, too */ +#define BSS_LIST_TIMEOUT (120 * HZ) +/* struct to store BSS info found during scan */ +#define BSS_LIST_MAX_RATE_LEN 32 /* 32 rates should be enough ... */ + +struct bss_info { + struct list_head list; + + u8 bssid[ETH_ALEN]; /* bssid */ + u8 ssid[IW_ESSID_MAX_SIZE]; /* essid */ + u8 ssid_len; /* length of ssid above */ + u8 channel; + u16 capa; /* BSS capabilities */ + u16 beacon_interval; /* beacon interval, Kus (1024 microseconds) */ + u8 rates[BSS_LIST_MAX_RATE_LEN]; /* supported rates in units of + 500 kbps, ORed with 0x80 for + basic rates */ + u8 rates_len; + + /* quality of received beacon */ + u8 rssi; + u8 link_qual; + u8 noise_level; + + unsigned long last_rx; /* time (jiffies) of last beacon received */ +}; + +/* a rx data buffer to collect rx fragments */ +struct rx_data_buf { + u8 sender[ETH_ALEN]; /* sender address */ + u16 seqnr; /* sequence number */ + u16 fragnr; /* last fragment received */ + unsigned long last_rx; /* jiffies of last rx */ + struct sk_buff *skb; /* == NULL if entry is free */ +}; + +#define NR_RX_DATA_BUF 8 + +/* Data for one loaded firmware file */ +struct fwentry { + const char *const fwname; + const struct firmware *fw; + int extfw_size; + int intfw_size; + /* pointer to loaded firmware, no need to free */ + u8 *extfw; /* external firmware, extfw_size bytes long */ + u8 *intfw; /* internal firmware, intfw_size bytes long */ + enum board_type board_type; /* board type */ + struct mib_fw_version fw_version; + int loaded; /* Loaded and parsed successfully */ +}; + +struct at76_priv { + struct usb_device *udev; /* USB device pointer */ + struct net_device *netdev; /* net device pointer */ + struct net_device_stats stats; /* net device stats */ + struct iw_statistics wstats; /* wireless stats */ + + struct sk_buff *rx_skb; /* skbuff for receiving data */ + void *bulk_out_buffer; /* buffer for sending data */ + + struct urb *tx_urb; /* URB for sending data */ + struct urb *rx_urb; /* URB for receiving data */ + + unsigned int tx_pipe; /* bulk out pipe */ + unsigned int rx_pipe; /* bulk in pipe */ + + struct mutex mtx; /* locks this structure */ + + /* work queues */ + struct work_struct work_assoc_done; + struct work_struct work_join; + struct work_struct work_new_bss; + struct work_struct work_start_scan; + struct work_struct work_set_promisc; + struct work_struct work_submit_rx; + struct delayed_work dwork_restart; + struct delayed_work dwork_get_scan; + struct delayed_work dwork_beacon; + struct delayed_work dwork_auth; + struct delayed_work dwork_assoc; + + struct tasklet_struct rx_tasklet; + + /* the WEP stuff */ + int wep_enabled; /* 1 if WEP is enabled */ + int wep_key_id; /* key id to be used */ + u8 wep_keys[WEP_KEYS][WEP_KEY_LEN]; /* the four WEP keys, + 5 or 13 bytes are used */ + u8 wep_keys_len[WEP_KEYS]; /* the length of the above keys */ + + int channel; + int iw_mode; + u8 bssid[ETH_ALEN]; + u8 essid[IW_ESSID_MAX_SIZE]; + int essid_size; + int radio_on; + int promisc; + + int preamble_type; /* 0 - long, 1 - short, 2 - auto */ + int auth_mode; /* authentication type: 0 open, 1 shared key */ + int txrate; /* 0,1,2,3 = 1,2,5.5,11 Mbps, 4 is auto */ + int frag_threshold; /* threshold for fragmentation of tx packets */ + int rts_threshold; /* threshold for RTS mechanism */ + int short_retry_limit; + + int scan_min_time; /* scan min channel time */ + int scan_max_time; /* scan max channel time */ + int scan_mode; /* SCAN_TYPE_ACTIVE, SCAN_TYPE_PASSIVE */ + int scan_need_any; /* if set, need to scan for any ESSID */ + + /* the list we got from scanning */ + spinlock_t bss_list_spinlock; /* protects bss_list operations */ + struct list_head bss_list; /* list of BSS we got beacons from */ + struct timer_list bss_list_timer; /* timer to purge old entries + from bss_list */ + struct bss_info *curr_bss; /* current BSS */ + u16 assoc_id; /* current association ID, if associated */ + + u8 wanted_bssid[ETH_ALEN]; + int wanted_bssid_valid; /* != 0 if wanted_bssid is to be used */ + + /* some data for infrastructure mode only */ + spinlock_t mgmt_spinlock; /* this spinlock protects access to + next_mgmt_bulk */ + + struct at76_tx_buffer *next_mgmt_bulk; /* pending management msg to + send via bulk out */ + enum mac_state mac_state; + enum { + SCAN_IDLE, + SCAN_IN_PROGRESS, + SCAN_COMPLETED + } scan_state; + time_t last_scan; + + int retries; /* remaining retries in case of timeout when + * sending AuthReq or AssocReq */ + u8 pm_mode; /* power management mode */ + u32 pm_period; /* power management period in microseconds */ + + struct reg_domain const *domain; /* reg domain description */ + + /* iwspy support */ + spinlock_t spy_spinlock; + struct iw_spy_data spy_data; + + struct iw_public_data wireless_data; + + /* These fields contain HW config provided by the device (not all of + * these fields are used by all board types) */ + u8 mac_addr[ETH_ALEN]; + u8 regulatory_domain; + + struct at76_card_config card_config; + + /* store rx fragments until complete */ + struct rx_data_buf rx_data[NR_RX_DATA_BUF]; + + enum board_type board_type; + struct mib_fw_version fw_version; + + unsigned int device_unplugged:1; + unsigned int netdev_registered:1; + struct set_mib_buffer mib_buf; /* global buffer for set_mib calls */ + + /* beacon counting */ + int beacon_period; /* period of mgmt beacons, Kus */ + int beacons_received; + unsigned long beacons_last_qual; /* time we restarted counting + beacons */ +}; + +struct at76_rx_radiotap { + struct ieee80211_radiotap_header rt_hdr; + __le64 rt_tsft; + u8 rt_flags; + u8 rt_rate; + s8 rt_signal; + s8 rt_noise; +}; + +#define AT76_RX_RADIOTAP_PRESENT \ + ((1 << IEEE80211_RADIOTAP_TSFT) | \ + (1 << IEEE80211_RADIOTAP_FLAGS) | \ + (1 << IEEE80211_RADIOTAP_RATE) | \ + (1 << IEEE80211_RADIOTAP_DB_ANTSIGNAL) | \ + (1 << IEEE80211_RADIOTAP_DB_ANTNOISE)) + +#define BEACON_MAX_DATA_LENGTH 1500 + +/* the maximum size of an AssocReq packet */ +#define ASSOCREQ_MAX_SIZE \ + (AT76_TX_HDRLEN + sizeof(struct ieee80211_assoc_request) + \ + 1 + 1 + IW_ESSID_MAX_SIZE + 1 + 1 + 4) + +/* for shared secret auth, add the challenge text size */ +#define AUTH_FRAME_SIZE (AT76_TX_HDRLEN + sizeof(struct ieee80211_auth)) + +/* Maximal number of AuthReq retries */ +#define AUTH_RETRIES 3 + +/* Maximal number of AssocReq retries */ +#define ASSOC_RETRIES 3 + +/* Beacon timeout in managed mode when we are connected */ +#define BEACON_TIMEOUT (10 * HZ) + +/* Timeout for authentication response */ +#define AUTH_TIMEOUT (1 * HZ) + +/* Timeout for association response */ +#define ASSOC_TIMEOUT (1 * HZ) + +/* Polling interval when scan is running */ +#define SCAN_POLL_INTERVAL (HZ / 4) + +/* Command completion timeout */ +#define CMD_COMPLETION_TIMEOUT (5 * HZ) + +#define DEF_RTS_THRESHOLD 1536 +#define DEF_FRAG_THRESHOLD 1536 +#define DEF_SHORT_RETRY_LIMIT 8 +#define DEF_CHANNEL 10 +#define DEF_SCAN_MIN_TIME 10 +#define DEF_SCAN_MAX_TIME 120 + +#define MAX_RTS_THRESHOLD (MAX_FRAG_THRESHOLD + 1) + +/* the max padding size for tx in bytes (see calc_padding) */ +#define MAX_PADDING_SIZE 53 + +#endif /* _AT76_USB_H */ diff --git a/drivers/staging/echo/Kconfig b/drivers/staging/echo/Kconfig new file mode 100644 index 000000000000..f1d41ea9cd48 --- /dev/null +++ b/drivers/staging/echo/Kconfig @@ -0,0 +1,9 @@ +config ECHO + tristate "Line Echo Canceller support" + default n + ---help--- + This driver provides line echo cancelling support for mISDN and + Zaptel drivers. + + To compile this driver as a module, choose M here. The module + will be called echo. diff --git a/drivers/staging/echo/Makefile b/drivers/staging/echo/Makefile new file mode 100644 index 000000000000..7d4caac12a8d --- /dev/null +++ b/drivers/staging/echo/Makefile @@ -0,0 +1 @@ +obj-$(CONFIG_ECHO) += echo.o diff --git a/drivers/staging/echo/TODO b/drivers/staging/echo/TODO new file mode 100644 index 000000000000..1ca09afd603e --- /dev/null +++ b/drivers/staging/echo/TODO @@ -0,0 +1,10 @@ +TODO: + - checkpatch.pl cleanups + - Lindent + - typedef removals + - handle bit_operations.h (merge in or make part of common code?) + - remove proc interface, only use echo.h interface (proc interface is + racy and not correct.) + +Please send patches to Greg Kroah-Hartman <greg@kroah.com> and Cc: Steve +Underwood <steveu@coppice.org> and David Rowe <david@rowetel.com> diff --git a/drivers/staging/echo/bit_operations.h b/drivers/staging/echo/bit_operations.h new file mode 100644 index 000000000000..b32f4bf99397 --- /dev/null +++ b/drivers/staging/echo/bit_operations.h @@ -0,0 +1,253 @@ +/* + * SpanDSP - a series of DSP components for telephony + * + * bit_operations.h - Various bit level operations, such as bit reversal + * + * Written by Steve Underwood <steveu@coppice.org> + * + * Copyright (C) 2006 Steve Underwood + * + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, as + * published by the Free Software Foundation. + * + * 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. + * + * $Id: bit_operations.h,v 1.11 2006/11/28 15:37:03 steveu Exp $ + */ + +/*! \file */ + +#if !defined(_BIT_OPERATIONS_H_) +#define _BIT_OPERATIONS_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(__i386__) || defined(__x86_64__) +/*! \brief Find the bit position of the highest set bit in a word + \param bits The word to be searched + \return The bit number of the highest set bit, or -1 if the word is zero. */ +static __inline__ int top_bit(unsigned int bits) +{ + int res; + + __asm__ (" xorl %[res],%[res];\n" + " decl %[res];\n" + " bsrl %[bits],%[res]\n" + : [res] "=&r" (res) + : [bits] "rm" (bits)); + return res; +} +/*- End of function --------------------------------------------------------*/ + +/*! \brief Find the bit position of the lowest set bit in a word + \param bits The word to be searched + \return The bit number of the lowest set bit, or -1 if the word is zero. */ +static __inline__ int bottom_bit(unsigned int bits) +{ + int res; + + __asm__ (" xorl %[res],%[res];\n" + " decl %[res];\n" + " bsfl %[bits],%[res]\n" + : [res] "=&r" (res) + : [bits] "rm" (bits)); + return res; +} +/*- End of function --------------------------------------------------------*/ +#else +static __inline__ int top_bit(unsigned int bits) +{ + int i; + + if (bits == 0) + return -1; + i = 0; + if (bits & 0xFFFF0000) + { + bits &= 0xFFFF0000; + i += 16; + } + if (bits & 0xFF00FF00) + { + bits &= 0xFF00FF00; + i += 8; + } + if (bits & 0xF0F0F0F0) + { + bits &= 0xF0F0F0F0; + i += 4; + } + if (bits & 0xCCCCCCCC) + { + bits &= 0xCCCCCCCC; + i += 2; + } + if (bits & 0xAAAAAAAA) + { + bits &= 0xAAAAAAAA; + i += 1; + } + return i; +} +/*- End of function --------------------------------------------------------*/ + +static __inline__ int bottom_bit(unsigned int bits) +{ + int i; + + if (bits == 0) + return -1; + i = 32; + if (bits & 0x0000FFFF) + { + bits &= 0x0000FFFF; + i -= 16; + } + if (bits & 0x00FF00FF) + { + bits &= 0x00FF00FF; + i -= 8; + } + if (bits & 0x0F0F0F0F) + { + bits &= 0x0F0F0F0F; + i -= 4; + } + if (bits & 0x33333333) + { + bits &= 0x33333333; + i -= 2; + } + if (bits & 0x55555555) + { + bits &= 0x55555555; + i -= 1; + } + return i; +} +/*- End of function --------------------------------------------------------*/ +#endif + +/*! \brief Bit reverse a byte. + \param data The byte to be reversed. + \return The bit reversed version of data. */ +static __inline__ uint8_t bit_reverse8(uint8_t x) +{ +#if defined(__i386__) || defined(__x86_64__) + /* If multiply is fast */ + return ((x*0x0802U & 0x22110U) | (x*0x8020U & 0x88440U))*0x10101U >> 16; +#else + /* If multiply is slow, but we have a barrel shifter */ + x = (x >> 4) | (x << 4); + x = ((x & 0xCC) >> 2) | ((x & 0x33) << 2); + return ((x & 0xAA) >> 1) | ((x & 0x55) << 1); +#endif +} +/*- End of function --------------------------------------------------------*/ + +/*! \brief Bit reverse a 16 bit word. + \param data The word to be reversed. + \return The bit reversed version of data. */ +uint16_t bit_reverse16(uint16_t data); + +/*! \brief Bit reverse a 32 bit word. + \param data The word to be reversed. + \return The bit reversed version of data. */ +uint32_t bit_reverse32(uint32_t data); + +/*! \brief Bit reverse each of the four bytes in a 32 bit word. + \param data The word to be reversed. + \return The bit reversed version of data. */ +uint32_t bit_reverse_4bytes(uint32_t data); + +/*! \brief Find the number of set bits in a 32 bit word. + \param x The word to be searched. + \return The number of set bits. */ +int one_bits32(uint32_t x); + +/*! \brief Create a mask as wide as the number in a 32 bit word. + \param x The word to be searched. + \return The mask. */ +uint32_t make_mask32(uint32_t x); + +/*! \brief Create a mask as wide as the number in a 16 bit word. + \param x The word to be searched. + \return The mask. */ +uint16_t make_mask16(uint16_t x); + +/*! \brief Find the least significant one in a word, and return a word + with just that bit set. + \param x The word to be searched. + \return The word with the single set bit. */ +static __inline__ uint32_t least_significant_one32(uint32_t x) +{ + return (x & (-(int32_t) x)); +} +/*- End of function --------------------------------------------------------*/ + +/*! \brief Find the most significant one in a word, and return a word + with just that bit set. + \param x The word to be searched. + \return The word with the single set bit. */ +static __inline__ uint32_t most_significant_one32(uint32_t x) +{ +#if defined(__i386__) || defined(__x86_64__) + return 1 << top_bit(x); +#else + x = make_mask32(x); + return (x ^ (x >> 1)); +#endif +} +/*- End of function --------------------------------------------------------*/ + +/*! \brief Find the parity of a byte. + \param x The byte to be checked. + \return 1 for odd, or 0 for even. */ +static __inline__ int parity8(uint8_t x) +{ + x = (x ^ (x >> 4)) & 0x0F; + return (0x6996 >> x) & 1; +} +/*- End of function --------------------------------------------------------*/ + +/*! \brief Find the parity of a 16 bit word. + \param x The word to be checked. + \return 1 for odd, or 0 for even. */ +static __inline__ int parity16(uint16_t x) +{ + x ^= (x >> 8); + x = (x ^ (x >> 4)) & 0x0F; + return (0x6996 >> x) & 1; +} +/*- End of function --------------------------------------------------------*/ + +/*! \brief Find the parity of a 32 bit word. + \param x The word to be checked. + \return 1 for odd, or 0 for even. */ +static __inline__ int parity32(uint32_t x) +{ + x ^= (x >> 16); + x ^= (x >> 8); + x = (x ^ (x >> 4)) & 0x0F; + return (0x6996 >> x) & 1; +} +/*- End of function --------------------------------------------------------*/ + +#ifdef __cplusplus +} +#endif + +#endif +/*- End of file ------------------------------------------------------------*/ diff --git a/drivers/staging/echo/echo.c b/drivers/staging/echo/echo.c new file mode 100644 index 000000000000..4a281b14fc58 --- /dev/null +++ b/drivers/staging/echo/echo.c @@ -0,0 +1,632 @@ +/* + * SpanDSP - a series of DSP components for telephony + * + * echo.c - A line echo canceller. This code is being developed + * against and partially complies with G168. + * + * Written by Steve Underwood <steveu@coppice.org> + * and David Rowe <david_at_rowetel_dot_com> + * + * Copyright (C) 2001, 2003 Steve Underwood, 2007 David Rowe + * + * Based on a bit from here, a bit from there, eye of toad, ear of + * bat, 15 years of failed attempts by David and a few fried brain + * cells. + * + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, as + * published by the Free Software Foundation. + * + * 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. + * + * $Id: echo.c,v 1.20 2006/12/01 18:00:48 steveu Exp $ + */ + +/*! \file */ + +/* Implementation Notes + David Rowe + April 2007 + + This code started life as Steve's NLMS algorithm with a tap + rotation algorithm to handle divergence during double talk. I + added a Geigel Double Talk Detector (DTD) [2] and performed some + G168 tests. However I had trouble meeting the G168 requirements, + especially for double talk - there were always cases where my DTD + failed, for example where near end speech was under the 6dB + threshold required for declaring double talk. + + So I tried a two path algorithm [1], which has so far given better + results. The original tap rotation/Geigel algorithm is available + in SVN http://svn.rowetel.com/software/oslec/tags/before_16bit. + It's probably possible to make it work if some one wants to put some + serious work into it. + + At present no special treatment is provided for tones, which + generally cause NLMS algorithms to diverge. Initial runs of a + subset of the G168 tests for tones (e.g ./echo_test 6) show the + current algorithm is passing OK, which is kind of surprising. The + full set of tests needs to be performed to confirm this result. + + One other interesting change is that I have managed to get the NLMS + code to work with 16 bit coefficients, rather than the original 32 + bit coefficents. This reduces the MIPs and storage required. + I evaulated the 16 bit port using g168_tests.sh and listening tests + on 4 real-world samples. + + I also attempted the implementation of a block based NLMS update + [2] but although this passes g168_tests.sh it didn't converge well + on the real-world samples. I have no idea why, perhaps a scaling + problem. The block based code is also available in SVN + http://svn.rowetel.com/software/oslec/tags/before_16bit. If this + code can be debugged, it will lead to further reduction in MIPS, as + the block update code maps nicely onto DSP instruction sets (it's a + dot product) compared to the current sample-by-sample update. + + Steve also has some nice notes on echo cancellers in echo.h + + + References: + + [1] Ochiai, Areseki, and Ogihara, "Echo Canceller with Two Echo + Path Models", IEEE Transactions on communications, COM-25, + No. 6, June + 1977. + http://www.rowetel.com/images/echo/dual_path_paper.pdf + + [2] The classic, very useful paper that tells you how to + actually build a real world echo canceller: + Messerschmitt, Hedberg, Cole, Haoui, Winship, "Digital Voice + Echo Canceller with a TMS320020, + http://www.rowetel.com/images/echo/spra129.pdf + + [3] I have written a series of blog posts on this work, here is + Part 1: http://www.rowetel.com/blog/?p=18 + + [4] The source code http://svn.rowetel.com/software/oslec/ + + [5] A nice reference on LMS filters: + http://en.wikipedia.org/wiki/Least_mean_squares_filter + + Credits: + + Thanks to Steve Underwood, Jean-Marc Valin, and Ramakrishnan + Muthukrishnan for their suggestions and email discussions. Thanks + also to those people who collected echo samples for me such as + Mark, Pawel, and Pavel. +*/ + +#include <linux/kernel.h> /* We're doing kernel work */ +#include <linux/module.h> +#include <linux/kernel.h> +#include <linux/slab.h> +#define malloc(a) kmalloc((a), GFP_KERNEL) +#define free(a) kfree(a) + +#include "bit_operations.h" +#include "echo.h" + +#define MIN_TX_POWER_FOR_ADAPTION 64 +#define MIN_RX_POWER_FOR_ADAPTION 64 +#define DTD_HANGOVER 600 /* 600 samples, or 75ms */ +#define DC_LOG2BETA 3 /* log2() of DC filter Beta */ + +/*-----------------------------------------------------------------------*\ + FUNCTIONS +\*-----------------------------------------------------------------------*/ + +/* adapting coeffs using the traditional stochastic descent (N)LMS algorithm */ + + +#ifdef __BLACKFIN_ASM__ +static void __inline__ lms_adapt_bg(echo_can_state_t *ec, int clean, int shift) +{ + int i, j; + int offset1; + int offset2; + int factor; + int exp; + int16_t *phist; + int n; + + if (shift > 0) + factor = clean << shift; + else + factor = clean >> -shift; + + /* Update the FIR taps */ + + offset2 = ec->curr_pos; + offset1 = ec->taps - offset2; + phist = &ec->fir_state_bg.history[offset2]; + + /* st: and en: help us locate the assembler in echo.s */ + + //asm("st:"); + n = ec->taps; + for (i = 0, j = offset2; i < n; i++, j++) + { + exp = *phist++ * factor; + ec->fir_taps16[1][i] += (int16_t) ((exp+(1<<14)) >> 15); + } + //asm("en:"); + + /* Note the asm for the inner loop above generated by Blackfin gcc + 4.1.1 is pretty good (note even parallel instructions used): + + R0 = W [P0++] (X); + R0 *= R2; + R0 = R0 + R3 (NS) || + R1 = W [P1] (X) || + nop; + R0 >>>= 15; + R0 = R0 + R1; + W [P1++] = R0; + + A block based update algorithm would be much faster but the + above can't be improved on much. Every instruction saved in + the loop above is 2 MIPs/ch! The for loop above is where the + Blackfin spends most of it's time - about 17 MIPs/ch measured + with speedtest.c with 256 taps (32ms). Write-back and + Write-through cache gave about the same performance. + */ +} + +/* + IDEAS for further optimisation of lms_adapt_bg(): + + 1/ The rounding is quite costly. Could we keep as 32 bit coeffs + then make filter pluck the MS 16-bits of the coeffs when filtering? + However this would lower potential optimisation of filter, as I + think the dual-MAC architecture requires packed 16 bit coeffs. + + 2/ Block based update would be more efficient, as per comments above, + could use dual MAC architecture. + + 3/ Look for same sample Blackfin LMS code, see if we can get dual-MAC + packing. + + 4/ Execute the whole e/c in a block of say 20ms rather than sample + by sample. Processing a few samples every ms is inefficient. +*/ + +#else +static __inline__ void lms_adapt_bg(echo_can_state_t *ec, int clean, int shift) +{ + int i; + + int offset1; + int offset2; + int factor; + int exp; + + if (shift > 0) + factor = clean << shift; + else + factor = clean >> -shift; + + /* Update the FIR taps */ + + offset2 = ec->curr_pos; + offset1 = ec->taps - offset2; + + for (i = ec->taps - 1; i >= offset1; i--) + { + exp = (ec->fir_state_bg.history[i - offset1]*factor); + ec->fir_taps16[1][i] += (int16_t) ((exp+(1<<14)) >> 15); + } + for ( ; i >= 0; i--) + { + exp = (ec->fir_state_bg.history[i + offset2]*factor); + ec->fir_taps16[1][i] += (int16_t) ((exp+(1<<14)) >> 15); + } +} +#endif + +/*- End of function --------------------------------------------------------*/ + +echo_can_state_t *echo_can_create(int len, int adaption_mode) +{ + echo_can_state_t *ec; + int i; + int j; + + ec = kmalloc(sizeof(*ec), GFP_KERNEL); + if (ec == NULL) + return NULL; + memset(ec, 0, sizeof(*ec)); + + ec->taps = len; + ec->log2taps = top_bit(len); + ec->curr_pos = ec->taps - 1; + + for (i = 0; i < 2; i++) + { + if ((ec->fir_taps16[i] = (int16_t *) malloc((ec->taps)*sizeof(int16_t))) == NULL) + { + for (j = 0; j < i; j++) + kfree(ec->fir_taps16[j]); + kfree(ec); + return NULL; + } + memset(ec->fir_taps16[i], 0, (ec->taps)*sizeof(int16_t)); + } + + fir16_create(&ec->fir_state, + ec->fir_taps16[0], + ec->taps); + fir16_create(&ec->fir_state_bg, + ec->fir_taps16[1], + ec->taps); + + for(i=0; i<5; i++) { + ec->xvtx[i] = ec->yvtx[i] = ec->xvrx[i] = ec->yvrx[i] = 0; + } + + ec->cng_level = 1000; + echo_can_adaption_mode(ec, adaption_mode); + + ec->snapshot = (int16_t*)malloc(ec->taps*sizeof(int16_t)); + memset(ec->snapshot, 0, sizeof(int16_t)*ec->taps); + + ec->cond_met = 0; + ec->Pstates = 0; + ec->Ltxacc = ec->Lrxacc = ec->Lcleanacc = ec->Lclean_bgacc = 0; + ec->Ltx = ec->Lrx = ec->Lclean = ec->Lclean_bg = 0; + ec->tx_1 = ec->tx_2 = ec->rx_1 = ec->rx_2 = 0; + ec->Lbgn = ec->Lbgn_acc = 0; + ec->Lbgn_upper = 200; + ec->Lbgn_upper_acc = ec->Lbgn_upper << 13; + + return ec; +} +/*- End of function --------------------------------------------------------*/ + +void echo_can_free(echo_can_state_t *ec) +{ + int i; + + fir16_free(&ec->fir_state); + fir16_free(&ec->fir_state_bg); + for (i = 0; i < 2; i++) + kfree(ec->fir_taps16[i]); + kfree(ec->snapshot); + kfree(ec); +} +/*- End of function --------------------------------------------------------*/ + +void echo_can_adaption_mode(echo_can_state_t *ec, int adaption_mode) +{ + ec->adaption_mode = adaption_mode; +} +/*- End of function --------------------------------------------------------*/ + +void echo_can_flush(echo_can_state_t *ec) +{ + int i; + + ec->Ltxacc = ec->Lrxacc = ec->Lcleanacc = ec->Lclean_bgacc = 0; + ec->Ltx = ec->Lrx = ec->Lclean = ec->Lclean_bg = 0; + ec->tx_1 = ec->tx_2 = ec->rx_1 = ec->rx_2 = 0; + + ec->Lbgn = ec->Lbgn_acc = 0; + ec->Lbgn_upper = 200; + ec->Lbgn_upper_acc = ec->Lbgn_upper << 13; + + ec->nonupdate_dwell = 0; + + fir16_flush(&ec->fir_state); + fir16_flush(&ec->fir_state_bg); + ec->fir_state.curr_pos = ec->taps - 1; + ec->fir_state_bg.curr_pos = ec->taps - 1; + for (i = 0; i < 2; i++) + memset(ec->fir_taps16[i], 0, ec->taps*sizeof(int16_t)); + + ec->curr_pos = ec->taps - 1; + ec->Pstates = 0; +} +/*- End of function --------------------------------------------------------*/ + +void echo_can_snapshot(echo_can_state_t *ec) { + memcpy(ec->snapshot, ec->fir_taps16[0], ec->taps*sizeof(int16_t)); +} +/*- End of function --------------------------------------------------------*/ + +/* Dual Path Echo Canceller ------------------------------------------------*/ + +int16_t echo_can_update(echo_can_state_t *ec, int16_t tx, int16_t rx) +{ + int32_t echo_value; + int clean_bg; + int tmp, tmp1; + + /* Input scaling was found be required to prevent problems when tx + starts clipping. Another possible way to handle this would be the + filter coefficent scaling. */ + + ec->tx = tx; ec->rx = rx; + tx >>=1; + rx >>=1; + + /* + Filter DC, 3dB point is 160Hz (I think), note 32 bit precision required + otherwise values do not track down to 0. Zero at DC, Pole at (1-Beta) + only real axis. Some chip sets (like Si labs) don't need + this, but something like a $10 X100P card does. Any DC really slows + down convergence. + + Note: removes some low frequency from the signal, this reduces + the speech quality when listening to samples through headphones + but may not be obvious through a telephone handset. + + Note that the 3dB frequency in radians is approx Beta, e.g. for + Beta = 2^(-3) = 0.125, 3dB freq is 0.125 rads = 159Hz. + */ + + if (ec->adaption_mode & ECHO_CAN_USE_RX_HPF) { + tmp = rx << 15; +#if 1 + /* Make sure the gain of the HPF is 1.0. This can still saturate a little under + impulse conditions, and it might roll to 32768 and need clipping on sustained peak + level signals. However, the scale of such clipping is small, and the error due to + any saturation should not markedly affect the downstream processing. */ + tmp -= (tmp >> 4); +#endif + ec->rx_1 += -(ec->rx_1>>DC_LOG2BETA) + tmp - ec->rx_2; + + /* hard limit filter to prevent clipping. Note that at this stage + rx should be limited to +/- 16383 due to right shift above */ + tmp1 = ec->rx_1 >> 15; + if (tmp1 > 16383) tmp1 = 16383; + if (tmp1 < -16383) tmp1 = -16383; + rx = tmp1; + ec->rx_2 = tmp; + } + + /* Block average of power in the filter states. Used for + adaption power calculation. */ + + { + int new, old; + + /* efficient "out with the old and in with the new" algorithm so + we don't have to recalculate over the whole block of + samples. */ + new = (int)tx * (int)tx; + old = (int)ec->fir_state.history[ec->fir_state.curr_pos] * + (int)ec->fir_state.history[ec->fir_state.curr_pos]; + ec->Pstates += ((new - old) + (1<<ec->log2taps)) >> ec->log2taps; + if (ec->Pstates < 0) ec->Pstates = 0; + } + + /* Calculate short term average levels using simple single pole IIRs */ + + ec->Ltxacc += abs(tx) - ec->Ltx; + ec->Ltx = (ec->Ltxacc + (1<<4)) >> 5; + ec->Lrxacc += abs(rx) - ec->Lrx; + ec->Lrx = (ec->Lrxacc + (1<<4)) >> 5; + + /* Foreground filter ---------------------------------------------------*/ + + ec->fir_state.coeffs = ec->fir_taps16[0]; + echo_value = fir16(&ec->fir_state, tx); + ec->clean = rx - echo_value; + ec->Lcleanacc += abs(ec->clean) - ec->Lclean; + ec->Lclean = (ec->Lcleanacc + (1<<4)) >> 5; + + /* Background filter ---------------------------------------------------*/ + + echo_value = fir16(&ec->fir_state_bg, tx); + clean_bg = rx - echo_value; + ec->Lclean_bgacc += abs(clean_bg) - ec->Lclean_bg; + ec->Lclean_bg = (ec->Lclean_bgacc + (1<<4)) >> 5; + + /* Background Filter adaption -----------------------------------------*/ + + /* Almost always adap bg filter, just simple DT and energy + detection to minimise adaption in cases of strong double talk. + However this is not critical for the dual path algorithm. + */ + ec->factor = 0; + ec->shift = 0; + if ((ec->nonupdate_dwell == 0)) { + int P, logP, shift; + + /* Determine: + + f = Beta * clean_bg_rx/P ------ (1) + + where P is the total power in the filter states. + + The Boffins have shown that if we obey (1) we converge + quickly and avoid instability. + + The correct factor f must be in Q30, as this is the fixed + point format required by the lms_adapt_bg() function, + therefore the scaled version of (1) is: + + (2^30) * f = (2^30) * Beta * clean_bg_rx/P + factor = (2^30) * Beta * clean_bg_rx/P ----- (2) + + We have chosen Beta = 0.25 by experiment, so: + + factor = (2^30) * (2^-2) * clean_bg_rx/P + + (30 - 2 - log2(P)) + factor = clean_bg_rx 2 ----- (3) + + To avoid a divide we approximate log2(P) as top_bit(P), + which returns the position of the highest non-zero bit in + P. This approximation introduces an error as large as a + factor of 2, but the algorithm seems to handle it OK. + + Come to think of it a divide may not be a big deal on a + modern DSP, so its probably worth checking out the cycles + for a divide versus a top_bit() implementation. + */ + + P = MIN_TX_POWER_FOR_ADAPTION + ec->Pstates; + logP = top_bit(P) + ec->log2taps; + shift = 30 - 2 - logP; + ec->shift = shift; + + lms_adapt_bg(ec, clean_bg, shift); + } + + /* very simple DTD to make sure we dont try and adapt with strong + near end speech */ + + ec->adapt = 0; + if ((ec->Lrx > MIN_RX_POWER_FOR_ADAPTION) && (ec->Lrx > ec->Ltx)) + ec->nonupdate_dwell = DTD_HANGOVER; + if (ec->nonupdate_dwell) + ec->nonupdate_dwell--; + + /* Transfer logic ------------------------------------------------------*/ + + /* These conditions are from the dual path paper [1], I messed with + them a bit to improve performance. */ + + if ((ec->adaption_mode & ECHO_CAN_USE_ADAPTION) && + (ec->nonupdate_dwell == 0) && + (8*ec->Lclean_bg < 7*ec->Lclean) /* (ec->Lclean_bg < 0.875*ec->Lclean) */ && + (8*ec->Lclean_bg < ec->Ltx) /* (ec->Lclean_bg < 0.125*ec->Ltx) */ ) + { + if (ec->cond_met == 6) { + /* BG filter has had better results for 6 consecutive samples */ + ec->adapt = 1; + memcpy(ec->fir_taps16[0], ec->fir_taps16[1], ec->taps*sizeof(int16_t)); + } + else + ec->cond_met++; + } + else + ec->cond_met = 0; + + /* Non-Linear Processing ---------------------------------------------------*/ + + ec->clean_nlp = ec->clean; + if (ec->adaption_mode & ECHO_CAN_USE_NLP) + { + /* Non-linear processor - a fancy way to say "zap small signals, to avoid + residual echo due to (uLaw/ALaw) non-linearity in the channel.". */ + + if ((16*ec->Lclean < ec->Ltx)) + { + /* Our e/c has improved echo by at least 24 dB (each factor of 2 is 6dB, + so 2*2*2*2=16 is the same as 6+6+6+6=24dB) */ + if (ec->adaption_mode & ECHO_CAN_USE_CNG) + { + ec->cng_level = ec->Lbgn; + + /* Very elementary comfort noise generation. Just random + numbers rolled off very vaguely Hoth-like. DR: This + noise doesn't sound quite right to me - I suspect there + are some overlfow issues in the filtering as it's too + "crackly". TODO: debug this, maybe just play noise at + high level or look at spectrum. + */ + + ec->cng_rndnum = 1664525U*ec->cng_rndnum + 1013904223U; + ec->cng_filter = ((ec->cng_rndnum & 0xFFFF) - 32768 + 5*ec->cng_filter) >> 3; + ec->clean_nlp = (ec->cng_filter*ec->cng_level*8) >> 14; + + } + else if (ec->adaption_mode & ECHO_CAN_USE_CLIP) + { + /* This sounds much better than CNG */ + if (ec->clean_nlp > ec->Lbgn) + ec->clean_nlp = ec->Lbgn; + if (ec->clean_nlp < -ec->Lbgn) + ec->clean_nlp = -ec->Lbgn; + } + else + { + /* just mute the residual, doesn't sound very good, used mainly + in G168 tests */ + ec->clean_nlp = 0; + } + } + else { + /* Background noise estimator. I tried a few algorithms + here without much luck. This very simple one seems to + work best, we just average the level using a slow (1 sec + time const) filter if the current level is less than a + (experimentally derived) constant. This means we dont + include high level signals like near end speech. When + combined with CNG or especially CLIP seems to work OK. + */ + if (ec->Lclean < 40) { + ec->Lbgn_acc += abs(ec->clean) - ec->Lbgn; + ec->Lbgn = (ec->Lbgn_acc + (1<<11)) >> 12; + } + } + } + + /* Roll around the taps buffer */ + if (ec->curr_pos <= 0) + ec->curr_pos = ec->taps; + ec->curr_pos--; + + if (ec->adaption_mode & ECHO_CAN_DISABLE) + ec->clean_nlp = rx; + + /* Output scaled back up again to match input scaling */ + + return (int16_t) ec->clean_nlp << 1; +} + +/*- End of function --------------------------------------------------------*/ + +/* This function is seperated from the echo canceller is it is usually called + as part of the tx process. See rx HP (DC blocking) filter above, it's + the same design. + + Some soft phones send speech signals with a lot of low frequency + energy, e.g. down to 20Hz. This can make the hybrid non-linear + which causes the echo canceller to fall over. This filter can help + by removing any low frequency before it gets to the tx port of the + hybrid. + + It can also help by removing and DC in the tx signal. DC is bad + for LMS algorithms. + + This is one of the classic DC removal filters, adjusted to provide sufficient + bass rolloff to meet the above requirement to protect hybrids from things that + upset them. The difference between successive samples produces a lousy HPF, and + then a suitably placed pole flattens things out. The final result is a nicely + rolled off bass end. The filtering is implemented with extended fractional + precision, which noise shapes things, giving very clean DC removal. +*/ + +int16_t echo_can_hpf_tx(echo_can_state_t *ec, int16_t tx) { + int tmp, tmp1; + + if (ec->adaption_mode & ECHO_CAN_USE_TX_HPF) { + tmp = tx << 15; +#if 1 + /* Make sure the gain of the HPF is 1.0. The first can still saturate a little under + impulse conditions, and it might roll to 32768 and need clipping on sustained peak + level signals. However, the scale of such clipping is small, and the error due to + any saturation should not markedly affect the downstream processing. */ + tmp -= (tmp >> 4); +#endif + ec->tx_1 += -(ec->tx_1>>DC_LOG2BETA) + tmp - ec->tx_2; + tmp1 = ec->tx_1 >> 15; + if (tmp1 > 32767) tmp1 = 32767; + if (tmp1 < -32767) tmp1 = -32767; + tx = tmp1; + ec->tx_2 = tmp; + } + + return tx; +} diff --git a/drivers/staging/echo/echo.h b/drivers/staging/echo/echo.h new file mode 100644 index 000000000000..7a91b4390f3b --- /dev/null +++ b/drivers/staging/echo/echo.h @@ -0,0 +1,220 @@ +/* + * SpanDSP - a series of DSP components for telephony + * + * echo.c - A line echo canceller. This code is being developed + * against and partially complies with G168. + * + * Written by Steve Underwood <steveu@coppice.org> + * and David Rowe <david_at_rowetel_dot_com> + * + * Copyright (C) 2001 Steve Underwood and 2007 David Rowe + * + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, as + * published by the Free Software Foundation. + * + * 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. + * + * $Id: echo.h,v 1.9 2006/10/24 13:45:28 steveu Exp $ + */ + +#ifndef __ECHO_H +#define __ECHO_H + +/*! \page echo_can_page Line echo cancellation for voice + +\section echo_can_page_sec_1 What does it do? +This module aims to provide G.168-2002 compliant echo cancellation, to remove +electrical echoes (e.g. from 2-4 wire hybrids) from voice calls. + +\section echo_can_page_sec_2 How does it work? +The heart of the echo cancellor is FIR filter. This is adapted to match the +echo impulse response of the telephone line. It must be long enough to +adequately cover the duration of that impulse response. The signal transmitted +to the telephone line is passed through the FIR filter. Once the FIR is +properly adapted, the resulting output is an estimate of the echo signal +received from the line. This is subtracted from the received signal. The result +is an estimate of the signal which originated at the far end of the line, free +from echos of our own transmitted signal. + +The least mean squares (LMS) algorithm is attributed to Widrow and Hoff, and +was introduced in 1960. It is the commonest form of filter adaption used in +things like modem line equalisers and line echo cancellers. There it works very +well. However, it only works well for signals of constant amplitude. It works +very poorly for things like speech echo cancellation, where the signal level +varies widely. This is quite easy to fix. If the signal level is normalised - +similar to applying AGC - LMS can work as well for a signal of varying +amplitude as it does for a modem signal. This normalised least mean squares +(NLMS) algorithm is the commonest one used for speech echo cancellation. Many +other algorithms exist - e.g. RLS (essentially the same as Kalman filtering), +FAP, etc. Some perform significantly better than NLMS. However, factors such +as computational complexity and patents favour the use of NLMS. + +A simple refinement to NLMS can improve its performance with speech. NLMS tends +to adapt best to the strongest parts of a signal. If the signal is white noise, +the NLMS algorithm works very well. However, speech has more low frequency than +high frequency content. Pre-whitening (i.e. filtering the signal to flatten its +spectrum) the echo signal improves the adapt rate for speech, and ensures the +final residual signal is not heavily biased towards high frequencies. A very +low complexity filter is adequate for this, so pre-whitening adds little to the +compute requirements of the echo canceller. + +An FIR filter adapted using pre-whitened NLMS performs well, provided certain +conditions are met: + + - The transmitted signal has poor self-correlation. + - There is no signal being generated within the environment being + cancelled. + +The difficulty is that neither of these can be guaranteed. + +If the adaption is performed while transmitting noise (or something fairly +noise like, such as voice) the adaption works very well. If the adaption is +performed while transmitting something highly correlative (typically narrow +band energy such as signalling tones or DTMF), the adaption can go seriously +wrong. The reason is there is only one solution for the adaption on a near +random signal - the impulse response of the line. For a repetitive signal, +there are any number of solutions which converge the adaption, and nothing +guides the adaption to choose the generalised one. Allowing an untrained +canceller to converge on this kind of narrowband energy probably a good thing, +since at least it cancels the tones. Allowing a well converged canceller to +continue converging on such energy is just a way to ruin its generalised +adaption. A narrowband detector is needed, so adapation can be suspended at +appropriate times. + +The adaption process is based on trying to eliminate the received signal. When +there is any signal from within the environment being cancelled it may upset +the adaption process. Similarly, if the signal we are transmitting is small, +noise may dominate and disturb the adaption process. If we can ensure that the +adaption is only performed when we are transmitting a significant signal level, +and the environment is not, things will be OK. Clearly, it is easy to tell when +we are sending a significant signal. Telling, if the environment is generating +a significant signal, and doing it with sufficient speed that the adaption will +not have diverged too much more we stop it, is a little harder. + +The key problem in detecting when the environment is sourcing significant +energy is that we must do this very quickly. Given a reasonably long sample of +the received signal, there are a number of strategies which may be used to +assess whether that signal contains a strong far end component. However, by the +time that assessment is complete the far end signal will have already caused +major mis-convergence in the adaption process. An assessment algorithm is +needed which produces a fairly accurate result from a very short burst of far +end energy. + +\section echo_can_page_sec_3 How do I use it? +The echo cancellor processes both the transmit and receive streams sample by +sample. The processing function is not declared inline. Unfortunately, +cancellation requires many operations per sample, so the call overhead is only +a minor burden. +*/ + +#include "fir.h" + +/* Mask bits for the adaption mode */ +#define ECHO_CAN_USE_ADAPTION 0x01 +#define ECHO_CAN_USE_NLP 0x02 +#define ECHO_CAN_USE_CNG 0x04 +#define ECHO_CAN_USE_CLIP 0x08 +#define ECHO_CAN_USE_TX_HPF 0x10 +#define ECHO_CAN_USE_RX_HPF 0x20 +#define ECHO_CAN_DISABLE 0x40 + +/*! + G.168 echo canceller descriptor. This defines the working state for a line + echo canceller. +*/ +typedef struct +{ + int16_t tx,rx; + int16_t clean; + int16_t clean_nlp; + + int nonupdate_dwell; + int curr_pos; + int taps; + int log2taps; + int adaption_mode; + + int cond_met; + int32_t Pstates; + int16_t adapt; + int32_t factor; + int16_t shift; + + /* Average levels and averaging filter states */ + int Ltxacc, Lrxacc, Lcleanacc, Lclean_bgacc; + int Ltx, Lrx; + int Lclean; + int Lclean_bg; + int Lbgn, Lbgn_acc, Lbgn_upper, Lbgn_upper_acc; + + /* foreground and background filter states */ + fir16_state_t fir_state; + fir16_state_t fir_state_bg; + int16_t *fir_taps16[2]; + + /* DC blocking filter states */ + int tx_1, tx_2, rx_1, rx_2; + + /* optional High Pass Filter states */ + int32_t xvtx[5], yvtx[5]; + int32_t xvrx[5], yvrx[5]; + + /* Parameters for the optional Hoth noise generator */ + int cng_level; + int cng_rndnum; + int cng_filter; + + /* snapshot sample of coeffs used for development */ + int16_t *snapshot; +} echo_can_state_t; + +/*! Create a voice echo canceller context. + \param len The length of the canceller, in samples. + \return The new canceller context, or NULL if the canceller could not be created. +*/ +echo_can_state_t *echo_can_create(int len, int adaption_mode); + +/*! Free a voice echo canceller context. + \param ec The echo canceller context. +*/ +void echo_can_free(echo_can_state_t *ec); + +/*! Flush (reinitialise) a voice echo canceller context. + \param ec The echo canceller context. +*/ +void echo_can_flush(echo_can_state_t *ec); + +/*! Set the adaption mode of a voice echo canceller context. + \param ec The echo canceller context. + \param adapt The mode. +*/ +void echo_can_adaption_mode(echo_can_state_t *ec, int adaption_mode); + +void echo_can_snapshot(echo_can_state_t *ec); + +/*! Process a sample through a voice echo canceller. + \param ec The echo canceller context. + \param tx The transmitted audio sample. + \param rx The received audio sample. + \return The clean (echo cancelled) received sample. +*/ +int16_t echo_can_update(echo_can_state_t *ec, int16_t tx, int16_t rx); + +/*! Process to high pass filter the tx signal. + \param ec The echo canceller context. + \param tx The transmitted auio sample. + \return The HP filtered transmit sample, send this to your D/A. +*/ +int16_t echo_can_hpf_tx(echo_can_state_t *ec, int16_t tx); + +#endif /* __ECHO_H */ diff --git a/drivers/staging/echo/fir.h b/drivers/staging/echo/fir.h new file mode 100644 index 000000000000..e1bfc4994886 --- /dev/null +++ b/drivers/staging/echo/fir.h @@ -0,0 +1,369 @@ +/* + * SpanDSP - a series of DSP components for telephony + * + * fir.h - General telephony FIR routines + * + * Written by Steve Underwood <steveu@coppice.org> + * + * Copyright (C) 2002 Steve Underwood + * + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, as + * published by the Free Software Foundation. + * + * 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. + * + * $Id: fir.h,v 1.8 2006/10/24 13:45:28 steveu Exp $ + */ + +/*! \page fir_page FIR filtering +\section fir_page_sec_1 What does it do? +???. + +\section fir_page_sec_2 How does it work? +???. +*/ + +#if !defined(_FIR_H_) +#define _FIR_H_ + +/* + Blackfin NOTES & IDEAS: + + A simple dot product function is used to implement the filter. This performs + just one MAC/cycle which is inefficient but was easy to implement as a first + pass. The current Blackfin code also uses an unrolled form of the filter + history to avoid 0 length hardware loop issues. This is wasteful of + memory. + + Ideas for improvement: + + 1/ Rewrite filter for dual MAC inner loop. The issue here is handling + history sample offsets that are 16 bit aligned - the dual MAC needs + 32 bit aligmnent. There are some good examples in libbfdsp. + + 2/ Use the hardware circular buffer facility tohalve memory usage. + + 3/ Consider using internal memory. + + Using less memory might also improve speed as cache misses will be + reduced. A drop in MIPs and memory approaching 50% should be + possible. + + The foreground and background filters currenlty use a total of + about 10 MIPs/ch as measured with speedtest.c on a 256 TAP echo + can. +*/ + +#if defined(USE_MMX) || defined(USE_SSE2) +#include "mmx.h" +#endif + +/*! + 16 bit integer FIR descriptor. This defines the working state for a single + instance of an FIR filter using 16 bit integer coefficients. +*/ +typedef struct +{ + int taps; + int curr_pos; + const int16_t *coeffs; + int16_t *history; +} fir16_state_t; + +/*! + 32 bit integer FIR descriptor. This defines the working state for a single + instance of an FIR filter using 32 bit integer coefficients, and filtering + 16 bit integer data. +*/ +typedef struct +{ + int taps; + int curr_pos; + const int32_t *coeffs; + int16_t *history; +} fir32_state_t; + +/*! + Floating point FIR descriptor. This defines the working state for a single + instance of an FIR filter using floating point coefficients and data. +*/ +typedef struct +{ + int taps; + int curr_pos; + const float *coeffs; + float *history; +} fir_float_state_t; + +#ifdef __cplusplus +extern "C" { +#endif + +static __inline__ const int16_t *fir16_create(fir16_state_t *fir, + const int16_t *coeffs, + int taps) +{ + fir->taps = taps; + fir->curr_pos = taps - 1; + fir->coeffs = coeffs; +#if defined(USE_MMX) || defined(USE_SSE2) || defined(__BLACKFIN_ASM__) + if ((fir->history = malloc(2*taps*sizeof(int16_t)))) + memset(fir->history, 0, 2*taps*sizeof(int16_t)); +#else + if ((fir->history = (int16_t *) malloc(taps*sizeof(int16_t)))) + memset(fir->history, 0, taps*sizeof(int16_t)); +#endif + return fir->history; +} +/*- End of function --------------------------------------------------------*/ + +static __inline__ void fir16_flush(fir16_state_t *fir) +{ +#if defined(USE_MMX) || defined(USE_SSE2) || defined(__BLACKFIN_ASM__) + memset(fir->history, 0, 2*fir->taps*sizeof(int16_t)); +#else + memset(fir->history, 0, fir->taps*sizeof(int16_t)); +#endif +} +/*- End of function --------------------------------------------------------*/ + +static __inline__ void fir16_free(fir16_state_t *fir) +{ + free(fir->history); +} +/*- End of function --------------------------------------------------------*/ + +#ifdef __BLACKFIN_ASM__ +static inline int32_t dot_asm(short *x, short *y, int len) +{ + int dot; + + len--; + + __asm__ + ( + "I0 = %1;\n\t" + "I1 = %2;\n\t" + "A0 = 0;\n\t" + "R0.L = W[I0++] || R1.L = W[I1++];\n\t" + "LOOP dot%= LC0 = %3;\n\t" + "LOOP_BEGIN dot%=;\n\t" + "A0 += R0.L * R1.L (IS) || R0.L = W[I0++] || R1.L = W[I1++];\n\t" + "LOOP_END dot%=;\n\t" + "A0 += R0.L*R1.L (IS);\n\t" + "R0 = A0;\n\t" + "%0 = R0;\n\t" + : "=&d" (dot) + : "a" (x), "a" (y), "a" (len) + : "I0", "I1", "A1", "A0", "R0", "R1" + ); + + return dot; +} +#endif +/*- End of function --------------------------------------------------------*/ + +static __inline__ int16_t fir16(fir16_state_t *fir, int16_t sample) +{ + int32_t y; +#if defined(USE_MMX) + int i; + mmx_t *mmx_coeffs; + mmx_t *mmx_hist; + + fir->history[fir->curr_pos] = sample; + fir->history[fir->curr_pos + fir->taps] = sample; + + mmx_coeffs = (mmx_t *) fir->coeffs; + mmx_hist = (mmx_t *) &fir->history[fir->curr_pos]; + i = fir->taps; + pxor_r2r(mm4, mm4); + /* 8 samples per iteration, so the filter must be a multiple of 8 long. */ + while (i > 0) + { + movq_m2r(mmx_coeffs[0], mm0); + movq_m2r(mmx_coeffs[1], mm2); + movq_m2r(mmx_hist[0], mm1); + movq_m2r(mmx_hist[1], mm3); + mmx_coeffs += 2; + mmx_hist += 2; + pmaddwd_r2r(mm1, mm0); + pmaddwd_r2r(mm3, mm2); + paddd_r2r(mm0, mm4); + paddd_r2r(mm2, mm4); + i -= 8; + } + movq_r2r(mm4, mm0); + psrlq_i2r(32, mm0); + paddd_r2r(mm0, mm4); + movd_r2m(mm4, y); + emms(); +#elif defined(USE_SSE2) + int i; + xmm_t *xmm_coeffs; + xmm_t *xmm_hist; + + fir->history[fir->curr_pos] = sample; + fir->history[fir->curr_pos + fir->taps] = sample; + + xmm_coeffs = (xmm_t *) fir->coeffs; + xmm_hist = (xmm_t *) &fir->history[fir->curr_pos]; + i = fir->taps; + pxor_r2r(xmm4, xmm4); + /* 16 samples per iteration, so the filter must be a multiple of 16 long. */ + while (i > 0) + { + movdqu_m2r(xmm_coeffs[0], xmm0); + movdqu_m2r(xmm_coeffs[1], xmm2); + movdqu_m2r(xmm_hist[0], xmm1); + movdqu_m2r(xmm_hist[1], xmm3); + xmm_coeffs += 2; + xmm_hist += 2; + pmaddwd_r2r(xmm1, xmm0); + pmaddwd_r2r(xmm3, xmm2); + paddd_r2r(xmm0, xmm4); + paddd_r2r(xmm2, xmm4); + i -= 16; + } + movdqa_r2r(xmm4, xmm0); + psrldq_i2r(8, xmm0); + paddd_r2r(xmm0, xmm4); + movdqa_r2r(xmm4, xmm0); + psrldq_i2r(4, xmm0); + paddd_r2r(xmm0, xmm4); + movd_r2m(xmm4, y); +#elif defined(__BLACKFIN_ASM__) + fir->history[fir->curr_pos] = sample; + fir->history[fir->curr_pos + fir->taps] = sample; + y = dot_asm((int16_t*)fir->coeffs, &fir->history[fir->curr_pos], fir->taps); +#else + int i; + int offset1; + int offset2; + + fir->history[fir->curr_pos] = sample; + + offset2 = fir->curr_pos; + offset1 = fir->taps - offset2; + y = 0; + for (i = fir->taps - 1; i >= offset1; i--) + y += fir->coeffs[i]*fir->history[i - offset1]; + for ( ; i >= 0; i--) + y += fir->coeffs[i]*fir->history[i + offset2]; +#endif + if (fir->curr_pos <= 0) + fir->curr_pos = fir->taps; + fir->curr_pos--; + return (int16_t) (y >> 15); +} +/*- End of function --------------------------------------------------------*/ + +static __inline__ const int16_t *fir32_create(fir32_state_t *fir, + const int32_t *coeffs, + int taps) +{ + fir->taps = taps; + fir->curr_pos = taps - 1; + fir->coeffs = coeffs; + fir->history = (int16_t *) malloc(taps*sizeof(int16_t)); + if (fir->history) + memset(fir->history, '\0', taps*sizeof(int16_t)); + return fir->history; +} +/*- End of function --------------------------------------------------------*/ + +static __inline__ void fir32_flush(fir32_state_t *fir) +{ + memset(fir->history, 0, fir->taps*sizeof(int16_t)); +} +/*- End of function --------------------------------------------------------*/ + +static __inline__ void fir32_free(fir32_state_t *fir) +{ + free(fir->history); +} +/*- End of function --------------------------------------------------------*/ + +static __inline__ int16_t fir32(fir32_state_t *fir, int16_t sample) +{ + int i; + int32_t y; + int offset1; + int offset2; + + fir->history[fir->curr_pos] = sample; + offset2 = fir->curr_pos; + offset1 = fir->taps - offset2; + y = 0; + for (i = fir->taps - 1; i >= offset1; i--) + y += fir->coeffs[i]*fir->history[i - offset1]; + for ( ; i >= 0; i--) + y += fir->coeffs[i]*fir->history[i + offset2]; + if (fir->curr_pos <= 0) + fir->curr_pos = fir->taps; + fir->curr_pos--; + return (int16_t) (y >> 15); +} +/*- End of function --------------------------------------------------------*/ + +#ifndef __KERNEL__ +static __inline__ const float *fir_float_create(fir_float_state_t *fir, + const float *coeffs, + int taps) +{ + fir->taps = taps; + fir->curr_pos = taps - 1; + fir->coeffs = coeffs; + fir->history = (float *) malloc(taps*sizeof(float)); + if (fir->history) + memset(fir->history, '\0', taps*sizeof(float)); + return fir->history; +} +/*- End of function --------------------------------------------------------*/ + +static __inline__ void fir_float_free(fir_float_state_t *fir) +{ + free(fir->history); +} +/*- End of function --------------------------------------------------------*/ + +static __inline__ int16_t fir_float(fir_float_state_t *fir, int16_t sample) +{ + int i; + float y; + int offset1; + int offset2; + + fir->history[fir->curr_pos] = sample; + + offset2 = fir->curr_pos; + offset1 = fir->taps - offset2; + y = 0; + for (i = fir->taps - 1; i >= offset1; i--) + y += fir->coeffs[i]*fir->history[i - offset1]; + for ( ; i >= 0; i--) + y += fir->coeffs[i]*fir->history[i + offset2]; + if (fir->curr_pos <= 0) + fir->curr_pos = fir->taps; + fir->curr_pos--; + return (int16_t) y; +} +/*- End of function --------------------------------------------------------*/ +#endif + +#ifdef __cplusplus +} +#endif + +#endif +/*- End of file ------------------------------------------------------------*/ diff --git a/drivers/staging/echo/mmx.h b/drivers/staging/echo/mmx.h new file mode 100644 index 000000000000..b5a3964865b6 --- /dev/null +++ b/drivers/staging/echo/mmx.h @@ -0,0 +1,288 @@ +/* + * mmx.h + * Copyright (C) 1997-2001 H. Dietz and R. Fisher + * + * This file is part of FFmpeg. + * + * FFmpeg is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * FFmpeg is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +#ifndef AVCODEC_I386MMX_H +#define AVCODEC_I386MMX_H + +/* + * The type of an value that fits in an MMX register (note that long + * long constant values MUST be suffixed by LL and unsigned long long + * values by ULL, lest they be truncated by the compiler) + */ + +typedef union { + long long q; /* Quadword (64-bit) value */ + unsigned long long uq; /* Unsigned Quadword */ + int d[2]; /* 2 Doubleword (32-bit) values */ + unsigned int ud[2]; /* 2 Unsigned Doubleword */ + short w[4]; /* 4 Word (16-bit) values */ + unsigned short uw[4]; /* 4 Unsigned Word */ + char b[8]; /* 8 Byte (8-bit) values */ + unsigned char ub[8]; /* 8 Unsigned Byte */ + float s[2]; /* Single-precision (32-bit) value */ +} mmx_t; /* On an 8-byte (64-bit) boundary */ + +/* SSE registers */ +typedef union { + char b[16]; +} xmm_t; + + +#define mmx_i2r(op,imm,reg) \ + __asm__ __volatile__ (#op " %0, %%" #reg \ + : /* nothing */ \ + : "i" (imm) ) + +#define mmx_m2r(op,mem,reg) \ + __asm__ __volatile__ (#op " %0, %%" #reg \ + : /* nothing */ \ + : "m" (mem)) + +#define mmx_r2m(op,reg,mem) \ + __asm__ __volatile__ (#op " %%" #reg ", %0" \ + : "=m" (mem) \ + : /* nothing */ ) + +#define mmx_r2r(op,regs,regd) \ + __asm__ __volatile__ (#op " %" #regs ", %" #regd) + + +#define emms() __asm__ __volatile__ ("emms") + +#define movd_m2r(var,reg) mmx_m2r (movd, var, reg) +#define movd_r2m(reg,var) mmx_r2m (movd, reg, var) +#define movd_r2r(regs,regd) mmx_r2r (movd, regs, regd) + +#define movq_m2r(var,reg) mmx_m2r (movq, var, reg) +#define movq_r2m(reg,var) mmx_r2m (movq, reg, var) +#define movq_r2r(regs,regd) mmx_r2r (movq, regs, regd) + +#define packssdw_m2r(var,reg) mmx_m2r (packssdw, var, reg) +#define packssdw_r2r(regs,regd) mmx_r2r (packssdw, regs, regd) +#define packsswb_m2r(var,reg) mmx_m2r (packsswb, var, reg) +#define packsswb_r2r(regs,regd) mmx_r2r (packsswb, regs, regd) + +#define packuswb_m2r(var,reg) mmx_m2r (packuswb, var, reg) +#define packuswb_r2r(regs,regd) mmx_r2r (packuswb, regs, regd) + +#define paddb_m2r(var,reg) mmx_m2r (paddb, var, reg) +#define paddb_r2r(regs,regd) mmx_r2r (paddb, regs, regd) +#define paddd_m2r(var,reg) mmx_m2r (paddd, var, reg) +#define paddd_r2r(regs,regd) mmx_r2r (paddd, regs, regd) +#define paddw_m2r(var,reg) mmx_m2r (paddw, var, reg) +#define paddw_r2r(regs,regd) mmx_r2r (paddw, regs, regd) + +#define paddsb_m2r(var,reg) mmx_m2r (paddsb, var, reg) +#define paddsb_r2r(regs,regd) mmx_r2r (paddsb, regs, regd) +#define paddsw_m2r(var,reg) mmx_m2r (paddsw, var, reg) +#define paddsw_r2r(regs,regd) mmx_r2r (paddsw, regs, regd) + +#define paddusb_m2r(var,reg) mmx_m2r (paddusb, var, reg) +#define paddusb_r2r(regs,regd) mmx_r2r (paddusb, regs, regd) +#define paddusw_m2r(var,reg) mmx_m2r (paddusw, var, reg) +#define paddusw_r2r(regs,regd) mmx_r2r (paddusw, regs, regd) + +#define pand_m2r(var,reg) mmx_m2r (pand, var, reg) +#define pand_r2r(regs,regd) mmx_r2r (pand, regs, regd) + +#define pandn_m2r(var,reg) mmx_m2r (pandn, var, reg) +#define pandn_r2r(regs,regd) mmx_r2r (pandn, regs, regd) + +#define pcmpeqb_m2r(var,reg) mmx_m2r (pcmpeqb, var, reg) +#define pcmpeqb_r2r(regs,regd) mmx_r2r (pcmpeqb, regs, regd) +#define pcmpeqd_m2r(var,reg) mmx_m2r (pcmpeqd, var, reg) +#define pcmpeqd_r2r(regs,regd) mmx_r2r (pcmpeqd, regs, regd) +#define pcmpeqw_m2r(var,reg) mmx_m2r (pcmpeqw, var, reg) +#define pcmpeqw_r2r(regs,regd) mmx_r2r (pcmpeqw, regs, regd) + +#define pcmpgtb_m2r(var,reg) mmx_m2r (pcmpgtb, var, reg) +#define pcmpgtb_r2r(regs,regd) mmx_r2r (pcmpgtb, regs, regd) +#define pcmpgtd_m2r(var,reg) mmx_m2r (pcmpgtd, var, reg) +#define pcmpgtd_r2r(regs,regd) mmx_r2r (pcmpgtd, regs, regd) +#define pcmpgtw_m2r(var,reg) mmx_m2r (pcmpgtw, var, reg) +#define pcmpgtw_r2r(regs,regd) mmx_r2r (pcmpgtw, regs, regd) + +#define pmaddwd_m2r(var,reg) mmx_m2r (pmaddwd, var, reg) +#define pmaddwd_r2r(regs,regd) mmx_r2r (pmaddwd, regs, regd) + +#define pmulhw_m2r(var,reg) mmx_m2r (pmulhw, var, reg) +#define pmulhw_r2r(regs,regd) mmx_r2r (pmulhw, regs, regd) + +#define pmullw_m2r(var,reg) mmx_m2r (pmullw, var, reg) +#define pmullw_r2r(regs,regd) mmx_r2r (pmullw, regs, regd) + +#define por_m2r(var,reg) mmx_m2r (por, var, reg) +#define por_r2r(regs,regd) mmx_r2r (por, regs, regd) + +#define pslld_i2r(imm,reg) mmx_i2r (pslld, imm, reg) +#define pslld_m2r(var,reg) mmx_m2r (pslld, var, reg) +#define pslld_r2r(regs,regd) mmx_r2r (pslld, regs, regd) +#define psllq_i2r(imm,reg) mmx_i2r (psllq, imm, reg) +#define psllq_m2r(var,reg) mmx_m2r (psllq, var, reg) +#define psllq_r2r(regs,regd) mmx_r2r (psllq, regs, regd) +#define psllw_i2r(imm,reg) mmx_i2r (psllw, imm, reg) +#define psllw_m2r(var,reg) mmx_m2r (psllw, var, reg) +#define psllw_r2r(regs,regd) mmx_r2r (psllw, regs, regd) + +#define psrad_i2r(imm,reg) mmx_i2r (psrad, imm, reg) +#define psrad_m2r(var,reg) mmx_m2r (psrad, var, reg) +#define psrad_r2r(regs,regd) mmx_r2r (psrad, regs, regd) +#define psraw_i2r(imm,reg) mmx_i2r (psraw, imm, reg) +#define psraw_m2r(var,reg) mmx_m2r (psraw, var, reg) +#define psraw_r2r(regs,regd) mmx_r2r (psraw, regs, regd) + +#define psrld_i2r(imm,reg) mmx_i2r (psrld, imm, reg) +#define psrld_m2r(var,reg) mmx_m2r (psrld, var, reg) +#define psrld_r2r(regs,regd) mmx_r2r (psrld, regs, regd) +#define psrlq_i2r(imm,reg) mmx_i2r (psrlq, imm, reg) +#define psrlq_m2r(var,reg) mmx_m2r (psrlq, var, reg) +#define psrlq_r2r(regs,regd) mmx_r2r (psrlq, regs, regd) +#define psrlw_i2r(imm,reg) mmx_i2r (psrlw, imm, reg) +#define psrlw_m2r(var,reg) mmx_m2r (psrlw, var, reg) +#define psrlw_r2r(regs,regd) mmx_r2r (psrlw, regs, regd) + +#define psubb_m2r(var,reg) mmx_m2r (psubb, var, reg) +#define psubb_r2r(regs,regd) mmx_r2r (psubb, regs, regd) +#define psubd_m2r(var,reg) mmx_m2r (psubd, var, reg) +#define psubd_r2r(regs,regd) mmx_r2r (psubd, regs, regd) +#define psubw_m2r(var,reg) mmx_m2r (psubw, var, reg) +#define psubw_r2r(regs,regd) mmx_r2r (psubw, regs, regd) + +#define psubsb_m2r(var,reg) mmx_m2r (psubsb, var, reg) +#define psubsb_r2r(regs,regd) mmx_r2r (psubsb, regs, regd) +#define psubsw_m2r(var,reg) mmx_m2r (psubsw, var, reg) +#define psubsw_r2r(regs,regd) mmx_r2r (psubsw, regs, regd) + +#define psubusb_m2r(var,reg) mmx_m2r (psubusb, var, reg) +#define psubusb_r2r(regs,regd) mmx_r2r (psubusb, regs, regd) +#define psubusw_m2r(var,reg) mmx_m2r (psubusw, var, reg) +#define psubusw_r2r(regs,regd) mmx_r2r (psubusw, regs, regd) + +#define punpckhbw_m2r(var,reg) mmx_m2r (punpckhbw, var, reg) +#define punpckhbw_r2r(regs,regd) mmx_r2r (punpckhbw, regs, regd) +#define punpckhdq_m2r(var,reg) mmx_m2r (punpckhdq, var, reg) +#define punpckhdq_r2r(regs,regd) mmx_r2r (punpckhdq, regs, regd) +#define punpckhwd_m2r(var,reg) mmx_m2r (punpckhwd, var, reg) +#define punpckhwd_r2r(regs,regd) mmx_r2r (punpckhwd, regs, regd) + +#define punpcklbw_m2r(var,reg) mmx_m2r (punpcklbw, var, reg) +#define punpcklbw_r2r(regs,regd) mmx_r2r (punpcklbw, regs, regd) +#define punpckldq_m2r(var,reg) mmx_m2r (punpckldq, var, reg) +#define punpckldq_r2r(regs,regd) mmx_r2r (punpckldq, regs, regd) +#define punpcklwd_m2r(var,reg) mmx_m2r (punpcklwd, var, reg) +#define punpcklwd_r2r(regs,regd) mmx_r2r (punpcklwd, regs, regd) + +#define pxor_m2r(var,reg) mmx_m2r (pxor, var, reg) +#define pxor_r2r(regs,regd) mmx_r2r (pxor, regs, regd) + + +/* 3DNOW extensions */ + +#define pavgusb_m2r(var,reg) mmx_m2r (pavgusb, var, reg) +#define pavgusb_r2r(regs,regd) mmx_r2r (pavgusb, regs, regd) + + +/* AMD MMX extensions - also available in intel SSE */ + + +#define mmx_m2ri(op,mem,reg,imm) \ + __asm__ __volatile__ (#op " %1, %0, %%" #reg \ + : /* nothing */ \ + : "m" (mem), "i" (imm)) +#define mmx_r2ri(op,regs,regd,imm) \ + __asm__ __volatile__ (#op " %0, %%" #regs ", %%" #regd \ + : /* nothing */ \ + : "i" (imm) ) + +#define mmx_fetch(mem,hint) \ + __asm__ __volatile__ ("prefetch" #hint " %0" \ + : /* nothing */ \ + : "m" (mem)) + + +#define maskmovq(regs,maskreg) mmx_r2ri (maskmovq, regs, maskreg) + +#define movntq_r2m(mmreg,var) mmx_r2m (movntq, mmreg, var) + +#define pavgb_m2r(var,reg) mmx_m2r (pavgb, var, reg) +#define pavgb_r2r(regs,regd) mmx_r2r (pavgb, regs, regd) +#define pavgw_m2r(var,reg) mmx_m2r (pavgw, var, reg) +#define pavgw_r2r(regs,regd) mmx_r2r (pavgw, regs, regd) + +#define pextrw_r2r(mmreg,reg,imm) mmx_r2ri (pextrw, mmreg, reg, imm) + +#define pinsrw_r2r(reg,mmreg,imm) mmx_r2ri (pinsrw, reg, mmreg, imm) + +#define pmaxsw_m2r(var,reg) mmx_m2r (pmaxsw, var, reg) +#define pmaxsw_r2r(regs,regd) mmx_r2r (pmaxsw, regs, regd) + +#define pmaxub_m2r(var,reg) mmx_m2r (pmaxub, var, reg) +#define pmaxub_r2r(regs,regd) mmx_r2r (pmaxub, regs, regd) + +#define pminsw_m2r(var,reg) mmx_m2r (pminsw, var, reg) +#define pminsw_r2r(regs,regd) mmx_r2r (pminsw, regs, regd) + +#define pminub_m2r(var,reg) mmx_m2r (pminub, var, reg) +#define pminub_r2r(regs,regd) mmx_r2r (pminub, regs, regd) + +#define pmovmskb(mmreg,reg) \ + __asm__ __volatile__ ("movmskps %" #mmreg ", %" #reg) + +#define pmulhuw_m2r(var,reg) mmx_m2r (pmulhuw, var, reg) +#define pmulhuw_r2r(regs,regd) mmx_r2r (pmulhuw, regs, regd) + +#define prefetcht0(mem) mmx_fetch (mem, t0) +#define prefetcht1(mem) mmx_fetch (mem, t1) +#define prefetcht2(mem) mmx_fetch (mem, t2) +#define prefetchnta(mem) mmx_fetch (mem, nta) + +#define psadbw_m2r(var,reg) mmx_m2r (psadbw, var, reg) +#define psadbw_r2r(regs,regd) mmx_r2r (psadbw, regs, regd) + +#define pshufw_m2r(var,reg,imm) mmx_m2ri(pshufw, var, reg, imm) +#define pshufw_r2r(regs,regd,imm) mmx_r2ri(pshufw, regs, regd, imm) + +#define sfence() __asm__ __volatile__ ("sfence\n\t") + +/* SSE2 */ +#define pshufhw_m2r(var,reg,imm) mmx_m2ri(pshufhw, var, reg, imm) +#define pshufhw_r2r(regs,regd,imm) mmx_r2ri(pshufhw, regs, regd, imm) +#define pshuflw_m2r(var,reg,imm) mmx_m2ri(pshuflw, var, reg, imm) +#define pshuflw_r2r(regs,regd,imm) mmx_r2ri(pshuflw, regs, regd, imm) + +#define pshufd_r2r(regs,regd,imm) mmx_r2ri(pshufd, regs, regd, imm) + +#define movdqa_m2r(var,reg) mmx_m2r (movdqa, var, reg) +#define movdqa_r2m(reg,var) mmx_r2m (movdqa, reg, var) +#define movdqa_r2r(regs,regd) mmx_r2r (movdqa, regs, regd) +#define movdqu_m2r(var,reg) mmx_m2r (movdqu, var, reg) +#define movdqu_r2m(reg,var) mmx_r2m (movdqu, reg, var) +#define movdqu_r2r(regs,regd) mmx_r2r (movdqu, regs, regd) + +#define pmullw_r2m(reg,var) mmx_r2m (pmullw, reg, var) + +#define pslldq_i2r(imm,reg) mmx_i2r (pslldq, imm, reg) +#define psrldq_i2r(imm,reg) mmx_i2r (psrldq, imm, reg) + +#define punpcklqdq_r2r(regs,regd) mmx_r2r (punpcklqdq, regs, regd) +#define punpckhqdq_r2r(regs,regd) mmx_r2r (punpckhqdq, regs, regd) + + +#endif /* AVCODEC_I386MMX_H */ diff --git a/drivers/staging/et131x/Kconfig b/drivers/staging/et131x/Kconfig new file mode 100644 index 000000000000..e11cf340856a --- /dev/null +++ b/drivers/staging/et131x/Kconfig @@ -0,0 +1,18 @@ +config ET131X + tristate "Agere ET-1310 Gigabit Ethernet support" + depends on NETDEV_1000 && PCI + default n + ---help--- + This driver supports Agere ET-1310 ethernet adapters. + + To compile this driver as a module, choose M here. The module + will be called et131x. + +config ET131X_DEBUG + bool "Enable et131x debugging" + depends on ET131X + default n + ---help--- + Say Y for detailed debug information. + + If in doubt, say N. diff --git a/drivers/staging/et131x/Makefile b/drivers/staging/et131x/Makefile new file mode 100644 index 000000000000..3ad571d8a684 --- /dev/null +++ b/drivers/staging/et131x/Makefile @@ -0,0 +1,18 @@ +# +# Makefile for the Agere ET-131x ethernet driver +# + +obj-$(CONFIG_ET131X) += et131x.o + +et131x-objs := et1310_eeprom.o \ + et1310_jagcore.o \ + et1310_mac.o \ + et1310_phy.o \ + et1310_pm.o \ + et1310_rx.o \ + et1310_tx.o \ + et131x_config.o \ + et131x_debug.o \ + et131x_initpci.o \ + et131x_isr.o \ + et131x_netdev.o diff --git a/drivers/staging/et131x/README b/drivers/staging/et131x/README new file mode 100644 index 000000000000..28752a502312 --- /dev/null +++ b/drivers/staging/et131x/README @@ -0,0 +1,25 @@ +This is a driver for the ET1310 network device. + +Based on the driver found at https://sourceforge.net/projects/et131x/ + +Cleaned up immensely by Olaf Hartman <o.hartmann@telovital.com> and Christoph +Hellwig <hch@infradead.org> + +Note, the powermanagement options were removed from the vendor provided +driver as they did not build properly at the time. + +TODO: + - kernel coding style cleanups + - forward port for latest network driver changes + - kill useless typecasts (e.g. in et1310_phy.c) + - alloc_etherdev is initializing memory with zero?!? + - add_timer call in et131x_netdev.c is correct? + - Add power saving functionality (suspend, sleep, resume) + - Implement a few more kernel Parameter (set mac ) + +Please send patches to: + Greg Kroah-Hartman <gregkh@suse.de> + +And Cc: Olaf Hartmann <o.hartmann@telovital.com> as he has this device and can +test any changes. + diff --git a/drivers/staging/et131x/et1310_address_map.h b/drivers/staging/et131x/et1310_address_map.h new file mode 100644 index 000000000000..3c85999d64db --- /dev/null +++ b/drivers/staging/et131x/et1310_address_map.h @@ -0,0 +1,2399 @@ +/* + * Agere Systems Inc. + * 10/100/1000 Base-T Ethernet Driver for the ET1301 and ET131x series MACs + * + * Copyright © 2005 Agere Systems Inc. + * All rights reserved. + * http://www.agere.com + * + *------------------------------------------------------------------------------ + * + * et1310_address_map.h - Contains the register mapping for the ET1310 + * + *------------------------------------------------------------------------------ + * + * SOFTWARE LICENSE + * + * This software is provided subject to the following terms and conditions, + * which you should read carefully before using the software. Using this + * software indicates your acceptance of these terms and conditions. If you do + * not agree with these terms and conditions, do not use the software. + * + * Copyright © 2005 Agere Systems Inc. + * All rights reserved. + * + * Redistribution and use in source or binary forms, with or without + * modifications, are permitted provided that the following conditions are met: + * + * . Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following Disclaimer as comments in the code as + * well as in the documentation and/or other materials provided with the + * distribution. + * + * . Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following Disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * . Neither the name of Agere Systems Inc. nor the names of the contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * Disclaimer + * + * THIS SOFTWARE IS PROVIDED “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, INFRINGEMENT AND THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ANY + * USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE IS SOLELY AT THE USERS OWN + * RISK. IN NO EVENT SHALL AGERE SYSTEMS INC. OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, INCLUDING, BUT NOT LIMITED TO, CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + */ + +#ifndef _ET1310_ADDRESS_MAP_H_ +#define _ET1310_ADDRESS_MAP_H_ + + +/* START OF GLOBAL REGISTER ADDRESS MAP */ + +typedef union _Q_ADDR_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused:22; // bits 10-31 + u32 addr:10; // bits 0-9 +#else + u32 addr:10; // bits 0-9 + u32 unused:22; // bits 10-31 +#endif + } bits; +} Q_ADDR_t, *PQ_ADDR_t; + +/* + * structure for tx queue start address reg in global address map + * located at address 0x0000 + * Defined earlier (Q_ADDR_t) + */ + +/* + * structure for tx queue end address reg in global address map + * located at address 0x0004 + * Defined earlier (Q_ADDR_t) + */ + +/* + * structure for rx queue start address reg in global address map + * located at address 0x0008 + * Defined earlier (Q_ADDR_t) + */ + +/* + * structure for rx queue end address reg in global address map + * located at address 0x000C + * Defined earlier (Q_ADDR_t) + */ + +/* + * structure for power management control status reg in global address map + * located at address 0x0010 + */ +typedef union _PM_CSR_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused:22; // bits 10-31 + u32 pm_jagcore_rx_rdy:1; // bit 9 + u32 pm_jagcore_tx_rdy:1; // bit 8 + u32 pm_phy_lped_en:1; // bit 7 + u32 pm_phy_sw_coma:1; // bit 6 + u32 pm_rxclk_gate:1; // bit 5 + u32 pm_txclk_gate:1; // bit 4 + u32 pm_sysclk_gate:1; // bit 3 + u32 pm_jagcore_rx_en:1; // bit 2 + u32 pm_jagcore_tx_en:1; // bit 1 + u32 pm_gigephy_en:1; // bit 0 +#else + u32 pm_gigephy_en:1; // bit 0 + u32 pm_jagcore_tx_en:1; // bit 1 + u32 pm_jagcore_rx_en:1; // bit 2 + u32 pm_sysclk_gate:1; // bit 3 + u32 pm_txclk_gate:1; // bit 4 + u32 pm_rxclk_gate:1; // bit 5 + u32 pm_phy_sw_coma:1; // bit 6 + u32 pm_phy_lped_en:1; // bit 7 + u32 pm_jagcore_tx_rdy:1; // bit 8 + u32 pm_jagcore_rx_rdy:1; // bit 9 + u32 unused:22; // bits 10-31 +#endif + } bits; +} PM_CSR_t, *PPM_CSR_t; + +/* + * structure for interrupt status reg in global address map + * located at address 0x0018 + */ +typedef union _INTERRUPT_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused5:11; // bits 21-31 + u32 slv_timeout:1; // bit 20 + u32 mac_stat_interrupt:1; // bit 19 + u32 rxmac_interrupt:1; // bit 18 + u32 txmac_interrupt:1; // bit 17 + u32 phy_interrupt:1; // bit 16 + u32 wake_on_lan:1; // bit 15 + u32 watchdog_interrupt:1; // bit 14 + u32 unused4:4; // bits 10-13 + u32 rxdma_err:1; // bit 9 + u32 rxdma_pkt_stat_ring_low:1; // bit 8 + u32 rxdma_fb_ring1_low:1; // bit 7 + u32 rxdma_fb_ring0_low:1; // bit 6 + u32 rxdma_xfr_done:1; // bit 5 + u32 txdma_err:1; // bit 4 + u32 txdma_isr:1; // bit 3 + u32 unused3:1; // bit 2 + u32 unused2:1; // bit 1 + u32 unused1:1; // bit 0 +#else + u32 unused1:1; // bit 0 + u32 unused2:1; // bit 1 + u32 unused3:1; // bit 2 + u32 txdma_isr:1; // bit 3 + u32 txdma_err:1; // bit 4 + u32 rxdma_xfr_done:1; // bit 5 + u32 rxdma_fb_ring0_low:1; // bit 6 + u32 rxdma_fb_ring1_low:1; // bit 7 + u32 rxdma_pkt_stat_ring_low:1; // bit 8 + u32 rxdma_err:1; // bit 9 + u32 unused4:4; // bits 10-13 + u32 watchdog_interrupt:1; // bit 14 + u32 wake_on_lan:1; // bit 15 + u32 phy_interrupt:1; // bit 16 + u32 txmac_interrupt:1; // bit 17 + u32 rxmac_interrupt:1; // bit 18 + u32 mac_stat_interrupt:1; // bit 19 + u32 slv_timeout:1; // bit 20 + u32 unused5:11; // bits 21-31 +#endif + } bits; +} INTERRUPT_t, *PINTERRUPT_t; + +/* + * structure for interrupt mask reg in global address map + * located at address 0x001C + * Defined earlier (INTERRUPT_t), but 'watchdog_interrupt' is not used. + */ + +/* + * structure for interrupt alias clear mask reg in global address map + * located at address 0x0020 + * Defined earlier (INTERRUPT_t) + */ + +/* + * structure for interrupt status alias reg in global address map + * located at address 0x0024 + * Defined earlier (INTERRUPT_t) + */ + +/* + * structure for software reset reg in global address map + * located at address 0x0028 + */ +typedef union _SW_RESET_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 selfclr_disable:1; // bit 31 + u32 unused:24; // bits 7-30 + u32 mmc_sw_reset:1; // bit 6 + u32 mac_stat_sw_reset:1; // bit 5 + u32 mac_sw_reset:1; // bit 4 + u32 rxmac_sw_reset:1; // bit 3 + u32 txmac_sw_reset:1; // bit 2 + u32 rxdma_sw_reset:1; // bit 1 + u32 txdma_sw_reset:1; // bit 0 +#else + u32 txdma_sw_reset:1; // bit 0 + u32 rxdma_sw_reset:1; // bit 1 + u32 txmac_sw_reset:1; // bit 2 + u32 rxmac_sw_reset:1; // bit 3 + u32 mac_sw_reset:1; // bit 4 + u32 mac_stat_sw_reset:1; // bit 5 + u32 mmc_sw_reset:1; // bit 6 + u32 unused:24; // bits 7-30 + u32 selfclr_disable:1; // bit 31 +#endif + } bits; +} SW_RESET_t, *PSW_RESET_t; + +/* + * structure for SLV Timer reg in global address map + * located at address 0x002C + */ +typedef union _SLV_TIMER_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused:8; // bits 24-31 + u32 timer_ini:24; // bits 0-23 +#else + u32 timer_ini:24; // bits 0-23 + u32 unused:8; // bits 24-31 +#endif + } bits; +} SLV_TIMER_t, *PSLV_TIMER_t; + +/* + * structure for MSI Configuration reg in global address map + * located at address 0x0030 + */ +typedef union _MSI_CONFIG_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused1:13; // bits 19-31 + u32 msi_tc:3; // bits 16-18 + u32 unused2:11; // bits 5-15 + u32 msi_vector:5; // bits 0-4 +#else + u32 msi_vector:5; // bits 0-4 + u32 unused2:11; // bits 5-15 + u32 msi_tc:3; // bits 16-18 + u32 unused1:13; // bits 19-31 +#endif + } bits; +} MSI_CONFIG_t, *PMSI_CONFIG_t; + +/* + * structure for Loopback reg in global address map + * located at address 0x0034 + */ +typedef union _LOOPBACK_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused:30; // bits 2-31 + u32 dma_loopback:1; // bit 1 + u32 mac_loopback:1; // bit 0 +#else + u32 mac_loopback:1; // bit 0 + u32 dma_loopback:1; // bit 1 + u32 unused:30; // bits 2-31 +#endif + } bits; +} LOOPBACK_t, *PLOOPBACK_t; + +/* + * GLOBAL Module of JAGCore Address Mapping + * Located at address 0x0000 + */ +typedef struct _GLOBAL_t { // Location: + Q_ADDR_t txq_start_addr; // 0x0000 + Q_ADDR_t txq_end_addr; // 0x0004 + Q_ADDR_t rxq_start_addr; // 0x0008 + Q_ADDR_t rxq_end_addr; // 0x000C + PM_CSR_t pm_csr; // 0x0010 + u32 unused; // 0x0014 + INTERRUPT_t int_status; // 0x0018 + INTERRUPT_t int_mask; // 0x001C + INTERRUPT_t int_alias_clr_en; // 0x0020 + INTERRUPT_t int_status_alias; // 0x0024 + SW_RESET_t sw_reset; // 0x0028 + SLV_TIMER_t slv_timer; // 0x002C + MSI_CONFIG_t msi_config; // 0x0030 + LOOPBACK_t loopback; // 0x0034 + u32 watchdog_timer; // 0x0038 +} GLOBAL_t, *PGLOBAL_t; + +/* END OF GLOBAL REGISTER ADDRESS MAP */ + + +/* START OF TXDMA REGISTER ADDRESS MAP */ + +/* + * structure for txdma control status reg in txdma address map + * located at address 0x1000 + */ +typedef union _TXDMA_CSR_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused2:19; // bits 13-31 + u32 traffic_class:4; // bits 9-12 + u32 sngl_epkt_mode:1; // bit 8 + u32 cache_thrshld:4; // bits 4-7 + u32 unused1:2; // bits 2-3 + u32 drop_TLP_disable:1; // bit 1 + u32 halt:1; // bit 0 +#else + u32 halt:1; // bit 0 + u32 drop_TLP_disable:1; // bit 1 + u32 unused1:2; // bits 2-3 + u32 cache_thrshld:4; // bits 4-7 + u32 sngl_epkt_mode:1; // bit 8 + u32 traffic_class:4; // bits 9-12 + u32 unused2:19; // bits 13-31 +#endif + } bits; +} TXDMA_CSR_t, *PTXDMA_CSR_t; + +/* + * structure for txdma packet ring base address hi reg in txdma address map + * located at address 0x1004 + * Defined earlier (u32) + */ + +/* + * structure for txdma packet ring base address low reg in txdma address map + * located at address 0x1008 + * Defined earlier (u32) + */ + +/* + * structure for txdma packet ring number of descriptor reg in txdma address + * map. Located at address 0x100C + */ +typedef union _TXDMA_PR_NUM_DES_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused:22; // bits 10-31 + u32 pr_ndes:10; // bits 0-9 +#else + u32 pr_ndes:10; // bits 0-9 + u32 unused:22; // bits 10-31 +#endif + } bits; +} TXDMA_PR_NUM_DES_t, *PTXDMA_PR_NUM_DES_t; + + +typedef union _DMA10W_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused:21; // bits 11-31 + u32 wrap:1; // bit 10 + u32 val:10; // bits 0-9 +#else + u32 val:10; // bits 0-9 + u32 wrap:1; // bit 10 + u32 unused:21; // bits 11-31 +#endif + } bits; +} DMA10W_t, *PDMA10W_t; + +/* + * structure for txdma tx queue write address reg in txdma address map + * located at address 0x1010 + * Defined earlier (DMA10W_t) + */ + +/* + * structure for txdma tx queue write address external reg in txdma address map + * located at address 0x1014 + * Defined earlier (DMA10W_t) + */ + +/* + * structure for txdma tx queue read address reg in txdma address map + * located at address 0x1018 + * Defined earlier (DMA10W_t) + */ + +/* + * structure for txdma status writeback address hi reg in txdma address map + * located at address 0x101C + * Defined earlier (u32) + */ + +/* + * structure for txdma status writeback address lo reg in txdma address map + * located at address 0x1020 + * Defined earlier (u32) + */ + +/* + * structure for txdma service request reg in txdma address map + * located at address 0x1024 + * Defined earlier (DMA10W_t) + */ + +/* + * structure for txdma service complete reg in txdma address map + * located at address 0x1028 + * Defined earlier (DMA10W_t) + */ + +typedef union _DMA4W_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused:27; // bits 5-31 + u32 wrap:1; // bit 4 + u32 val:4; // bit 0-3 +#else + u32 val:4; // bits 0-3 + u32 wrap:1; // bit 4 + u32 unused:27; // bits 5-31 +#endif + } bits; +} DMA4W_t, *PDMA4W_t; + +/* + * structure for txdma tx descriptor cache read index reg in txdma address map + * located at address 0x102C + * Defined earlier (DMA4W_t) + */ + +/* + * structure for txdma tx descriptor cache write index reg in txdma address map + * located at address 0x1030 + * Defined earlier (DMA4W_t) + */ + +/* + * structure for txdma error reg in txdma address map + * located at address 0x1034 + */ +typedef union _TXDMA_ERROR_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused3:22; // bits 10-31 + u32 WrbkRewind:1; // bit 9 + u32 WrbkResend:1; // bit 8 + u32 unused2:2; // bits 6-7 + u32 DescrRewind:1; // bit 5 + u32 DescrResend:1; // bit 4 + u32 unused1:2; // bits 2-3 + u32 PyldRewind:1; // bit 1 + u32 PyldResend:1; // bit 0 +#else + u32 PyldResend:1; // bit 0 + u32 PyldRewind:1; // bit 1 + u32 unused1:2; // bits 2-3 + u32 DescrResend:1; // bit 4 + u32 DescrRewind:1; // bit 5 + u32 unused2:2; // bits 6-7 + u32 WrbkResend:1; // bit 8 + u32 WrbkRewind:1; // bit 9 + u32 unused3:22; // bits 10-31 +#endif + } bits; +} TXDMA_ERROR_t, *PTXDMA_ERROR_t; + +/* + * Tx DMA Module of JAGCore Address Mapping + * Located at address 0x1000 + */ +typedef struct _TXDMA_t { // Location: + TXDMA_CSR_t csr; // 0x1000 + u32 pr_base_hi; // 0x1004 + u32 pr_base_lo; // 0x1008 + TXDMA_PR_NUM_DES_t pr_num_des; // 0x100C + DMA10W_t txq_wr_addr; // 0x1010 + DMA10W_t txq_wr_addr_ext; // 0x1014 + DMA10W_t txq_rd_addr; // 0x1018 + u32 dma_wb_base_hi; // 0x101C + u32 dma_wb_base_lo; // 0x1020 + DMA10W_t service_request; // 0x1024 + DMA10W_t service_complete; // 0x1028 + DMA4W_t cache_rd_index; // 0x102C + DMA4W_t cache_wr_index; // 0x1030 + TXDMA_ERROR_t TxDmaError; // 0x1034 + u32 DescAbortCount; // 0x1038 + u32 PayloadAbortCnt; // 0x103c + u32 WriteBackAbortCnt; // 0x1040 + u32 DescTimeoutCnt; // 0x1044 + u32 PayloadTimeoutCnt; // 0x1048 + u32 WriteBackTimeoutCnt; // 0x104c + u32 DescErrorCount; // 0x1050 + u32 PayloadErrorCnt; // 0x1054 + u32 WriteBackErrorCnt; // 0x1058 + u32 DroppedTLPCount; // 0x105c + DMA10W_t NewServiceComplete; // 0x1060 + u32 EthernetPacketCount; // 0x1064 +} TXDMA_t, *PTXDMA_t; + +/* END OF TXDMA REGISTER ADDRESS MAP */ + + +/* START OF RXDMA REGISTER ADDRESS MAP */ + +/* + * structure for control status reg in rxdma address map + * Located at address 0x2000 + */ +typedef union _RXDMA_CSR_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused2:14; // bits 18-31 + u32 halt_status:1; // bit 17 + u32 pkt_done_flush:1; // bit 16 + u32 pkt_drop_disable:1; // bit 15 + u32 unused1:1; // bit 14 + u32 fbr1_enable:1; // bit 13 + u32 fbr1_size:2; // bits 11-12 + u32 fbr0_enable:1; // bit 10 + u32 fbr0_size:2; // bits 8-9 + u32 dma_big_endian:1; // bit 7 + u32 pkt_big_endian:1; // bit 6 + u32 psr_big_endian:1; // bit 5 + u32 fbr_big_endian:1; // bit 4 + u32 tc:3; // bits 1-3 + u32 halt:1; // bit 0 +#else + u32 halt:1; // bit 0 + u32 tc:3; // bits 1-3 + u32 fbr_big_endian:1; // bit 4 + u32 psr_big_endian:1; // bit 5 + u32 pkt_big_endian:1; // bit 6 + u32 dma_big_endian:1; // bit 7 + u32 fbr0_size:2; // bits 8-9 + u32 fbr0_enable:1; // bit 10 + u32 fbr1_size:2; // bits 11-12 + u32 fbr1_enable:1; // bit 13 + u32 unused1:1; // bit 14 + u32 pkt_drop_disable:1; // bit 15 + u32 pkt_done_flush:1; // bit 16 + u32 halt_status:1; // bit 17 + u32 unused2:14; // bits 18-31 +#endif + } bits; +} RXDMA_CSR_t, *PRXDMA_CSR_t; + +/* + * structure for dma writeback lo reg in rxdma address map + * located at address 0x2004 + * Defined earlier (u32) + */ + +/* + * structure for dma writeback hi reg in rxdma address map + * located at address 0x2008 + * Defined earlier (u32) + */ + +/* + * structure for number of packets done reg in rxdma address map + * located at address 0x200C + */ +typedef union _RXDMA_NUM_PKT_DONE_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused:24; // bits 8-31 + u32 num_done:8; // bits 0-7 +#else + u32 num_done:8; // bits 0-7 + u32 unused:24; // bits 8-31 +#endif + } bits; +} RXDMA_NUM_PKT_DONE_t, *PRXDMA_NUM_PKT_DONE_t; + +/* + * structure for max packet time reg in rxdma address map + * located at address 0x2010 + */ +typedef union _RXDMA_MAX_PKT_TIME_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused:14; // bits 18-31 + u32 time_done:18; // bits 0-17 +#else + u32 time_done:18; // bits 0-17 + u32 unused:14; // bits 18-31 +#endif + } bits; +} RXDMA_MAX_PKT_TIME_t, *PRXDMA_MAX_PKT_TIME_t; + +/* + * structure for rx queue read address reg in rxdma address map + * located at address 0x2014 + * Defined earlier (DMA10W_t) + */ + +/* + * structure for rx queue read address external reg in rxdma address map + * located at address 0x2018 + * Defined earlier (DMA10W_t) + */ + +/* + * structure for rx queue write address reg in rxdma address map + * located at address 0x201C + * Defined earlier (DMA10W_t) + */ + +/* + * structure for packet status ring base address lo reg in rxdma address map + * located at address 0x2020 + * Defined earlier (u32) + */ + +/* + * structure for packet status ring base address hi reg in rxdma address map + * located at address 0x2024 + * Defined earlier (u32) + */ + +/* + * structure for packet status ring number of descriptors reg in rxdma address + * map. Located at address 0x2028 + */ +typedef union _RXDMA_PSR_NUM_DES_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused:20; // bits 12-31 + u32 psr_ndes:12; // bit 0-11 +#else + u32 psr_ndes:12; // bit 0-11 + u32 unused:20; // bits 12-31 +#endif + } bits; +} RXDMA_PSR_NUM_DES_t, *PRXDMA_PSR_NUM_DES_t; + +/* + * structure for packet status ring available offset reg in rxdma address map + * located at address 0x202C + */ +typedef union _RXDMA_PSR_AVAIL_OFFSET_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused:19; // bits 13-31 + u32 psr_avail_wrap:1; // bit 12 + u32 psr_avail:12; // bit 0-11 +#else + u32 psr_avail:12; // bit 0-11 + u32 psr_avail_wrap:1; // bit 12 + u32 unused:19; // bits 13-31 +#endif + } bits; +} RXDMA_PSR_AVAIL_OFFSET_t, *PRXDMA_PSR_AVAIL_OFFSET_t; + +/* + * structure for packet status ring full offset reg in rxdma address map + * located at address 0x2030 + */ +typedef union _RXDMA_PSR_FULL_OFFSET_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused:19; // bits 13-31 + u32 psr_full_wrap:1; // bit 12 + u32 psr_full:12; // bit 0-11 +#else + u32 psr_full:12; // bit 0-11 + u32 psr_full_wrap:1; // bit 12 + u32 unused:19; // bits 13-31 +#endif + } bits; +} RXDMA_PSR_FULL_OFFSET_t, *PRXDMA_PSR_FULL_OFFSET_t; + +/* + * structure for packet status ring access index reg in rxdma address map + * located at address 0x2034 + */ +typedef union _RXDMA_PSR_ACCESS_INDEX_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused:27; // bits 5-31 + u32 psr_ai:5; // bits 0-4 +#else + u32 psr_ai:5; // bits 0-4 + u32 unused:27; // bits 5-31 +#endif + } bits; +} RXDMA_PSR_ACCESS_INDEX_t, *PRXDMA_PSR_ACCESS_INDEX_t; + +/* + * structure for packet status ring minimum descriptors reg in rxdma address + * map. Located at address 0x2038 + */ +typedef union _RXDMA_PSR_MIN_DES_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused:20; // bits 12-31 + u32 psr_min:12; // bits 0-11 +#else + u32 psr_min:12; // bits 0-11 + u32 unused:20; // bits 12-31 +#endif + } bits; +} RXDMA_PSR_MIN_DES_t, *PRXDMA_PSR_MIN_DES_t; + +/* + * structure for free buffer ring base lo address reg in rxdma address map + * located at address 0x203C + * Defined earlier (u32) + */ + +/* + * structure for free buffer ring base hi address reg in rxdma address map + * located at address 0x2040 + * Defined earlier (u32) + */ + +/* + * structure for free buffer ring number of descriptors reg in rxdma address + * map. Located at address 0x2044 + */ +typedef union _RXDMA_FBR_NUM_DES_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused:22; // bits 10-31 + u32 fbr_ndesc:10; // bits 0-9 +#else + u32 fbr_ndesc:10; // bits 0-9 + u32 unused:22; // bits 10-31 +#endif + } bits; +} RXDMA_FBR_NUM_DES_t, *PRXDMA_FBR_NUM_DES_t; + +/* + * structure for free buffer ring 0 available offset reg in rxdma address map + * located at address 0x2048 + * Defined earlier (DMA10W_t) + */ + +/* + * structure for free buffer ring 0 full offset reg in rxdma address map + * located at address 0x204C + * Defined earlier (DMA10W_t) + */ + +/* + * structure for free buffer cache 0 full offset reg in rxdma address map + * located at address 0x2050 + */ +typedef union _RXDMA_FBC_RD_INDEX_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused:27; // bits 5-31 + u32 fbc_rdi:5; // bit 0-4 +#else + u32 fbc_rdi:5; // bit 0-4 + u32 unused:27; // bits 5-31 +#endif + } bits; +} RXDMA_FBC_RD_INDEX_t, *PRXDMA_FBC_RD_INDEX_t; + +/* + * structure for free buffer ring 0 minimum descriptor reg in rxdma address map + * located at address 0x2054 + */ +typedef union _RXDMA_FBR_MIN_DES_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused:22; // bits 10-31 + u32 fbr_min:10; // bits 0-9 +#else + u32 fbr_min:10; // bits 0-9 + u32 unused:22; // bits 10-31 +#endif + } bits; +} RXDMA_FBR_MIN_DES_t, *PRXDMA_FBR_MIN_DES_t; + +/* + * structure for free buffer ring 1 base address lo reg in rxdma address map + * located at address 0x2058 - 0x205C + * Defined earlier (RXDMA_FBR_BASE_LO_t and RXDMA_FBR_BASE_HI_t) + */ + +/* + * structure for free buffer ring 1 number of descriptors reg in rxdma address + * map. Located at address 0x2060 + * Defined earlier (RXDMA_FBR_NUM_DES_t) + */ + +/* + * structure for free buffer ring 1 available offset reg in rxdma address map + * located at address 0x2064 + * Defined Earlier (RXDMA_FBR_AVAIL_OFFSET_t) + */ + +/* + * structure for free buffer ring 1 full offset reg in rxdma address map + * located at address 0x2068 + * Defined Earlier (RXDMA_FBR_FULL_OFFSET_t) + */ + +/* + * structure for free buffer cache 1 read index reg in rxdma address map + * located at address 0x206C + * Defined Earlier (RXDMA_FBC_RD_INDEX_t) + */ + +/* + * structure for free buffer ring 1 minimum descriptor reg in rxdma address map + * located at address 0x2070 + * Defined Earlier (RXDMA_FBR_MIN_DES_t) + */ + +/* + * Rx DMA Module of JAGCore Address Mapping + * Located at address 0x2000 + */ +typedef struct _RXDMA_t { // Location: + RXDMA_CSR_t csr; // 0x2000 + u32 dma_wb_base_lo; // 0x2004 + u32 dma_wb_base_hi; // 0x2008 + RXDMA_NUM_PKT_DONE_t num_pkt_done; // 0x200C + RXDMA_MAX_PKT_TIME_t max_pkt_time; // 0x2010 + DMA10W_t rxq_rd_addr; // 0x2014 + DMA10W_t rxq_rd_addr_ext; // 0x2018 + DMA10W_t rxq_wr_addr; // 0x201C + u32 psr_base_lo; // 0x2020 + u32 psr_base_hi; // 0x2024 + RXDMA_PSR_NUM_DES_t psr_num_des; // 0x2028 + RXDMA_PSR_AVAIL_OFFSET_t psr_avail_offset; // 0x202C + RXDMA_PSR_FULL_OFFSET_t psr_full_offset; // 0x2030 + RXDMA_PSR_ACCESS_INDEX_t psr_access_index; // 0x2034 + RXDMA_PSR_MIN_DES_t psr_min_des; // 0x2038 + u32 fbr0_base_lo; // 0x203C + u32 fbr0_base_hi; // 0x2040 + RXDMA_FBR_NUM_DES_t fbr0_num_des; // 0x2044 + DMA10W_t fbr0_avail_offset; // 0x2048 + DMA10W_t fbr0_full_offset; // 0x204C + RXDMA_FBC_RD_INDEX_t fbr0_rd_index; // 0x2050 + RXDMA_FBR_MIN_DES_t fbr0_min_des; // 0x2054 + u32 fbr1_base_lo; // 0x2058 + u32 fbr1_base_hi; // 0x205C + RXDMA_FBR_NUM_DES_t fbr1_num_des; // 0x2060 + DMA10W_t fbr1_avail_offset; // 0x2064 + DMA10W_t fbr1_full_offset; // 0x2068 + RXDMA_FBC_RD_INDEX_t fbr1_rd_index; // 0x206C + RXDMA_FBR_MIN_DES_t fbr1_min_des; // 0x2070 +} RXDMA_t, *PRXDMA_t; + +/* END OF RXDMA REGISTER ADDRESS MAP */ + + +/* START OF TXMAC REGISTER ADDRESS MAP */ + +/* + * structure for control reg in txmac address map + * located at address 0x3000 + */ +typedef union _TXMAC_CTL_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused:24; // bits 8-31 + u32 cklseg_diable:1; // bit 7 + u32 ckbcnt_disable:1; // bit 6 + u32 cksegnum:1; // bit 5 + u32 async_disable:1; // bit 4 + u32 fc_disable:1; // bit 3 + u32 mcif_disable:1; // bit 2 + u32 mif_disable:1; // bit 1 + u32 txmac_en:1; // bit 0 +#else + u32 txmac_en:1; // bit 0 + u32 mif_disable:1; // bit 1 mac interface + u32 mcif_disable:1; // bit 2 mem. contr. interface + u32 fc_disable:1; // bit 3 + u32 async_disable:1; // bit 4 + u32 cksegnum:1; // bit 5 + u32 ckbcnt_disable:1; // bit 6 + u32 cklseg_diable:1; // bit 7 + u32 unused:24; // bits 8-31 +#endif + } bits; +} TXMAC_CTL_t, *PTXMAC_CTL_t; + +/* + * structure for shadow pointer reg in txmac address map + * located at address 0x3004 + */ +typedef union _TXMAC_SHADOW_PTR_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 reserved2:5; // bits 27-31 + u32 txq_rd_ptr:11; // bits 16-26 + u32 reserved:5; // bits 11-15 + u32 txq_wr_ptr:11; // bits 0-10 +#else + u32 txq_wr_ptr:11; // bits 0-10 + u32 reserved:5; // bits 11-15 + u32 txq_rd_ptr:11; // bits 16-26 + u32 reserved2:5; // bits 27-31 +#endif + } bits; +} TXMAC_SHADOW_PTR_t, *PTXMAC_SHADOW_PTR_t; + +/* + * structure for error count reg in txmac address map + * located at address 0x3008 + */ +typedef union _TXMAC_ERR_CNT_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused:20; // bits 12-31 + u32 reserved:4; // bits 8-11 + u32 txq_underrun:4; // bits 4-7 + u32 fifo_underrun:4; // bits 0-3 +#else + u32 fifo_underrun:4; // bits 0-3 + u32 txq_underrun:4; // bits 4-7 + u32 reserved:4; // bits 8-11 + u32 unused:20; // bits 12-31 +#endif + } bits; +} TXMAC_ERR_CNT_t, *PTXMAC_ERR_CNT_t; + +/* + * structure for max fill reg in txmac address map + * located at address 0x300C + */ +typedef union _TXMAC_MAX_FILL_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused:20; // bits 12-31 + u32 max_fill:12; // bits 0-11 +#else + u32 max_fill:12; // bits 0-11 + u32 unused:20; // bits 12-31 +#endif + } bits; +} TXMAC_MAX_FILL_t, *PTXMAC_MAX_FILL_t; + +/* + * structure for cf parameter reg in txmac address map + * located at address 0x3010 + */ +typedef union _TXMAC_CF_PARAM_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 cfep:16; // bits 16-31 + u32 cfpt:16; // bits 0-15 +#else + u32 cfpt:16; // bits 0-15 + u32 cfep:16; // bits 16-31 +#endif + } bits; +} TXMAC_CF_PARAM_t, *PTXMAC_CF_PARAM_t; + +/* + * structure for tx test reg in txmac address map + * located at address 0x3014 + */ +typedef union _TXMAC_TXTEST_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused2:15; // bits 17-31 + u32 reserved1:1; // bit 16 + u32 txtest_en:1; // bit 15 + u32 unused1:4; // bits 11-14 + u32 txqtest_ptr:11; // bits 0-11 +#else + u32 txqtest_ptr:11; // bits 0-10 + u32 unused1:4; // bits 11-14 + u32 txtest_en:1; // bit 15 + u32 reserved1:1; // bit 16 + u32 unused2:15; // bits 17-31 +#endif + } bits; +} TXMAC_TXTEST_t, *PTXMAC_TXTEST_t; + +/* + * structure for error reg in txmac address map + * located at address 0x3018 + */ +typedef union _TXMAC_ERR_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused2:23; // bits 9-31 + u32 fifo_underrun:1; // bit 8 + u32 unused1:2; // bits 6-7 + u32 ctrl2_err:1; // bit 5 + u32 txq_underrun:1; // bit 4 + u32 bcnt_err:1; // bit 3 + u32 lseg_err:1; // bit 2 + u32 segnum_err:1; // bit 1 + u32 seg0_err:1; // bit 0 +#else + u32 seg0_err:1; // bit 0 + u32 segnum_err:1; // bit 1 + u32 lseg_err:1; // bit 2 + u32 bcnt_err:1; // bit 3 + u32 txq_underrun:1; // bit 4 + u32 ctrl2_err:1; // bit 5 + u32 unused1:2; // bits 6-7 + u32 fifo_underrun:1; // bit 8 + u32 unused2:23; // bits 9-31 +#endif + } bits; +} TXMAC_ERR_t, *PTXMAC_ERR_t; + +/* + * structure for error interrupt reg in txmac address map + * located at address 0x301C + */ +typedef union _TXMAC_ERR_INT_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused2:23; // bits 9-31 + u32 fifo_underrun:1; // bit 8 + u32 unused1:2; // bits 6-7 + u32 ctrl2_err:1; // bit 5 + u32 txq_underrun:1; // bit 4 + u32 bcnt_err:1; // bit 3 + u32 lseg_err:1; // bit 2 + u32 segnum_err:1; // bit 1 + u32 seg0_err:1; // bit 0 +#else + u32 seg0_err:1; // bit 0 + u32 segnum_err:1; // bit 1 + u32 lseg_err:1; // bit 2 + u32 bcnt_err:1; // bit 3 + u32 txq_underrun:1; // bit 4 + u32 ctrl2_err:1; // bit 5 + u32 unused1:2; // bits 6-7 + u32 fifo_underrun:1; // bit 8 + u32 unused2:23; // bits 9-31 +#endif + } bits; +} TXMAC_ERR_INT_t, *PTXMAC_ERR_INT_t; + +/* + * structure for error interrupt reg in txmac address map + * located at address 0x3020 + */ +typedef union _TXMAC_CP_CTRL_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused:30; // bits 2-31 + u32 bp_req:1; // bit 1 + u32 bp_xonxoff:1; // bit 0 +#else + u32 bp_xonxoff:1; // bit 0 + u32 bp_req:1; // bit 1 + u32 unused:30; // bits 2-31 +#endif + } bits; +} TXMAC_BP_CTRL_t, *PTXMAC_BP_CTRL_t; + +/* + * Tx MAC Module of JAGCore Address Mapping + */ +typedef struct _TXMAC_t { // Location: + TXMAC_CTL_t ctl; // 0x3000 + TXMAC_SHADOW_PTR_t shadow_ptr; // 0x3004 + TXMAC_ERR_CNT_t err_cnt; // 0x3008 + TXMAC_MAX_FILL_t max_fill; // 0x300C + TXMAC_CF_PARAM_t cf_param; // 0x3010 + TXMAC_TXTEST_t tx_test; // 0x3014 + TXMAC_ERR_t err; // 0x3018 + TXMAC_ERR_INT_t err_int; // 0x301C + TXMAC_BP_CTRL_t bp_ctrl; // 0x3020 +} TXMAC_t, *PTXMAC_t; + +/* END OF TXMAC REGISTER ADDRESS MAP */ + +/* START OF RXMAC REGISTER ADDRESS MAP */ + +/* + * structure for rxmac control reg in rxmac address map + * located at address 0x4000 + */ +typedef union _RXMAC_CTRL_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 reserved:25; // bits 7-31 + u32 rxmac_int_disable:1; // bit 6 + u32 async_disable:1; // bit 5 + u32 mif_disable:1; // bit 4 + u32 wol_disable:1; // bit 3 + u32 pkt_filter_disable:1; // bit 2 + u32 mcif_disable:1; // bit 1 + u32 rxmac_en:1; // bit 0 +#else + u32 rxmac_en:1; // bit 0 + u32 mcif_disable:1; // bit 1 + u32 pkt_filter_disable:1; // bit 2 + u32 wol_disable:1; // bit 3 + u32 mif_disable:1; // bit 4 + u32 async_disable:1; // bit 5 + u32 rxmac_int_disable:1; // bit 6 + u32 reserved:25; // bits 7-31 +#endif + } bits; +} RXMAC_CTRL_t, *PRXMAC_CTRL_t; + +/* + * structure for Wake On Lan Control and CRC 0 reg in rxmac address map + * located at address 0x4004 + */ +typedef union _RXMAC_WOL_CTL_CRC0_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 crc0:16; // bits 16-31 + u32 reserve:4; // bits 12-15 + u32 ignore_pp:1; // bit 11 + u32 ignore_mp:1; // bit 10 + u32 clr_intr:1; // bit 9 + u32 ignore_link_chg:1; // bit 8 + u32 ignore_uni:1; // bit 7 + u32 ignore_multi:1; // bit 6 + u32 ignore_broad:1; // bit 5 + u32 valid_crc4:1; // bit 4 + u32 valid_crc3:1; // bit 3 + u32 valid_crc2:1; // bit 2 + u32 valid_crc1:1; // bit 1 + u32 valid_crc0:1; // bit 0 +#else + u32 valid_crc0:1; // bit 0 + u32 valid_crc1:1; // bit 1 + u32 valid_crc2:1; // bit 2 + u32 valid_crc3:1; // bit 3 + u32 valid_crc4:1; // bit 4 + u32 ignore_broad:1; // bit 5 + u32 ignore_multi:1; // bit 6 + u32 ignore_uni:1; // bit 7 + u32 ignore_link_chg:1; // bit 8 + u32 clr_intr:1; // bit 9 + u32 ignore_mp:1; // bit 10 + u32 ignore_pp:1; // bit 11 + u32 reserve:4; // bits 12-15 + u32 crc0:16; // bits 16-31 +#endif + } bits; +} RXMAC_WOL_CTL_CRC0_t, *PRXMAC_WOL_CTL_CRC0_t; + +/* + * structure for CRC 1 and CRC 2 reg in rxmac address map + * located at address 0x4008 + */ +typedef union _RXMAC_WOL_CRC12_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 crc2:16; // bits 16-31 + u32 crc1:16; // bits 0-15 +#else + u32 crc1:16; // bits 0-15 + u32 crc2:16; // bits 16-31 +#endif + } bits; +} RXMAC_WOL_CRC12_t, *PRXMAC_WOL_CRC12_t; + +/* + * structure for CRC 3 and CRC 4 reg in rxmac address map + * located at address 0x400C + */ +typedef union _RXMAC_WOL_CRC34_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 crc4:16; // bits 16-31 + u32 crc3:16; // bits 0-15 +#else + u32 crc3:16; // bits 0-15 + u32 crc4:16; // bits 16-31 +#endif + } bits; +} RXMAC_WOL_CRC34_t, *PRXMAC_WOL_CRC34_t; + +/* + * structure for Wake On Lan Source Address Lo reg in rxmac address map + * located at address 0x4010 + */ +typedef union _RXMAC_WOL_SA_LO_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 sa3:8; // bits 24-31 + u32 sa4:8; // bits 16-23 + u32 sa5:8; // bits 8-15 + u32 sa6:8; // bits 0-7 +#else + u32 sa6:8; // bits 0-7 + u32 sa5:8; // bits 8-15 + u32 sa4:8; // bits 16-23 + u32 sa3:8; // bits 24-31 +#endif + } bits; +} RXMAC_WOL_SA_LO_t, *PRXMAC_WOL_SA_LO_t; + +/* + * structure for Wake On Lan Source Address Hi reg in rxmac address map + * located at address 0x4014 + */ +typedef union _RXMAC_WOL_SA_HI_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 reserved:16; // bits 16-31 + u32 sa1:8; // bits 8-15 + u32 sa2:8; // bits 0-7 +#else + u32 sa2:8; // bits 0-7 + u32 sa1:8; // bits 8-15 + u32 reserved:16; // bits 16-31 +#endif + } bits; +} RXMAC_WOL_SA_HI_t, *PRXMAC_WOL_SA_HI_t; + +/* + * structure for Wake On Lan mask reg in rxmac address map + * located at address 0x4018 - 0x4064 + * Defined earlier (u32) + */ + +/* + * structure for Unicast Paket Filter Address 1 reg in rxmac address map + * located at address 0x4068 + */ +typedef union _RXMAC_UNI_PF_ADDR1_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 addr1_3:8; // bits 24-31 + u32 addr1_4:8; // bits 16-23 + u32 addr1_5:8; // bits 8-15 + u32 addr1_6:8; // bits 0-7 +#else + u32 addr1_6:8; // bits 0-7 + u32 addr1_5:8; // bits 8-15 + u32 addr1_4:8; // bits 16-23 + u32 addr1_3:8; // bits 24-31 +#endif + } bits; +} RXMAC_UNI_PF_ADDR1_t, *PRXMAC_UNI_PF_ADDR1_t; + +/* + * structure for Unicast Paket Filter Address 2 reg in rxmac address map + * located at address 0x406C + */ +typedef union _RXMAC_UNI_PF_ADDR2_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 addr2_3:8; // bits 24-31 + u32 addr2_4:8; // bits 16-23 + u32 addr2_5:8; // bits 8-15 + u32 addr2_6:8; // bits 0-7 +#else + u32 addr2_6:8; // bits 0-7 + u32 addr2_5:8; // bits 8-15 + u32 addr2_4:8; // bits 16-23 + u32 addr2_3:8; // bits 24-31 +#endif + } bits; +} RXMAC_UNI_PF_ADDR2_t, *PRXMAC_UNI_PF_ADDR2_t; + +/* + * structure for Unicast Paket Filter Address 1 & 2 reg in rxmac address map + * located at address 0x4070 + */ +typedef union _RXMAC_UNI_PF_ADDR3_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 addr2_1:8; // bits 24-31 + u32 addr2_2:8; // bits 16-23 + u32 addr1_1:8; // bits 8-15 + u32 addr1_2:8; // bits 0-7 +#else + u32 addr1_2:8; // bits 0-7 + u32 addr1_1:8; // bits 8-15 + u32 addr2_2:8; // bits 16-23 + u32 addr2_1:8; // bits 24-31 +#endif + } bits; +} RXMAC_UNI_PF_ADDR3_t, *PRXMAC_UNI_PF_ADDR3_t; + +/* + * structure for Multicast Hash reg in rxmac address map + * located at address 0x4074 - 0x4080 + * Defined earlier (u32) + */ + +/* + * structure for Packet Filter Control reg in rxmac address map + * located at address 0x4084 + */ +typedef union _RXMAC_PF_CTRL_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused2:9; // bits 23-31 + u32 min_pkt_size:7; // bits 16-22 + u32 unused1:12; // bits 4-15 + u32 filter_frag_en:1; // bit 3 + u32 filter_uni_en:1; // bit 2 + u32 filter_multi_en:1; // bit 1 + u32 filter_broad_en:1; // bit 0 +#else + u32 filter_broad_en:1; // bit 0 + u32 filter_multi_en:1; // bit 1 + u32 filter_uni_en:1; // bit 2 + u32 filter_frag_en:1; // bit 3 + u32 unused1:12; // bits 4-15 + u32 min_pkt_size:7; // bits 16-22 + u32 unused2:9; // bits 23-31 +#endif + } bits; +} RXMAC_PF_CTRL_t, *PRXMAC_PF_CTRL_t; + +/* + * structure for Memory Controller Interface Control Max Segment reg in rxmac + * address map. Located at address 0x4088 + */ +typedef union _RXMAC_MCIF_CTRL_MAX_SEG_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 reserved:22; // bits 10-31 + u32 max_size:8; // bits 2-9 + u32 fc_en:1; // bit 1 + u32 seg_en:1; // bit 0 +#else + u32 seg_en:1; // bit 0 + u32 fc_en:1; // bit 1 + u32 max_size:8; // bits 2-9 + u32 reserved:22; // bits 10-31 +#endif + } bits; +} RXMAC_MCIF_CTRL_MAX_SEG_t, *PRXMAC_MCIF_CTRL_MAX_SEG_t; + +/* + * structure for Memory Controller Interface Water Mark reg in rxmac address + * map. Located at address 0x408C + */ +typedef union _RXMAC_MCIF_WATER_MARK_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 reserved2:6; // bits 26-31 + u32 mark_hi:10; // bits 16-25 + u32 reserved1:6; // bits 10-15 + u32 mark_lo:10; // bits 0-9 +#else + u32 mark_lo:10; // bits 0-9 + u32 reserved1:6; // bits 10-15 + u32 mark_hi:10; // bits 16-25 + u32 reserved2:6; // bits 26-31 +#endif + } bits; +} RXMAC_MCIF_WATER_MARK_t, *PRXMAC_MCIF_WATER_MARK_t; + +/* + * structure for Rx Queue Dialog reg in rxmac address map. + * located at address 0x4090 + */ +typedef union _RXMAC_RXQ_DIAG_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 reserved2:6; // bits 26-31 + u32 rd_ptr:10; // bits 16-25 + u32 reserved1:6; // bits 10-15 + u32 wr_ptr:10; // bits 0-9 +#else + u32 wr_ptr:10; // bits 0-9 + u32 reserved1:6; // bits 10-15 + u32 rd_ptr:10; // bits 16-25 + u32 reserved2:6; // bits 26-31 +#endif + } bits; +} RXMAC_RXQ_DIAG_t, *PRXMAC_RXQ_DIAG_t; + +/* + * structure for space availiable reg in rxmac address map. + * located at address 0x4094 + */ +typedef union _RXMAC_SPACE_AVAIL_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 reserved2:15; // bits 17-31 + u32 space_avail_en:1; // bit 16 + u32 reserved1:6; // bits 10-15 + u32 space_avail:10; // bits 0-9 +#else + u32 space_avail:10; // bits 0-9 + u32 reserved1:6; // bits 10-15 + u32 space_avail_en:1; // bit 16 + u32 reserved2:15; // bits 17-31 +#endif + } bits; +} RXMAC_SPACE_AVAIL_t, *PRXMAC_SPACE_AVAIL_t; + +/* + * structure for management interface reg in rxmac address map. + * located at address 0x4098 + */ +typedef union _RXMAC_MIF_CTL_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 reserve:14; // bits 18-31 + u32 drop_pkt_en:1; // bit 17 + u32 drop_pkt_mask:17; // bits 0-16 +#else + u32 drop_pkt_mask:17; // bits 0-16 + u32 drop_pkt_en:1; // bit 17 + u32 reserve:14; // bits 18-31 +#endif + } bits; +} RXMAC_MIF_CTL_t, *PRXMAC_MIF_CTL_t; + +/* + * structure for Error reg in rxmac address map. + * located at address 0x409C + */ +typedef union _RXMAC_ERROR_REG_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 reserve:28; // bits 4-31 + u32 mif:1; // bit 3 + u32 async:1; // bit 2 + u32 pkt_filter:1; // bit 1 + u32 mcif:1; // bit 0 +#else + u32 mcif:1; // bit 0 + u32 pkt_filter:1; // bit 1 + u32 async:1; // bit 2 + u32 mif:1; // bit 3 + u32 reserve:28; // bits 4-31 +#endif + } bits; +} RXMAC_ERROR_REG_t, *PRXMAC_ERROR_REG_t; + +/* + * Rx MAC Module of JAGCore Address Mapping + */ +typedef struct _RXMAC_t { // Location: + RXMAC_CTRL_t ctrl; // 0x4000 + RXMAC_WOL_CTL_CRC0_t crc0; // 0x4004 + RXMAC_WOL_CRC12_t crc12; // 0x4008 + RXMAC_WOL_CRC34_t crc34; // 0x400C + RXMAC_WOL_SA_LO_t sa_lo; // 0x4010 + RXMAC_WOL_SA_HI_t sa_hi; // 0x4014 + u32 mask0_word0; // 0x4018 + u32 mask0_word1; // 0x401C + u32 mask0_word2; // 0x4020 + u32 mask0_word3; // 0x4024 + u32 mask1_word0; // 0x4028 + u32 mask1_word1; // 0x402C + u32 mask1_word2; // 0x4030 + u32 mask1_word3; // 0x4034 + u32 mask2_word0; // 0x4038 + u32 mask2_word1; // 0x403C + u32 mask2_word2; // 0x4040 + u32 mask2_word3; // 0x4044 + u32 mask3_word0; // 0x4048 + u32 mask3_word1; // 0x404C + u32 mask3_word2; // 0x4050 + u32 mask3_word3; // 0x4054 + u32 mask4_word0; // 0x4058 + u32 mask4_word1; // 0x405C + u32 mask4_word2; // 0x4060 + u32 mask4_word3; // 0x4064 + RXMAC_UNI_PF_ADDR1_t uni_pf_addr1; // 0x4068 + RXMAC_UNI_PF_ADDR2_t uni_pf_addr2; // 0x406C + RXMAC_UNI_PF_ADDR3_t uni_pf_addr3; // 0x4070 + u32 multi_hash1; // 0x4074 + u32 multi_hash2; // 0x4078 + u32 multi_hash3; // 0x407C + u32 multi_hash4; // 0x4080 + RXMAC_PF_CTRL_t pf_ctrl; // 0x4084 + RXMAC_MCIF_CTRL_MAX_SEG_t mcif_ctrl_max_seg; // 0x4088 + RXMAC_MCIF_WATER_MARK_t mcif_water_mark; // 0x408C + RXMAC_RXQ_DIAG_t rxq_diag; // 0x4090 + RXMAC_SPACE_AVAIL_t space_avail; // 0x4094 + + RXMAC_MIF_CTL_t mif_ctrl; // 0x4098 + RXMAC_ERROR_REG_t err_reg; // 0x409C +} RXMAC_t, *PRXMAC_t; + +/* END OF TXMAC REGISTER ADDRESS MAP */ + + +/* START OF MAC REGISTER ADDRESS MAP */ + +/* + * structure for configuration #1 reg in mac address map. + * located at address 0x5000 + */ +typedef union _MAC_CFG1_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 soft_reset:1; // bit 31 + u32 sim_reset:1; // bit 30 + u32 reserved3:10; // bits 20-29 + u32 reset_rx_mc:1; // bit 19 + u32 reset_tx_mc:1; // bit 18 + u32 reset_rx_fun:1; // bit 17 + u32 reset_tx_fun:1; // bit 16 + u32 reserved2:7; // bits 9-15 + u32 loop_back:1; // bit 8 + u32 reserved1:2; // bits 6-7 + u32 rx_flow:1; // bit 5 + u32 tx_flow:1; // bit 4 + u32 syncd_rx_en:1; // bit 3 + u32 rx_enable:1; // bit 2 + u32 syncd_tx_en:1; // bit 1 + u32 tx_enable:1; // bit 0 +#else + u32 tx_enable:1; // bit 0 + u32 syncd_tx_en:1; // bit 1 + u32 rx_enable:1; // bit 2 + u32 syncd_rx_en:1; // bit 3 + u32 tx_flow:1; // bit 4 + u32 rx_flow:1; // bit 5 + u32 reserved1:2; // bits 6-7 + u32 loop_back:1; // bit 8 + u32 reserved2:7; // bits 9-15 + u32 reset_tx_fun:1; // bit 16 + u32 reset_rx_fun:1; // bit 17 + u32 reset_tx_mc:1; // bit 18 + u32 reset_rx_mc:1; // bit 19 + u32 reserved3:10; // bits 20-29 + u32 sim_reset:1; // bit 30 + u32 soft_reset:1; // bit 31 +#endif + } bits; +} MAC_CFG1_t, *PMAC_CFG1_t; + +/* + * structure for configuration #2 reg in mac address map. + * located at address 0x5004 + */ +typedef union _MAC_CFG2_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 reserved3:16; // bits 16-31 + u32 preamble_len:4; // bits 12-15 + u32 reserved2:2; // bits 10-11 + u32 if_mode:2; // bits 8-9 + u32 reserved1:2; // bits 6-7 + u32 huge_frame:1; // bit 5 + u32 len_check:1; // bit 4 + u32 undefined:1; // bit 3 + u32 pad_crc:1; // bit 2 + u32 crc_enable:1; // bit 1 + u32 full_duplex:1; // bit 0 +#else + u32 full_duplex:1; // bit 0 + u32 crc_enable:1; // bit 1 + u32 pad_crc:1; // bit 2 + u32 undefined:1; // bit 3 + u32 len_check:1; // bit 4 + u32 huge_frame:1; // bit 5 + u32 reserved1:2; // bits 6-7 + u32 if_mode:2; // bits 8-9 + u32 reserved2:2; // bits 10-11 + u32 preamble_len:4; // bits 12-15 + u32 reserved3:16; // bits 16-31 +#endif + } bits; +} MAC_CFG2_t, *PMAC_CFG2_t; + +/* + * structure for Interpacket gap reg in mac address map. + * located at address 0x5008 + */ +typedef union _MAC_IPG_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 reserved:1; // bit 31 + u32 non_B2B_ipg_1:7; // bits 24-30 + u32 undefined2:1; // bit 23 + u32 non_B2B_ipg_2:7; // bits 16-22 + u32 min_ifg_enforce:8; // bits 8-15 + u32 undefined1:1; // bit 7 + u32 B2B_ipg:7; // bits 0-6 +#else + u32 B2B_ipg:7; // bits 0-6 + u32 undefined1:1; // bit 7 + u32 min_ifg_enforce:8; // bits 8-15 + u32 non_B2B_ipg_2:7; // bits 16-22 + u32 undefined2:1; // bit 23 + u32 non_B2B_ipg_1:7; // bits 24-30 + u32 reserved:1; // bit 31 +#endif + } bits; +} MAC_IPG_t, *PMAC_IPG_t; + +/* + * structure for half duplex reg in mac address map. + * located at address 0x500C + */ +typedef union _MAC_HFDP_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 reserved2:8; // bits 24-31 + u32 alt_beb_trunc:4; // bits 23-20 + u32 alt_beb_enable:1; // bit 19 + u32 bp_no_backoff:1; // bit 18 + u32 no_backoff:1; // bit 17 + u32 excess_defer:1; // bit 16 + u32 rexmit_max:4; // bits 12-15 + u32 reserved1:2; // bits 10-11 + u32 coll_window:10; // bits 0-9 +#else + u32 coll_window:10; // bits 0-9 + u32 reserved1:2; // bits 10-11 + u32 rexmit_max:4; // bits 12-15 + u32 excess_defer:1; // bit 16 + u32 no_backoff:1; // bit 17 + u32 bp_no_backoff:1; // bit 18 + u32 alt_beb_enable:1; // bit 19 + u32 alt_beb_trunc:4; // bits 23-20 + u32 reserved2:8; // bits 24-31 +#endif + } bits; +} MAC_HFDP_t, *PMAC_HFDP_t; + +/* + * structure for Maximum Frame Length reg in mac address map. + * located at address 0x5010 + */ +typedef union _MAC_MAX_FM_LEN_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 reserved:16; // bits 16-31 + u32 max_len:16; // bits 0-15 +#else + u32 max_len:16; // bits 0-15 + u32 reserved:16; // bits 16-31 +#endif + } bits; +} MAC_MAX_FM_LEN_t, *PMAC_MAX_FM_LEN_t; + +/* + * structure for Reserve 1 reg in mac address map. + * located at address 0x5014 - 0x5018 + * Defined earlier (u32) + */ + +/* + * structure for Test reg in mac address map. + * located at address 0x501C + */ +typedef union _MAC_TEST_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused:29; // bits 3-31 + u32 mac_test:3; // bits 0-2 +#else + u32 mac_test:3; // bits 0-2 + u32 unused:29; // bits 3-31 +#endif + } bits; +} MAC_TEST_t, *PMAC_TEST_t; + +/* + * structure for MII Management Configuration reg in mac address map. + * located at address 0x5020 + */ +typedef union _MII_MGMT_CFG_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 reset_mii_mgmt:1; // bit 31 + u32 reserved:25; // bits 6-30 + u32 scan_auto_incremt:1; // bit 5 + u32 preamble_suppress:1; // bit 4 + u32 undefined:1; // bit 3 + u32 mgmt_clk_reset:3; // bits 0-2 +#else + u32 mgmt_clk_reset:3; // bits 0-2 + u32 undefined:1; // bit 3 + u32 preamble_suppress:1; // bit 4 + u32 scan_auto_incremt:1; // bit 5 + u32 reserved:25; // bits 6-30 + u32 reset_mii_mgmt:1; // bit 31 +#endif + } bits; +} MII_MGMT_CFG_t, *PMII_MGMT_CFG_t; + +/* + * structure for MII Management Command reg in mac address map. + * located at address 0x5024 + */ +typedef union _MII_MGMT_CMD_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 reserved:30; // bits 2-31 + u32 scan_cycle:1; // bit 1 + u32 read_cycle:1; // bit 0 +#else + u32 read_cycle:1; // bit 0 + u32 scan_cycle:1; // bit 1 + u32 reserved:30; // bits 2-31 +#endif + } bits; +} MII_MGMT_CMD_t, *PMII_MGMT_CMD_t; + +/* + * structure for MII Management Address reg in mac address map. + * located at address 0x5028 + */ +typedef union _MII_MGMT_ADDR_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 reserved2:19; // bit 13-31 + u32 phy_addr:5; // bits 8-12 + u32 reserved1:3; // bits 5-7 + u32 reg_addr:5; // bits 0-4 +#else + u32 reg_addr:5; // bits 0-4 + u32 reserved1:3; // bits 5-7 + u32 phy_addr:5; // bits 8-12 + u32 reserved2:19; // bit 13-31 +#endif + } bits; +} MII_MGMT_ADDR_t, *PMII_MGMT_ADDR_t; + +/* + * structure for MII Management Control reg in mac address map. + * located at address 0x502C + */ +typedef union _MII_MGMT_CTRL_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 reserved:16; // bits 16-31 + u32 phy_ctrl:16; // bits 0-15 +#else + u32 phy_ctrl:16; // bits 0-15 + u32 reserved:16; // bits 16-31 +#endif + } bits; +} MII_MGMT_CTRL_t, *PMII_MGMT_CTRL_t; + +/* + * structure for MII Management Status reg in mac address map. + * located at address 0x5030 + */ +typedef union _MII_MGMT_STAT_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 reserved:16; // bits 16-31 + u32 phy_stat:16; // bits 0-15 +#else + u32 phy_stat:16; // bits 0-15 + u32 reserved:16; // bits 16-31 +#endif + } bits; +} MII_MGMT_STAT_t, *PMII_MGMT_STAT_t; + +/* + * structure for MII Management Indicators reg in mac address map. + * located at address 0x5034 + */ +typedef union _MII_MGMT_INDICATOR_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 reserved:29; // bits 3-31 + u32 not_valid:1; // bit 2 + u32 scanning:1; // bit 1 + u32 busy:1; // bit 0 +#else + u32 busy:1; // bit 0 + u32 scanning:1; // bit 1 + u32 not_valid:1; // bit 2 + u32 reserved:29; // bits 3-31 +#endif + } bits; +} MII_MGMT_INDICATOR_t, *PMII_MGMT_INDICATOR_t; + +/* + * structure for Interface Control reg in mac address map. + * located at address 0x5038 + */ +typedef union _MAC_IF_CTRL_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 reset_if_module:1; // bit 31 + u32 reserved4:3; // bit 28-30 + u32 tbi_mode:1; // bit 27 + u32 ghd_mode:1; // bit 26 + u32 lhd_mode:1; // bit 25 + u32 phy_mode:1; // bit 24 + u32 reset_per_mii:1; // bit 23 + u32 reserved3:6; // bits 17-22 + u32 speed:1; // bit 16 + u32 reset_pe100x:1; // bit 15 + u32 reserved2:4; // bits 11-14 + u32 force_quiet:1; // bit 10 + u32 no_cipher:1; // bit 9 + u32 disable_link_fail:1; // bit 8 + u32 reset_gpsi:1; // bit 7 + u32 reserved1:6; // bits 1-6 + u32 enab_jab_protect:1; // bit 0 +#else + u32 enab_jab_protect:1; // bit 0 + u32 reserved1:6; // bits 1-6 + u32 reset_gpsi:1; // bit 7 + u32 disable_link_fail:1; // bit 8 + u32 no_cipher:1; // bit 9 + u32 force_quiet:1; // bit 10 + u32 reserved2:4; // bits 11-14 + u32 reset_pe100x:1; // bit 15 + u32 speed:1; // bit 16 + u32 reserved3:6; // bits 17-22 + u32 reset_per_mii:1; // bit 23 + u32 phy_mode:1; // bit 24 + u32 lhd_mode:1; // bit 25 + u32 ghd_mode:1; // bit 26 + u32 tbi_mode:1; // bit 27 + u32 reserved4:3; // bit 28-30 + u32 reset_if_module:1; // bit 31 +#endif + } bits; +} MAC_IF_CTRL_t, *PMAC_IF_CTRL_t; + +/* + * structure for Interface Status reg in mac address map. + * located at address 0x503C + */ +typedef union _MAC_IF_STAT_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 reserved:22; // bits 10-31 + u32 excess_defer:1; // bit 9 + u32 clash:1; // bit 8 + u32 phy_jabber:1; // bit 7 + u32 phy_link_ok:1; // bit 6 + u32 phy_full_duplex:1; // bit 5 + u32 phy_speed:1; // bit 4 + u32 pe100x_link_fail:1; // bit 3 + u32 pe10t_loss_carrie:1; // bit 2 + u32 pe10t_sqe_error:1; // bit 1 + u32 pe10t_jabber:1; // bit 0 +#else + u32 pe10t_jabber:1; // bit 0 + u32 pe10t_sqe_error:1; // bit 1 + u32 pe10t_loss_carrie:1; // bit 2 + u32 pe100x_link_fail:1; // bit 3 + u32 phy_speed:1; // bit 4 + u32 phy_full_duplex:1; // bit 5 + u32 phy_link_ok:1; // bit 6 + u32 phy_jabber:1; // bit 7 + u32 clash:1; // bit 8 + u32 excess_defer:1; // bit 9 + u32 reserved:22; // bits 10-31 +#endif + } bits; +} MAC_IF_STAT_t, *PMAC_IF_STAT_t; + +/* + * structure for Mac Station Address, Part 1 reg in mac address map. + * located at address 0x5040 + */ +typedef union _MAC_STATION_ADDR1_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 Octet6:8; // bits 24-31 + u32 Octet5:8; // bits 16-23 + u32 Octet4:8; // bits 8-15 + u32 Octet3:8; // bits 0-7 +#else + u32 Octet3:8; // bits 0-7 + u32 Octet4:8; // bits 8-15 + u32 Octet5:8; // bits 16-23 + u32 Octet6:8; // bits 24-31 +#endif + } bits; +} MAC_STATION_ADDR1_t, *PMAC_STATION_ADDR1_t; + +/* + * structure for Mac Station Address, Part 2 reg in mac address map. + * located at address 0x5044 + */ +typedef union _MAC_STATION_ADDR2_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 Octet2:8; // bits 24-31 + u32 Octet1:8; // bits 16-23 + u32 reserved:16; // bits 0-15 +#else + u32 reserved:16; // bit 0-15 + u32 Octet1:8; // bits 16-23 + u32 Octet2:8; // bits 24-31 +#endif + } bits; +} MAC_STATION_ADDR2_t, *PMAC_STATION_ADDR2_t; + +/* + * MAC Module of JAGCore Address Mapping + */ +typedef struct _MAC_t { // Location: + MAC_CFG1_t cfg1; // 0x5000 + MAC_CFG2_t cfg2; // 0x5004 + MAC_IPG_t ipg; // 0x5008 + MAC_HFDP_t hfdp; // 0x500C + MAC_MAX_FM_LEN_t max_fm_len; // 0x5010 + u32 rsv1; // 0x5014 + u32 rsv2; // 0x5018 + MAC_TEST_t mac_test; // 0x501C + MII_MGMT_CFG_t mii_mgmt_cfg; // 0x5020 + MII_MGMT_CMD_t mii_mgmt_cmd; // 0x5024 + MII_MGMT_ADDR_t mii_mgmt_addr; // 0x5028 + MII_MGMT_CTRL_t mii_mgmt_ctrl; // 0x502C + MII_MGMT_STAT_t mii_mgmt_stat; // 0x5030 + MII_MGMT_INDICATOR_t mii_mgmt_indicator; // 0x5034 + MAC_IF_CTRL_t if_ctrl; // 0x5038 + MAC_IF_STAT_t if_stat; // 0x503C + MAC_STATION_ADDR1_t station_addr_1; // 0x5040 + MAC_STATION_ADDR2_t station_addr_2; // 0x5044 +} MAC_t, *PMAC_t; + +/* END OF MAC REGISTER ADDRESS MAP */ + +/* START OF MAC STAT REGISTER ADDRESS MAP */ + +/* + * structure for Carry Register One and it's Mask Register reg located in mac + * stat address map address 0x6130 and 0x6138. + */ +typedef union _MAC_STAT_REG_1_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 tr64:1; // bit 31 + u32 tr127:1; // bit 30 + u32 tr255:1; // bit 29 + u32 tr511:1; // bit 28 + u32 tr1k:1; // bit 27 + u32 trmax:1; // bit 26 + u32 trmgv:1; // bit 25 + u32 unused:8; // bits 17-24 + u32 rbyt:1; // bit 16 + u32 rpkt:1; // bit 15 + u32 rfcs:1; // bit 14 + u32 rmca:1; // bit 13 + u32 rbca:1; // bit 12 + u32 rxcf:1; // bit 11 + u32 rxpf:1; // bit 10 + u32 rxuo:1; // bit 9 + u32 raln:1; // bit 8 + u32 rflr:1; // bit 7 + u32 rcde:1; // bit 6 + u32 rcse:1; // bit 5 + u32 rund:1; // bit 4 + u32 rovr:1; // bit 3 + u32 rfrg:1; // bit 2 + u32 rjbr:1; // bit 1 + u32 rdrp:1; // bit 0 +#else + u32 rdrp:1; // bit 0 + u32 rjbr:1; // bit 1 + u32 rfrg:1; // bit 2 + u32 rovr:1; // bit 3 + u32 rund:1; // bit 4 + u32 rcse:1; // bit 5 + u32 rcde:1; // bit 6 + u32 rflr:1; // bit 7 + u32 raln:1; // bit 8 + u32 rxuo:1; // bit 9 + u32 rxpf:1; // bit 10 + u32 rxcf:1; // bit 11 + u32 rbca:1; // bit 12 + u32 rmca:1; // bit 13 + u32 rfcs:1; // bit 14 + u32 rpkt:1; // bit 15 + u32 rbyt:1; // bit 16 + u32 unused:8; // bits 17-24 + u32 trmgv:1; // bit 25 + u32 trmax:1; // bit 26 + u32 tr1k:1; // bit 27 + u32 tr511:1; // bit 28 + u32 tr255:1; // bit 29 + u32 tr127:1; // bit 30 + u32 tr64:1; // bit 31 +#endif + } bits; +} MAC_STAT_REG_1_t, *PMAC_STAT_REG_1_t; + +/* + * structure for Carry Register Two Mask Register reg in mac stat address map. + * located at address 0x613C + */ +typedef union _MAC_STAT_REG_2_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused:12; // bit 20-31 + u32 tjbr:1; // bit 19 + u32 tfcs:1; // bit 18 + u32 txcf:1; // bit 17 + u32 tovr:1; // bit 16 + u32 tund:1; // bit 15 + u32 tfrg:1; // bit 14 + u32 tbyt:1; // bit 13 + u32 tpkt:1; // bit 12 + u32 tmca:1; // bit 11 + u32 tbca:1; // bit 10 + u32 txpf:1; // bit 9 + u32 tdfr:1; // bit 8 + u32 tedf:1; // bit 7 + u32 tscl:1; // bit 6 + u32 tmcl:1; // bit 5 + u32 tlcl:1; // bit 4 + u32 txcl:1; // bit 3 + u32 tncl:1; // bit 2 + u32 tpfh:1; // bit 1 + u32 tdrp:1; // bit 0 +#else + u32 tdrp:1; // bit 0 + u32 tpfh:1; // bit 1 + u32 tncl:1; // bit 2 + u32 txcl:1; // bit 3 + u32 tlcl:1; // bit 4 + u32 tmcl:1; // bit 5 + u32 tscl:1; // bit 6 + u32 tedf:1; // bit 7 + u32 tdfr:1; // bit 8 + u32 txpf:1; // bit 9 + u32 tbca:1; // bit 10 + u32 tmca:1; // bit 11 + u32 tpkt:1; // bit 12 + u32 tbyt:1; // bit 13 + u32 tfrg:1; // bit 14 + u32 tund:1; // bit 15 + u32 tovr:1; // bit 16 + u32 txcf:1; // bit 17 + u32 tfcs:1; // bit 18 + u32 tjbr:1; // bit 19 + u32 unused:12; // bit 20-31 +#endif + } bits; +} MAC_STAT_REG_2_t, *PMAC_STAT_REG_2_t; + +/* + * MAC STATS Module of JAGCore Address Mapping + */ +typedef struct _MAC_STAT_t { // Location: + u32 pad[32]; // 0x6000 - 607C + + // Tx/Rx 0-64 Byte Frame Counter + u32 TR64; // 0x6080 + + // Tx/Rx 65-127 Byte Frame Counter + u32 TR127; // 0x6084 + + // Tx/Rx 128-255 Byte Frame Counter + u32 TR255; // 0x6088 + + // Tx/Rx 256-511 Byte Frame Counter + u32 TR511; // 0x608C + + // Tx/Rx 512-1023 Byte Frame Counter + u32 TR1K; // 0x6090 + + // Tx/Rx 1024-1518 Byte Frame Counter + u32 TRMax; // 0x6094 + + // Tx/Rx 1519-1522 Byte Good VLAN Frame Count + u32 TRMgv; // 0x6098 + + // Rx Byte Counter + u32 RByt; // 0x609C + + // Rx Packet Counter + u32 RPkt; // 0x60A0 + + // Rx FCS Error Counter + u32 RFcs; // 0x60A4 + + // Rx Multicast Packet Counter + u32 RMca; // 0x60A8 + + // Rx Broadcast Packet Counter + u32 RBca; // 0x60AC + + // Rx Control Frame Packet Counter + u32 RxCf; // 0x60B0 + + // Rx Pause Frame Packet Counter + u32 RxPf; // 0x60B4 + + // Rx Unknown OP Code Counter + u32 RxUo; // 0x60B8 + + // Rx Alignment Error Counter + u32 RAln; // 0x60BC + + // Rx Frame Length Error Counter + u32 RFlr; // 0x60C0 + + // Rx Code Error Counter + u32 RCde; // 0x60C4 + + // Rx Carrier Sense Error Counter + u32 RCse; // 0x60C8 + + // Rx Undersize Packet Counter + u32 RUnd; // 0x60CC + + // Rx Oversize Packet Counter + u32 ROvr; // 0x60D0 + + // Rx Fragment Counter + u32 RFrg; // 0x60D4 + + // Rx Jabber Counter + u32 RJbr; // 0x60D8 + + // Rx Drop + u32 RDrp; // 0x60DC + + // Tx Byte Counter + u32 TByt; // 0x60E0 + + // Tx Packet Counter + u32 TPkt; // 0x60E4 + + // Tx Multicast Packet Counter + u32 TMca; // 0x60E8 + + // Tx Broadcast Packet Counter + u32 TBca; // 0x60EC + + // Tx Pause Control Frame Counter + u32 TxPf; // 0x60F0 + + // Tx Deferral Packet Counter + u32 TDfr; // 0x60F4 + + // Tx Excessive Deferral Packet Counter + u32 TEdf; // 0x60F8 + + // Tx Single Collision Packet Counter + u32 TScl; // 0x60FC + + // Tx Multiple Collision Packet Counter + u32 TMcl; // 0x6100 + + // Tx Late Collision Packet Counter + u32 TLcl; // 0x6104 + + // Tx Excessive Collision Packet Counter + u32 TXcl; // 0x6108 + + // Tx Total Collision Packet Counter + u32 TNcl; // 0x610C + + // Tx Pause Frame Honored Counter + u32 TPfh; // 0x6110 + + // Tx Drop Frame Counter + u32 TDrp; // 0x6114 + + // Tx Jabber Frame Counter + u32 TJbr; // 0x6118 + + // Tx FCS Error Counter + u32 TFcs; // 0x611C + + // Tx Control Frame Counter + u32 TxCf; // 0x6120 + + // Tx Oversize Frame Counter + u32 TOvr; // 0x6124 + + // Tx Undersize Frame Counter + u32 TUnd; // 0x6128 + + // Tx Fragments Frame Counter + u32 TFrg; // 0x612C + + // Carry Register One Register + MAC_STAT_REG_1_t Carry1; // 0x6130 + + // Carry Register Two Register + MAC_STAT_REG_2_t Carry2; // 0x6134 + + // Carry Register One Mask Register + MAC_STAT_REG_1_t Carry1M; // 0x6138 + + // Carry Register Two Mask Register + MAC_STAT_REG_2_t Carry2M; // 0x613C +} MAC_STAT_t, *PMAC_STAT_t; + +/* END OF MAC STAT REGISTER ADDRESS MAP */ + + +/* START OF MMC REGISTER ADDRESS MAP */ + +/* + * structure for Main Memory Controller Control reg in mmc address map. + * located at address 0x7000 + */ +typedef union _MMC_CTRL_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 reserved:25; // bits 7-31 + u32 force_ce:1; // bit 6 + u32 rxdma_disable:1; // bit 5 + u32 txdma_disable:1; // bit 4 + u32 txmac_disable:1; // bit 3 + u32 rxmac_disable:1; // bit 2 + u32 arb_disable:1; // bit 1 + u32 mmc_enable:1; // bit 0 +#else + u32 mmc_enable:1; // bit 0 + u32 arb_disable:1; // bit 1 + u32 rxmac_disable:1; // bit 2 + u32 txmac_disable:1; // bit 3 + u32 txdma_disable:1; // bit 4 + u32 rxdma_disable:1; // bit 5 + u32 force_ce:1; // bit 6 + u32 reserved:25; // bits 7-31 +#endif + } bits; +} MMC_CTRL_t, *PMMC_CTRL_t; + +/* + * structure for Main Memory Controller Host Memory Access Address reg in mmc + * address map. Located at address 0x7004 + */ +typedef union _MMC_SRAM_ACCESS_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 byte_enable:16; // bits 16-31 + u32 reserved2:2; // bits 14-15 + u32 req_addr:10; // bits 4-13 + u32 reserved1:1; // bit 3 + u32 is_ctrl_word:1; // bit 2 + u32 wr_access:1; // bit 1 + u32 req_access:1; // bit 0 +#else + u32 req_access:1; // bit 0 + u32 wr_access:1; // bit 1 + u32 is_ctrl_word:1; // bit 2 + u32 reserved1:1; // bit 3 + u32 req_addr:10; // bits 4-13 + u32 reserved2:2; // bits 14-15 + u32 byte_enable:16; // bits 16-31 +#endif + } bits; +} MMC_SRAM_ACCESS_t, *PMMC_SRAM_ACCESS_t; + +/* + * structure for Main Memory Controller Host Memory Access Data reg in mmc + * address map. Located at address 0x7008 - 0x7014 + * Defined earlier (u32) + */ + +/* + * Memory Control Module of JAGCore Address Mapping + */ +typedef struct _MMC_t { // Location: + MMC_CTRL_t mmc_ctrl; // 0x7000 + MMC_SRAM_ACCESS_t sram_access; // 0x7004 + u32 sram_word1; // 0x7008 + u32 sram_word2; // 0x700C + u32 sram_word3; // 0x7010 + u32 sram_word4; // 0x7014 +} MMC_t, *PMMC_t; + +/* END OF MMC REGISTER ADDRESS MAP */ + + +/* START OF EXP ROM REGISTER ADDRESS MAP */ + +/* + * Expansion ROM Module of JAGCore Address Mapping + */ + +/* Take this out until it is not empty */ +#if 0 +typedef struct _EXP_ROM_t { + +} EXP_ROM_t, *PEXP_ROM_t; +#endif + +/* END OF EXP ROM REGISTER ADDRESS MAP */ + + +/* + * JAGCore Address Mapping + */ +typedef struct _ADDRESS_MAP_t { + GLOBAL_t global; + // unused section of global address map + u8 unused_global[4096 - sizeof(GLOBAL_t)]; + TXDMA_t txdma; + // unused section of txdma address map + u8 unused_txdma[4096 - sizeof(TXDMA_t)]; + RXDMA_t rxdma; + // unused section of rxdma address map + u8 unused_rxdma[4096 - sizeof(RXDMA_t)]; + TXMAC_t txmac; + // unused section of txmac address map + u8 unused_txmac[4096 - sizeof(TXMAC_t)]; + RXMAC_t rxmac; + // unused section of rxmac address map + u8 unused_rxmac[4096 - sizeof(RXMAC_t)]; + MAC_t mac; + // unused section of mac address map + u8 unused_mac[4096 - sizeof(MAC_t)]; + MAC_STAT_t macStat; + // unused section of mac stat address map + u8 unused_mac_stat[4096 - sizeof(MAC_STAT_t)]; + MMC_t mmc; + // unused section of mmc address map + u8 unused_mmc[4096 - sizeof(MMC_t)]; + // unused section of address map + u8 unused_[1015808]; + +/* Take this out until it is not empty */ +#if 0 + EXP_ROM_t exp_rom; +#endif + + u8 unused_exp_rom[4096]; // MGS-size TBD + u8 unused__[524288]; // unused section of address map +} ADDRESS_MAP_t, *PADDRESS_MAP_t; + +#endif /* _ET1310_ADDRESS_MAP_H_ */ diff --git a/drivers/staging/et131x/et1310_eeprom.c b/drivers/staging/et131x/et1310_eeprom.c new file mode 100644 index 000000000000..c2b194e6a54c --- /dev/null +++ b/drivers/staging/et131x/et1310_eeprom.c @@ -0,0 +1,480 @@ +/* + * Agere Systems Inc. + * 10/100/1000 Base-T Ethernet Driver for the ET1301 and ET131x series MACs + * + * Copyright © 2005 Agere Systems Inc. + * All rights reserved. + * http://www.agere.com + * + *------------------------------------------------------------------------------ + * + * et1310_eeprom.c - Code used to access the device's EEPROM + * + *------------------------------------------------------------------------------ + * + * SOFTWARE LICENSE + * + * This software is provided subject to the following terms and conditions, + * which you should read carefully before using the software. Using this + * software indicates your acceptance of these terms and conditions. If you do + * not agree with these terms and conditions, do not use the software. + * + * Copyright © 2005 Agere Systems Inc. + * All rights reserved. + * + * Redistribution and use in source or binary forms, with or without + * modifications, are permitted provided that the following conditions are met: + * + * . Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following Disclaimer as comments in the code as + * well as in the documentation and/or other materials provided with the + * distribution. + * + * . Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following Disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * . Neither the name of Agere Systems Inc. nor the names of the contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * Disclaimer + * + * THIS SOFTWARE IS PROVIDED “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, INFRINGEMENT AND THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ANY + * USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE IS SOLELY AT THE USERS OWN + * RISK. IN NO EVENT SHALL AGERE SYSTEMS INC. OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, INCLUDING, BUT NOT LIMITED TO, CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + */ + +#include "et131x_version.h" +#include "et131x_debug.h" +#include "et131x_defs.h" + +#include <linux/pci.h> +#include <linux/init.h> +#include <linux/module.h> +#include <linux/types.h> +#include <linux/kernel.h> + +#include <linux/sched.h> +#include <linux/ptrace.h> +#include <linux/slab.h> +#include <linux/ctype.h> +#include <linux/string.h> +#include <linux/timer.h> +#include <linux/interrupt.h> +#include <linux/in.h> +#include <linux/delay.h> +#include <asm/io.h> +#include <asm/system.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 "et1310_phy.h" +#include "et1310_pm.h" +#include "et1310_jagcore.h" +#include "et1310_eeprom.h" + +#include "et131x_adapter.h" +#include "et131x_initpci.h" +#include "et131x_isr.h" + +#include "et1310_tx.h" + + +/* + * EEPROM Defines + */ + +/* LBCIF Register Groups (addressed via 32-bit offsets) */ +#define LBCIF_DWORD0_GROUP_OFFSET 0xAC +#define LBCIF_DWORD1_GROUP_OFFSET 0xB0 + +/* LBCIF Registers (addressed via 8-bit offsets) */ +#define LBCIF_ADDRESS_REGISTER_OFFSET 0xAC +#define LBCIF_DATA_REGISTER_OFFSET 0xB0 +#define LBCIF_CONTROL_REGISTER_OFFSET 0xB1 +#define LBCIF_STATUS_REGISTER_OFFSET 0xB2 + +/* LBCIF Control Register Bits */ +#define LBCIF_CONTROL_SEQUENTIAL_READ 0x01 +#define LBCIF_CONTROL_PAGE_WRITE 0x02 +#define LBCIF_CONTROL_UNUSED1 0x04 +#define LBCIF_CONTROL_EEPROM_RELOAD 0x08 +#define LBCIF_CONTROL_UNUSED2 0x10 +#define LBCIF_CONTROL_TWO_BYTE_ADDR 0x20 +#define LBCIF_CONTROL_I2C_WRITE 0x40 +#define LBCIF_CONTROL_LBCIF_ENABLE 0x80 + +/* LBCIF Status Register Bits */ +#define LBCIF_STATUS_PHY_QUEUE_AVAIL 0x01 +#define LBCIF_STATUS_I2C_IDLE 0x02 +#define LBCIF_STATUS_ACK_ERROR 0x04 +#define LBCIF_STATUS_GENERAL_ERROR 0x08 +#define LBCIF_STATUS_UNUSED 0x30 +#define LBCIF_STATUS_CHECKSUM_ERROR 0x40 +#define LBCIF_STATUS_EEPROM_PRESENT 0x80 + +/* Miscellaneous Constraints */ +#define MAX_NUM_REGISTER_POLLS 1000 +#define MAX_NUM_WRITE_RETRIES 2 + +/* + * Define macros that allow individual register values to be extracted from a + * DWORD1 register grouping + */ +#define EXTRACT_DATA_REGISTER(x) (uint8_t)(x & 0xFF) +#define EXTRACT_STATUS_REGISTER(x) (uint8_t)((x >> 16) & 0xFF) +#define EXTRACT_CONTROL_REG(x) (uint8_t)((x >> 8) & 0xFF) + +/** + * EepromWriteByte - Write a byte to the ET1310's EEPROM + * @pAdapter: pointer to our private adapter structure + * @unAddress: the address to write + * @bData: the value to write + * @unEepronId: the ID of the EEPROM + * @unAddressingMode: how the EEPROM is to be accessed + * + * Returns SUCCESS or FAILURE + */ +int32_t EepromWriteByte(struct et131x_adapter *pAdapter, uint32_t unAddress, + uint8_t bData, uint32_t unEepromId, + uint32_t unAddressingMode) +{ + struct pci_dev *pdev = pAdapter->pdev; + int32_t nIndex; + int32_t nRetries; + int32_t nError = false; + int32_t nI2CWriteActive = 0; + int32_t nWriteSuccessful = 0; + uint8_t bControl; + uint8_t bStatus = 0; + uint32_t unDword1 = 0; + uint32_t unData = 0; + + /* + * The following excerpt is from "Serial EEPROM HW Design + * Specification" Version 0.92 (9/20/2004): + * + * Single Byte Writes + * + * For an EEPROM, an I2C single byte write is defined as a START + * condition followed by the device address, EEPROM address, one byte + * of data and a STOP condition. The STOP condition will trigger the + * EEPROM's internally timed write cycle to the nonvolatile memory. + * All inputs are disabled during this write cycle and the EEPROM will + * not respond to any access until the internal write is complete. + * The steps to execute a single byte write are as follows: + * + * 1. Check LBCIF Status Register for bits 6 & 3:2 all equal to 0 and + * bits 7,1:0 both equal to 1, at least once after reset. + * Subsequent operations need only to check that bits 1:0 are + * equal to 1 prior to starting a single byte write. + * + * 2. Write to the LBCIF Control Register: bit 7=1, bit 6=1, bit 3=0, + * and bits 1:0 both =0. Bit 5 should be set according to the + * type of EEPROM being accessed (1=two byte addressing, 0=one + * byte addressing). + * + * 3. Write the address to the LBCIF Address Register. + * + * 4. Write the data to the LBCIF Data Register (the I2C write will + * begin). + * + * 5. Monitor bit 1:0 of the LBCIF Status Register. When bits 1:0 are + * both equal to 1, the I2C write has completed and the internal + * write cycle of the EEPROM is about to start. (bits 1:0 = 01 is + * a legal state while waiting from both equal to 1, but bits + * 1:0 = 10 is invalid and implies that something is broken). + * + * 6. Check bit 3 of the LBCIF Status Register. If equal to 1, an + * error has occurred. + * + * 7. Check bit 2 of the LBCIF Status Register. If equal to 1 an ACK + * error has occurred on the address phase of the write. This + * could be due to an actual hardware failure or the EEPROM may + * still be in its internal write cycle from a previous write. + * This write operation was ignored and must be repeated later. + * + * 8. Set bit 6 of the LBCIF Control Register = 0. If another write is + * required, go to step 1. + */ + + /* Step 1: */ + for (nIndex = 0; nIndex < MAX_NUM_REGISTER_POLLS; nIndex++) { + /* Read registers grouped in DWORD1 */ + if (pci_read_config_dword(pdev, LBCIF_DWORD1_GROUP_OFFSET, + &unDword1)) { + nError = 1; + break; + } + + bStatus = EXTRACT_STATUS_REGISTER(unDword1); + + if (bStatus & LBCIF_STATUS_PHY_QUEUE_AVAIL && + bStatus & LBCIF_STATUS_I2C_IDLE) { + /* bits 1:0 are equal to 1 */ + break; + } + } + + if (nError || (nIndex >= MAX_NUM_REGISTER_POLLS)) { + return FAILURE; + } + + /* Step 2: */ + bControl = 0; + bControl |= LBCIF_CONTROL_LBCIF_ENABLE | LBCIF_CONTROL_I2C_WRITE; + + if (unAddressingMode == DUAL_BYTE) { + bControl |= LBCIF_CONTROL_TWO_BYTE_ADDR; + } + + if (pci_write_config_byte(pdev, LBCIF_CONTROL_REGISTER_OFFSET, + bControl)) { + return FAILURE; + } + + nI2CWriteActive = 1; + + /* Prepare EEPROM address for Step 3 */ + unAddress |= (unAddressingMode == DUAL_BYTE) ? + (unEepromId << 16) : (unEepromId << 8); + + for (nRetries = 0; nRetries < MAX_NUM_WRITE_RETRIES; nRetries++) { + /* Step 3:*/ + if (pci_write_config_dword(pdev, LBCIF_ADDRESS_REGISTER_OFFSET, + unAddress)) { + break; + } + + /* Step 4: */ + if (pci_write_config_byte(pdev, LBCIF_DATA_REGISTER_OFFSET, + bData)) { + break; + } + + /* Step 5: */ + for (nIndex = 0; nIndex < MAX_NUM_REGISTER_POLLS; nIndex++) { + /* Read registers grouped in DWORD1 */ + if (pci_read_config_dword(pdev, + LBCIF_DWORD1_GROUP_OFFSET, + &unDword1)) { + nError = 1; + break; + } + + bStatus = EXTRACT_STATUS_REGISTER(unDword1); + + if (bStatus & LBCIF_STATUS_PHY_QUEUE_AVAIL && + bStatus & LBCIF_STATUS_I2C_IDLE) { + /* I2C write complete */ + break; + } + } + + if (nError || (nIndex >= MAX_NUM_REGISTER_POLLS)) { + break; + } + + /* + * Step 6: Don't break here if we are revision 1, this is + * so we do a blind write for load bug. + */ + if (bStatus & LBCIF_STATUS_GENERAL_ERROR + && pAdapter->RevisionID == 0) { + break; + } + + /* Step 7 */ + if (bStatus & LBCIF_STATUS_ACK_ERROR) { + /* + * This could be due to an actual hardware failure + * or the EEPROM may still be in its internal write + * cycle from a previous write. This write operation + * was ignored and must be repeated later. + */ + udelay(10); + continue; + } + + nWriteSuccessful = 1; + break; + } + + /* Step 8: */ + udelay(10); + nIndex = 0; + while (nI2CWriteActive) { + bControl &= ~LBCIF_CONTROL_I2C_WRITE; + + if (pci_write_config_byte(pdev, LBCIF_CONTROL_REGISTER_OFFSET, + bControl)) { + nWriteSuccessful = 0; + } + + /* Do read until internal ACK_ERROR goes away meaning write + * completed + */ + do { + pci_write_config_dword(pdev, + LBCIF_ADDRESS_REGISTER_OFFSET, + unAddress); + do { + pci_read_config_dword(pdev, + LBCIF_DATA_REGISTER_OFFSET, &unData); + } while ((unData & 0x00010000) == 0); + } while (unData & 0x00040000); + + bControl = EXTRACT_CONTROL_REG(unData); + + if (bControl != 0xC0 || nIndex == 10000) { + break; + } + + nIndex++; + } + + return nWriteSuccessful ? SUCCESS : FAILURE; +} + +/** + * EepromReadByte - Read a byte from the ET1310's EEPROM + * @pAdapter: pointer to our private adapter structure + * @unAddress: the address from which to read + * @pbData: a pointer to a byte in which to store the value of the read + * @unEepronId: the ID of the EEPROM + * @unAddressingMode: how the EEPROM is to be accessed + * + * Returns SUCCESS or FAILURE + */ +int32_t EepromReadByte(struct et131x_adapter *pAdapter, uint32_t unAddress, + uint8_t *pbData, uint32_t unEepromId, + uint32_t unAddressingMode) +{ + struct pci_dev *pdev = pAdapter->pdev; + int32_t nIndex; + int32_t nError = 0; + uint8_t bControl; + uint8_t bStatus = 0; + uint32_t unDword1 = 0; + + /* + * The following excerpt is from "Serial EEPROM HW Design + * Specification" Version 0.92 (9/20/2004): + * + * Single Byte Reads + * + * A single byte read is similar to the single byte write, with the + * exception of the data flow: + * + * 1. Check LBCIF Status Register for bits 6 & 3:2 all equal to 0 and + * bits 7,1:0 both equal to 1, at least once after reset. + * Subsequent operations need only to check that bits 1:0 are equal + * to 1 prior to starting a single byte read. + * + * 2. Write to the LBCIF Control Register: bit 7=1, bit 6=0, bit 3=0, + * and bits 1:0 both =0. Bit 5 should be set according to the type + * of EEPROM being accessed (1=two byte addressing, 0=one byte + * addressing). + * + * 3. Write the address to the LBCIF Address Register (I2C read will + * begin). + * + * 4. Monitor bit 0 of the LBCIF Status Register. When =1, I2C read + * is complete. (if bit 1 =1 and bit 0 stays =0, a hardware failure + * has occurred). + * + * 5. Check bit 2 of the LBCIF Status Register. If =1, then an error + * has occurred. The data that has been returned from the PHY may + * be invalid. + * + * 6. Regardless of error status, read data byte from LBCIF Data + * Register. If another byte is required, go to step 1. + */ + + /* Step 1: */ + for (nIndex = 0; nIndex < MAX_NUM_REGISTER_POLLS; nIndex++) { + /* Read registers grouped in DWORD1 */ + if (pci_read_config_dword(pdev, LBCIF_DWORD1_GROUP_OFFSET, + &unDword1)) { + nError = 1; + break; + } + + bStatus = EXTRACT_STATUS_REGISTER(unDword1); + + if (bStatus & LBCIF_STATUS_PHY_QUEUE_AVAIL && + bStatus & LBCIF_STATUS_I2C_IDLE) { + /* bits 1:0 are equal to 1 */ + break; + } + } + + if (nError || (nIndex >= MAX_NUM_REGISTER_POLLS)) { + return FAILURE; + } + + /* Step 2: */ + bControl = 0; + bControl |= LBCIF_CONTROL_LBCIF_ENABLE; + + if (unAddressingMode == DUAL_BYTE) { + bControl |= LBCIF_CONTROL_TWO_BYTE_ADDR; + } + + if (pci_write_config_byte(pdev, LBCIF_CONTROL_REGISTER_OFFSET, + bControl)) { + return FAILURE; + } + + /* Step 3: */ + unAddress |= (unAddressingMode == DUAL_BYTE) ? + (unEepromId << 16) : (unEepromId << 8); + + if (pci_write_config_dword(pdev, LBCIF_ADDRESS_REGISTER_OFFSET, + unAddress)) { + return FAILURE; + } + + /* Step 4: */ + for (nIndex = 0; nIndex < MAX_NUM_REGISTER_POLLS; nIndex++) { + /* Read registers grouped in DWORD1 */ + if (pci_read_config_dword(pdev, LBCIF_DWORD1_GROUP_OFFSET, + &unDword1)) { + nError = 1; + break; + } + + bStatus = EXTRACT_STATUS_REGISTER(unDword1); + + if (bStatus & LBCIF_STATUS_PHY_QUEUE_AVAIL + && bStatus & LBCIF_STATUS_I2C_IDLE) { + /* I2C read complete */ + break; + } + } + + if (nError || (nIndex >= MAX_NUM_REGISTER_POLLS)) { + return FAILURE; + } + + /* Step 6: */ + *pbData = EXTRACT_DATA_REGISTER(unDword1); + + return (bStatus & LBCIF_STATUS_ACK_ERROR) ? FAILURE : SUCCESS; +} diff --git a/drivers/staging/et131x/et1310_eeprom.h b/drivers/staging/et131x/et1310_eeprom.h new file mode 100644 index 000000000000..9b6f8ad77b49 --- /dev/null +++ b/drivers/staging/et131x/et1310_eeprom.h @@ -0,0 +1,89 @@ +/* + * Agere Systems Inc. + * 10/100/1000 Base-T Ethernet Driver for the ET1301 and ET131x series MACs + * + * Copyright © 2005 Agere Systems Inc. + * All rights reserved. + * http://www.agere.com + * + *------------------------------------------------------------------------------ + * + * et1310_eeprom.h - Defines, structs, enums, prototypes, etc. used for EEPROM + * access routines + * + *------------------------------------------------------------------------------ + * + * SOFTWARE LICENSE + * + * This software is provided subject to the following terms and conditions, + * which you should read carefully before using the software. Using this + * software indicates your acceptance of these terms and conditions. If you do + * not agree with these terms and conditions, do not use the software. + * + * Copyright © 2005 Agere Systems Inc. + * All rights reserved. + * + * Redistribution and use in source or binary forms, with or without + * modifications, are permitted provided that the following conditions are met: + * + * . Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following Disclaimer as comments in the code as + * well as in the documentation and/or other materials provided with the + * distribution. + * + * . Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following Disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * . Neither the name of Agere Systems Inc. nor the names of the contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * Disclaimer + * + * THIS SOFTWARE IS PROVIDED “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, INFRINGEMENT AND THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ANY + * USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE IS SOLELY AT THE USERS OWN + * RISK. IN NO EVENT SHALL AGERE SYSTEMS INC. OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, INCLUDING, BUT NOT LIMITED TO, CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + */ + +#ifndef __ET1310_EEPROM_H__ +#define __ET1310_EEPROM_H__ + +#include "et1310_address_map.h" + +#ifndef SUCCESS +#define SUCCESS 0 +#define FAILURE 1 +#endif + +#ifndef READ +#define READ 0 +#define WRITE 1 +#endif + +#ifndef SINGLE_BYTE +#define SINGLE_BYTE 0 +#define DUAL_BYTE 1 +#endif + +/* Forward declaration of the private adapter structure */ +struct et131x_adapter; + +int32_t EepromWriteByte(struct et131x_adapter *adapter, u32 unAddress, + u8 bData, u32 unEepromId, + u32 unAddressingMode); +int32_t EepromReadByte(struct et131x_adapter *adapter, u32 unAddress, + u8 *pbData, u32 unEepromId, + u32 unAddressingMode); + +#endif /* _ET1310_EEPROM_H_ */ diff --git a/drivers/staging/et131x/et1310_jagcore.c b/drivers/staging/et131x/et1310_jagcore.c new file mode 100644 index 000000000000..993b30ea71e2 --- /dev/null +++ b/drivers/staging/et131x/et1310_jagcore.c @@ -0,0 +1,220 @@ +/* + * Agere Systems Inc. + * 10/100/1000 Base-T Ethernet Driver for the ET1301 and ET131x series MACs + * + * Copyright © 2005 Agere Systems Inc. + * All rights reserved. + * http://www.agere.com + * + *------------------------------------------------------------------------------ + * + * et1310_jagcore.c - All code pertaining to the ET1301/ET131x's JAGcore + * + *------------------------------------------------------------------------------ + * + * SOFTWARE LICENSE + * + * This software is provided subject to the following terms and conditions, + * which you should read carefully before using the software. Using this + * software indicates your acceptance of these terms and conditions. If you do + * not agree with these terms and conditions, do not use the software. + * + * Copyright © 2005 Agere Systems Inc. + * All rights reserved. + * + * Redistribution and use in source or binary forms, with or without + * modifications, are permitted provided that the following conditions are met: + * + * . Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following Disclaimer as comments in the code as + * well as in the documentation and/or other materials provided with the + * distribution. + * + * . Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following Disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * . Neither the name of Agere Systems Inc. nor the names of the contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * Disclaimer + * + * THIS SOFTWARE IS PROVIDED “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, INFRINGEMENT AND THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ANY + * USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE IS SOLELY AT THE USERS OWN + * RISK. IN NO EVENT SHALL AGERE SYSTEMS INC. OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, INCLUDING, BUT NOT LIMITED TO, CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + */ + +#include "et131x_version.h" +#include "et131x_debug.h" +#include "et131x_defs.h" + +#include <linux/init.h> +#include <linux/module.h> +#include <linux/types.h> +#include <linux/kernel.h> + +#include <linux/sched.h> +#include <linux/ptrace.h> +#include <linux/slab.h> +#include <linux/ctype.h> +#include <linux/string.h> +#include <linux/timer.h> +#include <linux/interrupt.h> +#include <linux/in.h> +#include <linux/delay.h> +#include <asm/io.h> +#include <asm/system.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 "et1310_phy.h" +#include "et1310_pm.h" +#include "et1310_jagcore.h" + +#include "et131x_adapter.h" +#include "et131x_initpci.h" + +/* Data for debugging facilities */ +#ifdef CONFIG_ET131X_DEBUG +extern dbg_info_t *et131x_dbginfo; +#endif /* CONFIG_ET131X_DEBUG */ + +/** + * ConfigGlobalRegs - Used to configure the global registers on the JAGCore + * @pAdpater: pointer to our adapter structure + */ +void ConfigGlobalRegs(struct et131x_adapter *pAdapter) +{ + struct _GLOBAL_t __iomem *pGbl = &pAdapter->CSRAddress->global; + + DBG_ENTER(et131x_dbginfo); + + if (pAdapter->RegistryPhyLoopbk == false) { + if (pAdapter->RegistryJumboPacket < 2048) { + /* Tx / RxDMA and Tx/Rx MAC interfaces have a 1k word + * block of RAM that the driver can split between Tx + * and Rx as it desires. Our default is to split it + * 50/50: + */ + writel(0, &pGbl->rxq_start_addr.value); + writel(pAdapter->RegistryRxMemEnd, + &pGbl->rxq_end_addr.value); + writel(pAdapter->RegistryRxMemEnd + 1, + &pGbl->txq_start_addr.value); + writel(INTERNAL_MEM_SIZE - 1, + &pGbl->txq_end_addr.value); + } else if (pAdapter->RegistryJumboPacket < 8192) { + /* For jumbo packets > 2k but < 8k, split 50-50. */ + writel(0, &pGbl->rxq_start_addr.value); + writel(INTERNAL_MEM_RX_OFFSET, + &pGbl->rxq_end_addr.value); + writel(INTERNAL_MEM_RX_OFFSET + 1, + &pGbl->txq_start_addr.value); + writel(INTERNAL_MEM_SIZE - 1, + &pGbl->txq_end_addr.value); + } else { + /* 9216 is the only packet size greater than 8k that + * is available. The Tx buffer has to be big enough + * for one whole packet on the Tx side. We'll make + * the Tx 9408, and give the rest to Rx + */ + writel(0x0000, &pGbl->rxq_start_addr.value); + writel(0x01b3, &pGbl->rxq_end_addr.value); + writel(0x01b4, &pGbl->txq_start_addr.value); + writel(INTERNAL_MEM_SIZE - 1, + &pGbl->txq_end_addr.value); + } + + /* Initialize the loopback register. Disable all loopbacks. */ + writel(0, &pGbl->loopback.value); + } else { + /* For PHY Line loopback, the memory is configured as if Tx + * and Rx both have all the memory. This is because the + * RxMAC will write data into the space, and the TxMAC will + * read it out. + */ + writel(0, &pGbl->rxq_start_addr.value); + writel(INTERNAL_MEM_SIZE - 1, &pGbl->rxq_end_addr.value); + writel(0, &pGbl->txq_start_addr.value); + writel(INTERNAL_MEM_SIZE - 1, &pGbl->txq_end_addr.value); + + /* Initialize the loopback register (MAC loopback). */ + writel(1, &pGbl->loopback.value); + } + + /* MSI Register */ + writel(0, &pGbl->msi_config.value); + + /* By default, disable the watchdog timer. It will be enabled when + * a packet is queued. + */ + writel(0, &pGbl->watchdog_timer); + + DBG_LEAVE(et131x_dbginfo); +} + +/** + * ConfigMMCRegs - Used to configure the main memory registers in the JAGCore + * @pAdapter: pointer to our adapter structure + */ +void ConfigMMCRegs(struct et131x_adapter *pAdapter) +{ + MMC_CTRL_t mmc_ctrl = { 0 }; + + DBG_ENTER(et131x_dbginfo); + + /* All we need to do is initialize the Memory Control Register */ + mmc_ctrl.bits.force_ce = 0x0; + mmc_ctrl.bits.rxdma_disable = 0x0; + mmc_ctrl.bits.txdma_disable = 0x0; + mmc_ctrl.bits.txmac_disable = 0x0; + mmc_ctrl.bits.rxmac_disable = 0x0; + mmc_ctrl.bits.arb_disable = 0x0; + mmc_ctrl.bits.mmc_enable = 0x1; + + writel(mmc_ctrl.value, &pAdapter->CSRAddress->mmc.mmc_ctrl.value); + + DBG_LEAVE(et131x_dbginfo); +} + +void et131x_enable_interrupts(struct et131x_adapter *adapter) +{ + uint32_t MaskValue; + + /* Enable all global interrupts */ + if ((adapter->FlowControl == TxOnly) || (adapter->FlowControl == Both)) { + MaskValue = INT_MASK_ENABLE; + } else { + MaskValue = INT_MASK_ENABLE_NO_FLOW; + } + + if (adapter->DriverNoPhyAccess) { + MaskValue |= 0x10000; + } + + adapter->CachedMaskValue.value = MaskValue; + writel(MaskValue, &adapter->CSRAddress->global.int_mask.value); +} + +void et131x_disable_interrupts(struct et131x_adapter * adapter) +{ + /* Disable all global interrupts */ + adapter->CachedMaskValue.value = INT_MASK_DISABLE; + writel(INT_MASK_DISABLE, &adapter->CSRAddress->global.int_mask.value); +} diff --git a/drivers/staging/et131x/et1310_jagcore.h b/drivers/staging/et131x/et1310_jagcore.h new file mode 100644 index 000000000000..9fc829336df1 --- /dev/null +++ b/drivers/staging/et131x/et1310_jagcore.h @@ -0,0 +1,112 @@ +/* + * Agere Systems Inc. + * 10/100/1000 Base-T Ethernet Driver for the ET1301 and ET131x series MACs + * + * Copyright © 2005 Agere Systems Inc. + * All rights reserved. + * http://www.agere.com + * + *------------------------------------------------------------------------------ + * + * et1310_jagcore.h - Defines, structs, enums, prototypes, etc. pertaining to + * the JAGCore + * + *------------------------------------------------------------------------------ + * + * SOFTWARE LICENSE + * + * This software is provided subject to the following terms and conditions, + * which you should read carefully before using the software. Using this + * software indicates your acceptance of these terms and conditions. If you do + * not agree with these terms and conditions, do not use the software. + * + * Copyright © 2005 Agere Systems Inc. + * All rights reserved. + * + * Redistribution and use in source or binary forms, with or without + * modifications, are permitted provided that the following conditions are met: + * + * . Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following Disclaimer as comments in the code as + * well as in the documentation and/or other materials provided with the + * distribution. + * + * . Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following Disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * . Neither the name of Agere Systems Inc. nor the names of the contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * Disclaimer + * + * THIS SOFTWARE IS PROVIDED “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, INFRINGEMENT AND THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ANY + * USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE IS SOLELY AT THE USERS OWN + * RISK. IN NO EVENT SHALL AGERE SYSTEMS INC. OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, INCLUDING, BUT NOT LIMITED TO, CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + */ + +#ifndef __ET1310_JAGCORE_H__ +#define __ET1310_JAGCORE_H__ + +#include "et1310_address_map.h" + + +#define INTERNAL_MEM_SIZE 0x400 //1024 of internal memory +#define INTERNAL_MEM_RX_OFFSET 0x1FF //50% Tx, 50% Rx + +#define REGS_MAX_ARRAY 4096 + +/* + * For interrupts, normal running is: + * rxdma_xfr_done, phy_interrupt, mac_stat_interrupt, + * watchdog_interrupt & txdma_xfer_done + * + * In both cases, when flow control is enabled for either Tx or bi-direction, + * we additional enable rx_fbr0_low and rx_fbr1_low, so we know when the + * buffer rings are running low. + */ +#define INT_MASK_DISABLE 0xffffffff + +// NOTE: Masking out MAC_STAT Interrupt for now... +//#define INT_MASK_ENABLE 0xfff6bf17 +//#define INT_MASK_ENABLE_NO_FLOW 0xfff6bfd7 +#define INT_MASK_ENABLE 0xfffebf17 +#define INT_MASK_ENABLE_NO_FLOW 0xfffebfd7 + +/* DATA STRUCTURES FOR DIRECT REGISTER ACCESS */ + +typedef struct { + u8 bReadWrite; + u32 nRegCount; + u32 nData[REGS_MAX_ARRAY]; + u32 nOffsets[REGS_MAX_ARRAY]; +} JAGCORE_ACCESS_REGS, *PJAGCORE_ACCESS_REGS; + +typedef struct { + u8 bReadWrite; + u32 nDataWidth; + u32 nRegCount; + u32 nOffsets[REGS_MAX_ARRAY]; + u32 nData[REGS_MAX_ARRAY]; +} PCI_CFG_SPACE_REGS, *PPCI_CFG_SPACE_REGS; + +/* Forward declaration of the private adapter structure */ +struct et131x_adapter; + +void ConfigGlobalRegs(struct et131x_adapter *pAdapter); +void ConfigMMCRegs(struct et131x_adapter *pAdapter); +void et131x_enable_interrupts(struct et131x_adapter *adapter); +void et131x_disable_interrupts(struct et131x_adapter *adapter); + +#endif /* __ET1310_JAGCORE_H__ */ diff --git a/drivers/staging/et131x/et1310_mac.c b/drivers/staging/et131x/et1310_mac.c new file mode 100644 index 000000000000..1924968ab24f --- /dev/null +++ b/drivers/staging/et131x/et1310_mac.c @@ -0,0 +1,792 @@ +/* + * Agere Systems Inc. + * 10/100/1000 Base-T Ethernet Driver for the ET1301 and ET131x series MACs + * + * Copyright © 2005 Agere Systems Inc. + * All rights reserved. + * http://www.agere.com + * + *------------------------------------------------------------------------------ + * + * et1310_mac.c - All code and routines pertaining to the MAC + * + *------------------------------------------------------------------------------ + * + * SOFTWARE LICENSE + * + * This software is provided subject to the following terms and conditions, + * which you should read carefully before using the software. Using this + * software indicates your acceptance of these terms and conditions. If you do + * not agree with these terms and conditions, do not use the software. + * + * Copyright © 2005 Agere Systems Inc. + * All rights reserved. + * + * Redistribution and use in source or binary forms, with or without + * modifications, are permitted provided that the following conditions are met: + * + * . Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following Disclaimer as comments in the code as + * well as in the documentation and/or other materials provided with the + * distribution. + * + * . Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following Disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * . Neither the name of Agere Systems Inc. nor the names of the contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * Disclaimer + * + * THIS SOFTWARE IS PROVIDED “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, INFRINGEMENT AND THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ANY + * USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE IS SOLELY AT THE USERS OWN + * RISK. IN NO EVENT SHALL AGERE SYSTEMS INC. OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, INCLUDING, BUT NOT LIMITED TO, CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + */ + +#include "et131x_version.h" +#include "et131x_debug.h" +#include "et131x_defs.h" + +#include <linux/init.h> +#include <linux/module.h> +#include <linux/types.h> +#include <linux/kernel.h> + +#include <linux/sched.h> +#include <linux/ptrace.h> +#include <linux/slab.h> +#include <linux/ctype.h> +#include <linux/string.h> +#include <linux/timer.h> +#include <linux/interrupt.h> +#include <linux/in.h> +#include <linux/delay.h> +#include <asm/io.h> +#include <asm/system.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/crc32.h> + +#include "et1310_phy.h" +#include "et1310_pm.h" +#include "et1310_jagcore.h" +#include "et1310_mac.h" + +#include "et131x_adapter.h" +#include "et131x_initpci.h" + +/* Data for debugging facilities */ +#ifdef CONFIG_ET131X_DEBUG +extern dbg_info_t *et131x_dbginfo; +#endif /* CONFIG_ET131X_DEBUG */ + +/** + * ConfigMacRegs1 - Initialize the first part of MAC regs + * @pAdpater: pointer to our adapter structure + */ +void ConfigMACRegs1(struct et131x_adapter *pAdapter) +{ + struct _MAC_t __iomem *pMac = &pAdapter->CSRAddress->mac; + MAC_STATION_ADDR1_t station1; + MAC_STATION_ADDR2_t station2; + MAC_IPG_t ipg; + MAC_HFDP_t hfdp; + MII_MGMT_CFG_t mii_mgmt_cfg; + + DBG_ENTER(et131x_dbginfo); + + /* First we need to reset everything. Write to MAC configuration + * register 1 to perform reset. + */ + writel(0xC00F0000, &pMac->cfg1.value); + + /* Next lets configure the MAC Inter-packet gap register */ + ipg.bits.non_B2B_ipg_1 = 0x38; // 58d + ipg.bits.non_B2B_ipg_2 = 0x58; // 88d + ipg.bits.min_ifg_enforce = 0x50; // 80d + ipg.bits.B2B_ipg = 0x60; // 96d + writel(ipg.value, &pMac->ipg.value); + + /* Next lets configure the MAC Half Duplex register */ + hfdp.bits.alt_beb_trunc = 0xA; + hfdp.bits.alt_beb_enable = 0x0; + hfdp.bits.bp_no_backoff = 0x0; + hfdp.bits.no_backoff = 0x0; + hfdp.bits.excess_defer = 0x1; + hfdp.bits.rexmit_max = 0xF; + hfdp.bits.coll_window = 0x37; // 55d + writel(hfdp.value, &pMac->hfdp.value); + + /* Next lets configure the MAC Interface Control register */ + writel(0, &pMac->if_ctrl.value); + + /* Let's move on to setting up the mii managment configuration */ + mii_mgmt_cfg.bits.reset_mii_mgmt = 0; + mii_mgmt_cfg.bits.scan_auto_incremt = 0; + mii_mgmt_cfg.bits.preamble_suppress = 0; + mii_mgmt_cfg.bits.mgmt_clk_reset = 0x7; + writel(mii_mgmt_cfg.value, &pMac->mii_mgmt_cfg.value); + + /* Next lets configure the MAC Station Address register. These + * values are read from the EEPROM during initialization and stored + * in the adapter structure. We write what is stored in the adapter + * structure to the MAC Station Address registers high and low. This + * station address is used for generating and checking pause control + * packets. + */ + station2.bits.Octet1 = pAdapter->CurrentAddress[0]; + station2.bits.Octet2 = pAdapter->CurrentAddress[1]; + station1.bits.Octet3 = pAdapter->CurrentAddress[2]; + station1.bits.Octet4 = pAdapter->CurrentAddress[3]; + station1.bits.Octet5 = pAdapter->CurrentAddress[4]; + station1.bits.Octet6 = pAdapter->CurrentAddress[5]; + writel(station1.value, &pMac->station_addr_1.value); + writel(station2.value, &pMac->station_addr_2.value); + + /* Max ethernet packet in bytes that will passed by the mac without + * being truncated. Allow the MAC to pass 4 more than our max packet + * size. This is 4 for the Ethernet CRC. + * + * Packets larger than (RegistryJumboPacket) that do not contain a + * VLAN ID will be dropped by the Rx function. + */ + writel(pAdapter->RegistryJumboPacket + 4, &pMac->max_fm_len.value); + + /* clear out MAC config reset */ + writel(0, &pMac->cfg1.value); + + DBG_LEAVE(et131x_dbginfo); +} + +/** + * ConfigMacRegs2 - Initialize the second part of MAC regs + * @pAdpater: pointer to our adapter structure + */ +void ConfigMACRegs2(struct et131x_adapter *pAdapter) +{ + int32_t delay = 0; + struct _MAC_t __iomem *pMac = &pAdapter->CSRAddress->mac; + MAC_CFG1_t cfg1; + MAC_CFG2_t cfg2; + MAC_IF_CTRL_t ifctrl; + TXMAC_CTL_t ctl; + + DBG_ENTER(et131x_dbginfo); + + ctl.value = readl(&pAdapter->CSRAddress->txmac.ctl.value); + cfg1.value = readl(&pMac->cfg1.value); + cfg2.value = readl(&pMac->cfg2.value); + ifctrl.value = readl(&pMac->if_ctrl.value); + + if (pAdapter->uiLinkSpeed == TRUEPHY_SPEED_1000MBPS) { + cfg2.bits.if_mode = 0x2; + ifctrl.bits.phy_mode = 0x0; + } else { + cfg2.bits.if_mode = 0x1; + ifctrl.bits.phy_mode = 0x1; + } + + /* We need to enable Rx/Tx */ + cfg1.bits.rx_enable = 0x1; + cfg1.bits.tx_enable = 0x1; + + /* Set up flow control */ + cfg1.bits.tx_flow = 0x1; + + if ((pAdapter->FlowControl == RxOnly) || + (pAdapter->FlowControl == Both)) { + cfg1.bits.rx_flow = 0x1; + } else { + cfg1.bits.rx_flow = 0x0; + } + + /* Initialize loop back to off */ + cfg1.bits.loop_back = 0; + + writel(cfg1.value, &pMac->cfg1.value); + + /* Now we need to initialize the MAC Configuration 2 register */ + cfg2.bits.preamble_len = 0x7; + cfg2.bits.huge_frame = 0x0; + /* LENGTH FIELD CHECKING bit4: Set this bit to cause the MAC to check + * the frame's length field to ensure it matches the actual data + * field length. Clear this bit if no length field checking is + * desired. Its default is 0. + */ + cfg2.bits.len_check = 0x1; + + if (pAdapter->RegistryPhyLoopbk == false) { + cfg2.bits.pad_crc = 0x1; + cfg2.bits.crc_enable = 0x1; + } else { + cfg2.bits.pad_crc = 0; + cfg2.bits.crc_enable = 0; + } + + /* 1 - full duplex, 0 - half-duplex */ + cfg2.bits.full_duplex = pAdapter->uiDuplexMode; + ifctrl.bits.ghd_mode = !pAdapter->uiDuplexMode; + + writel(ifctrl.value, &pMac->if_ctrl.value); + writel(cfg2.value, &pMac->cfg2.value); + + do { + udelay(10); + delay++; + cfg1.value = readl(&pMac->cfg1.value); + } while ((!cfg1.bits.syncd_rx_en || + !cfg1.bits.syncd_tx_en) && + delay < 100); + + if (delay == 100) { + DBG_ERROR(et131x_dbginfo, + "Syncd bits did not respond correctly cfg1 word 0x%08x\n", + cfg1.value); + } + + DBG_TRACE(et131x_dbginfo, + "Speed %d, Dup %d, CFG1 0x%08x, CFG2 0x%08x, if_ctrl 0x%08x\n", + pAdapter->uiLinkSpeed, pAdapter->uiDuplexMode, + readl(&pMac->cfg1.value), readl(&pMac->cfg2.value), + readl(&pMac->if_ctrl.value)); + + /* Enable TXMAC */ + ctl.bits.txmac_en = 0x1; + ctl.bits.fc_disable = 0x1; + writel(ctl.value, &pAdapter->CSRAddress->txmac.ctl.value); + + /* Ready to start the RXDMA/TXDMA engine */ + if (!MP_TEST_FLAG(pAdapter, fMP_ADAPTER_LOWER_POWER)) { + et131x_rx_dma_enable(pAdapter); + et131x_tx_dma_enable(pAdapter); + } else { + DBG_WARNING(et131x_dbginfo, + "Didn't enable Rx/Tx due to low-power mode\n"); + } + + DBG_LEAVE(et131x_dbginfo); +} + +void ConfigRxMacRegs(struct et131x_adapter *pAdapter) +{ + struct _RXMAC_t __iomem *pRxMac = &pAdapter->CSRAddress->rxmac; + RXMAC_WOL_SA_LO_t sa_lo; + RXMAC_WOL_SA_HI_t sa_hi; + RXMAC_PF_CTRL_t pf_ctrl = { 0 }; + + DBG_ENTER(et131x_dbginfo); + + /* Disable the MAC while it is being configured (also disable WOL) */ + writel(0x8, &pRxMac->ctrl.value); + + /* Initialize WOL to disabled. */ + writel(0, &pRxMac->crc0.value); + writel(0, &pRxMac->crc12.value); + writel(0, &pRxMac->crc34.value); + + /* We need to set the WOL mask0 - mask4 next. We initialize it to + * its default Values of 0x00000000 because there are not WOL masks + * as of this time. + */ + writel(0, &pRxMac->mask0_word0); + writel(0, &pRxMac->mask0_word1); + writel(0, &pRxMac->mask0_word2); + writel(0, &pRxMac->mask0_word3); + + writel(0, &pRxMac->mask1_word0); + writel(0, &pRxMac->mask1_word1); + writel(0, &pRxMac->mask1_word2); + writel(0, &pRxMac->mask1_word3); + + writel(0, &pRxMac->mask2_word0); + writel(0, &pRxMac->mask2_word1); + writel(0, &pRxMac->mask2_word2); + writel(0, &pRxMac->mask2_word3); + + writel(0, &pRxMac->mask3_word0); + writel(0, &pRxMac->mask3_word1); + writel(0, &pRxMac->mask3_word2); + writel(0, &pRxMac->mask3_word3); + + writel(0, &pRxMac->mask4_word0); + writel(0, &pRxMac->mask4_word1); + writel(0, &pRxMac->mask4_word2); + writel(0, &pRxMac->mask4_word3); + + /* Lets setup the WOL Source Address */ + sa_lo.bits.sa3 = pAdapter->CurrentAddress[2]; + sa_lo.bits.sa4 = pAdapter->CurrentAddress[3]; + sa_lo.bits.sa5 = pAdapter->CurrentAddress[4]; + sa_lo.bits.sa6 = pAdapter->CurrentAddress[5]; + writel(sa_lo.value, &pRxMac->sa_lo.value); + + sa_hi.bits.sa1 = pAdapter->CurrentAddress[0]; + sa_hi.bits.sa2 = pAdapter->CurrentAddress[1]; + writel(sa_hi.value, &pRxMac->sa_hi.value); + + /* Disable all Packet Filtering */ + writel(0, &pRxMac->pf_ctrl.value); + + /* Let's initialize the Unicast Packet filtering address */ + if (pAdapter->PacketFilter & ET131X_PACKET_TYPE_DIRECTED) { + SetupDeviceForUnicast(pAdapter); + pf_ctrl.bits.filter_uni_en = 1; + } else { + writel(0, &pRxMac->uni_pf_addr1.value); + writel(0, &pRxMac->uni_pf_addr2.value); + writel(0, &pRxMac->uni_pf_addr3.value); + } + + /* Let's initialize the Multicast hash */ + if (pAdapter->PacketFilter & ET131X_PACKET_TYPE_ALL_MULTICAST) { + pf_ctrl.bits.filter_multi_en = 0; + } else { + pf_ctrl.bits.filter_multi_en = 1; + SetupDeviceForMulticast(pAdapter); + } + + /* Runt packet filtering. Didn't work in version A silicon. */ + pf_ctrl.bits.min_pkt_size = NIC_MIN_PACKET_SIZE + 4; + pf_ctrl.bits.filter_frag_en = 1; + + if (pAdapter->RegistryJumboPacket > 8192) { + RXMAC_MCIF_CTRL_MAX_SEG_t mcif_ctrl_max_seg; + + /* In order to transmit jumbo packets greater than 8k, the + * FIFO between RxMAC and RxDMA needs to be reduced in size + * to (16k - Jumbo packet size). In order to implement this, + * we must use "cut through" mode in the RxMAC, which chops + * packets down into segments which are (max_size * 16). In + * this case we selected 256 bytes, since this is the size of + * the PCI-Express TLP's that the 1310 uses. + */ + mcif_ctrl_max_seg.bits.seg_en = 0x1; + mcif_ctrl_max_seg.bits.fc_en = 0x0; + mcif_ctrl_max_seg.bits.max_size = 0x10; + + writel(mcif_ctrl_max_seg.value, + &pRxMac->mcif_ctrl_max_seg.value); + } else { + writel(0, &pRxMac->mcif_ctrl_max_seg.value); + } + + /* Initialize the MCIF water marks */ + writel(0, &pRxMac->mcif_water_mark.value); + + /* Initialize the MIF control */ + writel(0, &pRxMac->mif_ctrl.value); + + /* Initialize the Space Available Register */ + writel(0, &pRxMac->space_avail.value); + + /* Initialize the the mif_ctrl register + * bit 3: Receive code error. One or more nibbles were signaled as + * errors during the reception of the packet. Clear this + * bit in Gigabit, set it in 100Mbit. This was derived + * experimentally at UNH. + * bit 4: Receive CRC error. The packet's CRC did not match the + * internally generated CRC. + * bit 5: Receive length check error. Indicates that frame length + * field value in the packet does not match the actual data + * byte length and is not a type field. + * bit 16: Receive frame truncated. + * bit 17: Drop packet enable + */ + if (pAdapter->uiLinkSpeed == TRUEPHY_SPEED_100MBPS) { + writel(0x30038, &pRxMac->mif_ctrl.value); + } else { + writel(0x30030, &pRxMac->mif_ctrl.value); + } + + /* Finally we initialize RxMac to be enabled & WOL disabled. Packet + * filter is always enabled since it is where the runt packets are + * supposed to be dropped. For version A silicon, runt packet + * dropping doesn't work, so it is disabled in the pf_ctrl register, + * but we still leave the packet filter on. + */ + writel(pf_ctrl.value, &pRxMac->pf_ctrl.value); + writel(0x9, &pRxMac->ctrl.value); + + DBG_LEAVE(et131x_dbginfo); +} + +void ConfigTxMacRegs(struct et131x_adapter *pAdapter) +{ + struct _TXMAC_t __iomem *pTxMac = &pAdapter->CSRAddress->txmac; + TXMAC_CF_PARAM_t Local; + + DBG_ENTER(et131x_dbginfo); + + /* We need to update the Control Frame Parameters + * cfpt - control frame pause timer set to 64 (0x40) + * cfep - control frame extended pause timer set to 0x0 + */ + if (pAdapter->FlowControl == None) { + writel(0, &pTxMac->cf_param.value); + } else { + Local.bits.cfpt = 0x40; + Local.bits.cfep = 0x0; + writel(Local.value, &pTxMac->cf_param.value); + } + + DBG_LEAVE(et131x_dbginfo); +} + +void ConfigMacStatRegs(struct et131x_adapter *pAdapter) +{ + struct _MAC_STAT_t __iomem *pDevMacStat = + &pAdapter->CSRAddress->macStat; + + DBG_ENTER(et131x_dbginfo); + + /* Next we need to initialize all the MAC_STAT registers to zero on + * the device. + */ + writel(0, &pDevMacStat->RFcs); + writel(0, &pDevMacStat->RAln); + writel(0, &pDevMacStat->RFlr); + writel(0, &pDevMacStat->RDrp); + writel(0, &pDevMacStat->RCde); + writel(0, &pDevMacStat->ROvr); + writel(0, &pDevMacStat->RFrg); + + writel(0, &pDevMacStat->TScl); + writel(0, &pDevMacStat->TDfr); + writel(0, &pDevMacStat->TMcl); + writel(0, &pDevMacStat->TLcl); + writel(0, &pDevMacStat->TNcl); + writel(0, &pDevMacStat->TOvr); + writel(0, &pDevMacStat->TUnd); + + /* Unmask any counters that we want to track the overflow of. + * Initially this will be all counters. It may become clear later + * that we do not need to track all counters. + */ + { + MAC_STAT_REG_1_t Carry1M = { 0xffffffff }; + + Carry1M.bits.rdrp = 0; + Carry1M.bits.rjbr = 1; + Carry1M.bits.rfrg = 0; + Carry1M.bits.rovr = 0; + Carry1M.bits.rund = 1; + Carry1M.bits.rcse = 1; + Carry1M.bits.rcde = 0; + Carry1M.bits.rflr = 0; + Carry1M.bits.raln = 0; + Carry1M.bits.rxuo = 1; + Carry1M.bits.rxpf = 1; + Carry1M.bits.rxcf = 1; + Carry1M.bits.rbca = 1; + Carry1M.bits.rmca = 1; + Carry1M.bits.rfcs = 0; + Carry1M.bits.rpkt = 1; + Carry1M.bits.rbyt = 1; + Carry1M.bits.trmgv = 1; + Carry1M.bits.trmax = 1; + Carry1M.bits.tr1k = 1; + Carry1M.bits.tr511 = 1; + Carry1M.bits.tr255 = 1; + Carry1M.bits.tr127 = 1; + Carry1M.bits.tr64 = 1; + + writel(Carry1M.value, &pDevMacStat->Carry1M.value); + } + + { + MAC_STAT_REG_2_t Carry2M = { 0xffffffff }; + + Carry2M.bits.tdrp = 1; + Carry2M.bits.tpfh = 1; + Carry2M.bits.tncl = 0; + Carry2M.bits.txcl = 1; + Carry2M.bits.tlcl = 0; + Carry2M.bits.tmcl = 0; + Carry2M.bits.tscl = 0; + Carry2M.bits.tedf = 1; + Carry2M.bits.tdfr = 0; + Carry2M.bits.txpf = 1; + Carry2M.bits.tbca = 1; + Carry2M.bits.tmca = 1; + Carry2M.bits.tpkt = 1; + Carry2M.bits.tbyt = 1; + Carry2M.bits.tfrg = 1; + Carry2M.bits.tund = 0; + Carry2M.bits.tovr = 0; + Carry2M.bits.txcf = 1; + Carry2M.bits.tfcs = 1; + Carry2M.bits.tjbr = 1; + + writel(Carry2M.value, &pDevMacStat->Carry2M.value); + } + + DBG_LEAVE(et131x_dbginfo); +} + +void ConfigFlowControl(struct et131x_adapter * pAdapter) +{ + if (pAdapter->uiDuplexMode == 0) { + pAdapter->FlowControl = None; + } else { + char RemotePause, RemoteAsyncPause; + + ET1310_PhyAccessMiBit(pAdapter, + TRUEPHY_BIT_READ, 5, 10, &RemotePause); + ET1310_PhyAccessMiBit(pAdapter, + TRUEPHY_BIT_READ, 5, 11, + &RemoteAsyncPause); + + if ((RemotePause == TRUEPHY_BIT_SET) && + (RemoteAsyncPause == TRUEPHY_BIT_SET)) { + pAdapter->FlowControl = pAdapter->RegistryFlowControl; + } else if ((RemotePause == TRUEPHY_BIT_SET) && + (RemoteAsyncPause == TRUEPHY_BIT_CLEAR)) { + if (pAdapter->RegistryFlowControl == Both) { + pAdapter->FlowControl = Both; + } else { + pAdapter->FlowControl = None; + } + } else if ((RemotePause == TRUEPHY_BIT_CLEAR) && + (RemoteAsyncPause == TRUEPHY_BIT_CLEAR)) { + pAdapter->FlowControl = None; + } else {/* if (RemotePause == TRUEPHY_CLEAR_BIT && + RemoteAsyncPause == TRUEPHY_SET_BIT) */ + if (pAdapter->RegistryFlowControl == Both) { + pAdapter->FlowControl = RxOnly; + } else { + pAdapter->FlowControl = None; + } + } + } +} + +/** + * UpdateMacStatHostCounters - Update the local copy of the statistics + * @pAdapter: pointer to the adapter structure + */ +void UpdateMacStatHostCounters(struct et131x_adapter *pAdapter) +{ + struct _ce_stats_t *stats = &pAdapter->Stats; + struct _MAC_STAT_t __iomem *pDevMacStat = + &pAdapter->CSRAddress->macStat; + + stats->collisions += readl(&pDevMacStat->TNcl); + stats->first_collision += readl(&pDevMacStat->TScl); + stats->tx_deferred += readl(&pDevMacStat->TDfr); + stats->excessive_collisions += readl(&pDevMacStat->TMcl); + stats->late_collisions += readl(&pDevMacStat->TLcl); + stats->tx_uflo += readl(&pDevMacStat->TUnd); + stats->max_pkt_error += readl(&pDevMacStat->TOvr); + + stats->alignment_err += readl(&pDevMacStat->RAln); + stats->crc_err += readl(&pDevMacStat->RCde); + stats->norcvbuf += readl(&pDevMacStat->RDrp); + stats->rx_ov_flow += readl(&pDevMacStat->ROvr); + stats->code_violations += readl(&pDevMacStat->RFcs); + stats->length_err += readl(&pDevMacStat->RFlr); + + stats->other_errors += readl(&pDevMacStat->RFrg); +} + +/** + * HandleMacStatInterrupt + * @pAdapter: pointer to the adapter structure + * + * One of the MACSTAT counters has wrapped. Update the local copy of + * the statistics held in the adapter structure, checking the "wrap" + * bit for each counter. + */ +void HandleMacStatInterrupt(struct et131x_adapter *pAdapter) +{ + MAC_STAT_REG_1_t Carry1; + MAC_STAT_REG_2_t Carry2; + + DBG_ENTER(et131x_dbginfo); + + /* Read the interrupt bits from the register(s). These are Clear On + * Write. + */ + Carry1.value = readl(&pAdapter->CSRAddress->macStat.Carry1.value); + Carry2.value = readl(&pAdapter->CSRAddress->macStat.Carry2.value); + + writel(Carry1.value, &pAdapter->CSRAddress->macStat.Carry1.value); + writel(Carry2.value, &pAdapter->CSRAddress->macStat.Carry2.value); + + /* We need to do update the host copy of all the MAC_STAT counters. + * For each counter, check it's overflow bit. If the overflow bit is + * set, then increment the host version of the count by one complete + * revolution of the counter. This routine is called when the counter + * block indicates that one of the counters has wrapped. + */ + if (Carry1.bits.rfcs) { + pAdapter->Stats.code_violations += COUNTER_WRAP_16_BIT; + } + if (Carry1.bits.raln) { + pAdapter->Stats.alignment_err += COUNTER_WRAP_12_BIT; + } + if (Carry1.bits.rflr) { + pAdapter->Stats.length_err += COUNTER_WRAP_16_BIT; + } + if (Carry1.bits.rfrg) { + pAdapter->Stats.other_errors += COUNTER_WRAP_16_BIT; + } + if (Carry1.bits.rcde) { + pAdapter->Stats.crc_err += COUNTER_WRAP_16_BIT; + } + if (Carry1.bits.rovr) { + pAdapter->Stats.rx_ov_flow += COUNTER_WRAP_16_BIT; + } + if (Carry1.bits.rdrp) { + pAdapter->Stats.norcvbuf += COUNTER_WRAP_16_BIT; + } + if (Carry2.bits.tovr) { + pAdapter->Stats.max_pkt_error += COUNTER_WRAP_12_BIT; + } + if (Carry2.bits.tund) { + pAdapter->Stats.tx_uflo += COUNTER_WRAP_12_BIT; + } + if (Carry2.bits.tscl) { + pAdapter->Stats.first_collision += COUNTER_WRAP_12_BIT; + } + if (Carry2.bits.tdfr) { + pAdapter->Stats.tx_deferred += COUNTER_WRAP_12_BIT; + } + if (Carry2.bits.tmcl) { + pAdapter->Stats.excessive_collisions += COUNTER_WRAP_12_BIT; + } + if (Carry2.bits.tlcl) { + pAdapter->Stats.late_collisions += COUNTER_WRAP_12_BIT; + } + if (Carry2.bits.tncl) { + pAdapter->Stats.collisions += COUNTER_WRAP_12_BIT; + } + + DBG_LEAVE(et131x_dbginfo); +} + +void SetupDeviceForMulticast(struct et131x_adapter *pAdapter) +{ + struct _RXMAC_t __iomem *rxmac = &pAdapter->CSRAddress->rxmac; + uint32_t nIndex; + uint32_t result; + uint32_t hash1 = 0; + uint32_t hash2 = 0; + uint32_t hash3 = 0; + uint32_t hash4 = 0; + PM_CSR_t pm_csr; + + DBG_ENTER(et131x_dbginfo); + + /* If ET131X_PACKET_TYPE_MULTICAST is specified, then we provision + * the multi-cast LIST. If it is NOT specified, (and "ALL" is not + * specified) then we should pass NO multi-cast addresses to the + * driver. + */ + if (pAdapter->PacketFilter & ET131X_PACKET_TYPE_MULTICAST) { + DBG_VERBOSE(et131x_dbginfo, + "MULTICAST flag is set, MCCount: %d\n", + pAdapter->MCAddressCount); + + /* Loop through our multicast array and set up the device */ + for (nIndex = 0; nIndex < pAdapter->MCAddressCount; nIndex++) { + DBG_VERBOSE(et131x_dbginfo, + "MCList[%d]: %02x:%02x:%02x:%02x:%02x:%02x\n", + nIndex, + pAdapter->MCList[nIndex][0], + pAdapter->MCList[nIndex][1], + pAdapter->MCList[nIndex][2], + pAdapter->MCList[nIndex][3], + pAdapter->MCList[nIndex][4], + pAdapter->MCList[nIndex][5]); + + result = ether_crc(6, pAdapter->MCList[nIndex]); + + result = (result & 0x3F800000) >> 23; + + if (result < 32) { + hash1 |= (1 << result); + } else if ((31 < result) && (result < 64)) { + result -= 32; + hash2 |= (1 << result); + } else if ((63 < result) && (result < 96)) { + result -= 64; + hash3 |= (1 << result); + } else { + result -= 96; + hash4 |= (1 << result); + } + } + } + + /* Write out the new hash to the device */ + pm_csr.value = readl(&pAdapter->CSRAddress->global.pm_csr.value); + if (pm_csr.bits.pm_phy_sw_coma == 0) { + writel(hash1, &rxmac->multi_hash1); + writel(hash2, &rxmac->multi_hash2); + writel(hash3, &rxmac->multi_hash3); + writel(hash4, &rxmac->multi_hash4); + } + + DBG_LEAVE(et131x_dbginfo); +} + +void SetupDeviceForUnicast(struct et131x_adapter *pAdapter) +{ + struct _RXMAC_t __iomem *rxmac = &pAdapter->CSRAddress->rxmac; + RXMAC_UNI_PF_ADDR1_t uni_pf1; + RXMAC_UNI_PF_ADDR2_t uni_pf2; + RXMAC_UNI_PF_ADDR3_t uni_pf3; + PM_CSR_t pm_csr; + + DBG_ENTER(et131x_dbginfo); + + /* Set up unicast packet filter reg 3 to be the first two octets of + * the MAC address for both address + * + * Set up unicast packet filter reg 2 to be the octets 2 - 5 of the + * MAC address for second address + * + * Set up unicast packet filter reg 3 to be the octets 2 - 5 of the + * MAC address for first address + */ + uni_pf3.bits.addr1_1 = pAdapter->CurrentAddress[0]; + uni_pf3.bits.addr1_2 = pAdapter->CurrentAddress[1]; + uni_pf3.bits.addr2_1 = pAdapter->CurrentAddress[0]; + uni_pf3.bits.addr2_2 = pAdapter->CurrentAddress[1]; + + uni_pf2.bits.addr2_3 = pAdapter->CurrentAddress[2]; + uni_pf2.bits.addr2_4 = pAdapter->CurrentAddress[3]; + uni_pf2.bits.addr2_5 = pAdapter->CurrentAddress[4]; + uni_pf2.bits.addr2_6 = pAdapter->CurrentAddress[5]; + + uni_pf1.bits.addr1_3 = pAdapter->CurrentAddress[2]; + uni_pf1.bits.addr1_4 = pAdapter->CurrentAddress[3]; + uni_pf1.bits.addr1_5 = pAdapter->CurrentAddress[4]; + uni_pf1.bits.addr1_6 = pAdapter->CurrentAddress[5]; + + pm_csr.value = readl(&pAdapter->CSRAddress->global.pm_csr.value); + if (pm_csr.bits.pm_phy_sw_coma == 0) { + writel(uni_pf1.value, &rxmac->uni_pf_addr1.value); + writel(uni_pf2.value, &rxmac->uni_pf_addr2.value); + writel(uni_pf3.value, &rxmac->uni_pf_addr3.value); + } + + DBG_LEAVE(et131x_dbginfo); +} diff --git a/drivers/staging/et131x/et1310_mac.h b/drivers/staging/et131x/et1310_mac.h new file mode 100644 index 000000000000..bd26cd351780 --- /dev/null +++ b/drivers/staging/et131x/et1310_mac.h @@ -0,0 +1,93 @@ +/* + * Agere Systems Inc. + * 10/100/1000 Base-T Ethernet Driver for the ET1301 and ET131x series MACs + * + * Copyright © 2005 Agere Systems Inc. + * All rights reserved. + * http://www.agere.com + * + *------------------------------------------------------------------------------ + * + * et1310_mac.h - Defines, structs, enums, prototypes, etc. pertaining to the + * MAC. + * + *------------------------------------------------------------------------------ + * + * SOFTWARE LICENSE + * + * This software is provided subject to the following terms and conditions, + * which you should read carefully before using the software. Using this + * software indicates your acceptance of these terms and conditions. If you do + * not agree with these terms and conditions, do not use the software. + * + * Copyright © 2005 Agere Systems Inc. + * All rights reserved. + * + * Redistribution and use in source or binary forms, with or without + * modifications, are permitted provided that the following conditions are met: + * + * . Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following Disclaimer as comments in the code as + * well as in the documentation and/or other materials provided with the + * distribution. + * + * . Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following Disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * . Neither the name of Agere Systems Inc. nor the names of the contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * Disclaimer + * + * THIS SOFTWARE IS PROVIDED “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, INFRINGEMENT AND THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ANY + * USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE IS SOLELY AT THE USERS OWN + * RISK. IN NO EVENT SHALL AGERE SYSTEMS INC. OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, INCLUDING, BUT NOT LIMITED TO, CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + */ + +#ifndef _ET1310_MAC_H_ +#define _ET1310_MAC_H_ + + +#include "et1310_address_map.h" + + +#define COUNTER_WRAP_28_BIT 0x10000000 +#define COUNTER_WRAP_22_BIT 0x400000 +#define COUNTER_WRAP_16_BIT 0x10000 +#define COUNTER_WRAP_12_BIT 0x1000 + +#define COUNTER_MASK_28_BIT (COUNTER_WRAP_28_BIT - 1) +#define COUNTER_MASK_22_BIT (COUNTER_WRAP_22_BIT - 1) +#define COUNTER_MASK_16_BIT (COUNTER_WRAP_16_BIT - 1) +#define COUNTER_MASK_12_BIT (COUNTER_WRAP_12_BIT - 1) + +#define UPDATE_COUNTER(HostCnt,DevCnt) \ + HostCnt = HostCnt + DevCnt; + +/* Forward declaration of the private adapter structure */ +struct et131x_adapter; + +void ConfigMACRegs1(struct et131x_adapter *adapter); +void ConfigMACRegs2(struct et131x_adapter *adapter); +void ConfigRxMacRegs(struct et131x_adapter *adapter); +void ConfigTxMacRegs(struct et131x_adapter *adapter); +void ConfigMacStatRegs(struct et131x_adapter *adapter); +void ConfigFlowControl(struct et131x_adapter *adapter); +void UpdateMacStatHostCounters(struct et131x_adapter *adapter); +void HandleMacStatInterrupt(struct et131x_adapter *adapter); +void SetupDeviceForMulticast(struct et131x_adapter *adapter); +void SetupDeviceForUnicast(struct et131x_adapter *adapter); + +#endif /* _ET1310_MAC_H_ */ diff --git a/drivers/staging/et131x/et1310_phy.c b/drivers/staging/et131x/et1310_phy.c new file mode 100644 index 000000000000..6c4fa54419ea --- /dev/null +++ b/drivers/staging/et131x/et1310_phy.c @@ -0,0 +1,1281 @@ +/* + * Agere Systems Inc. + * 10/100/1000 Base-T Ethernet Driver for the ET1301 and ET131x series MACs + * + * Copyright © 2005 Agere Systems Inc. + * All rights reserved. + * http://www.agere.com + * + *------------------------------------------------------------------------------ + * + * et1310_phy.c - Routines for configuring and accessing the PHY + * + *------------------------------------------------------------------------------ + * + * SOFTWARE LICENSE + * + * This software is provided subject to the following terms and conditions, + * which you should read carefully before using the software. Using this + * software indicates your acceptance of these terms and conditions. If you do + * not agree with these terms and conditions, do not use the software. + * + * Copyright © 2005 Agere Systems Inc. + * All rights reserved. + * + * Redistribution and use in source or binary forms, with or without + * modifications, are permitted provided that the following conditions are met: + * + * . Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following Disclaimer as comments in the code as + * well as in the documentation and/or other materials provided with the + * distribution. + * + * . Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following Disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * . Neither the name of Agere Systems Inc. nor the names of the contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * Disclaimer + * + * THIS SOFTWARE IS PROVIDED “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, INFRINGEMENT AND THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ANY + * USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE IS SOLELY AT THE USERS OWN + * RISK. IN NO EVENT SHALL AGERE SYSTEMS INC. OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, INCLUDING, BUT NOT LIMITED TO, CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + */ + +#include "et131x_version.h" +#include "et131x_debug.h" +#include "et131x_defs.h" + +#include <linux/pci.h> +#include <linux/init.h> +#include <linux/module.h> +#include <linux/types.h> +#include <linux/kernel.h> + +#include <linux/sched.h> +#include <linux/ptrace.h> +#include <linux/slab.h> +#include <linux/ctype.h> +#include <linux/string.h> +#include <linux/timer.h> +#include <linux/interrupt.h> +#include <linux/in.h> +#include <linux/delay.h> +#include <asm/io.h> +#include <asm/system.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/random.h> +#include <linux/delay.h> + +#include "et1310_phy.h" +#include "et1310_pm.h" +#include "et1310_jagcore.h" + +#include "et131x_adapter.h" +#include "et131x_netdev.h" +#include "et131x_initpci.h" + +#include "et1310_address_map.h" +#include "et1310_jagcore.h" +#include "et1310_tx.h" +#include "et1310_rx.h" +#include "et1310_mac.h" + +/* Data for debugging facilities */ +#ifdef CONFIG_ET131X_DEBUG +extern dbg_info_t *et131x_dbginfo; +#endif /* CONFIG_ET131X_DEBUG */ + +/* Prototypes for functions with local scope */ +static int et131x_xcvr_init(struct et131x_adapter *adapter); + +/** + * PhyMiRead - Read from the PHY through the MII Interface on the MAC + * @adapter: pointer to our private adapter structure + * @xcvrAddr: the address of the transciever + * @xcvrReg: the register to read + * @value: pointer to a 16-bit value in which the value will be stored + * + * Returns 0 on success, errno on failure (as defined in errno.h) + */ +int PhyMiRead(struct et131x_adapter *adapter, uint8_t xcvrAddr, + uint8_t xcvrReg, uint16_t *value) +{ + struct _MAC_t __iomem *mac = &adapter->CSRAddress->mac; + int status = 0; + uint32_t delay; + MII_MGMT_ADDR_t miiAddr; + MII_MGMT_CMD_t miiCmd; + MII_MGMT_INDICATOR_t miiIndicator; + + /* Save a local copy of the registers we are dealing with so we can + * set them back + */ + miiAddr.value = readl(&mac->mii_mgmt_addr.value); + miiCmd.value = readl(&mac->mii_mgmt_cmd.value); + + /* Stop the current operation */ + writel(0, &mac->mii_mgmt_cmd.value); + + /* Set up the register we need to read from on the correct PHY */ + { + MII_MGMT_ADDR_t mii_mgmt_addr = { 0 }; + + mii_mgmt_addr.bits.phy_addr = xcvrAddr; + mii_mgmt_addr.bits.reg_addr = xcvrReg; + writel(mii_mgmt_addr.value, &mac->mii_mgmt_addr.value); + } + + /* Kick the read cycle off */ + delay = 0; + + writel(0x1, &mac->mii_mgmt_cmd.value); + + do { + udelay(50); + delay++; + miiIndicator.value = readl(&mac->mii_mgmt_indicator.value); + } while ((miiIndicator.bits.not_valid || miiIndicator.bits.busy) && + delay < 50); + + /* If we hit the max delay, we could not read the register */ + if (delay >= 50) { + DBG_WARNING(et131x_dbginfo, + "xcvrReg 0x%08x could not be read\n", xcvrReg); + DBG_WARNING(et131x_dbginfo, "status is 0x%08x\n", + miiIndicator.value); + + status = -EIO; + } + + /* If we hit here we were able to read the register and we need to + * return the value to the caller + */ + /* TODO: make this stuff a simple readw()?! */ + { + MII_MGMT_STAT_t mii_mgmt_stat; + + mii_mgmt_stat.value = readl(&mac->mii_mgmt_stat.value); + *value = (uint16_t) mii_mgmt_stat.bits.phy_stat; + } + + /* Stop the read operation */ + writel(0, &mac->mii_mgmt_cmd.value); + + DBG_VERBOSE(et131x_dbginfo, " xcvr_addr = 0x%02x, " + "xcvr_reg = 0x%02x, " + "value = 0x%04x.\n", xcvrAddr, xcvrReg, *value); + + /* set the registers we touched back to the state at which we entered + * this function + */ + writel(miiAddr.value, &mac->mii_mgmt_addr.value); + writel(miiCmd.value, &mac->mii_mgmt_cmd.value); + + return status; +} + +/** + * MiWrite - Write to a PHY register through the MII interface of the MAC + * @adapter: pointer to our private adapter structure + * @xcvrReg: the register to read + * @value: 16-bit value to write + * + * Return 0 on success, errno on failure (as defined in errno.h) + */ +int MiWrite(struct et131x_adapter *adapter, uint8_t xcvrReg, uint16_t value) +{ + struct _MAC_t __iomem *mac = &adapter->CSRAddress->mac; + int status = 0; + uint8_t xcvrAddr = adapter->Stats.xcvr_addr; + uint32_t delay; + MII_MGMT_ADDR_t miiAddr; + MII_MGMT_CMD_t miiCmd; + MII_MGMT_INDICATOR_t miiIndicator; + + /* Save a local copy of the registers we are dealing with so we can + * set them back + */ + miiAddr.value = readl(&mac->mii_mgmt_addr.value); + miiCmd.value = readl(&mac->mii_mgmt_cmd.value); + + /* Stop the current operation */ + writel(0, &mac->mii_mgmt_cmd.value); + + /* Set up the register we need to write to on the correct PHY */ + { + MII_MGMT_ADDR_t mii_mgmt_addr; + + mii_mgmt_addr.bits.phy_addr = xcvrAddr; + mii_mgmt_addr.bits.reg_addr = xcvrReg; + writel(mii_mgmt_addr.value, &mac->mii_mgmt_addr.value); + } + + /* Add the value to write to the registers to the mac */ + writel(value, &mac->mii_mgmt_ctrl.value); + delay = 0; + + do { + udelay(50); + delay++; + miiIndicator.value = readl(&mac->mii_mgmt_indicator.value); + } while (miiIndicator.bits.busy && delay < 100); + + /* If we hit the max delay, we could not write the register */ + if (delay == 100) { + uint16_t TempValue; + + DBG_WARNING(et131x_dbginfo, + "xcvrReg 0x%08x could not be written", xcvrReg); + DBG_WARNING(et131x_dbginfo, "status is 0x%08x\n", + miiIndicator.value); + DBG_WARNING(et131x_dbginfo, "command is 0x%08x\n", + readl(&mac->mii_mgmt_cmd.value)); + + MiRead(adapter, xcvrReg, &TempValue); + + status = -EIO; + } + + /* Stop the write operation */ + writel(0, &mac->mii_mgmt_cmd.value); + + /* set the registers we touched back to the state at which we entered + * this function + */ + writel(miiAddr.value, &mac->mii_mgmt_addr.value); + writel(miiCmd.value, &mac->mii_mgmt_cmd.value); + + DBG_VERBOSE(et131x_dbginfo, " xcvr_addr = 0x%02x, " + "xcvr_reg = 0x%02x, " + "value = 0x%04x.\n", xcvrAddr, xcvrReg, value); + + return status; +} + +/** + * et131x_xcvr_find - Find the PHY ID + * @adapter: pointer to our private adapter structure + * + * Returns 0 on success, errno on failure (as defined in errno.h) + */ +int et131x_xcvr_find(struct et131x_adapter *adapter) +{ + int status = -ENODEV; + uint8_t xcvr_addr; + MI_IDR1_t idr1; + MI_IDR2_t idr2; + uint32_t xcvr_id; + + DBG_ENTER(et131x_dbginfo); + + /* We need to get xcvr id and address we just get the first one */ + for (xcvr_addr = 0; xcvr_addr < 32; xcvr_addr++) { + /* Read the ID from the PHY */ + PhyMiRead(adapter, xcvr_addr, + (uint8_t) offsetof(MI_REGS_t, idr1), + &idr1.value); + PhyMiRead(adapter, xcvr_addr, + (uint8_t) offsetof(MI_REGS_t, idr2), + &idr2.value); + + xcvr_id = (uint32_t) ((idr1.value << 16) | idr2.value); + + if ((idr1.value != 0) && (idr1.value != 0xffff)) { + DBG_TRACE(et131x_dbginfo, + "Xcvr addr: 0x%02x\tXcvr_id: 0x%08x\n", + xcvr_addr, xcvr_id); + + adapter->Stats.xcvr_id = xcvr_id; + adapter->Stats.xcvr_addr = xcvr_addr; + + status = 0; + break; + } + } + + DBG_LEAVE(et131x_dbginfo); + return status; +} + +/** + * et131x_setphy_normal - Set PHY for normal operation. + * @adapter: pointer to our private adapter structure + * + * Used by Power Management to force the PHY into 10 Base T half-duplex mode, + * when going to D3 in WOL mode. Also used during initialization to set the + * PHY for normal operation. + */ +int et131x_setphy_normal(struct et131x_adapter *adapter) +{ + int status; + + DBG_ENTER(et131x_dbginfo); + + /* Make sure the PHY is powered up */ + ET1310_PhyPowerDown(adapter, 0); + status = et131x_xcvr_init(adapter); + + DBG_LEAVE(et131x_dbginfo); + return status; +} + +/** + * et131x_xcvr_init - Init the phy if we are setting it into force mode + * @adapter: pointer to our private adapter structure + * + * Returns 0 on success, errno on failure (as defined in errno.h) + */ +static int et131x_xcvr_init(struct et131x_adapter *adapter) +{ + int status = 0; + MI_IMR_t imr; + MI_ISR_t isr; + MI_LCR2_t lcr2; + + DBG_ENTER(et131x_dbginfo); + + /* Zero out the adapter structure variable representing BMSR */ + adapter->Bmsr.value = 0; + + MiRead(adapter, (uint8_t) offsetof(MI_REGS_t, isr), &isr.value); + + MiRead(adapter, (uint8_t) offsetof(MI_REGS_t, imr), &imr.value); + + /* Set the link status interrupt only. Bad behavior when link status + * and auto neg are set, we run into a nested interrupt problem + */ + imr.bits.int_en = 0x1; + imr.bits.link_status = 0x1; + imr.bits.autoneg_status = 0x1; + + MiWrite(adapter, (uint8_t) offsetof(MI_REGS_t, imr), imr.value); + + /* Set the LED behavior such that LED 1 indicates speed (off = + * 10Mbits, blink = 100Mbits, on = 1000Mbits) and LED 2 indicates + * link and activity (on for link, blink off for activity). + * + * NOTE: Some customizations have been added here for specific + * vendors; The LED behavior is now determined by vendor data in the + * EEPROM. However, the above description is the default. + */ + if ((adapter->eepromData[1] & 0x4) == 0) { + MiRead(adapter, (uint8_t) offsetof(MI_REGS_t, lcr2), + &lcr2.value); + if ((adapter->eepromData[1] & 0x8) == 0) + lcr2.bits.led_tx_rx = 0x3; + else + lcr2.bits.led_tx_rx = 0x4; + lcr2.bits.led_link = 0xa; + MiWrite(adapter, (uint8_t) offsetof(MI_REGS_t, lcr2), + lcr2.value); + } + + /* Determine if we need to go into a force mode and set it */ + if (adapter->AiForceSpeed == 0 && adapter->AiForceDpx == 0) { + if ((adapter->RegistryFlowControl == TxOnly) || + (adapter->RegistryFlowControl == Both)) { + ET1310_PhyAccessMiBit(adapter, + TRUEPHY_BIT_SET, 4, 11, NULL); + } else { + ET1310_PhyAccessMiBit(adapter, + TRUEPHY_BIT_CLEAR, 4, 11, NULL); + } + + if (adapter->RegistryFlowControl == Both) { + ET1310_PhyAccessMiBit(adapter, + TRUEPHY_BIT_SET, 4, 10, NULL); + } else { + ET1310_PhyAccessMiBit(adapter, + TRUEPHY_BIT_CLEAR, 4, 10, NULL); + } + + /* Set the phy to autonegotiation */ + ET1310_PhyAutoNeg(adapter, true); + + /* NOTE - Do we need this? */ + ET1310_PhyAccessMiBit(adapter, TRUEPHY_BIT_SET, 0, 9, NULL); + + DBG_LEAVE(et131x_dbginfo); + return status; + } else { + ET1310_PhyAutoNeg(adapter, false); + + /* Set to the correct force mode. */ + if (adapter->AiForceDpx != 1) { + if ((adapter->RegistryFlowControl == TxOnly) || + (adapter->RegistryFlowControl == Both)) { + ET1310_PhyAccessMiBit(adapter, + TRUEPHY_BIT_SET, 4, 11, + NULL); + } else { + ET1310_PhyAccessMiBit(adapter, + TRUEPHY_BIT_CLEAR, 4, 11, + NULL); + } + + if (adapter->RegistryFlowControl == Both) { + ET1310_PhyAccessMiBit(adapter, + TRUEPHY_BIT_SET, 4, 10, + NULL); + } else { + ET1310_PhyAccessMiBit(adapter, + TRUEPHY_BIT_CLEAR, 4, 10, + NULL); + } + } else { + ET1310_PhyAccessMiBit(adapter, + TRUEPHY_BIT_CLEAR, 4, 10, NULL); + ET1310_PhyAccessMiBit(adapter, + TRUEPHY_BIT_CLEAR, 4, 11, NULL); + } + + switch (adapter->AiForceSpeed) { + case 10: + if (adapter->AiForceDpx == 1) { + TPAL_SetPhy10HalfDuplex(adapter); + } else if (adapter->AiForceDpx == 2) { + TPAL_SetPhy10FullDuplex(adapter); + } else { + TPAL_SetPhy10Force(adapter); + } + break; + case 100: + if (adapter->AiForceDpx == 1) { + TPAL_SetPhy100HalfDuplex(adapter); + } else if (adapter->AiForceDpx == 2) { + TPAL_SetPhy100FullDuplex(adapter); + } else { + TPAL_SetPhy100Force(adapter); + } + break; + case 1000: + TPAL_SetPhy1000FullDuplex(adapter); + break; + } + + DBG_LEAVE(et131x_dbginfo); + return status; + } +} + +void et131x_Mii_check(struct et131x_adapter *pAdapter, + MI_BMSR_t bmsr, MI_BMSR_t bmsr_ints) +{ + uint8_t ucLinkStatus; + uint32_t uiAutoNegStatus; + uint32_t uiSpeed; + uint32_t uiDuplex; + uint32_t uiMdiMdix; + uint32_t uiMasterSlave; + uint32_t uiPolarity; + unsigned long lockflags; + + DBG_ENTER(et131x_dbginfo); + + if (bmsr_ints.bits.link_status) { + if (bmsr.bits.link_status) { + pAdapter->PoMgmt.TransPhyComaModeOnBoot = 20; + + /* Update our state variables and indicate the + * connected state + */ + spin_lock_irqsave(&pAdapter->Lock, lockflags); + + pAdapter->MediaState = NETIF_STATUS_MEDIA_CONNECT; + MP_CLEAR_FLAG(pAdapter, fMP_ADAPTER_LINK_DETECTION); + + spin_unlock_irqrestore(&pAdapter->Lock, lockflags); + + /* Don't indicate state if we're in loopback mode */ + if (pAdapter->RegistryPhyLoopbk == false) { + netif_carrier_on(pAdapter->netdev); + } + } else { + DBG_WARNING(et131x_dbginfo, + "Link down cable problem\n"); + + if (pAdapter->uiLinkSpeed == TRUEPHY_SPEED_10MBPS) { + // NOTE - Is there a way to query this without TruePHY? + // && TRU_QueryCoreType(pAdapter->hTruePhy, 0) == EMI_TRUEPHY_A13O) { + uint16_t Register18; + + MiRead(pAdapter, 0x12, &Register18); + MiWrite(pAdapter, 0x12, Register18 | 0x4); + MiWrite(pAdapter, 0x10, Register18 | 0x8402); + MiWrite(pAdapter, 0x11, Register18 | 511); + MiWrite(pAdapter, 0x12, Register18); + } + + /* For the first N seconds of life, we are in "link + * detection" When we are in this state, we should + * only report "connected". When the LinkDetection + * Timer expires, we can report disconnected (handled + * in the LinkDetectionDPC). + */ + if ((MP_IS_FLAG_CLEAR + (pAdapter, fMP_ADAPTER_LINK_DETECTION)) + || (pAdapter->MediaState == + NETIF_STATUS_MEDIA_DISCONNECT)) { + spin_lock_irqsave(&pAdapter->Lock, lockflags); + pAdapter->MediaState = + NETIF_STATUS_MEDIA_DISCONNECT; + spin_unlock_irqrestore(&pAdapter->Lock, + lockflags); + + /* Only indicate state if we're in loopback + * mode + */ + if (pAdapter->RegistryPhyLoopbk == false) { + netif_carrier_off(pAdapter->netdev); + } + } + + pAdapter->uiLinkSpeed = 0; + pAdapter->uiDuplexMode = 0; + + /* Free the packets being actively sent & stopped */ + et131x_free_busy_send_packets(pAdapter); + + /* Re-initialize the send structures */ + et131x_init_send(pAdapter); + + /* Reset the RFD list and re-start RU */ + et131x_reset_recv(pAdapter); + + /* + * Bring the device back to the state it was during + * init prior to autonegotiation being complete. This + * way, when we get the auto-neg complete interrupt, + * we can complete init by calling ConfigMacREGS2. + */ + et131x_soft_reset(pAdapter); + + /* Setup ET1310 as per the documentation */ + et131x_adapter_setup(pAdapter); + + /* Setup the PHY into coma mode until the cable is + * plugged back in + */ + if (pAdapter->RegistryPhyComa == 1) { + EnablePhyComa(pAdapter); + } + } + } + + if (bmsr_ints.bits.auto_neg_complete || + ((pAdapter->AiForceDpx == 3) && (bmsr_ints.bits.link_status))) { + if (bmsr.bits.auto_neg_complete || (pAdapter->AiForceDpx == 3)) { + ET1310_PhyLinkStatus(pAdapter, + &ucLinkStatus, &uiAutoNegStatus, + &uiSpeed, &uiDuplex, &uiMdiMdix, + &uiMasterSlave, &uiPolarity); + + pAdapter->uiLinkSpeed = uiSpeed; + pAdapter->uiDuplexMode = uiDuplex; + + DBG_TRACE(et131x_dbginfo, + "pAdapter->uiLinkSpeed 0x%04x, pAdapter->uiDuplex 0x%08x\n", + pAdapter->uiLinkSpeed, + pAdapter->uiDuplexMode); + + pAdapter->PoMgmt.TransPhyComaModeOnBoot = 20; + + if (pAdapter->uiLinkSpeed == TRUEPHY_SPEED_10MBPS) { + // NOTE - Is there a way to query this without TruePHY? + // && TRU_QueryCoreType(pAdapter->hTruePhy, 0) == EMI_TRUEPHY_A13O) { + uint16_t Register18; + + MiRead(pAdapter, 0x12, &Register18); + MiWrite(pAdapter, 0x12, Register18 | 0x4); + MiWrite(pAdapter, 0x10, Register18 | 0x8402); + MiWrite(pAdapter, 0x11, Register18 | 511); + MiWrite(pAdapter, 0x12, Register18); + } + + ConfigFlowControl(pAdapter); + + if ((pAdapter->uiLinkSpeed == TRUEPHY_SPEED_1000MBPS) && + (pAdapter->RegistryJumboPacket > 2048)) + { + ET1310_PhyAndOrReg(pAdapter, 0x16, 0xcfff, + 0x2000); + } + + SetRxDmaTimer(pAdapter); + ConfigMACRegs2(pAdapter); + } + } + + DBG_LEAVE(et131x_dbginfo); +} + +/** + * TPAL_SetPhy10HalfDuplex - Force the phy into 10 Base T Half Duplex mode. + * @pAdapter: pointer to the adapter structure + * + * Also sets the MAC so it is syncd up properly + */ +void TPAL_SetPhy10HalfDuplex(struct et131x_adapter *pAdapter) +{ + DBG_ENTER(et131x_dbginfo); + + /* Power down PHY */ + ET1310_PhyPowerDown(pAdapter, 1); + + /* First we need to turn off all other advertisement */ + ET1310_PhyAdvertise1000BaseT(pAdapter, TRUEPHY_ADV_DUPLEX_NONE); + + ET1310_PhyAdvertise100BaseT(pAdapter, TRUEPHY_ADV_DUPLEX_NONE); + + /* Set our advertise values accordingly */ + ET1310_PhyAdvertise10BaseT(pAdapter, TRUEPHY_ADV_DUPLEX_HALF); + + /* Power up PHY */ + ET1310_PhyPowerDown(pAdapter, 0); + + DBG_LEAVE(et131x_dbginfo); +} + +/** + * TPAL_SetPhy10FullDuplex - Force the phy into 10 Base T Full Duplex mode. + * @pAdapter: pointer to the adapter structure + * + * Also sets the MAC so it is syncd up properly + */ +void TPAL_SetPhy10FullDuplex(struct et131x_adapter *pAdapter) +{ + DBG_ENTER(et131x_dbginfo); + + /* Power down PHY */ + ET1310_PhyPowerDown(pAdapter, 1); + + /* First we need to turn off all other advertisement */ + ET1310_PhyAdvertise1000BaseT(pAdapter, TRUEPHY_ADV_DUPLEX_NONE); + + ET1310_PhyAdvertise100BaseT(pAdapter, TRUEPHY_ADV_DUPLEX_NONE); + + /* Set our advertise values accordingly */ + ET1310_PhyAdvertise10BaseT(pAdapter, TRUEPHY_ADV_DUPLEX_FULL); + + /* Power up PHY */ + ET1310_PhyPowerDown(pAdapter, 0); + + DBG_LEAVE(et131x_dbginfo); +} + +/** + * TPAL_SetPhy10Force - Force Base-T FD mode WITHOUT using autonegotiation + * @pAdapter: pointer to the adapter structure + */ +void TPAL_SetPhy10Force(struct et131x_adapter *pAdapter) +{ + DBG_ENTER(et131x_dbginfo); + + /* Power down PHY */ + ET1310_PhyPowerDown(pAdapter, 1); + + /* Disable autoneg */ + ET1310_PhyAutoNeg(pAdapter, false); + + /* Disable all advertisement */ + ET1310_PhyAdvertise1000BaseT(pAdapter, TRUEPHY_ADV_DUPLEX_NONE); + ET1310_PhyAdvertise10BaseT(pAdapter, TRUEPHY_ADV_DUPLEX_NONE); + ET1310_PhyAdvertise100BaseT(pAdapter, TRUEPHY_ADV_DUPLEX_NONE); + + /* Force 10 Mbps */ + ET1310_PhySpeedSelect(pAdapter, TRUEPHY_SPEED_10MBPS); + + /* Force Full duplex */ + ET1310_PhyDuplexMode(pAdapter, TRUEPHY_DUPLEX_FULL); + + /* Power up PHY */ + ET1310_PhyPowerDown(pAdapter, 0); + + DBG_LEAVE(et131x_dbginfo); +} + +/** + * TPAL_SetPhy100HalfDuplex - Force 100 Base T Half Duplex mode. + * @pAdapter: pointer to the adapter structure + * + * Also sets the MAC so it is syncd up properly. + */ +void TPAL_SetPhy100HalfDuplex(struct et131x_adapter *pAdapter) +{ + DBG_ENTER(et131x_dbginfo); + + /* Power down PHY */ + ET1310_PhyPowerDown(pAdapter, 1); + + /* first we need to turn off all other advertisement */ + ET1310_PhyAdvertise1000BaseT(pAdapter, TRUEPHY_ADV_DUPLEX_NONE); + + ET1310_PhyAdvertise10BaseT(pAdapter, TRUEPHY_ADV_DUPLEX_NONE); + + /* Set our advertise values accordingly */ + ET1310_PhyAdvertise100BaseT(pAdapter, TRUEPHY_ADV_DUPLEX_HALF); + + /* Set speed */ + ET1310_PhySpeedSelect(pAdapter, TRUEPHY_SPEED_100MBPS); + + /* Power up PHY */ + ET1310_PhyPowerDown(pAdapter, 0); + + DBG_LEAVE(et131x_dbginfo); +} + +/** + * TPAL_SetPhy100FullDuplex - Force 100 Base T Full Duplex mode. + * @pAdapter: pointer to the adapter structure + * + * Also sets the MAC so it is syncd up properly + */ +void TPAL_SetPhy100FullDuplex(struct et131x_adapter *pAdapter) +{ + DBG_ENTER(et131x_dbginfo); + + /* Power down PHY */ + ET1310_PhyPowerDown(pAdapter, 1); + + /* First we need to turn off all other advertisement */ + ET1310_PhyAdvertise1000BaseT(pAdapter, TRUEPHY_ADV_DUPLEX_NONE); + + ET1310_PhyAdvertise10BaseT(pAdapter, TRUEPHY_ADV_DUPLEX_NONE); + + /* Set our advertise values accordingly */ + ET1310_PhyAdvertise100BaseT(pAdapter, TRUEPHY_ADV_DUPLEX_FULL); + + /* Power up PHY */ + ET1310_PhyPowerDown(pAdapter, 0); + + DBG_LEAVE(et131x_dbginfo); +} + +/** + * TPAL_SetPhy100Force - Force 100 BaseT FD mode WITHOUT using autonegotiation + * @pAdapter: pointer to the adapter structure + */ +void TPAL_SetPhy100Force(struct et131x_adapter *pAdapter) +{ + DBG_ENTER(et131x_dbginfo); + + /* Power down PHY */ + ET1310_PhyPowerDown(pAdapter, 1); + + /* Disable autoneg */ + ET1310_PhyAutoNeg(pAdapter, false); + + /* Disable all advertisement */ + ET1310_PhyAdvertise1000BaseT(pAdapter, TRUEPHY_ADV_DUPLEX_NONE); + ET1310_PhyAdvertise10BaseT(pAdapter, TRUEPHY_ADV_DUPLEX_NONE); + ET1310_PhyAdvertise100BaseT(pAdapter, TRUEPHY_ADV_DUPLEX_NONE); + + /* Force 100 Mbps */ + ET1310_PhySpeedSelect(pAdapter, TRUEPHY_SPEED_100MBPS); + + /* Force Full duplex */ + ET1310_PhyDuplexMode(pAdapter, TRUEPHY_DUPLEX_FULL); + + /* Power up PHY */ + ET1310_PhyPowerDown(pAdapter, 0); + + DBG_LEAVE(et131x_dbginfo); +} + +/** + * TPAL_SetPhy1000FullDuplex - Force 1000 Base T Full Duplex mode + * @pAdapter: pointer to the adapter structure + * + * Also sets the MAC so it is syncd up properly. + */ +void TPAL_SetPhy1000FullDuplex(struct et131x_adapter *pAdapter) +{ + DBG_ENTER(et131x_dbginfo); + + /* Power down PHY */ + ET1310_PhyPowerDown(pAdapter, 1); + + /* first we need to turn off all other advertisement */ + ET1310_PhyAdvertise100BaseT(pAdapter, TRUEPHY_ADV_DUPLEX_NONE); + + ET1310_PhyAdvertise10BaseT(pAdapter, TRUEPHY_ADV_DUPLEX_NONE); + + /* set our advertise values accordingly */ + ET1310_PhyAdvertise1000BaseT(pAdapter, TRUEPHY_ADV_DUPLEX_FULL); + + /* power up PHY */ + ET1310_PhyPowerDown(pAdapter, 0); + + DBG_LEAVE(et131x_dbginfo); +} + +/** + * TPAL_SetPhyAutoNeg - Set phy to autonegotiation mode. + * @pAdapter: pointer to the adapter structure + */ +void TPAL_SetPhyAutoNeg(struct et131x_adapter *pAdapter) +{ + DBG_ENTER(et131x_dbginfo); + + /* Power down PHY */ + ET1310_PhyPowerDown(pAdapter, 1); + + /* Turn on advertisement of all capabilities */ + ET1310_PhyAdvertise10BaseT(pAdapter, TRUEPHY_ADV_DUPLEX_BOTH); + + ET1310_PhyAdvertise100BaseT(pAdapter, TRUEPHY_ADV_DUPLEX_BOTH); + + if (pAdapter->DeviceID != ET131X_PCI_DEVICE_ID_FAST) { + ET1310_PhyAdvertise1000BaseT(pAdapter, TRUEPHY_ADV_DUPLEX_FULL); + } else { + ET1310_PhyAdvertise1000BaseT(pAdapter, TRUEPHY_ADV_DUPLEX_NONE); + } + + /* Make sure auto-neg is ON (it is disabled in FORCE modes) */ + ET1310_PhyAutoNeg(pAdapter, true); + + /* Power up PHY */ + ET1310_PhyPowerDown(pAdapter, 0); + + DBG_LEAVE(et131x_dbginfo); +} + + +/* + * The routines which follow provide low-level access to the PHY, and are used + * primarily by the routines above (although there are a few places elsewhere + * in the driver where this level of access is required). + */ + +static const uint16_t ConfigPhy[25][2] = { + /* Reg Value Register */ + /* Addr */ + {0x880B, 0x0926}, /* AfeIfCreg4B1000Msbs */ + {0x880C, 0x0926}, /* AfeIfCreg4B100Msbs */ + {0x880D, 0x0926}, /* AfeIfCreg4B10Msbs */ + + {0x880E, 0xB4D3}, /* AfeIfCreg4B1000Lsbs */ + {0x880F, 0xB4D3}, /* AfeIfCreg4B100Lsbs */ + {0x8810, 0xB4D3}, /* AfeIfCreg4B10Lsbs */ + + {0x8805, 0xB03E}, /* AfeIfCreg3B1000Msbs */ + {0x8806, 0xB03E}, /* AfeIfCreg3B100Msbs */ + {0x8807, 0xFF00}, /* AfeIfCreg3B10Msbs */ + + {0x8808, 0xE090}, /* AfeIfCreg3B1000Lsbs */ + {0x8809, 0xE110}, /* AfeIfCreg3B100Lsbs */ + {0x880A, 0x0000}, /* AfeIfCreg3B10Lsbs */ + + {0x300D, 1}, /* DisableNorm */ + + {0x280C, 0x0180}, /* LinkHoldEnd */ + + {0x1C21, 0x0002}, /* AlphaM */ + + {0x3821, 6}, /* FfeLkgTx0 */ + {0x381D, 1}, /* FfeLkg1g4 */ + {0x381E, 1}, /* FfeLkg1g5 */ + {0x381F, 1}, /* FfeLkg1g6 */ + {0x3820, 1}, /* FfeLkg1g7 */ + + {0x8402, 0x01F0}, /* Btinact */ + {0x800E, 20}, /* LftrainTime */ + {0x800F, 24}, /* DvguardTime */ + {0x8010, 46}, /* IdlguardTime */ + + {0, 0} + +}; + +/* condensed version of the phy initialization routine */ +void ET1310_PhyInit(struct et131x_adapter *pAdapter) +{ + uint16_t usData, usIndex; + + if (pAdapter == NULL) { + return; + } + + // get the identity (again ?) + MiRead(pAdapter, PHY_ID_1, &usData); + MiRead(pAdapter, PHY_ID_2, &usData); + + // what does this do/achieve ? + MiRead(pAdapter, PHY_MPHY_CONTROL_REG, &usData); // should read 0002 + MiWrite(pAdapter, PHY_MPHY_CONTROL_REG, 0x0006); + + // read modem register 0402, should I do something with the return data ? + MiWrite(pAdapter, PHY_INDEX_REG, 0x0402); + MiRead(pAdapter, PHY_DATA_REG, &usData); + + // what does this do/achieve ? + MiWrite(pAdapter, PHY_MPHY_CONTROL_REG, 0x0002); + + // get the identity (again ?) + MiRead(pAdapter, PHY_ID_1, &usData); + MiRead(pAdapter, PHY_ID_2, &usData); + + // what does this achieve ? + MiRead(pAdapter, PHY_MPHY_CONTROL_REG, &usData); // should read 0002 + MiWrite(pAdapter, PHY_MPHY_CONTROL_REG, 0x0006); + + // read modem register 0402, should I do something with the return data? + MiWrite(pAdapter, PHY_INDEX_REG, 0x0402); + MiRead(pAdapter, PHY_DATA_REG, &usData); + + MiWrite(pAdapter, PHY_MPHY_CONTROL_REG, 0x0002); + + // what does this achieve (should return 0x1040) + MiRead(pAdapter, PHY_CONTROL, &usData); + MiRead(pAdapter, PHY_MPHY_CONTROL_REG, &usData); // should read 0002 + MiWrite(pAdapter, PHY_CONTROL, 0x1840); + + MiWrite(pAdapter, PHY_MPHY_CONTROL_REG, 0x0007); + + // here the writing of the array starts.... + usIndex = 0; + while (ConfigPhy[usIndex][0] != 0x0000) { + // write value + MiWrite(pAdapter, PHY_INDEX_REG, ConfigPhy[usIndex][0]); + MiWrite(pAdapter, PHY_DATA_REG, ConfigPhy[usIndex][1]); + + // read it back + MiWrite(pAdapter, PHY_INDEX_REG, ConfigPhy[usIndex][0]); + MiRead(pAdapter, PHY_DATA_REG, &usData); + + // do a check on the value read back ? + usIndex++; + } + // here the writing of the array ends... + + MiRead(pAdapter, PHY_CONTROL, &usData); // 0x1840 + MiRead(pAdapter, PHY_MPHY_CONTROL_REG, &usData); // should read 0007 + MiWrite(pAdapter, PHY_CONTROL, 0x1040); + MiWrite(pAdapter, PHY_MPHY_CONTROL_REG, 0x0002); +} + +void ET1310_PhyReset(struct et131x_adapter *pAdapter) +{ + MiWrite(pAdapter, PHY_CONTROL, 0x8000); +} + +void ET1310_PhyPowerDown(struct et131x_adapter *pAdapter, bool down) +{ + uint16_t usData; + + MiRead(pAdapter, PHY_CONTROL, &usData); + + if (down == false) { + // Power UP + usData &= ~0x0800; + MiWrite(pAdapter, PHY_CONTROL, usData); + } else { + // Power DOWN + usData |= 0x0800; + MiWrite(pAdapter, PHY_CONTROL, usData); + } +} + +void ET1310_PhyAutoNeg(struct et131x_adapter *pAdapter, bool enable) +{ + uint16_t usData; + + MiRead(pAdapter, PHY_CONTROL, &usData); + + if (enable == true) { + // Autonegotiation ON + usData |= 0x1000; + MiWrite(pAdapter, PHY_CONTROL, usData); + } else { + // Autonegotiation OFF + usData &= ~0x1000; + MiWrite(pAdapter, PHY_CONTROL, usData); + } +} + +void ET1310_PhyDuplexMode(struct et131x_adapter *pAdapter, uint16_t duplex) +{ + uint16_t usData; + + MiRead(pAdapter, PHY_CONTROL, &usData); + + if (duplex == TRUEPHY_DUPLEX_FULL) { + // Set Full Duplex + usData |= 0x100; + MiWrite(pAdapter, PHY_CONTROL, usData); + } else { + // Set Half Duplex + usData &= ~0x100; + MiWrite(pAdapter, PHY_CONTROL, usData); + } +} + +void ET1310_PhySpeedSelect(struct et131x_adapter *pAdapter, uint16_t speed) +{ + uint16_t usData; + + // Read the PHY control register + MiRead(pAdapter, PHY_CONTROL, &usData); + + // Clear all Speed settings (Bits 6, 13) + usData &= ~0x2040; + + // Reset the speed bits based on user selection + switch (speed) { + case TRUEPHY_SPEED_10MBPS: + // Bits already cleared above, do nothing + break; + + case TRUEPHY_SPEED_100MBPS: + // 100M == Set bit 13 + usData |= 0x2000; + break; + + case TRUEPHY_SPEED_1000MBPS: + default: + usData |= 0x0040; + break; + } + + // Write back the new speed + MiWrite(pAdapter, PHY_CONTROL, usData); +} + +void ET1310_PhyAdvertise1000BaseT(struct et131x_adapter *pAdapter, + uint16_t duplex) +{ + uint16_t usData; + + // Read the PHY 1000 Base-T Control Register + MiRead(pAdapter, PHY_1000_CONTROL, &usData); + + // Clear Bits 8,9 + usData &= ~0x0300; + + switch (duplex) { + case TRUEPHY_ADV_DUPLEX_NONE: + // Duplex already cleared, do nothing + break; + + case TRUEPHY_ADV_DUPLEX_FULL: + // Set Bit 9 + usData |= 0x0200; + break; + + case TRUEPHY_ADV_DUPLEX_HALF: + // Set Bit 8 + usData |= 0x0100; + break; + + case TRUEPHY_ADV_DUPLEX_BOTH: + default: + usData |= 0x0300; + break; + } + + // Write back advertisement + MiWrite(pAdapter, PHY_1000_CONTROL, usData); +} + +void ET1310_PhyAdvertise100BaseT(struct et131x_adapter *pAdapter, + uint16_t duplex) +{ + uint16_t usData; + + // Read the Autonegotiation Register (10/100) + MiRead(pAdapter, PHY_AUTO_ADVERTISEMENT, &usData); + + // Clear bits 7,8 + usData &= ~0x0180; + + switch (duplex) { + case TRUEPHY_ADV_DUPLEX_NONE: + // Duplex already cleared, do nothing + break; + + case TRUEPHY_ADV_DUPLEX_FULL: + // Set Bit 8 + usData |= 0x0100; + break; + + case TRUEPHY_ADV_DUPLEX_HALF: + // Set Bit 7 + usData |= 0x0080; + break; + + case TRUEPHY_ADV_DUPLEX_BOTH: + default: + // Set Bits 7,8 + usData |= 0x0180; + break; + } + + // Write back advertisement + MiWrite(pAdapter, PHY_AUTO_ADVERTISEMENT, usData); +} + +void ET1310_PhyAdvertise10BaseT(struct et131x_adapter *pAdapter, + uint16_t duplex) +{ + uint16_t usData; + + // Read the Autonegotiation Register (10/100) + MiRead(pAdapter, PHY_AUTO_ADVERTISEMENT, &usData); + + // Clear bits 5,6 + usData &= ~0x0060; + + switch (duplex) { + case TRUEPHY_ADV_DUPLEX_NONE: + // Duplex already cleared, do nothing + break; + + case TRUEPHY_ADV_DUPLEX_FULL: + // Set Bit 6 + usData |= 0x0040; + break; + + case TRUEPHY_ADV_DUPLEX_HALF: + // Set Bit 5 + usData |= 0x0020; + break; + + case TRUEPHY_ADV_DUPLEX_BOTH: + default: + // Set Bits 5,6 + usData |= 0x0060; + break; + } + + // Write back advertisement + MiWrite(pAdapter, PHY_AUTO_ADVERTISEMENT, usData); +} + +void ET1310_PhyLinkStatus(struct et131x_adapter *pAdapter, + uint8_t *ucLinkStatus, + uint32_t *uiAutoNeg, + uint32_t *uiLinkSpeed, + uint32_t *uiDuplexMode, + uint32_t *uiMdiMdix, + uint32_t *uiMasterSlave, uint32_t *uiPolarity) +{ + uint16_t usMiStatus = 0; + uint16_t us1000BaseT = 0; + uint16_t usVmiPhyStatus = 0; + uint16_t usControl = 0; + + MiRead(pAdapter, PHY_STATUS, &usMiStatus); + MiRead(pAdapter, PHY_1000_STATUS, &us1000BaseT); + MiRead(pAdapter, PHY_PHY_STATUS, &usVmiPhyStatus); + MiRead(pAdapter, PHY_CONTROL, &usControl); + + if (ucLinkStatus) { + *ucLinkStatus = + (unsigned char)((usVmiPhyStatus & 0x0040) ? 1 : 0); + } + + if (uiAutoNeg) { + *uiAutoNeg = + (usControl & 0x1000) ? ((usVmiPhyStatus & 0x0020) ? + TRUEPHY_ANEG_COMPLETE : + TRUEPHY_ANEG_NOT_COMPLETE) : + TRUEPHY_ANEG_DISABLED; + } + + if (uiLinkSpeed) { + *uiLinkSpeed = (usVmiPhyStatus & 0x0300) >> 8; + } + + if (uiDuplexMode) { + *uiDuplexMode = (usVmiPhyStatus & 0x0080) >> 7; + } + + if (uiMdiMdix) { + /* NOTE: Need to complete this */ + *uiMdiMdix = 0; + } + + if (uiMasterSlave) { + *uiMasterSlave = + (us1000BaseT & 0x4000) ? TRUEPHY_CFG_MASTER : + TRUEPHY_CFG_SLAVE; + } + + if (uiPolarity) { + *uiPolarity = + (usVmiPhyStatus & 0x0400) ? TRUEPHY_POLARITY_INVERTED : + TRUEPHY_POLARITY_NORMAL; + } +} + +void ET1310_PhyAndOrReg(struct et131x_adapter *pAdapter, + uint16_t regnum, uint16_t andMask, uint16_t orMask) +{ + uint16_t reg; + + // Read the requested register + MiRead(pAdapter, regnum, ®); + + // Apply the AND mask + reg &= andMask; + + // Apply the OR mask + reg |= orMask; + + // Write the value back to the register + MiWrite(pAdapter, regnum, reg); +} + +void ET1310_PhyAccessMiBit(struct et131x_adapter *pAdapter, uint16_t action, + uint16_t regnum, uint16_t bitnum, uint8_t *value) +{ + uint16_t reg; + uint16_t mask = 0; + + // Create a mask to isolate the requested bit + mask = 0x0001 << bitnum; + + // Read the requested register + MiRead(pAdapter, regnum, ®); + + switch (action) { + case TRUEPHY_BIT_READ: + if (value != NULL) { + *value = (reg & mask) >> bitnum; + } + break; + + case TRUEPHY_BIT_SET: + reg |= mask; + MiWrite(pAdapter, regnum, reg); + break; + + case TRUEPHY_BIT_CLEAR: + reg &= ~mask; + MiWrite(pAdapter, regnum, reg); + break; + + default: + break; + } +} diff --git a/drivers/staging/et131x/et1310_phy.h b/drivers/staging/et131x/et1310_phy.h new file mode 100644 index 000000000000..d624cbbadbd7 --- /dev/null +++ b/drivers/staging/et131x/et1310_phy.h @@ -0,0 +1,910 @@ +/* + * Agere Systems Inc. + * 10/100/1000 Base-T Ethernet Driver for the ET1301 and ET131x series MACs + * + * Copyright © 2005 Agere Systems Inc. + * All rights reserved. + * http://www.agere.com + * + *------------------------------------------------------------------------------ + * + * et1310_phy.h - Defines, structs, enums, prototypes, etc. pertaining to the + * PHY. + * + *------------------------------------------------------------------------------ + * + * SOFTWARE LICENSE + * + * This software is provided subject to the following terms and conditions, + * which you should read carefully before using the software. Using this + * software indicates your acceptance of these terms and conditions. If you do + * not agree with these terms and conditions, do not use the software. + * + * Copyright © 2005 Agere Systems Inc. + * All rights reserved. + * + * Redistribution and use in source or binary forms, with or without + * modifications, are permitted provided that the following conditions are met: + * + * . Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following Disclaimer as comments in the code as + * well as in the documentation and/or other materials provided with the + * distribution. + * + * . Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following Disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * . Neither the name of Agere Systems Inc. nor the names of the contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * Disclaimer + * + * THIS SOFTWARE IS PROVIDED “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, INFRINGEMENT AND THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ANY + * USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE IS SOLELY AT THE USERS OWN + * RISK. IN NO EVENT SHALL AGERE SYSTEMS INC. OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, INCLUDING, BUT NOT LIMITED TO, CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + */ + +#ifndef _ET1310_PHY_H_ +#define _ET1310_PHY_H_ + +#include "et1310_address_map.h" + +#define TRUEPHY_SUCCESS 0 +#define TRUEPHY_FAILURE 1 +typedef void *TRUEPHY_HANDLE; +typedef void *TRUEPHY_PLATFORM_HANDLE; +typedef void *TRUEPHY_OSAL_HANDLE; + +/* MI Register Addresses */ +#define MI_CONTROL_REG 0 +#define MI_STATUS_REG 1 +#define MI_PHY_IDENTIFIER_1_REG 2 +#define MI_PHY_IDENTIFIER_2_REG 3 +#define MI_AUTONEG_ADVERTISEMENT_REG 4 +#define MI_AUTONEG_LINK_PARTNER_ABILITY_REG 5 +#define MI_AUTONEG_EXPANSION_REG 6 +#define MI_AUTONEG_NEXT_PAGE_TRANSMIT_REG 7 +#define MI_LINK_PARTNER_NEXT_PAGE_REG 8 +#define MI_1000BASET_CONTROL_REG 9 +#define MI_1000BASET_STATUS_REG 10 +#define MI_RESERVED11_REG 11 +#define MI_RESERVED12_REG 12 +#define MI_RESERVED13_REG 13 +#define MI_RESERVED14_REG 14 +#define MI_EXTENDED_STATUS_REG 15 + +/* VMI Register Addresses */ +#define VMI_RESERVED16_REG 16 +#define VMI_RESERVED17_REG 17 +#define VMI_RESERVED18_REG 18 +#define VMI_LOOPBACK_CONTROL_REG 19 +#define VMI_RESERVED20_REG 20 +#define VMI_MI_CONTROL_REG 21 +#define VMI_PHY_CONFIGURATION_REG 22 +#define VMI_PHY_CONTROL_REG 23 +#define VMI_INTERRUPT_MASK_REG 24 +#define VMI_INTERRUPT_STATUS_REG 25 +#define VMI_PHY_STATUS_REG 26 +#define VMI_LED_CONTROL_1_REG 27 +#define VMI_LED_CONTROL_2_REG 28 +#define VMI_RESERVED29_REG 29 +#define VMI_RESERVED30_REG 30 +#define VMI_RESERVED31_REG 31 + +/* PHY Register Mapping(MI) Management Interface Regs */ +typedef struct _MI_REGS_t { + u8 bmcr; // Basic mode control reg(Reg 0x00) + u8 bmsr; // Basic mode status reg(Reg 0x01) + u8 idr1; // Phy identifier reg 1(Reg 0x02) + u8 idr2; // Phy identifier reg 2(Reg 0x03) + u8 anar; // Auto-Negotiation advertisement(Reg 0x04) + u8 anlpar; // Auto-Negotiation link Partner Ability(Reg 0x05) + u8 aner; // Auto-Negotiation expansion reg(Reg 0x06) + u8 annptr; // Auto-Negotiation next page transmit reg(Reg 0x07) + u8 lpnpr; // link partner next page reg(Reg 0x08) + u8 gcr; // Gigabit basic mode control reg(Reg 0x09) + u8 gsr; // Gigabit basic mode status reg(Reg 0x0A) + u8 mi_res1[4]; // Future use by MI working group(Reg 0x0B - 0x0E) + u8 esr; // Extended status reg(Reg 0x0F) + u8 mi_res2[3]; // Future use by MI working group(Reg 0x10 - 0x12) + u8 loop_ctl; // Loopback Control Reg(Reg 0x13) + u8 mi_res3; // Future use by MI working group(Reg 0x14) + u8 mcr; // MI Control Reg(Reg 0x15) + u8 pcr; // Configuration Reg(Reg 0x16) + u8 phy_ctl; // PHY Control Reg(Reg 0x17) + u8 imr; // Interrupt Mask Reg(Reg 0x18) + u8 isr; // Interrupt Status Reg(Reg 0x19) + u8 psr; // PHY Status Reg(Reg 0x1A) + u8 lcr1; // LED Control 1 Reg(Reg 0x1B) + u8 lcr2; // LED Control 2 Reg(Reg 0x1C) + u8 mi_res4[3]; // Future use by MI working group(Reg 0x1D - 0x1F) +} MI_REGS_t, *PMI_REGS_t; + +/* MI Register 0: Basic mode control register */ +typedef union _MI_BMCR_t { + u16 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u16 reset:1; // bit 15 + u16 loopback:1; // bit 14 + u16 speed_sel:1; // bit 13 + u16 enable_autoneg:1; // bit 12 + u16 power_down:1; // bit 11 + u16 isolate:1; // bit 10 + u16 restart_autoneg:1; // bit 9 + u16 duplex_mode:1; // bit 8 + u16 col_test:1; // bit 7 + u16 speed_1000_sel:1; // bit 6 + u16 res1:6; // bits 0-5 +#else + u16 res1:6; // bits 0-5 + u16 speed_1000_sel:1; // bit 6 + u16 col_test:1; // bit 7 + u16 duplex_mode:1; // bit 8 + u16 restart_autoneg:1; // bit 9 + u16 isolate:1; // bit 10 + u16 power_down:1; // bit 11 + u16 enable_autoneg:1; // bit 12 + u16 speed_sel:1; // bit 13 + u16 loopback:1; // bit 14 + u16 reset:1; // bit 15 +#endif + } bits; +} MI_BMCR_t, *PMI_BMCR_t; + +/* MI Register 1: Basic mode status register */ +typedef union _MI_BMSR_t { + u16 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u16 link_100T4:1; // bit 15 + u16 link_100fdx:1; // bit 14 + u16 link_100hdx:1; // bit 13 + u16 link_10fdx:1; // bit 12 + u16 link_10hdx:1; // bit 11 + u16 link_100T2fdx:1; // bit 10 + u16 link_100T2hdx:1; // bit 9 + u16 extend_status:1; // bit 8 + u16 res1:1; // bit 7 + u16 preamble_supress:1; // bit 6 + u16 auto_neg_complete:1; // bit 5 + u16 remote_fault:1; // bit 4 + u16 auto_neg_able:1; // bit 3 + u16 link_status:1; // bit 2 + u16 jabber_detect:1; // bit 1 + u16 ext_cap:1; // bit 0 +#else + u16 ext_cap:1; // bit 0 + u16 jabber_detect:1; // bit 1 + u16 link_status:1; // bit 2 + u16 auto_neg_able:1; // bit 3 + u16 remote_fault:1; // bit 4 + u16 auto_neg_complete:1; // bit 5 + u16 preamble_supress:1; // bit 6 + u16 res1:1; // bit 7 + u16 extend_status:1; // bit 8 + u16 link_100T2hdx:1; // bit 9 + u16 link_100T2fdx:1; // bit 10 + u16 link_10hdx:1; // bit 11 + u16 link_10fdx:1; // bit 12 + u16 link_100hdx:1; // bit 13 + u16 link_100fdx:1; // bit 14 + u16 link_100T4:1; // bit 15 +#endif + } bits; +} MI_BMSR_t, *PMI_BMSR_t; + +/* MI Register 2: Physical Identifier 1 */ +typedef union _MI_IDR1_t { + u16 value; + struct { + u16 ieee_address:16; // 0x0282 default(bits 0-15) + } bits; +} MI_IDR1_t, *PMI_IDR1_t; + +/* MI Register 3: Physical Identifier 2 */ +typedef union _MI_IDR2_t { + u16 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u16 ieee_address:6; // 111100 default(bits 10-15) + u16 model_no:6; // 000001 default(bits 4-9) + u16 rev_no:4; // 0010 default(bits 0-3) +#else + u16 rev_no:4; // 0010 default(bits 0-3) + u16 model_no:6; // 000001 default(bits 4-9) + u16 ieee_address:6; // 111100 default(bits 10-15) +#endif + } bits; +} MI_IDR2_t, *PMI_IDR2_t; + +/* MI Register 4: Auto-negotiation advertisement register */ +typedef union _MI_ANAR_t { + u16 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u16 np_indication:1; // bit 15 + u16 res2:1; // bit 14 + u16 remote_fault:1; // bit 13 + u16 res1:1; // bit 12 + u16 cap_asmpause:1; // bit 11 + u16 cap_pause:1; // bit 10 + u16 cap_100T4:1; // bit 9 + u16 cap_100fdx:1; // bit 8 + u16 cap_100hdx:1; // bit 7 + u16 cap_10fdx:1; // bit 6 + u16 cap_10hdx:1; // bit 5 + u16 selector:5; // bits 0-4 +#else + u16 selector:5; // bits 0-4 + u16 cap_10hdx:1; // bit 5 + u16 cap_10fdx:1; // bit 6 + u16 cap_100hdx:1; // bit 7 + u16 cap_100fdx:1; // bit 8 + u16 cap_100T4:1; // bit 9 + u16 cap_pause:1; // bit 10 + u16 cap_asmpause:1; // bit 11 + u16 res1:1; // bit 12 + u16 remote_fault:1; // bit 13 + u16 res2:1; // bit 14 + u16 np_indication:1; // bit 15 +#endif + } bits; +} MI_ANAR_t, *PMI_ANAR_t; + +/* MI Register 5: Auto-negotiation link partner advertisement register */ +typedef struct _MI_ANLPAR_t { + u16 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u16 np_indication:1; // bit 15 + u16 acknowledge:1; // bit 14 + u16 remote_fault:1; // bit 13 + u16 res1:1; // bit 12 + u16 cap_asmpause:1; // bit 11 + u16 cap_pause:1; // bit 10 + u16 cap_100T4:1; // bit 9 + u16 cap_100fdx:1; // bit 8 + u16 cap_100hdx:1; // bit 7 + u16 cap_10fdx:1; // bit 6 + u16 cap_10hdx:1; // bit 5 + u16 selector:5; // bits 0-4 +#else + u16 selector:5; // bits 0-4 + u16 cap_10hdx:1; // bit 5 + u16 cap_10fdx:1; // bit 6 + u16 cap_100hdx:1; // bit 7 + u16 cap_100fdx:1; // bit 8 + u16 cap_100T4:1; // bit 9 + u16 cap_pause:1; // bit 10 + u16 cap_asmpause:1; // bit 11 + u16 res1:1; // bit 12 + u16 remote_fault:1; // bit 13 + u16 acknowledge:1; // bit 14 + u16 np_indication:1; // bit 15 +#endif + } bits; +} MI_ANLPAR_t, *PMI_ANLPAR_t; + +/* MI Register 6: Auto-negotiation expansion register */ +typedef union _MI_ANER_t { + u16 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u16 res:11; // bits 5-15 + u16 pdf:1; // bit 4 + u16 lp_np_able:1; // bit 3 + u16 np_able:1; // bit 2 + u16 page_rx:1; // bit 1 + u16 lp_an_able:1; // bit 0 +#else + u16 lp_an_able:1; // bit 0 + u16 page_rx:1; // bit 1 + u16 np_able:1; // bit 2 + u16 lp_np_able:1; // bit 3 + u16 pdf:1; // bit 4 + u16 res:11; // bits 5-15 +#endif + } bits; +} MI_ANER_t, *PMI_ANER_t; + +/* MI Register 7: Auto-negotiation next page transmit reg(0x07) */ +typedef union _MI_ANNPTR_t { + u16 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u16 np:1; // bit 15 + u16 res1:1; // bit 14 + u16 msg_page:1; // bit 13 + u16 ack2:1; // bit 12 + u16 toggle:1; // bit 11 + u16 msg:11; // bits 0-10 +#else + u16 msg:11; // bits 0-10 + u16 toggle:1; // bit 11 + u16 ack2:1; // bit 12 + u16 msg_page:1; // bit 13 + u16 res1:1; // bit 14 + u16 np:1; // bit 15 +#endif + } bits; +} MI_ANNPTR_t, *PMI_ANNPTR_t; + +/* MI Register 8: Link Partner Next Page Reg(0x08) */ +typedef union _MI_LPNPR_t { + u16 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u16 np:1; // bit 15 + u16 ack:1; // bit 14 + u16 msg_page:1; // bit 13 + u16 ack2:1; // bit 12 + u16 toggle:1; // bit 11 + u16 msg:11; // bits 0-10 +#else + u16 msg:11; // bits 0-10 + u16 toggle:1; // bit 11 + u16 ack2:1; // bit 12 + u16 msg_page:1; // bit 13 + u16 ack:1; // bit 14 + u16 np:1; // bit 15 +#endif + } bits; +} MI_LPNPR_t, *PMI_LPNPR_t; + +/* MI Register 9: 1000BaseT Control Reg(0x09) */ +typedef union _MI_GCR_t { + u16 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u16 test_mode:3; // bits 13-15 + u16 ms_config_en:1; // bit 12 + u16 ms_value:1; // bit 11 + u16 port_type:1; // bit 10 + u16 link_1000fdx:1; // bit 9 + u16 link_1000hdx:1; // bit 8 + u16 res:8; // bit 0-7 +#else + u16 res:8; // bit 0-7 + u16 link_1000hdx:1; // bit 8 + u16 link_1000fdx:1; // bit 9 + u16 port_type:1; // bit 10 + u16 ms_value:1; // bit 11 + u16 ms_config_en:1; // bit 12 + u16 test_mode:3; // bits 13-15 +#endif + } bits; +} MI_GCR_t, *PMI_GCR_t; + +/* MI Register 10: 1000BaseT Status Reg(0x0A) */ +typedef union _MI_GSR_t { + u16 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u16 ms_config_fault:1; // bit 15 + u16 ms_resolve:1; // bit 14 + u16 local_rx_status:1; // bit 13 + u16 remote_rx_status:1; // bit 12 + u16 link_1000fdx:1; // bit 11 + u16 link_1000hdx:1; // bit 10 + u16 res:2; // bits 8-9 + u16 idle_err_cnt:8; // bits 0-7 +#else + u16 idle_err_cnt:8; // bits 0-7 + u16 res:2; // bits 8-9 + u16 link_1000hdx:1; // bit 10 + u16 link_1000fdx:1; // bit 11 + u16 remote_rx_status:1; // bit 12 + u16 local_rx_status:1; // bit 13 + u16 ms_resolve:1; // bit 14 + u16 ms_config_fault:1; // bit 15 +#endif + } bits; +} MI_GSR_t, *PMI_GSR_t; + +/* MI Register 11 - 14: Reserved Regs(0x0B - 0x0E) */ +typedef union _MI_RES_t { + u16 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u16 res15:1; // bit 15 + u16 res14:1; // bit 14 + u16 res13:1; // bit 13 + u16 res12:1; // bit 12 + u16 res11:1; // bit 11 + u16 res10:1; // bit 10 + u16 res9:1; // bit 9 + u16 res8:1; // bit 8 + u16 res7:1; // bit 7 + u16 res6:1; // bit 6 + u16 res5:1; // bit 5 + u16 res4:1; // bit 4 + u16 res3:1; // bit 3 + u16 res2:1; // bit 2 + u16 res1:1; // bit 1 + u16 res0:1; // bit 0 +#else + u16 res0:1; // bit 0 + u16 res1:1; // bit 1 + u16 res2:1; // bit 2 + u16 res3:1; // bit 3 + u16 res4:1; // bit 4 + u16 res5:1; // bit 5 + u16 res6:1; // bit 6 + u16 res7:1; // bit 7 + u16 res8:1; // bit 8 + u16 res9:1; // bit 9 + u16 res10:1; // bit 10 + u16 res11:1; // bit 11 + u16 res12:1; // bit 12 + u16 res13:1; // bit 13 + u16 res14:1; // bit 14 + u16 res15:1; // bit 15 +#endif + } bits; +} MI_RES_t, *PMI_RES_t; + +/* MI Register 15: Extended status Reg(0x0F) */ +typedef union _MI_ESR_t { + u16 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u16 link_1000Xfdx:1; // bit 15 + u16 link_1000Xhdx:1; // bit 14 + u16 link_1000fdx:1; // bit 13 + u16 link_1000hdx:1; // bit 12 + u16 res:12; // bit 0-11 +#else + u16 res:12; // bit 0-11 + u16 link_1000hdx:1; // bit 12 + u16 link_1000fdx:1; // bit 13 + u16 link_1000Xhdx:1; // bit 14 + u16 link_1000Xfdx:1; // bit 15 +#endif + } bits; +} MI_ESR_t, *PMI_ESR_t; + +/* MI Register 16 - 18: Reserved Reg(0x10-0x12) */ + +/* MI Register 19: Loopback Control Reg(0x13) */ +typedef union _MI_LCR_t { + u16 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u16 mii_en:1; // bit 15 + u16 pcs_en:1; // bit 14 + u16 pmd_en:1; // bit 13 + u16 all_digital_en:1; // bit 12 + u16 replica_en:1; // bit 11 + u16 line_driver_en:1; // bit 10 + u16 res:10; // bit 0-9 +#else + u16 res:10; // bit 0-9 + u16 line_driver_en:1; // bit 10 + u16 replica_en:1; // bit 11 + u16 all_digital_en:1; // bit 12 + u16 pmd_en:1; // bit 13 + u16 pcs_en:1; // bit 14 + u16 mii_en:1; // bit 15 +#endif + } bits; +} MI_LCR_t, *PMI_LCR_t; + +/* MI Register 20: Reserved Reg(0x14) */ + +/* MI Register 21: Management Interface Control Reg(0x15) */ +typedef union _MI_MICR_t { + u16 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u16 res1:5; // bits 11-15 + u16 mi_error_count:7; // bits 4-10 + u16 res2:1; // bit 3 + u16 ignore_10g_fr:1; // bit 2 + u16 res3:1; // bit 1 + u16 preamble_supress_en:1; // bit 0 +#else + u16 preamble_supress_en:1; // bit 0 + u16 res3:1; // bit 1 + u16 ignore_10g_fr:1; // bit 2 + u16 res2:1; // bit 3 + u16 mi_error_count:7; // bits 4-10 + u16 res1:5; // bits 11-15 +#endif + } bits; +} MI_MICR_t, *PMI_MICR_t; + +/* MI Register 22: PHY Configuration Reg(0x16) */ +typedef union _MI_PHY_CONFIG_t { + u16 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u16 crs_tx_en:1; // bit 15 + u16 res1:1; // bit 14 + u16 tx_fifo_depth:2; // bits 12-13 + u16 speed_downshift:2; // bits 10-11 + u16 pbi_detect:1; // bit 9 + u16 tbi_rate:1; // bit 8 + u16 alternate_np:1; // bit 7 + u16 group_mdio_en:1; // bit 6 + u16 tx_clock_en:1; // bit 5 + u16 sys_clock_en:1; // bit 4 + u16 res2:1; // bit 3 + u16 mac_if_mode:3; // bits 0-2 +#else + u16 mac_if_mode:3; // bits 0-2 + u16 res2:1; // bit 3 + u16 sys_clock_en:1; // bit 4 + u16 tx_clock_en:1; // bit 5 + u16 group_mdio_en:1; // bit 6 + u16 alternate_np:1; // bit 7 + u16 tbi_rate:1; // bit 8 + u16 pbi_detect:1; // bit 9 + u16 speed_downshift:2; // bits 10-11 + u16 tx_fifo_depth:2; // bits 12-13 + u16 res1:1; // bit 14 + u16 crs_tx_en:1; // bit 15 +#endif + } bits; +} MI_PHY_CONFIG_t, *PMI_PHY_CONFIG_t; + +/* MI Register 23: PHY CONTROL Reg(0x17) */ +typedef union _MI_PHY_CONTROL_t { + u16 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u16 res1:1; // bit 15 + u16 tdr_en:1; // bit 14 + u16 res2:1; // bit 13 + u16 downshift_attempts:2; // bits 11-12 + u16 res3:5; // bit 6-10 + u16 jabber_10baseT:1; // bit 5 + u16 sqe_10baseT:1; // bit 4 + u16 tp_loopback_10baseT:1; // bit 3 + u16 preamble_gen_en:1; // bit 2 + u16 res4:1; // bit 1 + u16 force_int:1; // bit 0 +#else + u16 force_int:1; // bit 0 + u16 res4:1; // bit 1 + u16 preamble_gen_en:1; // bit 2 + u16 tp_loopback_10baseT:1; // bit 3 + u16 sqe_10baseT:1; // bit 4 + u16 jabber_10baseT:1; // bit 5 + u16 res3:5; // bit 6-10 + u16 downshift_attempts:2; // bits 11-12 + u16 res2:1; // bit 13 + u16 tdr_en:1; // bit 14 + u16 res1:1; // bit 15 +#endif + } bits; +} MI_PHY_CONTROL_t, *PMI_PHY_CONTROL_t; + +/* MI Register 24: Interrupt Mask Reg(0x18) */ +typedef union _MI_IMR_t { + u16 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u16 res1:6; // bits 10-15 + u16 mdio_sync_lost:1; // bit 9 + u16 autoneg_status:1; // bit 8 + u16 hi_bit_err:1; // bit 7 + u16 np_rx:1; // bit 6 + u16 err_counter_full:1; // bit 5 + u16 fifo_over_underflow:1; // bit 4 + u16 rx_status:1; // bit 3 + u16 link_status:1; // bit 2 + u16 automatic_speed:1; // bit 1 + u16 int_en:1; // bit 0 +#else + u16 int_en:1; // bit 0 + u16 automatic_speed:1; // bit 1 + u16 link_status:1; // bit 2 + u16 rx_status:1; // bit 3 + u16 fifo_over_underflow:1; // bit 4 + u16 err_counter_full:1; // bit 5 + u16 np_rx:1; // bit 6 + u16 hi_bit_err:1; // bit 7 + u16 autoneg_status:1; // bit 8 + u16 mdio_sync_lost:1; // bit 9 + u16 res1:6; // bits 10-15 +#endif + } bits; +} MI_IMR_t, *PMI_IMR_t; + +/* MI Register 25: Interrupt Status Reg(0x19) */ +typedef union _MI_ISR_t { + u16 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u16 res1:6; // bits 10-15 + u16 mdio_sync_lost:1; // bit 9 + u16 autoneg_status:1; // bit 8 + u16 hi_bit_err:1; // bit 7 + u16 np_rx:1; // bit 6 + u16 err_counter_full:1; // bit 5 + u16 fifo_over_underflow:1; // bit 4 + u16 rx_status:1; // bit 3 + u16 link_status:1; // bit 2 + u16 automatic_speed:1; // bit 1 + u16 int_en:1; // bit 0 +#else + u16 int_en:1; // bit 0 + u16 automatic_speed:1; // bit 1 + u16 link_status:1; // bit 2 + u16 rx_status:1; // bit 3 + u16 fifo_over_underflow:1; // bit 4 + u16 err_counter_full:1; // bit 5 + u16 np_rx:1; // bit 6 + u16 hi_bit_err:1; // bit 7 + u16 autoneg_status:1; // bit 8 + u16 mdio_sync_lost:1; // bit 9 + u16 res1:6; // bits 10-15 +#endif + } bits; +} MI_ISR_t, *PMI_ISR_t; + +/* MI Register 26: PHY Status Reg(0x1A) */ +typedef union _MI_PSR_t { + u16 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u16 res1:1; // bit 15 + u16 autoneg_fault:2; // bit 13-14 + u16 autoneg_status:1; // bit 12 + u16 mdi_x_status:1; // bit 11 + u16 polarity_status:1; // bit 10 + u16 speed_status:2; // bits 8-9 + u16 duplex_status:1; // bit 7 + u16 link_status:1; // bit 6 + u16 tx_status:1; // bit 5 + u16 rx_status:1; // bit 4 + u16 collision_status:1; // bit 3 + u16 autoneg_en:1; // bit 2 + u16 pause_en:1; // bit 1 + u16 asymmetric_dir:1; // bit 0 +#else + u16 asymmetric_dir:1; // bit 0 + u16 pause_en:1; // bit 1 + u16 autoneg_en:1; // bit 2 + u16 collision_status:1; // bit 3 + u16 rx_status:1; // bit 4 + u16 tx_status:1; // bit 5 + u16 link_status:1; // bit 6 + u16 duplex_status:1; // bit 7 + u16 speed_status:2; // bits 8-9 + u16 polarity_status:1; // bit 10 + u16 mdi_x_status:1; // bit 11 + u16 autoneg_status:1; // bit 12 + u16 autoneg_fault:2; // bit 13-14 + u16 res1:1; // bit 15 +#endif + } bits; +} MI_PSR_t, *PMI_PSR_t; + +/* MI Register 27: LED Control Reg 1(0x1B) */ +typedef union _MI_LCR1_t { + u16 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u16 res1:2; // bits 14-15 + u16 led_dup_indicate:2; // bits 12-13 + u16 led_10baseT:2; // bits 10-11 + u16 led_collision:2; // bits 8-9 + u16 res2:2; // bits 6-7 + u16 res3:2; // bits 4-5 + u16 pulse_dur:2; // bits 2-3 + u16 pulse_stretch1:1; // bit 1 + u16 pulse_stretch0:1; // bit 0 +#else + u16 pulse_stretch0:1; // bit 0 + u16 pulse_stretch1:1; // bit 1 + u16 pulse_dur:2; // bits 2-3 + u16 res3:2; // bits 4-5 + u16 res2:2; // bits 6-7 + u16 led_collision:2; // bits 8-9 + u16 led_10baseT:2; // bits 10-11 + u16 led_dup_indicate:2; // bits 12-13 + u16 res1:2; // bits 14-15 +#endif + } bits; +} MI_LCR1_t, *PMI_LCR1_t; + +/* MI Register 28: LED Control Reg 2(0x1C) */ +typedef union _MI_LCR2_t { + u16 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u16 led_link:4; // bits 12-15 + u16 led_tx_rx:4; // bits 8-11 + u16 led_100BaseTX:4; // bits 4-7 + u16 led_1000BaseT:4; // bits 0-3 +#else + u16 led_1000BaseT:4; // bits 0-3 + u16 led_100BaseTX:4; // bits 4-7 + u16 led_tx_rx:4; // bits 8-11 + u16 led_link:4; // bits 12-15 +#endif + } bits; +} MI_LCR2_t, *PMI_LCR2_t; + +/* MI Register 29 - 31: Reserved Reg(0x1D - 0x1E) */ + +/* TruePHY headers */ +typedef struct _TRUEPHY_ACCESS_MI_REGS_ { + TRUEPHY_HANDLE hTruePhy; + int32_t nPhyId; + u8 bReadWrite; + u8 *pbyRegs; + u8 *pwData; + int32_t nRegCount; +} TRUEPHY_ACCESS_MI_REGS, *PTRUEPHY_ACCESS_MI_REGS; + +/* TruePHY headers */ +typedef struct _TAG_TPAL_ACCESS_MI_REGS_ { + u32 nPhyId; + u8 bReadWrite; + u32 nRegCount; + u16 Data[4096]; + u8 Regs[4096]; +} TPAL_ACCESS_MI_REGS, *PTPAL_ACCESS_MI_REGS; + + +typedef TRUEPHY_HANDLE TPAL_HANDLE; + +/* Forward declaration of the private adapter structure */ +struct et131x_adapter; + +/* OS Specific Functions*/ +void TPAL_SetPhy10HalfDuplex(struct et131x_adapter *adapter); +void TPAL_SetPhy10FullDuplex(struct et131x_adapter *adapter); +void TPAL_SetPhy10Force(struct et131x_adapter *pAdapter); +void TPAL_SetPhy100HalfDuplex(struct et131x_adapter *adapter); +void TPAL_SetPhy100FullDuplex(struct et131x_adapter *adapter); +void TPAL_SetPhy100Force(struct et131x_adapter *pAdapter); +void TPAL_SetPhy1000FullDuplex(struct et131x_adapter *adapter); +void TPAL_SetPhyAutoNeg(struct et131x_adapter *adapter); + +/* Prototypes for ET1310_phy.c */ +int et131x_xcvr_find(struct et131x_adapter *adapter); +int et131x_setphy_normal(struct et131x_adapter *adapter); +int32_t PhyMiRead(struct et131x_adapter *adapter, + u8 xcvrAddr, u8 xcvrReg, u16 *value); + +/* static inline function does not work because et131x_adapter is not always + * defined + */ +#define MiRead(adapter, xcvrReg, value) \ + PhyMiRead((adapter), (adapter)->Stats.xcvr_addr, (xcvrReg), (value)) + +int32_t MiWrite(struct et131x_adapter *adapter, + u8 xcvReg, u16 value); +void et131x_Mii_check(struct et131x_adapter *pAdapter, + MI_BMSR_t bmsr, MI_BMSR_t bmsr_ints); + +/* This last is not strictly required (the driver could call the TPAL + * version instead), but this sets the adapter up correctly, and calls the + * access routine indirectly. This protects the driver from changes in TPAL. + */ +void SetPhy_10BaseTHalfDuplex(struct et131x_adapter *adapter); + +/* Defines for PHY access routines */ + +// Define bit operation flags +#define TRUEPHY_BIT_CLEAR 0 +#define TRUEPHY_BIT_SET 1 +#define TRUEPHY_BIT_READ 2 + +// Define read/write operation flags +#ifndef TRUEPHY_READ +#define TRUEPHY_READ 0 +#define TRUEPHY_WRITE 1 +#define TRUEPHY_MASK 2 +#endif + +// Define speeds +#define TRUEPHY_SPEED_10MBPS 0 +#define TRUEPHY_SPEED_100MBPS 1 +#define TRUEPHY_SPEED_1000MBPS 2 + +// Define duplex modes +#define TRUEPHY_DUPLEX_HALF 0 +#define TRUEPHY_DUPLEX_FULL 1 + +// Define master/slave configuration values +#define TRUEPHY_CFG_SLAVE 0 +#define TRUEPHY_CFG_MASTER 1 + +// Define MDI/MDI-X settings +#define TRUEPHY_MDI 0 +#define TRUEPHY_MDIX 1 +#define TRUEPHY_AUTO_MDI_MDIX 2 + +// Define 10Base-T link polarities +#define TRUEPHY_POLARITY_NORMAL 0 +#define TRUEPHY_POLARITY_INVERTED 1 + +// Define auto-negotiation results +#define TRUEPHY_ANEG_NOT_COMPLETE 0 +#define TRUEPHY_ANEG_COMPLETE 1 +#define TRUEPHY_ANEG_DISABLED 2 + +/* Define duplex advertisment flags */ +#define TRUEPHY_ADV_DUPLEX_NONE 0x00 +#define TRUEPHY_ADV_DUPLEX_FULL 0x01 +#define TRUEPHY_ADV_DUPLEX_HALF 0x02 +#define TRUEPHY_ADV_DUPLEX_BOTH \ + (TRUEPHY_ADV_DUPLEX_FULL | TRUEPHY_ADV_DUPLEX_HALF) + +#define PHY_CONTROL 0x00 //#define TRU_MI_CONTROL_REGISTER 0 +#define PHY_STATUS 0x01 //#define TRU_MI_STATUS_REGISTER 1 +#define PHY_ID_1 0x02 //#define TRU_MI_PHY_IDENTIFIER_1_REGISTER 2 +#define PHY_ID_2 0x03 //#define TRU_MI_PHY_IDENTIFIER_2_REGISTER 3 +#define PHY_AUTO_ADVERTISEMENT 0x04 //#define TRU_MI_ADVERTISEMENT_REGISTER 4 +#define PHY_AUTO_LINK_PARTNER 0x05 //#define TRU_MI_LINK_PARTNER_ABILITY_REGISTER 5 +#define PHY_AUTO_EXPANSION 0x06 //#define TRU_MI_EXPANSION_REGISTER 6 +#define PHY_AUTO_NEXT_PAGE_TX 0x07 //#define TRU_MI_NEXT_PAGE_TRANSMIT_REGISTER 7 +#define PHY_LINK_PARTNER_NEXT_PAGE 0x08 //#define TRU_MI_LINK_PARTNER_NEXT_PAGE_REGISTER 8 +#define PHY_1000_CONTROL 0x09 //#define TRU_MI_1000BASET_CONTROL_REGISTER 9 +#define PHY_1000_STATUS 0x0A //#define TRU_MI_1000BASET_STATUS_REGISTER 10 + +#define PHY_EXTENDED_STATUS 0x0F //#define TRU_MI_EXTENDED_STATUS_REGISTER 15 + +// some defines for modem registers that seem to be 'reserved' +#define PHY_INDEX_REG 0x10 +#define PHY_DATA_REG 0x11 + +#define PHY_MPHY_CONTROL_REG 0x12 //#define TRU_VMI_MPHY_CONTROL_REGISTER 18 + +#define PHY_LOOPBACK_CONTROL 0x13 //#define TRU_VMI_LOOPBACK_CONTROL_1_REGISTER 19 + //#define TRU_VMI_LOOPBACK_CONTROL_2_REGISTER 20 +#define PHY_REGISTER_MGMT_CONTROL 0x15 //#define TRU_VMI_MI_SEQ_CONTROL_REGISTER 21 +#define PHY_CONFIG 0x16 //#define TRU_VMI_CONFIGURATION_REGISTER 22 +#define PHY_PHY_CONTROL 0x17 //#define TRU_VMI_PHY_CONTROL_REGISTER 23 +#define PHY_INTERRUPT_MASK 0x18 //#define TRU_VMI_INTERRUPT_MASK_REGISTER 24 +#define PHY_INTERRUPT_STATUS 0x19 //#define TRU_VMI_INTERRUPT_STATUS_REGISTER 25 +#define PHY_PHY_STATUS 0x1A //#define TRU_VMI_PHY_STATUS_REGISTER 26 +#define PHY_LED_1 0x1B //#define TRU_VMI_LED_CONTROL_1_REGISTER 27 +#define PHY_LED_2 0x1C //#define TRU_VMI_LED_CONTROL_2_REGISTER 28 + //#define TRU_VMI_LINK_CONTROL_REGISTER 29 + //#define TRU_VMI_TIMING_CONTROL_REGISTER + +/* Prototypes for PHY access routines */ +void ET1310_PhyInit(struct et131x_adapter *adapter); +void ET1310_PhyReset(struct et131x_adapter *adapter); +void ET1310_PhyPowerDown(struct et131x_adapter *adapter, bool down); +void ET1310_PhyAutoNeg(struct et131x_adapter *adapter, bool enable); +void ET1310_PhyDuplexMode(struct et131x_adapter *adapter, u16 duplex); +void ET1310_PhySpeedSelect(struct et131x_adapter *adapter, u16 speed); +void ET1310_PhyAdvertise1000BaseT(struct et131x_adapter *adapter, + u16 duplex); +void ET1310_PhyAdvertise100BaseT(struct et131x_adapter *adapter, + u16 duplex); +void ET1310_PhyAdvertise10BaseT(struct et131x_adapter *adapter, + u16 duplex); +void ET1310_PhyLinkStatus(struct et131x_adapter *adapter, + u8 *ucLinkStatus, + u32 *uiAutoNeg, + u32 *uiLinkSpeed, + u32 *uiDuplexMode, + u32 *uiMdiMdix, + u32 *uiMasterSlave, u32 *uiPolarity); +void ET1310_PhyAndOrReg(struct et131x_adapter *adapter, + u16 regnum, u16 andMask, u16 orMask); +void ET1310_PhyAccessMiBit(struct et131x_adapter *adapter, + u16 action, + u16 regnum, u16 bitnum, u8 *value); + +#endif /* _ET1310_PHY_H_ */ diff --git a/drivers/staging/et131x/et1310_pm.c b/drivers/staging/et131x/et1310_pm.c new file mode 100644 index 000000000000..9539bc628cae --- /dev/null +++ b/drivers/staging/et131x/et1310_pm.c @@ -0,0 +1,207 @@ +/* + * Agere Systems Inc. + * 10/100/1000 Base-T Ethernet Driver for the ET1301 and ET131x series MACs + * + * Copyright © 2005 Agere Systems Inc. + * All rights reserved. + * http://www.agere.com + * + *------------------------------------------------------------------------------ + * + * et1310_pm.c - All power management related code (not completely implemented) + * + *------------------------------------------------------------------------------ + * + * SOFTWARE LICENSE + * + * This software is provided subject to the following terms and conditions, + * which you should read carefully before using the software. Using this + * software indicates your acceptance of these terms and conditions. If you do + * not agree with these terms and conditions, do not use the software. + * + * Copyright © 2005 Agere Systems Inc. + * All rights reserved. + * + * Redistribution and use in source or binary forms, with or without + * modifications, are permitted provided that the following conditions are met: + * + * . Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following Disclaimer as comments in the code as + * well as in the documentation and/or other materials provided with the + * distribution. + * + * . Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following Disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * . Neither the name of Agere Systems Inc. nor the names of the contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * Disclaimer + * + * THIS SOFTWARE IS PROVIDED “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, INFRINGEMENT AND THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ANY + * USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE IS SOLELY AT THE USERS OWN + * RISK. IN NO EVENT SHALL AGERE SYSTEMS INC. OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, INCLUDING, BUT NOT LIMITED TO, CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + */ + +#include "et131x_version.h" +#include "et131x_debug.h" +#include "et131x_defs.h" + +#include <linux/init.h> +#include <linux/module.h> +#include <linux/types.h> +#include <linux/kernel.h> + +#include <linux/sched.h> +#include <linux/ptrace.h> +#include <linux/slab.h> +#include <linux/ctype.h> +#include <linux/string.h> +#include <linux/timer.h> +#include <linux/interrupt.h> +#include <linux/in.h> +#include <linux/delay.h> +#include <asm/io.h> +#include <asm/system.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 "et1310_phy.h" +#include "et1310_pm.h" +#include "et1310_jagcore.h" +#include "et1310_mac.h" +#include "et1310_rx.h" + +#include "et131x_adapter.h" +#include "et131x_initpci.h" + +/* Data for debugging facilities */ +#ifdef CONFIG_ET131X_DEBUG +extern dbg_info_t *et131x_dbginfo; +#endif /* CONFIG_ET131X_DEBUG */ + +/** + * EnablePhyComa - called when network cable is unplugged + * @pAdapter: pointer to our adapter structure + * + * driver receive an phy status change interrupt while in D0 and check that + * phy_status is down. + * + * -- gate off JAGCore; + * -- set gigE PHY in Coma mode + * -- wake on phy_interrupt; Perform software reset JAGCore, + * re-initialize jagcore and gigE PHY + * + * Add D0-ASPM-PhyLinkDown Support: + * -- while in D0, when there is a phy_interrupt indicating phy link + * down status, call the MPSetPhyComa routine to enter this active + * state power saving mode + * -- while in D0-ASPM-PhyLinkDown mode, when there is a phy_interrupt + * indicating linkup status, call the MPDisablePhyComa routine to + * restore JAGCore and gigE PHY + */ +void EnablePhyComa(struct et131x_adapter *pAdapter) +{ + unsigned long lockflags; + PM_CSR_t GlobalPmCSR; + int32_t LoopCounter = 10; + + DBG_ENTER(et131x_dbginfo); + + GlobalPmCSR.value = readl(&pAdapter->CSRAddress->global.pm_csr.value); + + /* Save the GbE PHY speed and duplex modes. Need to restore this + * when cable is plugged back in + */ + pAdapter->PoMgmt.PowerDownSpeed = pAdapter->AiForceSpeed; + pAdapter->PoMgmt.PowerDownDuplex = pAdapter->AiForceDpx; + + /* Stop sending packets. */ + spin_lock_irqsave(&pAdapter->SendHWLock, lockflags); + MP_SET_FLAG(pAdapter, fMP_ADAPTER_LOWER_POWER); + spin_unlock_irqrestore(&pAdapter->SendHWLock, lockflags); + + /* Wait for outstanding Receive packets */ + while ((MP_GET_RCV_REF(pAdapter) != 0) && (LoopCounter-- > 0)) { + mdelay(2); + } + + /* Gate off JAGCore 3 clock domains */ + GlobalPmCSR.bits.pm_sysclk_gate = 0; + GlobalPmCSR.bits.pm_txclk_gate = 0; + GlobalPmCSR.bits.pm_rxclk_gate = 0; + writel(GlobalPmCSR.value, &pAdapter->CSRAddress->global.pm_csr.value); + + /* Program gigE PHY in to Coma mode */ + GlobalPmCSR.bits.pm_phy_sw_coma = 1; + writel(GlobalPmCSR.value, &pAdapter->CSRAddress->global.pm_csr.value); + + DBG_LEAVE(et131x_dbginfo); +} + +/** + * DisablePhyComa - Disable the Phy Coma Mode + * @pAdapter: pointer to our adapter structure + */ +void DisablePhyComa(struct et131x_adapter *pAdapter) +{ + PM_CSR_t GlobalPmCSR; + + DBG_ENTER(et131x_dbginfo); + + GlobalPmCSR.value = readl(&pAdapter->CSRAddress->global.pm_csr.value); + + /* Disable phy_sw_coma register and re-enable JAGCore clocks */ + GlobalPmCSR.bits.pm_sysclk_gate = 1; + GlobalPmCSR.bits.pm_txclk_gate = 1; + GlobalPmCSR.bits.pm_rxclk_gate = 1; + GlobalPmCSR.bits.pm_phy_sw_coma = 0; + writel(GlobalPmCSR.value, &pAdapter->CSRAddress->global.pm_csr.value); + + /* Restore the GbE PHY speed and duplex modes; + * Reset JAGCore; re-configure and initialize JAGCore and gigE PHY + */ + pAdapter->AiForceSpeed = pAdapter->PoMgmt.PowerDownSpeed; + pAdapter->AiForceDpx = pAdapter->PoMgmt.PowerDownDuplex; + + /* Re-initialize the send structures */ + et131x_init_send(pAdapter); + + /* Reset the RFD list and re-start RU */ + et131x_reset_recv(pAdapter); + + /* Bring the device back to the state it was during init prior to + * autonegotiation being complete. This way, when we get the auto-neg + * complete interrupt, we can complete init by calling ConfigMacREGS2. + */ + et131x_soft_reset(pAdapter); + + /* setup et1310 as per the documentation ?? */ + et131x_adapter_setup(pAdapter); + + /* Allow Tx to restart */ + MP_CLEAR_FLAG(pAdapter, fMP_ADAPTER_LOWER_POWER); + + /* Need to re-enable Rx. */ + et131x_rx_dma_enable(pAdapter); + + DBG_LEAVE(et131x_dbginfo); +} + diff --git a/drivers/staging/et131x/et1310_pm.h b/drivers/staging/et131x/et1310_pm.h new file mode 100644 index 000000000000..6802338e29d9 --- /dev/null +++ b/drivers/staging/et131x/et1310_pm.h @@ -0,0 +1,125 @@ +/* + * Agere Systems Inc. + * 10/100/1000 Base-T Ethernet Driver for the ET1301 and ET131x series MACs + * + * Copyright © 2005 Agere Systems Inc. + * All rights reserved. + * http://www.agere.com + * + *------------------------------------------------------------------------------ + * + * et1310_pm.h - Defines, structs, enums, prototypes, etc. pertaining to power + * management. + * + *------------------------------------------------------------------------------ + * + * SOFTWARE LICENSE + * + * This software is provided subject to the following terms and conditions, + * which you should read carefully before using the software. Using this + * software indicates your acceptance of these terms and conditions. If you do + * not agree with these terms and conditions, do not use the software. + * + * Copyright © 2005 Agere Systems Inc. + * All rights reserved. + * + * Redistribution and use in source or binary forms, with or without + * modifications, are permitted provided that the following conditions are met: + * + * . Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following Disclaimer as comments in the code as + * well as in the documentation and/or other materials provided with the + * distribution. + * + * . Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following Disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * . Neither the name of Agere Systems Inc. nor the names of the contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * Disclaimer + * + * THIS SOFTWARE IS PROVIDED “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, INFRINGEMENT AND THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ANY + * USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE IS SOLELY AT THE USERS OWN + * RISK. IN NO EVENT SHALL AGERE SYSTEMS INC. OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, INCLUDING, BUT NOT LIMITED TO, CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + */ + +#ifndef _ET1310_PM_H_ +#define _ET1310_PM_H_ + +#include "et1310_address_map.h" + +#define MAX_WOL_PACKET_SIZE 0x80 +#define MAX_WOL_MASK_SIZE ( MAX_WOL_PACKET_SIZE / 8 ) +#define NUM_WOL_PATTERNS 0x5 +#define CRC16_POLY 0x1021 + +/* Definition of NDIS_DEVICE_POWER_STATE */ +typedef enum { + NdisDeviceStateUnspecified = 0, + NdisDeviceStateD0, + NdisDeviceStateD1, + NdisDeviceStateD2, + NdisDeviceStateD3 +} NDIS_DEVICE_POWER_STATE; + +typedef struct _MP_POWER_MGMT { + /* variable putting the phy into coma mode when boot up with no cable + * plugged in after 5 seconds + */ + u8 TransPhyComaModeOnBoot; + + /* Array holding the five CRC values that the device is currently + * using for WOL. This will be queried when a pattern is to be + * removed. + */ + u32 localWolAndCrc0; + u16 WOLPatternList[NUM_WOL_PATTERNS]; + u8 WOLMaskList[NUM_WOL_PATTERNS][MAX_WOL_MASK_SIZE]; + u32 WOLMaskSize[NUM_WOL_PATTERNS]; + + /* IP address */ + union { + u32 u32; + u8 u8[4]; + } IPAddress; + + /* Current Power state of the adapter. */ + NDIS_DEVICE_POWER_STATE PowerState; + bool WOLState; + bool WOLEnabled; + bool Failed10Half; + bool bFailedStateTransition; + + /* Next two used to save power information at power down. This + * information will be used during power up to set up parts of Power + * Management in JAGCore + */ + u32 tx_en; + u32 rx_en; + u16 PowerDownSpeed; + u8 PowerDownDuplex; +} MP_POWER_MGMT, *PMP_POWER_MGMT; + +/* Forward declaration of the private adapter structure + * ( IS THERE A WAY TO DO THIS WITH A TYPEDEF??? ) + */ +struct et131x_adapter; + +u16 CalculateCCITCRC16(u8 *Pattern, u8 *Mask, u32 MaskSize); +void EnablePhyComa(struct et131x_adapter *adapter); +void DisablePhyComa(struct et131x_adapter *adapter); + +#endif /* _ET1310_PM_H_ */ diff --git a/drivers/staging/et131x/et1310_rx.c b/drivers/staging/et131x/et1310_rx.c new file mode 100644 index 000000000000..ec98da5da5bc --- /dev/null +++ b/drivers/staging/et131x/et1310_rx.c @@ -0,0 +1,1391 @@ +/* + * Agere Systems Inc. + * 10/100/1000 Base-T Ethernet Driver for the ET1301 and ET131x series MACs + * + * Copyright © 2005 Agere Systems Inc. + * All rights reserved. + * http://www.agere.com + * + *------------------------------------------------------------------------------ + * + * et1310_rx.c - Routines used to perform data reception + * + *------------------------------------------------------------------------------ + * + * SOFTWARE LICENSE + * + * This software is provided subject to the following terms and conditions, + * which you should read carefully before using the software. Using this + * software indicates your acceptance of these terms and conditions. If you do + * not agree with these terms and conditions, do not use the software. + * + * Copyright © 2005 Agere Systems Inc. + * All rights reserved. + * + * Redistribution and use in source or binary forms, with or without + * modifications, are permitted provided that the following conditions are met: + * + * . Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following Disclaimer as comments in the code as + * well as in the documentation and/or other materials provided with the + * distribution. + * + * . Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following Disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * . Neither the name of Agere Systems Inc. nor the names of the contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * Disclaimer + * + * THIS SOFTWARE IS PROVIDED “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, INFRINGEMENT AND THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ANY + * USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE IS SOLELY AT THE USERS OWN + * RISK. IN NO EVENT SHALL AGERE SYSTEMS INC. OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, INCLUDING, BUT NOT LIMITED TO, CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + */ + +#include "et131x_version.h" +#include "et131x_debug.h" +#include "et131x_defs.h" + +#include <linux/pci.h> +#include <linux/init.h> +#include <linux/module.h> +#include <linux/types.h> +#include <linux/kernel.h> + +#include <linux/sched.h> +#include <linux/ptrace.h> +#include <linux/slab.h> +#include <linux/ctype.h> +#include <linux/string.h> +#include <linux/timer.h> +#include <linux/interrupt.h> +#include <linux/in.h> +#include <linux/delay.h> +#include <asm/io.h> +#include <asm/system.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 "et1310_phy.h" +#include "et1310_pm.h" +#include "et1310_jagcore.h" + +#include "et131x_adapter.h" +#include "et131x_initpci.h" + +#include "et1310_rx.h" + +/* Data for debugging facilities */ +#ifdef CONFIG_ET131X_DEBUG +extern dbg_info_t *et131x_dbginfo; +#endif /* CONFIG_ET131X_DEBUG */ + + +void nic_return_rfd(struct et131x_adapter *pAdapter, PMP_RFD pMpRfd); + +/** + * et131x_rx_dma_memory_alloc + * @adapter: pointer to our private adapter structure + * + * Returns 0 on success and errno on failure (as defined in errno.h) + * + * Allocates Free buffer ring 1 for sure, free buffer ring 0 if required, + * and the Packet Status Ring. + */ +int et131x_rx_dma_memory_alloc(struct et131x_adapter *adapter) +{ + uint32_t OuterLoop, InnerLoop; + uint32_t bufsize; + uint32_t pktStatRingSize, FBRChunkSize; + RX_RING_t *rx_ring; + + DBG_ENTER(et131x_dbginfo); + + /* Setup some convenience pointers */ + rx_ring = (RX_RING_t *) & adapter->RxRing; + + /* Alloc memory for the lookup table */ +#ifdef USE_FBR0 + rx_ring->Fbr[0] = kmalloc(sizeof(FBRLOOKUPTABLE), GFP_KERNEL); +#endif + + rx_ring->Fbr[1] = kmalloc(sizeof(FBRLOOKUPTABLE), GFP_KERNEL); + + /* The first thing we will do is configure the sizes of the buffer + * rings. These will change based on jumbo packet support. Larger + * jumbo packets increases the size of each entry in FBR0, and the + * number of entries in FBR0, while at the same time decreasing the + * number of entries in FBR1. + * + * FBR1 holds "large" frames, FBR0 holds "small" frames. If FBR1 + * entries are huge in order to accomodate a "jumbo" frame, then it + * will have less entries. Conversely, FBR1 will now be relied upon + * to carry more "normal" frames, thus it's entry size also increases + * and the number of entries goes up too (since it now carries + * "small" + "regular" packets. + * + * In this scheme, we try to maintain 512 entries between the two + * rings. Also, FBR1 remains a constant size - when it's size doubles + * the number of entries halves. FBR0 increases in size, however. + */ + + if (adapter->RegistryJumboPacket < 2048) { +#ifdef USE_FBR0 + rx_ring->Fbr0BufferSize = 256; + rx_ring->Fbr0NumEntries = 512; +#endif + rx_ring->Fbr1BufferSize = 2048; + rx_ring->Fbr1NumEntries = 512; + } else if (adapter->RegistryJumboPacket < 4096) { +#ifdef USE_FBR0 + rx_ring->Fbr0BufferSize = 512; + rx_ring->Fbr0NumEntries = 1024; +#endif + rx_ring->Fbr1BufferSize = 4096; + rx_ring->Fbr1NumEntries = 512; + } else { +#ifdef USE_FBR0 + rx_ring->Fbr0BufferSize = 1024; + rx_ring->Fbr0NumEntries = 768; +#endif + rx_ring->Fbr1BufferSize = 16384; + rx_ring->Fbr1NumEntries = 128; + } + +#ifdef USE_FBR0 + adapter->RxRing.PsrNumEntries = adapter->RxRing.Fbr0NumEntries + + adapter->RxRing.Fbr1NumEntries; +#else + adapter->RxRing.PsrNumEntries = adapter->RxRing.Fbr1NumEntries; +#endif + + /* Allocate an area of memory for Free Buffer Ring 1 */ + bufsize = (sizeof(FBR_DESC_t) * rx_ring->Fbr1NumEntries) + 0xfff; + rx_ring->pFbr1RingVa = pci_alloc_consistent(adapter->pdev, + bufsize, + &rx_ring->pFbr1RingPa); + if (!rx_ring->pFbr1RingVa) { + DBG_ERROR(et131x_dbginfo, + "Cannot alloc memory for Free Buffer Ring 1\n"); + DBG_LEAVE(et131x_dbginfo); + return -ENOMEM; + } + + /* Save physical address + * + * NOTE: pci_alloc_consistent(), used above to alloc DMA regions, + * ALWAYS returns SAC (32-bit) addresses. If DAC (64-bit) addresses + * are ever returned, make sure the high part is retrieved here + * before storing the adjusted address. + */ + rx_ring->Fbr1Realpa = rx_ring->pFbr1RingPa; + + /* Align Free Buffer Ring 1 on a 4K boundary */ + et131x_align_allocated_memory(adapter, + &rx_ring->Fbr1Realpa, + &rx_ring->Fbr1offset, 0x0FFF); + + rx_ring->pFbr1RingVa = (void *)((uint8_t *) rx_ring->pFbr1RingVa + + rx_ring->Fbr1offset); + +#ifdef USE_FBR0 + /* Allocate an area of memory for Free Buffer Ring 0 */ + bufsize = (sizeof(FBR_DESC_t) * rx_ring->Fbr0NumEntries) + 0xfff; + rx_ring->pFbr0RingVa = pci_alloc_consistent(adapter->pdev, + bufsize, + &rx_ring->pFbr0RingPa); + if (!rx_ring->pFbr0RingVa) { + DBG_ERROR(et131x_dbginfo, + "Cannot alloc memory for Free Buffer Ring 0\n"); + DBG_LEAVE(et131x_dbginfo); + return -ENOMEM; + } + + /* Save physical address + * + * NOTE: pci_alloc_consistent(), used above to alloc DMA regions, + * ALWAYS returns SAC (32-bit) addresses. If DAC (64-bit) addresses + * are ever returned, make sure the high part is retrieved here before + * storing the adjusted address. + */ + rx_ring->Fbr0Realpa = rx_ring->pFbr0RingPa; + + /* Align Free Buffer Ring 0 on a 4K boundary */ + et131x_align_allocated_memory(adapter, + &rx_ring->Fbr0Realpa, + &rx_ring->Fbr0offset, 0x0FFF); + + rx_ring->pFbr0RingVa = (void *)((uint8_t *) rx_ring->pFbr0RingVa + + rx_ring->Fbr0offset); +#endif + + for (OuterLoop = 0; OuterLoop < (rx_ring->Fbr1NumEntries / FBR_CHUNKS); + OuterLoop++) { + uint64_t Fbr1Offset; + uint64_t Fbr1TempPa; + uint32_t Fbr1Align; + + /* This code allocates an area of memory big enough for N + * free buffers + (buffer_size - 1) so that the buffers can + * be aligned on 4k boundaries. If each buffer were aligned + * to a buffer_size boundary, the effect would be to double + * the size of FBR0. By allocating N buffers at once, we + * reduce this overhead. + */ + if (rx_ring->Fbr1BufferSize > 4096) { + Fbr1Align = 4096; + } else { + Fbr1Align = rx_ring->Fbr1BufferSize; + } + + FBRChunkSize = + (FBR_CHUNKS * rx_ring->Fbr1BufferSize) + Fbr1Align - 1; + rx_ring->Fbr1MemVa[OuterLoop] = + pci_alloc_consistent(adapter->pdev, FBRChunkSize, + &rx_ring->Fbr1MemPa[OuterLoop]); + + if (!rx_ring->Fbr1MemVa[OuterLoop]) { + DBG_ERROR(et131x_dbginfo, "Could not alloc memory\n"); + DBG_LEAVE(et131x_dbginfo); + return -ENOMEM; + } + + /* See NOTE in "Save Physical Address" comment above */ + Fbr1TempPa = rx_ring->Fbr1MemPa[OuterLoop]; + + et131x_align_allocated_memory(adapter, + &Fbr1TempPa, + &Fbr1Offset, (Fbr1Align - 1)); + + for (InnerLoop = 0; InnerLoop < FBR_CHUNKS; InnerLoop++) { + uint32_t index = (OuterLoop * FBR_CHUNKS) + InnerLoop; + + /* Save the Virtual address of this index for quick + * access later + */ + rx_ring->Fbr[1]->Va[index] = + (uint8_t *) rx_ring->Fbr1MemVa[OuterLoop] + + (InnerLoop * rx_ring->Fbr1BufferSize) + Fbr1Offset; + + /* now store the physical address in the descriptor + * so the device can access it + */ + rx_ring->Fbr[1]->PAHigh[index] = + (uint32_t) (Fbr1TempPa >> 32); + rx_ring->Fbr[1]->PALow[index] = (uint32_t) Fbr1TempPa; + + Fbr1TempPa += rx_ring->Fbr1BufferSize; + + rx_ring->Fbr[1]->Buffer1[index] = + rx_ring->Fbr[1]->Va[index]; + rx_ring->Fbr[1]->Buffer2[index] = + rx_ring->Fbr[1]->Va[index] - 4; + } + } + +#ifdef USE_FBR0 + /* Same for FBR0 (if in use) */ + for (OuterLoop = 0; OuterLoop < (rx_ring->Fbr0NumEntries / FBR_CHUNKS); + OuterLoop++) { + uint64_t Fbr0Offset; + uint64_t Fbr0TempPa; + + FBRChunkSize = ((FBR_CHUNKS + 1) * rx_ring->Fbr0BufferSize) - 1; + rx_ring->Fbr0MemVa[OuterLoop] = + pci_alloc_consistent(adapter->pdev, FBRChunkSize, + &rx_ring->Fbr0MemPa[OuterLoop]); + + if (!rx_ring->Fbr0MemVa[OuterLoop]) { + DBG_ERROR(et131x_dbginfo, "Could not alloc memory\n"); + DBG_LEAVE(et131x_dbginfo); + return -ENOMEM; + } + + /* See NOTE in "Save Physical Address" comment above */ + Fbr0TempPa = rx_ring->Fbr0MemPa[OuterLoop]; + + et131x_align_allocated_memory(adapter, + &Fbr0TempPa, + &Fbr0Offset, + rx_ring->Fbr0BufferSize - 1); + + for (InnerLoop = 0; InnerLoop < FBR_CHUNKS; InnerLoop++) { + uint32_t index = (OuterLoop * FBR_CHUNKS) + InnerLoop; + + rx_ring->Fbr[0]->Va[index] = + (uint8_t *) rx_ring->Fbr0MemVa[OuterLoop] + + (InnerLoop * rx_ring->Fbr0BufferSize) + Fbr0Offset; + + rx_ring->Fbr[0]->PAHigh[index] = + (uint32_t) (Fbr0TempPa >> 32); + rx_ring->Fbr[0]->PALow[index] = (uint32_t) Fbr0TempPa; + + Fbr0TempPa += rx_ring->Fbr0BufferSize; + + rx_ring->Fbr[0]->Buffer1[index] = + rx_ring->Fbr[0]->Va[index]; + rx_ring->Fbr[0]->Buffer2[index] = + rx_ring->Fbr[0]->Va[index] - 4; + } + } +#endif + + /* Allocate an area of memory for FIFO of Packet Status ring entries */ + pktStatRingSize = + sizeof(PKT_STAT_DESC_t) * adapter->RxRing.PsrNumEntries; + + rx_ring->pPSRingVa = pci_alloc_consistent(adapter->pdev, + pktStatRingSize + 0x0fff, + &rx_ring->pPSRingPa); + + if (!rx_ring->pPSRingVa) { + DBG_ERROR(et131x_dbginfo, + "Cannot alloc memory for Packet Status Ring\n"); + DBG_LEAVE(et131x_dbginfo); + return -ENOMEM; + } + + /* Save physical address + * + * NOTE : pci_alloc_consistent(), used above to alloc DMA regions, + * ALWAYS returns SAC (32-bit) addresses. If DAC (64-bit) addresses + * are ever returned, make sure the high part is retrieved here before + * storing the adjusted address. + */ + rx_ring->pPSRingRealPa = rx_ring->pPSRingPa; + + /* Align Packet Status Ring on a 4K boundary */ + et131x_align_allocated_memory(adapter, + &rx_ring->pPSRingRealPa, + &rx_ring->pPSRingOffset, 0x0FFF); + + rx_ring->pPSRingVa = (void *)((uint8_t *) rx_ring->pPSRingVa + + rx_ring->pPSRingOffset); + + /* Allocate an area of memory for writeback of status information */ + rx_ring->pRxStatusVa = pci_alloc_consistent(adapter->pdev, + sizeof(RX_STATUS_BLOCK_t) + + 0x7, &rx_ring->pRxStatusPa); + if (!rx_ring->pRxStatusVa) { + DBG_ERROR(et131x_dbginfo, + "Cannot alloc memory for Status Block\n"); + DBG_LEAVE(et131x_dbginfo); + return -ENOMEM; + } + + /* Save physical address */ + rx_ring->RxStatusRealPA = rx_ring->pRxStatusPa; + + /* Align write back on an 8 byte boundary */ + et131x_align_allocated_memory(adapter, + &rx_ring->RxStatusRealPA, + &rx_ring->RxStatusOffset, 0x07); + + rx_ring->pRxStatusVa = (void *)((uint8_t *) rx_ring->pRxStatusVa + + rx_ring->RxStatusOffset); + rx_ring->NumRfd = NIC_DEFAULT_NUM_RFD; + + /* Recv + * pci_pool_create initializes a lookaside list. After successful + * creation, nonpaged fixed-size blocks can be allocated from and + * freed to the lookaside list. + * RFDs will be allocated from this pool. + */ + rx_ring->RecvLookaside = kmem_cache_create(adapter->netdev->name, + sizeof(MP_RFD), + 0, + SLAB_CACHE_DMA | + SLAB_HWCACHE_ALIGN, + NULL); + + MP_SET_FLAG(adapter, fMP_ADAPTER_RECV_LOOKASIDE); + + /* The RFDs are going to be put on lists later on, so initialize the + * lists now. + */ + INIT_LIST_HEAD(&rx_ring->RecvList); + INIT_LIST_HEAD(&rx_ring->RecvPendingList); + + DBG_LEAVE(et131x_dbginfo); + return 0; +} + +/** + * et131x_rx_dma_memory_free - Free all memory allocated within this module. + * @adapter: pointer to our private adapter structure + */ +void et131x_rx_dma_memory_free(struct et131x_adapter *adapter) +{ + uint32_t index; + uint32_t bufsize; + uint32_t pktStatRingSize; + PMP_RFD pMpRfd; + RX_RING_t *rx_ring; + + DBG_ENTER(et131x_dbginfo); + + /* Setup some convenience pointers */ + rx_ring = (RX_RING_t *) & adapter->RxRing; + + /* Free RFDs and associated packet descriptors */ + DBG_ASSERT(rx_ring->nReadyRecv == rx_ring->NumRfd); + + while (!list_empty(&rx_ring->RecvList)) { + pMpRfd = (MP_RFD *) list_entry(rx_ring->RecvList.next, + MP_RFD, list_node); + + list_del(&pMpRfd->list_node); + et131x_rfd_resources_free(adapter, pMpRfd); + } + + while (!list_empty(&rx_ring->RecvPendingList)) { + pMpRfd = (MP_RFD *) list_entry(rx_ring->RecvPendingList.next, + MP_RFD, list_node); + list_del(&pMpRfd->list_node); + et131x_rfd_resources_free(adapter, pMpRfd); + } + + /* Free Free Buffer Ring 1 */ + if (rx_ring->pFbr1RingVa) { + /* First the packet memory */ + for (index = 0; index < + (rx_ring->Fbr1NumEntries / FBR_CHUNKS); index++) { + if (rx_ring->Fbr1MemVa[index]) { + uint32_t Fbr1Align; + + if (rx_ring->Fbr1BufferSize > 4096) { + Fbr1Align = 4096; + } else { + Fbr1Align = rx_ring->Fbr1BufferSize; + } + + bufsize = + (rx_ring->Fbr1BufferSize * FBR_CHUNKS) + + Fbr1Align - 1; + + pci_free_consistent(adapter->pdev, + bufsize, + rx_ring->Fbr1MemVa[index], + rx_ring->Fbr1MemPa[index]); + + rx_ring->Fbr1MemVa[index] = NULL; + } + } + + /* Now the FIFO itself */ + rx_ring->pFbr1RingVa = (void *)((uint8_t *) rx_ring->pFbr1RingVa - + rx_ring->Fbr1offset); + + bufsize = + (sizeof(FBR_DESC_t) * rx_ring->Fbr1NumEntries) + 0xfff; + + pci_free_consistent(adapter->pdev, + bufsize, + rx_ring->pFbr1RingVa, rx_ring->pFbr1RingPa); + + rx_ring->pFbr1RingVa = NULL; + } + +#ifdef USE_FBR0 + /* Now the same for Free Buffer Ring 0 */ + if (rx_ring->pFbr0RingVa) { + /* First the packet memory */ + for (index = 0; index < + (rx_ring->Fbr0NumEntries / FBR_CHUNKS); index++) { + if (rx_ring->Fbr0MemVa[index]) { + bufsize = + (rx_ring->Fbr0BufferSize * + (FBR_CHUNKS + 1)) - 1; + + pci_free_consistent(adapter->pdev, + bufsize, + rx_ring->Fbr0MemVa[index], + rx_ring->Fbr0MemPa[index]); + + rx_ring->Fbr0MemVa[index] = NULL; + } + } + + /* Now the FIFO itself */ + rx_ring->pFbr0RingVa = (void *)((uint8_t *) rx_ring->pFbr0RingVa - + rx_ring->Fbr0offset); + + bufsize = + (sizeof(FBR_DESC_t) * rx_ring->Fbr0NumEntries) + 0xfff; + + pci_free_consistent(adapter->pdev, + bufsize, + rx_ring->pFbr0RingVa, rx_ring->pFbr0RingPa); + + rx_ring->pFbr0RingVa = NULL; + } +#endif + + /* Free Packet Status Ring */ + if (rx_ring->pPSRingVa) { + rx_ring->pPSRingVa = (void *)((uint8_t *) rx_ring->pPSRingVa - + rx_ring->pPSRingOffset); + + pktStatRingSize = + sizeof(PKT_STAT_DESC_t) * adapter->RxRing.PsrNumEntries; + + pci_free_consistent(adapter->pdev, + pktStatRingSize + 0x0fff, + rx_ring->pPSRingVa, rx_ring->pPSRingPa); + + rx_ring->pPSRingVa = NULL; + } + + /* Free area of memory for the writeback of status information */ + if (rx_ring->pRxStatusVa) { + rx_ring->pRxStatusVa = (void *)((uint8_t *) rx_ring->pRxStatusVa - + rx_ring->RxStatusOffset); + + pci_free_consistent(adapter->pdev, + sizeof(RX_STATUS_BLOCK_t) + 0x7, + rx_ring->pRxStatusVa, rx_ring->pRxStatusPa); + + rx_ring->pRxStatusVa = NULL; + } + + /* Free receive buffer pool */ + + /* Free receive packet pool */ + + /* Destroy the lookaside (RFD) pool */ + if (MP_TEST_FLAG(adapter, fMP_ADAPTER_RECV_LOOKASIDE)) { + kmem_cache_destroy(rx_ring->RecvLookaside); + MP_CLEAR_FLAG(adapter, fMP_ADAPTER_RECV_LOOKASIDE); + } + + /* Free the FBR Lookup Table */ +#ifdef USE_FBR0 + kfree(rx_ring->Fbr[0]); +#endif + + kfree(rx_ring->Fbr[1]); + + /* Reset Counters */ + rx_ring->nReadyRecv = 0; + + DBG_LEAVE(et131x_dbginfo); +} + +/** + * et131x_init_recv - Initialize receive data structures. + * @adapter: pointer to our private adapter structure + * + * Returns 0 on success and errno on failure (as defined in errno.h) + */ +int et131x_init_recv(struct et131x_adapter *adapter) +{ + int status = -ENOMEM; + PMP_RFD pMpRfd = NULL; + uint32_t RfdCount; + uint32_t TotalNumRfd = 0; + RX_RING_t *rx_ring = NULL; + + DBG_ENTER(et131x_dbginfo); + + /* Setup some convenience pointers */ + rx_ring = (RX_RING_t *) & adapter->RxRing; + + /* Setup each RFD */ + for (RfdCount = 0; RfdCount < rx_ring->NumRfd; RfdCount++) { + pMpRfd = (MP_RFD *) kmem_cache_alloc(rx_ring->RecvLookaside, + GFP_ATOMIC | GFP_DMA); + + if (!pMpRfd) { + DBG_ERROR(et131x_dbginfo, + "Couldn't alloc RFD out of kmem_cache\n"); + status = -ENOMEM; + continue; + } + + status = et131x_rfd_resources_alloc(adapter, pMpRfd); + if (status != 0) { + DBG_ERROR(et131x_dbginfo, + "Couldn't alloc packet for RFD\n"); + kmem_cache_free(rx_ring->RecvLookaside, pMpRfd); + continue; + } + + /* Add this RFD to the RecvList */ + list_add_tail(&pMpRfd->list_node, &rx_ring->RecvList); + + /* Increment both the available RFD's, and the total RFD's. */ + rx_ring->nReadyRecv++; + TotalNumRfd++; + } + + if (TotalNumRfd > NIC_MIN_NUM_RFD) { + status = 0; + } + + rx_ring->NumRfd = TotalNumRfd; + + if (status != 0) { + kmem_cache_free(rx_ring->RecvLookaside, pMpRfd); + DBG_ERROR(et131x_dbginfo, + "Allocation problems in et131x_init_recv\n"); + } + + DBG_LEAVE(et131x_dbginfo); + return status; +} + +/** + * et131x_rfd_resources_alloc + * @adapter: pointer to our private adapter structure + * @pMpRfd: pointer to a RFD + * + * Returns 0 on success and errno on failure (as defined in errno.h) + */ +int et131x_rfd_resources_alloc(struct et131x_adapter *adapter, MP_RFD *pMpRfd) +{ + pMpRfd->Packet = NULL; + + return 0; +} + +/** + * et131x_rfd_resources_free - Free the packet allocated for the given RFD + * @adapter: pointer to our private adapter structure + * @pMpRfd: pointer to a RFD + */ +void et131x_rfd_resources_free(struct et131x_adapter *adapter, MP_RFD *pMpRfd) +{ + pMpRfd->Packet = NULL; + kmem_cache_free(adapter->RxRing.RecvLookaside, pMpRfd); +} + +/** + * ConfigRxDmaRegs - Start of Rx_DMA init sequence + * @pAdapter: pointer to our adapter structure + */ +void ConfigRxDmaRegs(struct et131x_adapter *pAdapter) +{ + struct _RXDMA_t __iomem *pRxDma = &pAdapter->CSRAddress->rxdma; + struct _rx_ring_t *pRxLocal = &pAdapter->RxRing; + PFBR_DESC_t pFbrEntry; + uint32_t iEntry; + RXDMA_PSR_NUM_DES_t psr_num_des; + unsigned long lockflags; + + DBG_ENTER(et131x_dbginfo); + + /* Halt RXDMA to perform the reconfigure. */ + et131x_rx_dma_disable(pAdapter); + + /* Load the completion writeback physical address + * + * NOTE : pci_alloc_consistent(), used above to alloc DMA regions, + * ALWAYS returns SAC (32-bit) addresses. If DAC (64-bit) addresses + * are ever returned, make sure the high part is retrieved here + * before storing the adjusted address. + */ + writel((uint32_t) (pRxLocal->RxStatusRealPA >> 32), + &pRxDma->dma_wb_base_hi); + writel((uint32_t) pRxLocal->RxStatusRealPA, &pRxDma->dma_wb_base_lo); + + memset(pRxLocal->pRxStatusVa, 0, sizeof(RX_STATUS_BLOCK_t)); + + /* Set the address and parameters of the packet status ring into the + * 1310's registers + */ + writel((uint32_t) (pRxLocal->pPSRingRealPa >> 32), + &pRxDma->psr_base_hi); + writel((uint32_t) pRxLocal->pPSRingRealPa, &pRxDma->psr_base_lo); + writel(pRxLocal->PsrNumEntries - 1, &pRxDma->psr_num_des.value); + writel(0, &pRxDma->psr_full_offset.value); + + psr_num_des.value = readl(&pRxDma->psr_num_des.value); + writel((psr_num_des.bits.psr_ndes * LO_MARK_PERCENT_FOR_PSR) / 100, + &pRxDma->psr_min_des.value); + + spin_lock_irqsave(&pAdapter->RcvLock, lockflags); + + /* These local variables track the PSR in the adapter structure */ + pRxLocal->local_psr_full.bits.psr_full = 0; + pRxLocal->local_psr_full.bits.psr_full_wrap = 0; + + /* Now's the best time to initialize FBR1 contents */ + pFbrEntry = (PFBR_DESC_t) pRxLocal->pFbr1RingVa; + for (iEntry = 0; iEntry < pRxLocal->Fbr1NumEntries; iEntry++) { + pFbrEntry->addr_hi = pRxLocal->Fbr[1]->PAHigh[iEntry]; + pFbrEntry->addr_lo = pRxLocal->Fbr[1]->PALow[iEntry]; + pFbrEntry->word2.bits.bi = iEntry; + pFbrEntry++; + } + + /* Set the address and parameters of Free buffer ring 1 (and 0 if + * required) into the 1310's registers + */ + writel((uint32_t) (pRxLocal->Fbr1Realpa >> 32), &pRxDma->fbr1_base_hi); + writel((uint32_t) pRxLocal->Fbr1Realpa, &pRxDma->fbr1_base_lo); + writel(pRxLocal->Fbr1NumEntries - 1, &pRxDma->fbr1_num_des.value); + + { + DMA10W_t fbr1_full = { 0 }; + + fbr1_full.bits.val = 0; + fbr1_full.bits.wrap = 1; + writel(fbr1_full.value, &pRxDma->fbr1_full_offset.value); + } + + /* This variable tracks the free buffer ring 1 full position, so it + * has to match the above. + */ + pRxLocal->local_Fbr1_full.bits.val = 0; + pRxLocal->local_Fbr1_full.bits.wrap = 1; + writel(((pRxLocal->Fbr1NumEntries * LO_MARK_PERCENT_FOR_RX) / 100) - 1, + &pRxDma->fbr1_min_des.value); + +#ifdef USE_FBR0 + /* Now's the best time to initialize FBR0 contents */ + pFbrEntry = (PFBR_DESC_t) pRxLocal->pFbr0RingVa; + for (iEntry = 0; iEntry < pRxLocal->Fbr0NumEntries; iEntry++) { + pFbrEntry->addr_hi = pRxLocal->Fbr[0]->PAHigh[iEntry]; + pFbrEntry->addr_lo = pRxLocal->Fbr[0]->PALow[iEntry]; + pFbrEntry->word2.bits.bi = iEntry; + pFbrEntry++; + } + + writel((uint32_t) (pRxLocal->Fbr0Realpa >> 32), &pRxDma->fbr0_base_hi); + writel((uint32_t) pRxLocal->Fbr0Realpa, &pRxDma->fbr0_base_lo); + writel(pRxLocal->Fbr0NumEntries - 1, &pRxDma->fbr0_num_des.value); + + { + DMA10W_t fbr0_full = { 0 }; + + fbr0_full.bits.val = 0; + fbr0_full.bits.wrap = 1; + writel(fbr0_full.value, &pRxDma->fbr0_full_offset.value); + } + + /* This variable tracks the free buffer ring 0 full position, so it + * has to match the above. + */ + pRxLocal->local_Fbr0_full.bits.val = 0; + pRxLocal->local_Fbr0_full.bits.wrap = 1; + writel(((pRxLocal->Fbr0NumEntries * LO_MARK_PERCENT_FOR_RX) / 100) - 1, + &pRxDma->fbr0_min_des.value); +#endif + + /* Program the number of packets we will receive before generating an + * interrupt. + * For version B silicon, this value gets updated once autoneg is + *complete. + */ + writel(pAdapter->RegistryRxNumBuffers, &pRxDma->num_pkt_done.value); + + /* The "time_done" is not working correctly to coalesce interrupts + * after a given time period, but rather is giving us an interrupt + * regardless of whether we have received packets. + * This value gets updated once autoneg is complete. + */ + writel(pAdapter->RegistryRxTimeInterval, &pRxDma->max_pkt_time.value); + + spin_unlock_irqrestore(&pAdapter->RcvLock, lockflags); + + DBG_LEAVE(et131x_dbginfo); +} + +/** + * SetRxDmaTimer - Set the heartbeat timer according to line rate. + * @pAdapter: pointer to our adapter structure + */ +void SetRxDmaTimer(struct et131x_adapter *pAdapter) +{ + /* For version B silicon, we do not use the RxDMA timer for 10 and 100 + * Mbits/s line rates. We do not enable and RxDMA interrupt coalescing. + */ + if ((pAdapter->uiLinkSpeed == TRUEPHY_SPEED_100MBPS) || + (pAdapter->uiLinkSpeed == TRUEPHY_SPEED_10MBPS)) { + writel(0, &pAdapter->CSRAddress->rxdma.max_pkt_time.value); + writel(1, &pAdapter->CSRAddress->rxdma.num_pkt_done.value); + } +} + +/** + * et131x_rx_dma_disable - Stop of Rx_DMA on the ET1310 + * @pAdapter: pointer to our adapter structure + */ +void et131x_rx_dma_disable(struct et131x_adapter *pAdapter) +{ + RXDMA_CSR_t csr; + + DBG_ENTER(et131x_dbginfo); + + /* Setup the receive dma configuration register */ + writel(0x00002001, &pAdapter->CSRAddress->rxdma.csr.value); + csr.value = readl(&pAdapter->CSRAddress->rxdma.csr.value); + if (csr.bits.halt_status != 1) { + udelay(5); + csr.value = readl(&pAdapter->CSRAddress->rxdma.csr.value); + if (csr.bits.halt_status != 1) { + DBG_ERROR(et131x_dbginfo, + "RX Dma failed to enter halt state. CSR 0x%08x\n", + csr.value); + } + } + + DBG_LEAVE(et131x_dbginfo); +} + +/** + * et131x_rx_dma_enable - re-start of Rx_DMA on the ET1310. + * @pAdapter: pointer to our adapter structure + */ +void et131x_rx_dma_enable(struct et131x_adapter *pAdapter) +{ + DBG_RX_ENTER(et131x_dbginfo); + + if (pAdapter->RegistryPhyLoopbk) { + /* RxDMA is disabled for loopback operation. */ + writel(0x1, &pAdapter->CSRAddress->rxdma.csr.value); + } else { + /* Setup the receive dma configuration register for normal operation */ + RXDMA_CSR_t csr = { 0 }; + + csr.bits.fbr1_enable = 1; + if (pAdapter->RxRing.Fbr1BufferSize == 4096) { + csr.bits.fbr1_size = 1; + } else if (pAdapter->RxRing.Fbr1BufferSize == 8192) { + csr.bits.fbr1_size = 2; + } else if (pAdapter->RxRing.Fbr1BufferSize == 16384) { + csr.bits.fbr1_size = 3; + } +#ifdef USE_FBR0 + csr.bits.fbr0_enable = 1; + if (pAdapter->RxRing.Fbr0BufferSize == 256) { + csr.bits.fbr0_size = 1; + } else if (pAdapter->RxRing.Fbr0BufferSize == 512) { + csr.bits.fbr0_size = 2; + } else if (pAdapter->RxRing.Fbr0BufferSize == 1024) { + csr.bits.fbr0_size = 3; + } +#endif + writel(csr.value, &pAdapter->CSRAddress->rxdma.csr.value); + + csr.value = readl(&pAdapter->CSRAddress->rxdma.csr.value); + if (csr.bits.halt_status != 0) { + udelay(5); + csr.value = readl(&pAdapter->CSRAddress->rxdma.csr.value); + if (csr.bits.halt_status != 0) { + DBG_ERROR(et131x_dbginfo, + "RX Dma failed to exit halt state. CSR 0x%08x\n", + csr.value); + } + } + } + + DBG_RX_LEAVE(et131x_dbginfo); +} + +/** + * nic_rx_pkts - Checks the hardware for available packets + * @pAdapter: pointer to our adapter + * + * Returns pMpRfd, a pointer to our MPRFD. + * + * Checks the hardware for available packets, using completion ring + * If packets are available, it gets an RFD from the RecvList, attaches + * the packet to it, puts the RFD in the RecvPendList, and also returns + * the pointer to the RFD. + */ +PMP_RFD nic_rx_pkts(struct et131x_adapter *pAdapter) +{ + struct _rx_ring_t *pRxLocal = &pAdapter->RxRing; + PRX_STATUS_BLOCK_t pRxStatusBlock; + PPKT_STAT_DESC_t pPSREntry; + PMP_RFD pMpRfd; + uint32_t nIndex; + uint8_t *pBufVa; + unsigned long lockflags; + struct list_head *element; + uint8_t ringIndex; + uint16_t bufferIndex; + uint32_t localLen; + PKT_STAT_DESC_WORD0_t Word0; + + + DBG_RX_ENTER(et131x_dbginfo); + + /* RX Status block is written by the DMA engine prior to every + * interrupt. It contains the next to be used entry in the Packet + * Status Ring, and also the two Free Buffer rings. + */ + pRxStatusBlock = (PRX_STATUS_BLOCK_t) pRxLocal->pRxStatusVa; + + if (pRxStatusBlock->Word1.bits.PSRoffset == + pRxLocal->local_psr_full.bits.psr_full && + pRxStatusBlock->Word1.bits.PSRwrap == + pRxLocal->local_psr_full.bits.psr_full_wrap) { + /* Looks like this ring is not updated yet */ + DBG_RX(et131x_dbginfo, "(0)\n"); + DBG_RX_LEAVE(et131x_dbginfo); + return NULL; + } + + /* The packet status ring indicates that data is available. */ + pPSREntry = (PPKT_STAT_DESC_t) (pRxLocal->pPSRingVa) + + pRxLocal->local_psr_full.bits.psr_full; + + /* Grab any information that is required once the PSR is + * advanced, since we can no longer rely on the memory being + * accurate + */ + localLen = pPSREntry->word1.bits.length; + ringIndex = (uint8_t) pPSREntry->word1.bits.ri; + bufferIndex = (uint16_t) pPSREntry->word1.bits.bi; + Word0 = pPSREntry->word0; + + DBG_RX(et131x_dbginfo, "RX PACKET STATUS\n"); + DBG_RX(et131x_dbginfo, "\tlength : %d\n", localLen); + DBG_RX(et131x_dbginfo, "\tringIndex : %d\n", ringIndex); + DBG_RX(et131x_dbginfo, "\tbufferIndex : %d\n", bufferIndex); + DBG_RX(et131x_dbginfo, "\tword0 : 0x%08x\n", Word0.value); + +#if 0 + /* Check the Status Word that the MAC has appended to the PSR + * entry in case the MAC has detected errors. + */ + if (Word0.value & ALCATEL_BAD_STATUS) { + DBG_ERROR(et131x_dbginfo, + "NICRxPkts >> Alcatel Status Word error." + "Value 0x%08x\n", pPSREntry->word0.value); + } +#endif + + /* Indicate that we have used this PSR entry. */ + if (++pRxLocal->local_psr_full.bits.psr_full > + pRxLocal->PsrNumEntries - 1) { + pRxLocal->local_psr_full.bits.psr_full = 0; + pRxLocal->local_psr_full.bits.psr_full_wrap ^= 1; + } + + writel(pRxLocal->local_psr_full.value, + &pAdapter->CSRAddress->rxdma.psr_full_offset.value); + +#ifndef USE_FBR0 + if (ringIndex != 1) { + DBG_ERROR(et131x_dbginfo, + "NICRxPkts PSR Entry %d indicates " + "Buffer Ring 0 in use\n", + pRxLocal->local_psr_full.bits.psr_full); + DBG_RX_LEAVE(et131x_dbginfo); + return NULL; + } +#endif + +#ifdef USE_FBR0 + if (ringIndex > 1 || + (ringIndex == 0 && + bufferIndex > pRxLocal->Fbr0NumEntries - 1) || + (ringIndex == 1 && + bufferIndex > pRxLocal->Fbr1NumEntries - 1)) +#else + if (ringIndex != 1 || + bufferIndex > pRxLocal->Fbr1NumEntries - 1) +#endif + { + /* Illegal buffer or ring index cannot be used by S/W*/ + DBG_ERROR(et131x_dbginfo, + "NICRxPkts PSR Entry %d indicates " + "length of %d and/or bad bi(%d)\n", + pRxLocal->local_psr_full.bits.psr_full, + localLen, bufferIndex); + DBG_RX_LEAVE(et131x_dbginfo); + return NULL; + } + + /* Get and fill the RFD. */ + spin_lock_irqsave(&pAdapter->RcvLock, lockflags); + + pMpRfd = NULL; + element = pRxLocal->RecvList.next; + pMpRfd = (PMP_RFD) list_entry(element, MP_RFD, list_node); + + if (pMpRfd == NULL) { + DBG_RX(et131x_dbginfo, + "NULL RFD returned from RecvList via list_entry()\n"); + DBG_RX_LEAVE(et131x_dbginfo); + spin_unlock_irqrestore(&pAdapter->RcvLock, lockflags); + return NULL; + } + + list_del(&pMpRfd->list_node); + pRxLocal->nReadyRecv--; + + spin_unlock_irqrestore(&pAdapter->RcvLock, lockflags); + + pMpRfd->iBufferIndex = bufferIndex; + pMpRfd->iRingIndex = ringIndex; + + /* In V1 silicon, there is a bug which screws up filtering of + * runt packets. Therefore runt packet filtering is disabled + * in the MAC and the packets are dropped here. They are + * also counted here. + */ + if (localLen < (NIC_MIN_PACKET_SIZE + 4)) { + pAdapter->Stats.other_errors++; + localLen = 0; + } + + if (localLen) { + if (pAdapter->ReplicaPhyLoopbk == 1) { + pBufVa = pRxLocal->Fbr[ringIndex]->Va[bufferIndex]; + + if (memcmp(&pBufVa[6], &pAdapter->CurrentAddress[0], + ETH_ALEN) == 0) { + if (memcmp(&pBufVa[42], "Replica packet", + ETH_HLEN)) { + pAdapter->ReplicaPhyLoopbkPF = 1; + } + } + DBG_WARNING(et131x_dbginfo, + "pBufVa:\t%02x:%02x:%02x:%02x:%02x:%02x\n", + pBufVa[6], pBufVa[7], pBufVa[8], + pBufVa[9], pBufVa[10], pBufVa[11]); + + DBG_WARNING(et131x_dbginfo, + "CurrentAddr:\t%02x:%02x:%02x:%02x:%02x:%02x\n", + pAdapter->CurrentAddress[0], + pAdapter->CurrentAddress[1], + pAdapter->CurrentAddress[2], + pAdapter->CurrentAddress[3], + pAdapter->CurrentAddress[4], + pAdapter->CurrentAddress[5]); + } + + /* Determine if this is a multicast packet coming in */ + if ((Word0.value & ALCATEL_MULTICAST_PKT) && + !(Word0.value & ALCATEL_BROADCAST_PKT)) { + /* Promiscuous mode and Multicast mode are + * not mutually exclusive as was first + * thought. I guess Promiscuous is just + * considered a super-set of the other + * filters. Generally filter is 0x2b when in + * promiscuous mode. + */ + if ((pAdapter->PacketFilter & ET131X_PACKET_TYPE_MULTICAST) + && !(pAdapter->PacketFilter & ET131X_PACKET_TYPE_PROMISCUOUS) + && !(pAdapter->PacketFilter & ET131X_PACKET_TYPE_ALL_MULTICAST)) { + pBufVa = pRxLocal->Fbr[ringIndex]-> + Va[bufferIndex]; + + /* Loop through our list to see if the + * destination address of this packet + * matches one in our list. + */ + for (nIndex = 0; + nIndex < pAdapter->MCAddressCount; + nIndex++) { + if (pBufVa[0] == + pAdapter->MCList[nIndex][0] + && pBufVa[1] == + pAdapter->MCList[nIndex][1] + && pBufVa[2] == + pAdapter->MCList[nIndex][2] + && pBufVa[3] == + pAdapter->MCList[nIndex][3] + && pBufVa[4] == + pAdapter->MCList[nIndex][4] + && pBufVa[5] == + pAdapter->MCList[nIndex][5]) { + break; + } + } + + /* If our index is equal to the number + * of Multicast address we have, then + * this means we did not find this + * packet's matching address in our + * list. Set the PacketSize to zero, + * so we free our RFD when we return + * from this function. + */ + if (nIndex == pAdapter->MCAddressCount) { + localLen = 0; + } + } + + if (localLen > 0) { + pAdapter->Stats.multircv++; + } + } else if (Word0.value & ALCATEL_BROADCAST_PKT) { + pAdapter->Stats.brdcstrcv++; + } else { + /* Not sure what this counter measures in + * promiscuous mode. Perhaps we should check + * the MAC address to see if it is directed + * to us in promiscuous mode. + */ + pAdapter->Stats.unircv++; + } + } + + if (localLen > 0) { + struct sk_buff *skb = NULL; + + //pMpRfd->PacketSize = localLen - 4; + pMpRfd->PacketSize = localLen; + + skb = dev_alloc_skb(pMpRfd->PacketSize + 2); + if (!skb) { + DBG_ERROR(et131x_dbginfo, + "Couldn't alloc an SKB for Rx\n"); + DBG_RX_LEAVE(et131x_dbginfo); + return NULL; + } + + pAdapter->net_stats.rx_bytes += pMpRfd->PacketSize; + + memcpy(skb_put(skb, pMpRfd->PacketSize), + pRxLocal->Fbr[ringIndex]->Va[bufferIndex], + pMpRfd->PacketSize); + + skb->dev = pAdapter->netdev; + skb->protocol = eth_type_trans(skb, pAdapter->netdev); + skb->ip_summed = CHECKSUM_NONE; + + netif_rx(skb); + } else { + pMpRfd->PacketSize = 0; + } + + nic_return_rfd(pAdapter, pMpRfd); + + DBG_RX(et131x_dbginfo, "(1)\n"); + DBG_RX_LEAVE(et131x_dbginfo); + return pMpRfd; +} + +/** + * et131x_reset_recv - Reset the receive list + * @pAdapter: pointer to our adapter + * + * Assumption, Rcv spinlock has been acquired. + */ +void et131x_reset_recv(struct et131x_adapter *pAdapter) +{ + PMP_RFD pMpRfd; + struct list_head *element; + + DBG_ENTER(et131x_dbginfo); + + DBG_ASSERT(!list_empty(&pAdapter->RxRing.RecvList)); + + /* Take all the RFD's from the pending list, and stick them on the + * RecvList. + */ + while (!list_empty(&pAdapter->RxRing.RecvPendingList)) { + element = pAdapter->RxRing.RecvPendingList.next; + + pMpRfd = (PMP_RFD) list_entry(element, MP_RFD, list_node); + + list_del(&pMpRfd->list_node); + list_add_tail(&pMpRfd->list_node, &pAdapter->RxRing.RecvList); + } + + DBG_LEAVE(et131x_dbginfo); +} + +/** + * et131x_handle_recv_interrupt - Interrupt handler for receive processing + * @pAdapter: pointer to our adapter + * + * Assumption, Rcv spinlock has been acquired. + */ +void et131x_handle_recv_interrupt(struct et131x_adapter *pAdapter) +{ + PMP_RFD pMpRfd = NULL; + struct sk_buff *PacketArray[NUM_PACKETS_HANDLED]; + PMP_RFD RFDFreeArray[NUM_PACKETS_HANDLED]; + uint32_t PacketArrayCount = 0; + uint32_t PacketsToHandle; + uint32_t PacketFreeCount = 0; + bool TempUnfinishedRec = false; + + DBG_RX_ENTER(et131x_dbginfo); + + PacketsToHandle = NUM_PACKETS_HANDLED; + + /* Process up to available RFD's */ + while (PacketArrayCount < PacketsToHandle) { + if (list_empty(&pAdapter->RxRing.RecvList)) { + DBG_ASSERT(pAdapter->RxRing.nReadyRecv == 0); + DBG_ERROR(et131x_dbginfo, "NO RFD's !!!!!!!!!!!!!\n"); + TempUnfinishedRec = true; + break; + } + + pMpRfd = nic_rx_pkts(pAdapter); + + if (pMpRfd == NULL) { + break; + } + + /* Do not receive any packets until a filter has been set. + * Do not receive any packets until we are at D0. + * Do not receive any packets until we have link. + * If length is zero, return the RFD in order to advance the + * Free buffer ring. + */ + if ((!pAdapter->PacketFilter) || + (pAdapter->PoMgmt.PowerState != NdisDeviceStateD0) || + (!MP_LINK_DETECTED(pAdapter)) || + (pMpRfd->PacketSize == 0)) { + continue; + } + + /* Increment the number of packets we received */ + pAdapter->Stats.ipackets++; + + /* Set the status on the packet, either resources or success */ + if (pAdapter->RxRing.nReadyRecv >= RFD_LOW_WATER_MARK) { + /* Put this RFD on the pending list + * + * NOTE: nic_rx_pkts() above is already returning the + * RFD to the RecvList, so don't additionally do that + * here. + * Besides, we don't really need (at this point) the + * pending list anyway. + */ + //spin_lock_irqsave( &pAdapter->RcvPendLock, lockflags ); + //list_add_tail( &pMpRfd->list_node, &pAdapter->RxRing.RecvPendingList ); + //spin_unlock_irqrestore( &pAdapter->RcvPendLock, lockflags ); + + /* Update the number of outstanding Recvs */ + //MP_INC_RCV_REF( pAdapter ); + } else { + RFDFreeArray[PacketFreeCount] = pMpRfd; + PacketFreeCount++; + + DBG_WARNING(et131x_dbginfo, + "RFD's are running out !!!!!!!!!!!!!\n"); + } + + PacketArray[PacketArrayCount] = pMpRfd->Packet; + PacketArrayCount++; + } + + if ((PacketArrayCount == NUM_PACKETS_HANDLED) || TempUnfinishedRec) { + pAdapter->RxRing.UnfinishedReceives = true; + writel(pAdapter->RegistryTxTimeInterval * NANO_IN_A_MICRO, + &pAdapter->CSRAddress->global.watchdog_timer); + } else { + /* Watchdog timer will disable itself if appropriate. */ + pAdapter->RxRing.UnfinishedReceives = false; + } + + DBG_RX_LEAVE(et131x_dbginfo); +} + +/** + * NICReturnRFD - Recycle a RFD and put it back onto the receive list + * @pAdapter: pointer to our adapter + * @pMpRfd: pointer to the RFD + */ +void nic_return_rfd(struct et131x_adapter *pAdapter, PMP_RFD pMpRfd) +{ + struct _rx_ring_t *pRxLocal = &pAdapter->RxRing; + struct _RXDMA_t __iomem *pRxDma = &pAdapter->CSRAddress->rxdma; + uint16_t bi = pMpRfd->iBufferIndex; + uint8_t ri = pMpRfd->iRingIndex; + unsigned long lockflags; + + DBG_RX_ENTER(et131x_dbginfo); + + /* We don't use any of the OOB data besides status. Otherwise, we + * need to clean up OOB data + */ + if ( +#ifdef USE_FBR0 + (ri == 0 && bi < pRxLocal->Fbr0NumEntries) || +#endif + (ri == 1 && bi < pRxLocal->Fbr1NumEntries)) { + spin_lock_irqsave(&pAdapter->FbrLock, lockflags); + + if (ri == 1) { + PFBR_DESC_t pNextDesc = + (PFBR_DESC_t) (pRxLocal->pFbr1RingVa) + + pRxLocal->local_Fbr1_full.bits.val; + + /* Handle the Free Buffer Ring advancement here. Write + * the PA / Buffer Index for the returned buffer into + * the oldest (next to be freed)FBR entry + */ + pNextDesc->addr_hi = pRxLocal->Fbr[1]->PAHigh[bi]; + pNextDesc->addr_lo = pRxLocal->Fbr[1]->PALow[bi]; + pNextDesc->word2.value = bi; + + if (++pRxLocal->local_Fbr1_full.bits.val > + (pRxLocal->Fbr1NumEntries - 1)) { + pRxLocal->local_Fbr1_full.bits.val = 0; + pRxLocal->local_Fbr1_full.bits.wrap ^= 1; + } + + writel(pRxLocal->local_Fbr1_full.value, + &pRxDma->fbr1_full_offset.value); + } +#ifdef USE_FBR0 + else { + PFBR_DESC_t pNextDesc = + (PFBR_DESC_t) pRxLocal->pFbr0RingVa + + pRxLocal->local_Fbr0_full.bits.val; + + /* Handle the Free Buffer Ring advancement here. Write + * the PA / Buffer Index for the returned buffer into + * the oldest (next to be freed) FBR entry + */ + pNextDesc->addr_hi = pRxLocal->Fbr[0]->PAHigh[bi]; + pNextDesc->addr_lo = pRxLocal->Fbr[0]->PALow[bi]; + pNextDesc->word2.value = bi; + + if (++pRxLocal->local_Fbr0_full.bits.val > + (pRxLocal->Fbr0NumEntries - 1)) { + pRxLocal->local_Fbr0_full.bits.val = 0; + pRxLocal->local_Fbr0_full.bits.wrap ^= 1; + } + + writel(pRxLocal->local_Fbr0_full.value, + &pRxDma->fbr0_full_offset.value); + } +#endif + spin_unlock_irqrestore(&pAdapter->FbrLock, lockflags); + } else { + DBG_ERROR(et131x_dbginfo, + "NICReturnRFD illegal Buffer Index returned\n"); + } + + /* The processing on this RFD is done, so put it back on the tail of + * our list + */ + spin_lock_irqsave(&pAdapter->RcvLock, lockflags); + list_add_tail(&pMpRfd->list_node, &pRxLocal->RecvList); + pRxLocal->nReadyRecv++; + spin_unlock_irqrestore(&pAdapter->RcvLock, lockflags); + + DBG_ASSERT(pRxLocal->nReadyRecv <= pRxLocal->NumRfd); + DBG_RX_LEAVE(et131x_dbginfo); +} diff --git a/drivers/staging/et131x/et1310_rx.h b/drivers/staging/et131x/et1310_rx.h new file mode 100644 index 000000000000..ea66dbcd8dfc --- /dev/null +++ b/drivers/staging/et131x/et1310_rx.h @@ -0,0 +1,373 @@ +/* + * Agere Systems Inc. + * 10/100/1000 Base-T Ethernet Driver for the ET1301 and ET131x series MACs + * + * Copyright © 2005 Agere Systems Inc. + * All rights reserved. + * http://www.agere.com + * + *------------------------------------------------------------------------------ + * + * et1310_rx.h - Defines, structs, enums, prototypes, etc. pertaining to data + * reception. + * + *------------------------------------------------------------------------------ + * + * SOFTWARE LICENSE + * + * This software is provided subject to the following terms and conditions, + * which you should read carefully before using the software. Using this + * software indicates your acceptance of these terms and conditions. If you do + * not agree with these terms and conditions, do not use the software. + * + * Copyright © 2005 Agere Systems Inc. + * All rights reserved. + * + * Redistribution and use in source or binary forms, with or without + * modifications, are permitted provided that the following conditions are met: + * + * . Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following Disclaimer as comments in the code as + * well as in the documentation and/or other materials provided with the + * distribution. + * + * . Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following Disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * . Neither the name of Agere Systems Inc. nor the names of the contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * Disclaimer + * + * THIS SOFTWARE IS PROVIDED “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, INFRINGEMENT AND THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ANY + * USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE IS SOLELY AT THE USERS OWN + * RISK. IN NO EVENT SHALL AGERE SYSTEMS INC. OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, INCLUDING, BUT NOT LIMITED TO, CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + */ + +#ifndef __ET1310_RX_H__ +#define __ET1310_RX_H__ + +#include "et1310_address_map.h" + +#define USE_FBR0 true + +#ifdef USE_FBR0 +//#define FBR0_BUFFER_SIZE 256 +#endif + +//#define FBR1_BUFFER_SIZE 2048 + +#define FBR_CHUNKS 32 + +#define MAX_DESC_PER_RING_RX 1024 + +/* number of RFDs - default and min */ +#ifdef USE_FBR0 +#define RFD_LOW_WATER_MARK 40 +#define NIC_MIN_NUM_RFD 64 +#define NIC_DEFAULT_NUM_RFD 1024 +#else +#define RFD_LOW_WATER_MARK 20 +#define NIC_MIN_NUM_RFD 64 +#define NIC_DEFAULT_NUM_RFD 256 +#endif + +#define NUM_PACKETS_HANDLED 256 + +#define ALCATEL_BAD_STATUS 0xe47f0000 +#define ALCATEL_MULTICAST_PKT 0x01000000 +#define ALCATEL_BROADCAST_PKT 0x02000000 + +/* typedefs for Free Buffer Descriptors */ +typedef union _FBR_WORD2_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 reserved:22; // bits 10-31 + u32 bi:10; // bits 0-9(Buffer Index) +#else + u32 bi:10; // bits 0-9(Buffer Index) + u32 reserved:22; // bit 10-31 +#endif + } bits; +} FBR_WORD2_t, *PFBR_WORD2_t; + +typedef struct _FBR_DESC_t { + u32 addr_lo; + u32 addr_hi; + FBR_WORD2_t word2; +} FBR_DESC_t, *PFBR_DESC_t; + +/* Typedefs for Packet Status Ring Descriptors */ +typedef union _PKT_STAT_DESC_WORD0_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + // top 16 bits are from the Alcatel Status Word as enumerated in + // PE-MCXMAC Data Sheet IPD DS54 0210-1 (also IPD-DS80 0205-2) +#if 0 + u32 asw_trunc:1; // bit 31(Rx frame truncated) +#endif + u32 asw_long_evt:1; // bit 31(Rx long event) + u32 asw_VLAN_tag:1; // bit 30(VLAN tag detected) + u32 asw_unsupported_op:1; // bit 29(unsupported OP code) + u32 asw_pause_frame:1; // bit 28(is a pause frame) + u32 asw_control_frame:1; // bit 27(is a control frame) + u32 asw_dribble_nibble:1; // bit 26(spurious bits after EOP) + u32 asw_broadcast:1; // bit 25(has a broadcast address) + u32 asw_multicast:1; // bit 24(has a multicast address) + u32 asw_OK:1; // bit 23(valid CRC + no code error) + u32 asw_too_long:1; // bit 22(frame length > 1518 bytes) + u32 asw_len_chk_err:1; // bit 21(frame length field incorrect) + u32 asw_CRC_err:1; // bit 20(CRC error) + u32 asw_code_err:1; // bit 19(one or more nibbles signalled as errors) + u32 asw_false_carrier_event:1; // bit 18(bad carrier since last good packet) + u32 asw_RX_DV_event:1; // bit 17(short receive event detected) + u32 asw_prev_pkt_dropped:1;// bit 16(e.g. IFG too small on previous) + u32 unused:5; // bits 11-15 + u32 vp:1; // bit 10(VLAN Packet) + u32 jp:1; // bit 9(Jumbo Packet) + u32 ft:1; // bit 8(Frame Truncated) + u32 drop:1; // bit 7(Drop packet) + u32 rxmac_error:1; // bit 6(RXMAC Error Indicator) + u32 wol:1; // bit 5(WOL Event) + u32 tcpp:1; // bit 4(TCP checksum pass) + u32 tcpa:1; // bit 3(TCP checksum assist) + u32 ipp:1; // bit 2(IP checksum pass) + u32 ipa:1; // bit 1(IP checksum assist) + u32 hp:1; // bit 0(hash pass) +#else + u32 hp:1; // bit 0(hash pass) + u32 ipa:1; // bit 1(IP checksum assist) + u32 ipp:1; // bit 2(IP checksum pass) + u32 tcpa:1; // bit 3(TCP checksum assist) + u32 tcpp:1; // bit 4(TCP checksum pass) + u32 wol:1; // bit 5(WOL Event) + u32 rxmac_error:1; // bit 6(RXMAC Error Indicator) + u32 drop:1; // bit 7(Drop packet) + u32 ft:1; // bit 8(Frame Truncated) + u32 jp:1; // bit 9(Jumbo Packet) + u32 vp:1; // bit 10(VLAN Packet) + u32 unused:5; // bits 11-15 + u32 asw_prev_pkt_dropped:1;// bit 16(e.g. IFG too small on previous) + u32 asw_RX_DV_event:1; // bit 17(short receive event detected) + u32 asw_false_carrier_event:1; // bit 18(bad carrier since last good packet) + u32 asw_code_err:1; // bit 19(one or more nibbles signalled as errors) + u32 asw_CRC_err:1; // bit 20(CRC error) + u32 asw_len_chk_err:1; // bit 21(frame length field incorrect) + u32 asw_too_long:1; // bit 22(frame length > 1518 bytes) + u32 asw_OK:1; // bit 23(valid CRC + no code error) + u32 asw_multicast:1; // bit 24(has a multicast address) + u32 asw_broadcast:1; // bit 25(has a broadcast address) + u32 asw_dribble_nibble:1; // bit 26(spurious bits after EOP) + u32 asw_control_frame:1; // bit 27(is a control frame) + u32 asw_pause_frame:1; // bit 28(is a pause frame) + u32 asw_unsupported_op:1; // bit 29(unsupported OP code) + u32 asw_VLAN_tag:1; // bit 30(VLAN tag detected) + u32 asw_long_evt:1; // bit 31(Rx long event) +#if 0 + u32 asw_trunc:1; // bit 31(Rx frame truncated) +#endif +#endif + } bits; +} PKT_STAT_DESC_WORD0_t, *PPKT_STAT_WORD0_t; + +typedef union _PKT_STAT_DESC_WORD1_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 unused:4; // bits 28-31 + u32 ri:2; // bits 26-27(Ring Index) + u32 bi:10; // bits 16-25(Buffer Index) + u32 length:16; // bit 0-15(length in bytes) +#else + u32 length:16; // bit 0-15(length in bytes) + u32 bi:10; // bits 16-25(Buffer Index) + u32 ri:2; // bits 26-27(Ring Index) + u32 unused:4; // bits 28-31 +#endif + } bits; +} PKT_STAT_DESC_WORD1_t, *PPKT_STAT_WORD1_t; + +typedef struct _PKT_STAT_DESC_t { + PKT_STAT_DESC_WORD0_t word0; + PKT_STAT_DESC_WORD1_t word1; +} PKT_STAT_DESC_t, *PPKT_STAT_DESC_t; + +/* Typedefs for the RX DMA status word */ + +/* + * RXSTAT_WORD0_t structure holds part of the status bits of the Rx DMA engine + * that get copied out to memory by the ET-1310. Word 0 is a 32 bit word + * whichcontains Free Buffer ring 0 and 1 available offset. + */ +typedef union _rxstat_word0_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 FBR1unused:5; // bits 27-31 + u32 FBR1wrap:1; // bit 26 + u32 FBR1offset:10; // bits 16-25 + u32 FBR0unused:5; // bits 11-15 + u32 FBR0wrap:1; // bit 10 + u32 FBR0offset:10; // bits 0-9 +#else + u32 FBR0offset:10; // bits 0-9 + u32 FBR0wrap:1; // bit 10 + u32 FBR0unused:5; // bits 11-15 + u32 FBR1offset:10; // bits 16-25 + u32 FBR1wrap:1; // bit 26 + u32 FBR1unused:5; // bits 27-31 +#endif + } bits; +} RXSTAT_WORD0_t, *PRXSTAT_WORD0_t; + +/* + * RXSTAT_WORD1_t structure holds part of the status bits of the Rx DMA engine + * that get copied out to memory by the ET-1310. Word 3 is a 32 bit word + * which contains the Packet Status Ring available offset. + */ +typedef union _rxstat_word1_t { + u32 value; + struct { +#ifdef _BIT_FIELDS_HTOL + u32 PSRunused:3; // bits 29-31 + u32 PSRwrap:1; // bit 28 + u32 PSRoffset:12; // bits 16-27 + u32 reserved:16; // bits 0-15 +#else + u32 reserved:16; // bits 0-15 + u32 PSRoffset:12; // bits 16-27 + u32 PSRwrap:1; // bit 28 + u32 PSRunused:3; // bits 29-31 +#endif + } bits; +} RXSTAT_WORD1_t, *PRXSTAT_WORD1_t; + +/* + * RX_STATUS_BLOCK_t is sructure representing the status of the Rx DMA engine + * it sits in free memory, and is pointed to by 0x101c / 0x1020 + */ +typedef struct _rx_status_block_t { + RXSTAT_WORD0_t Word0; + RXSTAT_WORD1_t Word1; +} RX_STATUS_BLOCK_t, *PRX_STATUS_BLOCK_t; + +/* + * Structure for look-up table holding free buffer ring pointers + */ +typedef struct _FbrLookupTable { + void *Va[MAX_DESC_PER_RING_RX]; + void *Buffer1[MAX_DESC_PER_RING_RX]; + void *Buffer2[MAX_DESC_PER_RING_RX]; + u32 PAHigh[MAX_DESC_PER_RING_RX]; + u32 PALow[MAX_DESC_PER_RING_RX]; +} FBRLOOKUPTABLE, *PFBRLOOKUPTABLE; + +typedef enum { + ONE_PACKET_INTERRUPT, + FOUR_PACKET_INTERRUPT +} eRX_INTERRUPT_STATE_t, *PeRX_INTERRUPT_STATE_t; + +/* + * Structure to hold the skb's in a list + */ +typedef struct rx_skb_list_elem { + struct list_head skb_list_elem; + dma_addr_t dma_addr; + struct sk_buff *skb; +} RX_SKB_LIST_ELEM, *PRX_SKB_LIST_ELEM; + +/* + * RX_RING_t is sructure representing the adaptor's local reference(s) to the + * rings + */ +typedef struct _rx_ring_t { +#ifdef USE_FBR0 + void *pFbr0RingVa; + dma_addr_t pFbr0RingPa; + void *Fbr0MemVa[MAX_DESC_PER_RING_RX / FBR_CHUNKS]; + dma_addr_t Fbr0MemPa[MAX_DESC_PER_RING_RX / FBR_CHUNKS]; + uint64_t Fbr0Realpa; + uint64_t Fbr0offset; + DMA10W_t local_Fbr0_full; + u32 Fbr0NumEntries; + u32 Fbr0BufferSize; +#endif + void *pFbr1RingVa; + dma_addr_t pFbr1RingPa; + void *Fbr1MemVa[MAX_DESC_PER_RING_RX / FBR_CHUNKS]; + dma_addr_t Fbr1MemPa[MAX_DESC_PER_RING_RX / FBR_CHUNKS]; + uint64_t Fbr1Realpa; + uint64_t Fbr1offset; + FBRLOOKUPTABLE *Fbr[2]; + DMA10W_t local_Fbr1_full; + u32 Fbr1NumEntries; + u32 Fbr1BufferSize; + + void *pPSRingVa; + dma_addr_t pPSRingPa; + uint64_t pPSRingRealPa; + uint64_t pPSRingOffset; + RXDMA_PSR_FULL_OFFSET_t local_psr_full; + u32 PsrNumEntries; + + void *pRxStatusVa; + dma_addr_t pRxStatusPa; + uint64_t RxStatusRealPA; + uint64_t RxStatusOffset; + + struct list_head RecvBufferPool; + + /* RECV */ + struct list_head RecvList; + struct list_head RecvPendingList; + u32 nReadyRecv; + + u32 NumRfd; + + bool UnfinishedReceives; + + struct list_head RecvPacketPool; + + /* lookaside lists */ + struct kmem_cache *RecvLookaside; +} RX_RING_t, *PRX_RING_t; + +/* Forward reference of RFD */ +struct _MP_RFD; + +/* Forward declaration of the private adapter structure */ +struct et131x_adapter; + +/* PROTOTYPES for Initialization */ +int et131x_rx_dma_memory_alloc(struct et131x_adapter *adapter); +void et131x_rx_dma_memory_free(struct et131x_adapter *adapter); +int et131x_rfd_resources_alloc(struct et131x_adapter *adapter, + struct _MP_RFD *pMpRfd); +void et131x_rfd_resources_free(struct et131x_adapter *adapter, + struct _MP_RFD *pMpRfd); +int et131x_init_recv(struct et131x_adapter *adapter); + +void ConfigRxDmaRegs(struct et131x_adapter *adapter); +void SetRxDmaTimer(struct et131x_adapter *adapter); +void et131x_rx_dma_disable(struct et131x_adapter *adapter); +void et131x_rx_dma_enable(struct et131x_adapter *adapter); + +void et131x_reset_recv(struct et131x_adapter *adapter); + +void et131x_handle_recv_interrupt(struct et131x_adapter *adapter); + +#endif /* __ET1310_RX_H__ */ diff --git a/drivers/staging/et131x/et1310_tx.c b/drivers/staging/et131x/et1310_tx.c new file mode 100644 index 000000000000..a95c2608a0c0 --- /dev/null +++ b/drivers/staging/et131x/et1310_tx.c @@ -0,0 +1,1525 @@ +/* + * Agere Systems Inc. + * 10/100/1000 Base-T Ethernet Driver for the ET1301 and ET131x series MACs + * + * Copyright © 2005 Agere Systems Inc. + * All rights reserved. + * http://www.agere.com + * + *------------------------------------------------------------------------------ + * + * et1310_tx.c - Routines used to perform data transmission. + * + *------------------------------------------------------------------------------ + * + * SOFTWARE LICENSE + * + * This software is provided subject to the following terms and conditions, + * which you should read carefully before using the software. Using this + * software indicates your acceptance of these terms and conditions. If you do + * not agree with these terms and conditions, do not use the software. + * + * Copyright © 2005 Agere Systems Inc. + * All rights reserved. + * + * Redistribution and use in source or binary forms, with or without + * modifications, are permitted provided that the following conditions are met: + * + * . Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following Disclaimer as comments in the code as + * well as in the documentation and/or other materials provided with the + * distribution. + * + * . Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following Disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * . Neither the name of Agere Systems Inc. nor the names of the contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * Disclaimer + * + * THIS SOFTWARE IS PROVIDED “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, INFRINGEMENT AND THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ANY + * USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE IS SOLELY AT THE USERS OWN + * RISK. IN NO EVENT SHALL AGERE SYSTEMS INC. OR CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, INCLUDING, BUT NOT LIMITED TO, CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + */ + +#include "et131x_version.h" +#include "et131x_debug.h" +#include "et131x_defs.h" + +#include <linux/pci.h> +#include <linux/init.h> +#include <linux/module.h> +#include <linux/types.h> +#include <linux/kernel.h> + +#include <linux/sched.h> +#include <linux/ptrace.h> +#include <linux/slab.h> +#include <linux/ctype.h> +#include <linux/string.h> +#include <linux/timer.h> +#include <linux/interrupt.h> +#include <linux/in.h> +#include <linux/delay.h> +#include <asm/io.h> +#include <asm/system.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 "et1310_phy.h" +#include "et1310_pm.h" +#include "et1310_jagcore.h" + +#include "et131x_adapter.h" +#include "et131x_initpci.h" +#include "et131x_isr.h" + +#include "et1310_tx.h" + +/* Data for debugging facilities */ +#ifdef CONFIG_ET131X_DEBUG +extern dbg_info_t *et131x_dbginfo; +#endif /* CONFIG_ET131X_DEBUG */ + +static void et131x_update_tcb_list(struct et131x_adapter *pAdapter); +static void et131x_check_send_wait_list(struct et131x_adapter *pAdapter); +static inline void et131x_free_send_packet(struct et131x_adapter *pAdapter, + PMP_TCB pMpTcb); +static int et131x_send_packet(struct sk_buff *skb, + struct et131x_adapter *pAdapter); +static int nic_send_packet(struct et131x_adapter *pAdapter, PMP_TCB pMpTcb); + +/** + * et131x_tx_dma_memory_alloc + * @adapter: pointer to our private adapter structure + * + * Returns 0 on success and errno on failure (as defined in errno.h). + * + * Allocates memory that will be visible both to the device and to the CPU. + * The OS will pass us packets, pointers to which we will insert in the Tx + * Descriptor queue. The device will read this queue to find the packets in + * memory. The device will update the "status" in memory each time it xmits a + * packet. + */ +int et131x_tx_dma_memory_alloc(struct et131x_adapter *adapter) +{ + int desc_size = 0; + TX_RING_t *tx_ring = &adapter->TxRing; + + DBG_ENTER(et131x_dbginfo); + + /* Allocate memory for the TCB's (Transmit Control Block) */ + adapter->TxRing.MpTcbMem = (MP_TCB *) kcalloc(NUM_TCB, sizeof(MP_TCB), + GFP_ATOMIC | GFP_DMA); + if (!adapter->TxRing.MpTcbMem) { + DBG_ERROR(et131x_dbginfo, "Cannot alloc memory for TCBs\n"); + DBG_LEAVE(et131x_dbginfo); + return -ENOMEM; + } + + /* Allocate enough memory for the Tx descriptor ring, and allocate + * some extra so that the ring can be aligned on a 4k boundary. + */ + desc_size = (sizeof(TX_DESC_ENTRY_t) * NUM_DESC_PER_RING_TX) + 4096 - 1; + tx_ring->pTxDescRingVa = + (PTX_DESC_ENTRY_t) pci_alloc_consistent(adapter->pdev, desc_size, + &tx_ring->pTxDescRingPa); + if (!adapter->TxRing.pTxDescRingVa) { + DBG_ERROR(et131x_dbginfo, "Cannot alloc memory for Tx Ring\n"); + DBG_LEAVE(et131x_dbginfo); + return -ENOMEM; + } + + /* Save physical address + * + * NOTE: pci_alloc_consistent(), used above to alloc DMA regions, + * ALWAYS returns SAC (32-bit) addresses. If DAC (64-bit) addresses + * are ever returned, make sure the high part is retrieved here before + * storing the adjusted address. + */ + tx_ring->pTxDescRingAdjustedPa = tx_ring->pTxDescRingPa; + + /* Align Tx Descriptor Ring on a 4k (0x1000) byte boundary */ + et131x_align_allocated_memory(adapter, + &tx_ring->pTxDescRingAdjustedPa, + &tx_ring->TxDescOffset, 0x0FFF); + + tx_ring->pTxDescRingVa += tx_ring->TxDescOffset; + + /* Allocate memory for the Tx status block */ + tx_ring->pTxStatusVa = pci_alloc_consistent(adapter->pdev, + sizeof(TX_STATUS_BLOCK_t), + &tx_ring->pTxStatusPa); + if (!adapter->TxRing.pTxStatusPa) { + DBG_ERROR(et131x_dbginfo, + "Cannot alloc memory for Tx status block\n"); + DBG_LEAVE(et131x_dbginfo); + return -ENOMEM; + } + + /* Allocate memory for a dummy buffer */ + tx_ring->pTxDummyBlkVa = pci_alloc_consistent(adapter->pdev, + NIC_MIN_PACKET_SIZE, + &tx_ring->pTxDummyBlkPa); + if (!adapter->TxRing.pTxDummyBlkPa) { + DBG_ERROR(et131x_dbginfo, + "Cannot alloc memory for Tx dummy buffer\n"); + DBG_LEAVE(et131x_dbginfo); + return -ENOMEM; + } + + DBG_LEAVE(et131x_dbginfo); + return 0; +} + +/** + * et131x_tx_dma_memory_free - Free all memory allocated within this module + * @adapter: pointer to our private adapter structure + * + * Returns 0 on success and errno on failure (as defined in errno.h). + */ +void et131x_tx_dma_memory_free(struct et131x_adapter *adapter) +{ + int desc_size = 0; + + DBG_ENTER(et131x_dbginfo); + + if (adapter->TxRing.pTxDescRingVa) { + /* Free memory relating to Tx rings here */ + adapter->TxRing.pTxDescRingVa -= adapter->TxRing.TxDescOffset; + + desc_size = + (sizeof(TX_DESC_ENTRY_t) * NUM_DESC_PER_RING_TX) + 4096 - 1; + + pci_free_consistent(adapter->pdev, + desc_size, + adapter->TxRing.pTxDescRingVa, + adapter->TxRing.pTxDescRingPa); + + adapter->TxRing.pTxDescRingVa = NULL; + } + + /* Free memory for the Tx status block */ + if (adapter->TxRing.pTxStatusVa) { + pci_free_consistent(adapter->pdev, + sizeof(TX_STATUS_BLOCK_t), + adapter->TxRing.pTxStatusVa, + adapter->TxRing.pTxStatusPa); + + adapter->TxRing.pTxStatusVa = NULL; + } + + /* Free memory for the dummy buffer */ + if (adapter->TxRing.pTxDummyBlkVa) { + pci_free_consistent(adapter->pdev, + NIC_MIN_PACKET_SIZE, + adapter->TxRing.pTxDummyBlkVa, + adapter->TxRing.pTxDummyBlkPa); + + adapter->TxRing.pTxDummyBlkVa = NULL; + } + + /* Free the memory for MP_TCB structures */ + if (adapter->TxRing.MpTcbMem) { + kfree(adapter->TxRing.MpTcbMem); + adapter->TxRing.MpTcbMem = NULL; + } + + DBG_LEAVE(et131x_dbginfo); +} + +/** + * ConfigTxDmaRegs - Set up the tx dma section of the JAGCore. + * @adapter: pointer to our private adapter structure + */ +void ConfigTxDmaRegs(struct et131x_adapter *pAdapter) +{ + struct _TXDMA_t __iomem *pTxDma = &pAdapter->CSRAddress->txdma; + + DBG_ENTER(et131x_dbginfo); + + /* Load the hardware with the start of the transmit descriptor ring. */ + writel((uint32_t) (pAdapter->TxRing.pTxDescRingAdjustedPa >> 32), + &pTxDma->pr_base_hi); + writel((uint32_t) pAdapter->TxRing.pTxDescRingAdjustedPa, + &pTxDma->pr_base_lo); + + /* Initialise the transmit DMA engine */ + writel(NUM_DESC_PER_RING_TX - 1, &pTxDma->pr_num_des.value); + + /* Load the completion writeback physical address + * + * NOTE: pci_alloc_consistent(), used above to alloc DMA regions, + * ALWAYS returns SAC (32-bit) addresses. If DAC (64-bit) addresses + * are ever returned, make sure the high part is retrieved here before + * storing the adjusted address. + */ + writel(0, &pTxDma->dma_wb_base_hi); + writel(pAdapter->TxRing.pTxStatusPa, &pTxDma->dma_wb_base_lo); + + memset(pAdapter->TxRing.pTxStatusVa, 0, sizeof(TX_STATUS_BLOCK_t)); + + writel(0, &pTxDma->service_request.value); + pAdapter->TxRing.txDmaReadyToSend.value = 0; + + DBG_LEAVE(et131x_dbginfo); +} + +/** + * et131x_tx_dma_disable - Stop of Tx_DMA on the ET1310 + * @pAdapter: pointer to our adapter structure + */ +void et131x_tx_dma_disable(struct et131x_adapter *pAdapter) +{ + DBG_ENTER(et131x_dbginfo); + + /* Setup the tramsmit dma configuration register */ + writel(0x101, &pAdapter->CSRAddress->txdma.csr.value); + + DBG_LEAVE(et131x_dbginfo); +} + +/** + * et131x_tx_dma_enable - re-start of Tx_DMA on the ET1310. + * @pAdapter: pointer to our adapter structure + * + * Mainly used after a return to the D0 (full-power) state from a lower state. + */ +void et131x_tx_dma_enable(struct et131x_adapter *pAdapter) +{ + DBG_ENTER(et131x_dbginfo); + + if (pAdapter->RegistryPhyLoopbk) { + /* TxDMA is disabled for loopback operation. */ + writel(0x101, &pAdapter->CSRAddress->txdma.csr.value); + } else { + TXDMA_CSR_t csr = { 0 }; + + /* Setup the transmit dma configuration register for normal + * operation + */ + csr.bits.sngl_epkt_mode = 1; + csr.bits.halt = 0; + csr.bits.cache_thrshld = pAdapter->RegistryDMACache; + writel(csr.value, &pAdapter->CSRAddress->txdma.csr.value); + } + + DBG_LEAVE(et131x_dbginfo); +} + +/** + * et131x_init_send - Initialize send data structures + * @adapter: pointer to our private adapter structure + */ +void et131x_init_send(struct et131x_adapter *adapter) +{ + PMP_TCB pMpTcb; + uint32_t TcbCount; + TX_RING_t *tx_ring; + + DBG_ENTER(et131x_dbginfo); + + /* Setup some convenience pointers */ + tx_ring = &adapter->TxRing; + pMpTcb = adapter->TxRing.MpTcbMem; + + tx_ring->TCBReadyQueueHead = pMpTcb; + + /* Go through and set up each TCB */ + for (TcbCount = 0; TcbCount < NUM_TCB; TcbCount++) { + memset(pMpTcb, 0, sizeof(MP_TCB)); + + /* Set the link pointer in HW TCB to the next TCB in the + * chain. If this is the last TCB in the chain, also set the + * tail pointer. + */ + if (TcbCount < NUM_TCB - 1) { + pMpTcb->Next = pMpTcb + 1; + } else { + tx_ring->TCBReadyQueueTail = pMpTcb; + pMpTcb->Next = (PMP_TCB) NULL; + } + + pMpTcb++; + } + + /* Curr send queue should now be empty */ + tx_ring->CurrSendHead = (PMP_TCB) NULL; + tx_ring->CurrSendTail = (PMP_TCB) NULL; + + INIT_LIST_HEAD(&adapter->TxRing.SendWaitQueue); + + DBG_LEAVE(et131x_dbginfo); +} + +/** + * et131x_send_packets - This function is called by the OS to send packets + * @skb: the packet(s) to send + * @netdev:device on which to TX the above packet(s) + * + * Return 0 in almost all cases; non-zero value in extreme hard failure only + */ +int et131x_send_packets(struct sk_buff *skb, struct net_device *netdev) +{ + int status = 0; + struct et131x_adapter *pAdapter = NULL; + + DBG_TX_ENTER(et131x_dbginfo); + + pAdapter = netdev_priv(netdev); + + /* Send these packets + * + * NOTE: The Linux Tx entry point is only given one packet at a time + * to Tx, so the PacketCount and it's array used makes no sense here + */ + + /* Queue is not empty or TCB is not available */ + if (!list_empty(&pAdapter->TxRing.SendWaitQueue) || + MP_TCB_RESOURCES_NOT_AVAILABLE(pAdapter)) { + /* NOTE: If there's an error on send, no need to queue the + * packet under Linux; if we just send an error up to the + * netif layer, it will resend the skb to us. + */ + DBG_VERBOSE(et131x_dbginfo, "TCB Resources Not Available\n"); + status = -ENOMEM; + } else { + /* We need to see if the link is up; if it's not, make the + * netif layer think we're good and drop the packet + */ + //if( MP_SHOULD_FAIL_SEND( pAdapter ) || pAdapter->DriverNoPhyAccess ) + if (MP_SHOULD_FAIL_SEND(pAdapter) || pAdapter->DriverNoPhyAccess + || !netif_carrier_ok(netdev)) { + DBG_VERBOSE(et131x_dbginfo, + "Can't Tx, Link is DOWN; drop the packet\n"); + + dev_kfree_skb_any(skb); + skb = NULL; + + pAdapter->net_stats.tx_dropped++; + } else { + status = et131x_send_packet(skb, pAdapter); + + if (status == -ENOMEM) { + + /* NOTE: If there's an error on send, no need + * to queue the packet under Linux; if we just + * send an error up to the netif layer, it + * will resend the skb to us. + */ + DBG_WARNING(et131x_dbginfo, + "Resources problem, Queue tx packet\n"); + } else if (status != 0) { + /* On any other error, make netif think we're + * OK and drop the packet + */ + DBG_WARNING(et131x_dbginfo, + "General error, drop packet\n"); + + dev_kfree_skb_any(skb); + skb = NULL; + + pAdapter->net_stats.tx_dropped++; + } + } + } + + DBG_TX_LEAVE(et131x_dbginfo); + return status; +} + +/** + * et131x_send_packet - Do the work to send a packet + * @skb: the packet(s) to send + * @pAdapter: a pointer to the device's private adapter structure + * + * Return 0 in almost all cases; non-zero value in extreme hard failure only. + * + * Assumption: Send spinlock has been acquired + */ +static int et131x_send_packet(struct sk_buff *skb, + struct et131x_adapter *pAdapter) +{ + int status = 0; + PMP_TCB pMpTcb = NULL; + uint16_t *pShBufVa; + unsigned long lockflags; + + DBG_TX_ENTER(et131x_dbginfo); + + /* Is our buffer scattered, or continuous? */ + if (skb_shinfo(skb)->nr_frags == 0) { + DBG_TX(et131x_dbginfo, "Scattered buffer: NO\n"); + } else { + DBG_TX(et131x_dbginfo, "Scattered buffer: YES, Num Frags: %d\n", + skb_shinfo(skb)->nr_frags); + } + + /* All packets must have at least a MAC address and a protocol type */ + if (skb->len < ETH_HLEN) { + DBG_ERROR(et131x_dbginfo, + "Packet size < ETH_HLEN (14 bytes)\n"); + DBG_LEAVE(et131x_dbginfo); + return -EIO; + } + + /* Get a TCB for this packet */ + spin_lock_irqsave(&pAdapter->TCBReadyQLock, lockflags); + + pMpTcb = pAdapter->TxRing.TCBReadyQueueHead; + + if (pMpTcb == NULL) { + spin_unlock_irqrestore(&pAdapter->TCBReadyQLock, lockflags); + + DBG_WARNING(et131x_dbginfo, "Can't obtain a TCB\n"); + DBG_TX_LEAVE(et131x_dbginfo); + return -ENOMEM; + } + + pAdapter->TxRing.TCBReadyQueueHead = pMpTcb->Next; + + if (pAdapter->TxRing.TCBReadyQueueHead == NULL) { + pAdapter->TxRing.TCBReadyQueueTail = NULL; + } + + spin_unlock_irqrestore(&pAdapter->TCBReadyQLock, lockflags); + + pMpTcb->PacketLength = skb->len; + pMpTcb->Packet = skb; + + if ((skb->data != NULL) && ((skb->len - skb->data_len) >= 6)) { + pShBufVa = (uint16_t *) skb->data; + + if ((pShBufVa[0] == 0xffff) && + (pShBufVa[1] == 0xffff) && (pShBufVa[2] == 0xffff)) { + MP_SET_FLAG(pMpTcb, fMP_DEST_BROAD); + } else if ((pShBufVa[0] & 0x3) == 0x0001) { + MP_SET_FLAG(pMpTcb, fMP_DEST_MULTI); + } + } + + pMpTcb->Next = NULL; + + /* Call the NIC specific send handler. */ + if (status == 0) { + status = nic_send_packet(pAdapter, pMpTcb); + } + + if (status != 0) { + spin_lock_irqsave(&pAdapter->TCBReadyQLock, lockflags); + + if (pAdapter->TxRing.TCBReadyQueueTail) { + pAdapter->TxRing.TCBReadyQueueTail->Next = pMpTcb; + } else { + /* Apparently ready Q is empty. */ + pAdapter->TxRing.TCBReadyQueueHead = pMpTcb; + } + + pAdapter->TxRing.TCBReadyQueueTail = pMpTcb; + + spin_unlock_irqrestore(&pAdapter->TCBReadyQLock, lockflags); + + DBG_TX_LEAVE(et131x_dbginfo); + return status; + } + + DBG_ASSERT(pAdapter->TxRing.nBusySend <= NUM_TCB); + + DBG_TX_LEAVE(et131x_dbginfo); + return 0; +} + +/** + * nic_send_packet - NIC specific send handler for version B silicon. + * @pAdapter: pointer to our adapter + * @pMpTcb: pointer to MP_TCB + * + * Returns 0 or errno. + */ +static int nic_send_packet(struct et131x_adapter *pAdapter, PMP_TCB pMpTcb) +{ + uint32_t loopIndex; + TX_DESC_ENTRY_t CurDesc[24]; + uint32_t FragmentNumber = 0; + uint32_t iThisCopy, iRemainder; + struct sk_buff *pPacket = pMpTcb->Packet; + uint32_t FragListCount = skb_shinfo(pPacket)->nr_frags + 1; + struct skb_frag_struct *pFragList = &skb_shinfo(pPacket)->frags[0]; + unsigned long lockflags1, lockflags2; + + DBG_TX_ENTER(et131x_dbginfo); + + /* Part of the optimizations of this send routine restrict us to + * sending 24 fragments at a pass. In practice we should never see + * more than 5 fragments. + * + * NOTE: The older version of this function (below) can handle any + * number of fragments. If needed, we can call this function, + * although it is less efficient. + */ + if (FragListCount > 23) { + DBG_TX_LEAVE(et131x_dbginfo); + return -EIO; + } + + memset(CurDesc, 0, sizeof(TX_DESC_ENTRY_t) * (FragListCount + 1)); + + for (loopIndex = 0; loopIndex < FragListCount; loopIndex++) { + /* If there is something in this element, lets get a + * descriptor from the ring and get the necessary data + */ + if (loopIndex == 0) { + /* If the fragments are smaller than a standard MTU, + * then map them to a single descriptor in the Tx + * Desc ring. However, if they're larger, as is + * possible with support for jumbo packets, then + * split them each across 2 descriptors. + * + * This will work until we determine why the hardware + * doesn't seem to like large fragments. + */ + if ((pPacket->len - pPacket->data_len) <= 1514) { + DBG_TX(et131x_dbginfo, + "Got packet of length %d, " + "filling desc entry %d, " + "TCB: 0x%p\n", + (pPacket->len - pPacket->data_len), + pAdapter->TxRing.txDmaReadyToSend.bits. + val, pMpTcb); + + CurDesc[FragmentNumber].DataBufferPtrHigh = 0; + + CurDesc[FragmentNumber].word2.bits. + length_in_bytes = + pPacket->len - pPacket->data_len; + + /* NOTE: Here, the dma_addr_t returned from + * pci_map_single() is implicitly cast as a + * uint32_t. Although dma_addr_t can be + * 64-bit, the address returned by + * pci_map_single() is always 32-bit + * addressable (as defined by the pci/dma + * subsystem) + */ + CurDesc[FragmentNumber++].DataBufferPtrLow = + pci_map_single(pAdapter->pdev, + pPacket->data, + pPacket->len - + pPacket->data_len, + PCI_DMA_TODEVICE); + } else { + DBG_TX(et131x_dbginfo, + "Got packet of length %d, " + "filling desc entry %d, " + "TCB: 0x%p\n", + (pPacket->len - pPacket->data_len), + pAdapter->TxRing.txDmaReadyToSend.bits. + val, pMpTcb); + + CurDesc[FragmentNumber].DataBufferPtrHigh = 0; + + CurDesc[FragmentNumber].word2.bits. + length_in_bytes = + ((pPacket->len - pPacket->data_len) / 2); + + /* NOTE: Here, the dma_addr_t returned from + * pci_map_single() is implicitly cast as a + * uint32_t. Although dma_addr_t can be + * 64-bit, the address returned by + * pci_map_single() is always 32-bit + * addressable (as defined by the pci/dma + * subsystem) + */ + CurDesc[FragmentNumber++].DataBufferPtrLow = + pci_map_single(pAdapter->pdev, + pPacket->data, + ((pPacket->len - + pPacket->data_len) / 2), + PCI_DMA_TODEVICE); + CurDesc[FragmentNumber].DataBufferPtrHigh = 0; + + CurDesc[FragmentNumber].word2.bits. + length_in_bytes = + ((pPacket->len - pPacket->data_len) / 2); + + /* NOTE: Here, the dma_addr_t returned from + * pci_map_single() is implicitly cast as a + * uint32_t. Although dma_addr_t can be + * 64-bit, the address returned by + * pci_map_single() is always 32-bit + * addressable (as defined by the pci/dma + * subsystem) + */ + CurDesc[FragmentNumber++].DataBufferPtrLow = + pci_map_single(pAdapter->pdev, + pPacket->data + + ((pPacket->len - + pPacket->data_len) / 2), + ((pPacket->len - + pPacket->data_len) / 2), + PCI_DMA_TODEVICE); + } + } else { + DBG_TX(et131x_dbginfo, + "Got packet of length %d," + "filling desc entry %d\n" + "TCB: 0x%p\n", + pFragList[loopIndex].size, + pAdapter->TxRing.txDmaReadyToSend.bits.val, + pMpTcb); + + CurDesc[FragmentNumber].DataBufferPtrHigh = 0; + + CurDesc[FragmentNumber].word2.bits.length_in_bytes = + pFragList[loopIndex - 1].size; + + /* NOTE: Here, the dma_addr_t returned from + * pci_map_page() is implicitly cast as a uint32_t. + * Although dma_addr_t can be 64-bit, the address + * returned by pci_map_page() is always 32-bit + * addressable (as defined by the pci/dma subsystem) + */ + CurDesc[FragmentNumber++].DataBufferPtrLow = + pci_map_page(pAdapter->pdev, + pFragList[loopIndex - 1].page, + pFragList[loopIndex - 1].page_offset, + pFragList[loopIndex - 1].size, + PCI_DMA_TODEVICE); + } + } + + if (FragmentNumber == 0) { + DBG_WARNING(et131x_dbginfo, "No. frags is 0\n"); + return -EIO; + } + + if (pAdapter->uiLinkSpeed == TRUEPHY_SPEED_1000MBPS) { + if (++pAdapter->TxRing.TxPacketsSinceLastinterrupt == + pAdapter->RegistryTxNumBuffers) { + CurDesc[FragmentNumber - 1].word3.value = 0x5; + pAdapter->TxRing.TxPacketsSinceLastinterrupt = 0; + } else { + CurDesc[FragmentNumber - 1].word3.value = 0x1; + } + } else { + CurDesc[FragmentNumber - 1].word3.value = 0x5; + } + + CurDesc[0].word3.bits.f = 1; + + pMpTcb->WrIndexStart = pAdapter->TxRing.txDmaReadyToSend; + pMpTcb->PacketStaleCount = 0; + + spin_lock_irqsave(&pAdapter->SendHWLock, lockflags1); + + iThisCopy = + NUM_DESC_PER_RING_TX - pAdapter->TxRing.txDmaReadyToSend.bits.val; + + if (iThisCopy >= FragmentNumber) { + iRemainder = 0; + iThisCopy = FragmentNumber; + } else { + iRemainder = FragmentNumber - iThisCopy; + } + + memcpy(pAdapter->TxRing.pTxDescRingVa + + pAdapter->TxRing.txDmaReadyToSend.bits.val, CurDesc, + sizeof(TX_DESC_ENTRY_t) * iThisCopy); + + pAdapter->TxRing.txDmaReadyToSend.bits.val += iThisCopy; + + if ((pAdapter->TxRing.txDmaReadyToSend.bits.val == 0) || + (pAdapter->TxRing.txDmaReadyToSend.bits.val == + NUM_DESC_PER_RING_TX)) { + if (pAdapter->TxRing.txDmaReadyToSend.bits.wrap) { + pAdapter->TxRing.txDmaReadyToSend.value = 0; + } else { + pAdapter->TxRing.txDmaReadyToSend.value = 0x400; + } + } + + if (iRemainder) { + memcpy(pAdapter->TxRing.pTxDescRingVa, + CurDesc + iThisCopy, + sizeof(TX_DESC_ENTRY_t) * iRemainder); + + pAdapter->TxRing.txDmaReadyToSend.bits.val += iRemainder; + } + + if (pAdapter->TxRing.txDmaReadyToSend.bits.val == 0) { + if (pAdapter->TxRing.txDmaReadyToSend.value) { + pMpTcb->WrIndex.value = NUM_DESC_PER_RING_TX - 1; + } else { + pMpTcb->WrIndex.value = + 0x400 | (NUM_DESC_PER_RING_TX - 1); + } + } else { + pMpTcb->WrIndex.value = + pAdapter->TxRing.txDmaReadyToSend.value - 1; + } + + spin_lock_irqsave(&pAdapter->TCBSendQLock, lockflags2); + + if (pAdapter->TxRing.CurrSendTail) { + pAdapter->TxRing.CurrSendTail->Next = pMpTcb; + } else { + pAdapter->TxRing.CurrSendHead = pMpTcb; + } + + pAdapter->TxRing.CurrSendTail = pMpTcb; + + DBG_ASSERT(pMpTcb->Next == NULL); + + pAdapter->TxRing.nBusySend++; + + spin_unlock_irqrestore(&pAdapter->TCBSendQLock, lockflags2); + + /* Write the new write pointer back to the device. */ + writel(pAdapter->TxRing.txDmaReadyToSend.value, + &pAdapter->CSRAddress->txdma.service_request.value); + + /* For Gig only, we use Tx Interrupt coalescing. Enable the software + * timer to wake us up if this packet isn't followed by N more. + */ + if (pAdapter->uiLinkSpeed == TRUEPHY_SPEED_1000MBPS) { + writel(pAdapter->RegistryTxTimeInterval * NANO_IN_A_MICRO, + &pAdapter->CSRAddress->global.watchdog_timer); + } + + spin_unlock_irqrestore(&pAdapter->SendHWLock, lockflags1); + + DBG_TX_LEAVE(et131x_dbginfo); + return 0; +} + +/* + * NOTE: For now, keep this older version of NICSendPacket around for + * reference, even though it's not used + */ +#if 0 + +/** + * NICSendPacket - NIC specific send handler. + * @pAdapter: pointer to our adapter + * @pMpTcb: pointer to MP_TCB + * + * Returns 0 on succes, errno on failure. + * + * This version of the send routine is designed for version A silicon. + * Assumption - Send spinlock has been acquired. + */ +static int nic_send_packet(struct et131x_adapter *pAdapter, PMP_TCB pMpTcb) +{ + uint32_t loopIndex, fragIndex, loopEnd; + uint32_t iSplitFirstElement = 0; + uint32_t SegmentSize = 0; + TX_DESC_ENTRY_t CurDesc; + TX_DESC_ENTRY_t *CurDescPostCopy = NULL; + uint32_t SlotsAvailable; + DMA10W_t Se |